@ordinatio/ui 1.6.0 → 1.7.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
@@ -245,6 +245,13 @@ Structure (each point is a test):
245
245
 
246
246
  ## Hooks
247
247
 
248
+ ### Form and screen hooks (1.7.0)
249
+
250
+ - `useFormActionKeepingInput(action, initialState)` returns `[state, onSubmit, pending]`: submits a form to an async action and keeps what the person typed when the action answers with an error. Needs React 19. The action must RETURN its errors (a thrown error goes to the error boundary). Put `onSubmit` on the form and give the form no `action` prop.
251
+ - `useSyncedSelect(value, resultKey)` returns a ref for a controlled `<select>`: keeps it showing `value` after a form reset. Pass the action's result as `resultKey`; every result must be a NEW object, never `null` or a shared constant.
252
+ - `useSavedNotice(state)` returns `{ showSaved, markEdited }`: a "Saved" notice that hides on the next edit. Every action result must be a new object.
253
+ - `useArrival<E extends HTMLElement>(active)` returns `{ ref, soft }`: scrolls a newly arrived row into view, focuses it and softens its highlight after `ARRIVAL_FADE_MS`, once per mount. The type argument is required; give the element `tabIndex={-1}`.
254
+
248
255
  ### `useKeyboardShortcuts()`
249
256
 
250
257
  Declarative keyboard shortcuts that respect form inputs and support modifier keys.
package/dist/index.d.mts CHANGED
@@ -1,6 +1,6 @@
1
1
  import * as react_jsx_runtime from 'react/jsx-runtime';
2
- import * as React from 'react';
3
- import { Component, ReactNode, ErrorInfo, ComponentType, CSSProperties, ElementType, RefObject } from 'react';
2
+ import * as react from 'react';
3
+ import { Component, ReactNode, ErrorInfo, ComponentType, CSSProperties, ElementType, RefObject, FormEvent } from 'react';
4
4
 
