-
Notifications
You must be signed in to change notification settings - Fork 30
/
date-range-picker.tsx
560 lines (529 loc) · 18 KB
/
date-range-picker.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
/* eslint-disable max-lines */
'use client'
import React, { type FC, useState, useEffect, useRef } from 'react'
import { Button } from './button'
import { Popover, PopoverContent, PopoverTrigger } from './popover'
import { Calendar } from './calendar'
import { DateInput } from './date-input'
import { Label } from './label'
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue
} from './select'
import { Switch } from './switch'
import { ChevronUpIcon, ChevronDownIcon, CheckIcon } from '@radix-ui/react-icons'
import { cn } from '@/lib/utils'
export interface DateRangePickerProps {
/** Click handler for applying the updates from DateRangePicker. */
onUpdate?: (values: { range: DateRange, rangeCompare?: DateRange }) => void
/** Initial value for start date */
initialDateFrom?: Date | string
/** Initial value for end date */
initialDateTo?: Date | string
/** Initial value for start date for compare */
initialCompareFrom?: Date | string
/** Initial value for end date for compare */
initialCompareTo?: Date | string
/** Alignment of popover */
align?: 'start' | 'center' | 'end'
/** Option for locale */
locale?: string
/** Option for showing compare feature */
showCompare?: boolean
}
const formatDate = (date: Date, locale: string = 'en-us'): string => {
return date.toLocaleDateString(locale, {
month: 'short',
day: 'numeric',
year: 'numeric'
})
}
const getDateAdjustedForTimezone = (dateInput: Date | string): Date => {
if (typeof dateInput === 'string') {
// Split the date string to get year, month, and day parts
const parts = dateInput.split('-').map((part) => parseInt(part, 10))
// Create a new Date object using the local timezone
// Note: Month is 0-indexed, so subtract 1 from the month part
const date = new Date(parts[0], parts[1] - 1, parts[2])
return date
} else {
// If dateInput is already a Date object, return it directly
return dateInput
}
}
interface DateRange {
from: Date
to: Date | undefined
}
interface Preset {
name: string
label: string
}
// Define presets
const PRESETS: Preset[] = [
{ name: 'today', label: 'Today' },
{ name: 'yesterday', label: 'Yesterday' },
{ name: 'last7', label: 'Last 7 days' },
{ name: 'last14', label: 'Last 14 days' },
{ name: 'last30', label: 'Last 30 days' },
{ name: 'thisWeek', label: 'This Week' },
{ name: 'lastWeek', label: 'Last Week' },
{ name: 'thisMonth', label: 'This Month' },
{ name: 'lastMonth', label: 'Last Month' }
]
/** The DateRangePicker component allows a user to select a range of dates */
export const DateRangePicker: FC<DateRangePickerProps> & {
filePath: string
} = ({
initialDateFrom = new Date(new Date().setHours(0, 0, 0, 0)),
initialDateTo,
initialCompareFrom,
initialCompareTo,
onUpdate,
align = 'end',
locale = 'en-US',
showCompare = true
}): JSX.Element => {
const [isOpen, setIsOpen] = useState(false)
const [range, setRange] = useState<DateRange>({
from: getDateAdjustedForTimezone(initialDateFrom),
to: initialDateTo
? getDateAdjustedForTimezone(initialDateTo)
: getDateAdjustedForTimezone(initialDateFrom)
})
const [rangeCompare, setRangeCompare] = useState<DateRange | undefined>(
initialCompareFrom
? {
from: new Date(new Date(initialCompareFrom).setHours(0, 0, 0, 0)),
to: initialCompareTo
? new Date(new Date(initialCompareTo).setHours(0, 0, 0, 0))
: new Date(new Date(initialCompareFrom).setHours(0, 0, 0, 0))
}
: undefined
)
// Refs to store the values of range and rangeCompare when the date picker is opened
const openedRangeRef = useRef<DateRange | undefined>()
const openedRangeCompareRef = useRef<DateRange | undefined>()
const [selectedPreset, setSelectedPreset] = useState<string | undefined>(undefined)
const [isSmallScreen, setIsSmallScreen] = useState(
typeof window !== 'undefined' ? window.innerWidth < 960 : false
)
useEffect(() => {
const handleResize = (): void => {
setIsSmallScreen(window.innerWidth < 960)
}
window.addEventListener('resize', handleResize)
// Clean up event listener on unmount
return () => {
window.removeEventListener('resize', handleResize)
}
}, [])
const getPresetRange = (presetName: string): DateRange => {
const preset = PRESETS.find(({ name }) => name === presetName)
if (!preset) throw new Error(`Unknown date range preset: ${presetName}`)
const from = new Date()
const to = new Date()
const first = from.getDate() - from.getDay()
switch (preset.name) {
case 'today':
from.setHours(0, 0, 0, 0)
to.setHours(23, 59, 59, 999)
break
case 'yesterday':
from.setDate(from.getDate() - 1)
from.setHours(0, 0, 0, 0)
to.setDate(to.getDate() - 1)
to.setHours(23, 59, 59, 999)
break
case 'last7':
from.setDate(from.getDate() - 6)
from.setHours(0, 0, 0, 0)
to.setHours(23, 59, 59, 999)
break
case 'last14':
from.setDate(from.getDate() - 13)
from.setHours(0, 0, 0, 0)
to.setHours(23, 59, 59, 999)
break
case 'last30':
from.setDate(from.getDate() - 29)
from.setHours(0, 0, 0, 0)
to.setHours(23, 59, 59, 999)
break
case 'thisWeek':
from.setDate(first)
from.setHours(0, 0, 0, 0)
to.setHours(23, 59, 59, 999)
break
case 'lastWeek':
from.setDate(from.getDate() - 7 - from.getDay())
to.setDate(to.getDate() - to.getDay() - 1)
from.setHours(0, 0, 0, 0)
to.setHours(23, 59, 59, 999)
break
case 'thisMonth':
from.setDate(1)
from.setHours(0, 0, 0, 0)
to.setHours(23, 59, 59, 999)
break
case 'lastMonth':
from.setMonth(from.getMonth() - 1)
from.setDate(1)
from.setHours(0, 0, 0, 0)
to.setDate(0)
to.setHours(23, 59, 59, 999)
break
}
return { from, to }
}
const setPreset = (preset: string): void => {
const range = getPresetRange(preset)
setRange(range)
if (rangeCompare) {
const rangeCompare = {
from: new Date(
range.from.getFullYear() - 1,
range.from.getMonth(),
range.from.getDate()
),
to: range.to
? new Date(
range.to.getFullYear() - 1,
range.to.getMonth(),
range.to.getDate()
)
: undefined
}
setRangeCompare(rangeCompare)
}
}
const checkPreset = (): void => {
for (const preset of PRESETS) {
const presetRange = getPresetRange(preset.name)
const normalizedRangeFrom = new Date(range.from);
normalizedRangeFrom.setHours(0, 0, 0, 0);
const normalizedPresetFrom = new Date(
presetRange.from.setHours(0, 0, 0, 0)
)
const normalizedRangeTo = new Date(range.to ?? 0);
normalizedRangeTo.setHours(0, 0, 0, 0);
const normalizedPresetTo = new Date(
presetRange.to?.setHours(0, 0, 0, 0) ?? 0
)
if (
normalizedRangeFrom.getTime() === normalizedPresetFrom.getTime() &&
normalizedRangeTo.getTime() === normalizedPresetTo.getTime()
) {
setSelectedPreset(preset.name)
return
}
}
setSelectedPreset(undefined)
}
const resetValues = (): void => {
setRange({
from:
typeof initialDateFrom === 'string'
? getDateAdjustedForTimezone(initialDateFrom)
: initialDateFrom,
to: initialDateTo
? typeof initialDateTo === 'string'
? getDateAdjustedForTimezone(initialDateTo)
: initialDateTo
: typeof initialDateFrom === 'string'
? getDateAdjustedForTimezone(initialDateFrom)
: initialDateFrom
})
setRangeCompare(
initialCompareFrom
? {
from:
typeof initialCompareFrom === 'string'
? getDateAdjustedForTimezone(initialCompareFrom)
: initialCompareFrom,
to: initialCompareTo
? typeof initialCompareTo === 'string'
? getDateAdjustedForTimezone(initialCompareTo)
: initialCompareTo
: typeof initialCompareFrom === 'string'
? getDateAdjustedForTimezone(initialCompareFrom)
: initialCompareFrom
}
: undefined
)
}
useEffect(() => {
checkPreset()
}, [range])
const PresetButton = ({
preset,
label,
isSelected
}: {
preset: string
label: string
isSelected: boolean
}): JSX.Element => (
<Button
className={cn(isSelected && 'pointer-events-none')}
variant="ghost"
onClick={() => {
setPreset(preset)
}}
>
<>
<span className={cn('pr-2 opacity-0', isSelected && 'opacity-70')}>
<CheckIcon width={18} height={18} />
</span>
{label}
</>
</Button>
)
// Helper function to check if two date ranges are equal
const areRangesEqual = (a?: DateRange, b?: DateRange): boolean => {
if (!a || !b) return a === b // If either is undefined, return true if both are undefined
return (
a.from.getTime() === b.from.getTime() &&
(!a.to || !b.to || a.to.getTime() === b.to.getTime())
)
}
useEffect(() => {
if (isOpen) {
openedRangeRef.current = range
openedRangeCompareRef.current = rangeCompare
}
}, [isOpen])
return (
<Popover
modal={true}
open={isOpen}
onOpenChange={(open: boolean) => {
if (!open) {
resetValues()
}
setIsOpen(open)
}}
>
<PopoverTrigger asChild>
<Button size={'lg'} variant="outline">
<div className="text-right">
<div className="py-1">
<div>{`${formatDate(range.from, locale)}${
range.to != null ? ' - ' + formatDate(range.to, locale) : ''
}`}</div>
</div>
{rangeCompare != null && (
<div className="opacity-60 text-xs -mt-1">
<>
vs. {formatDate(rangeCompare.from, locale)}
{rangeCompare.to != null
? ` - ${formatDate(rangeCompare.to, locale)}`
: ''}
</>
</div>
)}
</div>
<div className="pl-1 opacity-60 -mr-2 scale-125">
{isOpen ? (<ChevronUpIcon width={24} />) : (<ChevronDownIcon width={24} />)}
</div>
</Button>
</PopoverTrigger>
<PopoverContent align={align} className="w-auto">
<div className="flex py-2">
<div className="flex">
<div className="flex flex-col">
<div className="flex flex-col lg:flex-row gap-2 px-3 justify-end items-center lg:items-start pb-4 lg:pb-0">
{showCompare && (
<div className="flex items-center space-x-2 pr-4 py-1">
<Switch
defaultChecked={Boolean(rangeCompare)}
onCheckedChange={(checked: boolean) => {
if (checked) {
if (!range.to) {
setRange({
from: range.from,
to: range.from
})
}
setRangeCompare({
from: new Date(
range.from.getFullYear(),
range.from.getMonth(),
range.from.getDate() - 365
),
to: range.to
? new Date(
range.to.getFullYear() - 1,
range.to.getMonth(),
range.to.getDate()
)
: new Date(
range.from.getFullYear() - 1,
range.from.getMonth(),
range.from.getDate()
)
})
} else {
setRangeCompare(undefined)
}
}}
id="compare-mode"
/>
<Label htmlFor="compare-mode">Compare</Label>
</div>
)}
<div className="flex flex-col gap-2">
<div className="flex gap-2">
<DateInput
value={range.from}
onChange={(date) => {
const toDate =
range.to == null || date > range.to ? date : range.to
setRange((prevRange) => ({
...prevRange,
from: date,
to: toDate
}))
}}
/>
<div className="py-1">-</div>
<DateInput
value={range.to}
onChange={(date) => {
const fromDate = date < range.from ? date : range.from
setRange((prevRange) => ({
...prevRange,
from: fromDate,
to: date
}))
}}
/>
</div>
{rangeCompare != null && (
<div className="flex gap-2">
<DateInput
value={rangeCompare?.from}
onChange={(date) => {
if (rangeCompare) {
const compareToDate =
rangeCompare.to == null || date > rangeCompare.to
? date
: rangeCompare.to
setRangeCompare((prevRangeCompare) => ({
...prevRangeCompare,
from: date,
to: compareToDate
}))
} else {
setRangeCompare({
from: date,
to: new Date()
})
}
}}
/>
<div className="py-1">-</div>
<DateInput
value={rangeCompare?.to}
onChange={(date) => {
if (rangeCompare && rangeCompare.from) {
const compareFromDate =
date < rangeCompare.from
? date
: rangeCompare.from
setRangeCompare({
...rangeCompare,
from: compareFromDate,
to: date
})
}
}}
/>
</div>
)}
</div>
</div>
{ isSmallScreen && (
<Select defaultValue={selectedPreset} onValueChange={(value) => { setPreset(value) }}>
<SelectTrigger className="w-[180px] mx-auto mb-2">
<SelectValue placeholder="Select..." />
</SelectTrigger>
<SelectContent>
{PRESETS.map((preset) => (
<SelectItem key={preset.name} value={preset.name}>
{preset.label}
</SelectItem>
))}
</SelectContent>
</Select>
)}
<div>
<Calendar
mode="range"
onSelect={(value: { from?: Date, to?: Date } | undefined) => {
if (value?.from != null) {
setRange({ from: value.from, to: value?.to })
}
}}
selected={range}
numberOfMonths={isSmallScreen ? 1 : 2}
defaultMonth={
new Date(
new Date().setMonth(
new Date().getMonth() - (isSmallScreen ? 0 : 1)
)
)
}
/>
</div>
</div>
</div>
{!isSmallScreen && (
<div className="flex flex-col items-end gap-1 pr-2 pl-6 pb-6">
<div className="flex w-full flex-col items-end gap-1 pr-2 pl-6 pb-6">
{PRESETS.map((preset) => (
<PresetButton
key={preset.name}
preset={preset.name}
label={preset.label}
isSelected={selectedPreset === preset.name}
/>
))}
</div>
</div>
)}
</div>
<div className="flex justify-end gap-2 py-2 pr-4">
<Button
onClick={() => {
setIsOpen(false)
resetValues()
}}
variant="ghost"
>
Cancel
</Button>
<Button
onClick={() => {
setIsOpen(false)
if (
!areRangesEqual(range, openedRangeRef.current) ||
!areRangesEqual(rangeCompare, openedRangeCompareRef.current)
) {
onUpdate?.({ range, rangeCompare })
}
}}
>
Update
</Button>
</div>
</PopoverContent>
</Popover>
)
}
DateRangePicker.displayName = 'DateRangePicker'
DateRangePicker.filePath =
'libs/shared/ui-kit/src/lib/date-range-picker/date-range-picker.tsx'