@tristan2828/ui-foundation 4.94.0 → 4.95.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 CHANGED
@@ -93,6 +93,10 @@ export { ImageField } from './components/app/image-field.js';
93
93
  export { DEFAULT_IMAGE_TYPES } from './lib/image-file.js';
94
94
  export { formatPlainDate, parsePlainDate, plainDateExamples, unreadableDateMessage, } from './lib/plain-date.js';
95
95
  export { formatMonthDay, isMonthDay, monthDayProblem } from './lib/month-day.js';
96
+ export { RecurrenceField } from './components/app/recurrence-field.js';
97
+ export { atLocal, formatRule, nextAfterCompletion, nextOccurrence, nextOccurrences, normalizeRecurrence, parseRule, RecurrenceError, recurrenceFromWeekdays, recurrenceProblem, } from './lib/recurrence.js';
98
+ export { parseRecurrencePhrase, recurrencePhrase, } from './lib/recurrence-phrase.js';
99
+ export { formatOccurrence, formatRecurrence, todayIn, } from './lib/recurrence-format.js';
96
100
  export { ChoiceCell, LinkCell, LinkOut, NameCell, } from './components/app/row-edit-cells.js';
97
101
  export { ModuleCard, ModuleStrip, } from './components/app/module-card.js';
98
102
  export { WidgetCard, WidgetCardGroup, WidgetList, WidgetListItem, } from './components/app/widget-card.js';
