@ordinatio/ui 1.1.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 ADDED
@@ -0,0 +1,273 @@
1
+ # @ordinatio/ui
2
+
3
+ Battle-tested React components and hooks extracted from System 1701. Zero external UI library dependencies — works with any React setup (Tailwind, shadcn, CSS modules, vanilla CSS).
4
+
5
+ ---
6
+
7
+ ## Quick Start
8
+
9
+ ```bash
10
+ npm install @ordinatio/ui
11
+ ```
12
+
13
+ ```typescript
14
+ import {
15
+ ErrorBoundary,
16
+ EmailBodyRenderer,
17
+ EmailThreadView,
18
+ useKeyboardShortcuts,
19
+ cachedFetch,
20
+ prefetch,
21
+ } from '@ordinatio/ui';
22
+ ```
23
+
24
+ **Peer dependency:** React 18+
25
+
26
+ ---
27
+
28
+ ## Components
29
+
30
+ ### `<ErrorBoundary>`
31
+
32
+ Catches React rendering crashes, generates a unique timestamped error reference, and displays a user-friendly error card with a copy button. Zero external dependencies — uses inline styles.
33
+
34
+ ```tsx
35
+ import { ErrorBoundary, withErrorBoundary } from '@ordinatio/ui';
36
+
37
+ // Wrap any component tree
38
+ <ErrorBoundary
39
+ title="Something went wrong"
40
+ message="An error occurred while loading this section."
41
+ refHint="Copy this code and send to support."
42
+ onError={(error, errorInfo) => logToService(error)}
43
+ renderActions={(reset) => (
44
+ <>
45
+ <button onClick={reset}>Try Again</button>
46
+ <button onClick={() => window.location.href = '/'}>Go Home</button>
47
+ </>
48
+ )}
49
+ >
50
+ <YourComponent />
51
+ </ErrorBoundary>
52
+
53
+ // Or use the HOC
54
+ const SafeComponent = withErrorBoundary(DangerousComponent, {
55
+ title: 'Widget Error',
56
+ });
57
+ ```
58
+
59
+ **Features:**
60
+ - Unique error ref: `RENDER_100-20260409T120000` (copyable with one click)
61
+ - Component stack trace (collapsed by default)
62
+ - Custom title, message, and hint text
63
+ - Custom action buttons via `renderActions`
64
+ - `onError` callback for external error tracking
65
+ - Fallback UI prop for fully custom error display
66
+ - Clipboard copy with 2-second confirmation feedback
67
+ - Works in `'use client'` components (Next.js App Router)
68
+
69
+ **Props:**
70
+
71
+ | Prop | Type | Description |
72
+ |------|------|-------------|
73
+ | `children` | `ReactNode` | Content to protect |
74
+ | `fallback` | `ReactNode` | Custom fallback UI (replaces default error card) |
75
+ | `onError` | `(error, info) => void` | Error callback |
76
+ | `errorCode` | `string` | Override error code (default: RENDER_100) |
77
+ | `title` | `string` | Error card title |
78
+ | `message` | `string` | Error card message |
79
+ | `refHint` | `string` | Text below the error ref |
80
+ | `renderActions` | `(reset) => ReactNode` | Custom action buttons |
81
+ | `showDashboardButton` | `boolean` | Show "Back to Dashboard" link |
82
+
83
+ ---
84
+
85
+ ### `<EmailBodyRenderer>`
86
+
87
+ Renders email HTML in an isolated iframe to prevent CSS bleed into the host app. Auto-resizes, strips `<style>` tags, and opens all links in new tabs.
88
+
89
+ ```tsx
90
+ import { EmailBodyRenderer } from '@ordinatio/ui';
91
+
92
+ <EmailBodyRenderer
93
+ bodyHtml={email.bodyHtml}
94
+ bodyText={email.bodyText}
95
+ snippet={email.snippet}
96
+ minHeight="300px"
97
+ iframeStyles="body { font-family: Georgia, serif; }"
98
+ className="my-custom-class"
99
+ />
100
+ ```
101
+
102
+ **Features:**
103
+ - Strips `<style>` tags (baseline CSS bleed defense)
104
+ - `<base target="_blank">` — all links open in new tabs
105
+ - Auto-resize via `onLoad` (fits content height + 32px padding)
106
+ - Sandboxed: `allow-same-origin allow-popups`
107
+ - `referrerPolicy="no-referrer"` for privacy
108
+ - Falls back to `<pre>` for plain text, paragraph for snippet
109
+ - Returns `null` when no content
110
+
111
+ ---
112
+
113
+ ### `<EmailThreadView>`
114
+
115
+ Gmail-style email thread with expand/collapse. Shows sender avatars, names, date, and snippet preview. Generic — works with any message type.
116
+
117
+ ```tsx
118
+ import { EmailThreadView } from '@ordinatio/ui';
119
+ import type { ThreadMessage } from '@ordinatio/ui';
120
+
121
+ const messages: ThreadMessage[] = [...];
122
+
123
+ <EmailThreadView
124
+ messages={messages}
125
+ initialExpanded={['msg-latest']}
126
+ renderMessage={(msg, isExpanded) => (
127
+ <CustomMessageRenderer message={msg} />
128
+ )}
129
+ />
130
+ ```
131
+
132
+ **Features:**
133
+ - Auto-expands last message by default
134
+ - Click header to toggle expand/collapse
135
+ - Sender avatar initial (from name or email)
136
+ - Date formatting: `Apr 7, 10:30 AM`
137
+ - Snippet preview on collapsed messages (80 char truncation)
138
+ - Custom `renderMessage` callback for full control
139
+ - Generic type: `EmailThreadView<T extends ThreadMessage>`
140
+ - Single message: renders directly without thread UI
141
+
142
+ ---
143
+
144
+ ## Hooks
145
+
146
+ ### `useKeyboardShortcuts()`
147
+
148
+ Declarative keyboard shortcuts that respect form inputs and support modifier keys.
149
+
150
+ ```tsx
151
+ import { useKeyboardShortcuts } from '@ordinatio/ui';
152
+
153
+ useKeyboardShortcuts({
154
+ shortcuts: [
155
+ { key: 'r', handler: () => handleReply() },
156
+ { key: 'e', handler: () => handleArchive() },
157
+ { key: 'Escape', handler: () => closeModal() },
158
+ { key: 'k', handler: () => openSearch(), modifiers: { meta: true } },
159
+ { key: 's', handler: () => save(), modifiers: { meta: true } },
160
+ ],
161
+ enabled: !isModalOpen, // Disable when modal is active
162
+ });
163
+ ```
164
+
165
+ **Features:**
166
+ - Case-insensitive key matching
167
+ - Auto-ignores when focused in `INPUT`, `TEXTAREA`, `SELECT`, or `contentEditable`
168
+ - Modifier key support: `meta`, `ctrl`, `alt`, `shift`
169
+ - Without modifiers specified: ignores if any modifier is pressed (prevents conflicts)
170
+ - `enabled` flag for conditional activation
171
+ - Custom `ignoreTags` array
172
+ - Cleanup on unmount
173
+
174
+ ---
175
+
176
+ ## Cache Utilities
177
+
178
+ ### `cachedFetch()`
179
+
180
+ Stale-while-revalidate caching for API responses. Returns cached data instantly, revalidates in background.
181
+
182
+ ```typescript
183
+ import { cachedFetch, invalidateCache, prefetch, clearCache } from '@ordinatio/ui';
184
+
185
+ // Fetch with caching
186
+ const data = await cachedFetch<InboxResponse>('/api/email/messages');
187
+ // 1st call: fetches from server, caches
188
+ // 2nd call (within 30s): returns cache instantly
189
+ // 2nd call (30s-5min): returns cache, revalidates in background
190
+
191
+ // With callback (fires twice if revalidating)
192
+ await cachedFetch('/api/data', undefined, (data, fromCache) => {
193
+ if (!fromCache) setData(data); // Update UI with fresh data
194
+ });
195
+
196
+ // Custom timing
197
+ await cachedFetch('/api/data', { staleTime: 60_000, maxAge: 10 * 60_000 });
198
+
199
+ // After a mutation, invalidate
200
+ invalidateCache('/api/email/messages');
201
+
202
+ // Prefetch on app load (fire-and-forget)
203
+ prefetch('/api/email/messages');
204
+ prefetch('/api/tasks');
205
+
206
+ // Clear everything
207
+ clearCache();
208
+ ```
209
+
210
+ **Defaults:**
211
+ - `staleTime`: 30 seconds (data is "fresh")
212
+ - `maxAge`: 5 minutes (data is evicted)
213
+
214
+ **Features:**
215
+ - In-flight deduplication (concurrent requests for same URL share one fetch)
216
+ - `onData` callback fires twice when revalidating: once with cache, once with fresh
217
+ - `invalidateCache()` forces next fetch to go to server
218
+ - `prefetch()` warms cache without blocking
219
+ - Type-safe with generics: `cachedFetch<T>(url)`
220
+
221
+ ---
222
+
223
+ ## Error System
224
+
225
+ ```typescript
226
+ import { renderError, RENDER_ERRORS } from '@ordinatio/ui';
227
+
228
+ const { code, ref, timestamp, module, context } = renderError('RENDER_100', {
229
+ message: error.message,
230
+ componentName: 'OrderForm',
231
+ });
232
+ // → { code: 'RENDER_100', ref: 'RENDER_100-20260409T120000', module: 'RENDER', ... }
233
+ ```
234
+
235
+ | Code | Description |
236
+ |------|-------------|
237
+ | RENDER_100 | Generic component rendering failure |
238
+ | RENDER_101 | Page failed to render (route-level) |
239
+ | RENDER_102 | Data display crashed (null/undefined) |
240
+
241
+ ---
242
+
243
+ ## Testing
244
+
245
+ ```bash
246
+ pnpm --filter @ordinatio/ui test
247
+ ```
248
+
249
+ **62 tests** across 6 test files:
250
+
251
+ | File | Tests | Coverage |
252
+ |------|-------|----------|
253
+ | `error-boundary.test.tsx` | 13 | Catch, display, reset, HOC, fallback, callbacks |
254
+ | `email-body-renderer.test.tsx` | 10 | Iframe, style strip, fallbacks, custom styles |
255
+ | `email-thread-view.test.tsx` | 12 | Expand/collapse, avatars, custom renderer |
256
+ | `use-keyboard-shortcuts.test.ts` | 9 | Keys, modifiers, input ignore, cleanup |
257
+ | `use-cached-fetch.test.ts` | 9 | Cache, revalidation, dedup, prefetch |
258
+ | `render-errors.test.ts` | 9 | Ref format, context, registry |
259
+
260
+ ---
261
+
262
+ ## Design Decisions
263
+
264
+ - **Zero UI library dependency** — Inline styles, no Tailwind/shadcn requirement. Works anywhere React runs.
265
+ - **className + style props** — Components accept both for Tailwind/CSS module layering.
266
+ - **Generic types** — `EmailThreadView<T>` accepts any message shape extending `ThreadMessage`.
267
+ - **Pure cache** — `cachedFetch` is a module-level singleton (survives SPA navigation).
268
+
269
+ ---
270
+
271
+ ## License
272
+
273
+ MIT — part of the Ordinatio platform.