@tristan2828/ui-foundation 4.93.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.
@@ -0,0 +1,363 @@
1
+ // Repeating schedules (#326): one rule, stored RRULE-shaped (RFC 5545), and
2
+ // when it falls next. The backend's `foundation_backend.recurrence` is the
3
+ // same rules in Python; both read tests/fixtures/recurrence-cases.json, so
4
+ // a screen and the server agree on every next occurrence.
5
+ //
6
+ // A `Recurrence` (the contract's schema) is a rule (`FREQ=MONTHLY;BYDAY=2TU`,
7
+ // no DTSTART), the first day it can fall on (`start`), its times of day,
8
+ // its IANA zone, and whether it repeats from completion (`every!`).
9
+ //
10
+ // The days come from the rule; the times are put on them in the zone. npm's
11
+ // rrule walks the days as UTC midnights, with no time and no zone, so its
12
+ // maths never meets a DST change; each day's times then become instants in
13
+ // the zone. A time a DST change skips (02:30 the night clocks spring
14
+ // forward) is read an hour on; one it repeats (01:30 the night they fall
15
+ // back) is the first of the two, as Python's zoneinfo reads them. A day a
16
+ // month doesn't have is skipped: the 31st falls only in months with 31
17
+ // days, Feb 29 only in leap years, and -1 is every month's last day. COUNT
18
+ // counts occurrences, each time of each day.
19
+ import * as rruleModule from 'rrule';
20
+ // rrule ships an ES module build without `"type": "module"`: a bundler reads
21
+ // its named exports, Node its UMD build, whose exports sit on `default`.
22
+ // Read through Reflect so a bundler doesn't warn about a `default` it lacks.
23
+ const rrule = Reflect.get(rruleModule, 'default') ?? rruleModule;
24
+ export const FREQUENCIES = ['DAILY', 'WEEKLY', 'MONTHLY', 'YEARLY'];
25
+ /** RFC 5545's weekday codes, Monday first (Monday is 0 everywhere here). */
26
+ export const WEEKDAY_CODES = ['MO', 'TU', 'WE', 'TH', 'FR', 'SA', 'SU'];
27
+ /** What's wrong with a rule or a recurrence, in words a person can act on. */
28
+ export class RecurrenceError extends Error {
29
+ }
30
+ const TIME = /^([01]\d|2[0-3]):[0-5]\d$/;
31
+ const BYDAY = /^([+-]?[1-5])?(MO|TU|WE|TH|FR|SA|SU)$/;
32
+ const UNTIL = /^(\d{4})(\d{2})(\d{2})$/;
33
+ const DATE = /^(\d{4})-(\d{2})-(\d{2})$/;
34
+ const PARTS = new Set(['FREQ', 'INTERVAL', 'BYDAY', 'BYMONTHDAY', 'BYMONTH', 'UNTIL', 'COUNT']);
35
+ // How far ahead a rule must fall at least once (a 31st of February never does).
36
+ const HORIZON_YEARS = 28;
37
+ const DAY_MS = 86_400_000;
38
+ function integers(name, value, low, high) {
39
+ const found = [];
40
+ for (const part of value.split(',')) {
41
+ if (!/^[+-]?\d{1,4}$/.test(part))
42
+ throw new RecurrenceError(`${name} must be numbers; got ${value}.`);
43
+ const number = Number(part);
44
+ if (number < low || number > high || number === 0)
45
+ throw new RecurrenceError(`${name} ${number} is out of range.`);
46
+ if (!found.includes(number))
47
+ found.push(number);
48
+ }
49
+ return found;
50
+ }
51
+ /** `FREQ=…;…` → its parts; throws a RecurrenceError saying what's wrong. */
52
+ export function parseRule(text) {
53
+ const fields = new Map();
54
+ for (const part of text.trim().toUpperCase().split(';')) {
55
+ if (!part)
56
+ continue;
57
+ const at = part.indexOf('=');
58
+ if (at <= 0 || at === part.length - 1)
59
+ throw new RecurrenceError(`Rule part ${part} isn't NAME=value.`);
60
+ const name = part.slice(0, at);
61
+ if (fields.has(name))
62
+ throw new RecurrenceError(`${name} appears twice.`);
63
+ fields.set(name, part.slice(at + 1));
64
+ }
65
+ const unknown = [...fields.keys()].filter((name) => !PARTS.has(name)).sort();
66
+ if (unknown.length)
67
+ throw new RecurrenceError(`Rule part ${unknown[0]} isn't supported.`);
68
+ const freq = fields.get('FREQ');
69
+ if (!freq || !FREQUENCIES.includes(freq))
70
+ throw new RecurrenceError(`FREQ must be one of ${FREQUENCIES.join(', ')}.`);
71
+ const interval = fields.has('INTERVAL') ? integers('INTERVAL', fields.get('INTERVAL'), 1, 999)[0] : 1;
72
+ const byDay = [];
73
+ for (const part of fields.get('BYDAY')?.split(',') ?? []) {
74
+ const match = BYDAY.exec(part);
75
+ if (!match)
76
+ throw new RecurrenceError(`BYDAY ${part} isn't a weekday (MO to SU, with an nth of 1 to 5 or -1 to -5).`);
77
+ const nth = match[1] ? Number(match[1]) : null;
78
+ if (nth !== null && freq !== 'MONTHLY' && freq !== 'YEARLY') {
79
+ throw new RecurrenceError('An nth weekday (2TU, -1FR) needs FREQ=MONTHLY or YEARLY.');
80
+ }
81
+ const day = WEEKDAY_CODES.indexOf(match[2]);
82
+ if (!byDay.some((each) => each.nth === nth && each.day === day))
83
+ byDay.push({ nth, day });
84
+ }
85
+ const byMonthDay = fields.has('BYMONTHDAY') ? integers('BYMONTHDAY', fields.get('BYMONTHDAY'), -31, 31) : [];
86
+ if (byMonthDay.length && freq === 'WEEKLY')
87
+ throw new RecurrenceError("BYMONTHDAY can't go with FREQ=WEEKLY.");
88
+ const byMonth = fields.has('BYMONTH') ? integers('BYMONTH', fields.get('BYMONTH'), 1, 12) : [];
89
+ let until = null;
90
+ if (fields.has('UNTIL')) {
91
+ const match = UNTIL.exec(fields.get('UNTIL'));
92
+ if (!match || !isRealDay(`${match[1]}-${match[2]}-${match[3]}`))
93
+ throw new RecurrenceError('UNTIL must be a date, YYYYMMDD.');
94
+ until = `${match[1]}-${match[2]}-${match[3]}`;
95
+ }
96
+ const count = fields.has('COUNT') ? integers('COUNT', fields.get('COUNT'), 1, 9999)[0] : null;
97
+ if (until !== null && count !== null)
98
+ throw new RecurrenceError('A rule has UNTIL or COUNT, not both.');
99
+ return {
100
+ freq,
101
+ interval,
102
+ byDay: byDay.sort((a, b) => a.day - b.day || (a.nth ?? 0) - (b.nth ?? 0)),
103
+ byMonthDay: byMonthDay.sort((a, b) => Number(a < 0) - Number(b < 0) || a - b),
104
+ byMonth: byMonth.sort((a, b) => a - b),
105
+ until,
106
+ count,
107
+ };
108
+ }
109
+ /**
110
+ * The stored form, its parts always in one order (so two rules that mean
111
+ * the same are the same text): FREQ, INTERVAL (left out at 1), BYMONTH,
112
+ * BYMONTHDAY, BYDAY, UNTIL, COUNT.
113
+ */
114
+ export function formatRule(parts) {
115
+ const out = [`FREQ=${parts.freq}`];
116
+ if (parts.interval !== 1)
117
+ out.push(`INTERVAL=${parts.interval}`);
118
+ if (parts.byMonth.length)
119
+ out.push(`BYMONTH=${parts.byMonth.join(',')}`);
120
+ if (parts.byMonthDay.length)
121
+ out.push(`BYMONTHDAY=${parts.byMonthDay.join(',')}`);
122
+ if (parts.byDay.length)
123
+ out.push(`BYDAY=${parts.byDay.map(({ nth, day }) => `${nth ?? ''}${WEEKDAY_CODES[day]}`).join(',')}`);
124
+ if (parts.until)
125
+ out.push(`UNTIL=${parts.until.replaceAll('-', '')}`);
126
+ if (parts.count !== null)
127
+ out.push(`COUNT=${parts.count}`);
128
+ return out.join(';');
129
+ }
130
+ function isRealDay(value) {
131
+ const match = DATE.exec(value);
132
+ if (!match)
133
+ return false;
134
+ const moment = new Date(Date.UTC(Number(match[1]), Number(match[2]) - 1, Number(match[3])));
135
+ return moment.toISOString().slice(0, 10) === value;
136
+ }
137
+ /** Whether `name` is an IANA zone this browser knows. */
138
+ export function isTimeZone(name) {
139
+ try {
140
+ new Intl.DateTimeFormat('en-US', { timeZone: name });
141
+ return true;
142
+ }
143
+ catch {
144
+ return false;
145
+ }
146
+ }
147
+ /**
148
+ * The recurrence in its stored form (the rule's parts in order, the times
149
+ * sorted, each once), or a RecurrenceError saying what's wrong with it: the
150
+ * same checks the backend's `Recurrence` makes.
151
+ */
152
+ export function normalizeRecurrence(value) {
153
+ const parts = parseRule(value.rule);
154
+ if (!isRealDay(value.start))
155
+ throw new RecurrenceError('The start must be a date, YYYY-MM-DD.');
156
+ if (!value.times.length)
157
+ throw new RecurrenceError('It needs at least one time of day.');
158
+ for (const each of value.times) {
159
+ if (!TIME.test(each))
160
+ throw new RecurrenceError(`A time is HH:MM, 00:00 to 23:59; got ${each}.`);
161
+ }
162
+ if (!value.timeZone || !isTimeZone(value.timeZone))
163
+ throw new RecurrenceError(`Unknown time zone ${value.timeZone}.`);
164
+ const fromCompletion = value.fromCompletion ?? false;
165
+ if (parts.count !== null && fromCompletion) {
166
+ throw new RecurrenceError("“For N times” can't go with repeating from completion: each next one counts from when it's done.");
167
+ }
168
+ if (parts.until !== null && parts.until < value.start)
169
+ throw new RecurrenceError('It ends before it starts.');
170
+ const horizon = `${Math.min(Number(value.start.slice(0, 4)) + HORIZON_YEARS, 9999)}-12-31`;
171
+ if (days(parts, value.start, horizon).next().done)
172
+ throw new RecurrenceError('The rule never falls on a day (no month has that day).');
173
+ return { ...value, rule: formatRule(parts), times: [...new Set(value.times)].sort(), fromCompletion };
174
+ }
175
+ /** What's wrong with a recurrence, or null when nothing is. */
176
+ export function recurrenceProblem(value) {
177
+ try {
178
+ normalizeRecurrence(value);
179
+ return null;
180
+ }
181
+ catch (error) {
182
+ if (error instanceof RecurrenceError)
183
+ return error.message;
184
+ throw error;
185
+ }
186
+ }
187
+ // ------------------------------------------------------------ the days
188
+ const toUtcDay = (value) => new Date(`${value}T00:00:00Z`);
189
+ const dayOf = (moment) => moment.toISOString().slice(0, 10);
190
+ const FREQ_OF = {
191
+ DAILY: rrule.Frequency.DAILY,
192
+ WEEKLY: rrule.Frequency.WEEKLY,
193
+ MONTHLY: rrule.Frequency.MONTHLY,
194
+ YEARLY: rrule.Frequency.YEARLY,
195
+ };
196
+ const MONTH_LENGTHS = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
197
+ /**
198
+ * Whether no month the rule allows has any of its month days (the 30th of
199
+ * February): such a rule never falls, and rrule would walk to the year
200
+ * 9999 looking, since it checks UNTIL only on a day it finds.
201
+ */
202
+ export function monthDaysNeverFall(parts) {
203
+ if (!parts.byMonthDay.length)
204
+ return false;
205
+ const months = parts.byMonth.length ? parts.byMonth : MONTH_LENGTHS.map((_, at) => at + 1);
206
+ return !months.some((month) => parts.byMonthDay.some((day) => Math.abs(day) <= MONTH_LENGTHS[month - 1]));
207
+ }
208
+ /**
209
+ * The days the rule falls on from `start`, through UNTIL (and `stop`),
210
+ * as `'YYYY-MM-DD'`: rrule does the walking, from the start each time it's
211
+ * asked for more, four times as many as before.
212
+ */
213
+ function* days(parts, start, stop) {
214
+ if (monthDaysNeverFall(parts))
215
+ return;
216
+ const last = [parts.until, stop].filter((each) => !!each).sort()[0];
217
+ const weekdays = parts.byDay.map(({ nth, day }) => {
218
+ const weekday = rrule.Weekday.fromStr(WEEKDAY_CODES[day]);
219
+ return nth === null ? weekday : weekday.nth(nth);
220
+ });
221
+ const rule = new rrule.RRule({
222
+ freq: FREQ_OF[parts.freq],
223
+ interval: parts.interval,
224
+ dtstart: toUtcDay(start),
225
+ byweekday: weekdays.length ? weekdays : null,
226
+ bymonthday: parts.byMonthDay.length ? parts.byMonthDay : null,
227
+ bymonth: parts.byMonth.length ? parts.byMonth : null,
228
+ until: last ? toUtcDay(last) : null,
229
+ });
230
+ let given = 0;
231
+ for (let limit = 64;; limit *= 4) {
232
+ const found = rule.all((_, count) => count < limit);
233
+ for (const moment of found.slice(given))
234
+ yield dayOf(moment);
235
+ given = found.length;
236
+ if (found.length < limit)
237
+ return;
238
+ }
239
+ }
240
+ // ------------------------------------------------------ times in a zone
241
+ const zoneFormats = new Map();
242
+ function zoneFormat(timeZone) {
243
+ let format = zoneFormats.get(timeZone);
244
+ if (!format) {
245
+ format = new Intl.DateTimeFormat('en-US', {
246
+ timeZone,
247
+ hourCycle: 'h23',
248
+ year: 'numeric',
249
+ month: '2-digit',
250
+ day: '2-digit',
251
+ hour: '2-digit',
252
+ minute: '2-digit',
253
+ second: '2-digit',
254
+ });
255
+ zoneFormats.set(timeZone, format);
256
+ }
257
+ return format;
258
+ }
259
+ /** The wall clock in `timeZone` at an instant: `'YYYY-MM-DD'` and minutes past midnight. */
260
+ export function wallClock(moment, timeZone) {
261
+ const ms = typeof moment === 'number' ? moment : moment.getTime();
262
+ const parts = {};
263
+ for (const part of zoneFormat(timeZone).formatToParts(ms))
264
+ parts[part.type] = part.value;
265
+ const day = `${parts.year}-${parts.month}-${parts.day}`;
266
+ const [hour, minute, second] = [Number(parts.hour), Number(parts.minute), Number(parts.second)];
267
+ return { day, minutes: hour * 60 + minute, ms: Date.parse(`${day}T00:00:00Z`) + ((hour * 60 + minute) * 60 + second) * 1000 };
268
+ }
269
+ /** The zone's offset from UTC at an instant, in milliseconds. */
270
+ function offsetAt(ms, timeZone) {
271
+ const whole = Math.floor(ms / 1000) * 1000;
272
+ return wallClock(whole, timeZone).ms - whole;
273
+ }
274
+ /**
275
+ * `day` at `time` (`'HH:MM'`) in `timeZone`, as an instant. A time a DST
276
+ * change skips is read an hour on (the offset before the change); one it
277
+ * repeats is the first of the two, as Python's zoneinfo reads them.
278
+ */
279
+ export function atLocal(day, time, timeZone) {
280
+ const wall = Date.parse(`${day}T${time}:00Z`);
281
+ const before = offsetAt(wall - DAY_MS, timeZone);
282
+ const after = offsetAt(wall + DAY_MS, timeZone);
283
+ const fits = (offset) => offsetAt(wall - offset, timeZone) === offset;
284
+ if (fits(before))
285
+ return new Date(wall - before);
286
+ if (fits(after))
287
+ return new Date(wall - after);
288
+ return new Date(wall - before);
289
+ }
290
+ /** Every occurrence from `start` on, in order, COUNT applied. */
291
+ function* instants(value, start, parts = parseRule(value.rule)) {
292
+ const times = [...new Set(value.times)].sort();
293
+ let left = parts.count;
294
+ for (const day of days(parts, start)) {
295
+ // Sorted per day: across a DST change a later time can be the earlier instant.
296
+ const moments = [...new Set(times.map((time) => atLocal(day, time, value.timeZone).getTime()))].sort((a, b) => a - b);
297
+ for (const ms of moments) {
298
+ if (left !== null) {
299
+ if (left === 0)
300
+ return;
301
+ left -= 1;
302
+ }
303
+ yield new Date(ms);
304
+ }
305
+ if (left === 0)
306
+ return;
307
+ }
308
+ }
309
+ /** The next `count` occurrences strictly after `after`. */
310
+ export function nextOccurrences(value, after, count) {
311
+ const found = [];
312
+ if (count <= 0)
313
+ return found;
314
+ for (const moment of instants(value, value.start)) {
315
+ if (moment.getTime() > after.getTime()) {
316
+ found.push(moment);
317
+ if (found.length === count)
318
+ break;
319
+ }
320
+ }
321
+ return found;
322
+ }
323
+ /** The first occurrence strictly after `after`, or null once the rule has ended. */
324
+ export function nextOccurrence(value, after) {
325
+ return nextOccurrences(value, after, 1)[0] ?? null;
326
+ }
327
+ /**
328
+ * For a `fromCompletion` rule, the next occurrence once it's done at
329
+ * `doneAt`: the rule's days counted from the local day it was done, the
330
+ * first one after that day. A schedule rule's is just its next.
331
+ */
332
+ export function nextAfterCompletion(value, doneAt) {
333
+ if (!value.fromCompletion)
334
+ return nextOccurrence(value, doneAt);
335
+ const doneDay = wallClock(doneAt, value.timeZone).day;
336
+ for (const moment of instants(value, doneDay)) {
337
+ if (wallClock(moment, value.timeZone).day > doneDay)
338
+ return moment;
339
+ }
340
+ return null;
341
+ }
342
+ // ------------------------------------------ a weekday set and one time
343
+ const DAY_NAMES = ['mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun'];
344
+ /**
345
+ * The rule for a weekday set and one time (Monday 0, or `'mon,wed,fri'`
346
+ * as the reminders table stores it), exactly: due on the same days at the
347
+ * same time, from `start` on. Every day of the week is FREQ=DAILY.
348
+ */
349
+ export function recurrenceFromWeekdays(weekdays, time, timeZone, start) {
350
+ const chosen = typeof weekdays === 'string'
351
+ ? weekdays
352
+ .split(',')
353
+ .map((part) => part.trim().toLowerCase())
354
+ .filter(Boolean)
355
+ .map((name) => DAY_NAMES.indexOf(name))
356
+ : [...weekdays];
357
+ if (!chosen.length || chosen.some((day) => day < 0 || day > 6)) {
358
+ throw new RecurrenceError('The days must be some of mon, tue, wed, thu, fri, sat, sun.');
359
+ }
360
+ const unique = [...new Set(chosen)].sort();
361
+ const rule = unique.length === 7 ? 'FREQ=DAILY' : `FREQ=WEEKLY;BYDAY=${unique.map((day) => WEEKDAY_CODES[day]).join(',')}`;
362
+ return normalizeRecurrence({ rule, start, times: [time], timeZone, fromCompletion: false });
363
+ }
@@ -14,7 +14,9 @@ info:
14
14
  A path marked `x-optional: true` may be left out of an app's spec (an
