@ordinatio/ui 1.2.1 → 1.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -141,6 +141,45 @@ const messages: ThreadMessage[] = [...];
141
141
 
142
142
  ---
143
143
 
144
+ ### `<EntityPicker>`
145
+
146
+ A searchable single-select for a collection too large to list (people, companies, products): type, search through an async callback, choose by mouse or keyboard, clear. It knows nothing about what the items are.
147
+
148
+ ```tsx
149
+ import { EntityPicker } from '@ordinatio/ui';
150
+
151
+ <EntityPicker<Person>
152
+ value={selected} // controlled: the picker calls onChange, it never changes the value itself
153
+ onChange={setSelected} // the chosen item, or null when cleared
154
+ search={(query, signal) => findPeople(query, { signal })} // reject to show errorText; honour `signal` when you can
155
+ getKey={(person) => person.id}
156
+ getLabel={(person) => person.name || person.email}
157
+ ariaLabel="Person" // names the input AND its list; or pass `id` and use an external <label> (which names only the input)
158
+ name="contactId" // optional: a hidden input with the selected key, for plain forms / Server Actions
159
+ renderOption={(person, { active }) => <PersonRow person={person} active={active} />} // optional
160
+ />
161
+ ```
162
+
163
+ **Searching**
164
+ - Debounced (`debounceMs`, default 200); needs `minChars` typed (default 1; whitespace does not count, and the search receives the trimmed text).
165
+ - A superseded search is aborted, so a slow early answer can never overwrite a newer one.
166
+ - A failed search shows `errorText` (never silent: a `search` that rejects, throws, or resolves to something other than an array all count as failed); typing again retries.
167
+
168
+ **Keyboard, mouse and focus**
169
+ - The input shows the selected label until you type; leaving the field reverts a half-typed query to the selection (switching to another window does not). Focusing, choosing an option and Escape all leave the label selected, so typing replaces it instead of appending.
170
+ - Enter chooses the highlighted option and never submits an enclosing form while the popup (results or a status message) is showing. Arrow keys wrap and keep the highlight scrolled into view.
171
+ - While a new search is loading nothing is highlighted (hover included) and Enter and the arrow keys do nothing, so a result of an older query cannot be chosen by accident; clicking an option that is drawn still chooses it.
172
+ - Escape reverts typed text and closes the popup, and is not passed on to an enclosing dialog while there is either. Keys pressed while an IME is composing are ignored (`keyCode` 229 included; a few Android soft keyboards report 229 for every key, where Enter is then ignored but clicking still works).
173
+ - Options are chosen by click (so it works on touch); pressing anywhere in the popup, including its scrollbar, keeps focus in the input. Clearing returns focus to the input.
174
+
175
+ **Accessibility**
176
+ - Follows the WAI-ARIA 1.2 combobox pattern (role `combobox`, a `listbox` of `option`s that exists only when there are results; the loading, empty and error messages sit beside it, not inside). Those messages are announced through one always-mounted, visually hidden `role="status"` live region; the visible copies are `aria-hidden`.
177
+
178
+ **Forms, disabling and styling**
179
+ - `name` renders a hidden input with the selected key (`''` when none), for plain forms and Server Actions. `disabled` disables the input and the hidden input and removes the clear button; disabling while the user is typing reverts the text.
180
+ - Styling: plain elements with default inline styles. `classNames.<part>` (`root`, `input`, `clear`, `list`, `option`, `optionActive`, `message`) REPLACES that part's defaults entirely, so Tailwind or shadcn consumers can restyle everything; `style` layers onto the root defaults. Text props: `placeholder`, `clearLabel`, `loadingText`, `emptyText`, `errorText`. `clearable` (default true) shows a clear button while an item is selected.
181
+ - Nothing outlives the component: an unmounted picker cancels its timer and aborts its request.
182
+
144
183
  ## Hooks
145
184
 
146
185
  ### `useKeyboardShortcuts()`
