Skip to content

Rallly is an open-source scheduling and collaboration tool designed to make organizing events and meetings easier.

13.6 KB
Raw Blame
"use client";

import { zodResolver } from "@hookform/resolvers/zod";
import { mutationOptions } from "@next-safe-action/adapter-tanstack-query";
import { passwordManagerIgnoreProps } from "@rallly/ui";
import { Button } from "@rallly/ui/button";
import { ButtonGroup, ButtonGroupItem } from "@rallly/ui/button-group";
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from "@rallly/ui/form";
import { Input } from "@rallly/ui/input";
import { RadioGroup, RadioGroupItem } from "@rallly/ui/radio-group";
import { useMutation } from "@tanstack/react-query";
import { BriefcaseIcon, UserIcon } from "lucide-react";
import React from "react";
import { useForm } from "react-hook-form";
import * as z from "zod";
import { setupSpaceAction } from "@/app/[locale]/setup/actions";
import { TimeZoneSelect } from "@/components/time-zone-picker/time-zone-select";
import { IndustrySelect } from "@/features/space/components/industry-select";
import { industries } from "@/features/space/constants";
import { inferIndustry } from "@/features/space/utils";
import { JobTitleSelect } from "@/features/user/components/job-title-select";
import { JOB_TITLE_OTHER_MAX_LENGTH } from "@/features/user/constants";
import { Trans, useTranslation } from "@/i18n/client";
import { authClient } from "@/lib/auth-client";
import { getLocaleDefaults } from "@/lib/datetime/locales";
import type { TimeFormat } from "@/lib/datetime/types";
import { useLocale } from "@/lib/locale/client";
import { getBrowserTimeZone } from "@/lib/utils/date-time-utils";

function useSetupFormSchema() {
  const { t } = useTranslation();
  return React.useMemo(() => {
    return z
      .object({
        name: z.string().min(1).max(100),
        timeZone: z.string().min(1),
        timeFormat: z.enum(["hours12", "hours24"]),
        spaceType: z.enum(["personal", "work"]),
        organizationName: z.string().max(100),
        // Both optional: a required field against a guessed taxonomy forces
        // bad matches, and a skipped one reads as "none of these fit", which
        // is itself signal.
        industry: z.enum(industries).nullable(),
        jobTitle: z.string().max(JOB_TITLE_OTHER_MAX_LENGTH).nullable(),
      })
      .refine(
        (data) =>
          data.spaceType === "personal" ||
          data.organizationName.trim().length > 0,
        {
          path: ["organizationName"],
          message: t("organizationNameRequired", {
            defaultValue: "Organization name is required",
          }),
        },
      );
  }, [t]);
}

function SpaceTypeOption({
  value,
  icon,
  label,
}: {
  value: string;
  icon: React.ReactNode;
  label: string;
}) {
  const id = React.useId();
  return (
    <label
      htmlFor={id}
      className="group flex h-9 cursor-pointer items-center gap-2 rounded-lg border border-input bg-card px-3 text-sm transition-colors hover:bg-accent has-data-checked:border-primary has-data-checked:bg-primary/5"
    >
      <span className="text-muted-foreground group-has-data-checked:text-primary">
        {icon}
      </span>
      <span className="flex-1 font-normal">{label}</span>
      <RadioGroupItem className="hidden" id={id} value={value} />
    </label>
  );
}

