@tristan2828/ui-foundation 4.94.0 → 4.96.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.
@@ -1,11 +1,6 @@
1
1
  import { jsx as _jsx, Fragment as _Fragment, jsxs as _jsxs } from "react/jsx-runtime";
2
- // What an empty value reads as on a record (form standard 22.2, #F17): a
3
- // dash in the muted text tone, everywhere, with "Not set" as what a screen
4
- // reader says for it. Words given instead ("No budget yet") read as they
5
- // are. EntityView, its strip (KeyStats) and the inPlace presets' fields all
6
- // show it.
7
2
  import { EMPTY_DASH } from '../../lib/empty-value.js';
8
- /** The empty text in the muted tone; the dash is read as "Not set". */
9
- export function EmptyText({ text = EMPTY_DASH, className }) {
10
- return (_jsx("span", { "data-slot": "empty-value", className: className ?? 'text-muted-foreground', children: text === EMPTY_DASH ? (_jsxs(_Fragment, { children: [_jsx("span", { "aria-hidden": "true", children: EMPTY_DASH }), _jsx("span", { className: "sr-only", children: "Not set" })] })) : (text) }));
3
+ /** The empty text in the muted tone; the dash is read as `label`, "Not set" by default. */
4
+ export function EmptyText({ text = EMPTY_DASH, label = 'Not set', className, ...props }) {
5
+ return (_jsx("span", { "data-slot": "empty-value", ...props, className: className ?? 'text-muted-foreground', children: text === EMPTY_DASH ? (_jsxs(_Fragment, { children: [_jsx("span", { "aria-hidden": "true", children: EMPTY_DASH }), _jsx("span", { className: "sr-only", children: label })] })) : (text) }));
11
6
  }
@@ -39,6 +39,7 @@ import { cn } from 'cn';
39
39
  import { Button } from '../ui/button.js';
40
40
  import { Card } from '../ui/card.js';
41
41
  import { Skeleton } from '../ui/skeleton.js';
42
+ import { EmptyText } from './empty-value.js';
42
43
  // Whole class names per slot, so Tailwind generates them.
43
44
  const ICON_CLASS = {
44
45
  1: 'text-category-1',
@@ -94,7 +95,7 @@ function ChipValue({ state, value }) {
94
95
  if (state === 'loading')
95
96
  return (_jsxs(_Fragment, { children: [_jsx(Skeleton, { className: "h-4 w-4" }), _jsx("span", { className: "sr-only", children: "Loading" })] }));
96
97
  if (state === 'error')
97
- return (_jsxs("span", { className: "text-muted-foreground", children: [_jsx("span", { "aria-hidden": "true", children: "\u2014" }), _jsx("span", { className: "sr-only", children: "Couldn't load" })] }));
98
+ return (_jsx(EmptyText, { label: "Couldn't load" }));
98
99
  if (value === undefined)
99
100
  return null;
100
101
  return (_jsx("span", { "data-slot": "module-card-chip-value", className: "font-semibold tabular-nums", children: value }));
@@ -27,6 +27,7 @@ import { Freshness } from './freshness.js';
27
27
  import { NeedsYou } from './needs-you.js';
28
28
  import { WidgetCard, WidgetCardGroup } from './widget-card.js';
29
29
  import { Skeleton } from '../ui/skeleton.js';
30
+ import { EmptyText } from './empty-value.js';
30
31
  const WIDE_QUERY = '(min-width: 48rem)';
31
32
  const canMatchMedia = () => typeof window !== 'undefined' && typeof window.matchMedia === 'function';
32
33
  function subscribeWide(listener) {
@@ -59,5 +60,5 @@ function PartCard({ part }) {
59
60
  function OverviewTile({ id, part, open, controls, onToggle, }) {
60
61
  const { icon: Icon } = part;
61
62
  const state = part.error ? 'error' : part.isLoading ? 'loading' : part.empty ? 'empty' : 'success';
62
- return (_jsxs("button", { type: "button", id: id, "data-slot": "overview-tile", "data-state": state, "aria-expanded": open, "aria-controls": controls, onClick: onToggle, className: cn('glow-edge flex w-full min-w-0 flex-col items-start gap-0.5 rounded-lg bg-card px-3 py-2.5 text-left text-card-foreground', 'shadow-(--card-shadow) ring-1 ring-border outline-none hover:bg-muted', 'focus-visible:ring-3 focus-visible:ring-ring/50 aria-expanded:ring-2 aria-expanded:ring-primary'), children: [_jsxs("span", { className: "flex min-w-0 max-w-full items-center gap-1.5 type-label text-muted-foreground", children: [Icon && _jsx(Icon, { "aria-hidden": "true", className: "size-4 shrink-0 text-link" }), _jsx("span", { className: "truncate", children: part.title })] }), state === 'loading' ? (_jsxs(_Fragment, { children: [_jsx(Skeleton, { "data-state": "loading", className: "my-1 h-6 w-16" }), _jsx("span", { className: "sr-only", children: "Loading" })] })) : state === 'error' ? (_jsxs("span", { "data-state": "error", className: "type-numeric text-muted-foreground", children: [_jsx("span", { "aria-hidden": "true", children: "\u2014" }), _jsx("span", { className: "sr-only", children: "Couldn't load" })] })) : state === 'empty' ? (_jsx("span", { "data-state": "empty", className: "py-0.5 type-body text-muted-foreground", children: "Nothing yet" })) : (part.value !== undefined && (_jsx("span", { "data-slot": "overview-tile-value", className: "max-w-full truncate type-numeric text-foreground", children: part.value }))), state === 'success' && part.freshness && _jsx(Freshness, { ...part.freshness })] }));
63
+ return (_jsxs("button", { type: "button", id: id, "data-slot": "overview-tile", "data-state": state, "aria-expanded": open, "aria-controls": controls, onClick: onToggle, className: cn('glow-edge flex w-full min-w-0 flex-col items-start gap-0.5 rounded-lg bg-card px-3 py-2.5 text-left text-card-foreground', 'shadow-(--card-shadow) ring-1 ring-border outline-none hover:bg-muted', 'focus-visible:ring-3 focus-visible:ring-ring/50 aria-expanded:ring-2 aria-expanded:ring-primary'), children: [_jsxs("span", { className: "flex min-w-0 max-w-full items-center gap-1.5 type-label text-muted-foreground", children: [Icon && _jsx(Icon, { "aria-hidden": "true", className: "size-4 shrink-0 text-link" }), _jsx("span", { className: "truncate", children: part.title })] }), state === 'loading' ? (_jsxs(_Fragment, { children: [_jsx(Skeleton, { "data-state": "loading", className: "my-1 h-6 w-16" }), _jsx("span", { className: "sr-only", children: "Loading" })] })) : state === 'error' ? (_jsx(EmptyText, { "data-state": "error", label: "Couldn't load", className: "type-numeric text-muted-foreground" })) : state === 'empty' ? (_jsx("span", { "data-state": "empty", className: "py-0.5 type-body text-muted-foreground", children: "Nothing yet" })) : (part.value !== undefined && (_jsx("span", { "data-slot": "overview-tile-value", className: "max-w-full truncate type-numeric text-foreground", children: part.value }))), state === 'success' && part.freshness && _jsx(Freshness, { ...part.freshness })] }));
63
64
  }
@@ -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
+ }
@@ -2,9 +2,10 @@ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
2
  import { cn } from 'cn';
3
3
  import { Badge } from '../ui/badge.js';
4
4
  import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '../ui/tooltip.js';
5
+ import { EmptyText } from './empty-value.js';
5
6
  export function ValueList({ items, max = 2, className }) {
6
7
  if (items.length === 0) {
7
- return (_jsxs("span", { "data-slot": "value-list", "data-state": "empty", className: cn('text-muted-foreground', className), children: [_jsx("span", { "aria-hidden": "true", children: "\u2014" }), _jsx("span", { className: "sr-only", children: "None" })] }));
8
+ return (_jsx(EmptyText, { "data-slot": "value-list", "data-state": "empty", label: "None", className: cn('text-muted-foreground', className) }));
8
9
  }
9
10
  const shown = items.slice(0, Math.max(0, max));
10
11
  const folded = items.slice(shown.length);
@@ -75,6 +75,7 @@ import { Card, CardContent, CardHeader } from '../ui/card.js';
75
75
  import { Skeleton } from '../ui/skeleton.js';
76
76
  import { useIsMobile } from '../../hooks/use-mobile.js';
77
77
  import { useRememberedFlag } from '../../hooks/use-remembered-flag.js';
78
+ import { EmptyText } from './empty-value.js';
78
79
  const HEADER_LINK_CLASS = 'shrink-0 rounded-sm type-label text-foreground underline underline-offset-4 outline-none ' +
79
80
  'hover:decoration-2 focus-visible:ring-3 focus-visible:ring-ring/50';
80
81
  export function WidgetCard({ id, title, icon: Icon, to, value, line, freshness, headingLevel = 2, link, isLoading, error, onRetry, isEmpty, emptyMessage, empty, skeletonRows = 3, collapsible = false, defaultCollapsed = false, storageKey, summary: ownSummary, emptySummary, children, className, }) {
@@ -115,7 +116,7 @@ function WidgetCardSummary({ state, summary, emptySummary, }) {
115
116
  return (_jsxs(_Fragment, { children: [_jsx(Skeleton, { "data-state": "loading", className: "h-4 w-8" }), _jsx("span", { className: "sr-only", children: "Loading" })] }));
116
117
  }
117
118
  if (state === 'error') {
118
- return (_jsxs("span", { "data-state": "error", className: "type-label text-muted-foreground", children: [_jsx("span", { "aria-hidden": "true", children: "\u2014" }), _jsx("span", { className: "sr-only", children: "Couldn't load" })] }));
119
+ return (_jsx(EmptyText, { "data-state": "error", label: "Couldn't load", className: "type-label text-muted-foreground" }));
119
120
  }
120
121
  if (state === 'empty') {
121
122
  return emptySummary === undefined ? null : (_jsx("span", { "data-state": "empty", className: "type-label text-muted-foreground", children: emptySummary }));
package/dist/index.d.ts CHANGED
@@ -22,6 +22,8 @@ export { ChoiceButtons, type ChoiceButtonsOption, type ChoiceButtonsProps } from
22
22
  export { ReferenceCombobox, type ReferenceComboboxProps, type ReferenceRecord } from './components/app/reference-combobox.js';
23
23
  export { fieldRows, type FieldKind, type FieldRowItem, type FieldRowPlace, type FieldSize } from './lib/field-rows.js';
24
24
  export { KeyStats, type KeyStat, type KeyStatsProps } from './components/app/key-stats.js';
25
+ export { EmptyText, type EmptyTextProps } from './components/app/empty-value.js';
26
+ export { isEmptyValue } from './lib/empty-value.js';
25
27
  export { IconAction, type IconActionProps } from './components/app/icon-action.js';
26
28
  export { EntityView, type EntityViewEmptyFields, type EntityViewField, type EntityViewLayout, type EntityViewMobileOrder, type EntityViewPlacement, type EntityViewProps, type EntityViewRailFields, type EntityViewSection, } from './components/app/entity-view.js';
27
29
  export { entityViewTabSlug } from './lib/entity-view-tab.js';
@@ -29,7 +31,7 @@ export { usePrinting } from './components/app/print-context.js';
29
31
  export { RecordDialogRoute, RecordLink, type RecordDialogRouteProps, type RecordLinkProps, } from './components/app/record-dialog.js';
30
32
  export { recordDialogState, useNewRecordDialog, useOpenRecord, useRecordDialog, type NewRecordDialogContextValue, type RecordDialogBackground, type RecordDialogContextValue, type RecordDialogState, } from './components/app/record-dialog-context.js';
31
33
  export { FormDialog, type FormDialogProps } from './components/app/form-dialog.js';
32
- export { DeleteAction, type DeleteActionProps, type DeleteKind } from './components/app/delete-action.js';
34
+ export { DeleteAction, type DeleteActionProps, type DeleteKind, type DeleteReason } from './components/app/delete-action.js';
33
35
  export { notify, doneMessage, pastTense, type NotifyDoneOptions } from './components/app/notify.js';
34
36
  export { useAction, type ActionOutcome, type ActionState, type UseActionOptions } from './hooks/use-action.js';
35
37
  export { ActionError, type ActionErrorProps } from './components/app/action-error.js';
@@ -37,7 +39,7 @@ export { JobStatus, type JobProgress, type JobStatusProps } from './components/a
37
39
  export { OfflineNotice, type OfflineNoticeProps } from './components/app/offline-notice.js';
38
40
  export { useOffline } from './lib/connection.js';
39
41
  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';
42
+ 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
43
  export { linkHost, linkHref, linkRule } from './lib/link-href.js';
42
44
  export { DataEnvironmentBanner } from './components/app/data-environment-banner.js';
43
45
  export { EditableValue, type EditableValueProps } from './components/app/editable-value.js';
@@ -89,6 +91,10 @@ export { ImageField, type ImageFieldProps } from './components/app/image-field.j
89
91
  export { DEFAULT_IMAGE_TYPES, type ImageUpload, type ImageUploadResult } from './lib/image-file.js';
90
92
  export { formatPlainDate, parsePlainDate, plainDateExamples, unreadableDateMessage, type ParsePlainDateOptions, type PlainDate, } from './lib/plain-date.js';
91
93
  export { formatMonthDay, isMonthDay, monthDayProblem, type MonthDay } from './lib/month-day.js';
94
+ export { RecurrenceField, type RecurrenceFieldProps } from './components/app/recurrence-field.js';
95
+ export { atLocal, formatRule, nextAfterCompletion, nextOccurrence, nextOccurrences, normalizeRecurrence, parseRule, RecurrenceError, recurrenceFromWeekdays, recurrenceProblem, type Recurrence, type RuleParts, } from './lib/recurrence.js';
96
+ export { parseRecurrencePhrase, recurrencePhrase, type PhraseOptions, type PhraseResult, } from './lib/recurrence-phrase.js';
97
+ export { formatOccurrence, formatRecurrence, todayIn, type OccurrenceFormatOptions, type RecurrenceFormatOptions, } from './lib/recurrence-format.js';
92
98
  export { ChoiceCell, LinkCell, LinkOut, NameCell, type ChoiceCellProps, type LinkCellProps, type NameCellProps, } from './components/app/row-edit-cells.js';
93
99
  export { ModuleCard, ModuleStrip, type CategorySlot, type ModuleCardLink, type ModuleCardPlace, type ModuleCardProps, type ModuleStripMobile, type ModuleStripProps, } from './components/app/module-card.js';
94
100
  export { WidgetCard, WidgetCardGroup, WidgetList, WidgetListItem, type WidgetCardGroupProps, type WidgetCardLink, type WidgetCardProps, type WidgetListItemProps, } from './components/app/widget-card.js';
package/dist/index.js CHANGED
@@ -26,6 +26,10 @@ export { ChoiceButtons } from './components/app/choice-buttons.js';
26
26
  export { ReferenceCombobox } from './components/app/reference-combobox.js';
27
27
  export { fieldRows } from './lib/field-rows.js';
28
28
  export { KeyStats } from './components/app/key-stats.js';
29
+ // The record's empty value (4.96): a muted dash read as "Not set", for an
30
+ // app's own strips, summary lines and cells.
31
+ export { EmptyText } from './components/app/empty-value.js';
32
+ export { isEmptyValue } from './lib/empty-value.js';
29
33
  export { IconAction } from './components/app/icon-action.js';
30
34
  export { EntityView, } from './components/app/entity-view.js';
31
35
  export { entityViewTabSlug } from './lib/entity-view-tab.js';
@@ -93,6 +97,10 @@ export { ImageField } from './components/app/image-field.js';
93
97
  export { DEFAULT_IMAGE_TYPES } from './lib/image-file.js';
94
98
  export { formatPlainDate, parsePlainDate, plainDateExamples, unreadableDateMessage, } from './lib/plain-date.js';
95
99
  export { formatMonthDay, isMonthDay, monthDayProblem } from './lib/month-day.js';
100
+ export { RecurrenceField } from './components/app/recurrence-field.js';
101
+ export { atLocal, formatRule, nextAfterCompletion, nextOccurrence, nextOccurrences, normalizeRecurrence, parseRule, RecurrenceError, recurrenceFromWeekdays, recurrenceProblem, } from './lib/recurrence.js';
102
+ export { parseRecurrencePhrase, recurrencePhrase, } from './lib/recurrence-phrase.js';
103
+ export { formatOccurrence, formatRecurrence, todayIn, } from './lib/recurrence-format.js';
96
104
  export { ChoiceCell, LinkCell, LinkOut, NameCell, } from './components/app/row-edit-cells.js';
97
105
  export { ModuleCard, ModuleStrip, } from './components/app/module-card.js';
98
106
  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 };