@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.
@@ -219,7 +219,11 @@ function checkContract(specPath) {
219
219
  for (const [name, entry] of Object.entries(entries)) {
220
220
  const appEntry = app.components?.[section]?.[name]
221
221
  if (appEntry === undefined) {
222
- if (!optionalOnly.has(`${section}/${name}`)) problems.push(`missing components.${section}.${name}`)
222
+ // A component marked x-optional (Recurrence) is one an app's own
223
+ // schemas may reference; no path here needs it.
224
+ if (!entry['x-optional'] && !optionalOnly.has(`${section}/${name}`)) {
225
+ problems.push(`missing components.${section}.${name}`)
226
+ }
223
227
  } else if (!same(appEntry, entry)) {
224
228
  problems.push(`components.${section}.${name} differs`)
225
229
  }
@@ -4,28 +4,28 @@
4
4
  ## Index
5
5
 
6
6
  - [The reference files](#the-reference-files) · lines 44–66
7
- - [Before anything: the entity plan](#before-anything-the-entity-plan) · lines 68–832
7
+ - [Before anything: the entity plan](#before-anything-the-entity-plan) · lines 68–848
8
8
  - Step 1: Add `<Entity>` to `openapi.yaml` · lines 110–117
9
9
  - Step 2: `npm run gen:api` · lines 118–119
10
10
  - Step 3: Add gateway tests in `tests/gateway/<entity>.test.ts`, derived from the spec · lines 120–131
11
11
  - Step 4: Add MSW handlers in `src/mocks/<entity>.ts` · lines 132–141
12
12
  - Step 5: Add a gateway module in `src/api/gateway/<entity>.ts` · lines 142–146
13
- - Step 6: Copy the reference files, one for one, not just the two screens · lines 147–719
14
- - Step 7: Register routes · lines 720–735
15
- - Step 8: Add Playwright specs for all three screens · lines 736–814
16
- - Step 9: Register the nav entry and route names · lines 815–829
17
- - Step 10: `npm run verify`. · lines 830–832
18
- - [How a list opens a record](#how-a-list-opens-a-record) · lines 834–1153
19
- - [The record view](#the-record-view) · lines 983–1031
20
- - [Forms](#forms) · lines 1033–1085
21
- - [Dialogs](#dialogs) · lines 1087–1112
22
- - [Toasts and feedback](#toasts-and-feedback) · lines 1114–1153
23
- - [What not to copy](#what-not-to-copy) · lines 1155–1181
24
- - [After a commit, in the backend](#after-a-commit-in-the-backend) · lines 1183–1200
25
- - [Deleting](#deleting) · lines 1202–1233
26
- - [Fields only a script writes](#fields-only-a-script-writes) · lines 1235–1256
27
- - [Searching one part of the app](#searching-one-part-of-the-app) · lines 1258–1267
28
- - [What a chat is told about an entity](#what-a-chat-is-told-about-an-entity) · lines 1270–1312
13
+ - Step 6: Copy the reference files, one for one, not just the two screens · lines 147–735
14
+ - Step 7: Register routes · lines 736–751
15
+ - Step 8: Add Playwright specs for all three screens · lines 752–830
16
+ - Step 9: Register the nav entry and route names · lines 831–845
17
+ - Step 10: `npm run verify`. · lines 846–848
18
+ - [How a list opens a record](#how-a-list-opens-a-record) · lines 850–1169
19
+ - [The record view](#the-record-view) · lines 999–1047
20
+ - [Forms](#forms) · lines 1049–1101
21
+ - [Dialogs](#dialogs) · lines 1103–1128
22
+ - [Toasts and feedback](#toasts-and-feedback) · lines 1130–1169
23
+ - [What not to copy](#what-not-to-copy) · lines 1171–1197
24
+ - [After a commit, in the backend](#after-a-commit-in-the-backend) · lines 1199–1216
25
+ - [Deleting](#deleting) · lines 1218–1249
26
+ - [Fields only a script writes](#fields-only-a-script-writes) · lines 1251–1272
27
+ - [Searching one part of the app](#searching-one-part-of-the-app) · lines 1274–1283
28
+ - [What a chat is told about an entity](#what-a-chat-is-told-about-an-entity) · lines 1286–1328
29
29
 
30
30
  <!-- /index -->
31
31
 
@@ -252,6 +252,22 @@ is a filled-in example while the Widgets demo is still here).
252
252
  written, and the field shows it as written with nothing picked, refused
253
253
  until a day is picked.
254
254
 
255
+ **A `recurrence`** (how something repeats: a chore, a reminder, a
256
+ task) is the foundation's `Recurrence` schema: copy it from the
257
+ package's `openapi/foundation.yaml` into `components.schemas` (it's
258
+ `x-optional`, so `check-contract` holds it to the foundation's shape
259
+ once it's there) and reference it, nullable when it may not repeat.
260
+ On the form it's the foundation's `RecurrenceField` in a `Controller`
261
+ (presets, a phrase read as it's typed, and a preview of the next five);
262
+ the schema checks it with `recurrenceProblem(value)`, and a phrase the
263
+ field can't read gives `null`, so a required one is refused. The table
264
+ shows `formatRecurrence(value)` and a Next column (cell pattern 27);
265
+ editing in place is `inPlace.recurrence({ value, save })`. The backend
266
+ column is JSON, read and checked with
267
+ `foundation_backend.recurrence.Recurrence` (a 422 on the field for a
268
+ rule it refuses); `next_after` and `occurrences` say when it falls
269
+ (reminders.md "Repeating reminders").
270
+
255
271
  **An image on a record** (a photo of it) is the stored file's id on the
256
272
  wire (`string`, nullable), and on the form the foundation's
257
273
  `ImageField` in a `Controller` (`z.string().nullable()`): `value` and
@@ -3,45 +3,46 @@
3
3
  <!-- index: written by `npm run docs:index` in the package from the headings below; never edit it by hand -->
4
4
  ## Index
5
5
 
6
- - [The rules that apply to every cell](#the-rules-that-apply-to-every-cell) · lines 73–92
7
- - [1. Plain text](#1-plain-text) · lines 94–147
8
- - [2. Icon + label](#2-icon--label) · lines 149–172
9
- - [3. Icon in a badge](#3-icon-in-a-badge) · lines 174–187
10
- - [4. Icon only, label in a tooltip](#4-icon-only-label-in-a-tooltip) · lines 189–266
11
- - [Several values: the icons side by side, every name in one tooltip](#several-values-the-icons-side-by-side-every-name-in-one-tooltip) · lines 214–266
12
- - [5. Enum → tone-mapped badge](#5-enum--tone-mapped-badge) · lines 268–281
13
- - [6. Multi-value enum, clustered](#6-multi-value-enum-clustered) · lines 283–295
14
- - [7. Link as an outline button](#7-link-as-an-outline-button) · lines 297–318
15
- - [8. Date, relative](#8-date-relative) · lines 320–357
16
- - [9. Ordinal scale (bounded integer)](#9-ordinal-scale-bounded-integer) · lines 359–407
17
- - [Two variants the package draws: a step bar and a star](#two-variants-the-package-draws-a-step-bar-and-a-star) · lines 377–407
18
- - [10. Summary in the cell, detail in a popover](#10-summary-in-the-cell-detail-in-a-popover) · lines 409–459
19
- - [A second example: what a row depends on](#a-second-example-what-a-row-depends-on) · lines 427–459
20
- - [11. Number or currency — Unproven](#11-number-or-currency--unproven) · lines 461–501
21
- - [12. Boolean](#12-boolean) · lines 503–533
22
- - [13. Progress bar — Unproven](#13-progress-bar--unproven) · lines 535–571
23
- - [The compact form: `ProgressRing`](#the-compact-form-progressring) · lines 555–571
24
- - [14. Avatar and name — Unproven](#14-avatar-and-name--unproven) · lines 573–590
25
- - [15. Yes/no you flip in the row](#15-yesno-you-flip-in-the-row) · lines 592–701
26
- - [A variant: a pressed icon inside another value's cell](#a-variant-a-pressed-icon-inside-another-values-cell) · lines 618–701
27
- - [16. Title linking to the record's view](#16-title-linking-to-the-records-view) · lines 703–738
28
- - [17. Quick action on the view](#17-quick-action-on-the-view) · lines 740–813
29
- - [18. Editable value](#18-editable-value) · lines 815–1493
30
- - [Presets: one line per field](#presets-one-line-per-field) · lines 1125–1193
31
- - [Several fields edited as one](#several-fields-edited-as-one) · lines 1195–1231
32
- - [A link and its label](#a-link-and-its-label) · lines 1233–1257
33
- - [A list of sub-items](#a-list-of-sub-items) · lines 1259–1392
34
- - [In a table's rows](#in-a-tables-rows) · lines 1394–1479
35
- - [A table of a few short columns: `width="content"`](#a-table-of-a-few-short-columns-widthcontent) · lines 1481–1493
36
- - [19. Stage circle for an ordered status](#19-stage-circle-for-an-ordered-status) · lines 1495–1561
37
- - [20. Count linking to the related records](#20-count-linking-to-the-related-records) · lines 1563–1627
38
- - [21. Rows grouped under headings, and a pill filter](#21-rows-grouped-under-headings-and-a-pill-filter) · lines 1629–1727
39
- - [22. A highlighted row, and rows that are done](#22-a-highlighted-row-and-rows-that-are-done) · lines 1729–1758
40
- - [24. A list's rows: hover, lines, rows per page](#24-a-lists-rows-hover-lines-rows-per-page) · lines 1760–1798
41
- - [23. A Group menu, and a record read beside the list](#23-a-group-menu-and-a-record-read-beside-the-list) · lines 1800–1876
42
- - [24. A stored colour beside its name](#24-a-stored-colour-beside-its-name) · lines 1878–1901
43
- - [25. A list's tools: views, filters, columns, row actions, a phone's rows](#25-a-lists-tools-views-filters-columns-row-actions-a-phones-rows) · lines 1903–1989
44
- - [26. A record's related list, capped](#26-a-records-related-list-capped) · lines 1991–2027
6
+ - [The rules that apply to every cell](#the-rules-that-apply-to-every-cell) · lines 74–93
7
+ - [1. Plain text](#1-plain-text) · lines 95–148
8
+ - [2. Icon + label](#2-icon--label) · lines 150–173
9
+ - [3. Icon in a badge](#3-icon-in-a-badge) · lines 175–188
10
+ - [4. Icon only, label in a tooltip](#4-icon-only-label-in-a-tooltip) · lines 190–267
11
+ - [Several values: the icons side by side, every name in one tooltip](#several-values-the-icons-side-by-side-every-name-in-one-tooltip) · lines 215–267
12
+ - [5. Enum → tone-mapped badge](#5-enum--tone-mapped-badge) · lines 269–282
13
+ - [6. Multi-value enum, clustered](#6-multi-value-enum-clustered) · lines 284–296
14
+ - [7. Link as an outline button](#7-link-as-an-outline-button) · lines 298–319
15
+ - [8. Date, relative](#8-date-relative) · lines 321–358
16
+ - [9. Ordinal scale (bounded integer)](#9-ordinal-scale-bounded-integer) · lines 360–408
17
+ - [Two variants the package draws: a step bar and a star](#two-variants-the-package-draws-a-step-bar-and-a-star) · lines 378–408
18
+ - [10. Summary in the cell, detail in a popover](#10-summary-in-the-cell-detail-in-a-popover) · lines 410–460
19
+ - [A second example: what a row depends on](#a-second-example-what-a-row-depends-on) · lines 428–460
20
+ - [11. Number or currency — Unproven](#11-number-or-currency--unproven) · lines 462–502
21
+ - [12. Boolean](#12-boolean) · lines 504–534
22
+ - [13. Progress bar — Unproven](#13-progress-bar--unproven) · lines 536–572
23
+ - [The compact form: `ProgressRing`](#the-compact-form-progressring) · lines 556–572
24
+ - [14. Avatar and name — Unproven](#14-avatar-and-name--unproven) · lines 574–591
25
+ - [15. Yes/no you flip in the row](#15-yesno-you-flip-in-the-row) · lines 593–702
26
+ - [A variant: a pressed icon inside another value's cell](#a-variant-a-pressed-icon-inside-another-values-cell) · lines 619–702
27
+ - [16. Title linking to the record's view](#16-title-linking-to-the-records-view) · lines 704–739
28
+ - [17. Quick action on the view](#17-quick-action-on-the-view) · lines 741–814
29
+ - [18. Editable value](#18-editable-value) · lines 816–1494
30
+ - [Presets: one line per field](#presets-one-line-per-field) · lines 1126–1194
31
+ - [Several fields edited as one](#several-fields-edited-as-one) · lines 1196–1232
32
+ - [A link and its label](#a-link-and-its-label) · lines 1234–1258
33
+ - [A list of sub-items](#a-list-of-sub-items) · lines 1260–1393
34
+ - [In a table's rows](#in-a-tables-rows) · lines 1395–1480
35
+ - [A table of a few short columns: `width="content"`](#a-table-of-a-few-short-columns-widthcontent) · lines 1482–1494
36
+ - [19. Stage circle for an ordered status](#19-stage-circle-for-an-ordered-status) · lines 1496–1562
37
+ - [20. Count linking to the related records](#20-count-linking-to-the-related-records) · lines 1564–1628
38
+ - [21. Rows grouped under headings, and a pill filter](#21-rows-grouped-under-headings-and-a-pill-filter) · lines 1630–1728
39
+ - [22. A highlighted row, and rows that are done](#22-a-highlighted-row-and-rows-that-are-done) · lines 1730–1759
40
+ - [24. A list's rows: hover, lines, rows per page](#24-a-lists-rows-hover-lines-rows-per-page) · lines 1761–1799
41
+ - [23. A Group menu, and a record read beside the list](#23-a-group-menu-and-a-record-read-beside-the-list) · lines 1801–1877
42
+ - [24. A stored colour beside its name](#24-a-stored-colour-beside-its-name) · lines 1879–1902
43
+ - [25. A list's tools: views, filters, columns, row actions, a phone's rows](#25-a-lists-tools-views-filters-columns-row-actions-a-phones-rows) · lines 1904–1990
44
+ - [26. A record's related list, capped](#26-a-records-related-list-capped) · lines 1992–2028
45
+ - [27. A repeat and its next time](#27-a-repeat-and-its-next-time) · lines 2030–2075
45
46
 
46
47
  <!-- /index -->
47
48
 
@@ -2025,3 +2026,50 @@ const visits = useVisits({ provider: provider.id, sort: 'date:desc', page: 1, pa
2025
2026
  - On a DataTable of your own, `limit` and `viewAll` do the same.
2026
2027
  - The fixture `app/DataTable tools` Related draws a capped list and a
2027
2028
  short one with no link; the spec follows View all.
2029
+
2030
+ ## 27. A repeat and its next time
2031
+
2032
+ A record that repeats (a chore, a reminder) shows two columns: **Repeats**,
2033
+ the rule in words, and **Next**, when it falls next. The value is the
2034
+ contract's `Recurrence` (reminders.md "Repeating reminders"); both cells
2035
+ read it in the rule's own zone, so a reminder set in Chicago says 9:00 AM
2036
+ wherever it's looked at.
2037
+
2038
+ ```tsx
2039
+ import { formatOccurrence, formatRecurrence, nextOccurrence, EmptyText } from '@tristan2828/ui-foundation'
2040
+
2041
+ {
2042
+ id: 'repeats',
2043
+ header: 'Repeats',
2044
+ cell: ({ row }) => (row.original.repeats ? formatRecurrence(row.original.repeats) : <EmptyText />),
2045
+ },
2046
+ {
2047
+ id: 'next',
2048
+ header: 'Next',
2049
+ cell: ({ row }) => {
2050
+ const repeats = row.original.repeats
2051
+ if (!repeats) return <EmptyText />
2052
+ const next = nextOccurrence(repeats, new Date())
2053
+ if (!next) return <span className="text-muted-foreground">Ended</span>
2054
+ return (
2055
+ <time dateTime={next.toISOString()} className="tabular-nums">
2056
+ {formatOccurrence(next, repeats.timeZone)}
2057
+ </time>
2058
+ )
2059
+ },
2060
+ },
2061
+ ```
2062
+
2063
+ - **The label** reads "Every 2nd Tue at 9:00 AM", "Every Mon and Thu at
2064
+ 7:00 AM and 7:30 PM", "Every 30 days after done, at 9:00 AM" (from
2065
+ completion), "…, until Mar 1, 2027", "…, 10 times". `times: false`
2066
+ leaves the times out, for a table with its own time column. A rule it
2067
+ can't read shows as stored, never blank.
2068
+ - **Next** is "Tue, Dec 8, 9:00 AM", the year only when it isn't this
2069
+ one; a rule that has ended (UNTIL passed, COUNT used up) says Ended, in
2070
+ muted text. For a `fromCompletion` repeat whose next depends on being
2071
+ done, use the server's `next_at` if it sends one; `nextOccurrence`
2072
+ counts from the schedule's start.
2073
+ - **Sorting by Next** is the server's (`next_at`), not the cell's text.
2074
+ - The fixture `app/RecurrenceField` List cells draws both on six chores;
2075
+ its spec reads each cell.
@@ -55,7 +55,9 @@ One or two sentences: what one record is, and who uses the screens.
55
55
  time: OpenAPI `format: date`; the foundation's `DateField`; say
56
56
  whether it's optional), `month-day` (a day that comes round every
57
57
  year, no year: `'MM-DD'`; the foundation's `MonthDayField`; say
58
- whether it's optional).
58
+ whether it's optional), `recurrence` (how it repeats: the
59
+ foundation's `Recurrence` schema and `RecurrenceField`; say whether
60
+ it's optional).
59
61
  - *Not supported yet:* a yes/no that can also be unset (three states),
60
62
  file, and anything else.
61
63
  Write it anyway with a note; the playbook will stop and raise it
@@ -111,6 +111,59 @@ Scope it to the signed-in user, as Widgets are.
111
111
  that's the `tzdata` package, which the backend doesn't install: a
112
112
  Windows dev machine reads only `UTC` until it's added.
113
113
 
114
+ ## Repeating reminders (4.95)
115
+
116
+ A weekday set and one time is the simple schedule. For anything more
117
+ (every 2nd Tuesday, the last day of the month, several times a day, an
118
+ end, "every! 3 days" counted from when it's done), a reminder carries a
119
+ **recurrence**: the contract's `Recurrence` schema (in the package's
120
+ `openapi/foundation.yaml`, marked `x-optional`: copy it into
121
+ `components.schemas` and reference it from the reminder's schema), the
122
+ package's `RecurrenceField` on the form and `inPlace.recurrence` on the
123
+ view, and `foundation_backend.recurrence` on the server. Both sides read
124
+ the same rules and agree on every next occurrence.
125
+
126
+ - **The value**: `{ rule, start, times, timeZone, fromCompletion }`.
127
+ `rule` is RFC 5545's RRULE without DTSTART (`FREQ=MONTHLY;BYDAY=2TU`):
128
+ FREQ daily to yearly, INTERVAL, BYDAY with an nth (`2TU`, `-1FR`),
129
+ BYMONTHDAY (`-1` the last day), BYMONTH, UNTIL (a date) or COUNT.
130
+ `start` is the first day it can fall on; each of `times` is an
131
+ occurrence on every day the rule falls on, read in `timeZone`. A day a
132
+ month lacks is skipped (the 31st, Feb 29), as in RFC 5545.
133
+ - **The columns**: the app's reminders model inherits
134
+ `foundation_backend.recurrence_models.RecurringReminderFields` and its
135
+ migration adds them: `recurrence` (JSON), `next_at`, `sent_at`,
136
+ `last_sent_at`, `done_occurrence`, `done_at` (timestamps with time
137
+ zone), `nag_count` (integer, default 0), `nag_every_minutes` and
138
+ `nag_limit` (integers, null for no nagging). `days` and `time_of_day`
139
+ become nullable. Hand the model to the job as before
140
+ (`reminders.register(model=MyReminder)`).
141
+ - **What the job does with a row whose `recurrence` is set**: each
142
+ occurrence is due from its time until 15 minutes have passed, so
143
+ several a day go out; one missed past that is skipped, not sent late
144
+ (the run's line says "1 missed"). Sent and not done, it's re-sent
145
+ every `nag_every_minutes`, at most `nag_limit` times (3 when only the
146
+ interval is set). The next occurrence coming round ends the wait; a
147
+ `fromCompletion` rule waits for done instead. A row with no
148
+ `recurrence` is the weekday set, as before.
149
+ - **Done**: the app's Done button (or a notification action that calls
150
+ the app) runs `reminders.mark_done(row)` and commits: the occurrence is
151
+ recorded (`done_occurrence`, `done_at`), nagging stops, and the next is
152
+ pending; for `fromCompletion` it counts from the done time. After the
153
+ rule itself changes, `reminders.schedule_changed(row)` forgets where it
154
+ was.
155
+ - **Moving a simple schedule over**: `recurrence.from_weekdays(days,
156
+ time_of_day, time_zone, start=today)` (and the package's
157
+ `recurrenceFromWeekdays`) is the same schedule exactly; store its
158
+ `model_dump(by_alias=True, mode="json")` in `recurrence`.
159
+ `recurrence.as_weekdays(rule)` goes back when a rule is still that
160
+ simple.
161
+ - **On screens**: `RecurrenceField` in the form (a `Controller`; check
162
+ with `recurrenceProblem`), `inPlace.recurrence` on the view, and in the
163
+ list `formatRecurrence` for a Repeats column and `nextOccurrence` with
164
+ `formatOccurrence` for a Next one (cell-patterns.md "A repeat and its
165
+ next time").
166
+
114
167
  ## Testing
115
168
 
116
169
  Under MSW the page is held by MSW's service worker, so `usePushPermission`
@@ -259,6 +259,25 @@ export interface components {
259
259
  PushSubscriptionCreated: {
260
260
  id: number;
261
261
  };
262
+ /** @description A repeating schedule (RecurrenceField, foundation_backend.recurrence). The rule's days, each at every one of its times, read in its zone. */
263
+ Recurrence: {
264
+ /** @description RFC 5545's RRULE value, without DTSTART: FREQ (daily, weekly, monthly, yearly), INTERVAL, BYMONTH, BYMONTHDAY (-1 is the last day), BYDAY (an nth for monthly and yearly: 2TU, -1FR), UNTIL (a date, YYYYMMDD, the last day it can fall on) or COUNT (occurrences, each time of each day). "FREQ=MONTHLY;BYDAY=2TU". */
265
+ rule: string;
266
+ /**
267
+ * Format: date
268
+ * @description The first day it can fall on (DTSTART's date).
269
+ */
270
+ start: string;
271
+ /** @description Its times of day, HH:MM, in order, each once. */
272
+ times: string[];
273
+ /** @description The IANA zone its days and times are read in. */
274
+ timeZone: string;
275
+ /**
276
+ * @description Repeat from when it was done ("every!"), not from the schedule: the next one is the rule's days counted from the day it was done.
277
+ * @default false
278
+ */
279
+ fromCompletion: boolean;
280
+ };
262
281
  /** @description FastAPI's default 422 shape (RequestValidationError). */
263
282
  ValidationErrorBody: {
264
283
  detail: {
@@ -1,6 +1,7 @@
1
1
  import type { ReactNode } from 'react';
2
2
  import { type MonthDay } from '../../lib/month-day.js';
3
3
  import { type PlainDate } from '../../lib/plain-date.js';
4
+ import { type Recurrence } from '../../lib/recurrence.js';
4
5
  import type { EditInPlace } from './edit-in-place.js';
5
6
  /** What the value saves as: with `required: true` never `null` (a blank is refused). */
6
7
  export type InPlaceSaved<TValue, TRequired extends boolean> = TRequired extends true ? TValue : TValue | null;
@@ -78,6 +79,23 @@ export type InPlaceMonthDayConfig<TRequired extends boolean = boolean> = {
78
79
  locale?: string;
79
80
  placeholder?: string;
80
81
  };
82
+ /**
83
+ * How something repeats (RecurrenceField): presets, a phrase read as it's
84
+ * typed, and a preview. Enter in the box or leaving the field saves; a
85
+ * phrase it can't read isn't saved. Not `required`: emptying the box saves
86
+ * `null` (doesn't repeat).
87
+ */
88
+ export type InPlaceRecurrenceConfig<TRequired extends boolean = boolean> = {
89
+ required?: TRequired;
90
+ /** The IANA zone a new repeat is read in. Defaults to the value's, else the browser's. */
91
+ timeZone?: string;
92
+ /** The times a new repeat starts with. Defaults to 09:00. */
93
+ defaultTimes?: string[];
94
+ /** Today, `'YYYY-MM-DD'`, and "now", for a fixed preview (tests). Default to the clock. */
95
+ today?: string;
96
+ now?: Date;
97
+ locale?: string;
98
+ };
81
99
  /** One option of a select: its value and its words. */
82
100
  export type InPlaceOption<T> = {
83
101
  value: T;
@@ -208,6 +226,13 @@ export declare const inPlace: {
208
226
  * Reads as "Mar 14"; February 29 is a day, February 30 is refused.
209
227
  */
210
228
  monthDay<R extends boolean = false>(options: Common<MonthDay | null | undefined, InPlaceSaved<MonthDay, R>> & InPlaceMonthDayConfig<R>): EditInPlace;
229
+ /**
230
+ * How something repeats (the contract's `Recurrence`) in RecurrenceField:
231
+ * presets, a phrase read as it's typed ("every 2nd tue at 9am") and a
232
+ * preview of the next five. Reads as its label ("Every 2nd Tue at 9:00
233
+ * AM"); Enter or leaving saves, and a phrase it can't read is refused.
234
+ */
235
+ recurrence<R extends boolean = false>(options: Common<Recurrence | null | undefined, InPlaceSaved<Recurrence, R>> & InPlaceRecurrenceConfig<R>): EditInPlace;
211
236
  /**
212
237
  * One of a fixed list; its list opens with the field and a pick saves.
213
238
  * `look: 'buttons'` draws it as ChoiceButtons (`inPlace.choice`).
@@ -4,10 +4,13 @@ import { InputGroup, InputGroupAddon, InputGroupInput, InputGroupText } from '..
4
4
  import { linkHost, linkRule } from '../../lib/link-href.js';
5
5
  import { formatMonthDay, monthDayProblem } from '../../lib/month-day.js';
6
6
  import { formatPlainDate, unreadableDateMessage } from '../../lib/plain-date.js';
7
+ import { normalizeRecurrence, recurrenceProblem } from '../../lib/recurrence.js';
8
+ import { formatRecurrence } from '../../lib/recurrence-format.js';
7
9
  import { ChoiceButtons } from './choice-buttons.js';
8
10
  import { DateField } from './date-field.js';
9
11
  import { MonthDayField } from './month-day-field.js';
10
12
  import { OptionSelect } from './option-select.js';
13
+ import { RecurrenceField } from './recurrence-field.js';
11
14
  import { Parts, ReferencePicker } from './edit-in-place-controls.js';
12
15
  import { LinkOut } from './row-edit-cells.js';
13
16
  const REQUIRED = 'Required';
@@ -177,6 +180,20 @@ function monthDayKind(config) {
177
180
  : undefined, "aria-label": props.label, "aria-describedby": props.describedBy })),
178
181
  };
179
182
  }
183
+ function recurrenceKind(config) {
184
+ return {
185
+ editKind: 'text',
186
+ toDraft: (value) => value ?? null,
187
+ check: (draft) => {
188
+ if (draft === null)
189
+ return config.required ? { ok: false, message: REQUIRED } : { ok: true, value: null };
190
+ const problem = recurrenceProblem(draft);
191
+ return problem ? { ok: false, message: problem } : { ok: true, value: normalizeRecurrence(draft) };
192
+ },
193
+ show: (value) => (value ? formatRecurrence(value, { locale: config.locale }) : null),
194
+ control: (props) => (_jsx(RecurrenceField, { id: props.id, value: props.value, onChange: props.onChange, onProblem: props.onProblem, timeZone: config.timeZone, defaultTimes: config.defaultTimes, today: config.today, now: config.now, locale: config.locale, invalid: props.invalid, readOnly: props.disabled, "aria-label": props.label, "aria-describedby": props.describedBy })),
195
+ };
196
+ }
180
197
  function selectKind(config) {
181
198
  const labelOf = (value) => config.options.find((option) => option.value === value)?.label ?? String(value);
182
199
  const shownOf = (value) => (config.render ? config.render(value, labelOf(value)) : labelOf(value));
@@ -421,6 +438,15 @@ export const inPlace = {
421
438
  monthDay(options) {
422
439
  return single(monthDayKind(options), { ...options, value: options.value || null });
423
440
  },
441
+ /**
442
+ * How something repeats (the contract's `Recurrence`) in RecurrenceField:
443
+ * presets, a phrase read as it's typed ("every 2nd tue at 9am") and a
444
+ * preview of the next five. Reads as its label ("Every 2nd Tue at 9:00
445
+ * AM"); Enter or leaving saves, and a phrase it can't read is refused.
446
+ */
447
+ recurrence(options) {
448
+ return single(recurrenceKind(options), { ...options, value: options.value ?? null });
449
+ },
424
450
  /**
425
451
  * One of a fixed list; its list opens with the field and a pick saves.
426
452
  * `look: 'buttons'` draws it as ChoiceButtons (`inPlace.choice`).
@@ -0,0 +1,36 @@
1
+ import { type Recurrence } from '../../lib/recurrence.js';
2
+ export type RecurrenceFieldProps = {
3
+ /** The phrase box's id, for the field's `<FieldLabel htmlFor>`. */
4
+ id?: string;
5
+ /** The repeat, or `null` for none. */
6
+ value: Recurrence | null;
7
+ /** Called with each readable repeat, or `null` when the box is emptied or can't be read. */
8
+ onChange: (value: Recurrence | null) => void;
9
+ /** The IANA zone a new repeat is read in. Defaults to the value's, else the browser's. */
10
+ timeZone?: string;
11
+ /** The times a new repeat starts with when the phrase has none. Defaults to the value's, else 09:00. */
12
+ defaultTimes?: string[];
13
+ /** Today, `'YYYY-MM-DD'`: where a phrase's days count from. Defaults to today in the zone. */
14
+ today?: string;
15
+ /** What "now" is for the preview's next occurrences. Defaults to the clock. */
16
+ now?: Date;
17
+ /** How many next occurrences the preview lists. Defaults to 5; 0 hides the list. */
18
+ previewCount?: number;
19
+ /** Show the preset buttons (the default). */
20
+ presets?: boolean;
21
+ locale?: string;
22
+ /** The value was refused: `aria-invalid` on the box. */
23
+ invalid?: boolean;
24
+ readOnly?: boolean;
25
+ /**
26
+ * Told when the phrase can't be read (with why), and `null` once it can:
27
+ * editing in place gives it to `onProblem`, so the field won't save.
28
+ */
29
+ onProblem?: (message: string | null) => void;
30
+ /** Called when the box is left, for a form's `onBlur`. */
31
+ onBlur?: () => void;
32
+ className?: string;
33
+ 'aria-label'?: string;
34
+ 'aria-describedby'?: string;
35
+ };
36
+ export declare function RecurrenceField({ id, value, onChange, timeZone, defaultTimes, today, now, previewCount, presets, locale, invalid, readOnly, onProblem, onBlur, className, 'aria-label': ariaLabel, 'aria-describedby': describedBy, }: RecurrenceFieldProps): import("react").JSX.Element;
@@ -0,0 +1,143 @@
1
+ import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
2
+ // How something repeats (#326): a reminder's or a task's schedule. The
3
+ // value is the contract's `Recurrence` (`lib/recurrence.ts`), or `null`
4
+ // for none.
5
+ //
6
+ // Three parts, one under the other:
7
+ // - **Presets**, a row of toggle buttons: Daily, Weekdays, Weekly on Thu,
8
+ // Monthly on the 12th, Monthly on the 2nd Thu, Yearly on Nov 12 (each
9
+ // from the start day) and Custom. The one the value is stays pressed;
10
+ // Custom is pressed for anything else, and moves to the phrase box.
11
+ // - **The phrase box**, read as you type (`parseRecurrencePhrase`): "every
12
+ // 2nd tue at 9am", "every! 3 days", "every jan 1 until mar 1". What it
13
+ // can't read is said under it, and the field gives `null`, so a form
14
+ // never keeps the rule it had before (DateField does the same).
15
+ // - **The preview**: the rule's label ("Every 2nd Tue at 9:00 AM") and its
16
+ // next five occurrences, in the rule's zone, or why it can't be read.
17
+ //
18
+ // One control for the form (a react-hook-form `Controller`) and for
19
+ // editing in place (`inPlace.recurrence`: Enter in the box or leaving the
20
+ // field saves). The box is the field's labelled control (`id`); the
21
+ // presets name themselves "Presets".
22
+ import { useId, useRef, useState } from 'react';
23
+ import { RepeatIcon } from 'lucide-react';
24
+ import { cn } from 'cn';
25
+ import { Input } from '../ui/input.js';
26
+ import { ToggleGroup, ToggleGroupItem } from '../ui/toggle-group.js';
27
+ import { formatOccurrence, formatRecurrence, todayIn } from '../../lib/recurrence-format.js';
28
+ import { ordinalWord, parseRecurrencePhrase, recurrencePhrase } from '../../lib/recurrence-phrase.js';
29
+ import { nextOccurrences, normalizeRecurrence, recurrenceProblem, WEEKDAY_CODES } from '../../lib/recurrence.js';
30
+ function weekdayOf(day) {
31
+ return (new Date(`${day}T00:00:00Z`).getUTCDay() + 6) % 7;
32
+ }
33
+ function dayName(day, locale) {
34
+ return new Intl.DateTimeFormat(locale, { weekday: 'short', timeZone: 'UTC' }).format(Date.UTC(2024, 0, 1 + day));
35
+ }
36
+ /** The presets for a start day: each a rule built from that day. */
37
+ function presetsFor(start, locale) {
38
+ const [year, month, date] = start.split('-').map(Number);
39
+ const weekday = weekdayOf(start);
40
+ const lastOfMonth = new Date(Date.UTC(year, month, 0)).getUTCDate();
41
+ // The 2nd Thu; the last one when it's the month's last (a 5th, or a 4th with no 5th).
42
+ const nth = date + 7 > lastOfMonth ? -1 : Math.ceil(date / 7);
43
+ const code = WEEKDAY_CODES[weekday];
44
+ const yearDay = new Intl.DateTimeFormat(locale, { month: 'short', day: 'numeric', timeZone: 'UTC' }).format(Date.UTC(2024, month - 1, date));
45
+ return [
46
+ { id: 'daily', label: 'Daily', rule: 'FREQ=DAILY' },
47
+ { id: 'weekdays', label: 'Weekdays', rule: 'FREQ=WEEKLY;BYDAY=MO,TU,WE,TH,FR' },
48
+ { id: 'weekly', label: `Weekly on ${dayName(weekday, locale)}`, rule: `FREQ=WEEKLY;BYDAY=${code}` },
49
+ { id: 'monthly', label: `Monthly on the ${ordinalWord(date)}`, rule: `FREQ=MONTHLY;BYMONTHDAY=${date}` },
50
+ {
51
+ id: 'nth',
52
+ label: `Monthly on the ${nth === -1 ? 'last' : ordinalWord(nth)} ${dayName(weekday, locale)}`,
53
+ rule: `FREQ=MONTHLY;BYDAY=${nth}${code}`,
54
+ },
55
+ { id: 'yearly', label: `Yearly on ${yearDay}`, rule: `FREQ=YEARLY;BYMONTH=${month};BYMONTHDAY=${date}` },
56
+ { id: 'custom', label: 'Custom', rule: null },
57
+ ];
58
+ }
59
+ function browserZone() {
60
+ try {
61
+ return Intl.DateTimeFormat().resolvedOptions().timeZone || 'UTC';
62
+ }
63
+ catch {
64
+ return 'UTC';
65
+ }
66
+ }
67
+ const same = (a, b) => JSON.stringify(a) === JSON.stringify(b);
68
+ export function RecurrenceField({ id, value, onChange, timeZone, defaultTimes, today, now, previewCount = 5, presets = true, locale, invalid = false, readOnly = false, onProblem, onBlur, className, 'aria-label': ariaLabel, 'aria-describedby': describedBy, }) {
69
+ const zone = value?.timeZone ?? timeZone ?? browserZone();
70
+ const day = today ?? todayIn(zone, now);
71
+ const ownId = useId();
72
+ const boxId = id ?? `${ownId}-phrase`;
73
+ const messageId = `${ownId}-message`;
74
+ const previewId = `${ownId}-preview`;
75
+ const box = useRef(null);
76
+ // The box's text, and the value it last read (or was given). A new value
77
+ // from outside (a preset, the form's reset) is written back as its phrase.
78
+ const [text, setText] = useState(() => (value ? (recurrencePhrase(value, day) ?? '') : ''));
79
+ const [problem, setProblem] = useState(null);
80
+ const [known, setKnown] = useState(value);
81
+ if (!same(known, value)) {
82
+ setKnown(value);
83
+ if (value !== null || problem === null) {
84
+ setText(value ? (recurrencePhrase(value, day) ?? '') : '');
85
+ setProblem(null);
86
+ }
87
+ }
88
+ const emit = (next, why) => {
89
+ setKnown(next);
90
+ setProblem(why);
91
+ onProblem?.(why);
92
+ onChange(next);
93
+ };
94
+ const read = (phrase) => {
95
+ setText(phrase);
96
+ if (phrase.trim() === '') {
97
+ emit(null, null);
98
+ return;
99
+ }
100
+ const result = parseRecurrencePhrase(phrase, {
101
+ today: day,
102
+ timeZone: zone,
103
+ times: value?.times ?? defaultTimes,
104
+ start: value?.start,
105
+ });
106
+ if (result.ok)
107
+ emit(result.value, null);
108
+ else
109
+ emit(null, result.error);
110
+ };
111
+ const start = value?.start ?? day;
112
+ const options = presetsFor(start, locale);
113
+ const pressed = value ? (options.find((option) => option.rule === value.rule)?.id ?? 'custom') : null;
114
+ const pick = (preset) => {
115
+ if (preset.rule === null) {
116
+ box.current?.focus();
117
+ return;
118
+ }
119
+ const next = normalizeRecurrence({
120
+ rule: preset.rule,
121
+ start,
122
+ times: value?.times ?? defaultTimes ?? ['09:00'],
123
+ timeZone: zone,
124
+ fromCompletion: false,
125
+ });
126
+ setText(recurrencePhrase(next, day) ?? '');
127
+ emit(next, null);
128
+ };
129
+ // A press on a preset is its own: Enter there mustn't also reach editing
130
+ // in place's Enter-saves (it would save the draft from before the press).
131
+ const keepEnter = (event) => {
132
+ if (event.key === 'Enter')
133
+ event.stopPropagation();
134
+ };
135
+ const stored = value ? recurrenceProblem(value) : null;
136
+ const shownProblem = problem ?? stored;
137
+ const upcoming = value && !shownProblem && previewCount > 0 ? nextOccurrences(value, now ?? new Date(), previewCount) : [];
138
+ return (_jsxs("div", { "data-slot": "recurrence-field", className: cn('flex min-w-0 flex-col gap-2', className), children: [presets && (_jsx(ToggleGroup, { "data-slot": "recurrence-presets", variant: "outline", spacing: 1, "aria-label": "Presets", value: pressed ? [pressed] : [], onValueChange: (next) => {
139
+ const chosen = options.find((option) => option.id === (next[0] ?? pressed));
140
+ if (chosen)
141
+ pick(chosen);
142
+ }, onKeyDown: keepEnter, disabled: readOnly, className: "max-w-full flex-wrap", children: options.map((option) => (_jsx(ToggleGroupItem, { value: option.id, className: "h-(--control-height,--spacing(8)) px-3 font-normal text-muted-foreground aria-pressed:font-medium aria-pressed:text-foreground", children: option.label }, option.id))) })), _jsxs("div", { className: "relative", children: [_jsx(RepeatIcon, { "aria-hidden": "true", className: "pointer-events-none absolute top-1/2 left-2.5 size-4 -translate-y-1/2 text-muted-foreground" }), _jsx(Input, { ref: box, id: boxId, value: text, onChange: (event) => read(event.target.value), onBlur: onBlur, readOnly: readOnly, placeholder: "every 2nd tue at 9am", autoComplete: "off", spellCheck: false, className: "pl-8", "aria-label": ariaLabel, "aria-invalid": invalid || !!shownProblem || undefined, "aria-describedby": [shownProblem ? messageId : previewId, describedBy].filter(Boolean).join(' ') || undefined })] }), _jsx("div", { "data-slot": "recurrence-preview", "aria-live": "polite", className: "text-sm", children: shownProblem ? (_jsx("p", { id: messageId, className: "text-destructive-text", children: shownProblem })) : value ? (_jsxs("div", { id: previewId, children: [_jsx("p", { className: "font-medium text-foreground", children: formatRecurrence(value, { locale }) }), previewCount > 0 && (_jsx(_Fragment, { children: upcoming.length ? (_jsx("ol", { "aria-label": "Next", className: "mt-1 flex flex-col gap-0.5 text-muted-foreground tabular-nums", children: upcoming.map((moment) => (_jsx("li", { children: formatOccurrence(moment, value.timeZone, { locale, now }) }, moment.getTime()))) })) : (_jsx("p", { className: "mt-1 text-muted-foreground", children: "No more to come." })) }))] })) : (_jsx("p", { id: previewId, className: "text-muted-foreground", children: "Doesn\u2019t repeat. Pick a preset or type how it repeats." })) })] }));
143
+ }
package/dist/index.d.ts CHANGED
@@ -37,7 +37,7 @@ export { JobStatus, type JobProgress, type JobStatusProps } from './components/a
37
37
  export { OfflineNotice, type OfflineNoticeProps } from './components/app/offline-notice.js';
38
38
  export { useOffline } from './lib/connection.js';
39
39
  export { editInPlace, type EditControlProps, type EditInPlace, type EditInPlaceList, type EditInPlaceListOptions, type EditInPlaceOptions, type EditKind, type EditListAddProps, type EditListItemProps, } from './components/app/edit-in-place.js';
40
- export { inPlace, type InPlaceDateConfig, type InPlaceFieldsOptions, type InPlaceLinkConfig, type InPlaceLinkValue, type InPlaceMoneyConfig, type InPlaceMonthDayConfig, type InPlaceNumberConfig, type InPlaceOption, type InPlacePart, type InPlaceRecord, type InPlaceReferenceConfig, type InPlaceSaved, type InPlaceSelectConfig, type InPlaceTextConfig, } from './components/app/edit-in-place-presets.js';
40
+ export { inPlace, type InPlaceDateConfig, type InPlaceFieldsOptions, type InPlaceLinkConfig, type InPlaceLinkValue, type InPlaceMoneyConfig, type InPlaceMonthDayConfig, type InPlaceNumberConfig, type InPlaceOption, type InPlacePart, type InPlaceRecord, type InPlaceRecurrenceConfig, type InPlaceReferenceConfig, type InPlaceSaved, type InPlaceSelectConfig, type InPlaceTextConfig, } from './components/app/edit-in-place-presets.js';
41
41
  export { linkHost, linkHref, linkRule } from './lib/link-href.js';
42
42
  export { DataEnvironmentBanner } from './components/app/data-environment-banner.js';
43
43
  export { EditableValue, type EditableValueProps } from './components/app/editable-value.js';
@@ -89,6 +89,10 @@ export { ImageField, type ImageFieldProps } from './components/app/image-field.j
89
89
  export { DEFAULT_IMAGE_TYPES, type ImageUpload, type ImageUploadResult } from './lib/image-file.js';
90
90
  export { formatPlainDate, parsePlainDate, plainDateExamples, unreadableDateMessage, type ParsePlainDateOptions, type PlainDate, } from './lib/plain-date.js';
91
91
  export { formatMonthDay, isMonthDay, monthDayProblem, type MonthDay } from './lib/month-day.js';
92
+ export { RecurrenceField, type RecurrenceFieldProps } from './components/app/recurrence-field.js';
93
+ export { atLocal, formatRule, nextAfterCompletion, nextOccurrence, nextOccurrences, normalizeRecurrence, parseRule, RecurrenceError, recurrenceFromWeekdays, recurrenceProblem, type Recurrence, type RuleParts, } from './lib/recurrence.js';
94
+ export { parseRecurrencePhrase, recurrencePhrase, type PhraseOptions, type PhraseResult, } from './lib/recurrence-phrase.js';
95
+ export { formatOccurrence, formatRecurrence, todayIn, type OccurrenceFormatOptions, type RecurrenceFormatOptions, } from './lib/recurrence-format.js';
92
96
  export { ChoiceCell, LinkCell, LinkOut, NameCell, type ChoiceCellProps, type LinkCellProps, type NameCellProps, } from './components/app/row-edit-cells.js';
93
97
  export { ModuleCard, ModuleStrip, type CategorySlot, type ModuleCardLink, type ModuleCardPlace, type ModuleCardProps, type ModuleStripMobile, type ModuleStripProps, } from './components/app/module-card.js';
94
98
  export { WidgetCard, WidgetCardGroup, WidgetList, WidgetListItem, type WidgetCardGroupProps, type WidgetCardLink, type WidgetCardProps, type WidgetListItemProps, } from './components/app/widget-card.js';