@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/dist/index.mjs ADDED
@@ -0,0 +1,1658 @@
1
+ // src/components/error-boundary.tsx
2
+ import { Component, useState } from "react";
3
+
4
+ // src/lib/render-errors.ts
5
+ var MODULE = "RENDER";
6
+ function renderError(code, context) {
7
+ const ts = (/* @__PURE__ */ new Date()).toISOString().replace(/[-:]/g, "").replace(/\.\d+Z$/, "");
8
+ const ref = `${code}-${ts}`;
9
+ return {
10
+ code,
11
+ ref,
12
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
13
+ module: MODULE,
14
+ context: context ?? {}
15
+ };
16
+ }
17
+ var RENDER_ERRORS = {
18
+ RENDER_100: {
19
+ code: "RENDER_100",
20
+ severity: "error",
21
+ description: "A component failed to render",
22
+ diagnosis: [
23
+ "Check the component stack below for which component crashed",
24
+ "The error message usually indicates a null/undefined property access",
25
+ "Give the error ref to Claude for instant diagnosis"
26
+ ]
27
+ },
28
+ RENDER_101: {
29
+ code: "RENDER_101",
30
+ severity: "error",
31
+ description: "Page failed to load",
32
+ diagnosis: [
33
+ "The entire page crashed during rendering",
34
+ "This usually means the page component has a bug",
35
+ "Check if the API returned unexpected data"
36
+ ]
37
+ },
38
+ RENDER_102: {
39
+ code: "RENDER_102",
40
+ severity: "error",
41
+ description: "Data display crashed \u2014 likely missing or unexpected data",
42
+ diagnosis: [
43
+ "A component tried to display data that was null or undefined",
44
+ "Common cause: API response missing expected fields",
45
+ "The component stack shows which data component failed"
46
+ ]
47
+ }
48
+ };
49
+
50
+ // src/components/error-boundary.tsx
51
+ import { jsx, jsxs } from "react/jsx-runtime";
52
+ var styles = {
53
+ container: {
54
+ display: "flex",
55
+ alignItems: "center",
56
+ justifyContent: "center",
57
+ minHeight: "400px",
58
+ padding: "24px"
59
+ },
60
+ card: {
61
+ width: "100%",
62
+ maxWidth: "32rem",
63
+ border: "1px solid #fecaca",
64
+ borderRadius: "12px",
65
+ backgroundColor: "#fef2f2",
66
+ padding: "24px"
67
+ },
68
+ titleRow: {
69
+ display: "flex",
70
+ alignItems: "center",
71
+ gap: "8px",
72
+ color: "#991b1b",
73
+ fontSize: "18px",
74
+ fontWeight: 600,
75
+ marginBottom: "16px"
76
+ },
77
+ message: {
78
+ color: "#b91c1c",
79
+ marginBottom: "16px"
80
+ },
81
+ refBox: {
82
+ borderRadius: "8px",
83
+ backgroundColor: "#ffffff",
84
+ border: "1px solid #fecaca",
85
+ padding: "16px",
86
+ marginBottom: "16px"
87
+ },
88
+ refLabel: {
89
+ fontSize: "14px",
90
+ color: "#6b7280",
91
+ marginBottom: "4px"
92
+ },
93
+ refCode: {
94
+ fontFamily: "monospace",
95
+ fontSize: "18px",
96
+ fontWeight: 700,
97
+ color: "#991b1b",
98
+ userSelect: "all",
99
+ marginBottom: "8px"
100
+ },
101
+ refHint: {
102
+ fontSize: "12px",
103
+ color: "#9ca3af",
104
+ marginTop: "8px"
105
+ },
106
+ errorBox: {
107
+ borderRadius: "6px",
108
+ backgroundColor: "#fee2e2",
109
+ padding: "12px",
110
+ fontSize: "14px",
111
+ color: "#7f1d1d",
112
+ overflow: "auto",
113
+ maxHeight: "128px",
114
+ marginBottom: "16px"
115
+ },
116
+ detailsSummary: {
117
+ cursor: "pointer",
118
+ fontSize: "12px",
119
+ color: "#dc2626",
120
+ marginBottom: "8px"
121
+ },
122
+ detailsPre: {
123
+ marginTop: "8px",
124
+ borderRadius: "6px",
125
+ backgroundColor: "#fee2e2",
126
+ padding: "8px",
127
+ fontSize: "12px",
128
+ color: "#7f1d1d",
129
+ overflow: "auto",
130
+ maxHeight: "192px",
131
+ whiteSpace: "pre-wrap"
132
+ },
133
+ actions: {
134
+ display: "flex",
135
+ gap: "8px",
136
+ paddingTop: "8px"
137
+ },
138
+ button: {
139
+ display: "inline-flex",
140
+ alignItems: "center",
141
+ gap: "6px",
142
+ padding: "6px 12px",
143
+ borderRadius: "6px",
144
+ border: "1px solid #d1d5db",
145
+ backgroundColor: "#ffffff",
146
+ cursor: "pointer",
147
+ fontSize: "14px"
148
+ }
149
+ };
150
+ function CopyButton({ text }) {
151
+ const [copied, setCopied] = useState(false);
152
+ const handleCopy = async () => {
153
+ try {
154
+ await navigator.clipboard.writeText(text);
155
+ } catch (_clipboardErr) {
156
+ const el = document.createElement("textarea");
157
+ el.value = text;
158
+ document.body.appendChild(el);
159
+ el.select();
160
+ document.execCommand("copy");
161
+ document.body.removeChild(el);
162
+ }
163
+ setCopied(true);
164
+ setTimeout(() => setCopied(false), 2e3);
165
+ };
166
+ return /* @__PURE__ */ jsx("button", { onClick: handleCopy, style: styles.button, children: copied ? "Copied!" : "Copy Error Code" });
167
+ }
168
+ var ErrorBoundary = class extends Component {
169
+ constructor(props) {
170
+ super(props);
171
+ this.state = {
172
+ hasError: false,
173
+ error: null,
174
+ errorRef: null,
175
+ errorCode: null,
176
+ componentStack: null
177
+ };
178
+ }
179
+ static getDerivedStateFromError(error) {
180
+ const { code, ref } = renderError("RENDER_100", {
181
+ message: error.message,
182
+ name: error.name
183
+ });
184
+ return {
185
+ hasError: true,
186
+ error,
187
+ errorRef: ref,
188
+ errorCode: code
189
+ };
190
+ }
191
+ componentDidCatch(error, errorInfo) {
192
+ console.error(
193
+ `[${this.state.errorRef}] React rendering error:`,
194
+ {
195
+ ref: this.state.errorRef,
196
+ code: this.state.errorCode,
197
+ message: error.message,
198
+ stack: error.stack,
199
+ componentStack: errorInfo.componentStack
200
+ }
201
+ );
202
+ this.setState({
203
+ componentStack: errorInfo.componentStack || null
204
+ });
205
+ this.props.onError?.(error, errorInfo);
206
+ }
207
+ handleReset = () => {
208
+ this.setState({
209
+ hasError: false,
210
+ error: null,
211
+ errorRef: null,
212
+ errorCode: null,
213
+ componentStack: null
214
+ });
215
+ };
216
+ render() {
217
+ if (!this.state.hasError) {
218
+ return this.props.children;
219
+ }
220
+ if (this.props.fallback) {
221
+ return this.props.fallback;
222
+ }
223
+ const { error, errorRef, componentStack } = this.state;
224
+ return /* @__PURE__ */ jsx("div", { style: styles.container, children: /* @__PURE__ */ jsxs("div", { style: styles.card, children: [
225
+ /* @__PURE__ */ jsx("div", { style: styles.titleRow, children: this.props.title || "Something went wrong" }),
226
+ /* @__PURE__ */ jsx("p", { style: styles.message, children: this.props.message || "An error occurred while loading this component." }),
227
+ errorRef && /* @__PURE__ */ jsxs("div", { style: styles.refBox, children: [
228
+ /* @__PURE__ */ jsx("p", { style: styles.refLabel, children: "Error Reference:" }),
229
+ /* @__PURE__ */ jsx("p", { style: styles.refCode, children: errorRef }),
230
+ /* @__PURE__ */ jsx(CopyButton, { text: errorRef }),
231
+ /* @__PURE__ */ jsx("p", { style: styles.refHint, children: this.props.refHint || "Copy this code and give it to Claude for instant diagnosis." })
232
+ ] }),
233
+ error && /* @__PURE__ */ jsxs("div", { style: styles.errorBox, children: [
234
+ /* @__PURE__ */ jsx("strong", { children: "Error:" }),
235
+ " ",
236
+ error.message
237
+ ] }),
238
+ componentStack && /* @__PURE__ */ jsxs("details", { children: [
239
+ /* @__PURE__ */ jsx("summary", { style: styles.detailsSummary, children: "Technical details" }),
240
+ /* @__PURE__ */ jsx("pre", { style: styles.detailsPre, children: componentStack })
241
+ ] }),
242
+ /* @__PURE__ */ jsx("div", { style: styles.actions, children: this.props.renderActions ? this.props.renderActions(this.handleReset) : /* @__PURE__ */ jsx("button", { onClick: this.handleReset, style: styles.button, children: "Try Again" }) })
243
+ ] }) });
244
+ }
245
+ };
246
+ function withErrorBoundary(WrappedComponent, boundaryProps) {
247
+ return function WithErrorBoundaryWrapper(props) {
248
+ return /* @__PURE__ */ jsx(ErrorBoundary, { ...boundaryProps, children: /* @__PURE__ */ jsx(WrappedComponent, { ...props }) });
249
+ };
250
+ }
251
+
252
+ // src/components/email-body-renderer.tsx
253
+ import { useCallback, useEffect, useRef } from "react";
254
+ import { jsx as jsx2, jsxs as jsxs2 } from "react/jsx-runtime";
255
+ var DEFAULT_IFRAME_STYLES = `
256
+ body {
257
+ margin: 0;
258
+ padding: 16px;
259
+ font-family: system-ui, sans-serif;
260
+ overflow-x: auto;
261
+ overflow-y: hidden;
262
+ }
263
+ a { color: #2563eb; }
264
+ a[data-link-warning] {
265
+ border-bottom: 2px dashed #ef4444;
266
+ text-decoration: none;
267
+ }
268
+ .blocked-image {
269
+ background: #f3f4f6;
270
+ padding: 12px;
271
+ text-align: center;
272
+ border-radius: 6px;
273
+ margin: 4px 0;
274
+ font-size: 12px;
275
+ color: #9ca3af;
276
+ }
277
+ `;
278
+ function buildIframeCSP(imagePolicy) {
279
+ const imgSrc = imagePolicy === "block" ? "'none'" : "'self' https: data:";
280
+ return [
281
+ "default-src 'none'",
282
+ "style-src 'unsafe-inline'",
283
+ `img-src ${imgSrc}`,
284
+ "font-src data:",
285
+ "form-action 'none'",
286
+ "base-uri 'none'"
287
+ ].join("; ");
288
+ }
289
+ var BANNER_BUTTON_STYLE = {
290
+ padding: "4px 12px",
291
+ borderRadius: "4px",
292
+ border: "1px solid #d4d4d8",
293
+ background: "white",
294
+ fontSize: "12px",
295
+ cursor: "pointer",
296
+ color: "#18181b"
297
+ };
298
+ function EmailBodyRenderer({
299
+ bodyHtml,
300
+ bodyText,
301
+ snippet,
302
+ minHeight = "200px",
303
+ iframeStyles,
304
+ className,
305
+ style,
306
+ sanitize,
307
+ imagePolicy = "block",
308
+ onShowImages,
309
+ senderDomain,
310
+ onTrustSender
311
+ }) {
312
+ const iframeRef = useRef(null);
313
+ const observerRef = useRef(null);
314
+ const rafRef = useRef(0);
315
+ const keyCleanupRef = useRef(null);
316
+ const syncHeight = useCallback(() => {
317
+ cancelAnimationFrame(rafRef.current);
318
+ rafRef.current = requestAnimationFrame(() => {
319
+ const iframe = iframeRef.current;
320
+ if (!iframe?.contentDocument?.body) return;
321
+ const height = iframe.contentDocument.body.scrollHeight;
322
+ if (iframe.style.height !== height + "px") {
323
+ iframe.style.height = height + "px";
324
+ }
325
+ });
326
+ }, []);
327
+ const handleLoad = useCallback(() => {
328
+ const iframe = iframeRef.current;
329
+ if (!iframe?.contentDocument?.body) return;
330
+ syncHeight();
331
+ observerRef.current?.disconnect();
332
+ if (typeof ResizeObserver !== "undefined") {
333
+ const ro = new ResizeObserver(syncHeight);
334
+ ro.observe(iframe.contentDocument.body);
335
+ observerRef.current = ro;
336
+ }
337
+ if (process.env.NODE_ENV === "development") {
338
+ iframe.contentDocument?.addEventListener("securitypolicyviolation", (e) => {
339
+ console.warn("[EmailCSP] Blocked:", e.violatedDirective, e.blockedURI);
340
+ });
341
+ }
342
+ function forwardKeydown(e) {
343
+ const tag = e.target?.tagName;
344
+ if (tag === "INPUT" || tag === "TEXTAREA" || tag === "SELECT") return;
345
+ if (e.target?.isContentEditable) return;
346
+ const forwarded = new KeyboardEvent("keydown", {
347
+ key: e.key,
348
+ code: e.code,
349
+ metaKey: e.metaKey,
350
+ ctrlKey: e.ctrlKey,
351
+ altKey: e.altKey,
352
+ shiftKey: e.shiftKey,
353
+ bubbles: true,
354
+ cancelable: true
355
+ });
356
+ window.dispatchEvent(forwarded);
357
+ if (forwarded.defaultPrevented) e.preventDefault();
358
+ }
359
+ keyCleanupRef.current?.();
360
+ iframe.contentDocument.addEventListener("keydown", forwardKeydown);
361
+ keyCleanupRef.current = () => {
362
+ try {
363
+ iframe.contentDocument?.removeEventListener("keydown", forwardKeydown);
364
+ } catch (_e) {
365
+ }
366
+ };
367
+ }, [syncHeight]);
368
+ useEffect(() => {
369
+ return () => {
370
+ observerRef.current?.disconnect();
371
+ cancelAnimationFrame(rafRef.current);
372
+ keyCleanupRef.current?.();
373
+ };
374
+ }, []);
375
+ const containerStyle = {
376
+ border: "1px solid #e5e7eb",
377
+ borderRadius: "8px",
378
+ backgroundColor: "#ffffff",
379
+ overflow: "hidden",
380
+ ...style
381
+ };
382
+ let cleanHtml = null;
383
+ let trackingPixelCount = 0;
384
+ if (bodyHtml) {
385
+ const hasDangerousTags = /<(script|noscript|form|iframe|object|embed)\b/i.test(bodyHtml);
386
+ if (hasDangerousTags && sanitize) {
387
+ cleanHtml = sanitize(bodyHtml);
388
+ } else if (hasDangerousTags) {
389
+ cleanHtml = bodyHtml.replace(/<noscript[^>]*>[\s\S]*?<\/noscript>/gi, "").replace(/<script[^>]*>[\s\S]*?<\/script>/gi, "");
390
+ } else {
391
+ cleanHtml = bodyHtml;
392
+ }
393
+ if (cleanHtml) {
394
+ const trackerMatches = cleanHtml.match(/<img\s+[^>]*data-tracking-pixel="(?:high|medium)"[^>]*>/gi);
395
+ trackingPixelCount = trackerMatches?.length ?? 0;
396
+ cleanHtml = cleanHtml.replace(
397
+ /<img\s+[^>]*data-tracking-pixel="(?:high|medium)"[^>]*>/gi,
398
+ ""
399
+ );
400
+ }
401
+ if (cleanHtml && imagePolicy === "block") {
402
+ cleanHtml = cleanHtml.replace(
403
+ /<img\s+[^>]*data-blocked="true"[^>]*>/gi,
404
+ '<div class="blocked-image">\u{1F5BC} Image hidden for privacy</div>'
405
+ );
406
+ }
407
+ }
408
+ const proxyImageCount = bodyHtml?.match(/data-blocked="true"/gi)?.length ?? 0;
409
+ const externalImageCount = bodyHtml?.match(/<img\s+[^>]*src\s*=\s*["']https?:\/\//gi)?.length ?? 0;
410
+ const trackerCount = bodyHtml?.match(/data-tracking-pixel/gi)?.length ?? 0;
411
+ const blockedImageCount = Math.max(0, proxyImageCount + externalImageCount - trackerCount);
412
+ const showPrivacyBanner = blockedImageCount > 0 && imagePolicy === "block";
413
+ if (cleanHtml) {
414
+ const css = iframeStyles ?? DEFAULT_IFRAME_STYLES;
415
+ const csp = buildIframeCSP(imagePolicy);
416
+ const srcDoc = `<!DOCTYPE html><html><head><meta charset="utf-8"><meta http-equiv="Content-Security-Policy" content="${csp}"><base target="_blank"><style>${css}</style></head><body>${cleanHtml}</body></html>`;
417
+ return /* @__PURE__ */ jsxs2("div", { className, style: containerStyle, children: [
418
+ showPrivacyBanner && /* @__PURE__ */ jsxs2("div", { style: {
419
+ display: "flex",
420
+ alignItems: "center",
421
+ gap: "12px",
422
+ padding: "10px 16px",
423
+ background: "#fefce8",
424
+ borderBottom: "1px solid #fef08a",
425
+ fontSize: "13px",
426
+ color: "#854d0e"
427
+ }, children: [
428
+ /* @__PURE__ */ jsx2("span", { children: "\u{1F512} External images hidden for your privacy" }),
429
+ /* @__PURE__ */ jsxs2("div", { style: { display: "flex", gap: "8px", marginLeft: "auto" }, children: [
430
+ onShowImages && /* @__PURE__ */ jsx2("button", { type: "button", onClick: onShowImages, style: BANNER_BUTTON_STYLE, children: "Show images" }),
431
+ senderDomain && onTrustSender && /* @__PURE__ */ jsxs2("button", { type: "button", onClick: () => onTrustSender(senderDomain), style: BANNER_BUTTON_STYLE, children: [
432
+ "Always show from ",
433
+ senderDomain
434
+ ] })
435
+ ] })
436
+ ] }),
437
+ /* @__PURE__ */ jsx2(
438
+ "iframe",
439
+ {
440
+ ref: iframeRef,
441
+ srcDoc,
442
+ sandbox: "allow-same-origin allow-popups allow-popups-to-escape-sandbox",
443
+ referrerPolicy: "no-referrer",
444
+ style: { width: "100%", border: "none", minHeight, display: "block" },
445
+ onLoad: handleLoad,
446
+ title: "Email content"
447
+ }
448
+ ),
449
+ trackingPixelCount > 0 && /* @__PURE__ */ jsxs2("div", { style: {
450
+ display: "flex",
451
+ alignItems: "center",
452
+ gap: "6px",
453
+ padding: "6px 16px",
454
+ borderTop: "1px solid #e5e7eb",
455
+ fontSize: "12px",
456
+ color: "#6b7280"
457
+ }, children: [
458
+ /* @__PURE__ */ jsx2("span", { children: "\u{1F6E1}" }),
459
+ /* @__PURE__ */ jsxs2("span", { children: [
460
+ trackingPixelCount,
461
+ " email tracker",
462
+ trackingPixelCount > 1 ? "s" : "",
463
+ " blocked"
464
+ ] })
465
+ ] })
466
+ ] });
467
+ }
468
+ if (bodyText) {
469
+ return /* @__PURE__ */ jsx2("div", { className, style: containerStyle, children: /* @__PURE__ */ jsx2("pre", { style: {
470
+ whiteSpace: "pre-wrap",
471
+ fontFamily: "system-ui, sans-serif",
472
+ padding: "16px",
473
+ margin: 0,
474
+ fontSize: "14px"
475
+ }, children: bodyText }) });
476
+ }
477
+ if (snippet) {
478
+ return /* @__PURE__ */ jsx2("div", { className, style: containerStyle, children: /* @__PURE__ */ jsx2("p", { style: { padding: "16px", margin: 0, color: "#6b7280", fontSize: "14px" }, children: snippet }) });
479
+ }
480
+ return null;
481
+ }
482
+
483
+ // src/components/email-thread-view.tsx
484
+ import { useState as useState2 } from "react";
485
+ import { Fragment, jsx as jsx3, jsxs as jsxs3 } from "react/jsx-runtime";
486
+ var threadStyles = {
487
+ counter: {
488
+ fontSize: "14px",
489
+ color: "#6b7280",
490
+ marginBottom: "8px"
491
+ },
492
+ messageCard: {
493
+ borderWidth: "1px",
494
+ borderStyle: "solid",
495
+ borderColor: "#e5e7eb",
496
+ borderRadius: "8px",
497
+ overflow: "hidden",
498
+ marginBottom: "8px"
499
+ },
500
+ headerBase: {
501
+ width: "100%",
502
+ textAlign: "left",
503
+ padding: "16px",
504
+ display: "flex",
505
+ alignItems: "center",
506
+ justifyContent: "space-between",
507
+ cursor: "pointer",
508
+ borderWidth: 0,
509
+ borderStyle: "none",
510
+ backgroundColor: "transparent",
511
+ transition: "background-color 0.15s"
512
+ },
513
+ headerExpanded: {
514
+ borderBottomWidth: "1px",
515
+ borderBottomStyle: "solid",
516
+ borderBottomColor: "#e5e7eb",
517
+ backgroundColor: "rgba(249, 250, 251, 0.5)"
518
+ },
519
+ avatarRow: {
520
+ display: "flex",
521
+ alignItems: "center",
522
+ gap: "12px",
523
+ minWidth: 0
524
+ },
525
+ avatar: {
526
+ width: "32px",
527
+ height: "32px",
528
+ borderRadius: "50%",
529
+ backgroundColor: "#e5e7eb",
530
+ display: "flex",
531
+ alignItems: "center",
532
+ justifyContent: "center",
533
+ flexShrink: 0,
534
+ fontSize: "12px",
535
+ fontWeight: 500
536
+ },
537
+ senderName: {
538
+ fontWeight: 500,
539
+ fontSize: "14px"
540
+ },
541
+ snippetPreview: {
542
+ fontSize: "14px",
543
+ color: "#6b7280",
544
+ marginLeft: "8px",
545
+ overflow: "hidden",
546
+ textOverflow: "ellipsis",
547
+ whiteSpace: "nowrap"
548
+ },
549
+ dateLabel: {
550
+ fontSize: "12px",
551
+ color: "#6b7280",
552
+ flexShrink: 0,
553
+ marginLeft: "8px"
554
+ },
555
+ body: {
556
+ padding: "16px"
557
+ }
558
+ };
559
+ function formatDate(dateStr) {
560
+ return new Date(dateStr).toLocaleDateString("en-US", {
561
+ month: "short",
562
+ day: "numeric",
563
+ hour: "numeric",
564
+ minute: "2-digit"
565
+ });
566
+ }
567
+ function getInitial(msg) {
568
+ return (msg.fromName || msg.fromEmail)[0].toUpperCase();
569
+ }
570
+ function EmailThreadView({
571
+ messages,
572
+ initialExpanded,
573
+ renderMessage,
574
+ className,
575
+ style
576
+ }) {
577
+ const [expandedMessages, setExpandedMessages] = useState2(() => {
578
+ if (initialExpanded) return new Set(initialExpanded);
579
+ if (messages.length > 0) return /* @__PURE__ */ new Set([messages[messages.length - 1].id]);
580
+ return /* @__PURE__ */ new Set();
581
+ });
582
+ const toggleMessage = (id) => {
583
+ setExpandedMessages((prev) => {
584
+ const next = new Set(prev);
585
+ if (next.has(id)) next.delete(id);
586
+ else next.add(id);
587
+ return next;
588
+ });
589
+ };
590
+ if (messages.length === 0) return null;
591
+ if (messages.length === 1) {
592
+ const msg = messages[0];
593
+ if (renderMessage) return /* @__PURE__ */ jsx3(Fragment, { children: renderMessage(msg, true) });
594
+ return /* @__PURE__ */ jsx3(
595
+ EmailBodyRenderer,
596
+ {
597
+ bodyHtml: msg.bodyHtml,
598
+ bodyText: msg.bodyText,
599
+ snippet: msg.snippet ?? void 0,
600
+ className,
601
+ style
602
+ }
603
+ );
604
+ }
605
+ return /* @__PURE__ */ jsxs3("div", { className, style, children: [
606
+ /* @__PURE__ */ jsxs3("p", { style: threadStyles.counter, children: [
607
+ messages.length,
608
+ " messages in this thread"
609
+ ] }),
610
+ messages.map((msg) => {
611
+ const isExpanded = expandedMessages.has(msg.id);
612
+ return /* @__PURE__ */ jsxs3("div", { style: threadStyles.messageCard, children: [
613
+ /* @__PURE__ */ jsxs3(
614
+ "button",
615
+ {
616
+ onClick: () => toggleMessage(msg.id),
617
+ style: {
618
+ ...threadStyles.headerBase,
619
+ ...isExpanded ? threadStyles.headerExpanded : {}
620
+ },
621
+ children: [
622
+ /* @__PURE__ */ jsxs3("div", { style: threadStyles.avatarRow, children: [
623
+ /* @__PURE__ */ jsx3("div", { style: threadStyles.avatar, children: /* @__PURE__ */ jsx3("span", { children: getInitial(msg) }) }),
624
+ /* @__PURE__ */ jsxs3("div", { style: { minWidth: 0 }, children: [
625
+ /* @__PURE__ */ jsx3("span", { style: threadStyles.senderName, children: msg.fromName || msg.fromEmail }),
626
+ !isExpanded && msg.snippet && /* @__PURE__ */ jsxs3("span", { style: threadStyles.snippetPreview, children: [
627
+ " ",
628
+ "\u2014 ",
629
+ msg.snippet.substring(0, 80),
630
+ "..."
631
+ ] })
632
+ ] })
633
+ ] }),
634
+ /* @__PURE__ */ jsx3("span", { style: threadStyles.dateLabel, children: formatDate(msg.emailDate) })
635
+ ]
636
+ }
637
+ ),
638
+ isExpanded && /* @__PURE__ */ jsx3("div", { style: threadStyles.body, children: renderMessage ? renderMessage(msg, true) : /* @__PURE__ */ jsx3(
639
+ EmailBodyRenderer,
640
+ {
641
+ bodyHtml: msg.bodyHtml,
642
+ bodyText: msg.bodyText,
643
+ snippet: msg.snippet ?? void 0
644
+ }
645
+ ) })
646
+ ] }, msg.id);
647
+ })
648
+ ] });
649
+ }
650
+
651
+ // src/hooks/use-keyboard-shortcuts.ts
652
+ import { useEffect as useEffect2, useCallback as useCallback2 } from "react";
653
+ var DEFAULT_IGNORE_TAGS = ["INPUT", "TEXTAREA", "SELECT"];
654
+ function useKeyboardShortcuts({
655
+ shortcuts,
656
+ enabled = true,
657
+ ignoreTags = DEFAULT_IGNORE_TAGS
658
+ }) {
659
+ const handleKeyDown = useCallback2(
660
+ (e) => {
661
+ if (!enabled) return;
662
+ const tag = e.target?.tagName;
663
+ if (tag && ignoreTags.includes(tag)) return;
664
+ if (e.target?.isContentEditable) return;
665
+ for (const shortcut of shortcuts) {
666
+ const keyMatch = e.key.toLowerCase() === shortcut.key.toLowerCase();
667
+ if (!keyMatch) continue;
668
+ const mods = shortcut.modifiers;
669
+ if (mods) {
670
+ if (mods.meta && !e.metaKey) continue;
671
+ if (mods.ctrl && !e.ctrlKey) continue;
672
+ if (mods.alt && !e.altKey) continue;
673
+ if (mods.shift && !e.shiftKey) continue;
674
+ } else {
675
+ if (e.metaKey || e.ctrlKey || e.altKey) continue;
676
+ }
677
+ e.preventDefault();
678
+ shortcut.handler();
679
+ return;
680
+ }
681
+ },
682
+ [shortcuts, enabled, ignoreTags]
683
+ );
684
+ useEffect2(() => {
685
+ window.addEventListener("keydown", handleKeyDown);
686
+ return () => window.removeEventListener("keydown", handleKeyDown);
687
+ }, [handleKeyDown]);
688
+ }
689
+
690
+ // src/hooks/use-context-shortcuts.ts
691
+ import { useMemo } from "react";
692
+ function isOverlayActive() {
693
+ if (typeof document === "undefined") return false;
694
+ const radixOpen = document.querySelector('[data-state="open"][role="dialog"]');
695
+ if (radixOpen) return true;
696
+ const dialogs = document.querySelectorAll('dialog[open], [role="dialog"]');
697
+ return dialogs.length > 0;
698
+ }
699
+ function useContextShortcuts(context, handlers, enabled = true) {
700
+ const shortcuts = useMemo(() => {
701
+ const result = [];
702
+ for (const [actionName, def] of Object.entries(context.shortcuts)) {
703
+ const handler = handlers[actionName];
704
+ if (!handler) continue;
705
+ result.push({
706
+ key: def.key,
707
+ modifiers: def.modifiers,
708
+ handler: () => {
709
+ if (!isOverlayActive()) {
710
+ handler();
711
+ }
712
+ }
713
+ });
714
+ }
715
+ return result;
716
+ }, [context, ...Object.values(handlers)]);
717
+ const activeDefinitions = useMemo(
718
+ () => Object.entries(context.shortcuts).filter(([actionName]) => handlers[actionName]).map(([, def]) => def),
719
+ // eslint-disable-next-line react-hooks/exhaustive-deps
720
+ [context, ...Object.keys(handlers)]
721
+ );
722
+ useKeyboardShortcuts({ shortcuts, enabled });
723
+ return activeDefinitions;
724
+ }
725
+
726
+ // src/hooks/keyboard-shortcut-defaults.ts
727
+ var GLOBAL_SHORTCUTS = {
728
+ name: "global",
729
+ label: "Global",
730
+ shortcuts: {
731
+ search: {
732
+ key: "k",
733
+ modifiers: { meta: true },
734
+ action: "search",
735
+ description: "Open search",
736
+ display: "\u2318K"
737
+ },
738
+ help: {
739
+ key: "?",
740
+ action: "help",
741
+ description: "Show keyboard shortcuts",
742
+ display: "?"
743
+ }
744
+ }
745
+ };
746
+ var CLIENT_PROFILE_SHORTCUTS = {
747
+ name: "client-profile",
748
+ label: "Client Profile",
749
+ shortcuts: {
750
+ composeEmail: {
751
+ key: "e",
752
+ action: "composeEmail",
753
+ description: "Compose new email to this client",
754
+ display: "E"
755
+ },
756
+ addNote: {
757
+ key: "n",
758
+ action: "addNote",
759
+ description: "Add a note to the timeline",
760
+ display: "N"
761
+ },
762
+ createTask: {
763
+ key: "t",
764
+ action: "createTask",
765
+ description: "Create a task for this client",
766
+ display: "T"
767
+ },
768
+ closeForm: {
769
+ key: "Escape",
770
+ action: "closeForm",
771
+ description: "Close the active form or dialog",
772
+ display: "Esc"
773
+ }
774
+ }
775
+ };
776
+ var INBOX_SHORTCUTS = {
777
+ name: "inbox",
778
+ label: "Inbox",
779
+ shortcuts: {
780
+ nextEmail: {
781
+ key: "j",
782
+ action: "nextEmail",
783
+ description: "Next email",
784
+ display: "J"
785
+ },
786
+ prevEmail: {
787
+ key: "k",
788
+ action: "prevEmail",
789
+ description: "Previous email",
790
+ display: "K"
791
+ },
792
+ reply: {
793
+ key: "r",
794
+ action: "reply",
795
+ description: "Reply to email",
796
+ display: "R"
797
+ },
798
+ archive: {
799
+ key: "e",
800
+ action: "archive",
801
+ description: "Archive email",
802
+ display: "E"
803
+ },
804
+ createTask: {
805
+ key: "t",
806
+ action: "createTask",
807
+ description: "Create task from email",
808
+ display: "T"
809
+ },
810
+ forward: {
811
+ key: "f",
812
+ action: "forward",
813
+ description: "Forward email",
814
+ display: "F"
815
+ },
816
+ back: {
817
+ key: "Escape",
818
+ action: "back",
819
+ description: "Back to inbox list",
820
+ display: "Esc"
821
+ }
822
+ }
823
+ };
824
+ var FORM_SHORTCUTS = {
825
+ name: "form",
826
+ label: "Forms & Dialogs",
827
+ shortcuts: {
828
+ submit: {
829
+ key: "Enter",
830
+ modifiers: { meta: true },
831
+ action: "submit",
832
+ description: "Submit / send / save",
833
+ display: "\u2318\u21B5"
834
+ },
835
+ cancel: {
836
+ key: "Escape",
837
+ action: "cancel",
838
+ description: "Cancel and close",
839
+ display: "Esc"
840
+ }
841
+ }
842
+ };
843
+ var ALL_SHORTCUT_CONTEXTS = [
844
+ GLOBAL_SHORTCUTS,
845
+ CLIENT_PROFILE_SHORTCUTS,
846
+ INBOX_SHORTCUTS,
847
+ FORM_SHORTCUTS
848
+ ];
849
+ function getShortcut(context, action) {
850
+ return context.shortcuts[action];
851
+ }
852
+
853
+ // src/components/keyboard-shortcuts-panel.tsx
854
+ import { useEffect as useEffect3, useState as useState3 } from "react";
855
+ import { Fragment as Fragment2, jsx as jsx4, jsxs as jsxs4 } from "react/jsx-runtime";
856
+ function KeyboardShortcutsPanel({
857
+ contexts = ALL_SHORTCUT_CONTEXTS
858
+ }) {
859
+ const [open, setOpen] = useState3(false);
860
+ useEffect3(() => {
861
+ function handleKey(e) {
862
+ if (e.key === "?" && !e.metaKey && !e.ctrlKey && !e.altKey) {
863
+ const tag = e.target?.tagName;
864
+ if (tag === "INPUT" || tag === "TEXTAREA" || tag === "SELECT") return;
865
+ if (e.target?.isContentEditable) return;
866
+ e.preventDefault();
867
+ setOpen((prev) => !prev);
868
+ }
869
+ if (e.key === "Escape" && open) {
870
+ setOpen(false);
871
+ }
872
+ }
873
+ window.addEventListener("keydown", handleKey);
874
+ return () => window.removeEventListener("keydown", handleKey);
875
+ }, [open]);
876
+ if (!open) return null;
877
+ return /* @__PURE__ */ jsxs4(Fragment2, { children: [
878
+ /* @__PURE__ */ jsx4(
879
+ "div",
880
+ {
881
+ className: "fixed inset-0 z-50 bg-black/50 backdrop-blur-sm",
882
+ onClick: () => setOpen(false)
883
+ }
884
+ ),
885
+ /* @__PURE__ */ jsx4("div", { className: "fixed inset-x-0 top-[10%] z-50 mx-auto w-full max-w-lg", children: /* @__PURE__ */ jsxs4("div", { className: "rounded-xl border bg-background shadow-2xl overflow-hidden", children: [
886
+ /* @__PURE__ */ jsxs4("div", { className: "px-6 py-4 border-b", children: [
887
+ /* @__PURE__ */ jsx4("h2", { className: "text-lg font-semibold", children: "Keyboard Shortcuts" }),
888
+ /* @__PURE__ */ jsxs4("p", { className: "text-sm text-muted-foreground mt-0.5", children: [
889
+ "Press ",
890
+ /* @__PURE__ */ jsx4("kbd", { className: "px-1.5 py-0.5 bg-muted rounded text-xs font-mono", children: "?" }),
891
+ " to toggle this panel"
892
+ ] })
893
+ ] }),
894
+ /* @__PURE__ */ jsx4("div", { className: "px-6 py-4 max-h-[60vh] overflow-y-auto space-y-6", children: contexts.map((ctx) => /* @__PURE__ */ jsxs4("div", { children: [
895
+ /* @__PURE__ */ jsx4("h3", { className: "text-xs font-semibold text-muted-foreground uppercase tracking-wide mb-2", children: ctx.label }),
896
+ /* @__PURE__ */ jsx4("div", { className: "space-y-1", children: Object.entries(ctx.shortcuts).map(([key, def]) => /* @__PURE__ */ jsxs4("div", { className: "flex items-center justify-between py-1", children: [
897
+ /* @__PURE__ */ jsx4("span", { className: "text-sm", children: def.description }),
898
+ /* @__PURE__ */ jsx4("kbd", { className: "px-2 py-0.5 bg-muted rounded text-xs font-mono min-w-[2rem] text-center", children: def.display })
899
+ ] }, key)) })
900
+ ] }, ctx.name)) }),
901
+ /* @__PURE__ */ jsxs4("div", { className: "px-6 py-3 border-t bg-muted/30 text-xs text-muted-foreground text-center", children: [
902
+ "Press ",
903
+ /* @__PURE__ */ jsx4("kbd", { className: "px-1 py-0.5 bg-muted rounded", children: "Esc" }),
904
+ " to close"
905
+ ] })
906
+ ] }) })
907
+ ] });
908
+ }
909
+
910
+ // src/hooks/use-auto-save.ts
911
+ import { useEffect as useEffect4, useRef as useRef2, useCallback as useCallback3, useState as useState4 } from "react";
912
+ function useAutoSave({
913
+ data,
914
+ onSave,
915
+ delay = 5e3,
916
+ enabled = true
917
+ }) {
918
+ const [lastSavedAt, setLastSavedAt] = useState4(null);
919
+ const [isSaving, setIsSaving] = useState4(false);
920
+ const [saveError, setSaveError] = useState4(null);
921
+ const timerRef = useRef2(null);
922
+ const dataRef = useRef2(data);
923
+ const savedDataRef = useRef2(null);
924
+ dataRef.current = data;
925
+ const save = useCallback3(async () => {
926
+ const currentJson = JSON.stringify(dataRef.current);
927
+ if (currentJson === savedDataRef.current) return;
928
+ setIsSaving(true);
929
+ try {
930
+ await onSave(dataRef.current);
931
+ savedDataRef.current = currentJson;
932
+ setSaveError(null);
933
+ setLastSavedAt(/* @__PURE__ */ new Date());
934
+ } catch {
935
+ setSaveError("Failed to save draft");
936
+ } finally {
937
+ setIsSaving(false);
938
+ }
939
+ }, [onSave]);
940
+ useEffect4(() => {
941
+ if (!enabled) return;
942
+ if (timerRef.current) clearTimeout(timerRef.current);
943
+ timerRef.current = setTimeout(save, delay);
944
+ return () => {
945
+ if (timerRef.current) clearTimeout(timerRef.current);
946
+ };
947
+ }, [data, save, delay, enabled]);
948
+ return { lastSavedAt, isSaving, saveError };
949
+ }
950
+
951
+ // src/hooks/use-polling.ts
952
+ import { useEffect as useEffect5, useCallback as useCallback4, useRef as useRef3, useState as useState5 } from "react";
953
+ function usePolling({
954
+ fetcher,
955
+ interval = 3e4,
956
+ enabled = true,
957
+ onError
958
+ }) {
959
+ const [data, setData] = useState5(null);
960
+ const [isLoading, setIsLoading] = useState5(true);
961
+ const [isRefreshing, setIsRefreshing] = useState5(false);
962
+ const [error, setError] = useState5(null);
963
+ const mountedRef = useRef3(true);
964
+ const doFetch = useCallback4(async (isInitial = false) => {
965
+ if (isInitial) setIsLoading(true);
966
+ else setIsRefreshing(true);
967
+ try {
968
+ const result = await fetcher();
969
+ if (mountedRef.current) {
970
+ setData(result);
971
+ setError(null);
972
+ }
973
+ } catch (err) {
974
+ if (mountedRef.current) {
975
+ setError(err instanceof Error ? err.message : "Fetch failed");
976
+ onError?.(err);
977
+ }
978
+ } finally {
979
+ if (mountedRef.current) {
980
+ setIsLoading(false);
981
+ setIsRefreshing(false);
982
+ }
983
+ }
984
+ }, [fetcher, onError]);
985
+ useEffect5(() => {
986
+ mountedRef.current = true;
987
+ if (enabled) doFetch(true);
988
+ return () => {
989
+ mountedRef.current = false;
990
+ };
991
+ }, [doFetch, enabled]);
992
+ useEffect5(() => {
993
+ if (!enabled) return;
994
+ const timer = setInterval(() => doFetch(false), interval);
995
+ return () => clearInterval(timer);
996
+ }, [doFetch, interval, enabled]);
997
+ const refresh = useCallback4(() => doFetch(false), [doFetch]);
998
+ return { data, isLoading, isRefreshing, error, refresh };
999
+ }
1000
+
1001
+ // src/hooks/use-server-search.ts
1002
+ import { useEffect as useEffect6, useRef as useRef4, useState as useState6, useCallback as useCallback5 } from "react";
1003
+ function useServerSearch({
1004
+ fetcher,
1005
+ debounce = 150,
1006
+ minChars = 1,
1007
+ enabled = true
1008
+ }) {
1009
+ const [query, setQuery] = useState6("");
1010
+ const [results, setResults] = useState6([]);
1011
+ const [isSearching, setIsSearching] = useState6(false);
1012
+ const [isOpen, setIsOpen] = useState6(false);
1013
+ const timerRef = useRef4(null);
1014
+ useEffect6(() => {
1015
+ if (!enabled || query.length < minChars) {
1016
+ setResults([]);
1017
+ return;
1018
+ }
1019
+ if (timerRef.current) clearTimeout(timerRef.current);
1020
+ setIsSearching(true);
1021
+ timerRef.current = setTimeout(async () => {
1022
+ try {
1023
+ const data = await fetcher(query);
1024
+ setResults(data);
1025
+ setIsOpen(true);
1026
+ } catch {
1027
+ } finally {
1028
+ setIsSearching(false);
1029
+ }
1030
+ }, debounce);
1031
+ return () => {
1032
+ if (timerRef.current) clearTimeout(timerRef.current);
1033
+ };
1034
+ }, [query, fetcher, debounce, minChars, enabled]);
1035
+ const clear = useCallback5(() => {
1036
+ setQuery("");
1037
+ setResults([]);
1038
+ setIsOpen(false);
1039
+ }, []);
1040
+ return { query, setQuery, results, isSearching, isOpen, setIsOpen, clear };
1041
+ }
1042
+
1043
+ // src/hooks/use-iframe-focus-reclaim.ts
1044
+ import { useEffect as useEffect7 } from "react";
1045
+ function useIframeFocusReclaim(containerRef, enabled = true, iframeSelector = "iframe") {
1046
+ useEffect7(() => {
1047
+ if (!enabled) return;
1048
+ const el = containerRef.current;
1049
+ if (!el) return;
1050
+ el.focus();
1051
+ function reclaimFromIframe() {
1052
+ let attempts = 0;
1053
+ function tryReclaim() {
1054
+ if (document.activeElement?.tagName === "IFRAME") {
1055
+ el?.focus();
1056
+ }
1057
+ attempts++;
1058
+ if (attempts < 3 && document.activeElement?.tagName === "IFRAME") {
1059
+ setTimeout(tryReclaim, 100);
1060
+ }
1061
+ }
1062
+ requestAnimationFrame(tryReclaim);
1063
+ }
1064
+ function handleVisibilityChange() {
1065
+ if (document.visibilityState === "visible") {
1066
+ reclaimFromIframe();
1067
+ el?.querySelectorAll(iframeSelector).forEach(attachToIframeDoc);
1068
+ }
1069
+ }
1070
+ function fallbackKeydown(e) {
1071
+ if (!e.isTrusted) return;
1072
+ if (document.activeElement?.tagName !== "IFRAME") return;
1073
+ const tag = e.target?.tagName;
1074
+ if (tag === "INPUT" || tag === "TEXTAREA" || tag === "SELECT") return;
1075
+ if (e.target?.isContentEditable) return;
1076
+ const forwarded = new KeyboardEvent("keydown", {
1077
+ key: e.key,
1078
+ code: e.code,
1079
+ metaKey: e.metaKey,
1080
+ ctrlKey: e.ctrlKey,
1081
+ altKey: e.altKey,
1082
+ shiftKey: e.shiftKey,
1083
+ bubbles: true,
1084
+ cancelable: true
1085
+ });
1086
+ window.dispatchEvent(forwarded);
1087
+ if (forwarded.defaultPrevented) e.preventDefault();
1088
+ }
1089
+ window.addEventListener("focus", reclaimFromIframe);
1090
+ document.addEventListener("visibilitychange", handleVisibilityChange);
1091
+ document.addEventListener("keydown", fallbackKeydown);
1092
+ const perIframeCleanups = /* @__PURE__ */ new WeakMap();
1093
+ function forwardKeydown(e) {
1094
+ const ke = e;
1095
+ const tag = ke.target?.tagName;
1096
+ if (tag === "INPUT" || tag === "TEXTAREA" || tag === "SELECT") return;
1097
+ if (ke.target?.isContentEditable) return;
1098
+ const forwarded = new KeyboardEvent("keydown", {
1099
+ key: ke.key,
1100
+ code: ke.code,
1101
+ metaKey: ke.metaKey,
1102
+ ctrlKey: ke.ctrlKey,
1103
+ altKey: ke.altKey,
1104
+ shiftKey: ke.shiftKey,
1105
+ bubbles: true,
1106
+ cancelable: true
1107
+ });
1108
+ window.dispatchEvent(forwarded);
1109
+ if (forwarded.defaultPrevented) ke.preventDefault();
1110
+ }
1111
+ function attachToIframeDoc(iframe) {
1112
+ try {
1113
+ const doc = iframe.contentDocument;
1114
+ if (!doc) return;
1115
+ const existing = perIframeCleanups.get(iframe);
1116
+ if (existing) existing();
1117
+ doc.addEventListener("keydown", forwardKeydown);
1118
+ perIframeCleanups.set(iframe, () => {
1119
+ try {
1120
+ doc.removeEventListener("keydown", forwardKeydown);
1121
+ } catch (_e) {
1122
+ }
1123
+ });
1124
+ } catch (_e) {
1125
+ }
1126
+ }
1127
+ function watchIframe(iframe) {
1128
+ if (iframe.contentDocument?.readyState === "complete") {
1129
+ attachToIframeDoc(iframe);
1130
+ }
1131
+ const onLoad = () => attachToIframeDoc(iframe);
1132
+ iframe.addEventListener("load", onLoad);
1133
+ const prev = perIframeCleanups.get(iframe);
1134
+ perIframeCleanups.set(iframe, () => {
1135
+ iframe.removeEventListener("load", onLoad);
1136
+ prev?.();
1137
+ });
1138
+ }
1139
+ const initialIframes = el.querySelectorAll(iframeSelector);
1140
+ initialIframes.forEach(watchIframe);
1141
+ const observer = new MutationObserver((mutations) => {
1142
+ for (const m of mutations) {
1143
+ m.addedNodes.forEach((node) => {
1144
+ if (node instanceof HTMLIFrameElement && node.matches(iframeSelector)) {
1145
+ watchIframe(node);
1146
+ } else if (node instanceof Element) {
1147
+ node.querySelectorAll(iframeSelector).forEach(watchIframe);
1148
+ }
1149
+ });
1150
+ m.removedNodes.forEach((node) => {
1151
+ if (node instanceof HTMLIFrameElement) {
1152
+ perIframeCleanups.get(node)?.();
1153
+ perIframeCleanups.delete(node);
1154
+ }
1155
+ });
1156
+ }
1157
+ });
1158
+ observer.observe(el, { childList: true, subtree: true });
1159
+ return () => {
1160
+ window.removeEventListener("focus", reclaimFromIframe);
1161
+ document.removeEventListener("visibilitychange", handleVisibilityChange);
1162
+ document.removeEventListener("keydown", fallbackKeydown);
1163
+ observer.disconnect();
1164
+ el.querySelectorAll(iframeSelector).forEach((iframe) => {
1165
+ perIframeCleanups.get(iframe)?.();
1166
+ perIframeCleanups.delete(iframe);
1167
+ });
1168
+ };
1169
+ }, [containerRef, enabled, iframeSelector]);
1170
+ }
1171
+
1172
+ // src/hooks/use-cached-fetch.ts
1173
+ var cache = /* @__PURE__ */ new Map();
1174
+ var inflight = /* @__PURE__ */ new Map();
1175
+ var DEFAULT_STALE_TIME = 3e4;
1176
+ var DEFAULT_MAX_AGE = 5 * 6e4;
1177
+ async function cachedFetch(url, options, onData) {
1178
+ const staleTime = options?.staleTime ?? DEFAULT_STALE_TIME;
1179
+ const maxAge = options?.maxAge ?? DEFAULT_MAX_AGE;
1180
+ const key = url + (options?.fetchOptions?.method || "GET");
1181
+ const entry = cache.get(key);
1182
+ const now = Date.now();
1183
+ if (entry && now - entry.timestamp < staleTime) {
1184
+ onData?.(entry.data, true);
1185
+ return entry.data;
1186
+ }
1187
+ if (entry && now - entry.timestamp < maxAge) {
1188
+ onData?.(entry.data, true);
1189
+ revalidate(key, url, options?.fetchOptions).then((fresh) => {
1190
+ onData?.(fresh, false);
1191
+ }).catch(() => {
1192
+ });
1193
+ return entry.data;
1194
+ }
1195
+ return revalidate(key, url, options?.fetchOptions);
1196
+ }
1197
+ async function revalidate(key, url, options) {
1198
+ const existing = inflight.get(key);
1199
+ if (existing) return existing;
1200
+ const promise = fetch(url, options).then(async (res) => {
1201
+ if (!res.ok) throw new Error(`HTTP ${res.status}`);
1202
+ const data = await res.json();
1203
+ cache.set(key, { data, timestamp: Date.now() });
1204
+ inflight.delete(key);
1205
+ return data;
1206
+ }).catch((err) => {
1207
+ inflight.delete(key);
1208
+ throw err;
1209
+ });
1210
+ inflight.set(key, promise);
1211
+ return promise;
1212
+ }
1213
+ function invalidateCache(url, method = "GET") {
1214
+ cache.delete(url + method);
1215
+ }
1216
+ function prefetch(url) {
1217
+ const key = url + "GET";
1218
+ if (cache.has(key)) return;
1219
+ revalidate(key, url).catch(() => {
1220
+ });
1221
+ }
1222
+ function clearCache() {
1223
+ cache.clear();
1224
+ }
1225
+
1226
+ // src/hooks/use-preferences.ts
1227
+ import { useState as useState7, useEffect as useEffect8, useCallback as useCallback6 } from "react";
1228
+ function usePreferences({
1229
+ endpoint,
1230
+ defaults
1231
+ }) {
1232
+ const [preferences, setPreferences] = useState7(defaults ?? null);
1233
+ const [loading, setLoading] = useState7(true);
1234
+ const [error, setError] = useState7(null);
1235
+ const fetchPreferences = useCallback6(async () => {
1236
+ try {
1237
+ setError(null);
1238
+ const res = await fetch(endpoint);
1239
+ if (!res.ok) {
1240
+ if (res.status === 401) {
1241
+ setPreferences(defaults ?? null);
1242
+ return;
1243
+ }
1244
+ throw new Error("Failed to fetch preferences");
1245
+ }
1246
+ const data = await res.json();
1247
+ setPreferences(data.preferences ?? data);
1248
+ } catch (err) {
1249
+ setError(err instanceof Error ? err.message : "Failed to load preferences");
1250
+ } finally {
1251
+ setLoading(false);
1252
+ }
1253
+ }, [endpoint, defaults]);
1254
+ useEffect8(() => {
1255
+ fetchPreferences();
1256
+ }, [fetchPreferences]);
1257
+ const updatePreferences = useCallback6(
1258
+ async (updates) => {
1259
+ setPreferences((prev) => prev ? { ...prev, ...updates } : updates);
1260
+ setError(null);
1261
+ try {
1262
+ const res = await fetch(endpoint, {
1263
+ method: "PATCH",
1264
+ headers: { "Content-Type": "application/json" },
1265
+ body: JSON.stringify(updates)
1266
+ });
1267
+ if (!res.ok) {
1268
+ throw new Error("Failed to update preferences");
1269
+ }
1270
+ const data = await res.json();
1271
+ setPreferences(data.preferences ?? data);
1272
+ } catch (err) {
1273
+ setError(err instanceof Error ? err.message : "Failed to update preferences");
1274
+ await fetchPreferences();
1275
+ throw err;
1276
+ }
1277
+ },
1278
+ [endpoint, fetchPreferences]
1279
+ );
1280
+ return {
1281
+ preferences,
1282
+ loading,
1283
+ error,
1284
+ updatePreferences,
1285
+ refetch: fetchPreferences
1286
+ };
1287
+ }
1288
+
1289
+ // src/lib/date-helpers.ts
1290
+ function formatDateGroup(timestamp) {
1291
+ const date = typeof timestamp === "string" ? new Date(timestamp) : timestamp;
1292
+ const today = /* @__PURE__ */ new Date();
1293
+ const yesterday = new Date(today);
1294
+ yesterday.setDate(yesterday.getDate() - 1);
1295
+ if (date.toDateString() === today.toDateString()) return "Today";
1296
+ if (date.toDateString() === yesterday.toDateString()) return "Yesterday";
1297
+ return date.toLocaleDateString("en-US", { month: "short", day: "numeric", year: "numeric" });
1298
+ }
1299
+ function groupByDate(items, getTimestamp) {
1300
+ const groups = /* @__PURE__ */ new Map();
1301
+ for (const item of items) {
1302
+ const key = formatDateGroup(getTimestamp(item));
1303
+ const group = groups.get(key) ?? [];
1304
+ group.push(item);
1305
+ groups.set(key, group);
1306
+ }
1307
+ return groups;
1308
+ }
1309
+ function truncatePreview(text, limit = 180) {
1310
+ if (!text) return "";
1311
+ if (text.length <= limit) return text;
1312
+ return text.slice(0, limit).trimEnd() + "...";
1313
+ }
1314
+ function stripHtml(html) {
1315
+ return html.replace(/<[^>]*>/g, "");
1316
+ }
1317
+
1318
+ // src/lib/email-compose-helpers.ts
1319
+ var REPLY_LAYOUT_OPTIONS = [
1320
+ { value: "MODAL", label: "Modal" },
1321
+ { value: "SPLIT_HORIZONTAL", label: "Side by Side" },
1322
+ { value: "SPLIT_VERTICAL", label: "Stacked" },
1323
+ { value: "POPOUT", label: "Pop Out" }
1324
+ ];
1325
+ function isInlineLayout(layout) {
1326
+ return layout === "SPLIT_HORIZONTAL" || layout === "SPLIT_VERTICAL";
1327
+ }
1328
+ function isModalLayout(layout) {
1329
+ return layout === "MODAL" || layout === "POPOUT";
1330
+ }
1331
+ function getNextWeekday(dayOfWeek, hour) {
1332
+ const now = /* @__PURE__ */ new Date();
1333
+ const result = new Date(now);
1334
+ const diff = dayOfWeek - now.getDay();
1335
+ result.setDate(now.getDate() + (diff <= 0 ? diff + 7 : diff));
1336
+ result.setHours(hour, 0, 0, 0);
1337
+ return result;
1338
+ }
1339
+ function getTomorrowMorning() {
1340
+ const d = /* @__PURE__ */ new Date();
1341
+ d.setDate(d.getDate() + 1);
1342
+ d.setHours(9, 0, 0, 0);
1343
+ return d;
1344
+ }
1345
+ function getNextMondayMorning() {
1346
+ return getNextWeekday(1, 9);
1347
+ }
1348
+ function getQuickScheduleOptions() {
1349
+ const now = /* @__PURE__ */ new Date();
1350
+ const tomorrow9am = new Date(now);
1351
+ tomorrow9am.setDate(tomorrow9am.getDate() + 1);
1352
+ tomorrow9am.setHours(9, 0, 0, 0);
1353
+ const tomorrow2pm = new Date(tomorrow9am);
1354
+ tomorrow2pm.setHours(14, 0, 0, 0);
1355
+ return [
1356
+ { label: "In 1 hour", date: new Date(now.getTime() + 60 * 60 * 1e3) },
1357
+ { label: "In 2 hours", date: new Date(now.getTime() + 2 * 60 * 60 * 1e3) },
1358
+ { label: "Tomorrow morning (9 AM)", date: tomorrow9am },
1359
+ { label: "Tomorrow afternoon (2 PM)", date: tomorrow2pm },
1360
+ { label: "In 2 days", date: new Date(now.getTime() + 2 * 24 * 60 * 60 * 1e3) },
1361
+ { label: "In 1 week", date: new Date(now.getTime() + 7 * 24 * 60 * 60 * 1e3) }
1362
+ ];
1363
+ }
1364
+ function isValidScheduleDate(date) {
1365
+ return date.getTime() > Date.now();
1366
+ }
1367
+ function parseCustomSchedule(dateStr, timeStr = "09:00") {
1368
+ if (!dateStr) return null;
1369
+ const [year, month, day] = dateStr.split("-").map(Number);
1370
+ const [hour, minute] = timeStr.split(":").map(Number);
1371
+ const date = new Date(year, month - 1, day, hour, minute, 0, 0);
1372
+ return isValidScheduleDate(date) ? date : null;
1373
+ }
1374
+
1375
+ // src/lib/mime-helpers.ts
1376
+ function isPdf(mimeType, name) {
1377
+ return mimeType === "application/pdf" || (name?.toLowerCase().endsWith(".pdf") ?? false);
1378
+ }
1379
+ function isSpreadsheet(mimeType, name) {
1380
+ const ext = name?.toLowerCase().split(".").pop();
1381
+ return mimeType.includes("spreadsheet") || mimeType.includes("excel") || mimeType === "text/csv" || mimeType === "application/csv" || ext === "xlsx" || ext === "xls" || ext === "csv";
1382
+ }
1383
+ function isDocument(mimeType, name) {
1384
+ const ext = name?.toLowerCase().split(".").pop();
1385
+ return mimeType.includes("document") || mimeType.includes("word") || ext === "docx" || ext === "doc";
1386
+ }
1387
+ function isImage(mimeType) {
1388
+ return mimeType.startsWith("image/");
1389
+ }
1390
+ function isAudio(mimeType) {
1391
+ return mimeType.startsWith("audio/");
1392
+ }
1393
+ function isVideo(mimeType) {
1394
+ return mimeType.startsWith("video/");
1395
+ }
1396
+ function canViewInline(mimeType) {
1397
+ return isImage(mimeType) || isAudio(mimeType) || isVideo(mimeType);
1398
+ }
1399
+ function opensInNewTab(mimeType, name) {
1400
+ return isPdf(mimeType, name) || isSpreadsheet(mimeType, name);
1401
+ }
1402
+ function resolveContentType(mimeType, name) {
1403
+ if (mimeType !== "application/octet-stream") return mimeType;
1404
+ const ext = name?.toLowerCase().split(".").pop();
1405
+ if (!ext) return mimeType;
1406
+ const EXT_MAP = {
1407
+ pdf: "application/pdf",
1408
+ xlsx: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
1409
+ xls: "application/vnd.ms-excel",
1410
+ csv: "text/csv",
1411
+ docx: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
1412
+ doc: "application/msword",
1413
+ png: "image/png",
1414
+ jpg: "image/jpeg",
1415
+ jpeg: "image/jpeg",
1416
+ gif: "image/gif",
1417
+ webp: "image/webp",
1418
+ mp3: "audio/mpeg",
1419
+ wav: "audio/wav",
1420
+ mp4: "video/mp4",
1421
+ zip: "application/zip",
1422
+ json: "application/json",
1423
+ txt: "text/plain"
1424
+ };
1425
+ return EXT_MAP[ext] || mimeType;
1426
+ }
1427
+ function formatFileSize(bytes) {
1428
+ if (bytes === 0) return "0 B";
1429
+ const k = 1024;
1430
+ const sizes = ["B", "KB", "MB", "GB"];
1431
+ const i = Math.floor(Math.log(bytes) / Math.log(k));
1432
+ return `${parseFloat((bytes / Math.pow(k, i)).toFixed(1))} ${sizes[i]}`;
1433
+ }
1434
+
1435
+ // src/lib/phone-helpers.ts
1436
+ function formatPhone(phone) {
1437
+ if (!phone) return "";
1438
+ const digits = phone.replace(/\D/g, "");
1439
+ const normalized = digits.length === 11 && digits.startsWith("1") ? digits.slice(1) : digits;
1440
+ if (normalized.length === 10) {
1441
+ return `(${normalized.slice(0, 3)}) ${normalized.slice(3, 6)}-${normalized.slice(6)}`;
1442
+ }
1443
+ return phone;
1444
+ }
1445
+ function formatPhoneInput(value) {
1446
+ const digits = value.replace(/\D/g, "");
1447
+ if (digits.length <= 3) return digits;
1448
+ if (digits.length <= 6) return `(${digits.slice(0, 3)}) ${digits.slice(3)}`;
1449
+ return `(${digits.slice(0, 3)}) ${digits.slice(3, 6)}-${digits.slice(6, 10)}`;
1450
+ }
1451
+ function stripPhone(phone) {
1452
+ return phone.replace(/\D/g, "");
1453
+ }
1454
+
1455
+ // src/lib/activity-icons.tsx
1456
+ import {
1457
+ Activity,
1458
+ AlertOctagon,
1459
+ AlertTriangle,
1460
+ Archive,
1461
+ ArrowLeftRight,
1462
+ BellRing,
1463
+ Brain,
1464
+ Bug,
1465
+ Building2,
1466
+ Calendar,
1467
+ CalendarCheck,
1468
+ CalendarClock,
1469
+ CalendarX,
1470
+ CheckCircle,
1471
+ CheckCircle2,
1472
+ CheckSquare,
1473
+ Clock,
1474
+ Copy,
1475
+ Database,
1476
+ Download,
1477
+ Edit,
1478
+ Eye,
1479
+ FileDown,
1480
+ FileText,
1481
+ Gauge,
1482
+ Heart,
1483
+ Key,
1484
+ KeyRound,
1485
+ Lightbulb,
1486
+ Link as LinkIcon,
1487
+ ListTodo,
1488
+ Loader2,
1489
+ Lock,
1490
+ LogIn,
1491
+ LogOut,
1492
+ Mail,
1493
+ MailX,
1494
+ Map as Map2,
1495
+ MapPinCheck,
1496
+ MessageSquare,
1497
+ Package,
1498
+ PackageCheck,
1499
+ PenLine,
1500
+ Play,
1501
+ RefreshCw,
1502
+ Reply,
1503
+ RotateCcw,
1504
+ Ruler,
1505
+ Save,
1506
+ Search,
1507
+ Settings,
1508
+ Shield,
1509
+ ShieldAlert,
1510
+ ShieldBan,
1511
+ ShieldCheck,
1512
+ ShieldOff,
1513
+ ShieldX,
1514
+ Shirt,
1515
+ ShoppingBag,
1516
+ Sparkles,
1517
+ Tag,
1518
+ Target,
1519
+ Trash2,
1520
+ TrendingUp,
1521
+ Unlock,
1522
+ Upload,
1523
+ UserCog,
1524
+ UserMinus,
1525
+ UserPlus,
1526
+ XCircle,
1527
+ Zap
1528
+ } from "lucide-react";
1529
+ var ACTIVITY_ICONS = {
1530
+ Activity,
1531
+ AlertOctagon,
1532
+ AlertTriangle,
1533
+ Archive,
1534
+ ArrowLeftRight,
1535
+ BellRing,
1536
+ Brain,
1537
+ Bug,
1538
+ Building2,
1539
+ Calendar,
1540
+ CalendarCheck,
1541
+ CalendarClock,
1542
+ CalendarX,
1543
+ CheckCircle,
1544
+ CheckCircle2,
1545
+ CheckSquare,
1546
+ Clock,
1547
+ Copy,
1548
+ Database,
1549
+ Download,
1550
+ Edit,
1551
+ Eye,
1552
+ FileDown,
1553
+ FileText,
1554
+ Gauge,
1555
+ Heart,
1556
+ Key,
1557
+ KeyRound,
1558
+ Lightbulb,
1559
+ Link: LinkIcon,
1560
+ ListTodo,
1561
+ Loader2,
1562
+ Lock,
1563
+ LogIn,
1564
+ LogOut,
1565
+ Mail,
1566
+ MailX,
1567
+ Map: Map2,
1568
+ MapCheck: MapPinCheck,
1569
+ MessageSquare,
1570
+ Package,
1571
+ PackageCheck,
1572
+ PenLine,
1573
+ Play,
1574
+ RefreshCw,
1575
+ Reply,
1576
+ RotateCcw,
1577
+ Ruler,
1578
+ Save,
1579
+ Search,
1580
+ Settings,
1581
+ Shield,
1582
+ ShieldAlert,
1583
+ ShieldBan,
1584
+ ShieldCheck,
1585
+ ShieldOff,
1586
+ ShieldX,
1587
+ Shirt,
1588
+ ShoppingBag,
1589
+ Sparkles,
1590
+ Tag,
1591
+ Target,
1592
+ Trash2,
1593
+ TrendingUp,
1594
+ Unlock,
1595
+ Upload,
1596
+ UserCog,
1597
+ UserMinus,
1598
+ UserPlus,
1599
+ XCircle,
1600
+ Zap
1601
+ };
1602
+ function resolveActivityIcon(name) {
1603
+ return ACTIVITY_ICONS[name] ?? Activity;
1604
+ }
1605
+ export {
1606
+ ACTIVITY_ICONS,
1607
+ ALL_SHORTCUT_CONTEXTS,
1608
+ CLIENT_PROFILE_SHORTCUTS,
1609
+ EmailBodyRenderer,
1610
+ EmailThreadView,
1611
+ ErrorBoundary,
1612
+ FORM_SHORTCUTS,
1613
+ GLOBAL_SHORTCUTS,
1614
+ INBOX_SHORTCUTS,
1615
+ KeyboardShortcutsPanel,
1616
+ RENDER_ERRORS,
1617
+ REPLY_LAYOUT_OPTIONS,
1618
+ cachedFetch,
1619
+ canViewInline,
1620
+ clearCache,
1621
+ formatDateGroup,
1622
+ formatFileSize,
1623
+ formatPhone,
1624
+ formatPhoneInput,
1625
+ getNextMondayMorning,
1626
+ getNextWeekday,
1627
+ getQuickScheduleOptions,
1628
+ getShortcut,
1629
+ getTomorrowMorning,
1630
+ groupByDate,
1631
+ invalidateCache,
1632
+ isAudio,
1633
+ isDocument,
1634
+ isImage,
1635
+ isInlineLayout,
1636
+ isModalLayout,
1637
+ isPdf,
1638
+ isSpreadsheet,
1639
+ isValidScheduleDate,
1640
+ isVideo,
1641
+ opensInNewTab,
1642
+ parseCustomSchedule,
1643
+ prefetch,
1644
+ renderError,
1645
+ resolveActivityIcon,
1646
+ resolveContentType,
1647
+ stripHtml,
1648
+ stripPhone,
1649
+ truncatePreview,
1650
+ useAutoSave,
1651
+ useContextShortcuts,
1652
+ useIframeFocusReclaim,
1653
+ useKeyboardShortcuts,
1654
+ usePolling,
1655
+ usePreferences,
1656
+ useServerSearch,
1657
+ withErrorBoundary
1658
+ };