Refactors useLocale (#908)

* Removes unused component

* Refactors useLocale

We don't need to pass the locale prop everywhere

* Fixes syntax error

* Adds warning for missing localeProps

* Simplify i18n utils

* Update components/I18nLanguageHandler.tsx

Co-authored-by: Mihai C <[email protected]>

* Type fixes

Co-authored-by: Mihai C <[email protected]>
This commit is contained in:
Omar LópezandMihai C authored and GitHub committed 2021-10-12 13:11:33 +00:00
1 parent 7dd6fdde7a
commit cfd70172f0
35 files changed
+366 -440

No files matched your search

+3 -3
View File
@@ -16,8 +16,8 @@ import Avatar from "@components/ui/Avatar";
export default function User(props: inferSSRProps<typeof getServerSideProps>) {
const { isReady } = useTheme(props.user.theme);
const { user, localeProp, eventTypes } = props;
const { t, locale } = useLocale({ localeProp });
const { user, eventTypes } = props;
const { t } = useLocale();
return (
<>
@@ -50,7 +50,7 @@ export default function User(props: inferSSRProps<typeof getServerSideProps>) {
<Link href={`/${user.username}/${type.slug}`}>
<a className="block px-6 py-4">
<h2 className="font-semibold text-neutral-900 dark:text-white">{type.title}</h2>
<EventTypeDescription localeProp={locale} eventType={type} />
<EventTypeDescription eventType={type} />
</a>
</Link>
</div>
+3
View File
@@ -11,6 +11,8 @@ import superjson from "superjson";
import AppProviders from "@lib/app-providers";
import { seoConfig } from "@lib/config/next-seo.config";
import I18nLanguageHandler from "@components/I18nLanguageHandler";
import type { AppRouter } from "@server/routers/_app";
import "../styles/globals.css";
@@ -26,6 +28,7 @@ function MyApp(props: AppProps) {
return (
<AppProviders {...props}>
<DefaultSeo {...seoConfig.defaultNextSeo} />
<I18nLanguageHandler localeProp={pageProps.localeProp} />
<Component {...pageProps} err={err} />
</AppProviders>
);
+1 -2
View File
@@ -85,7 +85,7 @@ const EventTypePage = (props: inferSSRProps<typeof getServerSideProps>) => {
const { eventType, locationOptions, availability, team, teamMembers, hasPaymentIntegration, currency } =
props;
const { t, locale } = useLocale({ localeProp: props.localeProp });
const { t } = useLocale();
const router = useRouter();
const [successModalOpen, setSuccessModalOpen] = useState(false);
@@ -992,7 +992,6 @@ const EventTypePage = (props: inferSSRProps<typeof getServerSideProps>) => {
{t("delete")}
</DialogTrigger>
<ConfirmationDialogContent
localeProp={locale}
variety="danger"
title={t("delete_event_type")}
confirmBtnText={t("confirm_delete_event_type")}
+9 -238
View File
@@ -1,28 +1,18 @@
// TODO: replace headlessui with radix-ui
import { Menu, Transition } from "@headlessui/react";
import {
ChevronDownIcon,
DotsHorizontalIcon,
ExternalLinkIcon,
LinkIcon,
PlusIcon,
UsersIcon,
} from "@heroicons/react/solid";
import { SchedulingType, Prisma } from "@prisma/client";
import { ChevronDownIcon, PlusIcon } from "@heroicons/react/solid";
import { Prisma, SchedulingType } from "@prisma/client";
import { GetServerSidePropsContext } from "next";
import { serverSideTranslations } from "next-i18next/serverSideTranslations";
import Head from "next/head";
import Link from "next/link";
import { useRouter } from "next/router";
import React, { Fragment, useRef } from "react";
import { useMutation } from "react-query";
import { asStringOrNull } from "@lib/asStringOrNull";
import { getSession } from "@lib/auth";
import classNames from "@lib/classNames";
import { HttpError } from "@lib/core/http/error";
import { getOrSetUserLocaleFromHeaders } from "@lib/core/i18n/i18n.utils";
import { shouldShowOnboarding, ONBOARDING_NEXT_REDIRECT } from "@lib/getting-started";
import { ONBOARDING_NEXT_REDIRECT, shouldShowOnboarding } from "@lib/getting-started";
import { useLocale } from "@lib/hooks/useLocale";
import { useToggleQuery } from "@lib/hooks/useToggleQuery";
import createEventType from "@lib/mutations/event-types/create-event-type";
@@ -32,12 +22,10 @@ import { inferSSRProps } from "@lib/types/inferSSRProps";
import { Dialog, DialogClose, DialogContent } from "@components/Dialog";
import Shell from "@components/Shell";
import { Tooltip } from "@components/Tooltip";
import EventTypeDescription from "@components/eventtype/EventTypeDescription";
import EventTypeList from "@components/eventtype/EventTypeList";
import EventTypeListHeading from "@components/eventtype/EventTypeListHeading";
import { Alert } from "@components/ui/Alert";
import Avatar from "@components/ui/Avatar";
import AvatarGroup from "@components/ui/AvatarGroup";
import Badge from "@components/ui/Badge";
import { Button } from "@components/ui/Button";
import Dropdown, {
DropdownMenuContent,
@@ -50,12 +38,10 @@ import * as RadioArea from "@components/ui/form/radio-area";
import UserCalendarIllustration from "@components/ui/svg/UserCalendarIllustration";
type PageProps = inferSSRProps<typeof getServerSideProps>;
type EventType = PageProps["eventTypes"][number];
type Profile = PageProps["profiles"][number];
type MembershipCount = EventType["metadata"]["membershipCount"];
const EventTypesPage = (props: PageProps) => {
const { t, locale } = useLocale({ localeProp: props.localeProp });
const { t } = useLocale();
const CreateFirstEventTypeView = () => (
<div className="md:py-20">
@@ -63,218 +49,11 @@ const EventTypesPage = (props: PageProps) => {
<div className="block mx-auto text-center md:max-w-screen-sm">
<h3 className="mt-2 text-xl font-bold text-neutral-900">{t("new_event_type_heading")}</h3>
<p className="mt-1 mb-2 text-md text-neutral-600">{t("new_event_type_description")}</p>
<CreateNewEventDialog
localeProp={locale}
canAddEvents={props.canAddEvents}
profiles={props.profiles}
/>
<CreateNewEventDialog canAddEvents={props.canAddEvents} profiles={props.profiles} />
</div>
</div>
);
const EventTypeListHeading = ({
profile,
membershipCount,
}: {
profile?: Profile;
membershipCount: MembershipCount;
}) => (
<div className="flex mb-4">
<Link href="/settings/teams">
<a>
<Avatar
displayName={profile?.name || ""}
imageSrc={profile?.image || undefined}
size={8}
className="inline mt-1 mr-2"
/>
</a>
</Link>
<div>
<Link href="/settings/teams">
<a className="font-bold">{profile?.name || ""}</a>
</Link>
{membershipCount && (
<span className="relative ml-2 text-xs text-neutral-500 -top-px">
<Link href="/settings/teams">
<a>
<Badge variant="gray">
<UsersIcon className="inline w-3 h-3 mr-1 -mt-px" />
{membershipCount}
</Badge>
</a>
</Link>
</span>
)}
{profile?.slug && (
<Link href={`${process.env.NEXT_PUBLIC_APP_URL}/${profile.slug}`}>
<a className="block text-xs text-neutral-500">{`${process.env.NEXT_PUBLIC_APP_URL?.replace(
"https://",
""
)}/${profile.slug}`}</a>
</Link>
)}
</div>
</div>
);
const EventTypeList = ({
readOnly,
types,
profile,
}: {
profile: PageProps["profiles"][number];
readOnly: boolean;
types: EventType["eventTypes"];
}) => (
<div className="mb-16 -mx-4 overflow-hidden bg-white border border-gray-200 rounded-sm sm:mx-0">
<ul className="divide-y divide-neutral-200" data-testid="event-types">
{types.map((type) => (
<li
key={type.id}
className={classNames(
type.$disabled && "opacity-30 cursor-not-allowed pointer-events-none select-none"
)}
data-disabled={type.$disabled ? 1 : 0}>
<div
className={classNames(
"hover:bg-neutral-50 flex justify-between items-center ",
type.$disabled && "pointer-events-none"
)}>
<div className="flex items-center justify-between w-full px-4 py-4 sm:px-6 hover:bg-neutral-50">
<Link href={"/event-types/" + type.id}>
<a className="flex-grow text-sm truncate">
<div>
<span className="font-medium truncate text-neutral-900">{type.title}</span>
{type.hidden && (
<span className="ml-2 inline items-center px-1.5 py-0.5 rounded-sm text-xs font-medium bg-yellow-100 text-yellow-800">
{t("hidden")}
</span>
)}
{readOnly && (
<span className="ml-2 inline items-center px-1.5 py-0.5 rounded-sm text-xs font-medium bg-gray-100 text-gray-800">
{t("readonly")}
</span>
)}
</div>
<EventTypeDescription localeProp={locale} eventType={type} />
</a>
</Link>
<div className="flex-shrink-0 hidden mt-4 sm:flex sm:mt-0 sm:ml-5">
<div className="flex items-center space-x-2 overflow-hidden">
{type.users?.length > 1 && (
<AvatarGroup
size={8}
truncateAfter={4}
items={type.users.map((organizer) => ({
alt: organizer.name || "",
image: organizer.avatar || "",
}))}
/>
)}
<Tooltip content="Preview">
<a
href={`${process.env.NEXT_PUBLIC_APP_URL}/${profile.slug}/${type.slug}`}
target="_blank"
rel="noreferrer"
className="btn-icon">
<ExternalLinkIcon className="w-5 h-5 group-hover:text-black" />
</a>
</Tooltip>
<Tooltip content="Copy link">
<button
onClick={() => {
showToast("Link copied!", "success");
navigator.clipboard.writeText(
`${process.env.NEXT_PUBLIC_APP_URL}/${profile.slug}/${type.slug}`
);
}}
className="btn-icon">
<LinkIcon className="w-5 h-5 group-hover:text-black" />
</button>
</Tooltip>
</div>
</div>
</div>
<div className="flex flex-shrink-0 mr-5 sm:hidden">
<Menu as="div" className="inline-block text-left">
{({ open }) => (
<>
<div>
<Menu.Button className="p-2 mt-1 border border-transparent text-neutral-400 hover:border-gray-200">
<span className="sr-only">{t("open_options")}</span>
<DotsHorizontalIcon className="w-5 h-5" aria-hidden="true" />
</Menu.Button>
</div>
<Transition
show={open}
as={Fragment}
enter="transition ease-out duration-100"
enterFrom="transform opacity-0 scale-95"
enterTo="transform opacity-100 scale-100"
leave="transition ease-in duration-75"
leaveFrom="transform opacity-100 scale-100"
leaveTo="transform opacity-0 scale-95">
<Menu.Items
static
className="absolute right-0 z-10 w-56 mt-2 origin-top-right bg-white divide-y rounded-sm shadow-lg ring-1 ring-black ring-opacity-5 focus:outline-none divide-neutral-100">
<div className="py-1">
<Menu.Item>
{({ active }) => (
<a
href={`${process.env.NEXT_PUBLIC_APP_URL}/${profile.slug}/${type.slug}`}
target="_blank"
rel="noreferrer"
className={classNames(
active ? "bg-neutral-100 text-neutral-900" : "text-neutral-700",
"group flex items-center px-4 py-2 text-sm font-medium"
)}>
<ExternalLinkIcon
className="w-4 h-4 mr-3 text-neutral-400 group-hover:text-neutral-500"
aria-hidden="true"
/>
{t("preview")}
</a>
)}
</Menu.Item>
<Menu.Item>
{({ active }) => (
<button
onClick={() => {
showToast("Link copied!", "success");
navigator.clipboard.writeText(
`${process.env.NEXT_PUBLIC_APP_URL}/${profile.slug}/${type.slug}`
);
}}
className={classNames(
active ? "bg-neutral-100 text-neutral-900" : "text-neutral-700",
"group flex items-center px-4 py-2 text-sm w-full font-medium"
)}>
<LinkIcon
className="w-4 h-4 mr-3 text-neutral-400 group-hover:text-neutral-500"
aria-hidden="true"
/>
{t("copy_link")}
</button>
)}
</Menu.Item>
</div>
</Menu.Items>
</Transition>
</>
)}
</Menu>
</div>
</div>
</li>
))}
</ul>
</div>
);
return (
<div>
<Head>
@@ -328,19 +107,11 @@ const EventTypesPage = (props: PageProps) => {
);
};
const CreateNewEventDialog = ({
profiles,
canAddEvents,
localeProp,
}: {
profiles: Profile[];
canAddEvents: boolean;
localeProp: string;
}) => {
const CreateNewEventDialog = ({ profiles, canAddEvents }: { profiles: Profile[]; canAddEvents: boolean }) => {
const router = useRouter();
const teamId: number | null = Number(router.query.teamId) || null;
const modalOpen = useToggleQuery("new");
const { t } = useLocale({ localeProp });
const { t } = useLocale();
const createMutation = useMutation(createEventType, {
onSuccess: async ({ eventType }) => {
+15 -12
View File
@@ -13,7 +13,6 @@ import {
localeOptions,
OptionType,
} from "@lib/core/i18n/i18n.utils";
import { useLocale } from "@lib/hooks/useLocale";
import { isBrandingHidden } from "@lib/isBrandingHidden";
import prisma from "@lib/prisma";
import { trpc } from "@lib/trpc";
@@ -92,7 +91,6 @@ function HideBrandingInput(props: {
}
export default function Settings(props: Props) {
const { locale } = useLocale({ localeProp: props.localeProp });
const mutation = trpc.useMutation("viewer.updateProfile");
const [successModalOpen, setSuccessModalOpen] = useState(false);
@@ -101,14 +99,19 @@ export default function Settings(props: Props) {
const descriptionRef = useRef<HTMLTextAreaElement>();
const avatarRef = useRef<HTMLInputElement>(null);
const hideBrandingRef = useRef<HTMLInputElement>(null);
const [selectedTheme, setSelectedTheme] = useState({ value: props.user.theme });
const [selectedTimeZone, setSelectedTimeZone] = useState({ value: props.user.timeZone });
const [selectedWeekStartDay, setSelectedWeekStartDay] = useState({ value: props.user.weekStart });
const [selectedLanguage, setSelectedLanguage] = useState<OptionType>({
value: locale,
label: props.localeLabels[locale],
const [selectedTheme, setSelectedTheme] = useState<null | { value: string | null }>({
value: props.user.theme,
});
const [imageSrc, setImageSrc] = useState<string>(props.user.avatar);
const [selectedTimeZone, setSelectedTimeZone] = useState({ value: props.user.timeZone });
const [selectedWeekStartDay, setSelectedWeekStartDay] = useState({
value: props.user.weekStart,
label: "",
});
const [selectedLanguage, setSelectedLanguage] = useState<OptionType>({
value: props.localeProp,
label: props.localeLabels[props.localeProp],
});
const [imageSrc, setImageSrc] = useState<string>(props.user.avatar || "");
const [hasErrors, setHasErrors] = useState(false);
const [errorMessage, setErrorMessage] = useState("");
@@ -117,7 +120,7 @@ export default function Settings(props: Props) {
props.user.theme ? themeOptions.find((theme) => theme.value === props.user.theme) : null
);
setSelectedWeekStartDay({ value: props.user.weekStart, label: props.user.weekStart });
setSelectedLanguage({ value: locale, label: props.localeLabels[locale] });
setSelectedLanguage({ value: props.localeProp, label: props.localeLabels[props.localeProp] });
}, []);
const closeSuccessModal = () => {
@@ -276,7 +279,7 @@ export default function Settings(props: Props) {
<div className="mt-1">
<Select
id="languageSelect"
value={selectedLanguage || locale}
value={selectedLanguage || props.localeProp}
onChange={setSelectedLanguage}
classNamePrefix="react-select"
className="react-select-container border border-gray-300 rounded-sm shadow-sm focus:ring-neutral-500 focus:border-neutral-500 mt-1 block w-full sm:text-sm"
@@ -327,7 +330,7 @@ export default function Settings(props: Props) {
defaultValue={selectedTheme || themeOptions[0]}
value={selectedTheme || themeOptions[0]}
onChange={setSelectedTheme}
className="shadow-sm focus:ring-neutral-500 focus:border-neutral-500 mt-1 block w-full sm:text-sm border-gray-300 rounded-sm"
className="shadow-sm | { value: string } focus:ring-neutral-500 focus:border-neutral-500 mt-1 block w-full sm:text-sm border-gray-300 rounded-sm"
options={themeOptions}
/>
</div>
+11 -6
View File
@@ -1,3 +1,4 @@
import { GetServerSidePropsContext } from "next";
import { serverSideTranslations } from "next-i18next/serverSideTranslations";
import React from "react";
@@ -5,26 +6,26 @@ import { getSession } from "@lib/auth";
import { getOrSetUserLocaleFromHeaders } from "@lib/core/i18n/i18n.utils";
import { useLocale } from "@lib/hooks/useLocale";
import prisma from "@lib/prisma";
import { inferSSRProps } from "@lib/types/inferSSRProps";
import SettingsShell from "@components/SettingsShell";
import Shell from "@components/Shell";
import ChangePasswordSection from "@components/security/ChangePasswordSection";
import TwoFactorAuthSection from "@components/security/TwoFactorAuthSection";
export default function Security({ user, localeProp }) {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const { locale, t } = useLocale({ localeProp });
export default function Security({ user }: inferSSRProps<typeof getServerSideProps>) {
const { t } = useLocale();
return (
<Shell heading={t("security")} subtitle={t("manage_account_security")}>
<SettingsShell>
<ChangePasswordSection localeProp={locale} />
<TwoFactorAuthSection localeProp={locale} twoFactorEnabled={user.twoFactorEnabled} />
<ChangePasswordSection />
<TwoFactorAuthSection twoFactorEnabled={user.twoFactorEnabled} />
</SettingsShell>
</Shell>
);
}
export async function getServerSideProps(context) {
export async function getServerSideProps(context: GetServerSidePropsContext) {
const session = await getSession(context);
const locale = await getOrSetUserLocaleFromHeaders(context.req);
@@ -44,6 +45,10 @@ export async function getServerSideProps(context) {
},
});
if (!user) {
return { redirect: { permanent: false, destination: "/auth/login" } };
}
return {
props: {
localeProp: locale,
+3 -10
View File
@@ -8,7 +8,6 @@ import { useEffect, useRef, useState } from "react";
import { getSession } from "@lib/auth";
import { getOrSetUserLocaleFromHeaders } from "@lib/core/i18n/i18n.utils";
import { useLocale } from "@lib/hooks/useLocale";
import { Member } from "@lib/member";
import { Team } from "@lib/team";
@@ -20,7 +19,7 @@ import TeamList from "@components/team/TeamList";
import TeamListItem from "@components/team/TeamListItem";
import Button from "@components/ui/Button";
export default function Teams(props: { localeProp: string }) {
export default function Teams() {
const noop = () => undefined;
const [, loading] = useSession();
const [teams, setTeams] = useState([]);
@@ -29,7 +28,6 @@ export default function Teams(props: { localeProp: string }) {
const [editTeamEnabled, setEditTeamEnabled] = useState(false);
const [teamToEdit, setTeamToEdit] = useState<Team | null>();
const nameRef = useRef<HTMLInputElement>() as React.MutableRefObject<HTMLInputElement>;
const { locale } = useLocale({ localeProp: props.localeProp });
const handleErrors = async (resp: Response) => {
if (!resp.ok) {
@@ -114,11 +112,7 @@ export default function Teams(props: { localeProp: string }) {
</div>
<div>
{!!teams.length && (
<TeamList
localeProp={locale}
teams={teams}
onChange={loadData}
onEditTeam={editTeam}></TeamList>
<TeamList teams={teams} onChange={loadData} onEditTeam={editTeam}></TeamList>
)}
{!!invites.length && (
@@ -127,7 +121,6 @@ export default function Teams(props: { localeProp: string }) {
<ul className="px-4 mt-4 mb-2 bg-white border divide-y divide-gray-200 rounded">
{invites.map((team: Team) => (
<TeamListItem
localeProp={locale}
onChange={loadData}
key={team.id}
team={team}
@@ -140,7 +133,7 @@ export default function Teams(props: { localeProp: string }) {
</div>
</div>
)}
{!!editTeamEnabled && <EditTeam localeProp={locale} team={teamToEdit} onCloseEdit={onCloseEdit} />}
{!!editTeamEnabled && <EditTeam team={teamToEdit} onCloseEdit={onCloseEdit} />}
{showCreateTeamModal && (
<div
className="fixed inset-0 z-50 overflow-y-auto"
+4 -4
View File
@@ -21,10 +21,10 @@ import AvatarGroup from "@components/ui/AvatarGroup";
import Button from "@components/ui/Button";
import Text from "@components/ui/Text";
function TeamPage({ team, localeProp }: inferSSRProps<typeof getServerSideProps>) {
function TeamPage({ team }: inferSSRProps<typeof getServerSideProps>) {
const { isReady } = useTheme();
const showMembers = useToggleQuery("members");
const { t, locale } = useLocale({ localeProp: localeProp });
const { t } = useLocale();
const eventTypes = (
<ul className="space-y-3">
@@ -37,7 +37,7 @@ function TeamPage({ team, localeProp }: inferSSRProps<typeof getServerSideProps>
<a className="px-6 py-4 flex justify-between">
<div className="flex-shrink">
<h2 className="font-cal font-semibold text-neutral-900 dark:text-white">{type.title}</h2>
<EventTypeDescription localeProp={locale} className="text-sm" eventType={type} />
<EventTypeDescription className="text-sm" eventType={type} />
</div>
<div className="mt-1">
<AvatarGroup
@@ -68,7 +68,7 @@ function TeamPage({ team, localeProp }: inferSSRProps<typeof getServerSideProps>
<Avatar alt={teamName} imageSrc={team.logo} className="mx-auto w-20 h-20 rounded-full mb-4" />
<Text variant="headline">{teamName}</Text>
</div>
{(showMembers.isOn || !team.eventTypes.length) && <Team localeProp={locale} team={team} />}
{(showMembers.isOn || !team.eventTypes.length) && <Team team={team} />}
{!showMembers.isOn && team.eventTypes.length > 0 && (
<div className="mx-auto max-w-3xl">
{eventTypes}