Skip to content

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

♻️ Move handler-driven state updates out of effects (#3511)

Luke Vella5e75791bbbb8
diff --git a/apps/web/public/locales/en/app.json b/apps/web/public/locales/en/app.json
index 99bbe3c8f..deb809efb 100644
--- a/apps/web/public/locales/en/app.json
+++ b/apps/web/public/locales/en/app.json
@@ -599,6 +599,7 @@
"minutesAbbreviation": "min",
"mixedDurations": "Mixed",
"mixedOptionsDescription": "You can't have both time and date options in the same poll. Which would you like to keep?",
+ "mixedOptionsError": "A poll can't have both date and time options. Remove one kind to continue.",
"mixedOptionsKeepDates": "Keep date options",
"mixedOptionsKeepTimes": "Keep time options",
"mixedOptionsTitle": "Wait a minute… 🤔",
diff --git a/apps/web/src/app/[locale]/setup/components/setup-form.tsx b/apps/web/src/app/[locale]/setup/components/setup-form.tsx
index e2e192a77..0f8664787 100644
--- a/apps/web/src/app/[locale]/setup/components/setup-form.tsx
+++ b/apps/web/src/app/[locale]/setup/components/setup-form.tsx
@@ -117,29 +117,16 @@ export function SetupForm({
timeFormat: defaultTimeFormat ?? getLocaleDefaults(locale).timeFormat,
spaceType: "personal" as const,
organizationName: "",
- industry: null,
+ industry: inferIndustry({ email, organizationName: "" }) ?? null,
jobTitle: null,
},
});
const spaceType = form.watch("spaceType");
- const organizationName = form.watch("organizationName");
// 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);
- const setIndustryValue = form.setValue;
-
- React.useEffect(() => {
- if (industryTouched.current) {
- return;
- }
-
- setIndustryValue(
- "industry",
- inferIndustry({ email, organizationName }) ?? null,
- );
- }, [email, organizationName, setIndustryValue]);
return (
<Form {...form}>
@@ -318,6 +305,18 @@ export function SetupForm({
<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",
diff --git a/apps/web/src/components/image-upload/image-crop-dialog.tsx b/apps/web/src/components/image-upload/image-crop-dialog.tsx
index 76739e30a..909381550 100644
--- a/apps/web/src/components/image-upload/image-crop-dialog.tsx
+++ b/apps/web/src/components/image-upload/image-crop-dialog.tsx
@@ -38,6 +38,39 @@ export function ImageCropDialog({
onClose,
onCropComplete,
}: ImageCropDialogProps) {
+ return (
+ <Dialog open={open} onOpenChange={onClose}>
+ <DialogContent className="w-fit">
+ <DialogHeader>
+ <DialogTitle>
+ <Trans i18nKey="imageCropDialogTitle" defaults="Crop image" />
+ </DialogTitle>
+ </DialogHeader>
+ {/* Keyed by the image's preview URL, so every image starts from a
+ fresh crop, even one picked while the last dialog animates out */}
+ <ImageCropper
+ key={imageSrc}
+ imageSrc={imageSrc}
+ originalFile={originalFile}
+ isUploading={isUploading}
+ onCropComplete={onCropComplete}
+ />
+ </DialogContent>
+ </Dialog>
+ );
+}
+
+function ImageCropper({
+ imageSrc,
+ originalFile,
+ isUploading,
+ onCropComplete,
+}: {
+ imageSrc: string | null;
+ originalFile: File | null;
+ isUploading: boolean;
+ onCropComplete: (croppedFile: File) => Promise<void>;
+}) {
const { t } = useTranslation();
const [crop, setCrop] = React.useState<Crop>();
const [completedCrop, setCompletedCrop] = React.useState<PercentCrop>();
@@ -79,62 +112,46 @@ export function ImageCropDialog({
}
};
- // Reset crop state when dialog opens/closes
- React.useEffect(() => {
- if (!open) {
- setCrop(undefined);
- setCompletedCrop(undefined);
- }
- }, [open]);
-
return (
- <Dialog open={open} onOpenChange={onClose}>
- <DialogContent className="w-fit">
- <DialogHeader>
- <DialogTitle>
- <Trans i18nKey="imageCropDialogTitle" defaults="Crop image" />
- </DialogTitle>
- </DialogHeader>
-
- {imageSrc && (
- <div className="flex justify-center">
- <ReactCrop
- crop={crop}
- onChange={(_, percentCrop) => setCrop(percentCrop)}
- onComplete={(_, percentCrop) => {
- setCompletedCrop(percentCrop);
- }}
- aspect={1}
- minWidth={100}
- minHeight={100}
- className="max-h-96"
- >
- {/* biome-ignore lint/performance/noImgElement: required for react-image-crop */}
- <img
- ref={imgRef}
- alt={t("cropPreview", {
- defaultValue: "Crop preview",
- })}
- src={imageSrc}
- onLoad={onImageLoad}
- className="max-h-96 max-w-full"
- />
- </ReactCrop>
- </div>
- )}
-
- <DialogFooter>
- <Button
- variant="primary"
- className="w-full"
- loading={isUploading}
- onClick={handleCropComplete}
- disabled={!completedCrop}
+ <>
+ {imageSrc && (
+ <div className="flex justify-center">
+ <ReactCrop
+ crop={crop}
+ onChange={(_, percentCrop) => setCrop(percentCrop)}
+ onComplete={(_, percentCrop) => {
+ setCompletedCrop(percentCrop);
+ }}
+ aspect={1}
+ minWidth={100}
+ minHeight={100}
+ className="max-h-96"
>
- <Trans i18nKey="uploadImage" defaults="Upload" />
- </Button>
- </DialogFooter>
- </DialogContent>
- </Dialog>
+ {/* biome-ignore lint/performance/noImgElement: required for react-image-crop */}
+ <img
+ ref={imgRef}
+ alt={t("cropPreview", {
+ defaultValue: "Crop preview",
+ })}
+ src={imageSrc}
+ onLoad={onImageLoad}
+ className="max-h-96 max-w-full"
+ />
+ </ReactCrop>
+ </div>
+ )}
+
+ <DialogFooter>
+ <Button
+ variant="primary"
+ className="w-full"
+ loading={isUploading}
+ onClick={handleCropComplete}
+ disabled={!completedCrop}
+ >
+ <Trans i18nKey="uploadImage" defaults="Upload" />
+ </Button>
+ </DialogFooter>
+ </>
);
}
diff --git a/apps/web/src/components/scroll-container.tsx b/apps/web/src/components/scroll-container.tsx
index 9cdd4a0f2..cc1ffb44a 100644
--- a/apps/web/src/components/scroll-container.tsx
+++ b/apps/web/src/components/scroll-container.tsx
@@ -4,8 +4,12 @@ import * as React from "react";
const useIsOverflowing = <E extends Element | null>(
ref: React.RefObject<E>,
+ onChange?: (isOverflowing: boolean) => void,
) => {
const [isOverflowing, setIsOverflowing] = React.useState(false);
+ const notifyChange = React.useEffectEvent((next: boolean) => {
+ onChange?.(next);
+ });
React.useEffect(() => {
// Defer the state update to the next frame so it lands outside the
@@ -14,6 +18,7 @@ const useIsOverflowing = <E extends Element | null>(
// "ResizeObserver loop completed with undelivered notifications." on
// window.onerror.
let frame = 0;
+ let last: boolean | undefined;
const checkOverflow = () => {
cancelAnimationFrame(frame);
frame = requestAnimationFrame(() => {
@@ -22,7 +27,12 @@ const useIsOverflowing = <E extends Element | null>(
const overflowX = element.scrollWidth > element.clientWidth;
const overflowY = element.scrollHeight > element.clientHeight;
- setIsOverflowing(overflowX || overflowY);
+ const next = overflowX || overflowY;
+ setIsOverflowing(next);
+ if (next !== last) {
+ last = next;
+ notifyChange(next);
+ }
}
});
};
@@ -67,13 +77,7 @@ export function ScrollContainer({
const [isDragging, setIsDragging] = React.useState(false);
const [isPointerDown, setIsPointerDown] = React.useState(false);
const animation = React.useRef<{ stop: () => void } | null>(null);
- const isOverflowing = useIsOverflowing(ref);
-
- React.useEffect(() => {
- if (onOverflowChange) {
- onOverflowChange(isOverflowing);
- }
- }, [isOverflowing, onOverflowChange]);
+ const isOverflowing = useIsOverflowing(ref, onOverflowChange);
return (
<div
diff --git a/apps/web/src/features/event-types/components/edit-event-type-dialog.tsx b/apps/web/src/features/event-types/components/edit-event-type-dialog.tsx
index 189ac8d54..9482538e7 100644
--- a/apps/web/src/features/event-types/components/edit-event-type-dialog.tsx
+++ b/apps/web/src/features/event-types/components/edit-event-type-dialog.tsx
@@ -32,15 +32,36 @@ export function EditEventTypeDialog({
onOpenChange,
}: DialogProps & {
eventType: EventTypeDTO;
+}) {
+ return (
+ <Dialog open={open} onOpenChange={onOpenChange}>
+ <DialogContent size="lg">
+ <DialogHeader>
+ <DialogTitle>
+ <Trans i18nKey="editEventTypeTitle" defaults="Edit event type" />
+ </DialogTitle>
+ </DialogHeader>
+ {/* Mounted per open, so each edit starts from the event type it was
+ opened for and a cancelled edit leaves nothing behind */}
+ <EditEventTypeForm
+ eventType={eventType}
+ onSaved={() => onOpenChange?.(false)}
+ />
+ </DialogContent>
+ </Dialog>
+ );
+}
+
+function EditEventTypeForm({
+ eventType,
+ onSaved,
+}: {
+ eventType: EventTypeDTO;
+ onSaved: () => void;
}) {
const { t } = useTranslation();
const updateEventType = trpc.eventTypes.update.useMutation();
- const initialValues = React.useMemo(
- () => eventTypeToFormValues(eventType),
- [eventType],
- );
-
const [showMaxAttendees, setShowMaxAttendees] = React.useState(
eventType.capacity !== null,
);
@@ -52,24 +73,9 @@ export function EditEventTypeDialog({
const form = useForm({
resolver: zodResolver(formSchema),
- defaultValues: initialValues,
+ defaultValues: eventTypeToFormValues(eventType),
});
- React.useEffect(() => {
- form.reset(initialValues);
- setShowMaxAttendees(eventType.capacity !== null);
- setShowDescription(eventType.description !== null);
- }, [eventType.capacity, eventType.description, form, initialValues]);
-
- const handleOpenChange = (nextOpen: boolean) => {
- if (!nextOpen) {
- form.reset(initialValues);
- setShowMaxAttendees(eventType.capacity !== null);
- setShowDescription(eventType.description !== null);
- }
- onOpenChange?.(nextOpen);
- };
-
const onSubmit = form.handleSubmit(async (values) => {
const input = eventTypeValuesToInput(values);
@@ -90,45 +96,36 @@ export function EditEventTypeDialog({
has_max_attendees: input.capacity !== null,
has_description: input.description !== null,
});
- handleOpenChange(false);
+ onSaved();
});
return (
- <Dialog open={open} onOpenChange={handleOpenChange}>
- <DialogContent size="lg">
- <DialogHeader>
- <DialogTitle>
- <Trans i18nKey="editEventTypeTitle" defaults="Edit event type" />
- </DialogTitle>
- </DialogHeader>
- <Form {...form}>
- <form onSubmit={onSubmit} className="space-y-5">
- <EventTypeFormFields
- form={form}
- showMaxAttendees={showMaxAttendees}
- setShowMaxAttendees={setShowMaxAttendees}
- showDescription={showDescription}
- setShowDescription={setShowDescription}
- />
- <DialogFooter>
- <DialogClose
- render={
- <Button type="button" disabled={updateEventType.isPending} />
- }
- >
- <Trans i18nKey="cancel" defaults="Cancel" />
- </DialogClose>
- <Button
- type="submit"
- variant="primary"
- loading={updateEventType.isPending}
- >
- <Trans i18nKey="save" defaults="Save" />
- </Button>
- </DialogFooter>
- </form>
- </Form>
- </DialogContent>
- </Dialog>
+ <Form {...form}>
+ <form onSubmit={onSubmit} className="space-y-5">
+ <EventTypeFormFields
+ form={form}
+ showMaxAttendees={showMaxAttendees}
+ setShowMaxAttendees={setShowMaxAttendees}
+ showDescription={showDescription}
+ setShowDescription={setShowDescription}
+ />
+ <DialogFooter>
+ <DialogClose
+ render={
+ <Button type="button" disabled={updateEventType.isPending} />
+ }
+ >
+ <Trans i18nKey="cancel" defaults="Cancel" />
+ </DialogClose>
+ <Button
+ type="submit"
+ variant="primary"
+ loading={updateEventType.isPending}
+ >
+ <Trans i18nKey="save" defaults="Save" />
+ </Button>
+ </DialogFooter>
+ </form>
+ </Form>
);
}
diff --git a/apps/web/src/features/poll/components/create-poll.tsx b/apps/web/src/features/poll/components/create-poll.tsx
index 9dddd9b3c..dc7612d00 100644
--- a/apps/web/src/features/poll/components/create-poll.tsx
+++ b/apps/web/src/features/poll/components/create-poll.tsx
@@ -22,6 +22,7 @@ import type { ConferencingOptions } from "@/features/conferencing/components/con
import { toPollConferencing } from "@/features/conferencing/components/conferencing-field";
import { PollDetailsForm } from "@/features/poll/components/forms/poll-details-form";
import PollOptionsForm from "@/features/poll/components/forms/poll-options-form/poll-options-form";
+import { isAllDay } from "@/features/poll/components/forms/poll-options-form/utils";
import { PollSettingsForm } from "@/features/poll/components/forms/poll-settings";
import type { NewEventData } from "@/features/poll/components/forms/types";
import { SelectedOptionsCount } from "@/features/poll/components/selected-options-count";
@@ -157,7 +158,6 @@ export const CreatePoll = ({
allowTentativeVotes: true,
duration: 60,
lockTimeZone: false,
- allDay: false,
},
});
@@ -241,7 +241,7 @@ export const CreatePoll = ({
// Fall back to the organizer's zone so a converting poll is always
// anchored to a concrete zone.
timeZone:
- !formData?.lockTimeZone && !formData?.allDay
+ !formData?.lockTimeZone && !isAllDay(formData?.options ?? [])
? formData?.timeZone || user?.timeZone || getBrowserTimeZone()
: null,
hideParticipants: formData?.hideParticipants,
diff --git a/apps/web/src/features/poll/components/edit-poll.tsx b/apps/web/src/features/poll/components/edit-poll.tsx
index cc439c8f5..5cb463e44 100644
--- a/apps/web/src/features/poll/components/edit-poll.tsx
+++ b/apps/web/src/features/poll/components/edit-poll.tsx
@@ -23,6 +23,7 @@ import {
import { useParticipants, usePoll } from "@/features/poll/client";
import { PollDetailsForm } from "@/features/poll/components/forms/poll-details-form";
import PollOptionsForm from "@/features/poll/components/forms/poll-options-form/poll-options-form";
+import { isAllDay } from "@/features/poll/components/forms/poll-options-form/utils";
import { PollSettingsForm } from "@/features/poll/components/forms/poll-settings";
import type {
NewEventData,
@@ -84,9 +85,6 @@ function getDefaultValues(poll: PollDetails): NewEventData {
// All-day polls are neutral (lock doesn't apply).
lockTimeZone:
!poll.timeZone && poll.options.some((option) => option.duration > 0),
- allDay:
- poll.options.length > 0 &&
- poll.options.every((option) => option.duration === 0),
duration: poll.options[0]?.duration || 60,
hideParticipants: poll.hideParticipants,
hideScores: poll.hideScores,
@@ -112,7 +110,7 @@ function getDateChanges({
// The submitted frame for the options: null when locked or all-day
// (floating), else the organizer's zone.
const timeZone =
- !data.lockTimeZone && !data.allDay
+ !data.lockTimeZone && !isAllDay(data.options)
? data.timeZone || fallbackTimeZone
: null;
diff --git a/apps/web/src/features/poll/components/forms/poll-options-form/poll-options-form.tsx b/apps/web/src/features/poll/components/forms/poll-options-form/poll-options-form.tsx
index 1e2326762..f2d735bea 100644
--- a/apps/web/src/features/poll/components/forms/poll-options-form/poll-options-form.tsx
+++ b/apps/web/src/features/poll/components/forms/poll-options-form/poll-options-form.tsx
@@ -24,6 +24,7 @@ import { Trans, useTranslation } from "@/i18n/client";
import { getBrowserTimeZone } from "@/lib/utils/date-time-utils";
import type { NewEventData } from "../types";
import MonthCalendar from "./month-calendar/month-calendar";
+import { hasMixedOptionTypes, isAllDay } from "./utils";
import WeekCalendar from "./week-calendar";
const PollOptionsForm = ({
@@ -66,26 +67,7 @@ const PollOptionsForm = ({
const dateOrTimeRangeDialog = useDialog();
- React.useEffect(() => {
- if (watchOptions.length > 1) {
- const optionType = watchOptions[0].type;
- // all options needs to be the same type
- if (watchOptions.some((option) => option.type !== optionType)) {
- dateOrTimeRangeDialog.trigger();
- }
- }
- }, [watchOptions, dateOrTimeRangeDialog]);
-
- // Keep the derived allDay flag in sync: a poll is all-day when every option
- // is a whole-day date rather than a time slot. Consumed at submit to decide
- // whether a time zone is attached.
- const allDay =
- watchOptions.length > 0 &&
- watchOptions.every((option) => option.type === "date");
-
- React.useEffect(() => {
- setValue("allDay", allDay);
- }, [allDay, setValue]);
+ const allDay = isAllDay(watchOptions);
const watchNavigationDate = watch("navigationDate");
const navigationDate = new Date(watchNavigationDate ?? Date.now());
@@ -185,12 +167,21 @@ const PollOptionsForm = ({
name="options"
rules={{
validate: (options) => {
- return options.length > 0
- ? true
- : t("calendarHelp", {
- defaultValue:
- "You can't create a poll without any options. Add at least one option to continue.",
- });
+ if (options.length === 0) {
+ return t("calendarHelp", {
+ defaultValue:
+ "You can't create a poll without any options. Add at least one option to continue.",
+ });
+ }
+ // A draft restored from storage can be mixed without passing
+ // through the calendar's onChange, which opens the dialog
+ if (hasMixedOptionTypes(options)) {
+ return t("mixedOptionsError", {
+ defaultValue:
+ "A poll can't have both date and time options. Remove one kind to continue.",
+ });
+ }
+ return true;
},
}}
render={({ field }) => (
@@ -203,6 +194,9 @@ const PollOptionsForm = ({
}}
onChange={(options) => {
field.onChange(options);
+ if (hasMixedOptionTypes(options)) {
+ dateOrTimeRangeDialog.trigger();
+ }
}}
duration={watchDuration}
onChangeDuration={(duration) => {
diff --git a/apps/web/src/features/poll/components/forms/poll-options-form/utils.ts b/apps/web/src/features/poll/components/forms/poll-options-form/utils.ts
index ec8789cba..42540dce5 100644
--- a/apps/web/src/features/poll/components/forms/poll-options-form/utils.ts
+++ b/apps/web/src/features/poll/components/forms/poll-options-form/utils.ts
@@ -1,6 +1,14 @@
import { dayjs } from "@/lib/dayjs";
import type { DateTimeOption } from "./types";
+/** A poll is all-day when every option is a whole-day date. */
+export const isAllDay = (options: DateTimeOption[]) =>
+ options.length > 0 && options.every((option) => option.type === "date");
+
+/** All options in a poll need to be the same type. */
+export const hasMixedOptionTypes = (options: DateTimeOption[]) =>
+ options.some((option) => option.type !== options[0]?.type);
+
export const formatDateWithoutTz = (date: Date): string => {
return dayjs(date).format("YYYY-MM-DDTHH:mm:ss");
};
diff --git a/apps/web/src/features/poll/components/forms/types.ts b/apps/web/src/features/poll/components/forms/types.ts
index 2157ef12f..186eb3082 100644
--- a/apps/web/src/features/poll/components/forms/types.ts
+++ b/apps/web/src/features/poll/components/forms/types.ts
@@ -16,7 +16,6 @@ export type PollOptionsData = {
duration: number; // duration of the event in minutes
timeZone: string;
lockTimeZone: boolean; // when true, everyone sees the same wall-clock time (no per-viewer conversion)
- allDay: boolean; // derived: options are whole-day dates rather than time slots
view: string;
options: DateTimeOption[];
};
diff --git a/apps/web/src/features/poll/components/invite-by-email.tsx b/apps/web/src/features/poll/components/invite-by-email.tsx
index daa352d02..cee92e4d2 100644
--- a/apps/web/src/features/poll/components/invite-by-email.tsx
+++ b/apps/web/src/features/poll/components/invite-by-email.tsx
@@ -87,14 +87,6 @@ export function InviteByEmail({
[invites],
);
- // An optimistic row lives until the refreshed server list carries it.
- React.useEffect(() => {
- setSending((prev) => {
- const next = prev.filter((address) => !invitedEmails.has(address));
- return next.length === prev.length ? prev : next;
- });
- }, [invitedEmails]);
-
const rows: Row[] = [
...sending
.filter((address) => !invitedEmails.has(address))
@@ -131,7 +123,7 @@ export function InviteByEmail({
const sendInvite = useMutation(
mutationOptions(sendPollInviteAction, {
- onSuccess: (data, input) => {
+ onSuccess: async (data, input) => {
if (data.ok) {
announce(
t("shareDialogInviteSent", {
@@ -139,6 +131,12 @@ export function InviteByEmail({
email: input.email,
}),
);
+ // The optimistic row lives until the refreshed server list carries
+ // it. Joins the refetch every successful write already starts.
+ await invitesQuery.refetch({ cancelRefetch: false });
+ setSending((prev) =>
+ prev.filter((address) => address !== input.email),
+ );
return;
}
setSending((prev) => prev.filter((address) => address !== input.email));
diff --git a/apps/web/src/features/poll/components/selected-options-count.tsx b/apps/web/src/features/poll/components/selected-options-count.tsx
index 8ede5d30e..7e4202114 100644
--- a/apps/web/src/features/poll/components/selected-options-count.tsx
+++ b/apps/web/src/features/poll/components/selected-options-count.tsx
@@ -1,16 +1,17 @@
"use client";
import { useFormContext } from "react-hook-form";
+import { isAllDay } from "@/features/poll/components/forms/poll-options-form/utils";
import type { PollOptionsData } from "@/features/poll/components/forms/types";
import { Trans } from "@/i18n/client";
/** How many dates or times the poll form currently has selected. */
export const SelectedOptionsCount = () => {
const form = useFormContext<PollOptionsData>();
- const optionCount = form.watch("options").length;
- const allDay = form.watch("allDay");
+ const options = form.watch("options");
+ const optionCount = options.length;
- if (allDay) {
+ if (isAllDay(options)) {
return (
<Trans
i18nKey="createPollFooterDatesSelected"
diff --git a/packages/ui/src/event-calendar/event-calendar-month-view.tsx b/packages/ui/src/event-calendar/event-calendar-month-view.tsx
index cee163daf..cbe7b0a49 100644
--- a/packages/ui/src/event-calendar/event-calendar-month-view.tsx
+++ b/packages/ui/src/event-calendar/event-calendar-month-view.tsx
@@ -1014,9 +1014,9 @@ function EventCalendarMoreIndicator({
const isDragging = useEventCalendarSelector<unknown, boolean>(
(state) => state.drag !== null,
);
- useEffect(() => {
- if (isDragging) setOpen(false);
- }, [isDragging]);
+ if (isDragging && open) {
+ setOpen(false);
+ }
return (
<Popover open={open} onOpenChange={setOpen}>