15
15
  app without self-service sign-up omits /auth/register, an app that
16
16
  doesn't render DataEnvironmentBanner omits /environment, an app without
17
- reminders omits /push/*), but if present it must match.
17
+ reminders omits /push/*), but if present it must match. A component
18
+ marked `x-optional: true` (Recurrence, which no path here calls and an
19
+ app's own schemas reference) may be left out the same way.
18
20
 
19
21
  servers:
20
22
  - url: /api
@@ -331,6 +333,52 @@ components:
331
333
  properties:
332
334
  id: { type: integer }
333
335
 
336
+ Recurrence:
337
+ # Not called by any path here: a schema an app's own entities
338
+ # reference (a reminder's or a task's repeat). An app without one
339
+ # leaves it out; with one, it must match.
340
+ x-optional: true
341
+ type: object
342
+ description: >
343
+ A repeating schedule (RecurrenceField, foundation_backend.recurrence).
344
+ The rule's days, each at every one of its times, read in its zone.
345
+ required: [rule, start, times, timeZone]
346
+ properties:
347
+ rule:
348
+ type: string
349
+ minLength: 1
350
+ maxLength: 200
351
+ pattern: "^FREQ=(DAILY|WEEKLY|MONTHLY|YEARLY)(;(INTERVAL|BYMONTH|BYMONTHDAY|BYDAY|UNTIL|COUNT)=[A-Z0-9,+-]+)*$"
352
+ description: >
353
+ RFC 5545's RRULE value, without DTSTART: FREQ (daily, weekly,
354
+ monthly, yearly), INTERVAL, BYMONTH, BYMONTHDAY (-1 is the last
355
+ day), BYDAY (an nth for monthly and yearly: 2TU, -1FR), UNTIL
356
+ (a date, YYYYMMDD, the last day it can fall on) or COUNT
357
+ (occurrences, each time of each day). "FREQ=MONTHLY;BYDAY=2TU".
358
+ start:
359
+ type: string
360
+ format: date
361
+ description: The first day it can fall on (DTSTART's date).
362
+ times:
363
+ type: array
364
+ minItems: 1
365
+ maxItems: 24
366
+ items:
367
+ type: string
368
+ pattern: "^([01][0-9]|2[0-3]):[0-5][0-9]$"
369
+ description: Its times of day, HH:MM, in order, each once.
370
+ timeZone:
371
+ type: string
372
+ minLength: 1
373
+ maxLength: 64
374
+ description: The IANA zone its days and times are read in.
375
+ fromCompletion:
376
+ type: boolean
377
+ default: false
378
+ description: >
379
+ Repeat from when it was done ("every!"), not from the schedule:
380
+ the next one is the rule's days counted from the day it was done.
381
+
334
382
  ValidationErrorBody:
335
383
  type: object
336
384
  description: FastAPI's default 422 shape (RequestValidationError).
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tristan2828/ui-foundation",
3
- "version": "4.93.0",
3
+ "version": "4.95.0",
4
4
  "description": "Shared UI foundation for contract-first, database-backed React apps: shadcn primitives, DataTable/EntityForm composites, auth, the gateway error seam, design tokens, lint rules and the AI playbook.",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -148,6 +148,7 @@
148
148
  "react-markdown": "^10.1.0",
149
149
  "remark-gfm": "^4.0.1",
150
150
  "remark-parse": "^11.0.0",
151
+ "rrule": "2.8.1",
151
152
  "shadcn": "^4.22.1",
152
153
  "tw-animate-css": "^1.4.0",
153
154
  "unified": "^11.0.5"