package/dist/index.d.mts CHANGED
@@ -156,6 +156,221 @@ interface ArchiveButtonProps {
156
156
  */
157
157
  declare function ArchiveButton({ onArchive, archiving, disabled, label, archivingLabel, className, style, }: ArchiveButtonProps): react_jsx_runtime.JSX.Element;
158
158
 
159
+ interface EntityPickerClassNames {
160
+ root?: string;
161
+ input?: string;
162
+ clear?: string;
163
+ list?: string;
164
+ option?: string;
165
+ optionActive?: string;
166
+ message?: string;
167
+ }
168
+ interface EntityPickerProps<T> {
169
+ /** The selected item, or null. Controlled: the picker never changes it by itself, it calls `onChange`. */
170
+ value: T | null;
171
+ /** Called with the chosen item, or null when the selection is cleared. */
172
+ onChange: (item: T | null) => void;
173
+ /** Finds items for a query. Must honour `signal` when it can (a superseded search is aborted). Reject (or throw) to show `errorText`. */
174
+ search: (query: string, signal: AbortSignal) => Promise<T[]>;
175
+ /** A stable unique key for an item (used for list keys, the hidden input and ids). */
176
+ getKey: (item: T) => string;
177
+ /** The text for an item: shown in the input when selected, and the default option text. */
178
+ getLabel: (item: T) => string;
179
+ /** Draws an option row. Default: the label. */
180
+ renderOption?: (item: T, state: {
181
+ active: boolean;
182
+ }) => ReactNode;
183
+ /** Accessible name of the input AND its listbox. Pass this, or pass `id` and use an external <label> (which then names only the input). */
184
+ ariaLabel?: string;
185
+ id?: string;
186
+ /** When set, a hidden input with this name carries the selected key ('' when none), for plain forms. */
187
+ name?: string;
188
+ placeholder?: string;
189
+ disabled?: boolean;
190
+ /** Characters typed before a search runs (default 1). Typing fewer closes the list; nothing is searched on focus alone. */
191
+ minChars?: number;
192
+ /** Debounce in ms (default 200). */
193
+ debounceMs?: number;
194
+ /** Show a clear (×) button while an item is selected (default true). */
195
+ clearable?: boolean;
196
+ clearLabel?: string;
197
+ loadingText?: string;
198
+ emptyText?: string;
199
+ errorText?: string;
200
+ classNames?: EntityPickerClassNames;
201
+ /** Layered onto the ROOT's default styles only (to size or place the picker); other parts take `classNames`. */
202
+ style?: CSSProperties;
203
+ }
204
+ declare function EntityPicker<T>({ value, onChange, search, getKey, getLabel, renderOption, ariaLabel, id, name, placeholder, disabled, minChars, debounceMs, clearable, clearLabel, loadingText, emptyText, errorText, classNames, style, }: EntityPickerProps<T>): react_jsx_runtime.JSX.Element;
205
+
206
+ interface RichTextEditorProps {
207
+ /**
208
+ * Current HTML content. NOT sanitized by this component — see this
209
+ * file's own top-of-file "SANITIZATION CONTRACT" comment before passing
210
+ * anything other than this component's own onChange output back in.
211
+ * Updated externally (e.g. loading a draft) only applies while the
212
+ * editor is not focused — an external update while the user is actively
213
+ * typing would otherwise clobber their cursor position/in-progress edit.
214
+ */
215
+ content: string;
216
+ /** Called with the editor's current innerHTML on every edit. */
217
+ onChange: (html: string) => void;
218
+ placeholder?: string;
219
+ minHeight?: string;
220
+ maxHeight?: string;
221
+ autoFocus?: boolean;
222
+ /** Disables editing and hides the toolbar — for a read-only/sent state. Still subject to this file's own sanitization contract. */
223
+ editable?: boolean;
224
+ /**
225
+ * Temporarily blocks typing/formatting WITHOUT switching to the
226
+ * `editable={false}` rendering (toolbar and the contentEditable region
227
+ * stay mounted and visible, just inert) — for a brief, in-progress state
228
+ * like "a send is in flight" where `editable={false}`'s structural
229
+ * remount (see that prop's own branch) is the wrong tool: toggling the
230
+ * whole JSX branch gives the contentEditable region a BRAND NEW DOM node
231
+ * on the way back to editable, and this component's content-sync effect
232
+ * only re-populates a node it already knows changed, which byte-for-byte
233
+ * reproduced a real bug (WorldClass cycle 2) — a user's own just-typed
234
+ * content silently emptying out the moment a brief lock-then-unlock
235
+ * cycle completed. `locked` sets the DOM `contentEditable` attribute to
236
+ * false on the SAME node instead, so there is nothing to re-sync.
237
+ * Ignored when `editable={false}` (WorldClass cycle 3) — the read-only
238
+ * branch already has nothing interactive to lock, so `editable={false}`
239
+ * always wins if both are set.
240
+ */
241
+ locked?: boolean;
242
+ /**
243
+ * Optional extra toolbar content, right-aligned (e.g. a template picker
244
+ * in a consuming app). NOT covered by `locked` (WorldClass cycle 3) —
245
+ * this is arbitrary consumer-supplied content, not one of this
246
+ * component's own buttons, so there's nothing here for `locked` to
247
+ * reach; a consumer whose own toolbarRight content should also go inert
248
+ * while `locked` is set needs to gate that itself.
249
+ */
250
+ toolbarRight?: ReactNode;
251
+ /**
252
+ * Root-element override, matching ArchiveButton's own established
253
+ * contract: when given, the component renders "naked" (no inline
254
+ * defaults) on the ROOT element only. Unlike ArchiveButton (a single
255
+ * `<button>` with no internal structure), this component has real
256
+ * internal structure — a toolbar, buttons, the editable region — none of
257
+ * which `className`/`style` reach. Every sub-element instead carries a
258
+ * stable `ordinatio-rte-*` class (see each one below) specifically so
259
+ * external CSS can retheme them regardless of whether `className` is
260
+ * also set; there is no prop-level override for each sub-element.
261
+ */
262
+ className?: string;
263
+ style?: CSSProperties;
264
+ }
265
+ /**
266
+ * True when HTML has no visible text content (an empty editor's own
267
+ * innerHTML, e.g. "<br>" or "<p></p>"). Decodes &nbsp; (WorldClass cycle
268
+ * 1 — many browsers render a typed space in a contentEditable as a literal
269
+ * &nbsp; entity, not U+0020; stripping tags without decoding it left an
270
+ * &nbsp;-only body reading as non-empty text, silently enabling Send on a
271
+ * visually blank reply). Exported so ReplyPanel reuses this exact
272
+ * definition instead of carrying its own, independently-driftable copy.
273
+ */
274
+ declare function isEmptyHtml(html: string): boolean;
275
+ declare function RichTextEditor({ content, onChange, placeholder, minHeight, maxHeight, autoFocus, editable, locked, toolbarRight, className, style, }: RichTextEditorProps): react_jsx_runtime.JSX.Element;
276
+
277
+ /**
278
+ * Email compose mode — reply pre-fills the recipient,
279
+ * forward starts with an empty To field.
280
+ */
281
+ type ComposeMode = 'reply' | 'forward';
282
+ /**
283
+ * Reply layout modes for email detail pages.
284
+ * Controls how the compose panel is rendered.
285
+ */
286
+ type ReplyLayout = 'MODAL' | 'SPLIT_HORIZONTAL' | 'SPLIT_VERTICAL' | 'POPOUT';
287
+ /**
288
+ * All available reply layout options with labels for dropdowns.
289
+ */
290
+ declare const REPLY_LAYOUT_OPTIONS: {
291
+ value: ReplyLayout;
292
+ label: string;
293
+ }[];
294
+ /**
295
+ * Check if the layout renders the compose panel inline (not in a dialog).
296
+ */
297
+ declare function isInlineLayout(layout: ReplyLayout): boolean;
298
+ /**
299
+ * Check if the layout renders the compose panel in a dialog/modal.
300
+ */
301
+ declare function isModalLayout(layout: ReplyLayout): boolean;
302
+ /**
303
+ * Check if the layout opens compose in a new browser window.
304
+ */
305
+ declare function isPopoutLayout(layout: ReplyLayout): boolean;
306
+ interface SchedulePreset {
307
+ label: string;
308
+ date: Date;
309
+ }
310
+ /**
311
+ * Get the next occurrence of a weekday (Mon=1 ... Sun=0) at a given hour.
312
+ * If today matches but the hour has passed, returns next week.
313
+ */
314
+ declare function getNextWeekday(dayOfWeek: number, hour: number): Date;
315
+ /** Tomorrow at 9:00 AM local time. */
316
+ declare function getTomorrowMorning(): Date;
317
+ /** Next Monday at 9:00 AM local time. */
318
+ declare function getNextMondayMorning(): Date;
319
+ /**
320
+ * Quick schedule presets for "Send Later" UIs.
321
+ * Returns relative options (1h, 2h, tomorrow 9am, etc.).
322
+ *
323
+ * @example
324
+ * const options = getQuickScheduleOptions();
325
+ * // [{ label: "In 1 hour", date: Date }, ...]
326
+ */
327
+ declare function getQuickScheduleOptions(): SchedulePreset[];
328
+ /**
329
+ * Validate that a scheduled date is in the future.
330
+ */
331
+ declare function isValidScheduleDate(date: Date): boolean;
332
+ /**
333
+ * Parse a custom schedule from separate date and time strings.
334
+ * Returns null if invalid or in the past.
335
+ *
336
+ * @param dateStr - Date in YYYY-MM-DD format
337
+ * @param timeStr - Time in HH:MM format (default: "09:00")
338
+ */
339
+ declare function parseCustomSchedule(dateStr: string, timeStr?: string): Date | null;
340
+
341
+ interface ReplySendOverrides {
342
+ to?: string;
343
+ cc?: string;
344
+ bcc?: string;
345
+ subject?: string;
346
+ }
347
+ interface ReplyPanelProps {
348
+ /** 'reply' pre-fills To with the original sender; 'forward' starts with an empty To. */
349
+ mode?: ComposeMode;
350
+ /** The original message's subject — the panel strips any existing Re:/Fwd: prefix (case-insensitively) and applies its own mode's prefix exactly once; see prefixSubject's own doc comment for what this does and doesn't cover. */
351
+ subject: string;
352
+ /** Default To value for reply mode — the original sender's display name or email. Ignored in forward mode. */
353
+ toName: string;
354
+ /** Default To value for reply mode, preferred over toName when both are given (a real address, not just a display string). */
355
+ toEmail?: string;
356
+ /** Initial Cc value — e.g. the other original recipients, for a reply-all entry point. */
357
+ initialCc?: string;
358
+ /** Show the Cc/Bcc fields expanded from the start (e.g. already arriving as a reply-all). */
359
+ initialShowCcBcc?: boolean;
360
+ /** Called with the body HTML and any overrides the user actually changed (each field is undefined, not an empty string, when left at its default — so the caller only need pass what's genuinely different). */
361
+ onSend: (body: string, overrides: ReplySendOverrides) => Promise<void>;
362
+ /** Shown briefly after a successful send. Default: a generic per-mode confirmation. Pass '' to suppress it entirely. */
363
+ successMessage?: string;
364
+ onCancel?: () => void;
365
+ showCancel?: boolean;
366
+ sendButtonText?: string;
367
+ initialBody?: string;
368
+ /** Root-element override — see RichTextEditor's own identical contract (stable `ordinatio-reply-*` classes on every sub-element, not just the one `className`-targeted root). */
369
+ className?: string;
370
+ style?: CSSProperties;
371
+ }
372
+ declare function ReplyPanel({ mode, subject, toName, toEmail, initialCc, initialShowCcBcc, onSend, successMessage, onCancel, showCancel, sendButtonText, initialBody, className, style, }: ReplyPanelProps): react_jsx_runtime.JSX.Element;
373
+
159
374
  interface KeyboardShortcut {
160
375
  /** Key to listen for (e.g., 'r', 'e', 'Escape'). Case-insensitive. */
161
376
  key: string;
@@ -554,70 +769,6 @@ declare function truncatePreview(text: string | null | undefined, limit?: number
554
769
  */
555
770
  declare function stripHtml(html: string): string;
556
771
 
557
- /**
558
- * Email compose mode — reply pre-fills the recipient,
559
- * forward starts with an empty To field.
560
- */
561
- type ComposeMode = 'reply' | 'forward';
562
- /**
563
- * Reply layout modes for email detail pages.
564
- * Controls how the compose panel is rendered.
565
- */
566
- type ReplyLayout = 'MODAL' | 'SPLIT_HORIZONTAL' | 'SPLIT_VERTICAL' | 'POPOUT';
567
- /**
568
- * All available reply layout options with labels for dropdowns.
569
- */
570
- declare const REPLY_LAYOUT_OPTIONS: {
571
- value: ReplyLayout;
572
- label: string;
573
- }[];
574
- /**
575
- * Check if the layout renders the compose panel inline (not in a dialog).
576
- */
577
- declare function isInlineLayout(layout: ReplyLayout): boolean;
578
- /**
579
- * Check if the layout renders the compose panel in a dialog/modal.
580
- */
581
- declare function isModalLayout(layout: ReplyLayout): boolean;
582
- /**
583
- * Check if the layout opens compose in a new browser window.
584
- */
585
- declare function isPopoutLayout(layout: ReplyLayout): boolean;
586
- interface SchedulePreset {
587
- label: string;
588
- date: Date;
589
- }
590
- /**
591
- * Get the next occurrence of a weekday (Mon=1 ... Sun=0) at a given hour.
592
- * If today matches but the hour has passed, returns next week.
593
- */
594
- declare function getNextWeekday(dayOfWeek: number, hour: number): Date;
595
- /** Tomorrow at 9:00 AM local time. */
596
- declare function getTomorrowMorning(): Date;
597
- /** Next Monday at 9:00 AM local time. */
598
- declare function getNextMondayMorning(): Date;
599
- /**
600
- * Quick schedule presets for "Send Later" UIs.
601
- * Returns relative options (1h, 2h, tomorrow 9am, etc.).
602
- *
603
- * @example
604
- * const options = getQuickScheduleOptions();
605
- * // [{ label: "In 1 hour", date: Date }, ...]
606
- */
607
- declare function getQuickScheduleOptions(): SchedulePreset[];
608
- /**
609
- * Validate that a scheduled date is in the future.
610
- */
611
- declare function isValidScheduleDate(date: Date): boolean;
612
- /**
613
- * Parse a custom schedule from separate date and time strings.
614
- * Returns null if invalid or in the past.
615
- *
616
- * @param dateStr - Date in YYYY-MM-DD format
617
- * @param timeStr - Time in HH:MM format (default: "09:00")
618
- */
619
- declare function parseCustomSchedule(dateStr: string, timeStr?: string): Date | null;
620
-
621
772
  /**
622
773
  * Check if a file is a PDF by MIME type or file extension.
623
774
  * Handles Gmail's `application/octet-stream` by checking `.pdf` extension.
@@ -723,4 +874,4 @@ declare const ACTIVITY_ICONS: Record<string, IconComponent>;
723
874
  /** Return the icon component for a given icon name, or Activity as fallback. */
724
875
  declare function resolveActivityIcon(name: string): IconComponent;
725
876
 
726
- export { ACTIVITY_ICONS, ALL_SHORTCUT_CONTEXTS, ArchiveButton, type ArchiveButtonProps, CLIENT_PROFILE_SHORTCUTS, type CachedFetchOptions, type ComposeMode, EmailBodyRenderer, type EmailBodyRendererProps, EmailThreadView, type EmailThreadViewProps, ErrorBoundary, type ErrorBoundaryProps, FORM_SHORTCUTS, GLOBAL_SHORTCUTS, INBOX_SHORTCUTS, type KeyboardShortcut, KeyboardShortcutsPanel, RENDER_ERRORS, REPLY_LAYOUT_OPTIONS, type RenderErrorResult, type ReplyLayout, type SchedulePreset, type ShortcutContext, type ShortcutDefinition, type ThreadMessage, type UseAutoSaveOptions, type UseAutoSaveResult, type UseKeyboardShortcutsOptions, type UsePollingOptions, type UsePollingResult, type UsePreferencesOptions, type UsePreferencesResult, type UseServerSearchOptions, type UseServerSearchResult, cachedFetch, canViewInline, clearCache, formatDateGroup, formatFileSize, formatPhone, formatPhoneInput, getNextMondayMorning, getNextWeekday, getQuickScheduleOptions, getShortcut, getTomorrowMorning, groupByDate, invalidateCache, isAudio, isDocument, isImage, isInlineLayout, isModalLayout, isPdf, isPopoutLayout, isSpreadsheet, isTypingContext, isValidScheduleDate, isVideo, opensInNewTab, parseCustomSchedule, prefetch, renderError, resolveActivityIcon, resolveContentType, stripHtml, stripPhone, truncatePreview, useAutoSave, useContextShortcuts, useIframeFocusReclaim, useKeyboardShortcuts, usePolling, usePreferences, useServerSearch, withErrorBoundary };
877
+ export { ACTIVITY_ICONS, ALL_SHORTCUT_CONTEXTS, ArchiveButton, type ArchiveButtonProps, CLIENT_PROFILE_SHORTCUTS, type CachedFetchOptions, type ComposeMode, EmailBodyRenderer, type EmailBodyRendererProps, EmailThreadView, type EmailThreadViewProps, EntityPicker, type EntityPickerClassNames, type EntityPickerProps, ErrorBoundary, type ErrorBoundaryProps, FORM_SHORTCUTS, GLOBAL_SHORTCUTS, INBOX_SHORTCUTS, type KeyboardShortcut, KeyboardShortcutsPanel, RENDER_ERRORS, REPLY_LAYOUT_OPTIONS, type RenderErrorResult, type ReplyLayout, ReplyPanel, type ReplyPanelProps, type ReplySendOverrides, RichTextEditor, type RichTextEditorProps, type SchedulePreset, type ShortcutContext, type ShortcutDefinition, type ThreadMessage, type UseAutoSaveOptions, type UseAutoSaveResult, type UseKeyboardShortcutsOptions, type UsePollingOptions, type UsePollingResult, type UsePreferencesOptions, type UsePreferencesResult, type UseServerSearchOptions, type UseServerSearchResult, cachedFetch, canViewInline, clearCache, formatDateGroup, formatFileSize, formatPhone, formatPhoneInput, getNextMondayMorning, getNextWeekday, getQuickScheduleOptions, getShortcut, getTomorrowMorning, groupByDate, invalidateCache, isAudio, isDocument, isEmptyHtml, isImage, isInlineLayout, isModalLayout, isPdf, isPopoutLayout, isSpreadsheet, isTypingContext, isValidScheduleDate, isVideo, opensInNewTab, parseCustomSchedule, prefetch, renderError, resolveActivityIcon, resolveContentType, stripHtml, stripPhone, truncatePreview, useAutoSave, useContextShortcuts, useIframeFocusReclaim, useKeyboardShortcuts, usePolling, usePreferences, useServerSearch, withErrorBoundary };