fix: virtualised member list for reassign (#17386)

* wip virtual list for reassignemnt

* order in alpha and prio order

* loading state

* add flex shrink so status symbol doesnt move

* add gap to each item to make hovering not feel squished

* a11y indexing tab group

* useInViewObserver hook and move to lib

* use correct intersection target

* fix type errors

* remove type
This commit is contained in:
sean-brydon authored and GitHub committed 2024-10-29 17:47:43 +00:00
1 parent 1a55f2d8e2
commit 55671db5fd
9 files changed
+226 -123

No files matched your search

@@ -12,13 +12,12 @@ import { Builder, Query, Utils as QbUtils } from "react-awesome-query-builder";
import Shell from "@calcom/features/shell/Shell";
import { classNames } from "@calcom/lib";
import { useInViewObserver } from "@calcom/lib/hooks/useInViewObserver";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { trpc } from "@calcom/trpc/react";
import type { inferSSRProps } from "@calcom/types/inferSSRProps";
import { Button } from "@calcom/ui";
import { useInViewObserver } from "@lib/hooks/useInViewObserver";
import SingleForm, {
getServerSidePropsForSingleFormView as getServerSideProps,
} from "../../components/SingleForm";
@@ -67,7 +66,7 @@ const Result = ({ formId, jsonLogicQuery }: { formId: string; jsonLogicQuery: Js
<div className="w-full max-w-[2000px] overflow-x-scroll">
{!isPending && (
<div className="text-default text-md mx-4 mb-2">
{`${numberOfRows} ` + (numberOfRows === 1 ? t("row") : t("rows"))}
{`${numberOfRows} ${numberOfRows === 1 ? t("row") : t("rows")}`}
</div>
)}
<table
@@ -189,4 +189,5 @@ export function SelectWithValidation<
</div>
);
}
export default Select;
+43
View File
@@ -0,0 +1,43 @@
import React from "react";
const isInteractionObserverSupported = typeof window !== "undefined" && "IntersectionObserver" in window;
export const useInViewObserver = (onInViewCallback: () => void, root?: Element | Document | null) => {
const [node, setRef] = React.useState<HTMLElement | null>(null);
const onInViewCallbackRef = React.useRef(onInViewCallback);
onInViewCallbackRef.current = onInViewCallback;
React.useEffect(() => {
if (!isInteractionObserverSupported) {
// Skip interaction check if not supported in browser
return;
}
let observer: IntersectionObserver;
if (node && node.parentElement) {
observer = new IntersectionObserver(
([entry]) => {
if (entry.isIntersecting) {
onInViewCallbackRef.current();
}
},
{
// We want to accept null as root
root: root !== undefined ? root : document.body,
}
);
observer.observe(node);
}
return () => {
if (observer) {
observer.disconnect();
}
};
}, [node]);
return {
ref: setRef,
};
};
@@ -23,7 +23,7 @@ import { ZPublishInputSchema } from "./publish.schema";
import { ZRemoveHostsFromEventTypes } from "./removeHostsFromEventTypes.schema";
import { ZRemoveMemberInputSchema } from "./removeMember.schema";
import { ZResendInvitationInputSchema } from "./resendInvitation.schema";
import { ZGetRoundRobinHostsToReassignInputSchema } from "./roundRobin/getRoundRobinHostsToReasign.schema";
import { ZGetRoundRobinHostsInputSchema } from "./roundRobin/getRoundRobinHostsToReasign.schema";
import { ZRoundRobinManualReassignInputSchema } from "./roundRobin/roundRobinManualReassign.schema";
import { ZRoundRobinReassignInputSchema } from "./roundRobin/roundRobinReassign.schema";
import { ZSetInviteExpirationInputSchema } from "./setInviteExpiration.schema";
@@ -192,15 +192,13 @@ export const viewerTeamsRouter = router({
);
return handler(opts);
}),
getRoundRobinHostsToReassign: authedProcedure
.input(ZGetRoundRobinHostsToReassignInputSchema)
.query(async (opts) => {
const handler = await importHandler(
namespaced("getRoundRobinHostsToReassign"),
() => import("./roundRobin/getRoundRobinHostsToReasign.handler")
);
return handler(opts);
}),
getRoundRobinHostsToReassign: authedProcedure.input(ZGetRoundRobinHostsInputSchema).query(async (opts) => {
const handler = await importHandler(
namespaced("getRoundRobinHostsToReassign"),
() => import("./roundRobin/getRoundRobinHostsToReasign.handler")
);
return handler(opts);
}),
checkIfMembershipExists: authedProcedure
.input(ZCheckIfMembershipExistsInputSchema)
.mutation(async (opts) => {
@@ -1,10 +1,11 @@
import dayjs from "@calcom/dayjs";
import { ensureAvailableUsers } from "@calcom/features/bookings/lib/handleNewBooking/ensureAvailableUsers";
import { getEventTypesFromDB } from "@calcom/features/bookings/lib/handleNewBooking/getEventTypesFromDB";
import type { IsFixedAwareUser } from "@calcom/features/bookings/lib/handleNewBooking/types";
import { ErrorCode } from "@calcom/lib/errorCodes";
import logger from "@calcom/lib/logger";
import type { PrismaClient } from "@calcom/prisma";
import { userSelect } from "@calcom/prisma";
import { credentialForCalendarServiceSelect } from "@calcom/prisma/selects/credential";
import type { TrpcSessionUser } from "@calcom/trpc/server/trpc";
import type { TGetRoundRobinHostsToReassignInputSchema } from "./getRoundRobinHostsToReasign.schema";
@@ -17,65 +18,122 @@ type GetRoundRobinHostsToReassignOptions = {
input: TGetRoundRobinHostsToReassignInputSchema;
};
async function getTeamHostsFromDB({
eventTypeId,
prisma,
searchTerm,
cursor,
limit = 20,
excludeUserId,
}: {
eventTypeId: number;
prisma: PrismaClient;
searchTerm?: string;
cursor?: number;
limit?: number;
excludeUserId?: number;
}) {
const queryWhere = {
eventTypeId,
isFixed: false,
...(excludeUserId && { userId: { not: excludeUserId } }),
...(searchTerm && {
user: {
OR: [
{ name: { contains: searchTerm, mode: "insensitive" as const } },
{ email: { contains: searchTerm, mode: "insensitive" as const } },
],
},
}),
};
const [totalCount, hosts] = await Promise.all([
prisma.host.count({ where: queryWhere }),
prisma.host.findMany({
where: queryWhere,
select: {
isFixed: true,
priority: true,
user: {
select: {
...userSelect.select,
credentials: {
select: credentialForCalendarServiceSelect,
},
},
},
},
take: limit + 1, // Take one more to determine if there's a next page
...(cursor && { skip: 1, cursor: { userId_eventTypeId: { userId: cursor, eventTypeId } } }),
orderBy: [{ user: { name: "asc" } }, { priority: "desc" }],
}),
]);
const hasNextPage = hosts.length > limit;
const hosts_subset = hasNextPage ? hosts.slice(0, -1) : hosts;
return {
hosts: hosts_subset.map((host) => ({
...host.user,
isFixed: host.isFixed,
priority: host.priority ?? 2,
})),
totalCount,
hasNextPage,
nextCursor: hasNextPage ? hosts_subset[hosts_subset.length - 1].user.id : null,
};
}
async function getEventTypeFromDB(eventTypeId: number, prisma: PrismaClient) {
return prisma.eventType.findUniqueOrThrow({
where: { id: eventTypeId },
});
}
export const getRoundRobinHostsToReassign = async ({ ctx, input }: GetRoundRobinHostsToReassignOptions) => {
const { prisma } = ctx;
const { bookingId, limit, cursor, searchTerm } = input;
const gettingRoundRobinHostsToReassignLogger = logger.getSubLogger({
prefix: ["gettingRoundRobinHostsToReassign", `${input.bookingId}`],
prefix: ["gettingRoundRobinHostsToReassign", `${bookingId}`],
});
const booking = await prisma.booking.findUniqueOrThrow({
where: { id: input.bookingId },
where: { id: bookingId },
select: {
userId: true,
startTime: true,
endTime: true,
eventType: {
select: {
id: true,
timeZone: true,
teamId: true,
},
},
eventTypeId: true,
},
});
if (!booking?.eventType) {
throw new Error("Booking not found");
if (!booking.eventTypeId) {
throw new Error("Booking requires a event type to reassign hosts");
}
// Get event type
const eventType = await getEventTypesFromDB(booking.eventType.id);
if (!eventType) {
throw new Error("Event type not found");
}
if (!eventType.teamId) {
gettingRoundRobinHostsToReassignLogger.warn("Booking with event type that has no teamId", {
bookingId: input.bookingId,
eventTypeId: eventType.id,
teamId: eventType.teamId ?? -1,
});
return [];
}
const availableEventTypeUsers = eventType.hosts
.filter((h) => !h.isFixed && h.user.id !== booking.userId)
.map((host) => ({
...host.user,
isFixed: host.isFixed,
priority: host?.priority ?? 2,
}));
const { hosts, totalCount, nextCursor } = await getTeamHostsFromDB({
eventTypeId: booking.eventTypeId,
prisma,
searchTerm,
cursor,
limit,
excludeUserId: booking.userId ?? undefined,
});
let availableUsers: IsFixedAwareUser[] = [];
try {
const eventType = await getEventTypeFromDB(booking.eventTypeId, prisma);
availableUsers = await ensureAvailableUsers(
{ ...eventType, users: availableEventTypeUsers as IsFixedAwareUser[] },
// @ts-expect-error - TODO: We need to make sure nothing in the app needs the return type of getEventTypeFromDB as it fetches everything under the sun
{
users: hosts as IsFixedAwareUser[],
...eventType,
},
{
dateFrom: dayjs(booking.startTime).format(),
dateTo: dayjs(booking.endTime).format(),
timeZone: eventType.timeZone || "UTC",
timeZone: "UTC",
},
gettingRoundRobinHostsToReassignLogger
);
@@ -84,25 +142,23 @@ export const getRoundRobinHostsToReassign = async ({ ctx, input }: GetRoundRobin
availableUsers = [];
} else {
gettingRoundRobinHostsToReassignLogger.error(error);
// Log error and return empty array to avoid rethrowing the error
return [];
}
}
const availableUserIds = new Set(availableUsers.map((u) => u.id));
const roundRobinHostsToReassign = availableEventTypeUsers.reduce((acc, host) => {
const status = availableUserIds.has(host.id) ? "available" : "unavailable";
acc.push({
id: host.id,
name: host.name,
email: host.email,
status,
});
return acc;
}, [] as { id: number; name: string | null; email: string; status: string }[]);
const items = hosts.map((host) => ({
id: host.id,
name: host.name,
email: host.email,
status: availableUserIds.has(host.id) ? "available" : "unavailable",
}));
return roundRobinHostsToReassign;
return {
items,
nextCursor,
totalCount,
};
};
export default getRoundRobinHostsToReassign;
@@ -1,10 +1,12 @@
import { z } from "zod";
export const ZGetRoundRobinHostsToReassignInputSchema = z.object({
// New schema for fetching hosts
export const ZGetRoundRobinHostsInputSchema = z.object({
bookingId: z.number(),
exclude: z.enum(["fixedHosts"]).optional(),
exclude: z.literal("fixedHosts"),
cursor: z.number().optional(), // For pagination
limit: z.number().min(1).max(100).optional(),
searchTerm: z.string().optional(),
});
export type TGetRoundRobinHostsToReassignInputSchema = z.infer<
typeof ZGetRoundRobinHostsToReassignInputSchema
>;
export type TGetRoundRobinHostsToReassignInputSchema = z.infer<typeof ZGetRoundRobinHostsInputSchema>;