5
5
  interface ErrorBoundaryProps {
6
6
  children: ReactNode;
@@ -752,6 +752,42 @@ declare function useServerSearch<T>({ fetcher, debounce, minChars, enabled, }: U
752
752
  */
753
753
  declare function useIframeFocusReclaim(containerRef: RefObject<HTMLDivElement | null>, enabled?: boolean, iframeSelector?: string): void;
754
754
 
755
+ /**
756
+ * Submits a form to a server action without React resetting the fields. Needs React 19.
757
+ * Give the form `onSubmit={onSubmit}` and `method="post"`, and NO `action` prop. The action must RETURN its errors as state.
758
+ * @returns `[state, onSubmit, pending]`
759
+ */
760
+ declare function useFormActionKeepingInput<State>(action: (previousState: State, formData: FormData) => Promise<State>, initialState: State): readonly [State, (event: FormEvent<HTMLFormElement>) => void, boolean];
761
+
762
+ /**
763
+ * Keeps a controlled `<select>` showing `value` after a form action reset the form.
764
+ * Put the returned ref on the select; pass the state returned by useActionState as `resultKey`.
765
+ * Every action result must be a NEW value (a new object each time): with `null` or a shared constant the hook cannot see
766
+ * that an action finished, the select shows its first option, and the next submit sends that wrong value.
767
+ */
768
+ declare function useSyncedSelect(value: string, resultKey: unknown): RefObject<HTMLSelectElement | null>;
769
+
770
+ /**
771
+ * A "Saved" notice that hides on the next edit. `state` is the action's result: every result must be a NEW object
772
+ * (a shared constant such as `const OK = { saved: true }` would never show "Saved" a second time after an edit).
773
+ */
774
+ declare function useSavedNotice(state: {
775
+ saved?: boolean;
776
+ }): {
777
+ showSaved: boolean;
778
+ markEdited: () => void;
779
+ };
780
+
781
+ declare const ARRIVAL_FADE_MS = 3000;
782
+ /**
783
+ * Scrolls to, focuses and (after about 3 seconds) softens the one item a link asked for, once per mount.
784
+ * Pass the element type, e.g. `useArrival<HTMLLIElement>(active)`; put `ref` on the element and give it `tabIndex={-1}`.
785
+ */
786
+ declare function useArrival<E extends HTMLElement>(active: boolean): {
787
+ ref: react.RefObject<E | null>;
788
+ soft: boolean;
789
+ };
790
+
755
791
  interface CachedFetchOptions {
756
792
  /** fetch RequestInit options */
757
793
  fetchOptions?: RequestInit;
@@ -962,11 +998,11 @@ declare const RENDER_ERRORS: Record<string, {
962
998
  diagnosis: string[];
963
999
  }>;
964
1000
 
965
- type IconComponent = React.ComponentType<{
1001
+ type IconComponent = react.ComponentType<{
966
1002
  className?: string;
967
1003
  }>;
968
1004
  declare const ACTIVITY_ICONS: Record<string, IconComponent>;
969
1005
  /** Return the icon component for a given icon name, or Activity as fallback. */
970
1006
  declare function resolveActivityIcon(name: string): IconComponent;
971
1007
 
972
- export { ACTIVITY_ICONS, ALL_SHORTCUT_CONTEXTS, type ActivityFeedChip, ActivityFeedRow, type ActivityFeedRowClassNames, type ActivityFeedRowProps, ArchiveButton, type ArchiveButtonProps, CLIENT_PROFILE_SHORTCUTS, type CachedFetchOptions, type ComposeMode, ConfirmAction, type ConfirmActionClassNames, type ConfirmActionProps, type ConfirmActionResult, 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 };
1008
+ export { ACTIVITY_ICONS, ALL_SHORTCUT_CONTEXTS, ARRIVAL_FADE_MS, type ActivityFeedChip, ActivityFeedRow, type ActivityFeedRowClassNames, type ActivityFeedRowProps, ArchiveButton, type ArchiveButtonProps, CLIENT_PROFILE_SHORTCUTS, type CachedFetchOptions, type ComposeMode, ConfirmAction, type ConfirmActionClassNames, type ConfirmActionProps, type ConfirmActionResult, 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, useArrival, useAutoSave, useContextShortcuts, useFormActionKeepingInput, useIframeFocusReclaim, useKeyboardShortcuts, usePolling, usePreferences, useSavedNotice, useServerSearch, useSyncedSelect, withErrorBoundary };
package/dist/index.mjs CHANGED
@@ -805,6 +805,7 @@ var defaults2 = {
805
805
  actions: { display: "flex", flexWrap: "wrap", alignItems: "center", gap: "8px" }
806
806
  };
807
807
  var aboveOverlay = { position: "relative", zIndex: 1 };
808
+ var aboveOverlayShrunk = { ...aboveOverlay, width: "fit-content", maxWidth: "100%" };
808
809
  var visuallyHidden = { position: "absolute", width: "1px", height: "1px", overflow: "hidden", clip: "rect(0 0 0 0)", whiteSpace: "nowrap" };
809
810
  function ActivityFeedRow({
810
811
  sentence,
@@ -858,7 +859,7 @@ function ActivityFeedRow({
858
859
  ] }),
859
860
  /* @__PURE__ */ jsx6("time", { dateTime: valid ? date.toISOString() : void 0, ...part("time"), children: shownTime })
860
861
  ] }),
861
- shownChips.length > 0 || shownTags.length > 0 || hiddenTags > 0 ? /* @__PURE__ */ jsxs5("div", { ...part("chips", aboveOverlay), children: [
862
+ shownChips.length > 0 || shownTags.length > 0 || hiddenTags > 0 ? /* @__PURE__ */ jsxs5("div", { ...part("chips", aboveOverlayShrunk), children: [
862
863
  shownChips.map((chip, index) => chipNode(chip, `chip-${index}`, "chip")),
863
864
  shownTags.length > 0 ? /* @__PURE__ */ jsx6("span", { ...part("tagsLabel"), children: tagsLabel }) : null,
864
865
  shownTags.map((tag, index) => chipNode(tag, `tag-${index}`, "tag")),
@@ -871,7 +872,7 @@ function ActivityFeedRow({
871
872
  ] })
872
873
  ] }) : null
873
874
  ] }) : null,
874
- actions ? /* @__PURE__ */ jsx6("div", { ...part("actions", aboveOverlay), children: actions }) : null,
875
+ actions ? /* @__PURE__ */ jsx6("div", { ...part("actions", aboveOverlayShrunk), children: actions }) : null,
875
876
  clickable ? /* @__PURE__ */ jsx6(Link, { href, "aria-hidden": "true", tabIndex: -1, ...part("overlay", { position: "absolute", top: 0, right: 0, bottom: 0, left: 0 }) }) : null
876
877
  ] });
877
878
  }
@@ -2186,6 +2187,69 @@ function useIframeFocusReclaim(containerRef, enabled = true, iframeSelector = "i
2186
2187
  }, [containerRef, enabled, iframeSelector]);
2187
2188
  }
2188
2189
 
