Skip to content

Commit

Permalink
chore: migrate getting-started page
Browse files Browse the repository at this point in the history
  • Loading branch information
DmytroHryshyn committed Nov 8, 2023
1 parent 5bbc861 commit f141b21
Show file tree
Hide file tree
Showing 13 changed files with 163 additions and 32 deletions.
41 changes: 31 additions & 10 deletions apps/web/app/_trpc/createTRPCNextLayout.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
// repo link: https://github.com/trpc/next-13
// code is / will continue to be adapted for our usage
import { dehydrate, QueryClient } from "@tanstack/query-core";
import type { DehydratedState } from "@tanstack/react-query";
import type { DehydratedState, QueryKey } from "@tanstack/react-query";

import type { Maybe, TRPCClientError, TRPCClientErrorLike } from "@calcom/trpc";
import {
Expand All @@ -21,6 +21,26 @@ import {

import { createRecursiveProxy, createFlatProxy } from "@trpc/server/shared";

export function getArrayQueryKey(
queryKey: string | [string] | [string, ...unknown[]] | unknown[],
type: string
): QueryKey {
const queryKeyArrayed = Array.isArray(queryKey) ? queryKey : [queryKey];
const [arrayPath, input] = queryKeyArrayed;

if (!input && (!type || type === "any")) {
return arrayPath.length ? [arrayPath] : ([] as unknown as QueryKey);
}

return [
arrayPath,
{
...(typeof input !== "undefined" && { input: input }),
...(type && type !== "any" && { type: type }),
},
];
}

// copy starts
// copied from trpc/trpc repo
// ref: https://github.com/trpc/trpc/blob/main/packages/next/src/withTRPC.tsx#L37-#L58
Expand Down Expand Up @@ -89,10 +109,6 @@ type CreateTRPCNextLayout<TRouter extends AnyRouter> = DecoratedProcedureRecord<
queryClient: QueryClient;
};

function getQueryKey(path: string[], input: unknown) {
return input === undefined ? [path] : [path, input];
}

const getStateContainer = <TRouter extends AnyRouter>(opts: CreateTRPCNextLayoutOptions<TRouter>) => {
let _trpc: {
queryClient: QueryClient;
Expand Down Expand Up @@ -159,15 +175,16 @@ export function createTRPCNextLayout<TRouter extends AnyRouter>(

const pathStr = path.join(".");
const input = callOpts.args[0];
const queryKey = getQueryKey(path, input);

if (utilName === "fetchInfinite") {
return queryClient.fetchInfiniteQuery(queryKey, () => caller.query(pathStr, input));
return queryClient.fetchInfiniteQuery(getArrayQueryKey([path, input], "infinite"), () =>
caller.query(pathStr, input)
);
}

if (utilName === "prefetch") {
return queryClient.prefetchQuery({
queryKey,
queryKey: getArrayQueryKey([path, input], "query"),
queryFn: async () => {
const res = await callProcedure({
procedures: opts.router._def.procedures,
Expand All @@ -182,10 +199,14 @@ export function createTRPCNextLayout<TRouter extends AnyRouter>(
}

if (utilName === "prefetchInfinite") {
return queryClient.prefetchInfiniteQuery(queryKey, () => caller.query(pathStr, input));
return queryClient.prefetchInfiniteQuery(getArrayQueryKey([path, input], "infinite"), () =>
caller.query(pathStr, input)
);
}

return queryClient.fetchQuery(queryKey, () => caller.query(pathStr, input));
return queryClient.fetchQuery(getArrayQueryKey([path, input], "query"), () =>
caller.query(pathStr, input)
);
}) as CreateTRPCNextLayout<TRouter>;
});
}
14 changes: 11 additions & 3 deletions apps/web/app/_trpc/ssrInit.ts
Original file line number Diff line number Diff line change
@@ -1,23 +1,31 @@
import { serverSideTranslations } from "next-i18next/serverSideTranslations";
import { headers } from "next/headers";
import { headers, cookies } from "next/headers";
import superjson from "superjson";

import { getLocale } from "@calcom/features/auth/lib/getLocale";
import { CALCOM_VERSION } from "@calcom/lib/constants";
import prisma from "@calcom/prisma";
import { appRouter } from "@calcom/trpc/server/routers/_app";

import { createTRPCNextLayout } from "./createTRPCNextLayout";

export async function ssrInit(options?: { noI18nPreload: boolean }) {
const locale = headers().get("x-locale") ?? "en";
const req = {
headers: headers(),
cookies: cookies(),
};

// @ts-expect-error req object incompatible
const locale = await getLocale(req);

const i18n = (await serverSideTranslations(locale, ["common", "vital"])) || "en";

const ssr = createTRPCNextLayout({
router: appRouter,
transformer: superjson,
// @ts-expect-error req object incompatible
createContext() {
return { prisma, session: null, locale, i18n };
return { prisma, session: null, locale, i18n, req };
},
});

Expand Down
70 changes: 70 additions & 0 deletions apps/web/app/future/getting-started/[[...step]]/page.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
import LegacyPage from "@pages/getting-started/[[...step]]";
import { ssrInit } from "app/_trpc/ssrInit";
import { cookies, headers } from "next/headers";
import { redirect } from "next/navigation";

import { getServerSession } from "@calcom/features/auth/lib/getServerSession";
import prisma from "@calcom/prisma";

import PageWrapper from "@components/PageWrapperAppDir";

async function getData() {
const req = { headers: headers(), cookies: cookies() };

// @ts-expect-error emulate req
const session = await getServerSession({ req });

if (!session?.user?.id) {
return redirect("/auth/login");
}

const ssr = await ssrInit();
await ssr.viewer.me.prefetch();

const user = await prisma.user.findUnique({
where: {
id: session.user.id,
},
select: {
completedOnboarding: true,
teams: {
select: {
accepted: true,
team: {
select: {
id: true,
name: true,
logo: true,
},
},
},
},
},
});

if (!user) {
throw new Error("User from session not found");
}

if (user.completedOnboarding) {
redirect("/event-types");
}

return {
dehydratedState: await ssr.dehydrate(),
hasPendingInvites: user.teams.find((team) => team.accepted === false) ?? false,
};
}

export default async function Page() {
const props = await getData();

const h = headers();
const nonce = h.get("x-nonce") ?? undefined;

return (
<PageWrapper getLayout={null} requiresLicense={false} nonce={nonce} themeBasis={null} {...props}>
<LegacyPage />
</PageWrapper>
);
}
5 changes: 5 additions & 0 deletions apps/web/app/getTrpc.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import { trpc as trpcAppDir } from "app/_trpc/client";

import { trpc as trpcPageDir } from "@calcom/trpc";

export const getTprc = (isAppDir: boolean) => (isAppDir ? trpcAppDir : trpcPageDir);
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { getTprc } from "app/getTrpc";

import classNames from "@calcom/lib/classNames";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { trpc } from "@calcom/trpc/react";
import { List } from "@calcom/ui";
import { ArrowRight } from "@calcom/ui/components/icon";

Expand All @@ -11,10 +12,13 @@ import { StepConnectionLoader } from "../components/StepConnectionLoader";

interface IConnectCalendarsProps {
nextStep: () => void;
isAppDir?: boolean;
}

const ConnectedCalendars = (props: IConnectCalendarsProps) => {
const { nextStep } = props;
const trpc = getTprc(Boolean(props.isAppDir));

const queryConnectedCalendars = trpc.viewer.connectedCalendars.useQuery({ onboarding: true });
const { t } = useLocale();
const queryIntegrations = trpc.viewer.integrations.useQuery({
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { getTprc } from "app/getTrpc";

import classNames from "@calcom/lib/classNames";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { trpc } from "@calcom/trpc/react";
import { List } from "@calcom/ui";
import { ArrowRight } from "@calcom/ui/components/icon";

Expand All @@ -9,10 +10,12 @@ import { StepConnectionLoader } from "../components/StepConnectionLoader";

interface ConnectedAppStepProps {
nextStep: () => void;
isAppDir?: boolean;
}

const ConnectedVideoStep = (props: ConnectedAppStepProps) => {
const { nextStep } = props;
const trpc = getTprc(Boolean(props.isAppDir));
const { data: queryConnectedVideoApps, isLoading } = trpc.viewer.integrations.useQuery({
variant: "conferencing",
onlyInstalled: false,
Expand Down
Original file line number Diff line number Diff line change
@@ -1,25 +1,26 @@
import { getTprc } from "app/getTrpc";
import { useForm } from "react-hook-form";

import { Schedule } from "@calcom/features/schedules";
import { DEFAULT_SCHEDULE } from "@calcom/lib/availability";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import type { TRPCClientErrorLike } from "@calcom/trpc/react";
import { trpc } from "@calcom/trpc/react";
import type { AppRouter } from "@calcom/trpc/server/routers/_app";
import { Button, Form } from "@calcom/ui";
import { ArrowRight } from "@calcom/ui/components/icon";

interface ISetupAvailabilityProps {
nextStep: () => void;
defaultScheduleId?: number | null;
isAppDir?: boolean;
}

const SetupAvailability = (props: ISetupAvailabilityProps) => {
const { defaultScheduleId } = props;

const { t } = useLocale();
const { nextStep } = props;

const trpc = getTprc(Boolean(props.isAppDir));
const scheduleId = defaultScheduleId === null ? undefined : defaultScheduleId;
const queryAvailability = trpc.viewer.availability.schedule.get.useQuery(
{ scheduleId: defaultScheduleId ?? undefined },
Expand Down
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { getTprc } from "app/getTrpc";
import { useRouter } from "next/navigation";
import type { FormEvent } from "react";
import { useRef, useState } from "react";
Expand All @@ -8,7 +9,6 @@ import { useLocale } from "@calcom/lib/hooks/useLocale";
import { md } from "@calcom/lib/markdownIt";
import { telemetryEventTypes, useTelemetry } from "@calcom/lib/telemetry";
import turndown from "@calcom/lib/turndownService";
import { trpc } from "@calcom/trpc/react";
import type { Ensure } from "@calcom/types/utils";
import { Button, Editor, ImageUploader, Label, showToast } from "@calcom/ui";
import { ArrowRight } from "@calcom/ui/components/icon";
Expand All @@ -17,7 +17,9 @@ type FormData = {
bio: string;
};

const UserProfile = () => {
const UserProfile = (props: { isAppDir?: boolean }) => {
const trpc = getTprc(Boolean(props.isAppDir));
// @ts-expect-error Property 'useSuspenseQuery' does not exist on type
const [user] = trpc.viewer.me.useSuspenseQuery();
const { t } = useLocale();
const avatarRef = useRef<HTMLInputElement>(null);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { zodResolver } from "@hookform/resolvers/zod";
import { getTprc } from "app/getTrpc";
import { useEffect } from "react";
import { useForm } from "react-hook-form";
import { z } from "zod";
Expand All @@ -8,7 +9,6 @@ import { useTimePreferences } from "@calcom/features/bookings/lib";
import { FULL_NAME_LENGTH_MAX_LIMIT } from "@calcom/lib/constants";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { telemetryEventTypes, useTelemetry } from "@calcom/lib/telemetry";
import { trpc } from "@calcom/trpc/react";
import { Button, TimezoneSelect } from "@calcom/ui";
import { ArrowRight } from "@calcom/ui/components/icon";

Expand All @@ -17,10 +17,13 @@ import { UsernameAvailabilityField } from "@components/ui/UsernameAvailability";
interface IUserSettingsProps {
nextStep: () => void;
hideUsername?: boolean;
isAppDir?: boolean;
}

const UserSettings = (props: IUserSettingsProps) => {
const { nextStep } = props;
const trpc = getTprc(Boolean(props.isAppDir));
// @ts-expect-error Property 'useSuspenseQuery' does not exist on type
const [user] = trpc.viewer.me.useSuspenseQuery();
const { t } = useLocale();
const { setTimezone: setSelectedTimeZone, timezone: selectedTimeZone } = useTimePreferences();
Expand Down
3 changes: 3 additions & 0 deletions apps/web/next.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -155,6 +155,7 @@ const nextConfig = {
"@ewsjs",
"handlebars",
"ews-javascript-api",
"@tryvital",
],
},
i18n: {
Expand Down Expand Up @@ -234,6 +235,8 @@ const nextConfig = {
...config.resolve.fallback, // if you miss it, all the other options in fallback, specified
// by next.js will be dropped. Doesn't make much sense, but how it is
fs: false,
"pg-native": false,
"superagent-proxy": false,
};

/**
Expand Down
2 changes: 1 addition & 1 deletion apps/web/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
"analyze:server": "BUNDLE_ANALYZE=server next build",
"analyze:browser": "BUNDLE_ANALYZE=browser next build",
"clean": "rm -rf .turbo && rm -rf node_modules && rm -rf .next",
"dev": "next dev",
"dev": "NODE_OPTIONS=\"--max_old_space_size=8192\" next",
"dx": "yarn dev",
"test-codegen": "yarn playwright codegen http://localhost:3000",
"type-check": "tsc --pretty --noEmit",
Expand Down
Loading

0 comments on commit f141b21

Please sign in to comment.