@@ -0,0 +1,26 @@
1
+ import { type Recurrence } from './recurrence.js';
2
+ export type RecurrenceFormatOptions = {
3
+ locale?: string;
4
+ /** Leave the times out ("Every 2nd Tue"), for a cell beside a separate time. */
5
+ times?: boolean;
6
+ };
7
+ /**
8
+ * The repeat's label: its days, "after done" when it repeats from
9
+ * completion, its times, and how it ends. "Every 2nd Tue at 9:00 AM",
10
+ * "Every 3 days after done, at 9:00 AM", "Every weekday at 8:00 AM and
11
+ * 5:30 PM, until Mar 1, 2027", "Every day at 9:00 AM, 10 times". A rule
12
+ * it can't read shows as stored.
13
+ */
14
+ export declare function formatRecurrence(value: Recurrence, options?: RecurrenceFormatOptions): string;
15
+ export type OccurrenceFormatOptions = {
16
+ locale?: string;
17
+ /** What "now" is, for leaving out this year. Defaults to the clock. */
18
+ now?: Date;
19
+ };
20
+ /**
21
+ * One occurrence's day and time in the rule's zone: "Tue, Dec 8, 9:00 AM",
22
+ * with the year when it isn't this year's.
23
+ */
24
+ export declare function formatOccurrence(moment: Date, timeZone: string, options?: OccurrenceFormatOptions): string;
25
+ /** Today's date in `timeZone`, `'YYYY-MM-DD'`: where a phrase's days count from. */
26
+ export declare function todayIn(timeZone: string, now?: Date): string;
@@ -0,0 +1,139 @@
1
+ // A repeat in words (#326): its label for a list's Repeats cell and the
2
+ // field's preview ("Every 2nd Tue at 9:00 AM"), and an occurrence's
3
+ // date and time for a Next cell ("Tue, Dec 8, 9:00 AM"), both read in the
4
+ // rule's own zone. Day and month names and times come from Intl, in the
5
+ // locale given (the browser's when left out); the words around them are
6
+ // English, like the rest of the package.
7
+ import { listWords, ordinalWord } from './recurrence-phrase.js';
8
+ import { parseRule, wallClock } from './recurrence.js';
9
+ const WEEKDAYS_MO_FR = [0, 1, 2, 3, 4];
10
+ function dayName(day, locale, width = 'short') {
11
+ // 2024-01-01 was a Monday.
12
+ return new Intl.DateTimeFormat(locale, { weekday: width, timeZone: 'UTC' }).format(Date.UTC(2024, 0, 1 + day));
13
+ }
14
+ function monthDay(month, day, locale) {
15
+ return new Intl.DateTimeFormat(locale, { month: 'short', day: 'numeric', timeZone: 'UTC' }).format(Date.UTC(2024, month - 1, day));
16
+ }
17
+ function plainDay(value, locale) {
18
+ return new Intl.DateTimeFormat(locale, { dateStyle: 'medium', timeZone: 'UTC' }).format(Date.parse(`${value}T00:00:00Z`));
19
+ }
20
+ function clock(time, locale) {
21
+ return new Intl.DateTimeFormat(locale, { hour: 'numeric', minute: '2-digit', timeZone: 'UTC' }).format(Date.parse(`2024-01-01T${time}:00Z`));
22
+ }
23
+ function every(parts, unit) {
24
+ if (parts.interval === 1)
25
+ return `Every ${unit}`;
26
+ if (parts.interval === 2)
27
+ return `Every other ${unit}`;
28
+ return `Every ${parts.interval} ${unit}s`;
29
+ }
30
+ function nthDay(nth, day, locale) {
31
+ return `${nth === -1 ? 'last' : nth < -1 ? `${ordinalWord(-nth)} to last` : ordinalWord(nth)} ${dayName(day, locale)}`;
32
+ }
33
+ function monthDayWord(day) {
34
+ return day === -1 ? 'last day' : day < -1 ? `${ordinalWord(-day)} to last day` : ordinalWord(day);
35
+ }
36
+ /** The days part: "Every 2nd Tue", "Every weekday", "Every 3 months on the 15th". */
37
+ function days(parts, start, locale) {
38
+ const [, startMonth, startDay] = start.split('-').map(Number);
39
+ const startWeekday = (new Date(`${start}T00:00:00Z`).getUTCDay() + 6) % 7;
40
+ const weekdays = parts.byDay.filter(({ nth }) => nth === null).map(({ day }) => day);
41
+ const nths = parts.byDay.filter(({ nth }) => nth !== null);
42
+ const inMonths = parts.byMonth.length && parts.freq !== 'YEARLY' ? ` in ${listWords(parts.byMonth.map((month) => monthName(month, locale)))}` : '';
43
+ switch (parts.freq) {
44
+ case 'DAILY':
45
+ return `${every(parts, 'day')}${inMonths}`;
46
+ case 'WEEKLY': {
47
+ const chosen = weekdays.length ? weekdays : [startWeekday];
48
+ const names = listWords(chosen.map((day) => dayName(day, locale)));
49
+ if (parts.interval === 1) {
50
+ if (chosen.join() === WEEKDAYS_MO_FR.join())
51
+ return `Every weekday${inMonths}`;
52
+ if (chosen.join() === '5,6')
53
+ return `Every weekend${inMonths}`;
54
+ return `Every ${names}${inMonths}`;
55
+ }
56
+ return `${every(parts, 'week')} on ${names}${inMonths}`;
57
+ }
58
+ case 'MONTHLY': {
59
+ const on = nths.length
60
+ ? listWords(nths.map(({ nth, day }) => nthDay(nth, day, locale)))
61
+ : parts.byMonthDay.length
62
+ ? listWords(parts.byMonthDay.map(monthDayWord))
63
+ : weekdays.length
64
+ ? `every ${listWords(weekdays.map((day) => dayName(day, locale)))}`
65
+ : ordinalWord(startDay);
66
+ if (parts.interval === 1) {
67
+ if (parts.byMonthDay.length === 1 && parts.byMonthDay[0] === -1 && !nths.length)
68
+ return `Every last day of the month${inMonths}`;
69
+ if (weekdays.length && !nths.length && !parts.byMonthDay.length)
70
+ return `Every ${listWords(weekdays.map((day) => dayName(day, locale)))}${inMonths}`;
71
+ return `Every ${on}${inMonths}`;
72
+ }
73
+ return `${every(parts, 'month')} on the ${on}${inMonths}`;
74
+ }
75
+ case 'YEARLY': {
76
+ const months = parts.byMonth.length ? parts.byMonth : [startMonth];
77
+ if (nths.length) {
78
+ const on = listWords(nths.map(({ nth, day }) => nthDay(nth, day, locale)));
79
+ const of = listWords(months.map((month) => monthName(month, locale)));
80
+ return parts.interval === 1 ? `Every ${on} of ${of}` : `${every(parts, 'year')} on the ${on} of ${of}`;
81
+ }
82
+ const monthDays = parts.byMonthDay.length ? parts.byMonthDay : [startDay];
83
+ const dates = months.flatMap((month) => monthDays.map((day) => (day > 0 ? monthDay(month, day, locale) : `the ${monthDayWord(day)} of ${monthName(month, locale)}`)));
84
+ return parts.interval === 1 ? `Every ${listWords(dates)}` : `${every(parts, 'year')} on ${listWords(dates)}`;
85
+ }
86
+ }
87
+ }
88
+ function monthName(month, locale) {
89
+ return new Intl.DateTimeFormat(locale, { month: 'short', timeZone: 'UTC' }).format(Date.UTC(2024, month - 1, 1));
90
+ }
91
+ /**
92
+ * The repeat's label: its days, "after done" when it repeats from
93
+ * completion, its times, and how it ends. "Every 2nd Tue at 9:00 AM",
94
+ * "Every 3 days after done, at 9:00 AM", "Every weekday at 8:00 AM and
95
+ * 5:30 PM, until Mar 1, 2027", "Every day at 9:00 AM, 10 times". A rule
96
+ * it can't read shows as stored.
97
+ */
98
+ export function formatRecurrence(value, options = {}) {
99
+ let parts;
100
+ try {
101
+ parts = parseRule(value.rule);
102
+ }
103
+ catch {
104
+ return value.rule;
105
+ }
106
+ const { locale } = options;
107
+ let label = days(parts, value.start, locale);
108
+ if (value.fromCompletion)
109
+ label += ' after done';
110
+ if (options.times !== false && value.times.length) {
111
+ label += `${value.fromCompletion ? ',' : ''} at ${listWords(value.times.map((time) => clock(time, locale)))}`;
112
+ }
113
+ if (parts.until)
114
+ label += `, until ${plainDay(parts.until, locale)}`;
115
+ if (parts.count !== null)
116
+ label += `, ${parts.count} ${parts.count === 1 ? 'time' : 'times'}`;
117
+ return label;
118
+ }
119
+ /**
120
+ * One occurrence's day and time in the rule's zone: "Tue, Dec 8, 9:00 AM",
121
+ * with the year when it isn't this year's.
122
+ */
123
+ export function formatOccurrence(moment, timeZone, options = {}) {
124
+ const thisYear = wallClock(options.now ?? new Date(), timeZone).day.slice(0, 4);
125
+ const year = wallClock(moment, timeZone).day.slice(0, 4);
126
+ return new Intl.DateTimeFormat(options.locale, {
127
+ timeZone,
128
+ weekday: 'short',
129
+ month: 'short',
130
+ day: 'numeric',
131
+ year: year === thisYear ? undefined : 'numeric',
132
+ hour: 'numeric',
133
+ minute: '2-digit',
134
+ }).format(moment);
135
+ }
136
+ /** Today's date in `timeZone`, `'YYYY-MM-DD'`: where a phrase's days count from. */
137
+ export function todayIn(timeZone, now = new Date()) {
138
+ return wallClock(now, timeZone).day;
139
+ }
@@ -0,0 +1,33 @@
1
+ import { type Recurrence } from './recurrence.js';
2
+ export type PhraseOptions = {
3
+ /** Today, `'YYYY-MM-DD'` in the rule's zone: where a day with no year counts from. */
4
+ today: string;
5
+ /** The IANA zone the rule is read in. */
6
+ timeZone: string;
7
+ /** The times when the phrase has no "at" (the field's current ones). Defaults to 09:00. */
8
+ times?: string[];
9
+ /** The start when the phrase has no "starting". Defaults to `today`. */
10
+ start?: string;
11
+ };
12
+ export type PhraseResult = {
13
+ ok: true;
14
+ value: Recurrence;
15
+ } | {
16
+ ok: false;
17
+ error: string;
18
+ };
19
+ /**
20
+ * Reads a phrase into a Recurrence, or says why it can't. Live as you
21
+ * type: call it on every change and show the result's label or its error.
22
+ */
23
+ export declare function parseRecurrencePhrase(text: string, options: PhraseOptions): PhraseResult;
24
+ declare const ordinal: (value: number) => string;
25
+ declare const listWords: (words: string[], and?: string) => string;
26
+ /**
27
+ * The Recurrence as a phrase parseRecurrencePhrase reads back to it
28
+ * ("every 2nd tue at 9am until mar 1"), or null for a rule it can't say
29
+ * (several month days, BYMONTH on a daily rule). The start is said only
30
+ * when it's after `today`.
31
+ */
32
+ export declare function recurrencePhrase(value: Recurrence, today?: string): string | null;
33
+ export { ordinal as ordinalWord, listWords };
@@ -0,0 +1,466 @@
1
+ // How a repeat is typed (#326): a task app's phrases ("every 2nd tue at
2
+ // 9am", "every! 3 days", "every jan 1 until mar 1") read into a Recurrence
3
+ // as you type, with a clear refusal for what can't be read, and the way
4
+ // back, a Recurrence written as a phrase the reader takes again.
5
+ //
6
+ // What it reads, after "every" (or "every!", repeat from when it's done):
7
+ //
8
+ // - an interval: `day`, `3 days`, `other week`, `2 months`, `year`
9
+ // (`daily`, `weekly`, `monthly`, `yearly` alone too); a week can take
10
+ // `on mon, fri`, a month `on the 15th`, `on the 2nd tue`, `on the last day`
11
+ // - weekdays: `weekday`, `weekend`, `mon`, `mon, wed and fri`, `other tue`
12
+ // - a day of the month: `15th`, `2nd tue`, `last fri`, `last day of the month`
13
+ // - a day of the year: `jan 1`, `1 jan`
14
+ //
15
+ // then, in any order: `at 9am, 5:30pm` (`noon`, `17:00`), `starting dec 1`
16
+ // (`from`), `until mar 1` (`ending`), `for 10 times`. A day with no year is
17
+ // the next one: from today for `starting`, from the start for `until`.
18
+ import { normalizeRecurrence, RecurrenceError, formatRule, parseRule, WEEKDAY_CODES } from './recurrence.js';
19
+ const WEEKDAY_WORDS = [
20
+ [/^mon(day)?$/, 0],
21
+ [/^tue(s|sday)?$/, 1],
22
+ [/^wed(s|nesday)?$/, 2],
23
+ [/^thu(r|rs|rsday)?$/, 3],
24
+ [/^fri(day)?$/, 4],
25
+ [/^sat(urday)?$/, 5],
26
+ [/^sun(day)?$/, 6],
27
+ ];
28
+ const MONTH_WORDS = ['jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'dec'];
29
+ const ORDINAL_WORDS = { first: 1, second: 2, third: 3, fourth: 4, fifth: 5, last: -1 };
30
+ const WEEKDAY = String.raw `(?:mon(?:day)?|tue(?:s|sday)?|wed(?:s|nesday)?|thu(?:r|rs|rsday)?|fri(?:day)?|sat(?:urday)?|sun(?:day)?)`;
31
+ const MONTH = String.raw `(?:jan(?:uary)?|feb(?:ruary)?|mar(?:ch)?|apr(?:il)?|may|june?|july?|aug(?:ust)?|sep(?:t|tember)?|oct(?:ober)?|nov(?:ember)?|dec(?:ember)?)`;
32
+ const ORDINAL = String.raw `(?:(\d{1,2})(?:st|nd|rd|th)|first|second|third|fourth|fifth|last)`;
33
+ const EXAMPLES = '“every 3 days”, “every 2nd tue” or “every jan 1”';
34
+ const weekdayOf = (word) => WEEKDAY_WORDS.find(([pattern]) => pattern.test(word))?.[1] ?? -1;
35
+ const monthOf = (word) => MONTH_WORDS.indexOf(word.slice(0, 3)) + 1;
36
+ const pad = (value) => String(value).padStart(2, '0');
37
+ class Refusal extends Error {
38
+ }
39
+ /** A cursor over the phrase: each read skips spaces first and either matches where it is or moves nothing. */
40
+ class Reader {
41
+ at = 0;
42
+ text;
43
+ constructor(text) {
44
+ this.text = text;
45
+ }
46
+ read(pattern) {
47
+ const expression = new RegExp(String.raw `\s*(?:${pattern})(?![a-z0-9])`, 'y');
48
+ expression.lastIndex = this.at;
49
+ const match = expression.exec(this.text);
50
+ if (match)
51
+ this.at = expression.lastIndex;
52
+ return match;
53
+ }
54
+ get done() {
55
+ return this.text.slice(this.at).trim() === '';
56
+ }
57
+ get rest() {
58
+ return this.text.slice(this.at).trim();
59
+ }
60
+ }
61
+ function ordinalValue(word, digits) {
62
+ return digits ? Number(digits) : ORDINAL_WORDS[word];
63
+ }
64
+ function weekdayList(reader) {
65
+ const first = reader.read(WEEKDAY);
66
+ if (!first)
67
+ return [];
68
+ const days = [weekdayOf(first[0].trim())];
69
+ for (;;) {
70
+ const mark = reader.at;
71
+ const next = reader.read(String.raw `(?:,\s*and|,|and|&)\s*(${WEEKDAY})`);
72
+ if (!next) {
73
+ reader.at = mark;
74
+ break;
75
+ }
76
+ days.push(weekdayOf(next[1]));
77
+ }
78
+ return [...new Set(days)].sort();
79
+ }
80
+ function checkNth(nth, text) {
81
+ if (nth === 0 || nth > 5)
82
+ throw new Refusal(`“${text}”: a month has at most five of a weekday.`);
83
+ return nth;
84
+ }
85
+ function checkMonthDay(day) {
86
+ if (day < 1 || day > 31)
87
+ throw new Refusal('A month has at most 31 days.');
88
+ return day;
89
+ }
90
+ /** What comes after "every": the rule's frequency and days. */
91
+ function readBody(reader) {
92
+ const base = { freq: 'DAILY', interval: 1, byDay: [], byMonthDay: [], byMonth: [] };
93
+ let match = reader.read(String.raw `(\d+|other)\s+(day|week|month|year)s?`);
94
+ if (match) {
95
+ const interval = match[1] === 'other' ? 2 : Number(match[1]);
96
+ if (interval < 1)
97
+ throw new Refusal(`“every ${match[1]} ${match[2]}s” never comes round.`);
98
+ if (interval > 999)
99
+ throw new Refusal('That interval is too long.');
100
+ return readOn(reader, { ...base, interval, freq: unit(match[2]) });
101
+ }
102
+ match = reader.read(String.raw `(day|week|month|year)`);
103
+ if (match)
104
+ return readOn(reader, { ...base, freq: unit(match[1]) });
105
+ if (reader.read(String.raw `(?:weekday|workday)s?`))
106
+ return { ...base, freq: 'WEEKLY', byDay: [0, 1, 2, 3, 4].map(plainDay) };
107
+ if (reader.read(String.raw `weekends?`))
108
+ return { ...base, freq: 'WEEKLY', byDay: [5, 6].map(plainDay) };
109
+ match = reader.read(String.raw `last\s+day(?:\s+of\s+(?:the\s+)?month)?`);
110
+ if (match)
111
+ return { ...base, freq: 'MONTHLY', byMonthDay: [-1] };
112
+ match = reader.read(String.raw `${ORDINAL}\s+(${WEEKDAY})(?:\s+of\s+(?:the\s+|every\s+)?month)?`);
113
+ if (match) {
114
+ const word = match[0].trim().split(/\s+/)[0];
115
+ const nth = checkNth(ordinalValue(word, match[1]), match[0].trim());
116
+ return { ...base, freq: 'MONTHLY', byDay: [{ nth, day: weekdayOf(match[2]) }] };
117
+ }
118
+ match = reader.read(String.raw `(\d{1,2})(?:st|nd|rd|th)?\s+(${MONTH})|(${MONTH})\s+(\d{1,2})(?:st|nd|rd|th)?`);
119
+ if (match) {
120
+ const month = monthOf(match[2] ?? match[3]);
121
+ const day = Number(match[1] ?? match[4]);
122
+ if (day < 1 || day > [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month - 1]) {
123
+ throw new Refusal(`“${match[0].trim()}” isn't a day of the year.`);
124
+ }
125
+ return { ...base, freq: 'YEARLY', byMonth: [month], byMonthDay: [day] };
126
+ }
127
+ match = reader.read(String.raw `(\d{1,2})(?:st|nd|rd|th)(?:\s+day)?(?:\s+of\s+(?:the\s+|every\s+)?month)?`);
128
+ if (match)
129
+ return { ...base, freq: 'MONTHLY', byMonthDay: [checkMonthDay(Number(match[1]))] };
130
+ if (reader.read('other')) {
131
+ const days = weekdayList(reader);
132
+ if (!days.length)
133
+ throw new Refusal('Say which day after “every other”, like “every other tue”, or “every other week”.');
134
+ return { ...base, freq: 'WEEKLY', interval: 2, byDay: days.map(plainDay) };
135
+ }
136
+ const days = weekdayList(reader);
137
+ if (days.length)
138
+ return { ...base, freq: 'WEEKLY', byDay: days.map(plainDay) };
139
+ throw new Refusal(unread(reader));
140
+ }
141
+ const plainDay = (day) => ({ nth: null, day });
142
+ const unit = (word) => word === 'day' ? 'DAILY' : word === 'week' ? 'WEEKLY' : word === 'month' ? 'MONTHLY' : 'YEARLY';
143
+ /** A week's "on mon, fri", a month's "on the 15th" / "on the 2nd tue" / "on the last day". */
144
+ function readOn(reader, body) {
145
+ if (body.freq === 'WEEKLY') {
146
+ const mark = reader.at;
147
+ if (reader.read('on')) {
148
+ const days = weekdayList(reader);
149
+ if (!days.length)
150
+ throw new Refusal('Say which day after “on”, like “every week on mon”.');
151
+ return { ...body, byDay: days.map(plainDay) };
152
+ }
153
+ reader.at = mark;
154
+ }
155
+ if (body.freq === 'MONTHLY') {
156
+ const mark = reader.at;
157
+ if (reader.read(String.raw `on(?:\s+the)?`)) {
158
+ if (reader.read(String.raw `last\s+day`))
159
+ return { ...body, byMonthDay: [-1] };
160
+ const nth = reader.read(String.raw `${ORDINAL}\s+(${WEEKDAY})`);
161
+ if (nth) {
162
+ const word = nth[0].trim().split(/\s+/)[0];
163
+ return { ...body, byDay: [{ nth: checkNth(ordinalValue(word, nth[1]), nth[0].trim()), day: weekdayOf(nth[2]) }] };
164
+ }
165
+ const day = reader.read(String.raw `(\d{1,2})(?:st|nd|rd|th)?`);
166
+ if (day)
167
+ return { ...body, byMonthDay: [checkMonthDay(Number(day[1]))] };
168
+ throw new Refusal('Say which day after “on the”, like “every month on the 15th”.');
169
+ }
170
+ reader.at = mark;
171
+ }
172
+ return body;
173
+ }
174
+ function unread(reader) {
175
+ const word = reader.rest.split(/[\s,]+/).slice(0, 3).join(' ');
176
+ return `Couldn't read “${word}”. Try ${EXAMPLES}.`;
177
+ }
178
+ function readTime(reader) {
179
+ const match = reader.read(String.raw `noon|midnight|(\d{1,2})(?::(\d{2}))?\s*(am|pm|a\.m\.|p\.m\.|a|p)?`);
180
+ if (!match)
181
+ return null;
182
+ const word = match[0].trim();
183
+ if (word === 'noon')
184
+ return '12:00';
185
+ if (word === 'midnight')
186
+ return '00:00';
187
+ let hour = Number(match[1]);
188
+ const minute = match[2] ? Number(match[2]) : 0;
189
+ const half = match[3]?.[0];
190
+ if (half) {
191
+ if (hour < 1 || hour > 12)
192
+ throw new Refusal(`“${word}” isn't a time of day.`);
193
+ hour = (hour % 12) + (half === 'p' ? 12 : 0);
194
+ }
195
+ if (hour > 23 || minute > 59)
196
+ throw new Refusal(`“${word}” isn't a time of day.`);
197
+ return `${pad(hour)}:${pad(minute)}`;
198
+ }
199
+ function readTimes(reader) {
200
+ const first = readTime(reader);
201
+ if (!first)
202
+ throw new Refusal('Say a time after “at”, like “at 9am”.');
203
+ const times = [first];
204
+ for (;;) {
205
+ const mark = reader.at;
206
+ if (!reader.read(String.raw `,\s*and|,|and|&`))
207
+ break;
208
+ const next = readTime(reader);
209
+ if (!next) {
210
+ reader.at = mark;
211
+ break;
212
+ }
213
+ times.push(next);
214
+ }
215
+ return times;
216
+ }
217
+ const isLeap = (year) => (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;
218
+ const DAYS_IN = (year, month) => [31, isLeap(year) ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month - 1];
219
+ function addDays(day, count) {
220
+ return new Date(Date.parse(`${day}T00:00:00Z`) + count * 86_400_000).toISOString().slice(0, 10);
221
+ }
222
+ /** A day: `today`, `tomorrow`, `2026-12-01`, `dec 1`, `1 dec`, `dec 1, 2027`; no year is the next one on or after `from`. */
223
+ function readDate(reader, from, after) {
224
+ if (reader.read('today'))
225
+ return from;
226
+ if (reader.read('tomorrow'))
227
+ return addDays(from, 1);
228
+ const iso = reader.read(String.raw `(\d{4})-(\d{2})-(\d{2})`);
229
+ if (iso) {
230
+ const [year, month, day] = [Number(iso[1]), Number(iso[2]), Number(iso[3])];
231
+ if (month < 1 || month > 12 || day < 1 || day > DAYS_IN(year, month))
232
+ throw new Refusal(`“${iso[0].trim()}” isn't a day.`);
233
+ return iso[0].trim();
234
+ }
235
+ const match = reader.read(String.raw `(?:(${MONTH})\s+(\d{1,2})(?:st|nd|rd|th)?|(\d{1,2})(?:st|nd|rd|th)?\s+(${MONTH}))(?:,?\s+(\d{4}))?`);
236
+ if (!match)
237
+ throw new Refusal(`Say a day after “${after}”, like “${after} dec 1”.`);
238
+ const month = monthOf(match[1] ?? match[4]);
239
+ const day = Number(match[2] ?? match[3]);
240
+ const text = match[0].trim();
241
+ if (match[5]) {
242
+ const year = Number(match[5]);
243
+ if (day < 1 || day > DAYS_IN(year, month))
244
+ throw new Refusal(`“${text}” isn't a day.`);
245
+ return `${year}-${pad(month)}-${pad(day)}`;
246
+ }
247
+ if (day < 1 || day > (month === 2 ? 29 : DAYS_IN(2001, month)))
248
+ throw new Refusal(`“${text}” isn't a day.`);
249
+ // The next one on or after `from` (Feb 29: the next leap year's).
250
+ for (let year = Number(from.slice(0, 4));; year++) {
251
+ if (day > DAYS_IN(year, month))
252
+ continue;
253
+ const candidate = `${year}-${pad(month)}-${pad(day)}`;
254
+ if (candidate >= from)
255
+ return candidate;
256
+ }
257
+ }
258
+ /**
259
+ * Reads a phrase into a Recurrence, or says why it can't. Live as you
260
+ * type: call it on every change and show the result's label or its error.
261
+ */
262
+ export function parseRecurrencePhrase(text, options) {
263
+ try {
264
+ return { ok: true, value: readPhrase(text, options) };
265
+ }
266
+ catch (error) {
267
+ if (error instanceof Refusal || error instanceof RecurrenceError)
268
+ return { ok: false, error: error.message };
269
+ throw error;
270
+ }
271
+ }
272
+ function readPhrase(text, options) {
273
+ const normal = text.toLowerCase().replace(/[’']/g, "'").replace(/\s+/g, ' ').trim().replace(/[.]$/, '');
274
+ if (!normal)
275
+ throw new Refusal(`Type how it repeats, like ${EXAMPLES}.`);
276
+ const reader = new Reader(normal);
277
+ let fromCompletion = false;
278
+ let body;
279
+ const shortcut = reader.read(String.raw `(daily|weekly|monthly|yearly|annually|weekdays)`);
280
+ if (shortcut) {
281
+ const word = shortcut[1];
282
+ body =
283
+ word === 'weekdays'
284
+ ? { freq: 'WEEKLY', interval: 1, byDay: [0, 1, 2, 3, 4].map(plainDay), byMonthDay: [], byMonth: [] }
285
+ : {
286
+ freq: word === 'daily' ? 'DAILY' : word === 'weekly' ? 'WEEKLY' : word === 'monthly' ? 'MONTHLY' : 'YEARLY',
287
+ interval: 1,
288
+ byDay: [],
289
+ byMonthDay: [],
290
+ byMonth: [],
291
+ };
292
+ body = readOn(reader, body);
293
+ }
294
+ else {
295
+ const every = /^\s*every(!)?/.exec(normal);
296
+ if (!every)
297
+ throw new Refusal('Start with “every”, like “every 3 days” or “every mon”.');
298
+ reader.at = every[0].length;
299
+ fromCompletion = !!every[1];
300
+ if (reader.done)
301
+ throw new Refusal(`Say how often after “every”, like ${EXAMPLES}.`);
302
+ body = readBody(reader);
303
+ }
304
+ let times;
305
+ let start;
306
+ let untilAt;
307
+ let untilText;
308
+ let count = null;
309
+ const seen = new Set();
310
+ const once = (word) => {
311
+ if (seen.has(word))
312
+ throw new Refusal(`It says “${word}” twice.`);
313
+ seen.add(word);
314
+ };
315
+ while (!reader.done) {
316
+ reader.read(',');
317
+ if (reader.done)
318
+ break;
319
+ if (reader.read('at')) {
320
+ once('at');
321
+ times = readTimes(reader);
322
+ }
323
+ else if (reader.read('(?:starting|starts|start|from)(?:\\s+on)?')) {
324
+ once('starting');
325
+ start = readDate(reader, options.today, 'starting');
326
+ }
327
+ else if (reader.read('(?:until|till|ending|ends)(?:\\s+on)?')) {
328
+ once('until');
329
+ // Read once the start is known: a day with no year counts from it.
330
+ untilAt = reader.at;
331
+ readDate(reader, options.today, 'until');
332
+ untilText = reader.text.slice(untilAt, reader.at);
333
+ }
334
+ else if (reader.read('for')) {
335
+ once('for');
336
+ const match = reader.read(String.raw `(\d+)\s+times?`);
337
+ if (!match)
338
+ throw new Refusal('Say how many after “for”, like “for 10 times”.');
339
+ count = Number(match[1]);
340
+ if (count < 1)
341
+ throw new Refusal('“for 0 times” never comes round.');
342
+ if (count > 9999)
343
+ throw new Refusal('That is too many times.');
344
+ }
345
+ else {
346
+ throw new Refusal(unread(reader));
347
+ }
348
+ }
349
+ if (count !== null && untilText !== undefined)
350
+ throw new Refusal('Use “until” or “for N times”, not both.');
351
+ if (count !== null && fromCompletion) {
352
+ throw new Refusal('“every!” repeats from when it\'s done, so it can\'t stop after a number of times. Use “until”.');
353
+ }
354
+ const first = start ?? options.start ?? options.today;
355
+ const until = untilText === undefined ? null : readDate(new Reader(untilText), first, 'until');
356
+ return normalizeRecurrence({
357
+ rule: formatRule({ ...body, until, count }),
358
+ start: first,
359
+ times: times ?? options.times ?? ['09:00'],
360
+ timeZone: options.timeZone,
361
+ fromCompletion,
362
+ });
363
+ }
364
+ // ------------------------------------------------------- the way back
365
+ const DAY_WORDS = ['mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun'];
366
+ const ordinal = (value) => {
367
+ const tens = value % 100;
368
+ const suffix = tens >= 11 && tens <= 13 ? 'th' : ['th', 'st', 'nd', 'rd'][value % 10] ?? 'th';
369
+ return `${value}${suffix}`;
370
+ };
371
+ const listWords = (words, and = 'and') => words.length <= 1 ? words.join('') : `${words.slice(0, -1).join(', ')} ${and} ${words[words.length - 1]}`;
372
+ function phraseTime(time) {
373
+ const [hour, minute] = time.split(':').map(Number);
374
+ if (hour === 12 && minute === 0)
375
+ return 'noon';
376
+ const half = hour < 12 ? 'am' : 'pm';
377
+ const clock = hour % 12 || 12;
378
+ return minute ? `${clock}:${pad(minute)}${half}` : `${clock}${half}`;
379
+ }
380
+ function phraseDate(day, today) {
381
+ const [year, month, date] = day.split('-').map(Number);
382
+ const words = `${MONTH_WORDS[month - 1]} ${date}`;
383
+ return today && Number(today.slice(0, 4)) === year && day >= today ? words : `${words}, ${year}`;
384
+ }
385
+ const WEEKDAYS_MO_FR = 'MO,TU,WE,TH,FR';
386
+ /** The days part of a rule as a phrase ("every 2nd tue"), or null for one the reader can't write. */
387
+ function phraseBody(parts) {
388
+ const { freq, interval, byDay, byMonthDay, byMonth } = parts;
389
+ const codes = byDay.map(({ day }) => WEEKDAY_CODES[day]).join(',');
390
+ const plain = byDay.every(({ nth }) => nth === null);
391
+ const unitWord = { DAILY: 'day', WEEKLY: 'week', MONTHLY: 'month', YEARLY: 'year' }[freq];
392
+ const every = interval === 1 ? unitWord : interval === 2 ? `other ${unitWord}` : `${interval} ${unitWord}s`;
393
+ if (byMonth.length && !(freq === 'YEARLY' && byMonth.length === 1))
394
+ return null;
395
+ switch (freq) {
396
+ case 'DAILY':
397
+ return byDay.length || byMonthDay.length ? null : every;
398
+ case 'WEEKLY': {
399
+ if (!byDay.length)
400
+ return every;
401
+ if (!plain)
402
+ return null;
403
+ const names = listWords(byDay.map(({ day }) => DAY_WORDS[day]));
404
+ if (interval === 1)
405
+ return codes === WEEKDAYS_MO_FR ? 'weekday' : codes === 'SA,SU' ? 'weekend' : names;
406
+ return `${every} on ${names}`;
407
+ }
408
+ case 'MONTHLY': {
409
+ if (byDay.length && byMonthDay.length)
410
+ return null;
411
+ let on = null;
412
+ if (byDay.length === 1 && byDay[0].nth !== null) {
413
+ on = `${byDay[0].nth === -1 ? 'last' : ordinal(byDay[0].nth)} ${DAY_WORDS[byDay[0].day]}`;
414
+ }
415
+ else if (byMonthDay.length === 1) {
416
+ on = byMonthDay[0] === -1 ? 'last day' : byMonthDay[0] > 0 ? ordinal(byMonthDay[0]) : null;
417
+ if (on === null)
418
+ return null;
419
+ }
420
+ else if (byDay.length || byMonthDay.length) {
421
+ return null;
422
+ }
423
+ if (on === null)
424
+ return every;
425
+ if (interval === 1)
426
+ return on === 'last day' ? 'last day of the month' : on;
427
+ return `${every} on the ${on}`;
428
+ }
429
+ case 'YEARLY':
430
+ if (byDay.length)
431
+ return null;
432
+ if (!byMonth.length && !byMonthDay.length)
433
+ return every;
434
+ if (interval !== 1 || byMonth.length !== 1 || byMonthDay.length !== 1 || byMonthDay[0] < 1)
435
+ return null;
436
+ return `${MONTH_WORDS[byMonth[0] - 1]} ${byMonthDay[0]}`;
437
+ }
438
+ }
439
+ /**
440
+ * The Recurrence as a phrase parseRecurrencePhrase reads back to it
441
+ * ("every 2nd tue at 9am until mar 1"), or null for a rule it can't say
442
+ * (several month days, BYMONTH on a daily rule). The start is said only
443
+ * when it's after `today`.
444
+ */
445
+ export function recurrencePhrase(value, today) {
446
+ let parts;
447
+ try {
448
+ parts = parseRule(value.rule);
449
+ }
450
+ catch {
451
+ return null;
452
+ }
453
+ const body = phraseBody(parts);
454
+ if (body === null)
455
+ return null;
456
+ const words = [`${value.fromCompletion ? 'every!' : 'every'} ${body}`];
457
+ words.push(`at ${value.times.map(phraseTime).join(', ')}`);
458
+ if (today && value.start > today)
459
+ words.push(`starting ${phraseDate(value.start, today)}`);
460
+ if (parts.until)
461
+ words.push(`until ${phraseDate(parts.until, today && value.start > today ? value.start : today)}`);
462
+ if (parts.count !== null)
463
+ words.push(`for ${parts.count} times`);
464
+ return words.join(' ');
465
+ }
466
+ export { ordinal as ordinalWord, listWords };