Feature/booking filters (#6099)

* EventTypeFilter UI working

* Tidy + fix avatar + fix overflow

* Component store

* WIP - switchin to query filtering instead of state

* Push working

* Checkbox approach - weird conditional toggle for all bookings

* WIP

* the master query hook :O

* useTypedQuery

* Working typed query

* Typed query hook

* Add optional keys

* safeParse query params

* Add use callback

* Fix re-renders

* Remove local version of local query and use util branch

* Working team filters!

* working people filter!

* Tidy up

* NIT

Co-authored-by: zomars <[email protected]>
This commit is contained in:
sean-brydonandzomars authored and GitHub committed 2022-12-22 12:35:01 +00:00
1 parent 83b60de640
commit cefcb1eaf8
20 files changed
+556 -51

No files matched your search

@@ -0,0 +1,77 @@
import { useSession } from "next-auth/react";
import { Fragment, useState, useEffect } from "react";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { trpc, RouterOutputs } from "@calcom/trpc/react";
import { AnimatedPopover } from "@calcom/ui";
import { groupBy } from "../groupBy";
export type IEventTypesFilters = RouterOutputs["viewer"]["eventTypes"]["listWithTeam"];
export type IEventTypeFilter = IEventTypesFilters[0];
type GroupedEventTypeState = Record<
string,
{
team: {
id: number;
name: string;
} | null;
id: number;
title: string;
slug: string;
}[]
>;
export const EventTypeFilter = () => {
const { t } = useLocale();
const { data: user } = useSession();
const eventTypes = trpc.viewer.eventTypes.listWithTeam.useQuery();
const [groupedEventTypes, setGroupedEventTypes] = useState<GroupedEventTypeState>();
// Will be handled up the tree to redirect
useEffect(() => {
if (!eventTypes.data) return;
// Group event types by team
const grouped = groupBy<IEventTypeFilter>(
eventTypes.data.filter((el) => el.team),
(item) => item?.team?.name || ""
); // Add the team name
const individualEvents = eventTypes.data.filter((el) => !el.team);
// push indivdual events to the start of grouped array
setGroupedEventTypes({ user_own_event_types: individualEvents, ...grouped });
}, [eventTypes.data, user]);
if (!user) return null;
return (
<AnimatedPopover text={t("event_type")}>
<div className="">
{groupedEventTypes &&
Object.keys(groupedEventTypes).map((teamName) => (
<Fragment key={teamName}>
<div className="p-4 text-xs font-medium uppercase leading-none text-gray-500">
{teamName === "user_own_event_types" ? t("individual") : teamName}
</div>
{groupedEventTypes[teamName].map((eventType) => (
<Fragment key={eventType.id}>
<div className="item-center flex px-4 py-[6px]">
<p className="block self-center truncate text-sm font-medium text-gray-700">
{eventType.title}
</p>
<div className="ml-auto">
<input
type="checkbox"
name=""
id=""
className="text-primary-600 focus:ring-primary-500 mr-2 h-4 w-4 rounded border-gray-300 "
/>
</div>
</div>
</Fragment>
))}
</Fragment>
))}
</div>
</AnimatedPopover>
);
};
@@ -0,0 +1,43 @@
import { Fragment, ReactNode } from "react";
import { PeopleFilter } from "./PeopleFilter";
import { TeamsMemberFilter } from "./TeamFilter";
type FilterTypes = "teams" | "people";
type Filter = {
name: FilterTypes;
controllingQueryParams?: string[]; // this is what the filter controls - but also we show the filter if any of these query params are present
component: ReactNode;
showByDefault?: boolean;
};
const filters: Filter[] = [
{
name: "teams",
component: <TeamsMemberFilter />,
controllingQueryParams: ["teamId"],
showByDefault: true,
},
{
name: "people",
component: <PeopleFilter />,
controllingQueryParams: ["usersId"],
showByDefault: true,
},
];
export function FiltersContainer() {
return (
<div className="flex w-full space-x-2 overflow-x-scroll lg:justify-end ">
{filters.map((filter) => {
if (!filter.showByDefault) {
// TODO: check if any of the controllingQueryParams are present in the query params and show the filter if so
// TODO: Also check state to see if the user has toggled the filter
return null;
}
return <Fragment key={filter.name}>{filter.component}</Fragment>;
})}
</div>
);
}
@@ -0,0 +1,74 @@
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { trpc } from "@calcom/trpc/react";
import { AnimatedPopover, Avatar, Icon } from "@calcom/ui";
import { useFilterQuery } from "../lib/useFilterQuery";
export const PeopleFilter = () => {
const { t } = useLocale();
const { data: query, pushItemToKey, removeItemByKeyAndValue, removeByKey } = useFilterQuery();
const { data } = trpc.viewer.teams.listMembers.useQuery({});
if (!data || !data.length) return null;
// Get user names from query
const userNames = data?.filter((user) => query.userIds?.includes(user.id)).map((user) => user.name);
return (
<AnimatedPopover
text={userNames && userNames.length > 0 ? `${userNames.join(", ")}` : t("all_users_filter_label")}>
<div className="item-center flex px-4 py-[6px] focus-within:bg-gray-100">
<div className="mr-2 flex h-6 w-6 items-center justify-center">
<Icon.FiUser className="h-full w-full" />
</div>
<label htmlFor="allUsers" className="mr-auto self-center truncate text-sm font-medium text-gray-700">
{t("all_users_filter_label")}
</label>
<input
id="allUsers"
type="checkbox"
checked={!query.userIds}
onChange={() => {
// Always clear userIds on toggle as this is the toggle box for all users. No params means we are currently selecting all users
removeByKey("userIds");
}}
className="text-primary-600 focus:ring-primary-500 inline-flex h-4 w-4 place-self-center justify-self-end rounded border-gray-300 "
/>
</div>
{data &&
data.map((user) => (
<div className="item-center flex px-4 py-[6px] focus-within:bg-gray-100" key={`${user.id}`}>
<Avatar
imageSrc={user.avatar}
size="sm"
alt={`${user.name} Avatar`}
gravatarFallbackMd5="fallback"
className="self-center"
asChild
/>
<label
htmlFor={user.name ?? "NamelessUser"}
className="ml-2 mr-auto self-center truncate text-sm font-medium text-gray-700">
{user.name}
</label>
<input
id={user.name ?? "NamelessUser"}
name={user.name ?? "NamelessUser"}
type="checkbox"
checked={query.userIds?.includes(user.id)}
onChange={(e) => {
if (e.target.checked) {
pushItemToKey("userIds", user.id);
} else if (!e.target.checked) {
removeItemByKeyAndValue("userIds", user.id);
}
}}
className="text-primary-600 focus:ring-primary-500 inline-flex h-4 w-4 place-self-center justify-self-end rounded border-gray-300 "
/>
</div>
))}
</AnimatedPopover>
);
};
@@ -0,0 +1,75 @@
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { trpc } from "@calcom/trpc/react";
import { AnimatedPopover, Avatar, Icon } from "@calcom/ui";
import { useFilterQuery } from "../lib/useFilterQuery";
export const TeamsMemberFilter = () => {
const { t } = useLocale();
const { data: query, pushItemToKey, removeItemByKeyAndValue, removeByKey } = useFilterQuery();
const { data } = trpc.viewer.teams.list.useQuery();
if (!data || !data.length) return null;
// get team names from query
const teamNames = data?.filter((team) => query.teamIds?.includes(team.id)).map((team) => team.name);
return (
<AnimatedPopover
text={teamNames && teamNames.length > 0 ? `${teamNames.join(", ")}` : t("all_bookings_filter_label")}>
<div className="item-center flex px-4 py-[6px] focus-within:bg-gray-100">
<div className="mr-2 flex h-6 w-6 items-center justify-center">
<Icon.FiLayers className="h-full w-full" />
</div>
<label
htmlFor="allBookings"
className="mr-auto self-center truncate text-sm font-medium text-gray-700">
{t("all_bookings_filter_label")}
</label>
<input
id="allBookings"
type="checkbox"
checked={!query.teamIds}
onChange={() => {
removeByKey("teamIds"); // Always clear on toggle or not toggle (seems weird but when you know the behviour it works well )
}}
className="text-primary-600 focus:ring-primary-500 inline-flex h-4 w-4 place-self-center justify-self-end rounded border-gray-300 "
/>
</div>
{data &&
data.map((team) => (
<div className="item-center flex px-4 py-[6px] focus-within:bg-gray-100" key={`${team.id}`}>
<Avatar
imageSrc={team.logo}
size="sm"
alt={`${team.name} Avatar`}
gravatarFallbackMd5="fallback"
className="self-center"
asChild
/>
<label
htmlFor={team.name}
className="ml-2 mr-auto self-center truncate text-sm font-medium text-gray-700">
{team.name}
</label>
<input
id={team.name}
name={team.name}
type="checkbox"
checked={query.teamIds?.includes(team.id)}
onChange={(e) => {
if (e.target.checked) {
pushItemToKey("teamIds", team.id);
} else if (!e.target.checked) {
removeItemByKeyAndValue("teamIds", team.id);
}
}}
className="text-primary-600 focus:ring-primary-500 inline-flex h-4 w-4 place-self-center justify-self-end rounded border-gray-300 "
/>
</div>
))}
</AnimatedPopover>
);
};
+18
View File
@@ -0,0 +1,18 @@
type KeySelector<T> = (item: T) => string;
export function groupBy<T>(array: Iterable<T>, keySelector: KeySelector<T>): Record<string, T[]> {
return Array.from(array).reduce(
(acc: Record<string, T[]>, item: T) => {
const key = keySelector(item);
if (key in acc) {
// found key, push new item into existing array
acc[key].push(item);
} else {
// did not find key, create new array
acc[key] = [item];
}
return acc;
},
{} // start with empty object
);
}
@@ -0,0 +1,47 @@
import React, { ComponentProps } from "react";
import { HorizontalTabs, Shell } from "@calcom/ui";
import { VerticalTabItemProps, HorizontalTabItemProps } from "@calcom/ui/v2";
import { FiltersContainer } from "../components/FiltersContainer";
const tabs: (VerticalTabItemProps | HorizontalTabItemProps)[] = [
{
name: "upcoming",
href: "/bookings/upcoming",
},
{
name: "unconfirmed",
href: "/bookings/unconfirmed",
},
{
name: "recurring",
href: "/bookings/recurring",
},
{
name: "past",
href: "/bookings/past",
},
{
name: "cancelled",
href: "/bookings/cancelled",
},
];
export default function BookingLayout({
children,
...rest
}: { children: React.ReactNode } & ComponentProps<typeof Shell>) {
return (
<Shell {...rest}>
<div className="flex max-w-6xl flex-col sm:space-x-2">
<div className="flex flex-col lg:flex-row">
<HorizontalTabs tabs={tabs} />
<FiltersContainer />
</div>
<main className="w-full max-w-6xl">{children}</main>
</div>
</Shell>
);
}
export const getLayout = (page: React.ReactElement) => <BookingLayout>{page}</BookingLayout>;
@@ -0,0 +1,15 @@
import z from "zod";
import { queryNumberArray, useTypedQuery } from "@calcom/lib/hooks/useTypedQuery";
// TODO: Move this to zod utils
export const filterQuerySchema = z.object({
teamIds: queryNumberArray.optional(),
userIds: queryNumberArray.optional(),
status: z.enum(["upcoming", "recurring", "past", "cancelled", "unconfirmed"]),
eventTypeIds: queryNumberArray.optional(),
});
export function useFilterQuery() {
return useTypedQuery(filterQuerySchema);
}