2190
+ // src/hooks/use-form-action-keeping-input.ts
2191
+ import { useRef as useRef9, useState as useState11, useTransition } from "react";
2192
+ function useFormActionKeepingInput(action, initialState) {
2193
+ const [state, setState] = useState11(initialState);
2194
+ const [pending, startTransition] = useTransition();
2195
+ const inFlight = useRef9(false);
2196
+ const onSubmit = (event) => {
2197
+ event.preventDefault();
2198
+ if (inFlight.current || pending) return;
2199
+ const submitter = event.nativeEvent.submitter;
2200
+ const formData = new FormData(event.currentTarget, submitter);
2201
+ inFlight.current = true;
2202
+ startTransition(async () => {
2203
+ try {
2204
+ const next = await action(state, formData);
2205
+ setState(next);
2206
+ } finally {
2207
+ inFlight.current = false;
2208
+ }
2209
+ });
2210
+ };
2211
+ return [state, onSubmit, pending];
2212
+ }
2213
+
2214
+ // src/hooks/use-synced-select.ts
2215
+ import { useLayoutEffect, useRef as useRef10 } from "react";
2216
+ function useSyncedSelect(value, resultKey) {
2217
+ const ref = useRef10(null);
2218
+ useLayoutEffect(() => {
2219
+ if (ref.current && ref.current.value !== value) ref.current.value = value;
2220
+ }, [value, resultKey]);
2221
+ return ref;
2222
+ }
2223
+
2224
+ // src/hooks/use-saved-notice.ts
2225
+ import { useState as useState12 } from "react";
2226
+ function useSavedNotice(state) {
2227
+ const [editedAfter, setEditedAfter] = useState12(null);
2228
+ return {
2229
+ showSaved: Boolean(state.saved) && editedAfter !== state,
2230
+ markEdited: () => setEditedAfter(state)
2231
+ };
2232
+ }
2233
+
2234
+ // src/hooks/use-arrival.ts
2235
+ import { useEffect as useEffect12, useRef as useRef11, useState as useState13 } from "react";
2236
+ var ARRIVAL_FADE_MS = 3e3;
2237
+ function useArrival(active) {
2238
+ const ref = useRef11(null);
2239
+ const done = useRef11(false);
2240
+ const [soft, setSoft] = useState13(false);
2241
+ useEffect12(() => {
2242
+ const element = ref.current;
2243
+ if (!active || done.current || !element) return;
2244
+ done.current = true;
2245
+ const reduceMotion = typeof window.matchMedia === "function" && window.matchMedia("(prefers-reduced-motion: reduce)").matches;
2246
+ element.scrollIntoView({ block: "center", behavior: reduceMotion ? "auto" : "smooth" });
2247
+ element.focus({ preventScroll: true });
2248
+ setTimeout(() => setSoft(true), ARRIVAL_FADE_MS);
2249
+ }, [active]);
2250
+ return { ref, soft };
2251
+ }
2252
+
2189
2253
  // src/hooks/use-cached-fetch.ts
2190
2254
  var cache = /* @__PURE__ */ new Map();
2191
2255
  var inflight = /* @__PURE__ */ new Map();
@@ -2241,14 +2305,14 @@ function clearCache() {
2241
2305
  }
2242
2306
 
2243
2307
  // src/hooks/use-preferences.ts
2244
- import { useState as useState11, useEffect as useEffect12, useCallback as useCallback8 } from "react";
2308
+ import { useState as useState14, useEffect as useEffect13, useCallback as useCallback8 } from "react";
2245
2309
  function usePreferences({
2246
2310
  endpoint,
2247
2311
  defaults: defaults4
2248
2312
  }) {
2249
- const [preferences, setPreferences] = useState11(defaults4 ?? null);
2250
- const [loading, setLoading] = useState11(true);
2251
- const [error, setError] = useState11(null);
2313
+ const [preferences, setPreferences] = useState14(defaults4 ?? null);
2314
+ const [loading, setLoading] = useState14(true);
2315
+ const [error, setError] = useState14(null);
2252
2316
  const fetchPreferences = useCallback8(async () => {
2253
2317
  try {
2254
2318
  setError(null);
@@ -2268,7 +2332,7 @@ function usePreferences({
2268
2332
  setLoading(false);
2269
2333
  }
2270
2334
  }, [endpoint, defaults4]);
2271
- useEffect12(() => {
2335
+ useEffect13(() => {
2272
2336
  fetchPreferences();
2273
2337
  }, [fetchPreferences]);
2274
2338
  const updatePreferences = useCallback8(
@@ -2625,6 +2689,7 @@ function resolveActivityIcon(name) {
2625
2689
  export {
2626
2690
  ACTIVITY_ICONS,
2627
2691
  ALL_SHORTCUT_CONTEXTS,
2692
+ ARRIVAL_FADE_MS,
2628
2693
  ActivityFeedRow,
2629
2694
  ArchiveButton,
2630
2695
  CLIENT_PROFILE_SHORTCUTS,
@@ -2676,12 +2741,16 @@ export {
2676
2741
  stripHtml,
2677
2742
  stripPhone,
2678
2743
  truncatePreview,
2744
+ useArrival,
2679
2745
  useAutoSave,
2680
2746
  useContextShortcuts,
2747
+ useFormActionKeepingInput,
2681
2748
  useIframeFocusReclaim,
2682
2749
  useKeyboardShortcuts,
2683
2750
  usePolling,
2684
2751
  usePreferences,
2752
+ useSavedNotice,
2685
2753
  useServerSearch,
2754
+ useSyncedSelect,
2686
2755
  withErrorBoundary
2687
2756
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ordinatio/ui",
3
- "version": "1.6.0",
3
+ "version": "1.7.0",
4
4
  "private": false,
5
5
  "license": "MIT",
6
6
  "description": "Reusable React components and hooks for Ordinatio applications",