react-native-hilal 0.2.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -49,6 +49,15 @@ import {
49
49
  type DayRange,
50
50
  } from './month';
51
51
  import { PickerGrid, type PickerGridItem } from './PickerGrid';
52
+ import {
53
+ checkRangeLimits,
54
+ nextRange,
55
+ outsideRangeLimits,
56
+ rangeLength,
57
+ rangePosition,
58
+ type DayRangeSelection,
59
+ type RangePosition,
60
+ } from './range';
52
61
  import {
53
62
  createStyles,
54
63
  MAX_CELL_FONT_SCALE,
@@ -56,13 +65,20 @@ import {
56
65
  withSlots,
57
66
  } from './styles';
58
67
  import { resolveTheme } from './theme';
59
- import type { HilalCalendarProps, HilalLabels, SelectedDate } from './types';
68
+ import type {
69
+ DateRange,
70
+ HilalCalendarProps,
71
+ HilalLabels,
72
+ SelectedDate,
73
+ } from './types';
60
74
 
61
75
  const LABELS: Record<Locale, Required<HilalLabels> & { separator: string }> = {
62
76
  ar: {
63
77
  hijri: 'هجري',
64
78
  gregorian: 'ميلادي',
65
79
  today: 'اليوم',
80
+ rangeStart: 'بداية الفترة',
81
+ rangeEnd: 'نهاية الفترة',
66
82
  thisMonth: 'هذا الشهر',
67
83
  thisYear: 'هذه السنة',
68
84
  previousMonth: 'الشهر السابق',
@@ -79,6 +95,8 @@ const LABELS: Record<Locale, Required<HilalLabels> & { separator: string }> = {
79
95
  hijri: 'Hijri',
80
96
  gregorian: 'Gregorian',
81
97
  today: 'Today',
98
+ rangeStart: 'Start of range',
99
+ rangeEnd: 'End of range',
82
100
  thisMonth: 'This month',
83
101
  thisYear: 'This year',
84
102
  previousMonth: 'Previous month',
@@ -106,6 +124,26 @@ function epochDayOf(date: Date | undefined) {
106
124
  : undefined;
107
125
  }
108
126
 
127
+ /** A DateRange as epoch days, its ends in order; undefined without a start. */
128
+ function rangeOfDates(
129
+ dates: DateRange | undefined
130
+ ): DayRangeSelection | undefined {
131
+ const start = epochDayOf(dates?.start);
132
+ if (start === undefined) {
133
+ return undefined;
134
+ }
135
+ const end = epochDayOf(dates?.end ?? undefined);
136
+ if (end === undefined) {
137
+ return { start };
138
+ }
139
+ return { start: Math.min(start, end), end: Math.max(start, end) };
140
+ }
141
+
142
+ /** The days of a range drawn as selected: its two ends. */
143
+ function isRangeEnd(position: RangePosition | null) {
144
+ return position === 'start' || position === 'end' || position === 'single';
145
+ }
146
+
109
147
  function selectedDateOf(
110
148
  epochDay: number,
111
149
  locale: Locale,
@@ -113,12 +151,27 @@ function selectedDateOf(
113
151
  adjustment: number
114
152
  ): SelectedDate {
115
153
  const hijri = hijriOfEpochDay(epochDay, 'HilalCalendar', adjustment);
154
+ // Formatted on first read: isDateDisabled runs for every day of a
155
+ // range and rarely reads the texts. Enumerable getters, so the object
156
+ // still spreads and serializes like plain data.
157
+ let gregorianText: string | undefined;
158
+ let hijriText: string | undefined;
116
159
  return {
117
160
  gregorian: localDateOfEpochDay(epochDay),
118
161
  hijri,
119
162
  formatted: {
120
- gregorian: formatGregorian(civilFromDays(epochDay), { locale, digits }),
121
- hijri: formatHijri(hijri, { locale, digits }),
163
+ get gregorian() {
164
+ return (gregorianText ??= formatGregorian(civilFromDays(epochDay), {
165
+ locale,
166
+ digits,
167
+ }));
168
+ },
169
+ get hijri() {
170
+ return (hijriText ??= formatHijri(
171
+ hijriOfEpochDay(epochDay, 'HilalCalendar', adjustment),
172
+ { locale, digits }
173
+ ));
174
+ },
122
175
  },
123
176
  };
124
177
  }
@@ -156,6 +209,12 @@ export function HilalCalendar({
156
209
  value,
157
210
  defaultValue,
158
211
  onChange,
212
+ selectionMode = 'single',
213
+ rangeValue,
214
+ defaultRangeValue,
215
+ onRangeChange,
216
+ minRangeDays,
217
+ maxRangeDays,
159
218
  calendar: calendarProp = 'hijri',
160
219
  onCalendarChange,
161
220
  showCalendarToggle = true,
@@ -245,17 +304,31 @@ export function HilalCalendar({
245
304
  );
246
305
  const selectedDay = value !== undefined ? epochDayOf(value) : internalDay;
247
306
 
307
+ // Range selection: controlled through `rangeValue`, otherwise internal.
308
+ const rangeMode = selectionMode === 'range';
309
+ const rangeLimits = checkRangeLimits(minRangeDays, maxRangeDays);
310
+ const [internalRange, setInternalRange] = useState(() =>
311
+ rangeOfDates(defaultRangeValue)
312
+ );
313
+ const pickedRange =
314
+ rangeValue !== undefined
315
+ ? rangeOfDates(rangeValue ?? undefined)
316
+ : internalRange;
317
+ // The day the calendar opens on and follows: the selected day, or the
318
+ // start of the range.
319
+ const anchorDay = rangeMode ? pickedRange?.start : selectedDay;
320
+
248
321
  // Calendar: internal state that follows the prop when the prop changes.
249
322
  const [calendar, setCalendar] = useState(calendarProp);
250
323
  const [lastCalendarProp, setLastCalendarProp] = useState(calendarProp);
251
324
  const [month, setMonth] = useState(() =>
252
325
  monthContaining(
253
- clampDay(selectedDay ?? today, range),
326
+ clampDay(anchorDay ?? today, range),
254
327
  calendarProp,
255
328
  adjustment
256
329
  )
257
330
  );
258
- const [lastSelectedDay, setLastSelectedDay] = useState(selectedDay);
331
+ const [lastAnchorDay, setLastAnchorDay] = useState(anchorDay);
259
332
 
260
333
  // The month and year picker: which grid is shown, the year whose months
261
334
  // are listed, and the first year of the page of years.
@@ -279,7 +352,7 @@ export function HilalCalendar({
279
352
  setView('days');
280
353
  // Keep the selected day in view, or else the month being looked at.
281
354
  const anchor =
282
- selectedDay ?? clampDay(monthStart(current, adjustment), range);
355
+ anchorDay ?? clampDay(monthStart(current, adjustment), range);
283
356
  setMonth(monthContaining(clampDay(anchor, range), next, adjustment));
284
357
  };
285
358
 
@@ -287,7 +360,7 @@ export function HilalCalendar({
287
360
  month,
288
361
  calendar,
289
362
  range,
290
- selectedDay ?? today,
363
+ anchorDay ?? today,
291
364
  adjustment
292
365
  );
293
366
 
@@ -297,14 +370,14 @@ export function HilalCalendar({
297
370
  setLastCalendarProp(calendarProp);
298
371
  switchTo(calendarProp, shown);
299
372
  }
300
- if (selectedDay !== lastSelectedDay) {
301
- setLastSelectedDay(selectedDay);
373
+ if (anchorDay !== lastAnchorDay) {
374
+ setLastAnchorDay(anchorDay);
302
375
  if (
303
- selectedDay !== undefined &&
304
- selectedDay >= range.min &&
305
- selectedDay <= range.max
376
+ anchorDay !== undefined &&
377
+ anchorDay >= range.min &&
378
+ anchorDay <= range.max
306
379
  ) {
307
- const containing = monthContaining(selectedDay, calendar, adjustment);
380
+ const containing = monthContaining(anchorDay, calendar, adjustment);
308
381
  if (containing.year !== shown.year || containing.month !== shown.month) {
309
382
  setMonth(containing);
310
383
  }
@@ -380,6 +453,25 @@ export function HilalCalendar({
380
453
  );
381
454
 
382
455
  const onSelect = useStableCallback((epochDay: number) => {
456
+ if (rangeMode) {
457
+ const dateOf = (day: number) =>
458
+ selectedDateOf(day, locale, digits, adjustment);
459
+ const next = nextRange(
460
+ pickedRange,
461
+ epochDay,
462
+ isDateDisabled && ((day) => isDateDisabled(dateOf(day))),
463
+ rangeLimits
464
+ );
465
+ if (rangeValue === undefined) {
466
+ setInternalRange(next);
467
+ }
468
+ onRangeChange?.({
469
+ start: dateOf(next.start),
470
+ end: next.end === undefined ? null : dateOf(next.end),
471
+ days: rangeLength(next),
472
+ });
473
+ return;
474
+ }
383
475
  if (value === undefined) {
384
476
  setInternalDay(epochDay);
385
477
  }
@@ -394,6 +486,24 @@ export function HilalCalendar({
394
486
  onCalendarChange?.(next);
395
487
  };
396
488
 
489
+ // A day's spoken label: its date, then today and the ends of a range.
490
+ const dayLabel = (cell: { epochDay: number; accessibilityLabel: string }) => {
491
+ const position = rangeMode
492
+ ? rangePosition(pickedRange, cell.epochDay)
493
+ : null;
494
+ const label = withCurrent(
495
+ cell.accessibilityLabel,
496
+ cell.epochDay === today,
497
+ labels.today
498
+ );
499
+ if (position === 'start' || position === 'single') {
500
+ return `${label}${labels.separator}${labels.rangeStart}`;
501
+ }
502
+ return position === 'end'
503
+ ? `${label}${labels.separator}${labels.rangeEnd}`
504
+ : label;
505
+ };
506
+
397
507
  // Today's month and year in the shown calendar, for the picker's ring.
398
508
  const todayInCalendar = safeDateInCalendar(today, calendar, adjustment);
399
509
 
@@ -692,12 +802,29 @@ export function HilalCalendar({
692
802
  <DayCell
693
803
  key={cell.epochDay}
694
804
  {...cell}
695
- accessibilityLabel={withCurrent(
696
- cell.accessibilityLabel,
697
- cell.epochDay === today,
698
- labels.today
699
- )}
700
- selected={cell.epochDay === selectedDay}
805
+ accessibilityLabel={dayLabel(cell)}
806
+ // After the start, days that would make the range too
807
+ // short or too long can't be pressed.
808
+ disabled={
809
+ cell.disabled ||
810
+ (rangeMode &&
811
+ outsideRangeLimits(
812
+ pickedRange,
813
+ cell.epochDay,
814
+ rangeLimits
815
+ ))
816
+ }
817
+ selected={
818
+ rangeMode
819
+ ? isRangeEnd(rangePosition(pickedRange, cell.epochDay))
820
+ : cell.epochDay === selectedDay
821
+ }
822
+ rangePosition={
823
+ rangeMode
824
+ ? rangePosition(pickedRange, cell.epochDay)
825
+ : null
826
+ }
827
+ nextSide={row === 'row' ? 'end' : 'start'}
701
828
  today={cell.epochDay === today}
702
829
  styles={dayStyles}
703
830
  dayStyle={stableDayStyle}
@@ -6,8 +6,10 @@ export {
6
6
  type ThemeProp,
7
7
  } from './theme';
8
8
  export type {
9
+ DateRange,
9
10
  HilalCalendarProps,
10
11
  HilalLabels,
11
12
  HilalStyles,
12
13
  SelectedDate,
14
+ SelectedRange,
13
15
  } from './types';
@@ -0,0 +1,114 @@
1
+ /**
2
+ * Range selection: which days a range covers and how pressing a day
3
+ * changes it. Pure functions on epoch days, no React.
4
+ */
5
+
6
+ /** A picked range of days. `end` is undefined while only the start is picked. */
7
+ export type DayRangeSelection = { start: number; end?: number };
8
+
9
+ /** The fewest and most days a range may have, both ends included. */
10
+ export type RangeLimits = { min: number; max: number };
11
+
12
+ export const NO_RANGE_LIMITS: RangeLimits = { min: 1, max: Infinity };
13
+
14
+ /**
15
+ * Checks minRangeDays and maxRangeDays: whole numbers of at least 1, the
16
+ * minimum no larger than the maximum. Throws a RangeError otherwise.
17
+ */
18
+ export function checkRangeLimits(
19
+ min: number | undefined,
20
+ max: number | undefined
21
+ ): RangeLimits {
22
+ const limits = { min: min ?? 1, max: max ?? Infinity };
23
+ for (const [name, value] of [
24
+ ['minRangeDays', limits.min],
25
+ ['maxRangeDays', limits.max],
26
+ ] as const) {
27
+ if (!(value >= 1 && (Number.isInteger(value) || value === Infinity))) {
28
+ throw new RangeError(
29
+ `HilalCalendar: ${name} must be a whole number of at least 1, got ${value}`
30
+ );
31
+ }
32
+ }
33
+ if (limits.min > limits.max) {
34
+ throw new RangeError(
35
+ `HilalCalendar: minRangeDays (${limits.min}) is larger than maxRangeDays (${limits.max})`
36
+ );
37
+ }
38
+ return limits;
39
+ }
40
+
41
+ /**
42
+ * Whether `day` can't end the range started at `range.start` because the
43
+ * range would be shorter or longer than `limits`. Only days after the
44
+ * start of a range without an end; any other day can be pressed.
45
+ */
46
+ export function outsideRangeLimits(
47
+ range: DayRangeSelection | undefined,
48
+ day: number,
49
+ limits: RangeLimits
50
+ ) {
51
+ if (range === undefined || range.end !== undefined || day <= range.start) {
52
+ return false;
53
+ }
54
+ const length = day - range.start + 1;
55
+ return length < limits.min || length > limits.max;
56
+ }
57
+
58
+ /**
59
+ * The range after pressing `day`. The first press picks the start, the
60
+ * second the end. A press before the start, a press after a complete
61
+ * range, a press across a blocked day, or a press that would make the
62
+ * range shorter or longer than `limits` starts a new range instead.
63
+ */
64
+ export function nextRange(
65
+ current: DayRangeSelection | undefined,
66
+ day: number,
67
+ isBlocked?: (day: number) => boolean,
68
+ limits: RangeLimits = NO_RANGE_LIMITS
69
+ ): DayRangeSelection {
70
+ if (
71
+ current === undefined ||
72
+ current.end !== undefined ||
73
+ day < current.start
74
+ ) {
75
+ return { start: day };
76
+ }
77
+ const length = day - current.start + 1;
78
+ if (length < limits.min || length > limits.max) {
79
+ return { start: day };
80
+ }
81
+ if (isBlocked) {
82
+ for (let between = current.start + 1; between < day; between++) {
83
+ if (isBlocked(between)) {
84
+ return { start: day };
85
+ }
86
+ }
87
+ }
88
+ return { start: current.start, end: day };
89
+ }
90
+
91
+ /** Where a day sits in a range: its ends, inside it, or alone in it. */
92
+ export type RangePosition = 'start' | 'middle' | 'end' | 'single';
93
+
94
+ export function rangePosition(
95
+ range: DayRangeSelection | undefined,
96
+ day: number
97
+ ): RangePosition | null {
98
+ if (range === undefined) {
99
+ return null;
100
+ }
101
+ const end = range.end ?? range.start;
102
+ if (day === range.start) {
103
+ return end === range.start ? 'single' : 'start';
104
+ }
105
+ if (day === end) {
106
+ return 'end';
107
+ }
108
+ return day > range.start && day < end ? 'middle' : null;
109
+ }
110
+
111
+ /** Days in a complete range, both ends included. */
112
+ export function rangeLength(range: DayRangeSelection) {
113
+ return range.end === undefined ? null : range.end - range.start + 1;
114
+ }
@@ -14,6 +14,9 @@ const fill = {
14
14
 
15
15
  export type CalendarStyles = ReturnType<typeof createStyles>;
16
16
 
17
+ /** Space above and below each day cell. */
18
+ const SLOT_PADDING_VERTICAL = 2;
19
+
17
20
  /**
18
21
  * How far the phone's text size setting may grow the text of day cells,
19
22
  * weekday names and picker buttons, which have a fixed size: up to 1.3 a
@@ -121,6 +124,7 @@ const SLOTS = {
121
124
  secondaryDayText: 'secondaryText',
122
125
  pickerItem: 'pickerItem',
123
126
  pickerText: 'pickerText',
127
+ rangeBand: 'rangeBand',
124
128
  } as const;
125
129
 
126
130
  /**
@@ -241,7 +245,16 @@ function baseStyles(theme: HilalTheme) {
241
245
  // than 7 full-size cells, so today's ring never touches the
242
246
  // selected day.
243
247
  paddingHorizontal: 3,
244
- paddingVertical: 2,
248
+ paddingVertical: SLOT_PADDING_VERTICAL,
249
+ },
250
+ // The band behind a range: as tall as a day, across the whole slot so
251
+ // neighbouring days join. A layer with opacity, so any color works.
252
+ rangeBand: {
253
+ backgroundColor: theme.primary,
254
+ bottom: SLOT_PADDING_VERTICAL,
255
+ opacity: 0.15,
256
+ position: 'absolute',
257
+ top: SLOT_PADDING_VERTICAL,
245
258
  },
246
259
  day: {
247
260
  alignItems: 'center',
@@ -13,6 +13,18 @@ export type SelectedDate = {
13
13
  formatted: { gregorian: string; hijri: string };
14
14
  };
15
15
 
16
+ /** A range of days picked in the calendar (`selectionMode="range"`). */
17
+ export type SelectedRange = {
18
+ start: SelectedDate;
19
+ /** Null while only the start is picked. */
20
+ end: SelectedDate | null;
21
+ /** Days in the range, both ends included, or null while `end` is null. */
22
+ days: number | null;
23
+ };
24
+
25
+ /** A range to show as picked. Leave `end` out while only the start is picked. */
26
+ export type DateRange = { start: Date; end?: Date | null };
27
+
16
28
  type ViewSlot = StyleProp<ViewStyle>;
17
29
  type TextSlot = StyleProp<TextStyle>;
18
30
 
@@ -54,6 +66,8 @@ export type HilalStyles = {
54
66
  todayDayText?: TextSlot;
55
67
  /** Both texts of a disabled day. */
56
68
  disabledDayText?: TextSlot;
69
+ /** The band behind the days of a picked range. */
70
+ rangeBand?: ViewSlot;
57
71
  /** Each month or year in the month and year picker. */
58
72
  pickerItem?: ViewSlot;
59
73
  pickerText?: TextSlot;
@@ -70,6 +84,10 @@ export type HilalLabels = {
70
84
  gregorian?: string;
71
85
  /** Read by screen readers after today's date. */
72
86
  today?: string;
87
+ /** Read after the first day of a picked range. */
88
+ rangeStart?: string;
89
+ /** Read after the last day of a picked range. */
90
+ rangeEnd?: string;
73
91
  /** Read after the current month in the month picker. */
74
92
  thisMonth?: string;
75
93
  /** Read after the current year in the year picker. */
@@ -95,6 +113,35 @@ export type HilalCalendarProps = {
95
113
  /** Called when the user picks a day. */
96
114
  onChange?: (date: SelectedDate) => void;
97
115
 
116
+ /**
117
+ * 'single' (default) picks one day. 'range' picks a start and an end:
118
+ * the first press picks the start, the second the end, and a third
119
+ * starts over. A range never crosses a disabled day. In range mode,
120
+ * `value`, `defaultValue` and `onChange` are not used.
121
+ */
122
+ selectionMode?: 'single' | 'range';
123
+ /**
124
+ * Picked range (controlled), with `selectionMode="range"`. `null` shows
125
+ * no range.
126
+ */
127
+ rangeValue?: DateRange | null;
128
+ /** Initially picked range (uncontrolled), with `selectionMode="range"`. */
129
+ defaultRangeValue?: DateRange;
130
+ /** Called when the user changes the range, after each press. */
131
+ onRangeChange?: (range: SelectedRange) => void;
132
+ /**
133
+ * Fewest days a range may have, both ends included (so 3 nights are 4
134
+ * days). After the start is picked, days that would make the range
135
+ * shorter can't be pressed. Default 1.
136
+ */
137
+ minRangeDays?: number;
138
+ /**
139
+ * Most days a range may have, both ends included. After the start is
140
+ * picked, days that would make the range longer can't be pressed.
141
+ * Default: no limit.
142
+ */
143
+ maxRangeDays?: number;
144
+
98
145
  /** Calendar of the month grid. Default 'hijri'. */
99
146
  calendar?: CalendarType;
100
147
  /** Called when the user switches calendars with the toggle. */