Skip to content

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

♻️ Migrate poll options form display strings to Intl (#2522)

Luke Vella8ebfcffbf2c8
diff --git a/apps/web/src/app/[locale]/(optional-space)/layout.tsx b/apps/web/src/app/[locale]/(optional-space)/layout.tsx
index 3f0964e27..53c4dc898 100644
--- a/apps/web/src/app/[locale]/(optional-space)/layout.tsx
+++ b/apps/web/src/app/[locale]/(optional-space)/layout.tsx
@@ -36,6 +36,7 @@ export default async function Layout({
timeFormat={
deviceDateTimeConfig.timeFormat ?? user?.timeFormat ?? undefined
}
+ weekStart={user?.weekStart ?? undefined}
>
{children}
<PayWall />
diff --git a/apps/web/src/app/[locale]/(space)/layout.tsx b/apps/web/src/app/[locale]/(space)/layout.tsx
index 4b4f6d05a..5f845bade 100644
--- a/apps/web/src/app/[locale]/(space)/layout.tsx
+++ b/apps/web/src/app/[locale]/(space)/layout.tsx
@@ -34,7 +34,11 @@ export default async function Layout({
<SessionRefresher />
<LocaleSync userLocale={user?.locale} />
<TimeZoneMismatchDialog homeTimeZone={user?.timeZone} />
- <DateTimeProvider timeZone={user?.timeZone} timeFormat={user?.timeFormat}>
+ <DateTimeProvider
+ timeZone={user?.timeZone}
+ timeFormat={user?.timeFormat}
+ weekStart={user?.weekStart ?? undefined}
+ >
<SpaceProvider>
{children}
<PayWall />
diff --git a/apps/web/src/app/[locale]/(space)/settings/event-types/event-types-settings-page.tsx b/apps/web/src/app/[locale]/(space)/settings/event-types/event-types-settings-page.tsx
index c86847bcf..ff0995010 100644
--- a/apps/web/src/app/[locale]/(space)/settings/event-types/event-types-settings-page.tsx
+++ b/apps/web/src/app/[locale]/(space)/settings/event-types/event-types-settings-page.tsx
@@ -44,10 +44,10 @@ import { DeleteEventTypeDialog } from "@/features/event-types/components/delete-
import { EditEventTypeDialog } from "@/features/event-types/components/edit-event-type-dialog";
import type { EventTypeDTO } from "@/features/event-types/types";
import { Trans } from "@/i18n/client";
+import { formatDuration } from "@/lib/datetime/format";
import { useLocale } from "@/lib/locale/client";
import type { LocationType } from "@/lib/location";
import { trpc } from "@/trpc/client";
-import { formatDuration } from "@/utils/date-time-utils";
function EventTypesEmptyState({ onCreate }: { onCreate: () => void }) {
return (
diff --git a/apps/web/src/components/forms/poll-options-form/month-calendar/month-calendar.tsx b/apps/web/src/components/forms/poll-options-form/month-calendar/month-calendar.tsx
index aae19dbe2..3975b4ab5 100644
--- a/apps/web/src/components/forms/poll-options-form/month-calendar/month-calendar.tsx
+++ b/apps/web/src/components/forms/poll-options-form/month-calendar/month-calendar.tsx
@@ -28,12 +28,12 @@ import {
} from "@/components/empty-state";
import type { NewEventData } from "@/components/forms";
import { Trans, useTranslation } from "@/i18n/client";
+import { useDateTime, useDateTimeConfig } from "@/lib/datetime/client";
+import { formatDateParts } from "@/lib/datetime/format";
import { dayjs } from "@/lib/dayjs";
import {
expectTimeOption,
- formatDuration,
getBrowserTimeZone,
- getDateProps,
removeAllOptionsForDay,
} from "../../../../utils/date-time-utils";
import DateCard from "../../../date-card";
@@ -52,6 +52,8 @@ const MonthCalendar: React.FunctionComponent<DateTimePickerProps> = ({
onChangeDuration,
}) => {
const { t } = useTranslation();
+ const { locale } = useDateTimeConfig();
+ const { formatDuration } = useDateTime();
// Time-based options are the default. With no options yet the selected
// duration drives the mode (0 = all-day) so the first selection creates the
// right kind of option; once options exist their type is the source of truth.
@@ -355,14 +357,16 @@ const MonthCalendar: React.FunctionComponent<DateTimePickerProps> = ({
.sort((a, b) => (a > b ? 1 : -1))
.map((dateString) => {
const optionsForDay = optionsByDay[dateString];
+ const dateParts = formatDateParts(
+ new Date(`${dateString}T12:00:00`),
+ { locale },
+ );
return (
<div
key={dateString}
className="space-y-3 p-3 sm:flex sm:items-start sm:space-x-4 sm:space-y-0 sm:p-4"
>
- <DateCard
- {...getDateProps(new Date(`${dateString}T12:00:00`))}
- />
+ <DateCard day={dateParts.day} month={dateParts.month} />
<div className="grow space-y-3">
{optionsForDay.map(({ option, index }) => {
if (option.type === "date") {
@@ -555,11 +559,15 @@ const MonthCalendar: React.FunctionComponent<DateTimePickerProps> = ({
{datepicker.selection
.sort((a, b) => a.getTime() - b.getTime())
.map((selectedDate, i) => {
+ const dateParts = formatDateParts(selectedDate, {
+ locale,
+ });
return (
<DateCard
// biome-ignore lint/suspicious/noArrayIndexKey: Fix this later
key={i}
- {...getDateProps(selectedDate)}
+ day={dateParts.day}
+ month={dateParts.month}
// annotation={
// <CompactButton
// icon={XIcon}
diff --git a/apps/web/src/components/forms/poll-options-form/month-calendar/time-picker.tsx b/apps/web/src/components/forms/poll-options-form/month-calendar/time-picker.tsx
index de4565c4e..64370d7e3 100644
--- a/apps/web/src/components/forms/poll-options-form/month-calendar/time-picker.tsx
+++ b/apps/web/src/components/forms/poll-options-form/month-calendar/time-picker.tsx
@@ -7,8 +7,9 @@ import {
} from "@rallly/ui/select";
import * as React from "react";
+import { useDateTime, useDateTimeConfig } from "@/lib/datetime/client";
+import { formatDateTime } from "@/lib/datetime/format";
import { dayjs } from "@/lib/dayjs";
-import { getDuration } from "@/utils/date-time-utils";
export interface TimePickerProps {
value?: Date;
@@ -23,7 +24,14 @@ const TimePicker: React.FunctionComponent<TimePickerProps> = ({
className,
after,
}) => {
+ const { locale, timeFormat } = useDateTimeConfig();
+ const { formatDuration } = useDateTime();
const [open, setOpen] = React.useState(false);
+
+ // The form works in naive local times, so options format in the system zone.
+ const formatTime = (time: string | Date) =>
+ formatDateTime(time, { preset: "time", locale, timeFormat });
+
const getOptions = React.useCallback(() => {
if (!open) {
return [dayjs(value).toISOString()];
@@ -70,10 +78,10 @@ const TimePicker: React.FunctionComponent<TimePickerProps> = ({
return (
<SelectItem key={option} value={dayjs(option).toISOString()}>
<div className="flex items-center gap-2">
- <span>{dayjs(option).format("LT")}</span>
+ <span>{formatTime(option)}</span>
{after ? (
<span className="text-muted-foreground text-sm">
- {getDuration(dayjs(after), dayjs(option))}
+ {formatDuration(dayjs(option).diff(after, "minute"))}
</span>
) : null}
</div>
@@ -83,10 +91,10 @@ const TimePicker: React.FunctionComponent<TimePickerProps> = ({
) : (
<SelectItem value={dayjs(value).toISOString()}>
<div className="flex items-center gap-2">
- <span>{dayjs(value).format("LT")}</span>
+ <span>{formatTime(dayjs(value).toDate())}</span>
{after ? (
<span className="text-muted-foreground text-sm">
- {getDuration(dayjs(after), dayjs(value))}
+ {formatDuration(dayjs(value).diff(after, "minute"))}
</span>
) : null}
</div>
diff --git a/apps/web/src/components/forms/poll-options-form/week-calendar.tsx b/apps/web/src/components/forms/poll-options-form/week-calendar.tsx
index 874aace5a..7bdfeedb2 100644
--- a/apps/web/src/components/forms/poll-options-form/week-calendar.tsx
+++ b/apps/web/src/components/forms/poll-options-form/week-calendar.tsx
@@ -6,9 +6,10 @@ import type React from "react";
import type { CalendarProps } from "react-big-calendar";
import { Calendar } from "react-big-calendar";
import { createBreakpoint } from "react-use";
+import { useDateTime, useDateTimeConfig } from "@/lib/datetime/client";
+import { formatDateParts, formatDateTime } from "@/lib/datetime/format";
import { dayjs } from "@/lib/dayjs";
-import { getDuration } from "../../../utils/date-time-utils";
import DateNavigationToolbar from "./date-navigation-toolbar";
import dayjsLocalizer from "./dayjs-localizer";
import type { DateTimeOption, DateTimePickerProps } from "./types";
@@ -32,6 +33,8 @@ const WeekCalendar: React.FunctionComponent<DateTimePickerProps> = ({
duration = 60,
onChangeDuration,
}) => {
+ const { locale, timeFormat } = useDateTimeConfig();
+ const { formatDuration } = useDateTime();
const scrollToTime =
options.length > 0
? options[0].type === "timeSlot"
@@ -97,6 +100,9 @@ const WeekCalendar: React.FunctionComponent<DateTimePickerProps> = ({
eventWrapper: function EventWraper(props) {
const start = dayjs(props.event.start);
const end = dayjs(props.event.end);
+ // The form works in naive local times; format in the system zone.
+ const formatTime = (time: Date) =>
+ formatDateTime(time, { preset: "time", locale, timeFormat });
return (
// biome-ignore lint/a11y/noStaticElementInteractions: fix later
<div
@@ -114,11 +120,15 @@ const WeekCalendar: React.FunctionComponent<DateTimePickerProps> = ({
<XIcon className="size-3" />
</div>
<div>
- <div className="font-semibold">{start.format("LT")}</div>
- <div className="opacity-50">{getDuration(start, end)}</div>
+ <div className="font-semibold">
+ {formatTime(start.toDate())}
+ </div>
+ <div className="opacity-50">
+ {formatDuration(end.diff(start, "minute"))}
+ </div>
</div>
<div>
- <div className="opacity-50">{end.format("LT")}</div>
+ <div className="opacity-50">{formatTime(end.toDate())}</div>
</div>
</div>
);
@@ -126,14 +136,11 @@ const WeekCalendar: React.FunctionComponent<DateTimePickerProps> = ({
week: {
// biome-ignore lint/suspicious/noExplicitAny: Fix this later
header: function Header({ date }: any) {
+ const parts = formatDateParts(date, { locale });
return (
<span className="w-full rounded-md text-center text-xs tracking-tight">
- <span className="mr-1.5 font-normal">
- {dayjs(date).format("ddd")}
- </span>
- <span className="font-medium">
- {dayjs(date).format("DD")}
- </span>
+ <span className="mr-1.5 font-normal">{parts.weekday}</span>
+ <span className="font-medium">{parts.day}</span>
</span>
);
},
diff --git a/apps/web/src/components/headless-date-picker.tsx b/apps/web/src/components/headless-date-picker.tsx
index 48e4d1daa..37f673b04 100644
--- a/apps/web/src/components/headless-date-picker.tsx
+++ b/apps/web/src/components/headless-date-picker.tsx
@@ -1,5 +1,7 @@
import React from "react";
+import { useDateTimeConfig } from "@/lib/datetime/client";
+import { formatDateParts, formatDateTime } from "@/lib/datetime/format";
import { dayjs } from "@/lib/dayjs";
interface DayProps {
@@ -34,13 +36,19 @@ export const useHeadlessDatePicker = (
selection: Date[];
toggle: (date: Date) => void;
} => {
+ const { locale, weekStart } = useDateTimeConfig();
const [localSelection, setSelection] = React.useState<Date[]>([]);
const selection = options?.selection ?? localSelection;
const [localNavigationDate, setNavigationDate] = React.useState(today);
const navigationDate = dayjs(options?.date ?? localNavigationDate);
const firstDayOfMonth = navigationDate.startOf("month");
- const firstDayOfFirstWeek = firstDayOfMonth.startOf("week");
+ // dayjs's startOf("week") depends on the global locale; shift explicitly so
+ // the grid follows the viewer's week start.
+ const firstDayOfFirstWeek = firstDayOfMonth.subtract(
+ (firstDayOfMonth.day() - weekStart + 7) % 7,
+ "days",
+ );
const currentMonth = navigationDate.get("month");
@@ -49,7 +57,10 @@ export const useHeadlessDatePicker = (
const daysOfWeek: string[] = [];
for (let i = 0; i < 7; i++) {
- daysOfWeek.push(firstDayOfFirstWeek.add(i, "days").format("dd"));
+ daysOfWeek.push(
+ formatDateParts(firstDayOfFirstWeek.add(i, "days").toDate(), { locale })
+ .weekday,
+ );
}
let reachedEnd = false;
@@ -58,7 +69,7 @@ export const useHeadlessDatePicker = (
const d = firstDayOfFirstWeek.add(i, "days");
days.push({
date: d.toDate(),
- day: d.format("D"),
+ day: formatDateParts(d.toDate(), { locale }).day,
weekend: d.day() === 0 || d.day() === 6,
outOfMonth: d.month() !== currentMonth,
today: d.isSame(today, "day"),
@@ -72,7 +83,10 @@ export const useHeadlessDatePicker = (
return {
navigationDate: navigationDate.toDate(),
- label: navigationDate.format("MMMM YYYY"),
+ label: formatDateTime(navigationDate.toDate(), {
+ preset: "monthYear",
+ locale,
+ }),
next: () => {
const newDate = navigationDate.add(1, "month").startOf("month").toDate();
if (!options?.date) {
diff --git a/apps/web/src/components/poll-context.tsx b/apps/web/src/components/poll-context.tsx
index 942e138d6..a038b7a9b 100644
--- a/apps/web/src/components/poll-context.tsx
+++ b/apps/web/src/components/poll-context.tsx
@@ -3,13 +3,16 @@ import { TrashIcon } from "lucide-react";
import React from "react";
import { useTranslation } from "@/i18n/client";
import { useDateTimeConfig } from "@/lib/datetime/client";
-import { formatDateParts, formatDateTime } from "@/lib/datetime/format";
+import {
+ formatDateParts,
+ formatDateTime,
+ formatDuration,
+} from "@/lib/datetime/format";
import type { GetPollApiResponse } from "@/trpc/client/types";
import type {
ParsedDateOption,
ParsedTimeSlotOption,
} from "@/utils/date-time-utils";
-import { formatDuration } from "@/utils/date-time-utils";
import { useParticipants } from "./participants-provider";
import { useRequiredContext } from "./use-required-context";
diff --git a/apps/web/src/lib/datetime/client.tsx b/apps/web/src/lib/datetime/client.tsx
index 67377d10a..0c2854272 100644
--- a/apps/web/src/lib/datetime/client.tsx
+++ b/apps/web/src/lib/datetime/client.tsx
@@ -7,9 +7,10 @@ import React from "react";
import type { DateInput, DateTimePreset } from "@/lib/datetime/format";
import {
formatDateTime as baseFormatDateTime,
+ formatDuration as baseFormatDuration,
formatRelativeTime,
} from "@/lib/datetime/format";
-import { getWeekdayNames } from "@/lib/datetime/locales";
+import { getLocaleDefaults, getWeekdayNames } from "@/lib/datetime/locales";
import { normalizeTimeZone } from "@/lib/datetime/utils";
import { getBrowserTimeZone } from "@/utils/date-time-utils";
@@ -17,6 +18,7 @@ type DateTimeConfig = {
locale?: string;
timeZone?: string;
timeFormat?: TimeFormat;
+ weekStart?: number;
};
const DateTimeContext = React.createContext<DateTimeConfig | undefined>(
@@ -31,6 +33,7 @@ export function DateTimeProvider({
locale,
timeZone,
timeFormat,
+ weekStart,
children,
}: DateTimeConfig & { children: React.ReactNode }) {
const parent = React.useContext(DateTimeContext);
@@ -48,8 +51,9 @@ export function DateTimeProvider({
timeZone:
normalizeTimeZone(timeZone) ?? parent?.timeZone ?? browserTimeZone,
timeFormat: timeFormat ?? parent?.timeFormat,
+ weekStart: weekStart ?? parent?.weekStart,
}),
- [locale, timeZone, timeFormat, parent, browserTimeZone],
+ [locale, timeZone, timeFormat, weekStart, parent, browserTimeZone],
);
return (
@@ -62,11 +66,13 @@ export function DateTimeProvider({
export function useDateTimeConfig() {
const config = React.useContext(DateTimeContext);
const params = useParams<{ locale?: string }>();
+ const locale = config?.locale ?? params?.locale ?? defaultLocale;
return {
- locale: config?.locale ?? params?.locale ?? defaultLocale,
+ locale,
timeZone: config?.timeZone,
timeFormat: config?.timeFormat,
+ weekStart: config?.weekStart ?? getLocaleDefaults(locale).weekStart,
};
}
@@ -91,6 +97,7 @@ export function useDateTime() {
showTimeZone: opts?.showTimeZone,
}),
toRelativeTime: (value: DateInput) => formatRelativeTime(value, locale),
+ formatDuration: (minutes: number) => baseFormatDuration(minutes, locale),
weekdays: () => getWeekdayNames(locale),
}),
[locale, timeZone, timeFormat],
diff --git a/apps/web/src/lib/datetime/device.tsx b/apps/web/src/lib/datetime/device.tsx
index 18ce5a3cc..383124390 100644
--- a/apps/web/src/lib/datetime/device.tsx
+++ b/apps/web/src/lib/datetime/device.tsx
@@ -53,10 +53,12 @@ const DeviceDateTimeContext = React.createContext<DeviceDateTime | null>(null);
export function DeviceDateTimeProvider({
timeZone: initialTimeZone,
timeFormat: initialTimeFormat,
+ weekStart,
children,
}: {
timeZone?: string;
timeFormat?: TimeFormat;
+ weekStart?: number;
children: React.ReactNode;
}) {
const [timeZone, setTimeZoneState] = React.useState(initialTimeZone);
@@ -78,7 +80,11 @@ export function DeviceDateTimeProvider({
return (
<DeviceDateTimeContext.Provider value={value}>
- <DateTimeProvider timeZone={timeZone} timeFormat={timeFormat}>
+ <DateTimeProvider
+ timeZone={timeZone}
+ timeFormat={timeFormat}
+ weekStart={weekStart}
+ >
{children}
</DateTimeProvider>
</DeviceDateTimeContext.Provider>
diff --git a/apps/web/src/lib/datetime/format.ts b/apps/web/src/lib/datetime/format.ts
index 9ac1fb974..48dbf4b94 100644
--- a/apps/web/src/lib/datetime/format.ts
+++ b/apps/web/src/lib/datetime/format.ts
@@ -2,7 +2,12 @@ import type { TimeFormat } from "@rallly/database";
export type DateInput = Date | string | number;
-export type DatePreset = "date" | "dateLong" | "dateFull" | "weekday";
+export type DatePreset =
+ | "date"
+ | "dateLong"
+ | "dateFull"
+ | "weekday"
+ | "monthYear";
export type DateTimePreset = DatePreset | "time" | "datetime";
@@ -76,6 +81,8 @@ function presetOptions(
};
case "weekday":
return { weekday: "long" };
+ case "monthYear":
+ return { month: "long", year: "numeric" };
case "datetime":
return {
year: "numeric",
@@ -159,6 +166,35 @@ export function formatDateParts(
return parts;
}
+type DurationFormatCtor = new (
+ locale: string | undefined,
+ options: { style: "narrow" },
+) => { format(duration: { hours?: number; minutes?: number }): string };
+
+const durationFormatters = new Map<string, InstanceType<DurationFormatCtor>>();
+
+export function formatDuration(minutes: number, locale: string): string {
+ const hours = Math.floor(minutes / 60);
+ const mins = minutes % 60;
+ const DurationFormat = (Intl as { DurationFormat?: DurationFormatCtor })
+ .DurationFormat;
+ if (DurationFormat) {
+ let formatter = durationFormatters.get(locale);
+ if (!formatter) {
+ formatter = new DurationFormat(locale, { style: "narrow" });
+ durationFormatters.set(locale, formatter);
+ }
+ return formatter.format({ hours, minutes: mins });
+ }
+ if (hours && mins) {
+ return `${hours}h ${mins}m`;
+ }
+ if (hours) {
+ return `${hours}h`;
+ }
+ return `${mins}m`;
+}
+
const relativeFormatters = new Map<string, Intl.RelativeTimeFormat>();
// Largest-first; each entry is how many of the unit make up the next one.
diff --git a/apps/web/src/utils/date-time-utils.ts b/apps/web/src/utils/date-time-utils.ts
index 348b4117f..ba1d8b0d6 100644
--- a/apps/web/src/utils/date-time-utils.ts
+++ b/apps/web/src/utils/date-time-utils.ts
@@ -38,35 +38,6 @@ export interface ParsedTimeSlotOption {
export type ParsedDateTimeOpton = ParsedDateOption | ParsedTimeSlotOption;
-type DurationFormatCtor = new (
- locale: string | undefined,
- options: { style: "narrow" },
-) => { format(duration: { hours?: number; minutes?: number }): string };
-
-export const formatDuration = (minutes: number, locale?: string) => {
- const hours = Math.floor(minutes / 60);
- const mins = minutes % 60;
- const DurationFormat = (Intl as { DurationFormat?: DurationFormatCtor })
- .DurationFormat;
- if (DurationFormat) {
- return new DurationFormat(locale, { style: "narrow" }).format({
- hours,
- minutes: mins,
- });
- }
- if (hours && mins) {
- return `${hours}h ${mins}m`;
- }
- if (hours) {
- return `${hours}h`;
- }
- return `${mins}m`;
-};
-
-export const getDuration = (startTime: dayjs.Dayjs, endTime: dayjs.Dayjs) => {
- return formatDuration(endTime.diff(startTime, "minute"));
-};
-
export const removeAllOptionsForDay = (
options: DateTimeOption[],
date: Date,
@@ -79,15 +50,6 @@ export const removeAllOptionsForDay = (
});
};
-export const getDateProps = (date: Date) => {
- const d = dayjs(date);
- return {
- day: d.format("D"),
- dow: d.format("ddd"),
- month: d.format("MMM"),
- };
-};
-
export const expectTimeOption = (d: DateTimeOption): TimeOption => {
if (d.type === "date") {
throw new Error("Expected timeSlot but got date instead");