Skip to content

armgit / dub

Public Imported from GitHub
0

The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.

Integrate new date picker

Tim Wilson29c7f2440c9c
diff --git a/apps/web/lib/analytics/clicks.ts b/apps/web/lib/analytics/clicks.ts
index 0937d7d013..3a3c9ab12c 100644
--- a/apps/web/lib/analytics/clicks.ts
+++ b/apps/web/lib/analytics/clicks.ts
@@ -62,9 +62,10 @@ export const getClicks = async (
} else {
start = new Date(start!);
end = end ? new Date(end) : new Date(Date.now());
- if (getDaysDifference(start, end) > 180) {
- granularity = "month";
- }
+
+ const daysDifference = getDaysDifference(start, end);
+ if (daysDifference <= 1) granularity = "hour";
+ else if (daysDifference > 180) granularity = "month";
// swap start and end if start is greater than end
if (start > end) {
diff --git a/apps/web/lib/zod/schemas/analytics.ts b/apps/web/lib/zod/schemas/analytics.ts
index cba69398f7..ef0fa1816b 100644
--- a/apps/web/lib/zod/schemas/analytics.ts
+++ b/apps/web/lib/zod/schemas/analytics.ts
@@ -40,7 +40,6 @@ export const clickAnalyticsQuerySchema = z.object({
interval: z
.enum(intervals)
.optional()
- .default("24h")
.describe(
"The interval to retrieve analytics for. Takes precedence over start and end. If undefined, defaults to 24h.",
),
diff --git a/apps/web/package.json b/apps/web/package.json
index b63863787d..54289a5a8f 100644
--- a/apps/web/package.json
+++ b/apps/web/package.json
@@ -56,6 +56,7 @@
"cobe": "^0.6.3",
"concurrently": "^8.0.1",
"d3-array": "^3.2.4",
+ "date-fns": "^3.6.0",
"framer-motion": "^10.16.16",
"fuse.js": "^6.6.2",
"github-slugger": "^2.0.0",
diff --git a/apps/web/ui/analytics/bar-chart.module.css b/apps/web/ui/analytics/bar-chart.module.css
deleted file mode 100644
index 65a82adc3d..0000000000
--- a/apps/web/ui/analytics/bar-chart.module.css
+++ /dev/null
@@ -1,21 +0,0 @@
-.tooltip {
- z-index: 40;
- width: 200px;
- padding: 1rem !important;
- border-radius: 5px !important;
- box-shadow: rgba(0, 0, 0, 0.24) 0px 3px 8px !important;
-}
-
-.tooltip::after {
- content: "";
- position: absolute;
- width: 0px;
- height: 0px;
- margin: auto;
-
- border: 7px solid transparent;
- border-top-color: white;
-
- top: 100%;
- left: 95px;
-}
diff --git a/apps/web/ui/analytics/bar-chart.tsx b/apps/web/ui/analytics/bar-chart.tsx
deleted file mode 100644
index f564f9def7..0000000000
--- a/apps/web/ui/analytics/bar-chart.tsx
+++ /dev/null
@@ -1,258 +0,0 @@
-import { LoadingSpinner, useMediaQuery } from "@dub/ui";
-import { fetcher, nFormatter } from "@dub/utils";
-import { AxisBottom, AxisLeft } from "@visx/axis";
-import { localPoint } from "@visx/event";
-import { GridRows } from "@visx/grid";
-import { scaleBand, scaleLinear } from "@visx/scale";
-import { useTooltip, useTooltipInPortal } from "@visx/tooltip";
-import { motion } from "framer-motion";
-import { useCallback, useContext, useMemo } from "react";
-import useSWR from "swr";
-import { AnalyticsContext } from ".";
-import styles from "./bar-chart.module.css";
-
-const LEFT_AXIS_WIDTH = 30;
-const CHART_MAX_HEIGHT = 400;
-const CHART_MAX_WIDTH = 800;
-
-type TooltipData = {
- start: Date;
- end: Date;
- clicks: number;
- link: string;
-};
-
-const rangeFormatter = (maxN: number): number => {
- if (maxN < 5) return 5;
- /**
- * Get the max range for a chart based on the maxN value
- */
- return Math.ceil(maxN / 5) * 5;
-};
-
-export default function BarChart() {
- const { baseApiPath, queryString, interval } = useContext(AnalyticsContext);
-
- const { data } = useSWR<{ start: Date; clicks: number }[]>(
- `${baseApiPath}/timeseries?${queryString}`,
- fetcher,
- );
-
- const { width: screenWidth } = useMediaQuery();
-
- const [CHART_WIDTH, CHART_HEIGHT] = useMemo(() => {
- const width = screenWidth
- ? Math.min(screenWidth * 0.8, CHART_MAX_WIDTH)
- : CHART_MAX_WIDTH;
- const height = screenWidth
- ? Math.min(screenWidth * 0.5, CHART_MAX_HEIGHT)
- : CHART_MAX_HEIGHT;
- return [width, height];
- }, [screenWidth]);
-
- const xScale = useMemo(() => {
- return scaleBand({
- range: [0, CHART_WIDTH],
- domain: data ? data.map((d) => d.start) : [],
- padding: 0.4,
- });
- }, [data, interval]);
-
- const yScale = useMemo(() => {
- return scaleLinear({
- range: [CHART_HEIGHT, 0],
- domain: [
- 0,
- data ? rangeFormatter(Math.max(...data.map((d) => d.clicks))) : 0,
- ],
- nice: true,
- round: true,
- });
- }, [data, interval]);
-
- const formatTimestamp = useCallback(
- (e: Date) => {
- switch (interval) {
- case "1h":
- return new Date(e).toLocaleTimeString("en-us", {
- hour: "numeric",
- minute: "numeric",
- });
- case "24h":
- return new Date(e)
- .toLocaleDateString("en-us", {
- month: "short",
- day: "numeric",
- hour: "numeric",
- })
- .replace(",", " ");
- case "90d":
- case "all":
- return new Date(e).toLocaleDateString("en-us", {
- month: "short",
- year: "numeric",
- });
- default:
- return new Date(e).toLocaleDateString("en-us", {
- month: "short",
- day: "numeric",
- });
- }
- },
- [data, interval],
- );
- const {
- tooltipOpen,
- tooltipLeft,
- tooltipTop,
- tooltipData,
- hideTooltip,
- showTooltip,
- } = useTooltip<TooltipData>();
-
- const { containerRef, TooltipInPortal } = useTooltipInPortal({
- // TooltipInPortal is rendered in a separate child of <body /> and positioned
- // with page coordinates which should be updated on scroll. consider using
- // Tooltip or TooltipWithBounds if you don't need to render inside a Portal
- scroll: true,
- debounce: 100, // to avoid a weird tooltip flickering bug
- });
-
- let tooltipTimeout: number | undefined;
- return (
- <figure
- className={`
- ${
- data && data.length > 0 ? "" : "items-center justify-center"
- } my-10 flex`}
- style={{ width: CHART_WIDTH, height: CHART_HEIGHT }}
- >
- {data && data.length > 0 ? (
- <>
- <svg ref={containerRef} width={LEFT_AXIS_WIDTH}>
- <AxisLeft
- hideAxisLine
- hideTicks
- left={8}
- numTicks={4}
- scale={yScale}
- tickFormat={(d) => nFormatter(d as number)}
- tickLabelProps={() => ({
- fill: "#666666",
- filter: data ? "none" : "blur(8px)",
- fontSize: 14,
- textAnchor: "start",
- transition: "all 0.4s ease-in-out",
- })}
- />
- </svg>
- <svg
- className="overflow-visible"
- height={CHART_HEIGHT}
- width={`calc(100% - ${LEFT_AXIS_WIDTH}px)`}
- >
- <AxisBottom
- hideAxisLine
- hideTicks
- scale={xScale}
- tickFormat={formatTimestamp}
- tickLabelProps={() => ({
- fill: "#666666",
- filter: data ? "none" : "blur(8px)",
- fontSize: 12,
- textAnchor: "middle",
- transition: "all 0.4s ease-in-out",
- })}
- numTicks={6}
- top={CHART_HEIGHT - 5}
- />
- <GridRows
- numTicks={5}
- scale={yScale}
- stroke="#E1E1E1"
- width={CHART_WIDTH}
- />
- {data.map(({ start, clicks }, idx) => {
- const barWidth = xScale.bandwidth();
- const barHeight = CHART_HEIGHT - (yScale(clicks) ?? 0);
- const barX = xScale(start) ?? 0;
- const barY = CHART_HEIGHT - barHeight;
- return (
- <motion.rect
- key={`bar-${interval}-${start}`}
- transition={{ ease: "easeOut", duration: 0.3 }}
- className="!origin-bottom fill-[#2563eb]"
- initial={{ transform: "scaleY(0)" }}
- animate={{ transform: "scaleY(1)" }}
- x={barX}
- y={barY}
- width={barWidth}
- height={barHeight}
- onMouseLeave={() => {
- tooltipTimeout = window.setTimeout(() => {
- hideTooltip();
- }, 300);
- }}
- onMouseMove={(event) => {
- if (tooltipTimeout) clearTimeout(tooltipTimeout);
- // TooltipInPortal expects coordinates to be relative to containerRef
- // localPoint returns coordinates relative to the nearest SVG, which
- // is what containerRef is set to in this example.
- const eventSvgCoords = localPoint(event) ?? {
- x: 0,
- y: 0,
- };
- const left = barX + barWidth / 2 - 81;
- showTooltip({
- tooltipData: {
- start,
- end: data[idx + 1]?.start ?? new Date(),
- clicks,
- link: "https://google.com",
- },
- tooltipTop: eventSvgCoords.y - 150,
- tooltipLeft: left,
- });
- }}
- />
- );
- })}
- </svg>
- {tooltipOpen && tooltipData && (
- <TooltipInPortal
- top={tooltipTop}
- left={tooltipLeft}
- className={styles.tooltip}
- >
- {
- (
- <div className="text-center">
- <h3 className="my-1 text-black">
- <span className="text-2xl font-semibold">
- {nFormatter(tooltipData.clicks)}
- </span>{" "}
- click{tooltipData.clicks === 1 ? "" : "s"}
- </h3>
- <p className="text-xs text-gray-600">
- {formatTimestamp(tooltipData.start)} -{" "}
- {interval === "24h"
- ? new Date(tooltipData.end).toLocaleTimeString(
- "en-us",
- {
- hour: "numeric",
- },
- )
- : formatTimestamp(tooltipData.end)}
- </p>
- </div>
- ) as any
- }
- </TooltipInPortal>
- )}
- </>
- ) : (
- <LoadingSpinner />
- )}
- </figure>
- );
-}
diff --git a/apps/web/ui/analytics/clicks-chart.tsx b/apps/web/ui/analytics/clicks-chart.tsx
index c713232640..85c36c0445 100644
--- a/apps/web/ui/analytics/clicks-chart.tsx
+++ b/apps/web/ui/analytics/clicks-chart.tsx
@@ -1,5 +1,5 @@
import { LoadingSpinner } from "@dub/ui";
-import { fetcher, nFormatter } from "@dub/utils";
+import { fetcher, getDaysDifference, nFormatter } from "@dub/utils";
import { useCallback, useContext, useMemo } from "react";
import useSWR from "swr";
import { AnalyticsContext } from ".";
@@ -9,7 +9,7 @@ import XAxis from "../charts/x-axis";
import YAxis from "../charts/y-axis";
export default function ClicksChart() {
- const { baseApiPath, queryString, interval } = useContext(AnalyticsContext);
+ const { baseApiPath, queryString, start, end } = useContext(AnalyticsContext);
const { data } = useSWR<{ start: Date; clicks: number }[]>(
`${baseApiPath}/timeseries?${queryString}`,
@@ -27,29 +27,26 @@ export default function ClicksChart() {
const formatDate = useCallback(
(date: Date) => {
- switch (interval) {
- case "1h":
- case "24h":
- return date.toLocaleTimeString("en-US", {
- hour: "numeric",
- minute: "numeric",
- });
- case "ytd":
- case "1y":
- case "all":
- return date.toLocaleDateString("en-US", {
- month: "short",
- year: "numeric",
- });
- default:
- return date.toLocaleDateString("en-US", {
- weekday: "short",
- month: "short",
- day: "numeric",
- });
- }
+ const daysDifference = getDaysDifference(start, end);
+
+ if (daysDifference <= 1)
+ return date.toLocaleTimeString("en-US", {
+ hour: "numeric",
+ minute: "numeric",
+ });
+ else if (daysDifference > 180)
+ return date.toLocaleDateString("en-US", {
+ month: "short",
+ year: "numeric",
+ });
+
+ return date.toLocaleDateString("en-US", {
+ weekday: "short",
+ month: "short",
+ day: "numeric",
+ });
},
- [interval],
+ [start, end],
);
return (
diff --git a/apps/web/ui/analytics/index.tsx b/apps/web/ui/analytics/index.tsx
index e71f302101..7234e385c6 100644
--- a/apps/web/ui/analytics/index.tsx
+++ b/apps/web/ui/analytics/index.tsx
@@ -8,6 +8,7 @@
import { VALID_ANALYTICS_FILTERS } from "@/lib/analytics/constants";
import useWorkspace from "@/lib/swr/use-workspace";
import { fetcher } from "@dub/utils";
+import { subDays } from "date-fns";
import { useParams, usePathname, useSearchParams } from "next/navigation";
import { createContext, useMemo } from "react";
import useSWR from "swr";
@@ -25,7 +26,8 @@ export const AnalyticsContext = createContext<{
key?: string;
url?: string;
queryString: string;
- interval: string;
+ start: Date;
+ end: Date;
tagId?: string;
totalClicks?: number;
admin?: boolean;
@@ -34,7 +36,8 @@ export const AnalyticsContext = createContext<{
baseApiPath: "",
domain: "",
queryString: "",
- interval: "",
+ start: new Date(),
+ end: new Date(),
admin: false,
});
@@ -57,10 +60,17 @@ export default function Analytics({
const domainSlug = searchParams?.get("domain");
// key can be a path param (public stats pages) or a query param (stats pages in app)
key = searchParams?.get("key") || key;
- const interval = searchParams?.get("interval") || "24h";
const tagId = searchParams?.get("tagId") ?? undefined;
+ // Default to last 30 days
+ const { start, end } = useMemo(() => {
+ return {
+ start: new Date(searchParams?.get("start") || subDays(new Date(), 30)),
+ end: new Date(searchParams?.get("end") || new Date()),
+ };
+ }, [searchParams]);
+
const { basePath, domain, baseApiPath } = useMemo(() => {
// Workspace analytics page, e.g. app.dub.co/dub/analytics?domain=dub.sh&key=github
if (admin) {
@@ -99,11 +109,12 @@ export default function Analytics({
...(id && { workspaceId: id }),
...(domain && { domain }),
...(key && { key }),
- ...(interval && { interval }),
+ ...(start &&
+ end && { start: start.toISOString(), end: end.toISOString() }),
...(tagId && { tagId }),
...availableFilterParams,
}).toString();
- }, [id, domain, key, searchParams, interval, tagId]);
+ }, [id, domain, key, searchParams, start, end, tagId]);
const { data: totalClicks } = useSWR<number>(
`${baseApiPath}/count?${queryString}`,
@@ -121,7 +132,8 @@ export default function Analytics({
domain: domain || undefined, // domain for the link (e.g. dub.sh, stey.me, etc.)
key: key ? decodeURIComponent(key) : undefined, // link key (e.g. github, weathergpt, etc.)
url: staticUrl, // url for the link (only for public stats pages)
- interval, // time interval (e.g. 24h, 7d, 30d, etc.)
+ start, // start of time period
+ end, // end of time period
tagId, // id of a single tag
totalClicks, // total clicks for the link
admin, // whether the user is an admin
diff --git a/apps/web/ui/analytics/toggle.tsx b/apps/web/ui/analytics/toggle.tsx
index ebc9a4b518..397a1a6b8d 100644
--- a/apps/web/ui/analytics/toggle.tsx
+++ b/apps/web/ui/analytics/toggle.tsx
@@ -1,4 +1,10 @@
-import { BlurImage, DateRangePicker, ExpandingArrow, useScroll } from "@dub/ui";
+import {
+ BlurImage,
+ DateRangePicker,
+ ExpandingArrow,
+ useRouterStuff,
+ useScroll,
+} from "@dub/ui";
import {
DUB_LOGO,
GOOGLE_FAVICON_URL,
@@ -9,13 +15,14 @@ import {
import { setDate, setMonth, subDays, subMonths } from "date-fns";
import { useContext } from "react";
import { AnalyticsContext } from ".";
-import DateRangePickerOld from "./date-range-picker";
import ExportButton from "./export-button";
import FilterBar from "./filter-bar";
import SharePopover from "./share-popover";
export default function Toggle() {
- const { basePath, domain, key, url, admin } = useContext(AnalyticsContext);
+ const { basePath, domain, key, url, admin, start, end } =
+ useContext(AnalyticsContext);
+ const { queryParams } = useRouterStuff();
const scrolled = useScroll(80);
@@ -88,10 +95,22 @@ export default function Toggle() {
"justify-end": key,
})}
>
- <DateRangePickerOld />
<DateRangePicker
align="end"
- defaultValue={{ from: subDays(new Date(), 30), to: new Date() }}
+ defaultValue={{
+ from: start ? new Date(start) : subDays(new Date(), 30),
+ to: end ? new Date(end) : new Date(),
+ }}
+ onChange={(range) => {
+ if (!range || !range.from || !range.to) return;
+
+ queryParams({
+ set: {
+ start: range.from.toISOString(),
+ end: range.to.toISOString(),
+ },
+ });
+ }}
presets={[
{
label: "Last 24 hours",
diff --git a/packages/ui/src/date-picker/calendar.tsx b/packages/ui/src/date-picker/calendar.tsx
index d2109f09b6..816aded3cd 100644
--- a/packages/ui/src/date-picker/calendar.tsx
+++ b/packages/ui/src/date-picker/calendar.tsx
@@ -92,7 +92,7 @@ function Calendar({
className={className}
classNames={{
months: "flex space-y-0",
- month: "space-y-4 p-3",
+ month: "space-y-4 p-3 w-full",
nav: "gap-1 flex items-center rounded-full w-full h-full justify-between p-4",
table: "w-full border-collapse space-y-1",
head_cell:
@@ -100,7 +100,7 @@ function Calendar({
row: "w-full mt-0.5",
cell: "relative p-0 text-center focus-within:relative text-gray-900",
day: cn(
- "w-9 h-9 rounded text-sm text-gray-900",
+ "relative h-10 w-full sm:h-9 sm:w-9 rounded text-sm text-gray-900",
"hover:bg-gray-200 outline outline-offset-2 outline-0 focus-visible:outline-2 outline-blue-500",
),
day_today: "font-semibold",
@@ -240,19 +240,10 @@ function Calendar({
);
}
- const {
- children: buttonChildren,
- className: buttonClassName,
- ...buttonPropsRest
- } = buttonProps;
+ const { children: buttonChildren, ...buttonPropsRest } = buttonProps;
return (
- <button
- ref={buttonRef}
- {...buttonPropsRest}
- type="button"
- className={cn("relative", buttonClassName)}
- >
+ <button ref={buttonRef} {...buttonPropsRest} type="button">
{buttonChildren}
{today && (
<span
diff --git a/packages/ui/src/date-picker/date-range-picker.tsx b/packages/ui/src/date-picker/date-range-picker.tsx
index e220ca73f6..7ba076d303 100644
--- a/packages/ui/src/date-picker/date-range-picker.tsx
+++ b/packages/ui/src/date-picker/date-range-picker.tsx
@@ -1,6 +1,5 @@
import { cn } from "@dub/utils";
import { Time } from "@internationalized/date";
-import * as Popover from "@radix-ui/react-popover";
import {
AriaTimeFieldProps,
TimeValue,
@@ -18,7 +17,6 @@ import { enUS } from "date-fns/locale";
import { Calendar, ChevronDown, Minus } from "lucide-react";
import {
ComponentProps,
- ElementRef,
forwardRef,
useEffect,
useImperativeHandle,
@@ -28,6 +26,7 @@ import {
} from "react";
import { Button } from "../button";
import { useMediaQuery } from "../hooks";
+import { Popover, PopoverProps } from "../popover";
import { Calendar as CalendarPrimitive, type Matcher } from "./calendar";
//#region TimeInput
@@ -174,68 +173,34 @@ const Trigger = forwardRef<HTMLButtonElement, TriggerProps>(
forwardedRef,
) => {
return (
- <Popover.Trigger asChild>
- <button
- ref={forwardedRef}
- className={cn(triggerStyles({ hasError }), className)}
- {...props}
- >
- <Calendar
- className={cn(
- "h-4 w-4 shrink-0 text-gray-400",
- !!children && "text-gray-900",
- )}
- />
- <span className="flex-1 overflow-hidden text-ellipsis whitespace-nowrap text-left text-gray-900">
- {children ? (
- children
- ) : placeholder ? (
- <span className="text-gray-400">{placeholder}</span>
- ) : null}
- </span>
- <ChevronDown
- className={`h-4 w-4 flex-shrink-0 text-gray-400 transition-transform duration-75 group-data-[state=open]:rotate-180`}
- />
- </button>
- </Popover.Trigger>
+ <button
+ ref={forwardedRef}
+ className={cn(triggerStyles({ hasError }), className)}
+ {...props}
+ >
+ <Calendar
+ className={cn(
+ "h-4 w-4 shrink-0 text-gray-400",
+ !!children && "text-gray-900",
+ )}
+ />
+ <span className="flex-1 overflow-hidden text-ellipsis whitespace-nowrap text-left text-gray-900">
+ {children ? (
+ children
+ ) : placeholder ? (
+ <span className="text-gray-400">{placeholder}</span>
+ ) : null}
+ </span>
+ <ChevronDown
+ className={`h-4 w-4 flex-shrink-0 text-gray-400 transition-transform duration-75 group-data-[state=open]:rotate-180`}
+ />
+ </button>
);
},
);
Trigger.displayName = "DatePicker.Trigger";
-//#region Popover
-// ============================================================================
-
-const CalendarPopover = forwardRef<
- ElementRef<typeof Popover.Content>,
- ComponentProps<typeof Popover.Content>
->(({ align, className, children, ...props }, forwardedRef) => {
- return (
- <Popover.Portal>
- <Popover.Content
- ref={forwardedRef}
- sideOffset={10}
- side="bottom"
- align={align}
- avoidCollisions
- onOpenAutoFocus={(e) => e.preventDefault()}
- className={cn(
- "relative z-50 w-fit min-w-[calc(var(--radix-select-trigger-width)-2px)] max-w-[95vw]",
- "rounded-lg border border-gray-200 bg-white text-sm drop-shadow-lg",
- "animate-slide-up-fade will-change-[transform,opacity]",
- className,
- )}
- {...props}
- >
- {children}
- </Popover.Content>
- </Popover.Portal>
- );
-});
-
-CalendarPopover.displayName = "DatePicker.CalendarPopover";
-
//#region Preset
// ============================================================================
@@ -412,14 +377,6 @@ type CalendarProps = {
locale?: Locale;
};
-type Translations = {
- cancel?: string;
- apply?: string;
- start?: string;
- end?: string;
- range?: string;
-};
-
interface PickerProps extends CalendarProps {
className?: string;
disabled?: boolean;
@@ -431,7 +388,7 @@ interface PickerProps extends CalendarProps {
disableNavigation?: boolean;
hasError?: boolean;
id?: string;
- align?: "center" | "end" | "start";
+ align?: PopoverProps["align"];
"aria-invalid"?: boolean;
"aria-label"?: string;
"aria-labelledby"?: string;
@@ -583,22 +540,13 @@ const SingleDatePicker = ({
}, [value, defaultValue]);
return (
- <Popover.Root open={open} onOpenChange={onOpenChange}>
- <Trigger
- placeholder={placeholder}
- disabled={disabled}
- className={className}
- hasError={hasError}
- aria-required={props.required || props["aria-required"]}
- aria-invalid={props["aria-invalid"]}
- aria-label={props["aria-label"]}
- aria-labelledby={props["aria-labelledby"]}
- >
- {formattedDate}
- </Trigger>
- <CalendarPopover align={align}>
- <div className="flex">
- <div className="flex flex-col sm:flex-row sm:items-start">
+ <Popover
+ align={align}
+ openPopover={open}
+ setOpenPopover={onOpenChange}
+ content={
+ <div className="flex w-full">
+ <div className="flex w-full flex-col sm:flex-row sm:items-start">
{presets && presets.length > 0 && (
<div
className={cn(
@@ -644,14 +592,14 @@ const SingleDatePicker = ({
<div className="flex items-center gap-x-2 border-t border-gray-200 p-3">
<Button
variant="secondary"
- className="h-8"
+ className="sm:h-8"
type="button"
onClick={onCancel}
text="Cancel"
/>
<Button
variant="primary"
- className="h-8"
+ className="sm:h-8"
type="button"
onClick={onApply}
text="Apply"
@@ -660,8 +608,21 @@ const SingleDatePicker = ({
</div>
</div>
</div>
- </CalendarPopover>
- </Popover.Root>
+ }
+ >
+ <Trigger
+ placeholder={placeholder}
+ disabled={disabled}
+ className={className}
+ hasError={hasError}
+ aria-required={props.required || props["aria-required"]}
+ aria-invalid={props["aria-invalid"]}
+ aria-label={props["aria-label"]}
+ aria-labelledby={props["aria-labelledby"]}
+ >
+ {formattedDate}
+ </Trigger>
+ </Popover>
);
};
@@ -692,7 +653,7 @@ const RangeDatePicker = ({
className,
...props
}: RangeProps) => {
- const { isMobile } = useMediaQuery();
+ const { isDesktop } = useMediaQuery();
const [open, setOpen] = useState(false);
const [range, setRange] = useState<DateRange | undefined>(
@@ -884,22 +845,13 @@ const RangeDatePicker = ({
};
return (
- <Popover.Root open={open} onOpenChange={onOpenChange}>
- <Trigger
- placeholder={placeholder}
- disabled={disabled}
- className={className}
- hasError={hasError}
- aria-required={props.required || props["aria-required"]}
- aria-invalid={props["aria-invalid"]}
- aria-label={props["aria-label"]}
- aria-labelledby={props["aria-labelledby"]}
- >
- {displayRange}
- </Trigger>
- <CalendarPopover align={align}>
- <div className="flex">
- <div className="scrollbar-hide flex flex-col overflow-x-scroll sm:flex-row sm:items-start">
+ <Popover
+ align={align}
+ openPopover={open}
+ setOpenPopover={onOpenChange}
+ content={
+ <div className="flex w-full">
+ <div className="scrollbar-hide flex w-full flex-col overflow-x-scroll sm:flex-row sm:items-start">
{presets && presets.length > 0 && (
<div
className={cn(
@@ -924,7 +876,7 @@ const RangeDatePicker = ({
onSelect={onRangeChange}
month={month}
onMonthChange={setMonth}
- numberOfMonths={isMobile ? 1 : 2}
+ numberOfMonths={isDesktop ? 2 : 1}
disabled={disabledDays}
disableNavigation={disableNavigation}
showYearNavigation={showYearNavigation}
@@ -962,26 +914,18 @@ const RangeDatePicker = ({
</div>
</div>
)}
- <div className="border-t border-gray-200 p-3 sm:flex sm:items-center sm:justify-between">
- <p className="tabular-nums text-gray-900">
- {displayRange && (
- <>
- <span className="text-gray-700">Range:</span>{" "}
- <span className="font-medium">{displayRange}</span>
- </>
- )}
- </p>
+ <div className="border-t border-gray-200 p-3 sm:flex sm:items-center sm:justify-end">
<div className="mt-2 flex items-center gap-x-2 sm:mt-0">
<Button
variant="secondary"
- className="h-8"
+ className="sm:h-8"
type="button"
onClick={onCancel}
text="Cancel"
/>
<Button
variant="primary"
- className="h-8"
+ className="sm:h-8"
type="button"
onClick={onApply}
text="Apply"
@@ -991,8 +935,21 @@ const RangeDatePicker = ({
</div>
</div>
</div>
- </CalendarPopover>
- </Popover.Root>
+ }
+ >
+ <Trigger
+ placeholder={placeholder}
+ disabled={disabled}
+ className={className}
+ hasError={hasError}
+ aria-required={props.required || props["aria-required"]}
+ aria-invalid={props["aria-invalid"]}
+ aria-label={props["aria-label"]}
+ aria-labelledby={props["aria-labelledby"]}
+ >
+ {displayRange}
+ </Trigger>
+ </Popover>
);
};
@@ -1149,9 +1106,7 @@ type SingleDatePickerProps = {
} & PickerProps;
const DatePicker = ({ presets, ...props }: SingleDatePickerProps) => {
- if (presets) {
- validatePresets(presets, props);
- }
+ if (presets) validatePresets(presets, props);
return <SingleDatePicker presets={presets} {...(props as SingleProps)} />;
};
diff --git a/packages/ui/src/popover.tsx b/packages/ui/src/popover.tsx
index b8a6578934..665b505692 100644
--- a/packages/ui/src/popover.tsx
+++ b/packages/ui/src/popover.tsx
@@ -1,10 +1,18 @@
"use client";
import * as PopoverPrimitive from "@radix-ui/react-popover";
-import { Dispatch, ReactNode, SetStateAction } from "react";
+import { PropsWithChildren, ReactNode } from "react";
import { Drawer } from "vaul";
import { useMediaQuery } from "./hooks";
+export type PopoverProps = PropsWithChildren<{
+ content: ReactNode | string;
+ align?: "center" | "start" | "end";
+ openPopover: boolean;
+ setOpenPopover: (open: boolean) => void;
+ mobileOnly?: boolean;
+}>;
+
export function Popover({
children,
content,
@@ -12,14 +20,7 @@ export function Popover({
openPopover,
setOpenPopover,
mobileOnly,
-}: {
- children: ReactNode;
- content: ReactNode | string;
- align?: "center" | "start" | "end";
- openPopover: boolean;
- setOpenPopover: Dispatch<SetStateAction<boolean>>;
- mobileOnly?: boolean;
-}) {
+}: PopoverProps) {
const { isMobile } = useMediaQuery();
if (mobileOnly || isMobile) {
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index f5af36c6fc..45ec5a5573 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -166,6 +166,9 @@ importers:
d3-array:
specifier: ^3.2.4
version: 3.2.4
+ date-fns:
+ specifier: ^3.6.0
+ version: 3.6.0
framer-motion:
specifier: ^10.16.16