export function SetupForm({
  defaultName,
  defaultTimeZone,
  defaultTimeFormat,
  email,
}: {
  defaultName: string;
  defaultTimeZone?: string;
  defaultTimeFormat?: TimeFormat;
  /**
   * Only used to guess an industry. The server runs the same classifier on
   * the way in, so nothing here is trusted — this just lets the guess follow
   * the organization name as it is typed, which the server can't see yet.
   */
  email: string;
}) {
  const { t } = useTranslation();
  const { locale } = useLocale();
  const schema = useSetupFormSchema();
  const setupSpace = useMutation(mutationOptions(setupSpaceAction));

  const form = useForm({
    resolver: zodResolver(schema),
    defaultValues: {
      name: defaultName,
      timeZone: defaultTimeZone || getBrowserTimeZone(),
      timeFormat: defaultTimeFormat ?? getLocaleDefaults(locale).timeFormat,
      spaceType: "personal" as const,
      organizationName: "",
      industry: inferIndustry({ email, organizationName: "" }) ?? null,
      jobTitle: null,
    },
  });

  const spaceType = form.watch("spaceType");

  // The inferred value is a prefill, not an answer: once the user touches the
  // field it stops moving, and what gets stored is whatever they confirmed.
  const industryTouched = React.useRef(false);

  return (
    <Form {...form}>
      <form
        onSubmit={form.handleSubmit(
          async ({
            name,
            timeZone,
            timeFormat,
            spaceType,
            organizationName,
            industry,
            jobTitle,
          }) => {
            const res = await authClient.updateUser({
              name,
              timeZone,
              timeFormat,
              locale,
            });

            if (res.error) {
              form.setError("root", {
                message: res.error.message,
              });
              return;
            }

            // Server errors surface through the global mutation toast; the
            // button unlocks (isSuccess stays false) so the user can retry.
            // On success the action refreshes the page, which redirects
            // onward while the button stays loading.
            try {
              await setupSpace.mutateAsync(
                spaceType === "work"
                  ? {
                      spaceType,
                      organizationName: organizationName.trim(),
                      industry: industry ?? undefined,
                      jobTitle: jobTitle ?? undefined,
                    }
                  : { spaceType },
              );
            } catch {}
          },
        )}
        className="space-y-4"
      >
        <FormField
          control={form.control}
          name="name"
          render={({ field }) => (
            <FormItem>
              <FormLabel>
                <Trans i18nKey="name" defaults="Name" />
              </FormLabel>
              <FormControl>
                <Input
                  {...field}
                  autoComplete="name"
                  {...passwordManagerIgnoreProps}
                  placeholder={t("namePlaceholder", {
                    defaultValue: "Jessie Smith",
                  })}
                  disabled={form.formState.isSubmitting}
                  autoFocus={true}
                />
              </FormControl>
              <FormMessage />
            </FormItem>
          )}
        />
        <div className="grid grid-cols-2 gap-2">
          <FormField
            control={form.control}
            name="timeZone"
            render={({ field }) => (
              <FormItem>
                <FormLabel>
                  <Trans i18nKey="timeZone" defaults="Time zone" />
                </FormLabel>
                <FormControl>
                  <TimeZoneSelect
                    // The combobox input group is h-8 by default; match the
                    // h-9 controls in the rest of the form
                    className="min-w-0 [&_[data-slot=input-group]]:h-9"
                    value={field.value}
                    onValueChange={field.onChange}
                    disabled={form.formState.isSubmitting}
                  />
                </FormControl>
                <FormMessage />
              </FormItem>
            )}
          />
          <FormField
            control={form.control}
            name="timeFormat"
            render={({ field }) => (
              <FormItem>
                <FormLabel>
                  <Trans i18nKey="timeFormat" defaults="Time format" />
                </FormLabel>
                <FormControl>
                  <ButtonGroup
                    className="w-full"
                    value={field.value}
                    onValueChange={field.onChange}
                    disabled={form.formState.isSubmitting}
                  >
                    <ButtonGroupItem value="hours12">
                      <Trans i18nKey="12h" defaults="12-hour" />
                    </ButtonGroupItem>
                    <ButtonGroupItem value="hours24">
                      <Trans i18nKey="24h" defaults="24-hour" />
                    </ButtonGroupItem>
                  </ButtonGroup>
                </FormControl>
                <FormMessage />
              </FormItem>
            )}
          />
        </div>
        <FormField
          control={form.control}
          name="spaceType"
          render={({ field }) => (
            <FormItem>
              <FormLabel>
                <Trans
                  i18nKey="spaceTypeLabel"
                  defaults="What will you be using it for?"
                />
              </FormLabel>
              <FormControl>
                <RadioGroup
                  value={field.value}
                  onValueChange={(value) => {
                    field.onChange(value);
                    form.clearErrors("organizationName");
                  }}
                  className="grid grid-cols-2 gap-2"
                >
                  <SpaceTypeOption
                    value="personal"
                    icon={<UserIcon className="size-4" />}
                    label={t("spaceTypePersonal", {
                      defaultValue: "Personal",
                    })}
                  />
                  <SpaceTypeOption
                    value="work"
                    icon={<BriefcaseIcon className="size-4" />}
                    label={t("spaceTypeWork", { defaultValue: "Work" })}
                  />
                </RadioGroup>
              </FormControl>
              <FormMessage />
            </FormItem>
          )}
        />
        {spaceType === "work" ? (
          <>
            <FormField
              control={form.control}
              name="organizationName"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>
                    <Trans
                      i18nKey="organizationName"
                      defaults="Organization name"
                    />
                  </FormLabel>
                  <FormControl>
                    <Input
                      {...field}
                      {...passwordManagerIgnoreProps}
                      onChange={(event) => {
                        field.onChange(event);
                        if (!industryTouched.current) {
                          form.setValue(
                            "industry",
                            inferIndustry({
                              email,
                              organizationName: event.target.value,
                            }) ?? null,
                          );
                        }
                      }}
                      autoFocus={true}
                      placeholder={t("organizationNamePlaceholder", {
                        defaultValue: "e.g. Acme Corp",
                      })}
                      disabled={form.formState.isSubmitting}
                    />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />
            {/* Industry first: confirming a sector primes a more precise
                answer to the role question below. */}
            <FormField
              control={form.control}
              name="industry"
              render={({ field }) => (
                <FormItem>
                  <FormLabel htmlFor="industry">
                    <Trans i18nKey="industry" defaults="Industry" />
                    <span className="ml-1 font-normal text-muted-foreground">
                      <Trans i18nKey="optional" defaults="(optional)" />
                    </span>
                  </FormLabel>
                  <FormControl>
                    <IndustrySelect
                      id="industry"
                      value={field.value}
                      onValueChange={(value) => {
                        industryTouched.current = true;
                        field.onChange(value);
                      }}
                      disabled={form.formState.isSubmitting}
                    />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />
            <FormField
              control={form.control}
              name="jobTitle"
              render={({ field }) => (
                <FormItem>
                  <FormLabel htmlFor="jobTitle">
                    <Trans i18nKey="jobTitle" defaults="Your role" />
                    <span className="ml-1 font-normal text-muted-foreground">
                      <Trans i18nKey="optional" defaults="(optional)" />
                    </span>
                  </FormLabel>
                  <FormControl>
                    <JobTitleSelect
                      id="jobTitle"
                      value={field.value}
                      onValueChange={field.onChange}
                      disabled={form.formState.isSubmitting}
                    />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />
          </>
        ) : null}
        {form.formState.errors.root?.message ? (
          <FormMessage>{form.formState.errors.root.message}</FormMessage>
        ) : null}
        <div className="mt-6">
          <Button
            type="submit"
            variant="primary"
            size="lg"
            loading={form.formState.isSubmitting || setupSpace.isSuccess}
            className="w-full"
          >
            <Trans i18nKey="continue" defaults="Continue" />
          </Button>
        </div>
      </form>
    </Form>
  );
}