refactor: next/router hooks with next/navigation hooks (#9105)
Co-authored-by: Alex van Andel <[email protected]> Co-authored-by: Peer Richelsen <[email protected]> Co-authored-by: Bailey Pumfleet <[email protected]> Co-authored-by: Peer Richelsen <[email protected]> Co-authored-by: Hariom Balhara <[email protected]>
This commit is contained in:
152 files changed
+1802
-2565
No files matched your search
@@ -1,4 +1,4 @@
|
||||
import { useRouter } from "next/router";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useState } from "react";
|
||||
import { useForm } from "react-hook-form";
|
||||
import { Toaster } from "react-hot-toast";
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useRouter } from "next/router";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useState } from "react";
|
||||
import { useForm } from "react-hook-form";
|
||||
import { Toaster } from "react-hot-toast";
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { zodResolver } from "@hookform/resolvers/zod";
|
||||
import { useRouter } from "next/router";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useEffect, useState } from "react";
|
||||
import { Controller, useForm } from "react-hook-form";
|
||||
import { Toaster } from "react-hot-toast";
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import Link from "next/link";
|
||||
import { useRouter } from "next/router";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useEffect, useRef } from "react";
|
||||
|
||||
import useAddAppMutation from "@calcom/app-store/_utils/useAddAppMutation";
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useRouter } from "next/router";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useState } from "react";
|
||||
import { useForm } from "react-hook-form";
|
||||
import { Toaster } from "react-hot-toast";
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useRouter } from "next/router";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useState } from "react";
|
||||
import { useForm } from "react-hook-form";
|
||||
import { Toaster } from "react-hot-toast";
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { zodResolver } from "@hookform/resolvers/zod";
|
||||
import { useRouter } from "next/router";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useState } from "react";
|
||||
import { Controller, useForm } from "react-hook-form";
|
||||
import { Toaster } from "react-hot-toast";
|
||||
|
||||
@@ -1,9 +1,7 @@
|
||||
import type { App_RoutingForms_Form } from "@prisma/client";
|
||||
import type { NextRouter } from "next/router";
|
||||
import { useRouter } from "next/router";
|
||||
import { usePathname, useRouter, useSearchParams } from "next/navigation";
|
||||
import { createContext, forwardRef, useContext, useState } from "react";
|
||||
import { useForm } from "react-hook-form";
|
||||
import { Controller } from "react-hook-form";
|
||||
import { Controller, useForm } from "react-hook-form";
|
||||
import { v4 as uuidv4 } from "uuid";
|
||||
import { z } from "zod";
|
||||
|
||||
@@ -11,6 +9,7 @@ import { useOrgBranding } from "@calcom/features/ee/organizations/context/provid
|
||||
import { classNames } from "@calcom/lib";
|
||||
import { CAL_URL } from "@calcom/lib/constants";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import { useRouterQuery } from "@calcom/lib/hooks/useRouterQuery";
|
||||
import { trpc } from "@calcom/trpc/react";
|
||||
import type { ButtonProps } from "@calcom/ui";
|
||||
import {
|
||||
@@ -25,11 +24,11 @@ import {
|
||||
DropdownMenuItem,
|
||||
DropdownMenuTrigger,
|
||||
Form,
|
||||
SettingsToggle,
|
||||
showToast,
|
||||
Switch,
|
||||
TextAreaField,
|
||||
TextField,
|
||||
SettingsToggle,
|
||||
} from "@calcom/ui";
|
||||
import { MoreHorizontal } from "@calcom/ui/components/icon";
|
||||
|
||||
@@ -45,23 +44,23 @@ const newFormModalQuerySchema = z.object({
|
||||
target: z.string().optional(),
|
||||
});
|
||||
|
||||
const openModal = (router: NextRouter, option: z.infer<typeof newFormModalQuerySchema>) => {
|
||||
const query = {
|
||||
...router.query,
|
||||
dialog: "new-form",
|
||||
...option,
|
||||
export const useOpenModal = () => {
|
||||
const router = useRouter();
|
||||
const pathname = usePathname();
|
||||
const searchParams = useSearchParams();
|
||||
const openModal = (option: z.infer<typeof newFormModalQuerySchema>) => {
|
||||
const newQuery = new URLSearchParams(searchParams);
|
||||
newQuery.set("dialog", "new-form");
|
||||
Object.keys(option).forEach((key) => {
|
||||
newQuery.set(key, option[key as keyof typeof option] || "");
|
||||
});
|
||||
router.push(`${pathname}?${newQuery.toString()}`);
|
||||
};
|
||||
router.push(
|
||||
{
|
||||
pathname: router.pathname,
|
||||
query,
|
||||
},
|
||||
undefined,
|
||||
{ shallow: true }
|
||||
);
|
||||
return openModal;
|
||||
};
|
||||
|
||||
function NewFormDialog({ appUrl }: { appUrl: string }) {
|
||||
const routerQuery = useRouterQuery();
|
||||
const { t } = useLocale();
|
||||
const router = useRouter();
|
||||
const utils = trpc.useContext();
|
||||
@@ -84,7 +83,7 @@ function NewFormDialog({ appUrl }: { appUrl: string }) {
|
||||
shouldConnect: boolean;
|
||||
}>();
|
||||
|
||||
const { action, target } = router.query as z.infer<typeof newFormModalQuerySchema>;
|
||||
const { action, target } = routerQuery as z.infer<typeof newFormModalQuerySchema>;
|
||||
|
||||
const formToDuplicate = action === "duplicate" ? target : null;
|
||||
const teamId = action === "new" ? Number(target) : null;
|
||||
@@ -158,7 +157,6 @@ function NewFormDialog({ appUrl }: { appUrl: string }) {
|
||||
}
|
||||
|
||||
const dropdownCtx = createContext<{ dropdown: boolean }>({ dropdown: false });
|
||||
|
||||
export const FormActionsDropdown = ({
|
||||
children,
|
||||
disabled,
|
||||
@@ -196,6 +194,7 @@ function Dialogs({
|
||||
deleteDialogFormId: string | null;
|
||||
}) {
|
||||
const utils = trpc.useContext();
|
||||
const router = useRouter();
|
||||
const { t } = useLocale();
|
||||
const deleteMutation = trpc.viewer.appRoutingForms.deleteForm.useMutation({
|
||||
onMutate: async ({ id: formId }) => {
|
||||
@@ -216,6 +215,7 @@ function Dialogs({
|
||||
onSuccess: () => {
|
||||
showToast(t("form_deleted"), "success");
|
||||
setDeleteDialogOpen(false);
|
||||
router.push(`${appUrl}/forms`);
|
||||
},
|
||||
onSettled: () => {
|
||||
utils.viewer.appRoutingForms.forms.invalidate();
|
||||
@@ -412,7 +412,7 @@ export const FormAction = forwardRef(function FormAction<T extends typeof Button
|
||||
});
|
||||
|
||||
const { t } = useLocale();
|
||||
const router = useRouter();
|
||||
const openModal = useOpenModal();
|
||||
const actionData: Record<
|
||||
FormActionType,
|
||||
ButtonProps & { as?: React.ElementType; render?: FormActionProps<unknown>["render"] }
|
||||
@@ -427,7 +427,7 @@ export const FormAction = forwardRef(function FormAction<T extends typeof Button
|
||||
},
|
||||
},
|
||||
duplicate: {
|
||||
onClick: () => openModal(router, { action: "duplicate", target: routingForm?.id }),
|
||||
onClick: () => openModal({ action: "duplicate", target: routingForm?.id }),
|
||||
},
|
||||
embed: {
|
||||
as: EmbedButton,
|
||||
@@ -446,7 +446,7 @@ export const FormAction = forwardRef(function FormAction<T extends typeof Button
|
||||
loading: _delete.isLoading,
|
||||
},
|
||||
create: {
|
||||
onClick: () => createAction({ router, teamId: null }),
|
||||
onClick: () => openModal({ action: "new", target: "" }),
|
||||
},
|
||||
copyRedirectUrl: {
|
||||
onClick: () => {
|
||||
@@ -486,7 +486,6 @@ export const FormAction = forwardRef(function FormAction<T extends typeof Button
|
||||
...action,
|
||||
...(additionalProps as ButtonProps),
|
||||
} as ButtonProps & { render?: FormActionProps<unknown>["render"] };
|
||||
|
||||
if (actionProps.render) {
|
||||
return actionProps.render({
|
||||
routingForm,
|
||||
@@ -517,7 +516,3 @@ export const FormAction = forwardRef(function FormAction<T extends typeof Button
|
||||
</DropdownMenuItem>
|
||||
);
|
||||
});
|
||||
|
||||
export const createAction = ({ router, teamId }: { router: NextRouter; teamId: number | null }) => {
|
||||
openModal(router, { action: "new", target: teamId ? String(teamId) : "" });
|
||||
};
|
||||
@@ -1,5 +1,4 @@
|
||||
// TODO: i18n
|
||||
import { useRouter } from "next/router";
|
||||
import { useEffect } from "react";
|
||||
import { useFormContext } from "react-hook-form";
|
||||
|
||||
@@ -14,6 +13,7 @@ import { WEBAPP_URL } from "@calcom/lib/constants";
|
||||
import useApp from "@calcom/lib/hooks/useApp";
|
||||
import { useHasPaidPlan } from "@calcom/lib/hooks/useHasPaidPlan";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import { useRouterQuery } from "@calcom/lib/hooks/useRouterQuery";
|
||||
import { trpc } from "@calcom/trpc/react";
|
||||
import type {
|
||||
AppGetServerSidePropsContext,
|
||||
@@ -21,46 +21,54 @@ import type {
|
||||
AppSsrInit,
|
||||
AppUser,
|
||||
} from "@calcom/types/AppGetServerSideProps";
|
||||
import { Badge, ButtonGroup, EmptyScreen, List, ListLinkItem, Tooltip, Button } from "@calcom/ui";
|
||||
import { CreateButtonWithTeamsList } from "@calcom/ui";
|
||||
import {
|
||||
GitMerge,
|
||||
ExternalLink,
|
||||
Link as LinkIcon,
|
||||
Edit,
|
||||
Download,
|
||||
Code,
|
||||
Copy,
|
||||
Trash,
|
||||
Menu,
|
||||
MessageCircle,
|
||||
FileText,
|
||||
Shuffle,
|
||||
Badge,
|
||||
Button,
|
||||
ButtonGroup,
|
||||
CreateButtonWithTeamsList,
|
||||
EmptyScreen,
|
||||
List,
|
||||
ListLinkItem,
|
||||
Tooltip,
|
||||
} from "@calcom/ui";
|
||||
import {
|
||||
BarChart,
|
||||
CheckCircle,
|
||||
Code,
|
||||
Copy,
|
||||
Download,
|
||||
Edit,
|
||||
ExternalLink,
|
||||
FileText,
|
||||
GitMerge,
|
||||
Link as LinkIcon,
|
||||
Mail,
|
||||
Menu,
|
||||
MessageCircle,
|
||||
Shuffle,
|
||||
Trash,
|
||||
} from "@calcom/ui/components/icon";
|
||||
|
||||
import type { inferSSRProps } from "@lib/types/inferSSRProps";
|
||||
|
||||
import {
|
||||
createAction,
|
||||
FormAction,
|
||||
FormActionsDropdown,
|
||||
FormActionsProvider,
|
||||
useOpenModal,
|
||||
} from "../../components/FormActions";
|
||||
import type { RoutingFormWithResponseCount } from "../../components/SingleForm";
|
||||
import { isFallbackRoute } from "../../lib/isFallbackRoute";
|
||||
|
||||
function NewFormButton() {
|
||||
const { t } = useLocale();
|
||||
const router = useRouter();
|
||||
const openModal = useOpenModal();
|
||||
return (
|
||||
<CreateButtonWithTeamsList
|
||||
subtitle={t("create_routing_form_on").toUpperCase()}
|
||||
data-testid="new-routing-form"
|
||||
createFunction={(teamId) => {
|
||||
createAction({ router, teamId: teamId ?? null });
|
||||
openModal({ action: "new", target: teamId ? String(teamId) : "" });
|
||||
}}
|
||||
/>
|
||||
);
|
||||
@@ -68,17 +76,18 @@ function NewFormButton() {
|
||||
|
||||
export default function RoutingForms({
|
||||
appUrl,
|
||||
}: inferSSRProps<typeof getServerSideProps> & { appUrl: string }) {
|
||||
}: inferSSRProps<typeof getServerSideProps> & {
|
||||
appUrl: string;
|
||||
}) {
|
||||
const { t } = useLocale();
|
||||
const { hasPaidPlan } = useHasPaidPlan();
|
||||
const router = useRouter();
|
||||
|
||||
const routerQuery = useRouterQuery();
|
||||
const hookForm = useFormContext<RoutingFormWithResponseCount>();
|
||||
useEffect(() => {
|
||||
hookForm.reset({});
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, []);
|
||||
const filters = getTeamsFiltersFromQuery(router.query);
|
||||
const filters = getTeamsFiltersFromQuery(routerQuery);
|
||||
|
||||
const queryRes = trpc.viewer.appRoutingForms.forms.useQuery({
|
||||
filters,
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
import type { GetServerSidePropsContext } from "next";
|
||||
import type { NextRouter } from "next/router";
|
||||
import { useRouter } from "next/router";
|
||||
import type { AppProps as NextAppProps } from "next/app";
|
||||
import React from "react";
|
||||
import { useForm, FormProvider } from "react-hook-form";
|
||||
import { FormProvider, useForm } from "react-hook-form";
|
||||
|
||||
import { useParamsWithFallback } from "@calcom/lib/hooks/useParamsWithFallback";
|
||||
import type { AppPrisma, AppSsrInit, AppUser } from "@calcom/types/AppGetServerSideProps";
|
||||
|
||||
import type { AppProps } from "@lib/app-providers";
|
||||
@@ -15,7 +15,7 @@ type Component = {
|
||||
default: React.ComponentType & Pick<AppProps["Component"], "getLayout">;
|
||||
getServerSideProps?: (context: GetServerSidePropsContext, ...rest: GetServerSidePropsRestArgs) => void;
|
||||
};
|
||||
const getComponent = (route: string | NextRouter): Component => {
|
||||
const getComponent = (route: string | NextAppProps["router"]): Component => {
|
||||
const defaultRoute = "forms";
|
||||
const routeKey =
|
||||
typeof route === "string" ? route || defaultRoute : route?.query?.pages?.[0] || defaultRoute;
|
||||
@@ -23,9 +23,9 @@ const getComponent = (route: string | NextRouter): Component => {
|
||||
};
|
||||
|
||||
export default function LayoutHandler(props: { [key: string]: unknown }) {
|
||||
const params = useParamsWithFallback();
|
||||
const methods = useForm();
|
||||
const router = useRouter();
|
||||
const pageKey = router?.query?.pages?.[0] || "forms";
|
||||
const pageKey = params?.pages?.[0] || "forms";
|
||||
const PageComponent = getComponent(pageKey).default;
|
||||
return (
|
||||
<FormProvider {...methods}>
|
||||
@@ -34,7 +34,7 @@ export default function LayoutHandler(props: { [key: string]: unknown }) {
|
||||
);
|
||||
}
|
||||
|
||||
LayoutHandler.getLayout = (page: React.ReactElement, router: NextRouter) => {
|
||||
LayoutHandler.getLayout = (page: React.ReactElement, router: NextAppProps["router"]) => {
|
||||
const component = getComponent(router).default;
|
||||
if (component && "getLayout" in component) {
|
||||
return component.getLayout?.(page, router);
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import Head from "next/head";
|
||||
import { useRouter } from "next/router";
|
||||
import { useRouter, useSearchParams } from "next/navigation";
|
||||
import type { FormEvent } from "react";
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { Toaster } from "react-hot-toast";
|
||||
@@ -295,14 +295,16 @@ export const getServerSideProps = async function getServerSideProps(
|
||||
};
|
||||
|
||||
const usePrefilledResponse = (form: Props["form"]) => {
|
||||
const router = useRouter();
|
||||
|
||||
const searchParams = useSearchParams();
|
||||
const prefillResponse: Response = {};
|
||||
|
||||
// Prefill the form from query params
|
||||
form.fields?.forEach((field) => {
|
||||
const valuesFromQuery = searchParams?.getAll(getFieldIdentifier(field)).filter(Boolean);
|
||||
// We only want to keep arrays if the field is a multi-select
|
||||
const value = valuesFromQuery.length > 1 ? valuesFromQuery : valuesFromQuery[0];
|
||||
prefillResponse[field.id] = {
|
||||
value: router.query[getFieldIdentifier(field)] || "",
|
||||
value: value || "",
|
||||
label: field.label,
|
||||
};
|
||||
});
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { zodResolver } from "@hookform/resolvers/zod";
|
||||
import { useRouter } from "next/router";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useEffect, useState } from "react";
|
||||
import { Controller, useForm } from "react-hook-form";
|
||||
import { Toaster } from "react-hot-toast";
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useRouter } from "next/router";
|
||||
import { usePathname } from "next/navigation";
|
||||
|
||||
import { useAppContextWithSchema } from "@calcom/app-store/EventTypeAppContext";
|
||||
import AppCard from "@calcom/app-store/_components/AppCard";
|
||||
@@ -6,7 +6,7 @@ import useIsAppEnabled from "@calcom/app-store/_utils/useIsAppEnabled";
|
||||
import type { EventTypeAppCardComponent } from "@calcom/app-store/types";
|
||||
import { WEBAPP_URL } from "@calcom/lib/constants";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import { Alert, TextField, Select } from "@calcom/ui";
|
||||
import { Alert, Select, TextField } from "@calcom/ui";
|
||||
|
||||
import { paymentOptions } from "../lib/constants";
|
||||
import type { appDataSchema } from "../zod";
|
||||
@@ -14,7 +14,7 @@ import type { appDataSchema } from "../zod";
|
||||
type Option = { value: string; label: string };
|
||||
|
||||
const EventTypeAppCard: EventTypeAppCardComponent = function EventTypeAppCard({ app, eventType }) {
|
||||
const { asPath } = useRouter();
|
||||
const pathname = usePathname();
|
||||
const [getAppData, setAppData, LockedIcon, disabled] = useAppContextWithSchema<typeof appDataSchema>();
|
||||
const price = getAppData("price");
|
||||
const currency = getAppData("currency");
|
||||
@@ -37,7 +37,7 @@ const EventTypeAppCard: EventTypeAppCardComponent = function EventTypeAppCard({
|
||||
.trim();
|
||||
return (
|
||||
<AppCard
|
||||
returnTo={WEBAPP_URL + asPath}
|
||||
returnTo={WEBAPP_URL + pathname}
|
||||
setAppData={setAppData}
|
||||
app={app}
|
||||
disableSwitch={disabled}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { useRouter } from "next/router";
|
||||
import { useSearchParams } from "next/navigation";
|
||||
import type { CSSProperties } from "react";
|
||||
import { useState, useEffect } from "react";
|
||||
import { useEffect, useRef, useState, useCallback } from "react";
|
||||
|
||||
import type { Message } from "./embed";
|
||||
import { sdkActionManager } from "./sdk-event";
|
||||
@@ -177,14 +177,35 @@ function isValidNamespace(ns: string | null | undefined) {
|
||||
return typeof ns !== "undefined" && ns !== null;
|
||||
}
|
||||
|
||||
export const useEmbedTheme = () => {
|
||||
const router = useRouter();
|
||||
const [theme, setTheme] = useState(embedStore.theme || (router.query.theme as typeof embedStore.theme));
|
||||
/**
|
||||
* It handles any URL change done through Web history API as well
|
||||
* History API is currenty being used by Booker/utils/query-param
|
||||
*/
|
||||
const useUrlChange = (callback: (newUrl: string) => void) => {
|
||||
const currentFullUrl = isBrowser ? new URL(document.URL) : null;
|
||||
const pathname = currentFullUrl?.pathname ?? "";
|
||||
const searchParams = currentFullUrl?.searchParams ?? null;
|
||||
const lastKnownUrl = useRef(`${pathname}?${searchParams}`);
|
||||
useEffect(() => {
|
||||
router.events.on("routeChangeComplete", () => {
|
||||
sdkActionManager?.fire("__routeChanged", {});
|
||||
});
|
||||
}, [router.events]);
|
||||
const newUrl = `${pathname}?${searchParams}`;
|
||||
if (lastKnownUrl.current !== newUrl) {
|
||||
lastKnownUrl.current = newUrl;
|
||||
callback(newUrl);
|
||||
}
|
||||
}, [pathname, searchParams, callback]);
|
||||
};
|
||||
|
||||
export const useEmbedTheme = () => {
|
||||
const searchParams = useSearchParams();
|
||||
const [theme, setTheme] = useState(
|
||||
embedStore.theme || (searchParams?.get("theme") as typeof embedStore.theme)
|
||||
);
|
||||
|
||||
const onUrlChange = useCallback(() => {
|
||||
sdkActionManager?.fire("__routeChanged", {});
|
||||
}, []);
|
||||
useUrlChange(onUrlChange);
|
||||
|
||||
embedStore.setTheme = setTheme;
|
||||
return theme;
|
||||
};
|
||||
@@ -363,7 +384,6 @@ const methods = {
|
||||
};
|
||||
|
||||
export type InterfaceWithParent = {
|
||||
// Ensure that only one argument is read by the method
|
||||
[key in keyof typeof methods]: (firstAndOnlyArg: Parameters<(typeof methods)[key]>[number]) => void;
|
||||
};
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { zodResolver } from "@hookform/resolvers/zod";
|
||||
import { noop } from "lodash";
|
||||
import { useRouter } from "next/router";
|
||||
import { useSearchParams } from "next/navigation";
|
||||
import type { FC } from "react";
|
||||
import { useReducer, useState } from "react";
|
||||
import { Controller, useForm } from "react-hook-form";
|
||||
@@ -27,8 +27,8 @@ import {
|
||||
SkeletonButton,
|
||||
SkeletonContainer,
|
||||
SkeletonText,
|
||||
TextField,
|
||||
Switch,
|
||||
TextField,
|
||||
} from "@calcom/ui";
|
||||
import { AlertCircle, Edit } from "@calcom/ui/components/icon";
|
||||
|
||||
@@ -265,13 +265,13 @@ interface EditModalState extends Pick<App, "keys"> {
|
||||
}
|
||||
|
||||
const AdminAppsListContainer = () => {
|
||||
const searchParams = useSearchParams();
|
||||
const { t } = useLocale();
|
||||
const router = useRouter();
|
||||
const { category } = querySchema.parse(router.query);
|
||||
const category = searchParams.get("category") || AppCategories.calendar;
|
||||
|
||||
const { data: apps, isLoading } = trpc.viewer.appsRouter.listLocal.useQuery(
|
||||
{ category },
|
||||
{ enabled: router.isReady }
|
||||
{ enabled: searchParams !== null }
|
||||
);
|
||||
|
||||
const [modalState, setModalState] = useReducer(
|
||||
|
||||
@@ -3,13 +3,7 @@ import { useState } from "react";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import { trpc } from "@calcom/trpc/react";
|
||||
import type { ButtonProps } from "@calcom/ui";
|
||||
import {
|
||||
Button,
|
||||
ConfirmationDialogContent,
|
||||
Dialog,
|
||||
DialogTrigger,
|
||||
showToast,
|
||||
} from "@calcom/ui";
|
||||
import { Button, ConfirmationDialogContent, Dialog, DialogTrigger, showToast } from "@calcom/ui";
|
||||
import { Trash } from "@calcom/ui/components/icon";
|
||||
|
||||
export default function DisconnectIntegration({
|
||||
|
||||
@@ -3,7 +3,7 @@ import type { UseMutationResult } from "@tanstack/react-query";
|
||||
import { useMutation } from "@tanstack/react-query";
|
||||
import { useSession } from "next-auth/react";
|
||||
import type { TFunction } from "next-i18next";
|
||||
import { useRouter } from "next/router";
|
||||
import { useRouter, useSearchParams } from "next/navigation";
|
||||
import { useEffect, useMemo, useRef, useState } from "react";
|
||||
import type { FieldError } from "react-hook-form";
|
||||
import { useForm } from "react-hook-form";
|
||||
@@ -14,23 +14,24 @@ import { createPaymentLink } from "@calcom/app-store/stripepayment/lib/client";
|
||||
import dayjs from "@calcom/dayjs";
|
||||
import { VerifyCodeDialog } from "@calcom/features/bookings/components/VerifyCodeDialog";
|
||||
import {
|
||||
useTimePreferences,
|
||||
mapBookingToMutationInput,
|
||||
createBooking,
|
||||
createRecurringBooking,
|
||||
mapBookingToMutationInput,
|
||||
mapRecurringBookingToMutationInput,
|
||||
useTimePreferences,
|
||||
} from "@calcom/features/bookings/lib";
|
||||
import { getBookingFieldsWithSystemFields } from "@calcom/features/bookings/lib/getBookingFields";
|
||||
import getBookingResponsesSchema, {
|
||||
getBookingResponsesPartialSchema,
|
||||
} from "@calcom/features/bookings/lib/getBookingResponsesSchema";
|
||||
import { getFullName } from "@calcom/features/form-builder/utils";
|
||||
import { bookingSuccessRedirect } from "@calcom/lib/bookingSuccessRedirect";
|
||||
import { useBookingSuccessRedirect } from "@calcom/lib/bookingSuccessRedirect";
|
||||
import { MINUTES_TO_BOOK } from "@calcom/lib/constants";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import { useRouterQuery } from "@calcom/lib/hooks/useRouterQuery";
|
||||
import { HttpError } from "@calcom/lib/http-error";
|
||||
import { trpc } from "@calcom/trpc";
|
||||
import { Form, Button, Alert, EmptyScreen, showToast } from "@calcom/ui";
|
||||
import { Alert, Button, EmptyScreen, Form, showToast } from "@calcom/ui";
|
||||
import { Calendar } from "@calcom/ui/components/icon";
|
||||
|
||||
import { useBookerStore } from "../../store";
|
||||
@@ -43,7 +44,10 @@ type BookEventFormProps = {
|
||||
};
|
||||
|
||||
export const BookEventForm = ({ onCancel }: BookEventFormProps) => {
|
||||
const searchParams = useSearchParams();
|
||||
const routerQuery = useRouterQuery();
|
||||
const session = useSession();
|
||||
const bookingSuccessRedirect = useBookingSuccessRedirect();
|
||||
const reserveSlotMutation = trpc.viewer.public.slots.reserveSlot.useMutation({
|
||||
trpc: { context: { skipBatch: true } },
|
||||
});
|
||||
@@ -113,10 +117,10 @@ export const BookEventForm = ({ onCancel }: BookEventFormProps) => {
|
||||
});
|
||||
|
||||
const parsedQuery = querySchema.parse({
|
||||
...router.query,
|
||||
...routerQuery,
|
||||
// `guest` because we need to support legacy URL with `guest` query param support
|
||||
// `guests` because the `name` of the corresponding bookingField is `guests`
|
||||
guests: router.query.guests || router.query.guest,
|
||||
guests: searchParams?.getAll("guests") || searchParams?.getAll("guest"),
|
||||
});
|
||||
|
||||
const defaultUserValues = {
|
||||
@@ -204,11 +208,11 @@ export const BookEventForm = ({ onCancel }: BookEventFormProps) => {
|
||||
});
|
||||
|
||||
const createBookingMutation = useMutation(createBooking, {
|
||||
onSuccess: async (responseData) => {
|
||||
onSuccess: (responseData) => {
|
||||
const { uid, paymentUid } = responseData;
|
||||
const fullName = getFullName(bookingForm.getValues("responses.name"));
|
||||
if (paymentUid) {
|
||||
return await router.push(
|
||||
return router.push(
|
||||
createPaymentLink({
|
||||
paymentUid,
|
||||
date: timeslot,
|
||||
@@ -234,7 +238,6 @@ export const BookEventForm = ({ onCancel }: BookEventFormProps) => {
|
||||
};
|
||||
|
||||
return bookingSuccessRedirect({
|
||||
router,
|
||||
successRedirectUrl: eventType?.successRedirectUrl || "",
|
||||
query,
|
||||
bookingUid: uid,
|
||||
@@ -264,7 +267,6 @@ export const BookEventForm = ({ onCancel }: BookEventFormProps) => {
|
||||
};
|
||||
|
||||
return bookingSuccessRedirect({
|
||||
router,
|
||||
successRedirectUrl: eventType?.successRedirectUrl || "",
|
||||
query,
|
||||
bookingUid: uid,
|
||||
@@ -347,12 +349,12 @@ export const BookEventForm = ({ onCancel }: BookEventFormProps) => {
|
||||
rescheduleUid: rescheduleUid || undefined,
|
||||
bookingUid: (bookingData && bookingData.uid) || seatedEventData?.bookingUid || undefined,
|
||||
username: username || "",
|
||||
metadata: Object.keys(router.query)
|
||||
metadata: Object.keys(routerQuery)
|
||||
.filter((key) => key.startsWith("metadata"))
|
||||
.reduce(
|
||||
(metadata, key) => ({
|
||||
...metadata,
|
||||
[key.substring("metadata[".length, key.length - 1)]: router.query[key],
|
||||
[key.substring("metadata[".length, key.length - 1)]: searchParams?.get(key),
|
||||
}),
|
||||
{}
|
||||
),
|
||||
@@ -368,7 +370,7 @@ export const BookEventForm = ({ onCancel }: BookEventFormProps) => {
|
||||
};
|
||||
|
||||
if (!eventType) {
|
||||
console.warn("No event type found for event", router.query);
|
||||
console.warn("No event type found for event", routerQuery);
|
||||
return <Alert severity="warning" message={t("error_booking_event")} />;
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,119 @@
|
||||
import type {
|
||||
DefaultEventLocationType,
|
||||
EventLocationTypeFromApp,
|
||||
LocationObject,
|
||||
} from "@calcom/app-store/locations";
|
||||
import { getEventLocationType, getTranslatedLocation } from "@calcom/app-store/locations";
|
||||
import { classNames } from "@calcom/lib";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import { Tooltip } from "@calcom/ui";
|
||||
import { Link } from "@calcom/ui/components/icon";
|
||||
|
||||
const excludeNullValues = (value: unknown) => !!value;
|
||||
|
||||
function RenderIcon({
|
||||
eventLocationType,
|
||||
isTooltip,
|
||||
}: {
|
||||
eventLocationType: DefaultEventLocationType | EventLocationTypeFromApp;
|
||||
isTooltip: boolean;
|
||||
}) {
|
||||
return (
|
||||
<img
|
||||
src={eventLocationType.iconUrl}
|
||||
className={classNames(
|
||||
"me-[10px] h-4 w-4 opacity-70 dark:opacity-100",
|
||||
!eventLocationType.iconUrl?.startsWith("/app-store") ? "dark:invert-[.65]" : "",
|
||||
!eventLocationType.iconUrl?.startsWith("/app-store") && isTooltip && "invert"
|
||||
)}
|
||||
alt={`${eventLocationType.label} icon`}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function RenderLocationTooltip({ locations }: { locations: LocationObject[] }) {
|
||||
const { t } = useLocale();
|
||||
|
||||
return (
|
||||
<div className="my-2 me-2 flex w-full flex-col space-y-3 break-words">
|
||||
<p>{t("select_on_next_step")}</p>
|
||||
{locations.map(
|
||||
(
|
||||
location: Pick<Partial<LocationObject>, "link" | "address"> &
|
||||
Omit<LocationObject, "link" | "address">,
|
||||
index: number
|
||||
) => {
|
||||
const eventLocationType = getEventLocationType(location.type);
|
||||
if (!eventLocationType) {
|
||||
return null;
|
||||
}
|
||||
const translatedLocation = getTranslatedLocation(location, eventLocationType, t);
|
||||
return (
|
||||
<div key={`${location.type}-${index}`} className="font-sm flex flex-row items-center">
|
||||
<RenderIcon eventLocationType={eventLocationType} isTooltip />
|
||||
<p className="line-clamp-1">{translatedLocation}</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function AvailableEventLocations({ locations }: { locations: LocationObject[] }) {
|
||||
const { t } = useLocale();
|
||||
|
||||
const renderLocations = locations.map(
|
||||
(
|
||||
location: Pick<Partial<LocationObject>, "link" | "address"> & Omit<LocationObject, "link" | "address">,
|
||||
index: number
|
||||
) => {
|
||||
const eventLocationType = getEventLocationType(location.type);
|
||||
if (!eventLocationType) {
|
||||
// It's possible that the location app got uninstalled
|
||||
return null;
|
||||
}
|
||||
if (eventLocationType.variable === "hostDefault") {
|
||||
return null;
|
||||
}
|
||||
|
||||
const translatedLocation = getTranslatedLocation(location, eventLocationType, t);
|
||||
|
||||
return (
|
||||
<div key={`${location.type}-${index}`} className="flex flex-row items-center text-sm font-medium">
|
||||
{eventLocationType.iconUrl === "/link.svg" ? (
|
||||
<Link className="text-default ml-[2px] h-4 w-4 ltr:mr-[10px] rtl:ml-[10px] " />
|
||||
) : (
|
||||
<RenderIcon eventLocationType={eventLocationType} isTooltip={false} />
|
||||
)}
|
||||
<Tooltip content={translatedLocation}>
|
||||
<p className="line-clamp-1">{translatedLocation}</p>
|
||||
</Tooltip>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
);
|
||||
|
||||
const filteredLocations = renderLocations.filter(excludeNullValues) as JSX.Element[];
|
||||
|
||||
return filteredLocations.length > 1 ? (
|
||||
<div className="flex flex-row items-center text-sm font-medium">
|
||||
<img
|
||||
src="/map-pin.svg"
|
||||
className={classNames("me-[10px] h-4 w-4 opacity-70 dark:invert")}
|
||||
alt="map-pin"
|
||||
/>
|
||||
<Tooltip content={<RenderLocationTooltip locations={locations} />}>
|
||||
<p className="line-clamp-1">
|
||||
{t("location_options", {
|
||||
locationCount: filteredLocations.length,
|
||||
})}
|
||||
</p>
|
||||
</Tooltip>
|
||||
</div>
|
||||
) : filteredLocations.length === 1 ? (
|
||||
<div className="text-default mr-6 flex w-full flex-col space-y-4 break-words text-sm">
|
||||
{filteredLocations}
|
||||
</div>
|
||||
) : null;
|
||||
}
|
||||
@@ -5,10 +5,10 @@ import classNames from "@calcom/lib/classNames";
|
||||
import getPaymentAppData from "@calcom/lib/getPaymentAppData";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import { Clock, CheckSquare, RefreshCcw, CreditCard } from "@calcom/ui/components/icon";
|
||||
import { AvailableEventLocations } from "@calcom/web/components/booking/AvailableEventLocations";
|
||||
|
||||
import type { PublicEvent } from "../../types";
|
||||
import { EventDetailBlocks } from "../../types";
|
||||
import { AvailableEventLocations } from "./AvailableEventLocations";
|
||||
import { EventDuration } from "./Duration";
|
||||
import { EventOccurences } from "./Occurences";
|
||||
import { EventPrice } from "./Price";
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
import { useRouter } from "next/router";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useState } from "react";
|
||||
import { Controller, useForm } from "react-hook-form";
|
||||
import z from "zod";
|
||||
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import { useRouterQuery } from "@calcom/lib/hooks/useRouterQuery";
|
||||
import { trpc } from "@calcom/trpc/react";
|
||||
import { Avatar, Button, Form, ImageUploader, Alert, Label, TextAreaField } from "@calcom/ui";
|
||||
import { Alert, Avatar, Button, Form, ImageUploader, Label, TextAreaField } from "@calcom/ui";
|
||||
import { ArrowRight, Plus } from "@calcom/ui/components/icon";
|
||||
|
||||
const querySchema = z.object({
|
||||
@@ -15,7 +16,8 @@ const querySchema = z.object({
|
||||
export const AboutOrganizationForm = () => {
|
||||
const { t } = useLocale();
|
||||
const router = useRouter();
|
||||
const { id: orgId } = querySchema.parse(router.query);
|
||||
const routerQuery = useRouterQuery();
|
||||
const { id: orgId } = querySchema.parse(routerQuery);
|
||||
const [serverErrorMessage, setServerErrorMessage] = useState<string | null>(null);
|
||||
const [image, setImage] = useState("");
|
||||
|
||||
|
||||
@@ -1,12 +1,13 @@
|
||||
import { ArrowRight } from "lucide-react";
|
||||
import { useRouter } from "next/router";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { Controller, useForm } from "react-hook-form";
|
||||
import { z } from "zod";
|
||||
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import { useRouterQuery } from "@calcom/lib/hooks/useRouterQuery";
|
||||
import { MembershipRole } from "@calcom/prisma/enums";
|
||||
import { trpc } from "@calcom/trpc/react";
|
||||
import { Button, showToast, TextAreaField, Form } from "@calcom/ui";
|
||||
import { Button, Form, showToast, TextAreaField } from "@calcom/ui";
|
||||
|
||||
const querySchema = z.object({
|
||||
id: z.string().transform((val) => parseInt(val)),
|
||||
@@ -15,7 +16,8 @@ const querySchema = z.object({
|
||||
export const AddNewOrgAdminsForm = () => {
|
||||
const { t, i18n } = useLocale();
|
||||
const router = useRouter();
|
||||
const { id: orgId } = querySchema.parse(router.query);
|
||||
const routerQuery = useRouterQuery();
|
||||
const { id: orgId } = querySchema.parse(routerQuery);
|
||||
const newAdminsFormMethods = useForm<{
|
||||
emails: string[];
|
||||
}>();
|
||||
|
||||
@@ -1,13 +1,14 @@
|
||||
import { useRouter } from "next/router";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useState } from "react";
|
||||
import { useForm, useFieldArray } from "react-hook-form";
|
||||
import { useFieldArray, useForm } from "react-hook-form";
|
||||
import { z } from "zod";
|
||||
|
||||
import { classNames } from "@calcom/lib";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import { useRouterQuery } from "@calcom/lib/hooks/useRouterQuery";
|
||||
import { trpc } from "@calcom/trpc/react";
|
||||
import { Button, showToast, TextField } from "@calcom/ui";
|
||||
import { Plus, X, ArrowRight } from "@calcom/ui/components/icon";
|
||||
import { ArrowRight, Plus, X } from "@calcom/ui/components/icon";
|
||||
|
||||
const querySchema = z.object({
|
||||
id: z.string().transform((val) => parseInt(val)),
|
||||
@@ -26,7 +27,8 @@ const schema = z.object({
|
||||
export const AddNewTeamsForm = () => {
|
||||
const { t } = useLocale();
|
||||
const router = useRouter();
|
||||
const { id: orgId } = querySchema.parse(router.query);
|
||||
const routerQuery = useRouterQuery();
|
||||
const { id: orgId } = querySchema.parse(routerQuery);
|
||||
const [counter, setCounter] = useState(1);
|
||||
|
||||
const { register, control, handleSubmit, formState, trigger, setValue, getValues } = useForm({
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { signIn } from "next-auth/react";
|
||||
import { useRouter } from "next/router";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useState } from "react";
|
||||
import { Controller, useForm } from "react-hook-form";
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useRouter } from "next/router";
|
||||
import { useRouter } from "next/navigation";
|
||||
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import { trpc } from "@calcom/trpc/react";
|
||||
|
||||
@@ -1,13 +1,14 @@
|
||||
import { zodResolver } from "@hookform/resolvers/zod";
|
||||
import { useRouter } from "next/router";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useState } from "react";
|
||||
import { Controller, useForm } from "react-hook-form";
|
||||
import { z } from "zod";
|
||||
|
||||
import { isPasswordValid } from "@calcom/features/auth/lib/isPasswordValid";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import { useRouterQuery } from "@calcom/lib/hooks/useRouterQuery";
|
||||
import { trpc } from "@calcom/trpc/react";
|
||||
import { Button, Form, Alert, PasswordField } from "@calcom/ui";
|
||||
import { Alert, Button, Form, PasswordField } from "@calcom/ui";
|
||||
import { ArrowRight } from "@calcom/ui/components/icon";
|
||||
|
||||
const querySchema = z.object({
|
||||
@@ -33,7 +34,8 @@ const formSchema = z.object({
|
||||
export const SetPasswordForm = () => {
|
||||
const { t } = useLocale();
|
||||
const router = useRouter();
|
||||
const { id: orgId } = querySchema.parse(router.query);
|
||||
const routerQuery = useRouterQuery();
|
||||
const { id: orgId } = querySchema.parse(routerQuery);
|
||||
|
||||
const [serverErrorMessage, setServerErrorMessage] = useState<string | null>(null);
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useRouter } from "next/router";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { Controller, useForm } from "react-hook-form";
|
||||
|
||||
import LicenseRequired from "@calcom/features/ee/common/components/LicenseRequired";
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useRouter } from "next/router";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { Controller, useForm } from "react-hook-form";
|
||||
|
||||
import LicenseRequired from "@calcom/features/ee/common/components/LicenseRequired";
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { zodResolver } from "@hookform/resolvers/zod";
|
||||
import type { Prisma } from "@prisma/client";
|
||||
import { LinkIcon } from "lucide-react";
|
||||
import { useRouter } from "next/router";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useState, useLayoutEffect } from "react";
|
||||
import { Controller, useForm } from "react-hook-form";
|
||||
import { z } from "zod";
|
||||
@@ -223,24 +223,24 @@ const OrgProfileView = () => {
|
||||
</div>
|
||||
)}
|
||||
{/* Disable Org disbanding */}
|
||||
{/* <hr className="border-subtle my-8 border" />
|
||||
<div className="text-default mb-3 text-base font-semibold">{t("danger_zone")}</div>
|
||||
{currentOrganisation?.user.role === "OWNER" ? (
|
||||
<Dialog>
|
||||
<DialogTrigger asChild>
|
||||
<Button color="destructive" className="border" StartIcon={Trash2}>
|
||||
{t("disband_org")}
|
||||
</Button>
|
||||
</DialogTrigger>
|
||||
<ConfirmationDialogContent
|
||||
variety="danger"
|
||||
title={t("disband_org")}
|
||||
confirmBtnText={t("confirm")}
|
||||
onConfirm={deleteTeam}>
|
||||
{t("disband_org_confirmation_message")}
|
||||
</ConfirmationDialogContent>
|
||||
</Dialog>
|
||||
) : null} */}
|
||||
{/* <hr className="border-subtle my-8 border" />
|
||||
<div className="text-default mb-3 text-base font-semibold">{t("danger_zone")}</div>
|
||||
{currentOrganisation?.user.role === "OWNER" ? (
|
||||
<Dialog>
|
||||
<DialogTrigger asChild>
|
||||
<Button color="destructive" className="border" StartIcon={Trash2}>
|
||||
{t("disband_org")}
|
||||
</Button>
|
||||
</DialogTrigger>
|
||||
<ConfirmationDialogContent
|
||||
variety="danger"
|
||||
title={t("disband_org")}
|
||||
confirmBtnText={t("confirm")}
|
||||
onConfirm={deleteTeam}>
|
||||
{t("disband_org_confirmation_message")}
|
||||
</ConfirmationDialogContent>
|
||||
</Dialog>
|
||||
) : null} */}
|
||||
{/* LEAVE ORG should go above here ^ */}
|
||||
</>
|
||||
)}
|
||||
|
||||
@@ -1,14 +1,14 @@
|
||||
import type { Payment } from "@prisma/client";
|
||||
import { useElements, useStripe, PaymentElement, Elements } from "@stripe/react-stripe-js";
|
||||
import { Elements, PaymentElement, useElements, useStripe } from "@stripe/react-stripe-js";
|
||||
import type stripejs from "@stripe/stripe-js";
|
||||
import type { StripeElementLocale } from "@stripe/stripe-js";
|
||||
import { useRouter } from "next/router";
|
||||
import { useRouter, useSearchParams } from "next/navigation";
|
||||
import type { SyntheticEvent } from "react";
|
||||
import { useEffect, useState } from "react";
|
||||
|
||||
import getStripe from "@calcom/app-store/stripepayment/lib/client";
|
||||
import type { StripePaymentData, StripeSetupIntentData } from "@calcom/app-store/stripepayment/lib/server";
|
||||
import { bookingSuccessRedirect } from "@calcom/lib/bookingSuccessRedirect";
|
||||
import { useBookingSuccessRedirect } from "@calcom/lib/bookingSuccessRedirect";
|
||||
import { CAL_URL } from "@calcom/lib/constants";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import { Button, CheckboxField } from "@calcom/ui";
|
||||
@@ -35,11 +35,13 @@ type States =
|
||||
const PaymentForm = (props: Props) => {
|
||||
const { t, i18n } = useLocale();
|
||||
const router = useRouter();
|
||||
const searchParams = useSearchParams();
|
||||
const [state, setState] = useState<States>({ status: "idle" });
|
||||
const stripe = useStripe();
|
||||
const elements = useElements();
|
||||
const paymentOption = props.payment.paymentOption;
|
||||
const [holdAcknowledged, setHoldAcknowledged] = useState<boolean>(paymentOption === "HOLD" ? false : true);
|
||||
const bookingSuccessRedirect = useBookingSuccessRedirect();
|
||||
|
||||
useEffect(() => {
|
||||
elements?.update({ locale: i18n.language as StripeElementLocale });
|
||||
@@ -48,13 +50,13 @@ const PaymentForm = (props: Props) => {
|
||||
const handleSubmit = async (ev: SyntheticEvent) => {
|
||||
ev.preventDefault();
|
||||
|
||||
if (!stripe || !elements || !router.isReady) return;
|
||||
if (!stripe || !elements) return;
|
||||
setState({ status: "processing" });
|
||||
|
||||
let payload;
|
||||
const params: { [k: string]: any } = {
|
||||
uid: props.bookingUid,
|
||||
email: router.query.email,
|
||||
email: searchParams.get("email"),
|
||||
};
|
||||
if (paymentOption === "HOLD" && "setupIntent" in props.payment.data) {
|
||||
payload = await stripe.confirmSetup({
|
||||
@@ -86,7 +88,6 @@ const PaymentForm = (props: Props) => {
|
||||
}
|
||||
|
||||
return bookingSuccessRedirect({
|
||||
router,
|
||||
successRedirectUrl: props.eventType.successRedirectUrl,
|
||||
query: params,
|
||||
bookingUid: props.bookingUid,
|
||||
|
||||
@@ -1,20 +1,21 @@
|
||||
import { useRouter } from "next/router";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useEffect } from "react";
|
||||
|
||||
import { HOSTED_CAL_FEATURES } from "@calcom/lib/constants";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import { useParamsWithFallback } from "@calcom/lib/hooks/useParamsWithFallback";
|
||||
import { trpc } from "@calcom/trpc/react";
|
||||
import { AppSkeletonLoader as SkeletonLoader } from "@calcom/ui";
|
||||
import { Meta } from "@calcom/ui";
|
||||
import { AppSkeletonLoader as SkeletonLoader, Meta } from "@calcom/ui";
|
||||
|
||||
import { getLayout } from "../../../settings/layouts/SettingsLayout";
|
||||
import SSOConfiguration from "../components/SSOConfiguration";
|
||||
|
||||
const SAMLSSO = () => {
|
||||
const params = useParamsWithFallback();
|
||||
const { t } = useLocale();
|
||||
const router = useRouter();
|
||||
|
||||
const teamId = Number(router.query.id);
|
||||
const teamId = Number(params.id);
|
||||
|
||||
const { data: team, isLoading } = trpc.viewer.teams.get.useQuery(
|
||||
{ teamId },
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useRouter } from "next/router";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useEffect } from "react";
|
||||
|
||||
import { HOSTED_CAL_FEATURES } from "@calcom/lib/constants";
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { useSession } from "next-auth/react";
|
||||
import { useRouter } from "next/router";
|
||||
import { useRouter, useSearchParams } from "next/navigation";
|
||||
import { useState } from "react";
|
||||
import { z } from "zod";
|
||||
|
||||
@@ -33,10 +33,13 @@ type FormValues = {
|
||||
};
|
||||
|
||||
const AddNewTeamMembers = () => {
|
||||
const searchParams = useSearchParams();
|
||||
const session = useSession();
|
||||
const router = useRouter();
|
||||
const { id: teamId } = router.isReady ? querySchema.parse(router.query) : { id: -1 };
|
||||
const teamQuery = trpc.viewer.teams.get.useQuery({ teamId }, { enabled: router.isReady });
|
||||
const teamId = searchParams?.get("id") ? Number(searchParams.get("id")) : -1;
|
||||
const teamQuery = trpc.viewer.teams.get.useQuery(
|
||||
{ teamId },
|
||||
{ enabled: session.status === "authenticated" }
|
||||
);
|
||||
if (session.status === "loading" || !teamQuery.data) return <AddNewTeamMemberSkeleton />;
|
||||
|
||||
return <AddNewTeamMembersForm defaultValues={{ members: teamQuery.data.members }} teamId={teamId} />;
|
||||
@@ -49,16 +52,17 @@ export const AddNewTeamMembersForm = ({
|
||||
defaultValues: FormValues;
|
||||
teamId: number;
|
||||
}) => {
|
||||
const searchParams = useSearchParams();
|
||||
const { t, i18n } = useLocale();
|
||||
|
||||
const router = useRouter();
|
||||
const utils = trpc.useContext();
|
||||
|
||||
const showDialog = router.query.inviteModal === "true";
|
||||
const showDialog = searchParams?.get("inviteModal") === "true";
|
||||
const [memberInviteModal, setMemberInviteModal] = useState(showDialog);
|
||||
const [inviteLinkSettingsModal, setInviteLinkSettingsModal] = useState(false);
|
||||
|
||||
const { data: team, isLoading } = trpc.viewer.teams.get.useQuery({ teamId });
|
||||
const { data: team, isLoading } = trpc.viewer.teams.get.useQuery({ teamId }, { enabled: !!teamId });
|
||||
|
||||
const inviteMemberMutation = trpc.viewer.teams.inviteMember.useMutation();
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useRouter } from "next/router";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useState } from "react";
|
||||
import { Controller, useForm } from "react-hook-form";
|
||||
import { z } from "zod";
|
||||
@@ -6,6 +6,7 @@ import { z } from "zod";
|
||||
import { extractDomainFromWebsiteUrl } from "@calcom/ee/organizations/lib/utils";
|
||||
import { getSafeRedirectUrl } from "@calcom/lib/getSafeRedirectUrl";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import { useParamsWithFallback } from "@calcom/lib/hooks/useParamsWithFallback";
|
||||
import slugify from "@calcom/lib/slugify";
|
||||
import { telemetryEventTypes, useTelemetry } from "@calcom/lib/telemetry";
|
||||
import { trpc } from "@calcom/trpc/react";
|
||||
@@ -24,7 +25,8 @@ export const CreateANewTeamForm = () => {
|
||||
const { t } = useLocale();
|
||||
const router = useRouter();
|
||||
const telemetry = useTelemetry();
|
||||
const parsedQuery = querySchema.safeParse(router.query);
|
||||
const params = useParamsWithFallback();
|
||||
const parsedQuery = querySchema.safeParse(params);
|
||||
const [serverErrorMessage, setServerErrorMessage] = useState<string | null>(null);
|
||||
const orgBranding = useOrgBranding();
|
||||
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
import { UsersIcon, XIcon } from "lucide-react";
|
||||
import { useRouter } from "next/router";
|
||||
import { useState } from "react";
|
||||
import type { PropsWithChildren } from "react";
|
||||
import { useState } from "react";
|
||||
|
||||
import { useFlagMap } from "@calcom/features/flags/context/provider";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import { useParamsWithFallback } from "@calcom/lib/hooks/useParamsWithFallback";
|
||||
import { trpc } from "@calcom/trpc";
|
||||
import { Button, Tooltip, showToast } from "@calcom/ui";
|
||||
import { Button, showToast, Tooltip } from "@calcom/ui";
|
||||
|
||||
const GoogleIcon = () => (
|
||||
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||
@@ -35,11 +35,11 @@ function gotoUrl(url: string, newTab?: boolean) {
|
||||
export function GoogleWorkspaceInviteButton(
|
||||
props: PropsWithChildren<{ onSuccess: (data: string[]) => void }>
|
||||
) {
|
||||
const router = useRouter();
|
||||
const featureFlags = useFlagMap();
|
||||
const utils = trpc.useContext();
|
||||
const { t } = useLocale();
|
||||
const teamId = Number(router.query.id);
|
||||
const params = useParamsWithFallback();
|
||||
const teamId = Number(params.id);
|
||||
const [googleWorkspaceLoading, setGoogleWorkspaceLoading] = useState(false);
|
||||
const { data: credential } = trpc.viewer.googleWorkspace.checkForGWorkspace.useQuery();
|
||||
const { data: hasGcalInstalled } = trpc.viewer.appsRouter.checkGlobalKeys.useQuery({
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import Link from "next/link";
|
||||
import { useRouter } from "next/router";
|
||||
import { useSearchParams } from "next/navigation";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useState } from "react";
|
||||
|
||||
import InviteLinkSettingsModal from "@calcom/ee/teams/components/InviteLinkSettingsModal";
|
||||
@@ -52,13 +53,12 @@ interface Props {
|
||||
}
|
||||
|
||||
export default function TeamListItem(props: Props) {
|
||||
const searchParams = useSearchParams();
|
||||
const { t, i18n } = useLocale();
|
||||
|
||||
const router = useRouter();
|
||||
const utils = trpc.useContext();
|
||||
const team = props.team;
|
||||
|
||||
const showDialog = router.query.inviteModal === "true";
|
||||
const showDialog = searchParams?.get("inviteModal") === "true";
|
||||
const [openMemberInvitationModal, setOpenMemberInvitationModal] = useState(showDialog);
|
||||
const [openInviteLinkSettingsModal, setOpenInviteLinkSettingsModal] = useState(false);
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useRouter } from "next/router";
|
||||
import { useRouter, useSearchParams } from "next/navigation";
|
||||
import { useEffect, useMemo, useState } from "react";
|
||||
|
||||
import { APP_NAME, WEBAPP_URL } from "@calcom/lib/constants";
|
||||
@@ -12,6 +12,8 @@ import SkeletonLoaderTeamList from "./SkeletonloaderTeamList";
|
||||
import TeamList from "./TeamList";
|
||||
|
||||
export function TeamsListing() {
|
||||
const searchParams = useSearchParams();
|
||||
const token = searchParams?.get("token");
|
||||
const { t } = useLocale();
|
||||
const trpcContext = trpc.useContext();
|
||||
const router = useRouter();
|
||||
@@ -79,9 +81,9 @@ export function TeamsListing() {
|
||||
|
||||
useEffect(() => {
|
||||
if (!router) return;
|
||||
if (router.query.token) inviteMemberByToken({ token: router.query.token as string });
|
||||
if (token) inviteMemberByToken({ token });
|
||||
else setInviteTokenChecked(true);
|
||||
}, [router, inviteMemberByToken, setInviteTokenChecked]);
|
||||
}, [router, inviteMemberByToken, setInviteTokenChecked, token]);
|
||||
|
||||
if (isLoading || !inviteTokenChecked) {
|
||||
return <SkeletonLoaderTeamList />;
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useRouter } from "next/router";
|
||||
import { useRouter } from "next/navigation";
|
||||
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import { trpc } from "@calcom/trpc/react";
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
import { useRouter } from "next/router";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { Controller, useForm } from "react-hook-form";
|
||||
|
||||
import { APP_NAME } from "@calcom/lib/constants";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import { useParamsWithFallback } from "@calcom/lib/hooks/useParamsWithFallback";
|
||||
import { MembershipRole } from "@calcom/prisma/enums";
|
||||
import { trpc } from "@calcom/trpc/react";
|
||||
import {
|
||||
@@ -52,6 +53,7 @@ interface TeamAppearanceValues {
|
||||
}
|
||||
|
||||
const ProfileView = () => {
|
||||
const params = useParamsWithFallback();
|
||||
const { t } = useLocale();
|
||||
const router = useRouter();
|
||||
const utils = trpc.useContext();
|
||||
@@ -67,7 +69,7 @@ const ProfileView = () => {
|
||||
});
|
||||
|
||||
const { data: team, isLoading } = trpc.viewer.teams.get.useQuery(
|
||||
{ teamId: Number(router.query.id) },
|
||||
{ teamId: Number(params.id) },
|
||||
{
|
||||
onError: () => {
|
||||
router.push("/settings");
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useRouter } from "next/router";
|
||||
import { usePathname } from "next/navigation";
|
||||
|
||||
import { WEBAPP_URL } from "@calcom/lib/constants";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
@@ -8,9 +8,9 @@ import { ExternalLink } from "@calcom/ui/components/icon";
|
||||
import { getLayout } from "../../../settings/layouts/SettingsLayout";
|
||||
|
||||
const BillingView = () => {
|
||||
const pathname = usePathname();
|
||||
const { t } = useLocale();
|
||||
const router = useRouter();
|
||||
const returnTo = router.asPath;
|
||||
const returnTo = pathname;
|
||||
const billingHref = `/api/integrations/stripepayment/portal?returnTo=${WEBAPP_URL}${returnTo}`;
|
||||
return (
|
||||
<>
|
||||
|
||||
@@ -1,12 +1,13 @@
|
||||
import { useSession } from "next-auth/react";
|
||||
import { useRouter } from "next/router";
|
||||
import { useRouter, useSearchParams } from "next/navigation";
|
||||
import { useState } from "react";
|
||||
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import { useParamsWithFallback } from "@calcom/lib/hooks/useParamsWithFallback";
|
||||
import { MembershipRole } from "@calcom/prisma/enums";
|
||||
import { trpc } from "@calcom/trpc/react";
|
||||
import type { RouterOutputs } from "@calcom/trpc/react";
|
||||
import { Button, Meta, TextField, showToast } from "@calcom/ui";
|
||||
import { trpc } from "@calcom/trpc/react";
|
||||
import { Button, Meta, showToast, TextField } from "@calcom/ui";
|
||||
import { Plus } from "@calcom/ui/components/icon";
|
||||
|
||||
import { getLayout } from "../../../settings/layouts/SettingsLayout";
|
||||
@@ -64,16 +65,18 @@ function MembersList(props: MembersListProps) {
|
||||
}
|
||||
|
||||
const MembersView = () => {
|
||||
const searchParams = useSearchParams();
|
||||
const { t, i18n } = useLocale();
|
||||
|
||||
const router = useRouter();
|
||||
const session = useSession();
|
||||
|
||||
const utils = trpc.useContext();
|
||||
const params = useParamsWithFallback();
|
||||
|
||||
const teamId = Number(router.query.id);
|
||||
const teamId = Number(params.id);
|
||||
|
||||
const showDialog = router.query.inviteModal === "true";
|
||||
const showDialog = searchParams?.get("inviteModal") === "true";
|
||||
const [showMemberInvitationModal, setShowMemberInvitationModal] = useState(showDialog);
|
||||
const [showInviteLinkSettingsModal, setInviteLinkSettingsModal] = useState(false);
|
||||
|
||||
@@ -84,7 +87,7 @@ const MembersView = () => {
|
||||
distinctUser: true,
|
||||
},
|
||||
{
|
||||
enabled: router.isReady,
|
||||
enabled: searchParams !== null,
|
||||
}
|
||||
);
|
||||
|
||||
|
||||
@@ -2,8 +2,8 @@ import { zodResolver } from "@hookform/resolvers/zod";
|
||||
import type { Prisma } from "@prisma/client";
|
||||
import { useSession } from "next-auth/react";
|
||||
import Link from "next/link";
|
||||
import { useRouter } from "next/router";
|
||||
import { useState, useLayoutEffect } from "react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useLayoutEffect, useState } from "react";
|
||||
import { Controller, useForm } from "react-hook-form";
|
||||
import { z } from "zod";
|
||||
|
||||
@@ -12,29 +12,31 @@ import { getOrgFullDomain } from "@calcom/features/ee/organizations/lib/orgDomai
|
||||
import { IS_TEAM_BILLING_ENABLED, WEBAPP_URL } from "@calcom/lib/constants";
|
||||
import { getPlaceholderAvatar } from "@calcom/lib/defaultAvatarImage";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import { useParamsWithFallback } from "@calcom/lib/hooks/useParamsWithFallback";
|
||||
import { md } from "@calcom/lib/markdownIt";
|
||||
import { markdownToSafeHTML } from "@calcom/lib/markdownToSafeHTML";
|
||||
import objectKeys from "@calcom/lib/objectKeys";
|
||||
import turndown from "@calcom/lib/turndownService";
|
||||
import { MembershipRole } from "@calcom/prisma/enums";
|
||||
import { trpc } from "@calcom/trpc/react";
|
||||
import { SkeletonContainer, SkeletonText } from "@calcom/ui";
|
||||
import {
|
||||
Avatar,
|
||||
Button,
|
||||
ConfirmationDialogContent,
|
||||
Dialog,
|
||||
DialogTrigger,
|
||||
Editor,
|
||||
Form,
|
||||
ImageUploader,
|
||||
Label,
|
||||
LinkIconButton,
|
||||
Meta,
|
||||
showToast,
|
||||
SkeletonContainer,
|
||||
SkeletonText,
|
||||
TextField,
|
||||
Editor,
|
||||
} from "@calcom/ui";
|
||||
import { ExternalLink, Link as LinkIcon, Trash2, LogOut } from "@calcom/ui/components/icon";
|
||||
import { ExternalLink, Link as LinkIcon, LogOut, Trash2 } from "@calcom/ui/components/icon";
|
||||
|
||||
import { getLayout } from "../../../settings/layouts/SettingsLayout";
|
||||
|
||||
@@ -53,6 +55,8 @@ const teamProfileFormSchema = z.object({
|
||||
});
|
||||
|
||||
const ProfileView = () => {
|
||||
const params = useParamsWithFallback();
|
||||
const teamId = Number(params.id);
|
||||
const { t } = useLocale();
|
||||
const router = useRouter();
|
||||
const utils = trpc.useContext();
|
||||
@@ -79,9 +83,9 @@ const ProfileView = () => {
|
||||
});
|
||||
|
||||
const { data: team, isLoading } = trpc.viewer.teams.get.useQuery(
|
||||
{ teamId: Number(router.query.id) },
|
||||
{ teamId },
|
||||
{
|
||||
enabled: !!router.query.id,
|
||||
enabled: !!teamId,
|
||||
onError: () => {
|
||||
router.push("/settings");
|
||||
},
|
||||
|
||||
@@ -1,11 +1,20 @@
|
||||
import { noop } from "lodash";
|
||||
import { useRouter } from "next/router";
|
||||
import { useMemo } from "react";
|
||||
import { Controller, useForm } from "react-hook-form";
|
||||
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import { localeOptions } from "@calcom/lib/i18n";
|
||||
import { nameOfDay } from "@calcom/lib/weekday";
|
||||
import { Button, EmailField, Form, Label, Select, TextField, TimezoneSelect } from "@calcom/ui";
|
||||
import {
|
||||
Avatar,
|
||||
Button,
|
||||
EmailField,
|
||||
Form,
|
||||
ImageUploader,
|
||||
Label,
|
||||
Select,
|
||||
TextField,
|
||||
TimezoneSelect,
|
||||
} from "@calcom/ui";
|
||||
|
||||
import type { UserAdminRouterOutputs } from "../server/trpc-router";
|
||||
|
||||
@@ -38,16 +47,8 @@ export const UserForm = ({
|
||||
onSubmit: (data: FormValues) => void;
|
||||
submitLabel?: string;
|
||||
}) => {
|
||||
const router = useRouter();
|
||||
const { t } = useLocale();
|
||||
|
||||
const localeOptions = useMemo(() => {
|
||||
return (router.locales || []).map((locale) => ({
|
||||
value: locale,
|
||||
label: new Intl.DisplayNames(locale, { type: "language" }).of(locale) || "",
|
||||
}));
|
||||
}, [router.locales]);
|
||||
|
||||
const timeFormatOptions = [
|
||||
{ value: 12, label: t("12_hour") },
|
||||
{ value: 24, label: t("24_hour") },
|
||||
@@ -73,7 +74,7 @@ export const UserForm = ({
|
||||
{ value: "GOOGLE", label: "GOOGLE" },
|
||||
{ value: "SAML", label: "SAML" },
|
||||
];
|
||||
|
||||
const defaultLocale = defaultValues?.locale || localeOptions[0].value;
|
||||
const form = useForm<FormValues>({
|
||||
defaultValues: {
|
||||
avatar: defaultValues?.avatar,
|
||||
@@ -82,8 +83,8 @@ export const UserForm = ({
|
||||
email: defaultValues?.email,
|
||||
bio: defaultValues?.bio,
|
||||
locale: {
|
||||
value: defaultValues?.locale || localeOptions[0].value,
|
||||
label: localeOptions.find((option) => option.value === localeProp)?.label || "",
|
||||
value: defaultLocale,
|
||||
label: new Intl.DisplayNames(defaultLocale, { type: "language" }).of(defaultLocale) || "",
|
||||
},
|
||||
timeFormat: {
|
||||
value: defaultValues?.timeFormat || 12,
|
||||
@@ -111,8 +112,7 @@ export const UserForm = ({
|
||||
|
||||
return (
|
||||
<Form form={form} className="space-y-4" handleSubmit={onSubmit}>
|
||||
{/* TODO: Enable Avatar uploader in a follow up */}
|
||||
{/* <div className="flex items-center">
|
||||
<div className="flex items-center">
|
||||
<Controller
|
||||
control={form.control}
|
||||
name="avatar"
|
||||
@@ -133,7 +133,7 @@ export const UserForm = ({
|
||||
</>
|
||||
)}
|
||||
/>
|
||||
</div> */}
|
||||
</div>
|
||||
<Controller
|
||||
name="role"
|
||||
control={form.control}
|
||||
|
||||
@@ -32,16 +32,17 @@ function UsersTableBare() {
|
||||
showToast("User has been deleted", "success");
|
||||
// Lets not invalidated the whole cache, just remove the user from the cache.
|
||||
// usefull cause in prod this will be fetching 100k+ users
|
||||
utils.viewer.admin.listPaginated.setInfiniteData({ limit: FETCH_LIMIT }, (data) => {
|
||||
if (!data) {
|
||||
// FIXME: Tested locally and it doesnt't work, need to investigate
|
||||
utils.viewer.admin.listPaginated.setInfiniteData({ limit: FETCH_LIMIT }, (cachedData) => {
|
||||
if (!cachedData) {
|
||||
return {
|
||||
pages: [],
|
||||
pageParams: [],
|
||||
};
|
||||
}
|
||||
return {
|
||||
...data,
|
||||
pages: data.pages.map((page) => ({
|
||||
...cachedData,
|
||||
pages: cachedData.pages.map((page) => ({
|
||||
...page,
|
||||
rows: page.rows.filter((row) => row.id !== userToDelete),
|
||||
})),
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useRouter } from "next/router";
|
||||
import { usePathname, useRouter } from "next/navigation";
|
||||
|
||||
import { getParserWithGeneric } from "@calcom/prisma/zod-utils";
|
||||
import { trpc } from "@calcom/trpc/react";
|
||||
@@ -10,13 +10,14 @@ import { UserForm } from "../components/UserForm";
|
||||
import { userBodySchema } from "../schemas/userBodySchema";
|
||||
|
||||
const UsersAddView = () => {
|
||||
const pathname = usePathname();
|
||||
const router = useRouter();
|
||||
const utils = trpc.useContext();
|
||||
const mutation = trpc.viewer.users.add.useMutation({
|
||||
onSuccess: async () => {
|
||||
showToast("User added successfully", "success");
|
||||
await utils.viewer.users.list.invalidate();
|
||||
router.replace(router.asPath.replace("/add", ""));
|
||||
router.replace(pathname?.replace("/add", ""));
|
||||
},
|
||||
onError: (err) => {
|
||||
console.error(err.message);
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
import { useRouter } from "next/router";
|
||||
import { usePathname, useRouter } from "next/navigation";
|
||||
import { z } from "zod";
|
||||
|
||||
import NoSSR from "@calcom/core/components/NoSSR";
|
||||
import { useParamsWithFallback } from "@calcom/lib/hooks/useParamsWithFallback";
|
||||
import { getParserWithGeneric } from "@calcom/prisma/zod-utils";
|
||||
import { trpc } from "@calcom/trpc/react";
|
||||
import { Meta, showToast } from "@calcom/ui";
|
||||
@@ -14,8 +15,8 @@ import { userBodySchema } from "../schemas/userBodySchema";
|
||||
const userIdSchema = z.object({ id: z.coerce.number() });
|
||||
|
||||
const UsersEditPage = () => {
|
||||
const router = useRouter();
|
||||
const input = userIdSchema.safeParse(router.query);
|
||||
const params = useParamsWithFallback();
|
||||
const input = userIdSchema.safeParse(params);
|
||||
|
||||
if (!input.success) return <div>Invalid input</div>;
|
||||
|
||||
@@ -23,16 +24,16 @@ const UsersEditPage = () => {
|
||||
};
|
||||
|
||||
const UsersEditView = ({ userId }: { userId: number }) => {
|
||||
const pathname = usePathname();
|
||||
const router = useRouter();
|
||||
const [data] = trpc.viewer.users.get.useSuspenseQuery({ userId });
|
||||
const { user } = data;
|
||||
const utils = trpc.useContext();
|
||||
const mutation = trpc.viewer.users.update.useMutation({
|
||||
onSuccess: async () => {
|
||||
await utils.viewer.users.list.invalidate();
|
||||
await utils.viewer.users.get.invalidate();
|
||||
Promise.all([utils.viewer.users.list.invalidate(), utils.viewer.users.get.invalidate()]);
|
||||
showToast("User updated successfully", "success");
|
||||
router.replace(`${router.asPath.split("/users/")[0]}/users`);
|
||||
router.replace(`${pathname?.split("/users/")[0]}/users`);
|
||||
},
|
||||
onError: (err) => {
|
||||
console.error(err.message);
|
||||
@@ -52,8 +53,6 @@ const UsersEditView = ({ userId }: { userId: number }) => {
|
||||
...parsedValues,
|
||||
userId: user.id,
|
||||
};
|
||||
// TODO: Add support for avatar in the API
|
||||
delete data.avatar;
|
||||
// Don't send username if it's the same as the current one
|
||||
if (user.username === data.username) delete data.username;
|
||||
mutation.mutate(data);
|
||||
|
||||
@@ -30,8 +30,7 @@ const userBodySchema = User.pick({
|
||||
identityProvider: true,
|
||||
// away: true,
|
||||
role: true,
|
||||
// @note: disallowing avatar changes via API for now. We can add it later if needed. User should upload image via UI.
|
||||
// avatar: true,
|
||||
avatar: true,
|
||||
});
|
||||
|
||||
/** This helps to prevent reaching the 4MB payload limit by avoiding base64 and instead passing the avatar url */
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
import { useRouter } from "next/router";
|
||||
import { useRouter } from "next/navigation";
|
||||
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import { HttpError } from "@calcom/lib/http-error";
|
||||
import { trpc } from "@calcom/trpc/react";
|
||||
import type { SVGComponent } from "@calcom/types/SVGComponent";
|
||||
import { showToast, EmptyScreen as ClassicEmptyScreen, CreateButtonWithTeamsList } from "@calcom/ui";
|
||||
import { Smartphone, Mail, Zap } from "@calcom/ui/components/icon";
|
||||
import { CreateButtonWithTeamsList, EmptyScreen as ClassicEmptyScreen, showToast } from "@calcom/ui";
|
||||
import { Mail, Smartphone, Zap } from "@calcom/ui/components/icon";
|
||||
|
||||
type WorkflowExampleType = {
|
||||
Icon: SVGComponent;
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import Link from "next/link";
|
||||
import { useRouter } from "next/router";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useEffect, useState } from "react";
|
||||
|
||||
import useLockedFieldsManager from "@calcom/features/ee/managed-event-types/hooks/useLockedFieldsManager";
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useRouter } from "next/router";
|
||||
import { useRouter } from "next/navigation";
|
||||
import type { Dispatch, SetStateAction } from "react";
|
||||
import { useMemo, useState } from "react";
|
||||
import type { UseFormReturn } from "react-hook-form";
|
||||
@@ -163,7 +163,12 @@ export default function WorkflowDetailsPage(props: Props) {
|
||||
<div className="bg-muted border-subtle w-full rounded-md border p-3 py-5 md:ml-3 md:p-8">
|
||||
{form.getValues("trigger") && (
|
||||
<div>
|
||||
<WorkflowStepContainer form={form} user={props.user} teamId={teamId} readOnly={props.readOnly} />
|
||||
<WorkflowStepContainer
|
||||
form={form}
|
||||
user={props.user}
|
||||
teamId={teamId}
|
||||
readOnly={props.readOnly}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
{form.getValues("steps") && (
|
||||
@@ -211,7 +216,7 @@ export default function WorkflowDetailsPage(props: Props) {
|
||||
isOpenDialog={deleteDialogOpen}
|
||||
setIsOpenDialog={setDeleteDialogOpen}
|
||||
workflowId={workflowId}
|
||||
additionalFunction={async () => await router.push("/workflows")}
|
||||
additionalFunction={async () => router.push("/workflows")}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import type { Workflow, WorkflowStep, Membership } from "@prisma/client";
|
||||
import Link from "next/link";
|
||||
import { useRouter } from "next/router";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useState } from "react";
|
||||
|
||||
import classNames from "@calcom/lib/classNames";
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import type { WorkflowTriggerEvents } from "@prisma/client";
|
||||
import { WorkflowActions, WorkflowTemplates } from "@prisma/client";
|
||||
|
||||
import type { TimeFormat } from "@calcom/lib/timeFormat";
|
||||
import { WorkflowActions, WorkflowTemplates } from "@calcom/prisma/enums";
|
||||
|
||||
import {
|
||||
whatsappEventCancelledTemplate,
|
||||
@@ -10,6 +10,14 @@ import {
|
||||
whatsappReminderTemplate,
|
||||
} from "../lib/reminders/templates/whatsapp";
|
||||
|
||||
export function shouldScheduleEmailReminder(action: WorkflowActions) {
|
||||
return action === WorkflowActions.EMAIL_ATTENDEE || action === WorkflowActions.EMAIL_HOST;
|
||||
}
|
||||
|
||||
export function shouldScheduleSMSReminder(action: WorkflowActions) {
|
||||
return action === WorkflowActions.SMS_ATTENDEE || action === WorkflowActions.SMS_NUMBER;
|
||||
}
|
||||
|
||||
export function isSMSAction(action: WorkflowActions) {
|
||||
return action === WorkflowActions.SMS_ATTENDEE || action === WorkflowActions.SMS_NUMBER;
|
||||
}
|
||||
|
||||
@@ -6,8 +6,12 @@ import dayjs from "@calcom/dayjs";
|
||||
import logger from "@calcom/lib/logger";
|
||||
import prisma from "@calcom/prisma";
|
||||
import type { TimeUnit } from "@calcom/prisma/enums";
|
||||
import { WorkflowActions, WorkflowMethods, WorkflowTemplates } from "@calcom/prisma/enums";
|
||||
import { WorkflowTriggerEvents } from "@calcom/prisma/enums";
|
||||
import {
|
||||
WorkflowActions,
|
||||
WorkflowMethods,
|
||||
WorkflowTemplates,
|
||||
WorkflowTriggerEvents,
|
||||
} from "@calcom/prisma/enums";
|
||||
import { bookingMetadataSchema } from "@calcom/prisma/zod-utils";
|
||||
|
||||
import type { BookingInfo, timeUnitLowerCase } from "./smsReminderManager";
|
||||
@@ -26,6 +30,18 @@ if (process.env.SENDGRID_API_KEY) {
|
||||
client.setApiKey(sendgridAPIKey);
|
||||
}
|
||||
|
||||
async function getBatchId() {
|
||||
if (!process.env.SENDGRID_API_KEY) {
|
||||
console.info("No sendgrid API key provided, returning DUMMY_BATCH_ID");
|
||||
return "DUMMY_BATCH_ID";
|
||||
}
|
||||
const batchIdResponse = await client.request({
|
||||
url: "/v3/mail/batch",
|
||||
method: "POST",
|
||||
});
|
||||
return batchIdResponse[1].batch_id as string;
|
||||
}
|
||||
|
||||
export const scheduleEmailReminder = async (
|
||||
evt: BookingInfo,
|
||||
triggerEvent: WorkflowTriggerEvents,
|
||||
@@ -59,7 +75,6 @@ export const scheduleEmailReminder = async (
|
||||
|
||||
if (!process.env.SENDGRID_API_KEY || !process.env.SENDGRID_EMAIL) {
|
||||
console.error("Sendgrid credentials are missing from the .env file");
|
||||
return;
|
||||
}
|
||||
|
||||
const sandboxMode = process.env.NEXT_PUBLIC_IS_E2E ? true : false;
|
||||
@@ -133,10 +148,30 @@ export const scheduleEmailReminder = async (
|
||||
// Allows debugging generated email content without waiting for sendgrid to send emails
|
||||
log.debug(`Sending Email for trigger ${triggerEvent}`, JSON.stringify(emailContent));
|
||||
|
||||
const batchIdResponse = await client.request({
|
||||
url: "/v3/mail/batch",
|
||||
method: "POST",
|
||||
});
|
||||
const batchId = await getBatchId();
|
||||
|
||||
function sendEmail(data: Partial<MailData>) {
|
||||
if (!process.env.SENDGRID_API_KEY) {
|
||||
console.info("No sendgrid API key provided, skipping email");
|
||||
return Promise.resolve();
|
||||
}
|
||||
return sgMail.send({
|
||||
to: data.to,
|
||||
from: {
|
||||
email: senderEmail,
|
||||
name: sender,
|
||||
},
|
||||
subject: emailContent.emailSubject,
|
||||
html: emailContent.emailBody,
|
||||
batchId,
|
||||
replyTo: evt.organizer.email,
|
||||
mailSettings: {
|
||||
sandboxMode: {
|
||||
enable: sandboxMode,
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
if (
|
||||
triggerEvent === WorkflowTriggerEvents.NEW_EVENT ||
|
||||
@@ -144,43 +179,11 @@ export const scheduleEmailReminder = async (
|
||||
triggerEvent === WorkflowTriggerEvents.RESCHEDULE_EVENT
|
||||
) {
|
||||
try {
|
||||
if (Array.isArray(sendTo)) {
|
||||
for (const email of sendTo) {
|
||||
await sgMail.send({
|
||||
to: email,
|
||||
from: {
|
||||
email: senderEmail,
|
||||
name: sender,
|
||||
},
|
||||
subject: emailContent.emailSubject,
|
||||
html: emailContent.emailBody,
|
||||
batchId: batchIdResponse[1].batch_id,
|
||||
replyTo: evt.organizer.email,
|
||||
mailSettings: {
|
||||
sandboxMode: {
|
||||
enable: sandboxMode,
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
} else {
|
||||
await sgMail.send({
|
||||
to: sendTo,
|
||||
from: {
|
||||
email: senderEmail,
|
||||
name: sender,
|
||||
},
|
||||
subject: emailContent.emailSubject,
|
||||
html: emailContent.emailBody,
|
||||
batchId: batchIdResponse[1].batch_id,
|
||||
replyTo: evt.organizer.email,
|
||||
mailSettings: {
|
||||
sandboxMode: {
|
||||
enable: sandboxMode,
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
if (!sendTo) throw new Error("No email addresses provided");
|
||||
const addressees = Array.isArray(sendTo) ? sendTo : [sendTo];
|
||||
const promises = addressees.map((email) => sendEmail({ to: email }));
|
||||
// TODO: Maybe don't await for this?
|
||||
await Promise.all(promises);
|
||||
} catch (error) {
|
||||
console.log("Error sending Email");
|
||||
}
|
||||
@@ -196,24 +199,11 @@ export const scheduleEmailReminder = async (
|
||||
!scheduledDate.isAfter(currentDate.add(72, "hour"))
|
||||
) {
|
||||
try {
|
||||
await sgMail.send({
|
||||
// If sendEmail failed then workflowReminer will not be created, failing E2E tests
|
||||
await sendEmail({
|
||||
to: sendTo,
|
||||
from: {
|
||||
email: senderEmail,
|
||||
name: sender,
|
||||
},
|
||||
subject: emailContent.emailSubject,
|
||||
html: emailContent.emailBody,
|
||||
batchId: batchIdResponse[1].batch_id,
|
||||
sendAt: scheduledDate.unix(),
|
||||
replyTo: evt.organizer.email,
|
||||
mailSettings: {
|
||||
sandboxMode: {
|
||||
enable: sandboxMode,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
await prisma.workflowReminder.create({
|
||||
data: {
|
||||
bookingUid: uid,
|
||||
@@ -221,7 +211,7 @@ export const scheduleEmailReminder = async (
|
||||
method: WorkflowMethods.EMAIL,
|
||||
scheduledDate: scheduledDate.toDate(),
|
||||
scheduled: true,
|
||||
referenceId: batchIdResponse[1].batch_id,
|
||||
referenceId: batchId,
|
||||
seatReferenceId: seatReferenceUid,
|
||||
},
|
||||
});
|
||||
|
||||
@@ -2,13 +2,12 @@ import type { Workflow, WorkflowsOnEventTypes, WorkflowStep } from "@prisma/clie
|
||||
|
||||
import { isWhatsappAction } from "@calcom/features/ee/workflows/lib/actionHelperFunctions";
|
||||
import { SENDER_ID, SENDER_NAME } from "@calcom/lib/constants";
|
||||
import { WorkflowMethods, WorkflowTriggerEvents } from "@calcom/prisma/enums";
|
||||
import { WorkflowActions } from "@calcom/prisma/enums";
|
||||
import { WorkflowActions, WorkflowMethods, WorkflowTriggerEvents } from "@calcom/prisma/enums";
|
||||
import type { CalendarEvent } from "@calcom/types/Calendar";
|
||||
|
||||
import { scheduleEmailReminder, deleteScheduledEmailReminder } from "./emailReminderManager";
|
||||
import { scheduleSMSReminder, deleteScheduledSMSReminder } from "./smsReminderManager";
|
||||
import { scheduleWhatsappReminder, deleteScheduledWhatsappReminder } from "./whatsappReminderManager";
|
||||
import { deleteScheduledEmailReminder, scheduleEmailReminder } from "./emailReminderManager";
|
||||
import { deleteScheduledSMSReminder, scheduleSMSReminder } from "./smsReminderManager";
|
||||
import { deleteScheduledWhatsappReminder, scheduleWhatsappReminder } from "./whatsappReminderManager";
|
||||
|
||||
type ExtendedCalendarEvent = CalendarEvent & {
|
||||
metadata?: { videoCallUrl: string | undefined };
|
||||
@@ -199,7 +198,6 @@ export interface SendCancelledRemindersArgs {
|
||||
|
||||
export const sendCancelledReminders = async (args: SendCancelledRemindersArgs) => {
|
||||
const { workflows, smsReminderNumber, evt, hideBranding } = args;
|
||||
|
||||
if (!workflows.length) return;
|
||||
|
||||
for (const workflowRef of workflows) {
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { useSession } from "next-auth/react";
|
||||
import { useRouter } from "next/router";
|
||||
import { useRouter } from "next/navigation";
|
||||
import type { Dispatch, SetStateAction } from "react";
|
||||
import { useState } from "react";
|
||||
|
||||
@@ -7,9 +7,10 @@ import Shell from "@calcom/features/shell/Shell";
|
||||
import { classNames } from "@calcom/lib";
|
||||
import { WEBAPP_URL } from "@calcom/lib/constants";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import { useRouterQuery } from "@calcom/lib/hooks/useRouterQuery";
|
||||
import { HttpError } from "@calcom/lib/http-error";
|
||||
import { trpc } from "@calcom/trpc/react";
|
||||
import { AnimatedPopover, Avatar, showToast, CreateButtonWithTeamsList } from "@calcom/ui";
|
||||
import { AnimatedPopover, Avatar, CreateButtonWithTeamsList, showToast } from "@calcom/ui";
|
||||
|
||||
import { FilterResults } from "../../../filters/components/FilterResults";
|
||||
import { TeamsFilter } from "../../../filters/components/TeamsFilter";
|
||||
@@ -23,12 +24,8 @@ function WorkflowsPage() {
|
||||
const { t } = useLocale();
|
||||
const session = useSession();
|
||||
const router = useRouter();
|
||||
const [checkedFilterItems, setCheckedFilterItems] = useState<{ userId: number | null; teamIds: number[] }>({
|
||||
userId: session.data?.user.id || null,
|
||||
teamIds: [],
|
||||
});
|
||||
|
||||
const filters = getTeamsFiltersFromQuery(router.query);
|
||||
const routerQuery = useRouterQuery();
|
||||
const filters = getTeamsFiltersFromQuery(routerQuery);
|
||||
|
||||
const queryRes = trpc.viewer.workflows.filteredList.useQuery({
|
||||
filters,
|
||||
|
||||
@@ -2,7 +2,7 @@ import { zodResolver } from "@hookform/resolvers/zod";
|
||||
import type { WorkflowStep } from "@prisma/client";
|
||||
import { isValidPhoneNumber } from "libphonenumber-js";
|
||||
import { useSession } from "next-auth/react";
|
||||
import { useRouter } from "next/router";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useEffect, useState } from "react";
|
||||
import { useForm } from "react-hook-form";
|
||||
import { z } from "zod";
|
||||
@@ -11,15 +11,20 @@ import Shell from "@calcom/features/shell/Shell";
|
||||
import { classNames } from "@calcom/lib";
|
||||
import { SENDER_ID } from "@calcom/lib/constants";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import { useParamsWithFallback } from "@calcom/lib/hooks/useParamsWithFallback";
|
||||
import { HttpError } from "@calcom/lib/http-error";
|
||||
import { TimeUnit, WorkflowActions, WorkflowTemplates } from "@calcom/prisma/enums";
|
||||
import { WorkflowTriggerEvents, MembershipRole } from "@calcom/prisma/enums";
|
||||
import {
|
||||
MembershipRole,
|
||||
TimeUnit,
|
||||
WorkflowActions,
|
||||
WorkflowTemplates,
|
||||
WorkflowTriggerEvents,
|
||||
} from "@calcom/prisma/enums";
|
||||
import { stringOrNumber } from "@calcom/prisma/zod-utils";
|
||||
import { trpc } from "@calcom/trpc/react";
|
||||
import useMeQuery from "@calcom/trpc/react/hooks/useMeQuery";
|
||||
import type { MultiSelectCheckboxesOptionType as Option } from "@calcom/ui";
|
||||
import { Alert, Button, Form, showToast, Badge } from "@calcom/ui";
|
||||
|
||||
import useMeQuery from "@lib/hooks/useMeQuery";
|
||||
import { Alert, Badge, Button, Form, showToast } from "@calcom/ui";
|
||||
|
||||
import LicenseRequired from "../../common/components/LicenseRequired";
|
||||
import SkeletonLoader from "../components/SkeletonLoaderEdit";
|
||||
@@ -82,6 +87,7 @@ function WorkflowPage() {
|
||||
const { t, i18n } = useLocale();
|
||||
const session = useSession();
|
||||
const router = useRouter();
|
||||
const params = useParamsWithFallback();
|
||||
|
||||
const [selectedEventTypes, setSelectedEventTypes] = useState<Option[]>([]);
|
||||
const [isAllDataLoaded, setIsAllDataLoaded] = useState(false);
|
||||
@@ -92,7 +98,7 @@ function WorkflowPage() {
|
||||
resolver: zodResolver(formSchema),
|
||||
});
|
||||
|
||||
const { workflow: workflowId } = router.isReady ? querySchema.parse(router.query) : { workflow: -1 };
|
||||
const { workflow: workflowId } = params ? querySchema.parse(params) : { workflow: -1 };
|
||||
const utils = trpc.useContext();
|
||||
|
||||
const userQuery = useMeQuery();
|
||||
@@ -106,7 +112,7 @@ function WorkflowPage() {
|
||||
} = trpc.viewer.workflows.get.useQuery(
|
||||
{ id: +workflowId },
|
||||
{
|
||||
enabled: router.isReady && !!workflowId,
|
||||
enabled: !!workflowId,
|
||||
}
|
||||
);
|
||||
|
||||
@@ -186,7 +192,7 @@ function WorkflowPage() {
|
||||
"success"
|
||||
);
|
||||
}
|
||||
await router.push("/workflows");
|
||||
router.push("/workflows");
|
||||
},
|
||||
onError: (err) => {
|
||||
if (err instanceof HttpError) {
|
||||
@@ -245,7 +251,7 @@ function WorkflowPage() {
|
||||
});
|
||||
}
|
||||
updateMutation.mutate({
|
||||
id: parseInt(router.query.workflow as string, 10),
|
||||
id: workflowId,
|
||||
name: values.name,
|
||||
activeOn: activeOnEventTypeIds,
|
||||
steps: values.steps,
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { zodResolver } from "@hookform/resolvers/zod";
|
||||
import { isValidPhoneNumber } from "libphonenumber-js";
|
||||
import { useRouter } from "next/router";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useEffect } from "react";
|
||||
import { useState } from "react";
|
||||
import { useForm } from "react-hook-form";
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { useRouter } from "next/router";
|
||||
import { useSearchParams } from "next/navigation";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useEffect, useState } from "react";
|
||||
import { useForm } from "react-hook-form";
|
||||
import { z } from "zod";
|
||||
@@ -32,6 +33,7 @@ const querySchema = z.object({
|
||||
});
|
||||
|
||||
const DuplicateDialog = () => {
|
||||
const searchParams = useSearchParams();
|
||||
const { t } = useLocale();
|
||||
const router = useRouter();
|
||||
const [firstRender, setFirstRender] = useState(true);
|
||||
@@ -49,14 +51,17 @@ const DuplicateDialog = () => {
|
||||
const { register } = form;
|
||||
|
||||
useEffect(() => {
|
||||
if (router.query.dialog === "duplicate") {
|
||||
form.setValue("id", Number(router.query.id as string) || -1);
|
||||
form.setValue("title", (router.query.title as string) || "");
|
||||
form.setValue("slug", t("event_type_duplicate_copy_text", { slug: router.query.slug as string }));
|
||||
form.setValue("description", (router.query.description as string) || "");
|
||||
form.setValue("length", Number(router.query.length) || 30);
|
||||
if (searchParams?.get("dialog") === "duplicate") {
|
||||
form.setValue("id", Number(searchParams?.get("id") as string) || -1);
|
||||
form.setValue("title", (searchParams?.get("title") as string) || "");
|
||||
form.setValue(
|
||||
"slug",
|
||||
t("event_type_duplicate_copy_text", { slug: searchParams?.get("slug") as string })
|
||||
);
|
||||
form.setValue("description", (searchParams?.get("description") as string) || "");
|
||||
form.setValue("length", Number(searchParams?.get("length")) || 30);
|
||||
}
|
||||
}, [router.query.dialog]);
|
||||
}, [searchParams?.get("dialog")]);
|
||||
|
||||
const duplicateMutation = trpc.viewer.eventTypes.duplicate.useMutation({
|
||||
onSuccess: async ({ eventType }) => {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useRouter } from "next/router";
|
||||
import { usePathname, useRouter, useSearchParams } from "next/navigation";
|
||||
import { useState } from "react";
|
||||
import { z } from "zod";
|
||||
|
||||
@@ -8,35 +8,36 @@ import type { FilterContextType } from "./provider";
|
||||
import { FilterProvider } from "./provider";
|
||||
|
||||
export function FiltersProvider({ children }: { children: React.ReactNode }) {
|
||||
// useRouter to get initial values from query params
|
||||
// searchParams to get initial values from query params
|
||||
const searchParams = useSearchParams();
|
||||
const router = useRouter();
|
||||
const { startTime, endTime, teamId, userId, eventTypeId, filter, memberUserId } = router.query;
|
||||
const pathname = usePathname();
|
||||
const querySchema = z.object({
|
||||
startTime: z.string().optional(),
|
||||
endTime: z.string().optional(),
|
||||
teamId: z.coerce.number().optional(),
|
||||
userId: z.coerce.number().optional(),
|
||||
memberUserId: z.coerce.number().optional(),
|
||||
eventTypeId: z.coerce.number().optional(),
|
||||
filter: z.enum(["event-type", "user"]).optional(),
|
||||
startTime: z.string().nullable(),
|
||||
endTime: z.string().nullable(),
|
||||
teamId: z.coerce.number().nullable(),
|
||||
userId: z.coerce.number().nullable(),
|
||||
memberUserId: z.coerce.number().nullable(),
|
||||
eventTypeId: z.coerce.number().nullable(),
|
||||
filter: z.enum(["event-type", "user"]).nullable(),
|
||||
});
|
||||
|
||||
let startTimeParsed,
|
||||
endTimeParsed,
|
||||
teamIdParsed: number | undefined,
|
||||
teamIdParsed: number | undefined | null,
|
||||
userIdParsed,
|
||||
eventTypeIdParsed,
|
||||
filterParsed,
|
||||
memberUserIdParsed;
|
||||
|
||||
const safe = querySchema.safeParse({
|
||||
startTime,
|
||||
endTime,
|
||||
teamId,
|
||||
userId,
|
||||
eventTypeId,
|
||||
filter,
|
||||
memberUserId,
|
||||
startTime: searchParams.get("startTime"),
|
||||
endTime: searchParams.get("endTime"),
|
||||
teamId: searchParams.get("teamId"),
|
||||
userId: searchParams.get("userId"),
|
||||
eventTypeId: searchParams.get("eventTypeId"),
|
||||
filter: searchParams.get("filter"),
|
||||
memberUserId: searchParams.get("memberUserId"),
|
||||
});
|
||||
|
||||
if (!safe.success) {
|
||||
@@ -115,24 +116,19 @@ export function FiltersProvider({ children }: { children: React.ReactNode }) {
|
||||
dateRange,
|
||||
} = newConfigFilters;
|
||||
const [startTime, endTime] = dateRange || [null, null];
|
||||
|
||||
const mergedQueryParams = {
|
||||
...(router.query || {}),
|
||||
...(selectedMemberUserId !== undefined && { memberUserId: selectedMemberUserId }),
|
||||
...(selectedTeamId !== undefined && { teamId: selectedTeamId }),
|
||||
...(selectedUserId !== undefined && { userId: selectedUserId }),
|
||||
...(selectedEventTypeId !== undefined && { eventTypeId: selectedEventTypeId }),
|
||||
...(selectedFilter !== undefined &&
|
||||
selectedFilter &&
|
||||
selectedFilter?.length > 0 && { filter: selectedFilter[0] }),
|
||||
...(isAll !== undefined && { isAll }),
|
||||
...(startTime !== undefined && startTime && { startTime: startTime.toISOString() }),
|
||||
...(endTime !== undefined && endTime && { endTime: endTime.toISOString() }),
|
||||
};
|
||||
|
||||
router.push({
|
||||
query: mergedQueryParams,
|
||||
});
|
||||
const newSearchParams = new URLSearchParams(searchParams);
|
||||
function setParamsIfDefined(key: string, value: string | number | boolean | null | undefined) {
|
||||
if (value !== undefined && value !== null) newSearchParams.set(key, value.toString());
|
||||
}
|
||||
setParamsIfDefined("memberUserId", selectedMemberUserId);
|
||||
setParamsIfDefined("teamId", selectedTeamId);
|
||||
setParamsIfDefined("userId", selectedUserId);
|
||||
setParamsIfDefined("eventTypeId", selectedEventTypeId);
|
||||
setParamsIfDefined("isAll", isAll);
|
||||
setParamsIfDefined("startTime", startTime?.toISOString());
|
||||
setParamsIfDefined("endTime", endTime?.toISOString());
|
||||
setParamsIfDefined("filter", selectedFilter?.[0]);
|
||||
router.push(`${pathname}?${newSearchParams.toString()}`);
|
||||
},
|
||||
clearFilters: () => {
|
||||
const { initialConfig } = configFilters;
|
||||
@@ -152,12 +148,11 @@ export function FiltersProvider({ children }: { children: React.ReactNode }) {
|
||||
initialConfig,
|
||||
});
|
||||
|
||||
router.push({
|
||||
query: {
|
||||
...(teamId && { teamId: teamId }),
|
||||
...(userId && { userId: userId }),
|
||||
},
|
||||
});
|
||||
const newSearchParams = new URLSearchParams();
|
||||
if (teamId) newSearchParams.set("teamId", teamId.toString());
|
||||
if (userId) newSearchParams.set("userId", userId.toString());
|
||||
|
||||
router.push(`${pathname}?${newSearchParams.toString()}`);
|
||||
},
|
||||
}}>
|
||||
{children}
|
||||
|
||||
@@ -10,7 +10,7 @@ import {
|
||||
useRegisterActions,
|
||||
} from "kbar";
|
||||
import type { Action } from "kbar";
|
||||
import { useRouter } from "next/router";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useMemo } from "react";
|
||||
|
||||
import { appStoreMetadata } from "@calcom/app-store/appStoreMetaData";
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useRouter } from "next/router";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useForm } from "react-hook-form";
|
||||
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "@radix-ui/react-collapsible";
|
||||
import { useSession } from "next-auth/react";
|
||||
import Link from "next/link";
|
||||
import { useRouter } from "next/router";
|
||||
import { usePathname, useRouter, useSearchParams } from "next/navigation";
|
||||
import type { ComponentProps } from "react";
|
||||
import React, { Suspense, useEffect, useState } from "react";
|
||||
|
||||
@@ -10,26 +10,25 @@ import { classNames } from "@calcom/lib";
|
||||
import { HOSTED_CAL_FEATURES, WEBAPP_URL } from "@calcom/lib/constants";
|
||||
import { getPlaceholderAvatar } from "@calcom/lib/defaultAvatarImage";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import { IdentityProvider } from "@calcom/prisma/enums";
|
||||
import { MembershipRole, UserPermissionRole } from "@calcom/prisma/enums";
|
||||
import { IdentityProvider, MembershipRole, UserPermissionRole } from "@calcom/prisma/enums";
|
||||
import { trpc } from "@calcom/trpc/react";
|
||||
import useAvatarQuery from "@calcom/trpc/react/hooks/useAvatarQuery";
|
||||
import type { VerticalTabItemProps } from "@calcom/ui";
|
||||
import { Badge, Button, ErrorBoundary, Skeleton, useMeta, VerticalTabItem } from "@calcom/ui";
|
||||
import {
|
||||
User,
|
||||
Key,
|
||||
CreditCard,
|
||||
Terminal,
|
||||
Users,
|
||||
Loader,
|
||||
Lock,
|
||||
ArrowLeft,
|
||||
Building,
|
||||
ChevronDown,
|
||||
ChevronRight,
|
||||
Plus,
|
||||
CreditCard,
|
||||
Key,
|
||||
Loader,
|
||||
Lock,
|
||||
Menu,
|
||||
Building,
|
||||
Plus,
|
||||
Terminal,
|
||||
User,
|
||||
Users,
|
||||
} from "@calcom/ui/components/icon";
|
||||
|
||||
const tabs: VerticalTabItemProps[] = [
|
||||
@@ -193,20 +192,23 @@ const SettingsSidebarContainer = ({
|
||||
navigationIsOpenedOnMobile,
|
||||
bannersHeight,
|
||||
}: SettingsSidebarContainerProps) => {
|
||||
const searchParams = useSearchParams();
|
||||
const { t } = useLocale();
|
||||
const router = useRouter();
|
||||
const tabsWithPermissions = useTabs();
|
||||
const [teamMenuState, setTeamMenuState] =
|
||||
useState<{ teamId: number | undefined; teamMenuOpen: boolean }[]>();
|
||||
|
||||
const { data: teams } = trpc.viewer.teams.list.useQuery();
|
||||
const { data: currentOrg } = trpc.viewer.organizations.listCurrent.useQuery();
|
||||
const session = useSession();
|
||||
const { data: currentOrg } = trpc.viewer.organizations.listCurrent.useQuery(undefined, {
|
||||
enabled: !!session.data?.user?.organizationId,
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
if (teams) {
|
||||
const teamStates = teams?.map((team) => ({
|
||||
teamId: team.id,
|
||||
teamMenuOpen: String(team.id) === router.query.id,
|
||||
teamMenuOpen: String(team.id) === searchParams?.get("id"),
|
||||
}));
|
||||
setTeamMenuState(teamStates);
|
||||
setTimeout(() => {
|
||||
@@ -216,7 +218,7 @@ const SettingsSidebarContainer = ({
|
||||
tabMembers?.scrollIntoView({ behavior: "smooth" });
|
||||
}, 100);
|
||||
}
|
||||
}, [router.query.id, teams]);
|
||||
}, [searchParams?.get("id"), teams]);
|
||||
|
||||
return (
|
||||
<nav
|
||||
@@ -363,11 +365,11 @@ const SettingsSidebarContainer = ({
|
||||
<>
|
||||
{/* TODO */}
|
||||
{/* <VerticalTabItem
|
||||
name={t("general")}
|
||||
href={`${WEBAPP_URL}/settings/my-account/appearance`}
|
||||
textClassNames="px-3 text-emphasis font-medium text-sm"
|
||||
disableChevron
|
||||
/> */}
|
||||
name={t("general")}
|
||||
href={`${WEBAPP_URL}/settings/my-account/appearance`}
|
||||
textClassNames="px-3 text-emphasis font-medium text-sm"
|
||||
disableChevron
|
||||
/> */}
|
||||
<VerticalTabItem
|
||||
name={t("appearance")}
|
||||
href={`/settings/teams/${team.id}/appearance`}
|
||||
@@ -445,7 +447,7 @@ export default function SettingsLayout({
|
||||
children,
|
||||
...rest
|
||||
}: { children: React.ReactNode } & ComponentProps<typeof Shell>) {
|
||||
const router = useRouter();
|
||||
const pathname = usePathname();
|
||||
const state = useState(false);
|
||||
const { t } = useLocale();
|
||||
const [sideContainerOpen, setSideContainerOpen] = state;
|
||||
@@ -467,7 +469,7 @@ export default function SettingsLayout({
|
||||
if (sideContainerOpen) {
|
||||
setSideContainerOpen(!sideContainerOpen);
|
||||
}
|
||||
}, [router.asPath]);
|
||||
}, [pathname]);
|
||||
|
||||
return (
|
||||
<Shell
|
||||
|
||||
@@ -1,80 +0,0 @@
|
||||
import { useNProgress } from "@tanem/react-nprogress";
|
||||
import type { NextRouter } from "next/router";
|
||||
import type { PropsWithChildren } from "react";
|
||||
import { useEffect, useState, forwardRef } from "react";
|
||||
|
||||
import { classNames } from "@calcom/lib";
|
||||
|
||||
interface NProgressOptions {
|
||||
isAnimating: boolean;
|
||||
}
|
||||
|
||||
export type NProgressProps = PropsWithChildren<NProgressOptions>;
|
||||
|
||||
const NProgress = forwardRef<HTMLDivElement, NProgressProps>(({ isAnimating, ...rest }, ref) => {
|
||||
const { animationDuration, isFinished, progress } = useNProgress({
|
||||
isAnimating,
|
||||
});
|
||||
|
||||
return (
|
||||
<div
|
||||
{...rest}
|
||||
ref={ref}
|
||||
className={classNames("fixed left-0 top-0 w-full", isFinished ? "opacity-0" : "opacity-100")}
|
||||
style={{
|
||||
transition: `opacity ${animationDuration}ms linear`,
|
||||
}}>
|
||||
<div
|
||||
className="bg-brand-emphasis h-0.5 w-full"
|
||||
style={{
|
||||
marginLeft: `${(-1 + progress) * 100}%`,
|
||||
transition: `margin-left ${animationDuration}ms linear`,
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
});
|
||||
|
||||
NProgress.displayName = "NProgress";
|
||||
|
||||
export const NProgressNextRouter = ({ router }: { router: NextRouter }) => {
|
||||
const [state, setState] = useState({
|
||||
isRouteChanging: false,
|
||||
loadingKey: 0,
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
const handleRouteChangeStart = () => {
|
||||
setState((prevState) => ({
|
||||
...prevState,
|
||||
isRouteChanging: true,
|
||||
loadingKey: prevState.loadingKey ^ 1,
|
||||
}));
|
||||
};
|
||||
|
||||
const handleRouteChangeEnd = () => {
|
||||
setState((prevState) => ({
|
||||
...prevState,
|
||||
isRouteChanging: false,
|
||||
}));
|
||||
};
|
||||
|
||||
router.events.on("routeChangeStart", handleRouteChangeStart);
|
||||
router.events.on("routeChangeComplete", handleRouteChangeEnd);
|
||||
router.events.on("routeChangeError", handleRouteChangeEnd);
|
||||
|
||||
return () => {
|
||||
router.events.off("routeChangeStart", handleRouteChangeStart);
|
||||
router.events.off("routeChangeComplete", handleRouteChangeEnd);
|
||||
router.events.off("routeChangeError", handleRouteChangeEnd);
|
||||
};
|
||||
}, [router.events]);
|
||||
|
||||
const isAnimating = state.isRouteChanging;
|
||||
|
||||
return (
|
||||
<>
|
||||
<NProgress isAnimating={isAnimating} key={state.loadingKey} />
|
||||
</>
|
||||
);
|
||||
};
|
||||
@@ -2,10 +2,9 @@ import type { User as UserAuth } from "next-auth";
|
||||
import { signOut, useSession } from "next-auth/react";
|
||||
import dynamic from "next/dynamic";
|
||||
import Link from "next/link";
|
||||
import type { NextRouter } from "next/router";
|
||||
import { useRouter } from "next/router";
|
||||
import type { Dispatch, ReactNode, SetStateAction, ReactElement } from "react";
|
||||
import React, { Fragment, useEffect, useState, useRef, useMemo, cloneElement } from "react";
|
||||
import { usePathname, useRouter } from "next/navigation";
|
||||
import type { Dispatch, ReactElement, ReactNode, SetStateAction } from "react";
|
||||
import React, { cloneElement, Fragment, useEffect, useMemo, useRef, useState } from "react";
|
||||
import { Toaster } from "react-hot-toast";
|
||||
|
||||
import dayjs from "@calcom/dayjs";
|
||||
@@ -36,6 +35,7 @@ import type { SVGComponent } from "@calcom/types/SVGComponent";
|
||||
import {
|
||||
Avatar,
|
||||
Button,
|
||||
ButtonOrLink,
|
||||
Credits,
|
||||
Dropdown,
|
||||
DropdownItem,
|
||||
@@ -47,18 +47,19 @@ import {
|
||||
ErrorBoundary,
|
||||
HeadSeo,
|
||||
Logo,
|
||||
showToast,
|
||||
SkeletonText,
|
||||
Tooltip,
|
||||
showToast,
|
||||
useCalcomTheme,
|
||||
ButtonOrLink,
|
||||
} from "@calcom/ui";
|
||||
import {
|
||||
ArrowLeft,
|
||||
ArrowRight,
|
||||
BarChart,
|
||||
Calendar,
|
||||
ChevronDown,
|
||||
Clock,
|
||||
Copy,
|
||||
Download,
|
||||
ExternalLink,
|
||||
FileText,
|
||||
@@ -69,18 +70,15 @@ import {
|
||||
Map,
|
||||
Moon,
|
||||
MoreHorizontal,
|
||||
ChevronDown,
|
||||
Copy,
|
||||
Settings,
|
||||
User as UserIcon,
|
||||
Users,
|
||||
Zap,
|
||||
User as UserIcon,
|
||||
} from "@calcom/ui/components/icon";
|
||||
import { Discord } from "@calcom/ui/components/icon/Discord";
|
||||
|
||||
import { useOrgBranding } from "../ee/organizations/context/provider";
|
||||
import FreshChatProvider from "../ee/support/lib/freshchat/FreshChatProvider";
|
||||
import { NProgressNextRouter } from "./NProgressPageIndicator";
|
||||
import { TeamInviteBadge } from "./TeamInviteBadge";
|
||||
|
||||
// need to import without ssr to prevent hydration errors
|
||||
@@ -120,12 +118,9 @@ function useRedirectToLoginIfUnauthenticated(isPublic = false) {
|
||||
}
|
||||
|
||||
if (!loading && !session) {
|
||||
router.replace({
|
||||
pathname: "/auth/login",
|
||||
query: {
|
||||
callbackUrl: `${WEBAPP_URL}${location.pathname}${location.search}`,
|
||||
},
|
||||
});
|
||||
const urlSearchParams = new URLSearchParams();
|
||||
urlSearchParams.set("callbackUrl", `${WEBAPP_URL}${location.pathname}${location.search}`);
|
||||
router.replace(`/auth/login?${urlSearchParams.toString()}`);
|
||||
}
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [loading, session, isPublic]);
|
||||
@@ -161,7 +156,6 @@ function AppTop({ setBannersHeight }: { setBannersHeight: Dispatch<SetStateActio
|
||||
|
||||
return (
|
||||
<div ref={bannerRef} className="sticky top-0 z-10 w-full divide-y divide-black">
|
||||
<NProgressNextRouter router={router} />
|
||||
<TeamsUpgradeBanner />
|
||||
<OrgUpgradeBanner />
|
||||
<ImpersonatingBanner />
|
||||
@@ -185,9 +179,7 @@ function useRedirectToOnboardingIfNeeded() {
|
||||
|
||||
useEffect(() => {
|
||||
if (isRedirectingToOnboarding && !needsEmailVerification) {
|
||||
router.replace({
|
||||
pathname: "/getting-started",
|
||||
});
|
||||
router.replace("/getting-started");
|
||||
}
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [isRedirectingToOnboarding, needsEmailVerification]);
|
||||
@@ -513,11 +505,11 @@ export type NavigationItemType = {
|
||||
isCurrent?: ({
|
||||
item,
|
||||
isChild,
|
||||
router,
|
||||
pathname,
|
||||
}: {
|
||||
item: Pick<NavigationItemType, "href">;
|
||||
isChild?: boolean;
|
||||
router: NextRouter;
|
||||
pathname: string;
|
||||
}) => boolean;
|
||||
};
|
||||
|
||||
@@ -535,10 +527,7 @@ const navigation: NavigationItemType[] = [
|
||||
href: "/bookings/upcoming",
|
||||
icon: Calendar,
|
||||
badge: <UnconfirmedBookingBadge />,
|
||||
isCurrent: ({ router }) => {
|
||||
const path = router.asPath.split("?")[0];
|
||||
return path.startsWith("/bookings");
|
||||
},
|
||||
isCurrent: ({ pathname }) => pathname?.startsWith("/bookings"),
|
||||
},
|
||||
{
|
||||
name: "availability",
|
||||
@@ -556,30 +545,27 @@ const navigation: NavigationItemType[] = [
|
||||
name: "apps",
|
||||
href: "/apps",
|
||||
icon: Grid,
|
||||
isCurrent: ({ router, item }) => {
|
||||
const path = router.asPath.split("?")[0];
|
||||
isCurrent: ({ pathname: path, item }) => {
|
||||
// During Server rendering path is /v2/apps but on client it becomes /apps(weird..)
|
||||
return path.startsWith(item.href) || path.startsWith("/v2" + item.href);
|
||||
return path?.startsWith(item.href) || path?.startsWith("/v2" + item.href);
|
||||
},
|
||||
child: [
|
||||
{
|
||||
name: "app_store",
|
||||
href: "/apps",
|
||||
isCurrent: ({ router, item }) => {
|
||||
const path = router.asPath.split("?")[0];
|
||||
isCurrent: ({ pathname: path, item }) => {
|
||||
// During Server rendering path is /v2/apps but on client it becomes /apps(weird..)
|
||||
return (
|
||||
(path.startsWith(item.href) || path.startsWith("/v2" + item.href)) && !path.includes("/installed")
|
||||
(path?.startsWith(item.href) || path?.startsWith("/v2" + item.href)) &&
|
||||
!path.includes("/installed")
|
||||
);
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "installed_apps",
|
||||
href: "/apps/installed/calendar",
|
||||
isCurrent: ({ router }) => {
|
||||
const path = router.asPath;
|
||||
return path.startsWith("/apps/installed/") || path.startsWith("/v2/apps/installed/");
|
||||
},
|
||||
isCurrent: ({ pathname: path }) =>
|
||||
path?.startsWith("/apps/installed/") || path?.startsWith("/v2/apps/installed/"),
|
||||
},
|
||||
],
|
||||
},
|
||||
@@ -592,9 +578,7 @@ const navigation: NavigationItemType[] = [
|
||||
name: "Routing Forms",
|
||||
href: "/routing-forms/forms",
|
||||
icon: FileText,
|
||||
isCurrent: ({ router }) => {
|
||||
return router.asPath.startsWith("/routing-forms/");
|
||||
},
|
||||
isCurrent: ({ pathname }) => pathname?.startsWith("/routing-forms/"),
|
||||
},
|
||||
{
|
||||
name: "workflows",
|
||||
@@ -647,8 +631,8 @@ function useShouldDisplayNavigationItem(item: NavigationItemType) {
|
||||
return true;
|
||||
}
|
||||
|
||||
const defaultIsCurrent: NavigationItemType["isCurrent"] = ({ isChild, item, router }) => {
|
||||
return isChild ? item.href === router.asPath : item.href ? router.asPath.startsWith(item.href) : false;
|
||||
const defaultIsCurrent: NavigationItemType["isCurrent"] = ({ isChild, item, pathname }) => {
|
||||
return isChild ? item.href === pathname : item.href ? pathname?.startsWith(item.href) : false;
|
||||
};
|
||||
|
||||
const NavigationItem: React.FC<{
|
||||
@@ -658,9 +642,9 @@ const NavigationItem: React.FC<{
|
||||
}> = (props) => {
|
||||
const { item, isChild } = props;
|
||||
const { t, isLocaleReady } = useLocale();
|
||||
const router = useRouter();
|
||||
const pathname = usePathname();
|
||||
const isCurrent: NavigationItemType["isCurrent"] = item.isCurrent || defaultIsCurrent;
|
||||
const current = isCurrent({ isChild: !!isChild, item, router });
|
||||
const current = isCurrent({ isChild: !!isChild, item, pathname });
|
||||
const shouldDisplayNavigationItem = useShouldDisplayNavigationItem(props.item);
|
||||
|
||||
if (!shouldDisplayNavigationItem) return null;
|
||||
@@ -699,7 +683,7 @@ const NavigationItem: React.FC<{
|
||||
</Link>
|
||||
</Tooltip>
|
||||
{item.child &&
|
||||
isCurrent({ router, isChild, item }) &&
|
||||
isCurrent({ pathname, isChild, item }) &&
|
||||
item.child.map((item, index) => <NavigationItem index={index} key={item.name} item={item} isChild />)}
|
||||
</Fragment>
|
||||
);
|
||||
@@ -736,10 +720,10 @@ const MobileNavigationItem: React.FC<{
|
||||
isChild?: boolean;
|
||||
}> = (props) => {
|
||||
const { item, isChild } = props;
|
||||
const router = useRouter();
|
||||
const pathname = usePathname();
|
||||
const { t, isLocaleReady } = useLocale();
|
||||
const isCurrent: NavigationItemType["isCurrent"] = item.isCurrent || defaultIsCurrent;
|
||||
const current = isCurrent({ isChild: !!isChild, item, router });
|
||||
const current = isCurrent({ isChild: !!isChild, item, pathname });
|
||||
const shouldDisplayNavigationItem = useShouldDisplayNavigationItem(props.item);
|
||||
|
||||
if (!shouldDisplayNavigationItem) return null;
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import { useRouter } from "next/router";
|
||||
import z from "zod";
|
||||
import { useRouter, useSearchParams } from "next/navigation";
|
||||
|
||||
import { APP_NAME } from "@calcom/lib/constants";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
@@ -11,105 +10,97 @@ import type { WebhookFormSubmitData } from "../components/WebhookForm";
|
||||
import WebhookForm from "../components/WebhookForm";
|
||||
import { subscriberUrlReserved } from "../lib/subscriberUrlReserved";
|
||||
|
||||
const querySchema = z.object({ id: z.string() });
|
||||
|
||||
const EditWebhook = () => {
|
||||
const searchParams = useSearchParams();
|
||||
const id = searchParams.get("id");
|
||||
|
||||
if (!id) return <SkeletonContainer />;
|
||||
|
||||
// I think we should do SSR for this page
|
||||
return <Component webhookId={id} />;
|
||||
};
|
||||
|
||||
function Component({ webhookId }: { webhookId: string }) {
|
||||
const { t } = useLocale();
|
||||
const utils = trpc.useContext();
|
||||
const router = useRouter();
|
||||
|
||||
function Component({ webhookId }: { webhookId: string }) {
|
||||
const { data: installedApps, isLoading } = trpc.viewer.integrations.useQuery(
|
||||
{ variant: "other", onlyInstalled: true },
|
||||
{
|
||||
suspense: true,
|
||||
enabled: router.isReady,
|
||||
}
|
||||
);
|
||||
const { data: webhook } = trpc.viewer.webhook.get.useQuery(
|
||||
{ webhookId },
|
||||
{
|
||||
suspense: true,
|
||||
enabled: router.isReady,
|
||||
}
|
||||
);
|
||||
const { data: webhooks } = trpc.viewer.webhook.list.useQuery(undefined, {
|
||||
const { data: installedApps, isLoading } = trpc.viewer.integrations.useQuery(
|
||||
{ variant: "other", onlyInstalled: true },
|
||||
{
|
||||
suspense: true,
|
||||
enabled: router.isReady,
|
||||
});
|
||||
const editWebhookMutation = trpc.viewer.webhook.edit.useMutation({
|
||||
async onSuccess() {
|
||||
await utils.viewer.webhook.list.invalidate();
|
||||
showToast(t("webhook_updated_successfully"), "success");
|
||||
router.back();
|
||||
},
|
||||
onError(error) {
|
||||
showToast(`${error.message}`, "error");
|
||||
},
|
||||
});
|
||||
enabled: !!webhookId,
|
||||
}
|
||||
);
|
||||
const { data: webhook } = trpc.viewer.webhook.get.useQuery(
|
||||
{ webhookId },
|
||||
{
|
||||
suspense: true,
|
||||
enabled: !!webhookId,
|
||||
}
|
||||
);
|
||||
const { data: webhooks } = trpc.viewer.webhook.list.useQuery(undefined, {
|
||||
suspense: true,
|
||||
enabled: !!webhookId,
|
||||
});
|
||||
const editWebhookMutation = trpc.viewer.webhook.edit.useMutation({
|
||||
async onSuccess() {
|
||||
await utils.viewer.webhook.list.invalidate();
|
||||
showToast(t("webhook_updated_successfully"), "success");
|
||||
router.back();
|
||||
},
|
||||
onError(error) {
|
||||
showToast(`${error.message}`, "error");
|
||||
},
|
||||
});
|
||||
|
||||
if (isLoading || !webhook) return <SkeletonContainer />;
|
||||
if (isLoading || !webhook) return <SkeletonContainer />;
|
||||
|
||||
return (
|
||||
<>
|
||||
<Meta
|
||||
title={t("edit_webhook")}
|
||||
description={t("add_webhook_description", { appName: APP_NAME })}
|
||||
backButton
|
||||
/>
|
||||
<WebhookForm
|
||||
webhook={webhook}
|
||||
noRoutingFormTriggers={!!webhook.teamId}
|
||||
onSubmit={(values: WebhookFormSubmitData) => {
|
||||
if (
|
||||
subscriberUrlReserved({
|
||||
subscriberUrl: values.subscriberUrl,
|
||||
id: webhook.id,
|
||||
webhooks,
|
||||
teamId: webhook.teamId ?? undefined,
|
||||
userId: webhook.userId ?? undefined,
|
||||
})
|
||||
) {
|
||||
showToast(t("webhook_subscriber_url_reserved"), "error");
|
||||
return;
|
||||
}
|
||||
|
||||
if (values.changeSecret) {
|
||||
values.secret = values.newSecret.length ? values.newSecret : null;
|
||||
}
|
||||
|
||||
if (!values.payloadTemplate) {
|
||||
values.payloadTemplate = null;
|
||||
}
|
||||
|
||||
editWebhookMutation.mutate({
|
||||
id: webhook.id,
|
||||
return (
|
||||
<>
|
||||
<Meta
|
||||
title={t("edit_webhook")}
|
||||
description={t("add_webhook_description", { appName: APP_NAME })}
|
||||
backButton
|
||||
/>
|
||||
<WebhookForm
|
||||
webhook={webhook}
|
||||
noRoutingFormTriggers={!!webhook.teamId}
|
||||
onSubmit={(values: WebhookFormSubmitData) => {
|
||||
if (
|
||||
subscriberUrlReserved({
|
||||
subscriberUrl: values.subscriberUrl,
|
||||
eventTriggers: values.eventTriggers,
|
||||
active: values.active,
|
||||
payloadTemplate: values.payloadTemplate,
|
||||
secret: values.secret,
|
||||
});
|
||||
}}
|
||||
apps={installedApps?.items.map((app) => app.slug)}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
id: webhook.id,
|
||||
webhooks,
|
||||
teamId: webhook.teamId ?? undefined,
|
||||
userId: webhook.userId ?? undefined,
|
||||
})
|
||||
) {
|
||||
showToast(t("webhook_subscriber_url_reserved"), "error");
|
||||
return;
|
||||
}
|
||||
|
||||
if (!router.isReady) return null;
|
||||
if (values.changeSecret) {
|
||||
values.secret = values.newSecret.length ? values.newSecret : null;
|
||||
}
|
||||
|
||||
const parsed = querySchema.safeParse(router.query);
|
||||
if (!values.payloadTemplate) {
|
||||
values.payloadTemplate = null;
|
||||
}
|
||||
|
||||
if (!parsed.success) {
|
||||
throw new Error("Invalid query");
|
||||
}
|
||||
|
||||
// tRPC useQuery needs webhookId to be available and it becomes available only after router.isReady is true
|
||||
// It causes this requirement of a new component.
|
||||
// I think we should do SSR for this page
|
||||
return <Component webhookId={parsed.data.id} />;
|
||||
};
|
||||
editWebhookMutation.mutate({
|
||||
id: webhook.id,
|
||||
subscriberUrl: values.subscriberUrl,
|
||||
eventTriggers: values.eventTriggers,
|
||||
active: values.active,
|
||||
payloadTemplate: values.payloadTemplate,
|
||||
secret: values.secret,
|
||||
});
|
||||
}}
|
||||
apps={installedApps?.items.map((app) => app.slug)}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
EditWebhook.getLayout = getLayout;
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { useSession } from "next-auth/react";
|
||||
import { useRouter } from "next/router";
|
||||
import { useRouter, useSearchParams } from "next/navigation";
|
||||
|
||||
import { APP_NAME } from "@calcom/lib/constants";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
@@ -12,23 +12,24 @@ import WebhookForm from "../components/WebhookForm";
|
||||
import { subscriberUrlReserved } from "../lib/subscriberUrlReserved";
|
||||
|
||||
const NewWebhookView = () => {
|
||||
const searchParams = useSearchParams();
|
||||
const { t } = useLocale();
|
||||
const utils = trpc.useContext();
|
||||
const router = useRouter();
|
||||
const session = useSession();
|
||||
|
||||
const teamId = router.query.teamId ? +router.query.teamId : undefined;
|
||||
const teamId = searchParams?.get("teamId") ? Number(searchParams.get("teamId")) : undefined;
|
||||
|
||||
const { data: installedApps, isLoading } = trpc.viewer.integrations.useQuery(
|
||||
{ variant: "other", onlyInstalled: true },
|
||||
{
|
||||
suspense: true,
|
||||
enabled: router.isReady,
|
||||
enabled: session.status === "authenticated",
|
||||
}
|
||||
);
|
||||
const { data: webhooks } = trpc.viewer.webhook.list.useQuery(undefined, {
|
||||
suspense: true,
|
||||
enabled: router.isReady,
|
||||
enabled: session.status === "authenticated",
|
||||
});
|
||||
|
||||
const createWebhookMutation = trpc.viewer.webhook.create.useMutation({
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { useRouter } from "next/router";
|
||||
import { useSession } from "next-auth/react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { Suspense } from "react";
|
||||
|
||||
import { APP_NAME, WEBAPP_URL } from "@calcom/lib/constants";
|
||||
@@ -6,8 +7,7 @@ import { useBookerUrl } from "@calcom/lib/hooks/useBookerUrl";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import { trpc } from "@calcom/trpc/react";
|
||||
import type { WebhooksByViewer } from "@calcom/trpc/server/routers/viewer/webhook/getByViewer.handler";
|
||||
import { Meta, EmptyScreen, CreateButtonWithTeamsList } from "@calcom/ui";
|
||||
import { Avatar } from "@calcom/ui";
|
||||
import { Avatar, CreateButtonWithTeamsList, EmptyScreen, Meta } from "@calcom/ui";
|
||||
import { Link as LinkIcon } from "@calcom/ui/components/icon";
|
||||
|
||||
import { getLayout } from "../../settings/layouts/SettingsLayout";
|
||||
@@ -16,10 +16,11 @@ import { WebhookListItem, WebhookListSkeleton } from "../components";
|
||||
const WebhooksView = () => {
|
||||
const { t } = useLocale();
|
||||
const router = useRouter();
|
||||
const session = useSession();
|
||||
|
||||
const { data } = trpc.viewer.webhook.getByViewer.useQuery(undefined, {
|
||||
suspense: true,
|
||||
enabled: router.isReady,
|
||||
enabled: session.status === "authenticated",
|
||||
});
|
||||
|
||||
return (
|
||||
|
||||
@@ -1,33 +1,43 @@
|
||||
import type { NextRouter } from "next/router";
|
||||
import type { Booking, EventType } from "@prisma/client";
|
||||
import { useRouter, useSearchParams } from "next/navigation";
|
||||
|
||||
import type { Booking, EventType } from ".prisma/client";
|
||||
|
||||
export const bookingSuccessRedirect = async ({
|
||||
successRedirectUrl,
|
||||
bookingUid,
|
||||
query,
|
||||
router,
|
||||
}: {
|
||||
successRedirectUrl: EventType["successRedirectUrl"];
|
||||
bookingUid: Booking["uid"] | undefined;
|
||||
function getNewSeachParams(args: {
|
||||
query: Record<string, string | null | undefined | boolean>;
|
||||
router: NextRouter;
|
||||
}) => {
|
||||
if (successRedirectUrl) {
|
||||
const url = new URL(successRedirectUrl);
|
||||
Object.entries(query).forEach(([key, value]) => {
|
||||
if (value === null || value === undefined) {
|
||||
return;
|
||||
}
|
||||
url.searchParams.append(key, String(value));
|
||||
});
|
||||
|
||||
// Using parent ensures, Embed iframe would redirect outside of the iframe.
|
||||
window.parent.location.href = url.toString();
|
||||
return;
|
||||
}
|
||||
return router.push({
|
||||
pathname: `/booking/${bookingUid}`,
|
||||
query,
|
||||
searchParams?: URLSearchParams;
|
||||
}) {
|
||||
const { query, searchParams } = args;
|
||||
const newSearchParams = new URLSearchParams(searchParams);
|
||||
Object.entries(query).forEach(([key, value]) => {
|
||||
if (value === null || value === undefined) {
|
||||
return;
|
||||
}
|
||||
newSearchParams.append(key, String(value));
|
||||
});
|
||||
return newSearchParams;
|
||||
}
|
||||
|
||||
export const useBookingSuccessRedirect = () => {
|
||||
const router = useRouter();
|
||||
const searchParams = useSearchParams();
|
||||
const bookingSuccessRedirect = ({
|
||||
successRedirectUrl,
|
||||
bookingUid,
|
||||
query,
|
||||
}: {
|
||||
successRedirectUrl: EventType["successRedirectUrl"];
|
||||
bookingUid: Booking["uid"] | undefined;
|
||||
query: Record<string, string | null | undefined | boolean>;
|
||||
}) => {
|
||||
if (successRedirectUrl) {
|
||||
const url = new URL(successRedirectUrl);
|
||||
// Using parent ensures, Embed iframe would redirect outside of the iframe.
|
||||
const newSearchParams = getNewSeachParams({ query, searchParams });
|
||||
window.parent.location.href = `${url.toString()}?${newSearchParams.toString()}`;
|
||||
return;
|
||||
}
|
||||
const newSearchParams = getNewSeachParams({ query });
|
||||
return router.push(`/booking/${bookingUid}?${newSearchParams.toString()}`);
|
||||
};
|
||||
|
||||
return bookingSuccessRedirect;
|
||||
};
|
||||
@@ -0,0 +1,13 @@
|
||||
"use client";
|
||||
|
||||
import { useParams } from "next/navigation";
|
||||
import { useRouter } from "next/router";
|
||||
|
||||
/**
|
||||
* This hook is a workaround until pages are migrated to app directory.
|
||||
*/
|
||||
export function useParamsWithFallback() {
|
||||
const router = useRouter();
|
||||
const params = useParams();
|
||||
return params || router.query;
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
import { useSearchParams } from "next/navigation";
|
||||
|
||||
/**
|
||||
* An alternative to Object.fromEntries that allows duplicate keys.
|
||||
*/
|
||||
function fromEntriesWithDuplicateKeys(entries: ReturnType<ReturnType<typeof useSearchParams>["entries"]>) {
|
||||
const result: Record<string, string | string[]> = {};
|
||||
// Consider setting atleast ES2015 as target
|
||||
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
||||
// @ts-ignore
|
||||
for (const [key, value] of entries) {
|
||||
if (result.hasOwnProperty(key)) {
|
||||
let currentValue = result[key];
|
||||
if (!Array.isArray(currentValue)) {
|
||||
currentValue = [currentValue];
|
||||
}
|
||||
currentValue.push(value);
|
||||
result[key] = currentValue;
|
||||
} else {
|
||||
result[key] = value;
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* This hook returns the query object from the router. It is an attempt to
|
||||
* keep the original query object from the old useRouter hook.
|
||||
* At least until everything is properly migrated to the new router.
|
||||
* @returns {Object} routerQuery
|
||||
*/
|
||||
export const useRouterQuery = () => {
|
||||
const searchParams = useSearchParams();
|
||||
const routerQuery = fromEntriesWithDuplicateKeys(searchParams.entries());
|
||||
return routerQuery;
|
||||
};
|
||||
@@ -1,10 +1,16 @@
|
||||
import { useRouter } from "next/router";
|
||||
import { usePathname, useRouter } from "next/navigation";
|
||||
import { useCallback, useMemo } from "react";
|
||||
import { z } from "zod";
|
||||
|
||||
type OptionalKeys<T> = { [K in keyof T]-?: Record<string, unknown> extends Pick<T, K> ? K : never }[keyof T];
|
||||
import { useRouterQuery } from "./useRouterQuery";
|
||||
|
||||
type FilteredKeys<T, U> = { [K in keyof T as T[K] extends U ? K : never]: T[K] };
|
||||
type OptionalKeys<T> = {
|
||||
[K in keyof T]-?: Record<string, unknown> extends Pick<T, K> ? K : never;
|
||||
}[keyof T];
|
||||
|
||||
type FilteredKeys<T, U> = {
|
||||
[K in keyof T as T[K] extends U ? K : never]: T[K];
|
||||
};
|
||||
|
||||
// Take array as a string and return zod array
|
||||
export const queryNumberArray = z
|
||||
@@ -31,8 +37,9 @@ export function useTypedQuery<T extends z.AnyZodObject>(schema: T) {
|
||||
type OutputOptionalKeys = OptionalKeys<Output>;
|
||||
type ArrayOutput = FilteredKeys<FullOutput, Array<unknown>>;
|
||||
type ArrayOutputKeys = keyof ArrayOutput;
|
||||
|
||||
const { query: unparsedQuery, ...router } = useRouter();
|
||||
const router = useRouter();
|
||||
const unparsedQuery = useRouterQuery();
|
||||
const pathname = usePathname();
|
||||
const parsedQuerySchema = schema.safeParse(unparsedQuery);
|
||||
|
||||
let parsedQuery: Output = useMemo(() => {
|
||||
@@ -46,19 +53,18 @@ export function useTypedQuery<T extends z.AnyZodObject>(schema: T) {
|
||||
const setQuery = useCallback(
|
||||
function setQuery<J extends OutputKeys>(key: J, value: Output[J]) {
|
||||
// Remove old value by key so we can merge new value
|
||||
const { [key]: _, ...newQuery } = parsedQuery;
|
||||
const newValue = { ...newQuery, [key]: value };
|
||||
const search = new URLSearchParams(newValue).toString();
|
||||
router.replace({ query: search }, undefined, { shallow: true });
|
||||
const search = new URLSearchParams(parsedQuery);
|
||||
search.set(String(key), String(value));
|
||||
router.replace(`${pathname}?${search.toString()}`);
|
||||
},
|
||||
[parsedQuery, router]
|
||||
);
|
||||
|
||||
// Delete a key from the query
|
||||
function removeByKey(key: OutputOptionalKeys) {
|
||||
const { [key]: _, ...newQuery } = parsedQuery;
|
||||
const search = new URLSearchParams(newQuery).toString();
|
||||
router.replace({ query: search }, undefined, { shallow: true });
|
||||
const search = new URLSearchParams(parsedQuery);
|
||||
search.delete(String(key));
|
||||
router.replace(`${pathname}?${search.toString()}`);
|
||||
}
|
||||
|
||||
// push item to existing key
|
||||
@@ -89,9 +95,7 @@ export function useTypedQuery<T extends z.AnyZodObject>(schema: T) {
|
||||
|
||||
// Remove all query params from the URL
|
||||
function removeAllQueryParams() {
|
||||
const { asPath } = router;
|
||||
const newPath = asPath.split("?")[0];
|
||||
router.replace(newPath, undefined, { shallow: true });
|
||||
router.replace(pathname);
|
||||
}
|
||||
|
||||
return {
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
"use client";
|
||||
|
||||
import { usePathname, useSearchParams } from "next/navigation";
|
||||
|
||||
export const useUrlMatchesCurrentUrl = (url: string) => {
|
||||
// I don't know why usePathname ReturnType doesn't include null.
|
||||
// It can certainly have null value https://nextjs.org/docs/app/api-reference/functions/use-pathname#:~:text=usePathname%20can%20return%20null%20when%20a%20fallback%20route%20is%20being%20rendered%20or%20when%20a%20pages%20directory%20page%20has%20been%20automatically%20statically%20optimized%20by%20Next.js%20and%20the%20router%20is%20not%20ready.
|
||||
const pathname = usePathname() as null | string;
|
||||
const searchParams = useSearchParams();
|
||||
const query = searchParams.toString();
|
||||
let pathnameWithQuery;
|
||||
if (query) {
|
||||
pathnameWithQuery = `${pathname}?${query}`;
|
||||
} else {
|
||||
pathnameWithQuery = pathname;
|
||||
}
|
||||
// TODO: It should actually re-order the params before comparing ?a=1&b=2 should match with ?b=2&a=1
|
||||
return pathnameWithQuery ? pathnameWithQuery.includes(url) : false;
|
||||
};
|
||||
@@ -13,3 +13,11 @@ export function getLocaleFromHeaders(req: IncomingMessage): string {
|
||||
}
|
||||
return preferredLocale ?? i18n.defaultLocale;
|
||||
}
|
||||
|
||||
// Workaround for using router.locales from old router
|
||||
export const locales = i18n.locales as string[];
|
||||
|
||||
export const localeOptions = locales.map((locale) => ({
|
||||
value: locale,
|
||||
label: new Intl.DisplayNames(locale, { type: "language" }).of(locale) || "",
|
||||
}));
|
||||
@@ -21,6 +21,7 @@
|
||||
"ical.js": "^1.4.0",
|
||||
"ics": "^2.37.0",
|
||||
"jimp": "^0.16.1",
|
||||
"next-collect": "^0.2.1",
|
||||
"next-i18next": "^13.2.2",
|
||||
"react-hot-toast": "^2.3.0",
|
||||
"rrule": "^2.7.1",
|
||||
|
||||
Vendored
+7
@@ -22,3 +22,10 @@ export declare module "next" {
|
||||
pagination: { take: number; skip: number };
|
||||
}
|
||||
}
|
||||
|
||||
export declare module "next/navigation" {
|
||||
interface Params {
|
||||
[key: string]: string;
|
||||
}
|
||||
export declare function useParams(): Params | null;
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
import { useAutoAnimate } from "@formkit/auto-animate/react";
|
||||
import { useRouter } from "next/router";
|
||||
import { usePathname, useRouter, useSearchParams } from "next/navigation";
|
||||
import type { UIEvent } from "react";
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
|
||||
@@ -53,6 +53,8 @@ interface CategoryTabProps {
|
||||
}
|
||||
|
||||
function CategoryTab({ selectedCategory, categories, searchText }: CategoryTabProps) {
|
||||
const pathname = usePathname();
|
||||
const searchParams = useSearchParams();
|
||||
const { t } = useLocale();
|
||||
const router = useRouter();
|
||||
const { ref, calculateScroll, leftVisible, rightVisible } = useShouldShowArrows();
|
||||
@@ -92,7 +94,7 @@ function CategoryTab({ selectedCategory, categories, searchText }: CategoryTabPr
|
||||
ref={ref}>
|
||||
<li
|
||||
onClick={() => {
|
||||
router.replace(router.asPath.split("?")[0], undefined, { shallow: true });
|
||||
router.replace(pathname);
|
||||
}}
|
||||
className={classNames(
|
||||
selectedCategory === null ? "bg-emphasis text-default" : "bg-muted text-emphasis",
|
||||
@@ -105,11 +107,11 @@ function CategoryTab({ selectedCategory, categories, searchText }: CategoryTabPr
|
||||
key={pos}
|
||||
onClick={() => {
|
||||
if (selectedCategory === cat) {
|
||||
router.replace(router.asPath.split("?")[0], undefined, { shallow: true });
|
||||
router.replace(pathname);
|
||||
} else {
|
||||
router.replace(router.asPath.split("?")[0] + `?category=${cat}`, undefined, {
|
||||
shallow: true,
|
||||
});
|
||||
const _searchParams = new URLSearchParams(searchParams);
|
||||
_searchParams.set("category", cat);
|
||||
router.replace(`${pathname}?${_searchParams.toString()}`);
|
||||
}
|
||||
}}
|
||||
className={classNames(
|
||||
@@ -133,10 +135,11 @@ function CategoryTab({ selectedCategory, categories, searchText }: CategoryTabPr
|
||||
}
|
||||
|
||||
export function AllApps({ apps, searchText, categories, userAdminTeams }: AllAppsPropsType) {
|
||||
const router = useRouter();
|
||||
const searchParams = useSearchParams();
|
||||
const { t } = useLocale();
|
||||
const [selectedCategory, setSelectedCategory] = useState<string | null>(null);
|
||||
const [appsContainerRef, enableAnimation] = useAutoAnimate<HTMLDivElement>();
|
||||
const categoryQuery = searchParams?.get("category");
|
||||
|
||||
if (searchText) {
|
||||
enableAnimation && enableAnimation(false);
|
||||
@@ -144,12 +147,10 @@ export function AllApps({ apps, searchText, categories, userAdminTeams }: AllApp
|
||||
|
||||
useEffect(() => {
|
||||
const queryCategory =
|
||||
typeof router.query.category === "string" && categories.includes(router.query.category)
|
||||
? router.query.category
|
||||
: null;
|
||||
typeof categoryQuery === "string" && categories.includes(categoryQuery) ? categoryQuery : null;
|
||||
setSelectedCategory(queryCategory);
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [router.query.category]);
|
||||
}, [categoryQuery]);
|
||||
|
||||
const filteredApps = apps
|
||||
.filter((app) =>
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { useRouter } from "next/router";
|
||||
import { usePathname } from "next/navigation";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useEffect, useState } from "react";
|
||||
|
||||
import useAddAppMutation from "@calcom/app-store/_utils/useAddAppMutation";
|
||||
@@ -35,7 +36,6 @@ interface AppCardProps {
|
||||
|
||||
export function AppCard({ app, credentials, searchText, userAdminTeams }: AppCardProps) {
|
||||
const { t } = useLocale();
|
||||
|
||||
const allowedMultipleInstalls = app.categories && app.categories.indexOf("calendar") > -1;
|
||||
const appAdded = (credentials && credentials.length) || 0;
|
||||
|
||||
@@ -78,9 +78,9 @@ export function AppCard({ app, credentials, searchText, userAdminTeams }: AppCar
|
||||
</h3>
|
||||
</div>
|
||||
{/* TODO: add reviews <div className="flex text-sm text-default">
|
||||
<span>{props.rating} stars</span> <StarIcon className="ml-1 mt-0.5 h-4 w-4 text-yellow-600" />
|
||||
<span className="pl-1 text-subtle">{props.reviews} reviews</span>
|
||||
</div> */}
|
||||
<span>{props.rating} stars</span> <StarIcon className="ml-1 mt-0.5 h-4 w-4 text-yellow-600" />
|
||||
<span className="pl-1 text-subtle">{props.reviews} reviews</span>
|
||||
</div> */}
|
||||
<p
|
||||
className="text-default mt-2 flex-grow text-sm"
|
||||
style={{
|
||||
@@ -189,11 +189,12 @@ const InstallAppButtonChild = ({
|
||||
} & ButtonProps) => {
|
||||
const { t } = useLocale();
|
||||
const router = useRouter();
|
||||
const pathname = usePathname();
|
||||
|
||||
const mutation = useAddAppMutation(null, {
|
||||
onSuccess: (data) => {
|
||||
// Refresh SSR page content without actual reload
|
||||
router.replace(router.asPath);
|
||||
router.replace(pathname);
|
||||
if (data?.setupPending) return;
|
||||
showToast(t("app_successfully_installed"), "success");
|
||||
},
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import Link from "next/link";
|
||||
import { useRouter } from "next/router";
|
||||
import { usePathname } from "next/navigation";
|
||||
import { Children, Fragment, useEffect, useState } from "react";
|
||||
|
||||
type BreadcrumbProps = {
|
||||
@@ -44,11 +44,11 @@ export const BreadcrumbItem = ({ children, href, listProps }: BreadcrumbItemProp
|
||||
};
|
||||
|
||||
export const BreadcrumbContainer = () => {
|
||||
const router = useRouter();
|
||||
const pathname = usePathname();
|
||||
const [, setBreadcrumbs] = useState<{ href: string; label: string }[]>();
|
||||
|
||||
useEffect(() => {
|
||||
const rawPath = router.asPath.split("?")[0]; // this will ignore any query params for now?
|
||||
const rawPath = pathname; // Pathname doesn't include search params anymore
|
||||
|
||||
let pathArray = rawPath.split("/");
|
||||
pathArray.shift();
|
||||
@@ -63,7 +63,7 @@ export const BreadcrumbContainer = () => {
|
||||
};
|
||||
});
|
||||
setBreadcrumbs(allBreadcrumbs);
|
||||
}, [router.asPath]);
|
||||
}, [pathname]);
|
||||
};
|
||||
|
||||
export default Breadcrumb;
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useRouter } from "next/router";
|
||||
import { usePathname, useRouter, useSearchParams } from "next/navigation";
|
||||
|
||||
import { useBookerUrl } from "@calcom/lib/hooks/useBookerUrl";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
@@ -38,6 +38,8 @@ export type CreateBtnProps = {
|
||||
export function CreateButton(props: CreateBtnProps) {
|
||||
const { t } = useLocale();
|
||||
const router = useRouter();
|
||||
const searchParams = useSearchParams();
|
||||
const pathname = usePathname();
|
||||
const bookerUrl = useBookerUrl();
|
||||
|
||||
const {
|
||||
@@ -56,23 +58,17 @@ export function CreateButton(props: CreateBtnProps) {
|
||||
|
||||
// inject selection data into url for correct router history
|
||||
const openModal = (option: Option) => {
|
||||
const query = {
|
||||
...router.query,
|
||||
dialog: "new",
|
||||
eventPage: option.slug,
|
||||
teamId: option.teamId,
|
||||
};
|
||||
if (!option.teamId) {
|
||||
delete query.teamId;
|
||||
const _searchParams = new URLSearchParams(searchParams);
|
||||
function setParamsIfDefined(key: string, value: string | number | boolean | null | undefined) {
|
||||
if (value !== undefined && value !== null) _searchParams.set(key, value.toString());
|
||||
}
|
||||
router.push(
|
||||
{
|
||||
pathname: router.pathname,
|
||||
query,
|
||||
},
|
||||
undefined,
|
||||
{ shallow: true }
|
||||
);
|
||||
setParamsIfDefined("dialog", "new");
|
||||
setParamsIfDefined("eventPage", option.slug);
|
||||
setParamsIfDefined("teamId", option.teamId);
|
||||
if (!option.teamId) {
|
||||
_searchParams.delete("teamId");
|
||||
}
|
||||
router.push(`${pathname}?${_searchParams.toString()}`);
|
||||
};
|
||||
|
||||
return (
|
||||
@@ -138,7 +134,7 @@ export function CreateButton(props: CreateBtnProps) {
|
||||
</DropdownMenuContent>
|
||||
</Dropdown>
|
||||
)}
|
||||
{router.query.dialog === "new" && CreateDialog}
|
||||
{searchParams.get("dialog") === "new" && CreateDialog}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
import * as DialogPrimitive from "@radix-ui/react-dialog";
|
||||
import { useRouter } from "next/router";
|
||||
import { usePathname, useRouter, useSearchParams } from "next/navigation";
|
||||
import type { ReactNode } from "react";
|
||||
import React, { useState } from "react";
|
||||
|
||||
@@ -14,44 +14,56 @@ 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 router = useRouter();
|
||||
const pathname = usePathname();
|
||||
const searchParams = useSearchParams();
|
||||
const newSearchParams = new URLSearchParams(searchParams);
|
||||
const { children, name, ...dialogProps } = props;
|
||||
// only used if name is set
|
||||
const [open, setOpen] = useState(!!dialogProps.open);
|
||||
|
||||
// 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) {
|
||||
router.query["dialog"] = name;
|
||||
newSearchParams.set("dialog", name);
|
||||
} else {
|
||||
const query = router.query;
|
||||
clearQueryParamsOnClose.forEach((queryParam) => {
|
||||
delete query[queryParam];
|
||||
newSearchParams.delete(queryParam);
|
||||
});
|
||||
router.push(
|
||||
{
|
||||
pathname: router.pathname,
|
||||
query,
|
||||
},
|
||||
undefined,
|
||||
{ shallow: true }
|
||||
);
|
||||
router.push(`${pathname}?${newSearchParams.toString()}`);
|
||||
}
|
||||
setOpen(open);
|
||||
setDialogState(open ? DIALOG_STATE.OPEN : DIALOG_STATE.CLOSING);
|
||||
};
|
||||
// handles initial state
|
||||
if (!open && router.query["dialog"] === name) {
|
||||
setOpen(true);
|
||||
|
||||
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 = open;
|
||||
dialogProps.open = dialogState === DIALOG_STATE.OPEN ? true : false;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,20 +1,18 @@
|
||||
import { render, screen } from "@testing-library/react";
|
||||
import { vi } from "vitest";
|
||||
|
||||
import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogClose } from "./Dialog";
|
||||
import { Dialog, DialogClose, DialogContent, DialogFooter, DialogHeader } from "./Dialog";
|
||||
|
||||
vi.mock("next/router", () => ({
|
||||
vi.mock("next/navigation", () => ({
|
||||
usePathname() {
|
||||
return "";
|
||||
},
|
||||
useSearchParams() {
|
||||
return new URLSearchParams();
|
||||
},
|
||||
useRouter() {
|
||||
return {
|
||||
route: "/",
|
||||
pathname: "",
|
||||
query: "",
|
||||
asPath: "",
|
||||
push: vi.fn(),
|
||||
events: {
|
||||
on: vi.fn(),
|
||||
off: vi.fn(),
|
||||
},
|
||||
beforePopState: vi.fn(() => null),
|
||||
prefetch: vi.fn(() => null),
|
||||
};
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { noop } from "lodash";
|
||||
import { useRouter } from "next/router";
|
||||
import { useRouter, useSearchParams } from "next/navigation";
|
||||
import type { Dispatch, SetStateAction } from "react";
|
||||
import { useEffect, useState } from "react";
|
||||
|
||||
@@ -27,12 +27,13 @@ function WizardForm<T extends DefaultStep>(props: {
|
||||
finishLabel?: string;
|
||||
stepLabel?: React.ComponentProps<typeof Steps>["stepLabel"];
|
||||
}) {
|
||||
const searchParams = useSearchParams();
|
||||
const { href, steps, nextLabel = "Next", finishLabel = "Finish", prevLabel = "Back", stepLabel } = props;
|
||||
const router = useRouter();
|
||||
const step = parseInt((router.query.step as string) || "1");
|
||||
const step = parseInt((searchParams?.get("step") as string) || "1");
|
||||
const currentStep = steps[step - 1];
|
||||
const setStep = (newStep: number) => {
|
||||
router.replace(`${href}?step=${newStep || 1}`, undefined, { shallow: true });
|
||||
router.replace(`${href}?step=${newStep || 1}`);
|
||||
};
|
||||
const [currentStepIsLoading, setCurrentStepIsLoading] = useState(false);
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { merge } from "lodash";
|
||||
import type { NextSeoProps } from "next-seo";
|
||||
import { NextSeo } from "next-seo";
|
||||
import { useRouter } from "next/router";
|
||||
import { usePathname } from "next/navigation";
|
||||
|
||||
import type { AppImageProps, MeetingImageProps } from "@calcom/lib/OgImages";
|
||||
import { constructAppImage, constructGenericImage, constructMeetingImage } from "@calcom/lib/OgImages";
|
||||
@@ -69,9 +69,9 @@ const buildSeoMeta = (pageProps: {
|
||||
};
|
||||
|
||||
export const HeadSeo = (props: HeadSeoProps): JSX.Element => {
|
||||
const path = usePathname();
|
||||
// The below code sets the defaultUrl for our canonical tags
|
||||
// Get the router's path
|
||||
const path = useRouter().asPath;
|
||||
const selfHostedOrigin = WEBSITE_URL || "https://cal.com";
|
||||
// Set the default URL to either the current URL (if self-hosted) or https://cal.com canonical URL
|
||||
const defaultUrl = IS_CALCOM
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import Link from "next/link";
|
||||
import { useRouter } from "next/router";
|
||||
|
||||
import classNames from "@calcom/lib/classNames";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import { useUrlMatchesCurrentUrl } from "@calcom/lib/hooks/useUrlMatchesCurrentUrl";
|
||||
import type { SVGComponent } from "@calcom/types/SVGComponent";
|
||||
|
||||
import { Avatar } from "../../avatar";
|
||||
@@ -28,9 +28,8 @@ const HorizontalTabItem = function ({
|
||||
...props
|
||||
}: HorizontalTabItemProps) {
|
||||
const { t, isLocaleReady } = useLocale();
|
||||
const { asPath } = useRouter();
|
||||
|
||||
const isCurrent = asPath === href;
|
||||
const isCurrent = useUrlMatchesCurrentUrl(href);
|
||||
|
||||
return (
|
||||
<Link
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
import Link from "next/link";
|
||||
import { useRouter } from "next/router";
|
||||
import { Fragment } from "react";
|
||||
|
||||
import classNames from "@calcom/lib/classNames";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import { useUrlMatchesCurrentUrl } from "@calcom/lib/hooks/useUrlMatchesCurrentUrl";
|
||||
import type { SVGComponent } from "@calcom/types/SVGComponent";
|
||||
|
||||
import { ChevronRight, ExternalLink } from "../../icon";
|
||||
@@ -39,8 +39,8 @@ const VerticalTabItem = ({
|
||||
...props
|
||||
}: VerticalTabItemProps) => {
|
||||
const { t } = useLocale();
|
||||
const { asPath } = useRouter();
|
||||
const isCurrent = asPath.startsWith(href);
|
||||
const isCurrent = useUrlMatchesCurrentUrl(href);
|
||||
|
||||
return (
|
||||
<Fragment key={name}>
|
||||
{!props.hidden && (
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
import { noop } from "lodash";
|
||||
import { useRouter } from "next/router";
|
||||
import { usePathname } from "next/navigation";
|
||||
import React, { useEffect, useState } from "react";
|
||||
import { Toaster } from "react-hot-toast";
|
||||
|
||||
import { APP_NAME } from "@calcom/lib/constants";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import { StepCard, Steps, Button, SkeletonText } from "@calcom/ui";
|
||||
import { Button, SkeletonText, StepCard, Steps } from "@calcom/ui";
|
||||
|
||||
export function WizardLayout({
|
||||
children,
|
||||
@@ -17,7 +17,7 @@ export function WizardLayout({
|
||||
} & { maxSteps?: number; currentStep?: number; isOptionalCallback?: () => void }) {
|
||||
const { t, isLocaleReady } = useLocale();
|
||||
const [meta, setMeta] = useState({ title: "", subtitle: " " });
|
||||
const router = useRouter();
|
||||
const pathname = usePathname();
|
||||
const { title, subtitle } = meta;
|
||||
|
||||
useEffect(() => {
|
||||
@@ -25,7 +25,7 @@ export function WizardLayout({
|
||||
title: window.document.title,
|
||||
subtitle: window.document.querySelector('meta[name="description"]')?.getAttribute("content") || "",
|
||||
});
|
||||
}, [router.asPath]);
|
||||
}, [pathname]);
|
||||
|
||||
return (
|
||||
<div
|
||||
|
||||
@@ -38,6 +38,7 @@
|
||||
"downshift": "^6.1.9",
|
||||
"lucide-react": "^0.171.0",
|
||||
"next": "^13.4.6",
|
||||
"next-seo": "^4.26.0",
|
||||
"react": "^18.2.0",
|
||||
"react-colorful": "^5.6.0",
|
||||
"react-feather": "^2.0.10",
|
||||
|
||||
Reference in new issue
Block a user