@bevelo/date 0.0.0-stage → 0.1.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.
package/dist/index.js ADDED
@@ -0,0 +1,449 @@
1
+ import { a as fromEpochDay, c as toDate, d as assertValidDate, f as assertValidDateTime, g as utcMilliseconds, h as pad, i as fromDate, l as toEpochDay, m as hasIntl, n as dayOfYear, o as isLeapYear, p as assertWeekday, r as daysInMonth, s as isValidDate, t as dayOfWeek } from "./civil-SGLjw0gL.js";
2
+ import { C as startOfMonth, S as startOfDay, _ as endOfWeek, a as offsetAt, b as max, c as zonedParts, d as addMonths, f as addYears, g as endOfMonth, h as eachDay, i as instantFor, l as MAX_RANGE_DAYS, m as differenceInDays, n as dayLength, o as startOfDay$1, p as compare, r as formatInZone, s as zoneIds, t as civilInZone, u as addDays, v as isSameDay, w as startOfWeek, x as min, y as isSameMonth } from "./timezone-BmJA-u4N.js";
3
+ import { dateOrder, datePlaceholder, formatDateInput, parseDateInput, parseTypedDate } from "./pattern.js";
4
+ // src/calendar.ts
5
+ const MONTH_GRID_DEFAULTS = {
6
+ weekStartsOn: 0,
7
+ showOutsideDays: true
8
+ };
9
+ /**
10
+ * Builds the weeks of a month grid.
11
+ *
12
+ * Always 4 to 6 rows and deterministic for the same inputs. With the default
13
+ * `showOutsideDays: true` every row has seven cells; every cell carries a
14
+ * complete CivilDate so a renderer never has to deal with a null or invent a
15
+ * placeholder.
16
+ *
17
+ * When `showOutsideDays` is false, cells of adjacent months are removed from
18
+ * the first and last rows, which can therefore be shorter than seven. This is a
19
+ * deliberate deviation from the seven-column shape: the cell type has no null,
20
+ * so leaving a hole would mean fabricating a date for it, and repacking the days
21
+ * would move Feb 1 out of its weekday column. Callers that need a fixed column
22
+ * count (the common case, and the default) keep outside days and use
23
+ * `inMonth` to blank them.
24
+ */
25
+ function generateMonthGrid(options) {
26
+ const { month } = options;
27
+ assertValidDate(month);
28
+ const weekStartsOn = options.weekStartsOn ?? MONTH_GRID_DEFAULTS.weekStartsOn;
29
+ const showOutsideDays = options.showOutsideDays ?? MONTH_GRID_DEFAULTS.showOutsideDays;
30
+ assertWeekday(weekStartsOn);
31
+ const first = startOfWeek(startOfMonth(month), weekStartsOn);
32
+ const last = endOfWeek(endOfMonth(month), weekStartsOn);
33
+ const start = toEpochDay(first);
34
+ const end = toEpochDay(last);
35
+ const cells = [];
36
+ for (let day = start; day <= end; day += 1) {
37
+ const date = fromEpochDay(day);
38
+ cells.push({
39
+ date,
40
+ inMonth: date.year === month.year && date.month === month.month
41
+ });
42
+ }
43
+ const weeks = [];
44
+ for (let index = 0; index < cells.length; index += 7) {
45
+ const week = cells.slice(index, index + 7);
46
+ weeks.push(showOutsideDays ? week : week.filter((cell) => cell.inMonth));
47
+ }
48
+ return weeks;
49
+ }
50
+ /**
51
+ * The twelve months of a year with their lengths.
52
+ *
53
+ * A year view only needs names (from Intl, in the view) and lengths (here); it
54
+ * does not need 365 dates, so this returns the small summary.
55
+ */
56
+ function generateYear(year) {
57
+ const months = [];
58
+ for (let month = 1; month <= 12; month += 1) months.push({
59
+ month,
60
+ days: daysInMonth(year, month)
61
+ });
62
+ return months;
63
+ }
64
+ /**
65
+ * The ISO-8601 week number of a date.
66
+ *
67
+ * ISO weeks start Monday and week 1 is the week containing January 4, which
68
+ * means late December can belong to the next year's week 1 and early January to
69
+ * the previous year's last week. Computed from the ordinal day and the ISO
70
+ * weekday rather than by counting Thursdays, which is equivalent and shorter.
71
+ */
72
+ function isoWeek(date) {
73
+ assertValidDate(date);
74
+ const sunday = dayOfWeek(date);
75
+ const weekday = sunday === 0 ? 7 : sunday;
76
+ const ordinal = dayOfYear(date);
77
+ const week = Math.floor((ordinal - weekday + 10) / 7);
78
+ if (week < 1) {
79
+ const previousYear = date.year - 1;
80
+ return {
81
+ year: previousYear,
82
+ week: isoWeeksInYear(previousYear)
83
+ };
84
+ }
85
+ if (week > isoWeeksInYear(date.year)) return {
86
+ year: date.year + 1,
87
+ week: 1
88
+ };
89
+ return {
90
+ year: date.year,
91
+ week
92
+ };
93
+ }
94
+ /**
95
+ * Number of ISO weeks in a year: 53 when January 1 is a Thursday, or a Wednesday
96
+ * in a leap year; 52 otherwise.
97
+ *
98
+ * Anchored on January 1 rather than on December 31 so the rule fits in one
99
+ * expression: a year has 53 ISO weeks exactly when it has a Thursday in its
100
+ * final week, which happens when Jan 1 is Thu (or Wed in a leap year).
101
+ */
102
+ function isoWeeksInYear(year) {
103
+ const januaryFirst = dayOfWeek({
104
+ year,
105
+ month: 1,
106
+ day: 1
107
+ });
108
+ const isoJanuaryFirst = januaryFirst === 0 ? 7 : januaryFirst;
109
+ return isoJanuaryFirst === 4 || isLeapYear(year) && isoJanuaryFirst === 3 ? 53 : 52;
110
+ }
111
+ /**
112
+ * Short weekday names in a locale, ordered from `weekStartsOn`.
113
+ *
114
+ * Intl supplies the names (never a hand-rolled table: that is wrong for most
115
+ * locales). When Intl is unavailable or the locale is malformed, the English
116
+ * three-letter names are returned so a calendar still renders instead of
117
+ * throwing over a locale string.
118
+ */
119
+ function weekdayNames(locale, weekStartsOn) {
120
+ assertWeekday(weekStartsOn);
121
+ let base = ENGLISH_WEEKDAYS;
122
+ if (typeof Intl !== "undefined" && typeof Intl.DateTimeFormat === "function") try {
123
+ const formatter = new Intl.DateTimeFormat(locale, {
124
+ weekday: "short",
125
+ timeZone: "UTC"
126
+ });
127
+ base = SUNDAY_OFFSETS.map((offset) => formatter.format(new Date(Date.UTC(2021, 0, 3 + offset))));
128
+ } catch {
129
+ base = ENGLISH_WEEKDAYS;
130
+ }
131
+ return SUNDAY_OFFSETS.map((offset) => {
132
+ return base[(weekStartsOn + offset) % 7] ?? "";
133
+ });
134
+ }
135
+ const SUNDAY_OFFSETS = [
136
+ 0,
137
+ 1,
138
+ 2,
139
+ 3,
140
+ 4,
141
+ 5,
142
+ 6
143
+ ];
144
+ const ENGLISH_WEEKDAYS = [
145
+ "Sun",
146
+ "Mon",
147
+ "Tue",
148
+ "Wed",
149
+ "Thu",
150
+ "Fri",
151
+ "Sat"
152
+ ];
153
+ // src/range.ts
154
+ /**
155
+ * Orders the endpoints, returning a fresh range. Reversed ranges come out of a
156
+ * pointer drag before the user has dragged far enough, so normalizing is the
157
+ * default rather than the caller's responsibility.
158
+ */
159
+ function normalizeRange(range) {
160
+ assertValidDate(range.start);
161
+ assertValidDate(range.end);
162
+ return toEpochDay(range.start) <= toEpochDay(range.end) ? {
163
+ start: { ...range.start },
164
+ end: { ...range.end }
165
+ } : {
166
+ start: { ...range.end },
167
+ end: { ...range.start }
168
+ };
169
+ }
170
+ /** True when `date` is inside the range, endpoints included. */
171
+ function rangeContains(range, date) {
172
+ const normalized = normalizeRange(range);
173
+ const value = toEpochDay(date);
174
+ return toEpochDay(normalized.start) <= value && value <= toEpochDay(normalized.end);
175
+ }
176
+ /**
177
+ * True when the two ranges share at least one day.
178
+ *
179
+ * Inclusive endpoints mean ranges that touch (one ends the day before the other
180
+ * starts) do not overlap; that distinction is what mergeRanges uses.
181
+ */
182
+ function rangesOverlap(a, b) {
183
+ const left = normalizeRange(a);
184
+ const right = normalizeRange(b);
185
+ return toEpochDay(left.start) <= toEpochDay(right.end) && toEpochDay(right.start) <= toEpochDay(left.end);
186
+ }
187
+ /**
188
+ * The days both ranges contain, or undefined when they are disjoint.
189
+ *
190
+ * Undefined rather than an empty range: an empty inclusive range has no
191
+ * representation (end would be the day before start), and callers need to know
192
+ * the difference between "no overlap" and "a range covering zero days".
193
+ */
194
+ function intersectRanges(a, b) {
195
+ const left = normalizeRange(a);
196
+ const right = normalizeRange(b);
197
+ const start = Math.max(toEpochDay(left.start), toEpochDay(right.start));
198
+ const end = Math.min(toEpochDay(left.end), toEpochDay(right.end));
199
+ if (start > end) return;
200
+ return {
201
+ start: fromEpochDay(start),
202
+ end: fromEpochDay(end)
203
+ };
204
+ }
205
+ /**
206
+ * Sorts and coalesces overlapping or adjacent ranges.
207
+ *
208
+ * Adjacent means one range ends the day before the next begins: with inclusive
209
+ * ends, Jan 1-5 and Jan 6-10 are one continuous selection, and showing two chips
210
+ * for it would be wrong. The input array and its dates are not mutated.
211
+ */
212
+ function mergeRanges(list) {
213
+ const sorted = list.map((range) => normalizeRange(range)).sort((a, b) => toEpochDay(a.start) - toEpochDay(b.start));
214
+ const merged = [];
215
+ for (const range of sorted) {
216
+ const last = merged[merged.length - 1];
217
+ if (last !== void 0 && toEpochDay(range.start) <= toEpochDay(last.end) + 1) {
218
+ if (toEpochDay(range.end) > toEpochDay(last.end)) last.end = { ...range.end };
219
+ continue;
220
+ }
221
+ merged.push({
222
+ start: { ...range.start },
223
+ end: { ...range.end }
224
+ });
225
+ }
226
+ return merged;
227
+ }
228
+ /**
229
+ * Clips a range to `bounds`, or undefined when they do not intersect.
230
+ *
231
+ * Clamping rather than shifting: a selection outside the allowed window should
232
+ * shrink to the visible part, not slide into it.
233
+ */
234
+ function clampRange(range, bounds) {
235
+ return intersectRanges(range, bounds);
236
+ }
237
+ /** Number of days in the range, endpoints included; at least 1. */
238
+ function rangeLength(range) {
239
+ const normalized = normalizeRange(range);
240
+ return toEpochDay(normalized.end) - toEpochDay(normalized.start) + 1;
241
+ }
242
+ /** Every day of the range, ascending; capped by eachDay's MAX_RANGE_DAYS. */
243
+ function eachDayInRange(range) {
244
+ const normalized = normalizeRange(range);
245
+ return eachDay(normalized.start, normalized.end);
246
+ }
247
+ // src/format.ts
248
+ const DEFAULT_LOCALE = "en-US";
249
+ const DEFAULT_STYLE = "medium";
250
+ const dateFormatters = /* @__PURE__ */ new Map();
251
+ function dateFormatter(locale, style) {
252
+ const cacheKey = `${locale}\u0000${style}`;
253
+ const cached = dateFormatters.get(cacheKey);
254
+ if (cached !== void 0) return cached;
255
+ const formatter = new Intl.DateTimeFormat(locale, {
256
+ dateStyle: style,
257
+ timeZone: "UTC"
258
+ });
259
+ dateFormatters.set(cacheKey, formatter);
260
+ return formatter;
261
+ }
262
+ /**
263
+ * Formats a date for display.
264
+ *
265
+ * @example formatDate({ year: 2024, month: 3, day: 5 }, { locale: "en-US", style: "long" }) // "March 5, 2024"
266
+ *
267
+ * Falls back to `formatISODate` when Intl is unavailable or the locale is
268
+ * malformed; a stray locale string should not crash a calendar.
269
+ */
270
+ function formatDate(date, options = {}) {
271
+ assertValidDate(date);
272
+ if (!hasIntl()) return formatISODate(date);
273
+ const locale = options.locale ?? DEFAULT_LOCALE;
274
+ const style = options.style ?? DEFAULT_STYLE;
275
+ try {
276
+ return dateFormatter(locale, style).format(utcDate(date));
277
+ } catch (error) {
278
+ if (error instanceof RangeError) return formatISODate(date);
279
+ throw error;
280
+ }
281
+ }
282
+ const rangeFormatters = /* @__PURE__ */ new Map();
283
+ function rangeFormatter(locale) {
284
+ const cached = rangeFormatters.get(locale);
285
+ if (cached !== void 0) return cached;
286
+ const formatter = new Intl.DateTimeFormat(locale, {
287
+ dateStyle: DEFAULT_STYLE,
288
+ timeZone: "UTC"
289
+ });
290
+ rangeFormatters.set(locale, formatter);
291
+ return formatter;
292
+ }
293
+ /**
294
+ * Formats both ends of an inclusive range.
295
+ *
296
+ * The range is normalized first, so a reversed selection still renders in
297
+ * chronological order. Falls back to two ISO dates joined by an en dash when
298
+ * Intl or `formatRange` is missing.
299
+ */
300
+ function formatRange(range, options = {}) {
301
+ const normalized = normalizeRange(range);
302
+ const fallback = `${formatISODate(normalized.start)} – ${formatISODate(normalized.end)}`;
303
+ if (!hasIntl()) return fallback;
304
+ const locale = options.locale ?? DEFAULT_LOCALE;
305
+ try {
306
+ const formatter = rangeFormatter(locale);
307
+ const start = utcDate(normalized.start);
308
+ const end = utcDate(normalized.end);
309
+ if (typeof formatter.formatRange === "function") return formatter.formatRange(start, end);
310
+ return `${formatter.format(start)} – ${formatter.format(end)}`;
311
+ } catch (error) {
312
+ if (error instanceof RangeError) return fallback;
313
+ throw error;
314
+ }
315
+ }
316
+ /**
317
+ * Formats a date relative to `now`.
318
+ *
319
+ * The ladder is deliberate: days under a week, then weeks under a month, then
320
+ * months under a year, then years — so the output stays useful at any distance
321
+ * instead of saying "412 days ago". Rounded with a minimum magnitude of one, so
322
+ * 8 days is "last week" and not "this week". `now` is an argument rather than
323
+ * Date.now() because a relative label must be reproducible in a test.
324
+ *
325
+ * Falls back to the date's ISO form when Intl is unavailable.
326
+ */
327
+ function formatRelative(date, now, options = {}) {
328
+ assertValidDate(date);
329
+ assertValidDate(now);
330
+ if (!hasIntl() || typeof Intl.RelativeTimeFormat !== "function") return formatISODate(date);
331
+ const locale = options.locale ?? DEFAULT_LOCALE;
332
+ const { value, unit } = relativeValue(differenceInDays(now, date));
333
+ try {
334
+ return new Intl.RelativeTimeFormat(locale, { numeric: "auto" }).format(value, unit);
335
+ } catch (error) {
336
+ if (error instanceof RangeError) return formatISODate(date);
337
+ throw error;
338
+ }
339
+ }
340
+ function relativeValue(days) {
341
+ const magnitude = Math.abs(days);
342
+ const sign = days < 0 ? -1 : 1;
343
+ if (magnitude < 7) return {
344
+ value: days,
345
+ unit: "day"
346
+ };
347
+ if (magnitude < 30) return {
348
+ value: sign * Math.max(1, Math.round(magnitude / 7)),
349
+ unit: "week"
350
+ };
351
+ if (magnitude < 365) return {
352
+ value: sign * Math.max(1, Math.round(magnitude / 30.4375)),
353
+ unit: "month"
354
+ };
355
+ return {
356
+ value: sign * Math.max(1, Math.round(magnitude / 365.25)),
357
+ unit: "year"
358
+ };
359
+ }
360
+ /**
361
+ * Parses a date string, returning undefined instead of throwing.
362
+ *
363
+ * ISO `YYYY-MM-DD` (including expanded years like `+010000-01-01`) is tried
364
+ * first because it is unambiguous. Then the locale's numeric form is tried, in
365
+ * the field order Intl reports for that locale (`dateOrder`, from pattern.ts):
366
+ * "3/5/2024" is March 5 in en-US and "05/03/2024" is March 5 in en-GB. Only
367
+ * four-digit years are accepted, so a 2-digit year can never be silently
368
+ * reinterpreted. A malformed tag falls back to that function's ISO order, the
369
+ * same floor `formatDate` uses, so reading and writing agree.
370
+ *
371
+ * Undefined is the contract rather than an exception: this runs on every
372
+ * keystroke of a date input.
373
+ */
374
+ function parseDate(input, options = {}) {
375
+ if (typeof input !== "string") return;
376
+ const value = input.trim();
377
+ if (value === "") return;
378
+ const iso = parseIso(value);
379
+ if (iso !== void 0) return iso;
380
+ if (!hasIntl()) return;
381
+ const order = dateOrder(options.locale ?? DEFAULT_LOCALE);
382
+ if (!/^\d/.test(value) || !/\d$/.test(value)) return;
383
+ const tokens = value.split(/\D+/);
384
+ if (tokens.length !== 3) return;
385
+ const fields = {};
386
+ for (const [index, field] of order.entries()) {
387
+ const token = tokens[index];
388
+ if (token === void 0) return;
389
+ if (field === "year" ? !/^\d{4}$/.test(token) : !/^\d{1,2}$/.test(token)) return;
390
+ fields[field] = Number(token);
391
+ }
392
+ const candidate = {
393
+ year: fields.year,
394
+ month: fields.month,
395
+ day: fields.day
396
+ };
397
+ return isValidDate(candidate) ? candidate : void 0;
398
+ }
399
+ /**
400
+ * ISO 8601 date, e.g. "2024-03-05".
401
+ *
402
+ * Years outside 0..9999 use the expanded form ("+010000", "-000001") so the
403
+ * string always round-trips through the expanded-year parser.
404
+ */
405
+ function formatISODate(date) {
406
+ assertValidDate(date);
407
+ return `${isoYear(date.year)}-${pad(date.month, 2)}-${pad(date.day, 2)}`;
408
+ }
409
+ /**
410
+ * ISO 8601 date-time without a zone suffix, e.g. "2024-03-05T09:07:00.005".
411
+ *
412
+ * No "Z": a civil date-time names a wall clock, not an instant, and appending Z
413
+ * would be a lie about a timezone this type does not have.
414
+ */
415
+ function formatISODateTime(value) {
416
+ assertValidDateTime(value);
417
+ const { time } = value;
418
+ return `${formatISODate(value.date)}T${pad(time.hour, 2)}:${pad(time.minute, 2)}:${pad(time.second, 2)}.${pad(time.millisecond, 3)}`;
419
+ }
420
+ function isoYear(year) {
421
+ if (year >= 0 && year <= 9999) return pad(year, 4);
422
+ return year < 0 ? `-${pad(-year, 6)}` : `+${pad(year, 6)}`;
423
+ }
424
+ function parseIso(value) {
425
+ const standard = /^(\d{4})-(\d{2})-(\d{2})$/.exec(value);
426
+ if (standard !== null) return validOrUndefined(Number(standard[1]), Number(standard[2]), Number(standard[3]));
427
+ const expanded = /^([+-]\d{6})-(\d{2})-(\d{2})$/.exec(value);
428
+ if (expanded !== null) return validOrUndefined(Number(expanded[1]), Number(expanded[2]), Number(expanded[3]));
429
+ }
430
+ function validOrUndefined(year, month, day) {
431
+ const candidate = {
432
+ year,
433
+ month,
434
+ day
435
+ };
436
+ return isValidDate(candidate) ? candidate : void 0;
437
+ }
438
+ function utcDate(date) {
439
+ return new Date(utcMilliseconds({
440
+ date,
441
+ time: {
442
+ hour: 0,
443
+ minute: 0,
444
+ second: 0,
445
+ millisecond: 0
446
+ }
447
+ }));
448
+ }
449
+ export { MAX_RANGE_DAYS, addDays, addMonths, addYears, civilInZone, clampRange, compare, dateOrder, datePlaceholder, dayLength, dayOfWeek, dayOfYear, daysInMonth, differenceInDays, eachDay, eachDayInRange, endOfMonth, endOfWeek, formatDate, formatDateInput, formatISODate, formatISODateTime, formatInZone, formatRange, formatRelative, fromDate, fromEpochDay, generateMonthGrid, generateYear, instantFor, intersectRanges, isLeapYear, isSameDay, isSameMonth, isValidDate, isoWeek, isoWeeksInYear, max, mergeRanges, min, normalizeRange, offsetAt, parseDate, parseDateInput, parseTypedDate, rangeContains, rangeLength, rangesOverlap, startOfDay, startOfDay$1 as startOfDayInZone, startOfMonth, startOfWeek, toDate, toEpochDay, weekdayNames, zoneIds, zonedParts };