@startsimpli/integrations 0.2.50 → 0.2.51

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@startsimpli/integrations",
3
- "version": "0.2.50",
3
+ "version": "0.2.51",
4
4
  "description": "Provider-agnostic types, API clients, hooks, and UI primitives for email + calendar integrations across StartSimpli apps, plus foundry customer email (subpath ./comms).",
5
5
  "main": "./src/index.ts",
6
6
  "types": "./src/index.ts",
@@ -64,8 +64,8 @@
64
64
  "react-dom": "^19.0.0",
65
65
  "typescript": "^6.0.0",
66
66
  "vitest": "^3.0.0",
67
- "@startsimpli/ui": "0.4.164",
68
- "@startsimpli/llm": "0.4.25"
67
+ "@startsimpli/llm": "0.4.25",
68
+ "@startsimpli/ui": "0.4.164"
69
69
  },
70
70
  "scripts": {
71
71
  "type-check": "tsc --noEmit",
@@ -18,6 +18,7 @@ import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
18
18
  import { http, HttpResponse } from 'msw';
19
19
  import { setupServer } from 'msw/node';
20
20
 
21
+ import { DraftItem } from '../components/DraftReview';
21
22
  import { CustomerEmailsPage } from '../components/pages/CustomerEmailsPage';
22
23
  import { createCommsApi, setApiBase } from '../api/index';
23
24
  import type { Draft } from '../types/index';
@@ -45,6 +46,11 @@ const server = setupServer(
45
46
  const results = drafts.filter((d) => d.approval === wanted);
46
47
  return HttpResponse.json({ count: results.length, next: null, previous: null, results });
47
48
  }
49
+ const pv = hit.path.match(/^\/drafts\/([^/]+)\/preview\/$/);
50
+ if (pv) {
51
+ const d = drafts.find((x) => x.id === pv[1])!;
52
+ return HttpResponse.json({ subject: d.subject, preheader: d.preheader, html: d.html, text: d.text });
53
+ }
48
54
  const m = hit.path.match(/^\/drafts\/([^/]+)\/$/);
49
55
  if (m && hit.method === 'GET') {
50
56
  const d = drafts.find((x) => x.id === m[1])!;
@@ -183,4 +189,54 @@ describe('Announcements fold', () => {
183
189
  const { region } = await openFold();
184
190
  expect(await within(region).findByText('Waiting for you')).toBeInTheDocument();
185
191
  });
192
+
193
+ it('opens the viewer on a draft that is already listed when it is asked to', async () => {
194
+ const d = draft({ id: 'f-2', program_key: 'announcement', window: [] as any, item_keys: [] });
195
+ drafts.push(d);
196
+ const qc = new QueryClient({ defaultOptions: { queries: { retry: false } } });
197
+ const ui = (open: boolean) => (
198
+ <QueryClientProvider client={qc}>
199
+ <DraftItem api={createCommsApi(SLUG)} draft={d} startPreviewing={open} />
200
+ </QueryClientProvider>
201
+ );
202
+ const { rerender } = render(ui(false));
203
+ expect(screen.queryByTitle(/email preview/i)).toBeNull();
204
+ rerender(ui(true));
205
+ expect(await screen.findByTitle(/email preview/i)).toBeInTheDocument();
206
+ });
207
+
208
+ describe('loading an email from a file', () => {
209
+ const file = (content: string, name = 'engine.comms-content.json') =>
210
+ new File([content], name, { type: 'application/json' });
211
+ const email = { subject: 'Meet the engine, {{first_name}}', preheader: 'Faster patterns', html: '<h1>Hi</h1><p><img src="https://cdn.test/a.png" alt="A"></p>', text: 'Hi' };
212
+
213
+ it('saves the file as a draft exactly as written (html untouched) and opens it in the inbox viewer, never approving', async () => {
214
+ createReply = () => {
215
+ const d = draft({ id: 'f-1', program_key: 'announcement', ...email, window: [] as any, item_keys: [] });
216
+ drafts.push(d);
217
+ return HttpResponse.json(d, { status: 201 });
218
+ };
219
+ const { user, region } = await openFold();
220
+ await user.upload(within(region).getByLabelText(/load an email from a file/i), file(JSON.stringify(email)));
221
+ await waitFor(() => expect(posts()).toHaveLength(1));
222
+ expect(posts()[0].body).toEqual(email);
223
+ expect(await screen.findByTitle(/email preview/i)).toBeInTheDocument();
224
+ expect(screen.getByRole('group', { name: /inbox row/i })).toBeInTheDocument();
225
+ expect(hits.filter((h) => h.path.includes('approve') || h.path.includes('test'))).toEqual([]);
226
+ });
227
+
228
+ it('refuses a file that is not an email, and saves nothing', async () => {
229
+ const { user, region } = await openFold();
230
+ await user.upload(within(region).getByLabelText(/load an email from a file/i), file('{"hello":1}'));
231
+ expect(await within(region).findByText(/needs a subject and html/i)).toBeInTheDocument();
232
+ expect(posts()).toHaveLength(0);
233
+ });
234
+
235
+ it('refuses a file that is not JSON', async () => {
236
+ const { user, region } = await openFold();
237
+ await user.upload(within(region).getByLabelText(/load an email from a file/i), file('not json'));
238
+ expect(await within(region).findByText(/not valid JSON/i)).toBeInTheDocument();
239
+ expect(posts()).toHaveLength(0);
240
+ });
241
+ });
186
242
  });
@@ -354,11 +354,11 @@ describe('comeback sequence settings (A2)', () => {
354
354
  const step2 = within(fold).getAllByRole('listitem')[1];
355
355
  await userEvent.click(within(step2).getByRole('button', { name: /^preview$/i }));
356
356
  await waitFor(() => expect(hits.some((h) => h.method === 'GET' && h.path === '/programs/comeback/steps/1/preview/')).toBe(true));
357
- const frame = await within(fold).findByTitle(/email preview/i);
357
+ const frame = await screen.findByTitle(/email preview/i);
358
358
  expect(frame.tagName).toBe('IFRAME');
359
359
  expect(frame.getAttribute('srcdoc')).toContain('<p>Hi Quinn, step 1</p>');
360
360
  expect(frame.hasAttribute('sandbox')).toBe(true);
361
- expect(within(fold).getByText('Preview subject 1')).toBeInTheDocument();
361
+ expect(screen.getAllByText('Preview subject 1')).toHaveLength(1);
362
362
  });
363
363
 
364
364
  it('sends a test of a step to the admin only, on click', async () => {
@@ -546,14 +546,58 @@ describe('draft review (A4)', () => {
546
546
  it('previews a draft as the SERVER rendered it (G2), in a sandboxed iframe', async () => {
547
547
  renderPage();
548
548
  const fold = await openFold(/^product updates$/i);
549
- await userEvent.click(await within(fold).findByRole('button', { name: /^preview$/i }));
549
+ await userEvent.click(await within(fold).findByRole('button', { name: /^preview as inbox$/i }));
550
550
  await waitFor(() => expect(hits.some((h) => h.method === 'GET' && h.path === '/drafts/d-1/preview/')).toBe(true));
551
- const frame = await within(fold).findByTitle(/email preview/i);
551
+ const frame = await screen.findByTitle(/email preview/i);
552
552
  expect(frame.getAttribute('srcdoc')).toContain('<p>Hi Quinn, New: stitch counter</p>');
553
553
  expect(frame.hasAttribute('sandbox')).toBe(true);
554
554
  expect(writes()).toEqual([]);
555
555
  });
556
556
 
557
+ describe('inbox viewer', () => {
558
+ async function openViewer() {
559
+ renderPage();
560
+ const fold = await openFold(/^product updates$/i);
561
+ await userEvent.click(await within(fold).findByRole('button', { name: /^preview as inbox$/i }));
562
+ const frame = await screen.findByTitle(/email preview/i);
563
+ return { frame };
564
+ }
565
+
566
+ it('shows the inbox row: sender name, subject once, and the preheader snippet', async () => {
567
+ await openViewer();
568
+ const row = screen.getByRole('group', { name: /inbox row/i });
569
+ expect(within(row).getByText('Crochets')).toBeInTheDocument();
570
+ expect(screen.getAllByText('Rendered: New: stitch counter')).toHaveLength(1);
571
+ expect(within(row).getByText(/Count rows hands-free/)).toBeInTheDocument();
572
+ });
573
+
574
+ it('switches the rendered email between desktop (700px) and mobile (375px) width', async () => {
575
+ const { frame } = await openViewer();
576
+ expect(screen.getByRole('button', { name: /^desktop$/i })).toHaveAttribute('aria-pressed', 'true');
577
+ expect(frame.style.width).toBe('700px');
578
+ await userEvent.click(screen.getByRole('button', { name: /^mobile$/i }));
579
+ expect(screen.getByRole('button', { name: /^mobile$/i })).toHaveAttribute('aria-pressed', 'true');
580
+ expect(frame.style.width).toBe('375px');
581
+ expect(frame.getAttribute('srcdoc')).toContain('<p>Hi Quinn, New: stitch counter</p>');
582
+ });
583
+
584
+ it('shows the plain-text version, and goes back to the email', async () => {
585
+ await openViewer();
586
+ await userEvent.click(screen.getByRole('button', { name: /^plain text$/i }));
587
+ expect(screen.queryByTitle(/email preview/i)).toBeNull();
588
+ expect(screen.getByText('Stitch counter', { selector: 'pre' })).toBeInTheDocument();
589
+ await userEvent.click(screen.getByRole('button', { name: /^email$/i }));
590
+ expect(screen.getByTitle(/email preview/i)).toBeInTheDocument();
591
+ });
592
+
593
+ it('never writes: viewing is read-only', async () => {
594
+ await openViewer();
595
+ await userEvent.click(screen.getByRole('button', { name: /^mobile$/i }));
596
+ await userEvent.click(screen.getByRole('button', { name: /^plain text$/i }));
597
+ expect(writes()).toEqual([]);
598
+ });
599
+ });
600
+
557
601
  it('a draft whose writing failed offers only Discard', async () => {
558
602
  db.drafts = [draft({ subject: '', error: 'generation_failed' })];
559
603
  renderPage();
@@ -0,0 +1,233 @@
1
+ /**
2
+ * The email viewer (bd startsim-uwiw6.4): previewing an email is ONE page-sized
3
+ * thing, not a panel nested inside a fold inside a list card.
4
+ *
5
+ * - a back link, one slim toolbar (Desktop | Mobile, Email | Plain text), the inbox row
6
+ * (sender, subject, preheader) and the email in a single frame;
7
+ * - the subject appears once; the sender is the foundry's sender name, else the
8
+ * foundry's own name, never the literal "Sender";
9
+ * - plain text wraps on words and keeps line breaks;
10
+ * - the html is the server's render in a sandboxed frame (no scripts);
11
+ * - with a host-provided link target, "Preview as inbox" / step "Preview" are links to it.
12
+ */
13
+ import * as React from 'react';
14
+ import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it } from 'vitest';
15
+ import { render, screen, within } from '@testing-library/react';
16
+ import userEvent from '@testing-library/user-event';
17
+ import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
18
+ import { http, HttpResponse } from 'msw';
19
+ import { setupServer } from 'msw/node';
20
+
21
+ import { EmailPreview } from '../components/EmailPreview';
22
+ import { EmailPreviewPage, parsePreviewItemId, previewItemId } from '../components/EmailPreviewPage';
23
+ import { CustomerEmailsPage } from '../components/pages/CustomerEmailsPage';
24
+ import { createCommsApi, setApiBase } from '../api/index';
25
+ import type { CommsSettings } from '../types/index';
26
+ import { BASE, P, SLUG, comeback, draft, productUpdate, settings } from './fixtures';
27
+
28
+ const email = {
29
+ subject: 'Meet the engine',
30
+ preheader: 'Faster, steadier patterns',
31
+ html: '<h1>Hi</h1>',
32
+ text: 'Line one is a supercalifragilisticexpialidocious_unbrokenword_that_must_not_split\nLine two',
33
+ };
34
+
35
+ describe('EmailPreview (the viewer itself)', () => {
36
+ const view = (over = {}) =>
37
+ render(<EmailPreview email={email} sender={{ name: 'Crochets', address: 'crochets@mail.test' }} backHref="/back" backLabel="Back to Customer emails" {...over} />);
38
+
39
+ it('has a back link, a slim toolbar and the inbox row, in one frame', () => {
40
+ view();
41
+ expect(screen.getByRole('link', { name: /back to customer emails/i })).toHaveAttribute('href', '/back');
42
+ expect(screen.getByRole('button', { name: /^desktop$/i })).toHaveAttribute('aria-pressed', 'true');
43
+ expect(screen.getByRole('button', { name: /^mobile$/i })).toBeInTheDocument();
44
+ expect(screen.getByRole('button', { name: /^email$/i })).toBeInTheDocument();
45
+ expect(screen.getByRole('button', { name: /^plain text$/i })).toBeInTheDocument();
46
+ expect(screen.getAllByTitle(/email preview/i)).toHaveLength(1);
47
+ });
48
+
49
+ it('shows the subject once, with the sender and preheader on the inbox row', () => {
50
+ view();
51
+ expect(screen.getAllByText('Meet the engine')).toHaveLength(1);
52
+ const row = screen.getByRole('group', { name: /inbox row/i });
53
+ expect(within(row).getByText('Crochets')).toBeInTheDocument();
54
+ expect(within(row).getByText('Meet the engine')).toBeInTheDocument();
55
+ expect(within(row).getByText(/Faster, steadier patterns/)).toBeInTheDocument();
56
+ });
57
+
58
+ it('never prints the literal "Sender"', () => {
59
+ view({ sender: { name: '' } });
60
+ expect(screen.queryByText(/^sender$/i)).toBeNull();
61
+ });
62
+
63
+ it('lays the email out at 700px on desktop and 375px on mobile', async () => {
64
+ view();
65
+ const frame = screen.getByTitle(/email preview/i);
66
+ expect(frame.style.width).toBe('700px');
67
+ await userEvent.click(screen.getByRole('button', { name: /^mobile$/i }));
68
+ expect(screen.getByTitle(/email preview/i).style.width).toBe('375px');
69
+ expect(screen.getByTitle(/email preview/i).getAttribute('srcdoc')).toBe('<h1>Hi</h1>');
70
+ });
71
+
72
+ it('runs no scripts in the frame and has no internal scroll box', () => {
73
+ view();
74
+ const frame = screen.getByTitle(/email preview/i);
75
+ expect(frame.getAttribute('sandbox') ?? '').not.toMatch(/allow-scripts/);
76
+ expect(frame.getAttribute('scrolling')).toBe('no');
77
+ expect(frame.className).not.toMatch(/h-\[720px\]/);
78
+ });
79
+
80
+ it('wraps plain text on words (not mid-word) and keeps its line breaks', async () => {
81
+ view();
82
+ await userEvent.click(screen.getByRole('button', { name: /^plain text$/i }));
83
+ expect(screen.queryByTitle(/email preview/i)).toBeNull();
84
+ const pre = screen.getByText(/Line one is/, { selector: 'pre' });
85
+ expect(pre.className).toMatch(/whitespace-pre-wrap/);
86
+ expect(pre.className).not.toMatch(/break-all/);
87
+ expect(pre.textContent).toContain('\nLine two');
88
+ });
89
+
90
+ it('calls onBack from the back link when given, without following the href', async () => {
91
+ let back = 0;
92
+ view({ onBack: () => { back += 1; } });
93
+ await userEvent.click(screen.getByRole('link', { name: /back to customer emails/i }));
94
+ expect(back).toBe(1);
95
+ });
96
+ });
97
+
98
+ // ---- the page: fetches the server render + the sender ------------------------------------------
99
+
100
+ interface Hit { method: string; path: string }
101
+ let hits: Hit[] = [];
102
+ let sets: CommsSettings;
103
+ const rel = (p: string) => p.replace(new URL(P).pathname, '');
104
+
105
+ const server = setupServer(
106
+ http.all(`${P}/*`, ({ request }) => {
107
+ const path = rel(new URL(request.url).pathname);
108
+ hits.push({ method: request.method, path });
109
+ if (path === '/settings/') return HttpResponse.json(sets);
110
+ if (path === '/programs/') return HttpResponse.json([comeback(), productUpdate()]);
111
+ if (path === '/drafts/d-1/preview/') return HttpResponse.json({ subject: 'Rendered subject', preheader: 'Rendered pre', html: '<p>server html</p>', text: 'plain' });
112
+ if (path === '/programs/comeback/steps/1/preview/') return HttpResponse.json({ subject: 'Step subject', preheader: '', html: '<p>step html</p>', text: 'step plain' });
113
+ if (path === '/drafts/') {
114
+ const pending = new URL(request.url).searchParams.get('status') === 'pending';
115
+ return HttpResponse.json({ count: pending ? 1 : 0, next: null, previous: null, results: pending ? [draft()] : [] });
116
+ }
117
+ return HttpResponse.json({});
118
+ }),
119
+ );
120
+ beforeAll(() => {
121
+ server.listen({ onUnhandledRequest: 'error' });
122
+ setApiBase(`${BASE}/api/v1`);
123
+ });
124
+ afterAll(() => server.close());
125
+ beforeEach(() => {
126
+ hits = [];
127
+ sets = settings();
128
+ });
129
+ afterEach(() => server.resetHandlers());
130
+
131
+ const qc = () => new QueryClient({ defaultOptions: { queries: { retry: false } } });
132
+ const pageFor = (itemId: string, props = {}) =>
133
+ render(
134
+ <QueryClientProvider client={qc()}>
135
+ <EmailPreviewPage api={createCommsApi(SLUG)} itemId={itemId} fallbackSenderName="Crochets Foundry" backHref="/foundry/crochets/customer-emails" {...props} />
136
+ </QueryClientProvider>,
137
+ );
138
+
139
+ describe('EmailPreviewPage', () => {
140
+ it('previews a draft as the SERVER rendered it, never writing', async () => {
141
+ pageFor('d-1');
142
+ const frame = await screen.findByTitle(/email preview/i);
143
+ expect(frame.getAttribute('srcdoc')).toBe('<p>server html</p>');
144
+ expect(screen.getAllByText('Rendered subject')).toHaveLength(1);
145
+ expect(hits.filter((h) => h.method !== 'GET')).toEqual([]);
146
+ expect(screen.getByRole('link', { name: /back/i })).toHaveAttribute('href', '/foundry/crochets/customer-emails');
147
+ });
148
+
149
+ it('previews a comeback step from its item id', async () => {
150
+ pageFor('step.comeback.1');
151
+ expect((await screen.findByTitle(/email preview/i)).getAttribute('srcdoc')).toBe('<p>step html</p>');
152
+ expect(hits.some((h) => h.path === '/programs/comeback/steps/1/preview/')).toBe(true);
153
+ });
154
+
155
+ it('shows the configured sender name', async () => {
156
+ pageFor('d-1');
157
+ await screen.findByTitle(/email preview/i);
158
+ expect(within(screen.getByRole('group', { name: /inbox row/i })).getByText('Crochets')).toBeInTheDocument();
159
+ });
160
+
161
+ it('with no sender configured, falls back to the foundry name, never "Sender"', async () => {
162
+ sets = settings({ sender_name: '', from_address: null });
163
+ pageFor('d-1');
164
+ await screen.findByTitle(/email preview/i);
165
+ const row = screen.getByRole('group', { name: /inbox row/i });
166
+ expect(within(row).getByText('Crochets Foundry')).toBeInTheDocument();
167
+ expect(screen.queryByText(/^sender$/i)).toBeNull();
168
+ });
169
+
170
+ it('uses the name part of a Name <address> from line when only that is configured', async () => {
171
+ sets = settings({ sender_name: '', from_address: 'Acme Co <hi@mail.acme.test>' });
172
+ pageFor('d-1');
173
+ await screen.findByTitle(/email preview/i);
174
+ expect(within(screen.getByRole('group', { name: /inbox row/i })).getByText('Acme Co')).toBeInTheDocument();
175
+ });
176
+ });
177
+
178
+ describe('preview item ids', () => {
179
+ it('round-trips a draft and a step', () => {
180
+ expect(parsePreviewItemId('d-1')).toEqual({ kind: 'draft', id: 'd-1' });
181
+ expect(previewItemId({ kind: 'draft', id: 'd-1' })).toBe('d-1');
182
+ expect(parsePreviewItemId('step.comeback.2')).toEqual({ kind: 'step', programKey: 'comeback', index: 2 });
183
+ expect(previewItemId({ kind: 'step', programKey: 'comeback', index: 2 })).toBe('step.comeback.2');
184
+ });
185
+ });
186
+
187
+ // ---- the launch points -----------------------------------------------------------------
188
+
189
+ describe('launching the viewer from the Customer emails page', () => {
190
+ const mountPage = (props = {}) =>
191
+ render(
192
+ <QueryClientProvider client={qc()}>
193
+ <CustomerEmailsPage api={createCommsApi(SLUG)} foundrySlug={SLUG} pollIntervalMs={10} {...props} />
194
+ </QueryClientProvider>,
195
+ );
196
+ const open = async (name: RegExp) => {
197
+ await userEvent.click(await screen.findByRole('button', { name }));
198
+ return screen.findByRole('region', { name });
199
+ };
200
+
201
+ it('with a viewer link target, a draft "Preview as inbox" is a link to it and fetches no preview', async () => {
202
+ mountPage({ viewerHref: (id: string) => `/foundry/${SLUG}/customer-emails/${id}/preview` });
203
+ const fold = await open(/^product updates$/i);
204
+ const link = await within(fold).findByRole('link', { name: /^preview as inbox$/i });
205
+ expect(link).toHaveAttribute('href', `/foundry/${SLUG}/customer-emails/d-1/preview`);
206
+ expect(hits.some((h) => h.path.includes('/preview/'))).toBe(false);
207
+ });
208
+
209
+ it('with a viewer link target, a comeback step "Preview" links to the same viewer', async () => {
210
+ mountPage({ viewerHref: (id: string) => `/v/${id}` });
211
+ const fold = await open(/^comeback sequence settings$/i);
212
+ const step2 = within(fold).getAllByRole('listitem')[1];
213
+ expect(within(step2).getByRole('link', { name: /^preview$/i })).toHaveAttribute('href', '/v/step.comeback.1');
214
+ });
215
+
216
+ it('with an onOpenViewer handler, a click hands over the href instead of reloading', async () => {
217
+ const opened: string[] = [];
218
+ mountPage({ viewerHref: (id: string) => `/v/${id}`, onOpenViewer: (href: string) => opened.push(href) });
219
+ const fold = await open(/^product updates$/i);
220
+ await userEvent.click(await within(fold).findByRole('link', { name: /^preview as inbox$/i }));
221
+ expect(opened).toEqual(['/v/d-1']);
222
+ });
223
+
224
+ it('without a host link target, the button opens the same viewer full-viewport and Back closes it', async () => {
225
+ mountPage();
226
+ const fold = await open(/^product updates$/i);
227
+ await userEvent.click(await within(fold).findByRole('button', { name: /^preview as inbox$/i }));
228
+ const frame = await screen.findByTitle(/email preview/i);
229
+ expect(frame.closest('[data-email-viewer]')).not.toBeNull();
230
+ await userEvent.click(screen.getByRole('link', { name: /back/i }));
231
+ expect(screen.queryByTitle(/email preview/i)).toBeNull();
232
+ });
233
+ });
@@ -13,6 +13,8 @@ import { Button, Input, Label, Textarea } from '@startsimpli/ui';
13
13
  import type { CommsApi } from '../api/comms';
14
14
  import { DEFAULT_POLL_MS, useCreateDraft, useDraft } from '../hooks/index';
15
15
  import type { CommsAsset } from '../types/index';
16
+
17
+ type EmailContentInput = { subject: string; html: string; preheader?: string; text?: string };
16
18
  import { DraftReview } from './DraftReview';
17
19
  import { ImageLibrary } from './ImageLibrary';
18
20
  import { ErrorNotice, Note, humanize, useFieldId } from './_shared';
@@ -24,6 +26,24 @@ export interface AnnouncementComposerProps {
24
26
 
25
27
  type Mode = 'write' | 'notes';
26
28
 
29
+ /** An email file in the composer's own JSON format: {subject, preheader?, html, text?}. */
30
+ function parseEmailFile(raw: string): { input?: EmailContentInput; error?: string } {
31
+ let data: unknown;
32
+ try {
33
+ data = JSON.parse(raw);
34
+ } catch {
35
+ return { error: 'That file is not valid JSON.' };
36
+ }
37
+ const o = (data && typeof data === 'object' ? data : {}) as Record<string, unknown>;
38
+ const str = (k: string) => (typeof o[k] === 'string' ? (o[k] as string) : undefined);
39
+ const subject = str('subject');
40
+ const html = str('html');
41
+ if (!subject?.trim() || !html?.trim()) return { error: 'That file needs a subject and html to be an email.' };
42
+ const preheader = str('preheader');
43
+ const text = str('text');
44
+ return { input: { subject, html, ...(preheader !== undefined ? { preheader } : {}), ...(text !== undefined ? { text } : {}) } };
45
+ }
46
+
27
47
  const escapeHtml = (s: string) => s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
28
48
 
29
49
  const IMAGE = /!\[([^\]]*)\]\((https?:\/\/[^\s)]+)\)/g;
@@ -87,6 +107,7 @@ export function AnnouncementComposer({ api, pollIntervalMs = DEFAULT_POLL_MS }:
87
107
  const [following, setFollowing] = useState<string | null>(null);
88
108
  const [status, setStatus] = useState<string | null>(null);
89
109
  const [failure, setFailure] = useState<string | null>(null);
110
+ const [loadedId, setLoadedId] = useState<string | null>(null);
90
111
 
91
112
  const onFinished = useCallback((error: string | null) => {
92
113
  setFollowing(null);
@@ -97,6 +118,20 @@ export function AnnouncementComposer({ api, pollIntervalMs = DEFAULT_POLL_MS }:
97
118
  const insertImage = (a: CommsAsset) =>
98
119
  setMessage((m) => `${m.trimEnd()}${m.trim() ? '\n\n' : ''}![${a.alt}](${a.url})`);
99
120
 
121
+ const loadFile = async (file: File | undefined) => {
122
+ if (!file) return;
123
+ setStatus(null);
124
+ setFailure(null);
125
+ const { input, error } = parseEmailFile(await file.text());
126
+ if (!input) return setFailure(error ?? 'That file could not be read.');
127
+ create.mutate(input, {
128
+ onSuccess: (d) => {
129
+ setLoadedId(d.id);
130
+ setStatus(`Loaded "${file.name}" as a draft. It opens in the email viewer; nothing is sent until you approve it.`);
131
+ },
132
+ });
133
+ };
134
+
100
135
  const canSave = mode === 'write' ? !!subject.trim() && !!message.trim() : !!notes.trim();
101
136
 
102
137
  const submit = () => {
@@ -180,6 +215,21 @@ export function AnnouncementComposer({ api, pollIntervalMs = DEFAULT_POLL_MS }:
180
215
  </div>
181
216
  )}
182
217
 
218
+ <div className="space-y-1">
219
+ <Label htmlFor={`${ids}-file`}>Load an email from a file (.json)</Label>
220
+ <input
221
+ id={`${ids}-file`}
222
+ type="file"
223
+ accept=".json,application/json"
224
+ className="block text-sm"
225
+ onChange={(e) => {
226
+ void loadFile(e.target.files?.[0]);
227
+ e.target.value = '';
228
+ }}
229
+ />
230
+ <Note>{'A file with {"subject", "preheader", "html", "text"}. The file becomes a draft and opens in the email viewer.'}</Note>
231
+ </div>
232
+
183
233
  <Button type="submit" disabled={!canSave || create.isPending || !!following}>
184
234
  {mode === 'write' ? 'Save as draft' : 'Write a draft from my notes'}
185
235
  </Button>
@@ -190,7 +240,7 @@ export function AnnouncementComposer({ api, pollIntervalMs = DEFAULT_POLL_MS }:
190
240
  ) : null}
191
241
  {status ? <Note>{status}</Note> : null}
192
242
  <ErrorNotice error={create.error ?? (failure ? new Error(failure) : null)} />
193
- <DraftReview api={api} pollIntervalMs={pollIntervalMs} />
243
+ <DraftReview api={api} pollIntervalMs={pollIntervalMs} openId={loadedId} />
194
244
  </div>
195
245
  );
196
246
  }
@@ -15,14 +15,13 @@ import {
15
15
  useApproveDraft,
16
16
  useDiscardDraft,
17
17
  useRetryDraft,
18
- useDraftPreview,
19
18
  useDrafts,
20
19
  useSendTest,
21
20
  useUpdateDraft,
22
21
  } from '../hooks/index';
23
22
  import type { Draft, DraftAction, DraftPatch } from '../types/index';
24
23
  import { AudiencePanel } from './AudiencePanel';
25
- import { EmailPreview } from './EmailPreview';
24
+ import { PreviewAsInbox } from './EmailPreviewPage';
26
25
  import { SchedulePicker } from './SchedulePicker';
27
26
  import { ScheduledSends } from './ScheduledSends';
28
27
  import { ErrorNotice, Note, formatDate, formatDateTime, humanize, useFieldId } from './_shared';
@@ -32,6 +31,8 @@ export interface DraftReviewProps {
32
31
  pollIntervalMs?: number;
33
32
  /** Drafts per server page. Default 10. */
34
33
  pageSize?: number;
34
+ /** A draft whose inbox viewer opens by itself (the one just loaded from a file). */
35
+ openId?: string | null;
35
36
  }
36
37
 
37
38
  function DraftEditor({ api, draft, onDone }: { api: CommsApi; draft: Draft; onDone: () => void }) {
@@ -92,17 +93,18 @@ export function DraftItem({
92
93
  api,
93
94
  draft,
94
95
  onSentImmediately,
96
+ startPreviewing = false,
95
97
  }: {
96
98
  api: CommsApi;
97
99
  draft: Draft;
98
100
  onSentImmediately?: (draft: Draft) => void;
101
+ /** Open the inbox viewer straight away (a draft just loaded from a file). */
102
+ startPreviewing?: boolean;
99
103
  }) {
100
104
  const [editing, setEditing] = useState(false);
101
- const [previewing, setPreviewing] = useState(false);
102
105
  const [auditing, setAuditing] = useState(false);
103
106
  const [scheduling, setScheduling] = useState(false);
104
107
  const ready = !draft.generating && !draft.error;
105
- const preview = useDraftPreview(api, draft.id, previewing && ready);
106
108
  const sendTest = useSendTest(api);
107
109
  const approve = useApproveDraft(api);
108
110
  const discard = useDiscardDraft(api);
@@ -123,7 +125,7 @@ export function DraftItem({
123
125
  <div className="flex flex-wrap gap-2">
124
126
  {ready ? (
125
127
  <>
126
- <Button type="button" size="sm" variant="outline" onClick={() => setPreviewing((v) => !v)}>Preview</Button>
128
+ <PreviewAsInbox api={api} source={{ kind: 'draft', id: draft.id }} label="Preview as inbox" autoOpen={startPreviewing} />
127
129
  {allowed(draft, 'edit') ? (
128
130
  <>
129
131
  <Button type="button" size="sm" variant="outline" onClick={() => setEditing((v) => !v)}>Edit</Button>
@@ -184,10 +186,9 @@ export function DraftItem({
184
186
  : draft.notice.reason}
185
187
  </Note>
186
188
  ) : null}
187
- <ErrorNotice error={sendTest.error ?? approve.error ?? discard.error ?? retry.error ?? preview.error} />
189
+ <ErrorNotice error={sendTest.error ?? approve.error ?? discard.error ?? retry.error} />
188
190
  {editing && ready ? <DraftEditor api={api} draft={draft} onDone={() => setEditing(false)} /> : null}
189
191
  {auditing && ready ? <AudiencePanel api={api} draftId={draft.id} /> : null}
190
- {previewing && preview.data ? <EmailPreview email={preview.data} /> : null}
191
192
  {scheduling && ready ? (
192
193
  <SchedulePicker
193
194
  api={api}
@@ -225,7 +226,7 @@ function NeedsAttention({ api, pollIntervalMs, onSentImmediately }: {
225
226
  );
226
227
  }
227
228
 
228
- export function DraftReview({ api, pollIntervalMs = DEFAULT_POLL_MS, pageSize = 10 }: DraftReviewProps): ReactElement | null {
229
+ export function DraftReview({ api, pollIntervalMs = DEFAULT_POLL_MS, pageSize = 10, openId = null }: DraftReviewProps): ReactElement | null {
229
230
  const [page, setPage] = useState(1);
230
231
  const [justSent, setJustSent] = useState<Draft | null>(null);
231
232
  const drafts = useDrafts(api, { status: 'pending', page, page_size: pageSize }, pollIntervalMs);
@@ -257,7 +258,7 @@ export function DraftReview({ api, pollIntervalMs = DEFAULT_POLL_MS, pageSize =
257
258
  <h3 className="text-sm font-medium">Waiting for approval</h3>
258
259
  <ul className="divide-y">
259
260
  {results.map((d) => (
260
- <DraftItem key={d.id} api={api} draft={d} onSentImmediately={setJustSent} />
261
+ <DraftItem key={d.id} api={api} draft={d} onSentImmediately={setJustSent} startPreviewing={d.id === openId} />
261
262
  ))}
262
263
  </ul>
263
264
  {count > pageSize ? (
@@ -1,28 +1,171 @@
1
1
  /**
2
- * Renders a server-rendered email (subject, preheader, html) as the customer
3
- * would see it: html inside a sandboxed <iframe srcDoc>, never injected into
4
- * the admin page (email CSS would leak, and DOMPurify would strip it).
2
+ * The email viewer: ONE page-sized view of an email the way a recipient meets it, not a panel
3
+ * inside a list inside a fold. A back link and a slim toolbar on one line, the inbox row
4
+ * (sender, subject, preheader) as a mail client lists it, then the email in a single frame at
5
+ * its full height, so the page scrolls and the frame does not.
6
+ *
7
+ * It covers the viewport (a portal-free `fixed` layer), so it reads the same whether a host
8
+ * routes to it or the Customer emails page opens it in place. The html is the SERVER's render
9
+ * through the brand wrapper, shown in a sandboxed <iframe srcDoc>, never injected into the admin
10
+ * page (email CSS would leak, and DOMPurify would strip it). The frame runs no scripts; it is
11
+ * same-origin only so the page can read its height. Viewing never writes anything.
5
12
  */
6
- import type { ReactElement } from 'react';
13
+ import { useCallback, useEffect, useRef, useState, type ReactElement } from 'react';
14
+ import { Button } from '@startsimpli/ui';
15
+
16
+ import type { Sender } from '../hooks/index';
7
17
  import type { RenderedEmail } from '../types/index';
8
18
 
9
19
  export interface EmailPreviewProps {
10
20
  email: RenderedEmail;
21
+ sender: Sender;
22
+ /** Where the back link goes (and what it is called). */
23
+ backHref?: string;
24
+ backLabel?: string;
25
+ /** Handle Back in place (client navigation, or closing an overlay) instead of following the href. */
26
+ onBack?: () => void;
11
27
  title?: string;
12
28
  }
13
29
 
14
- export function EmailPreview({ email, title = 'Email preview' }: EmailPreviewProps): ReactElement {
30
+ type Width = 'desktop' | 'mobile';
31
+ type Part = 'email' | 'text';
32
+
33
+ const WIDTH_PX: Record<Width, number> = { desktop: 700, mobile: 375 };
34
+
35
+ function Toggle<T extends string>({ label, value, options, onChange }: {
36
+ label: string;
37
+ value: T;
38
+ options: readonly (readonly [T, string])[];
39
+ onChange: (v: T) => void;
40
+ }) {
41
+ return (
42
+ <div role="group" aria-label={label} className="flex gap-1">
43
+ {options.map(([v, text]) => (
44
+ <Button
45
+ key={v}
46
+ type="button"
47
+ size="sm"
48
+ variant={value === v ? 'default' : 'outline'}
49
+ aria-pressed={value === v}
50
+ onClick={() => onChange(v)}
51
+ >
52
+ {text}
53
+ </Button>
54
+ ))}
55
+ </div>
56
+ );
57
+ }
58
+
59
+ /** The email at `width`, as tall as its content: the page scrolls, not the frame. */
60
+ function EmailFrame({ html, width, title }: { html: string; width: number; title: string }) {
61
+ const ref = useRef<HTMLIFrameElement>(null);
62
+ const observer = useRef<ResizeObserver | null>(null);
63
+ const [height, setHeight] = useState(600);
64
+
65
+ const measure = useCallback(() => {
66
+ const root = ref.current?.contentDocument?.documentElement;
67
+ if (!root) return;
68
+ const h = Math.ceil(root.getBoundingClientRect().height);
69
+ if (h > 0) setHeight(h);
70
+ }, []);
71
+
72
+ const onLoad = useCallback(() => {
73
+ measure();
74
+ const root = ref.current?.contentDocument?.documentElement;
75
+ observer.current?.disconnect();
76
+ if (root && typeof ResizeObserver !== 'undefined') {
77
+ observer.current = new ResizeObserver(measure);
78
+ observer.current.observe(root);
79
+ }
80
+ }, [measure]);
81
+
82
+ useEffect(() => () => observer.current?.disconnect(), []);
83
+
84
+ return (
85
+ <iframe
86
+ ref={ref}
87
+ title={title}
88
+ // No allow-scripts: nothing in the email runs. allow-same-origin only lets us read its height.
89
+ sandbox="allow-same-origin"
90
+ scrolling="no"
91
+ srcDoc={html}
92
+ onLoad={onLoad}
93
+ style={{ width, maxWidth: '100%', height }}
94
+ className="block border-0 bg-white"
95
+ />
96
+ );
97
+ }
98
+
99
+ export function EmailPreview({
100
+ email,
101
+ sender,
102
+ backHref = '#',
103
+ backLabel = 'Back',
104
+ onBack,
105
+ title = 'Email preview',
106
+ }: EmailPreviewProps): ReactElement {
107
+ const [width, setWidth] = useState<Width>('desktop');
108
+ const [part, setPart] = useState<Part>('email');
109
+ const px = WIDTH_PX[width];
110
+ const device = width === 'mobile' ? 'rounded-[28px] border-8 border-neutral-800' : 'shadow-sm';
111
+
15
112
  return (
16
- <div className="mt-2 rounded-md border">
17
- <div className="border-b px-3 py-2 text-sm">
18
- <div>
19
- <span className="text-muted-foreground">Subject: </span>
113
+ <div data-email-viewer className="fixed inset-0 z-50 overflow-y-auto bg-neutral-100 text-neutral-900 dark:bg-neutral-900 dark:text-neutral-100">
114
+ <div className="mx-auto flex max-w-4xl flex-wrap items-center justify-between gap-x-4 gap-y-2 px-4 py-3">
115
+ <a
116
+ href={backHref}
117
+ className="text-sm text-neutral-600 hover:text-neutral-900 hover:underline dark:text-neutral-400 dark:hover:text-neutral-100"
118
+ onClick={(e) => {
119
+ if (!onBack) return;
120
+ e.preventDefault();
121
+ onBack();
122
+ }}
123
+ >
124
+ {`← ${backLabel}`}
125
+ </a>
126
+ <div className="flex flex-wrap items-center gap-3">
127
+ <Toggle
128
+ label="Screen width"
129
+ value={width}
130
+ options={[['desktop', 'Desktop'], ['mobile', 'Mobile']] as const}
131
+ onChange={setWidth}
132
+ />
133
+ <Toggle
134
+ label="Email or plain text"
135
+ value={part}
136
+ options={[['email', 'Email'], ['text', 'Plain text']] as const}
137
+ onChange={setPart}
138
+ />
139
+ </div>
140
+ </div>
141
+
142
+ {/* The inbox row, as a mail client lists it: sender, then the subject with the preheader greyed after it. */}
143
+ <div
144
+ role="group"
145
+ aria-label="Inbox row"
146
+ className="mx-auto flex max-w-4xl items-baseline gap-4 bg-white px-4 py-3 text-sm text-neutral-900 dark:bg-neutral-800 dark:text-neutral-100"
147
+ >
148
+ <span className="w-40 shrink-0 truncate font-semibold">{sender.name}</span>
149
+ <span className="min-w-0 flex-1 truncate">
20
150
  <span className="font-medium">{email.subject}</span>
151
+ {email.preheader ? <span className="text-neutral-500">{` - ${email.preheader}`}</span> : null}
152
+ </span>
153
+ </div>
154
+
155
+ <div className="px-4 py-8">
156
+ <div className={`mx-auto w-fit max-w-full overflow-hidden bg-white ${device}`}>
157
+ {part === 'email' ? (
158
+ <EmailFrame html={email.html} width={px} title={title} />
159
+ ) : (
160
+ <pre
161
+ style={{ width: px, maxWidth: '100%' }}
162
+ className="whitespace-pre-wrap break-words p-6 font-mono text-sm text-neutral-900"
163
+ >
164
+ {email.text}
165
+ </pre>
166
+ )}
21
167
  </div>
22
- {email.preheader ? <div className="text-muted-foreground">{email.preheader}</div> : null}
23
168
  </div>
24
- {/* sandbox="" : no scripts, no same-origin, no navigation of the admin page. */}
25
- <iframe title={title} sandbox="" srcDoc={email.html} className="h-[480px] w-full bg-white" />
26
169
  </div>
27
170
  );
28
171
  }
@@ -0,0 +1,161 @@
1
+ /**
2
+ * The viewer, wired to the comms API: fetches the SERVER's render of a draft or of a comeback step
3
+ * and who it is from, and shows it in the one-page viewer. Reading only; nothing here approves,
4
+ * sends or writes.
5
+ *
6
+ * `itemId` is what a URL carries: a draft id, or `step.<programKey>.<index>` for a comeback step.
7
+ * Hosts that can route mount this at a page of their own; hosts that cannot get the same viewer
8
+ * from <PreviewAsInbox> opening it in place.
9
+ */
10
+ import { createContext, useContext, useEffect, useState, type ReactElement, type ReactNode } from 'react';
11
+ import { Button } from '@startsimpli/ui';
12
+
13
+ import type { CommsApi } from '../api/comms';
14
+ import { useDraftPreview, useSender, useStepPreview } from '../hooks/index';
15
+ import { EmailPreview } from './EmailPreview';
16
+ import { ErrorNotice, Note } from './_shared';
17
+
18
+ export type PreviewSource =
19
+ | { kind: 'draft'; id: string }
20
+ | { kind: 'step'; programKey: string; index: number };
21
+
22
+ export function previewItemId(source: PreviewSource): string {
23
+ return source.kind === 'draft' ? source.id : `step.${source.programKey}.${source.index}`;
24
+ }
25
+
26
+ export function parsePreviewItemId(itemId: string): PreviewSource {
27
+ const m = itemId.match(/^step\.([^.]+)\.(\d+)$/);
28
+ return m ? { kind: 'step', programKey: m[1], index: Number(m[2]) } : { kind: 'draft', id: itemId };
29
+ }
30
+
31
+ export interface EmailPreviewPageProps {
32
+ api: CommsApi;
33
+ itemId: string;
34
+ /** Shown as the sender when the foundry has none configured: the foundry's own name. */
35
+ fallbackSenderName: string;
36
+ backHref?: string;
37
+ backLabel?: string;
38
+ onBack?: () => void;
39
+ }
40
+
41
+ export function EmailPreviewPage({
42
+ api,
43
+ itemId,
44
+ fallbackSenderName,
45
+ backHref = '#',
46
+ backLabel = 'Back to Customer emails',
47
+ onBack,
48
+ }: EmailPreviewPageProps): ReactElement {
49
+ const source = parsePreviewItemId(itemId);
50
+ const draft = useDraftPreview(api, source.kind === 'draft' ? source.id : '', source.kind === 'draft');
51
+ const step = useStepPreview(
52
+ api,
53
+ source.kind === 'step' ? source.programKey : '',
54
+ source.kind === 'step' ? source.index : 0,
55
+ source.kind === 'step',
56
+ );
57
+ const sender = useSender(api, true, fallbackSenderName);
58
+ const query = source.kind === 'draft' ? draft : step;
59
+
60
+ if (query.data) {
61
+ return <EmailPreview email={query.data} sender={sender} backHref={backHref} backLabel={backLabel} onBack={onBack} />;
62
+ }
63
+ return (
64
+ <div data-email-viewer className="fixed inset-0 z-50 overflow-y-auto bg-neutral-100 px-4 py-3 dark:bg-neutral-900">
65
+ <a
66
+ href={backHref}
67
+ className="text-sm text-neutral-600 hover:underline dark:text-neutral-400"
68
+ onClick={(e) => {
69
+ if (!onBack) return;
70
+ e.preventDefault();
71
+ onBack();
72
+ }}
73
+ >
74
+ {`← ${backLabel}`}
75
+ </a>
76
+ <div className="mx-auto max-w-4xl py-8">
77
+ {query.error ? <ErrorNotice error={query.error} /> : <Note>Loading…</Note>}
78
+ </div>
79
+ </div>
80
+ );
81
+ }
82
+
83
+ // ---- launch points ------------------------------------------------------------------------------
84
+
85
+ interface ViewerLinks {
86
+ /** Where the viewer lives for an item id, when the host routes to it. */
87
+ href?: (itemId: string) => string;
88
+ /** Follow that href in the host (client navigation) instead of a full page load. */
89
+ open?: (href: string) => void;
90
+ /** Where Back goes in the host. */
91
+ foundryName: string;
92
+ }
93
+
94
+ const ViewerLinksContext = createContext<ViewerLinks>({ foundryName: '' });
95
+
96
+ export function ViewerLinksProvider({ value, children }: { value: ViewerLinks; children: ReactNode }): ReactElement {
97
+ return <ViewerLinksContext.Provider value={value}>{children}</ViewerLinksContext.Provider>;
98
+ }
99
+
100
+ /**
101
+ * "Preview as inbox" / "Preview": a link to the host's viewer page when it has one, otherwise a
102
+ * button that opens the same viewer over the page and closes with Back.
103
+ */
104
+ export function PreviewAsInbox({
105
+ api,
106
+ source,
107
+ label,
108
+ autoOpen = false,
109
+ }: {
110
+ api: CommsApi;
111
+ source: PreviewSource;
112
+ label: string;
113
+ /** Open the viewer by itself (a draft just loaded from a file). */
114
+ autoOpen?: boolean;
115
+ }): ReactElement {
116
+ const { href, open, foundryName } = useContext(ViewerLinksContext);
117
+ const [shown, setShown] = useState(false);
118
+ const itemId = previewItemId(source);
119
+
120
+ useEffect(() => {
121
+ if (!autoOpen) return;
122
+ if (!href) return setShown(true);
123
+ const to = href(itemId);
124
+ if (open) open(to);
125
+ else window.location.assign(to);
126
+ // Only when asked to open, not when the host's callbacks change identity.
127
+ // eslint-disable-next-line react-hooks/exhaustive-deps
128
+ }, [autoOpen]);
129
+
130
+ if (href) {
131
+ const to = href(itemId);
132
+ return (
133
+ <Button asChild size="sm" variant="outline">
134
+ <a
135
+ href={to}
136
+ onClick={(e) => {
137
+ if (!open || e.metaKey || e.ctrlKey || e.shiftKey || e.button !== 0) return;
138
+ e.preventDefault();
139
+ open(to);
140
+ }}
141
+ >
142
+ {label}
143
+ </a>
144
+ </Button>
145
+ );
146
+ }
147
+ return (
148
+ <>
149
+ <Button type="button" size="sm" variant="outline" onClick={() => setShown(true)}>{label}</Button>
150
+ {shown ? (
151
+ <EmailPreviewPage
152
+ api={api}
153
+ itemId={itemId}
154
+ fallbackSenderName={foundryName || api.slug}
155
+ backLabel="Back"
156
+ onBack={() => setShown(false)}
157
+ />
158
+ ) : null}
159
+ </>
160
+ );
161
+ }
@@ -21,7 +21,6 @@ import {
21
21
  usePrograms,
22
22
  useSendTest,
23
23
  useStepGeneration,
24
- useStepPreview,
25
24
  useUpdateProgram,
26
25
  } from '../hooks/index';
27
26
  import {
@@ -30,7 +29,7 @@ import {
30
29
  type SequenceProgram,
31
30
  type SequenceStep,
32
31
  } from '../types/index';
33
- import { EmailPreview } from './EmailPreview';
32
+ import { PreviewAsInbox } from './EmailPreviewPage';
34
33
  import { ErrorNotice, Note, humanize, useFieldId } from './_shared';
35
34
 
36
35
  export interface SequenceSettingsProps {
@@ -188,9 +187,7 @@ function StepRow({
188
187
  const step = program.config.steps[index];
189
188
  const status = stepStatus(step);
190
189
  const [editing, setEditing] = useState(false);
191
- const [previewing, setPreviewing] = useState(false);
192
190
  const [watching, setWatching] = useState(false);
193
- const preview = useStepPreview(api, program.key, index, previewing && status !== 'empty');
194
191
  const sendTest = useSendTest(api);
195
192
  const generate = useGenerateStep(api);
196
193
  const generation = useStepGeneration(api, program.key, index, watching, pollIntervalMs);
@@ -211,7 +208,7 @@ function StepRow({
211
208
  <Button type="button" size="sm" variant="outline" onClick={() => setEditing((v) => !v)}>Edit</Button>
212
209
  {status !== 'empty' ? (
213
210
  <>
214
- <Button type="button" size="sm" variant="outline" onClick={() => setPreviewing((v) => !v)}>Preview</Button>
211
+ <PreviewAsInbox api={api} source={{ kind: 'step', programKey: program.key, index }} label="Preview" />
215
212
  <Button
216
213
  type="button"
217
214
  size="sm"
@@ -251,9 +248,8 @@ function StepRow({
251
248
  {sendTest.data && !sendTest.data.sent ? (
252
249
  <ErrorNotice error={new Error(`Test not sent: ${humanize(sendTest.data.reason || 'refused')}`)} />
253
250
  ) : null}
254
- <ErrorNotice error={sendTest.error ?? generate.error ?? approve.error ?? preview.error ?? (failed ? new Error(failed) : null)} />
251
+ <ErrorNotice error={sendTest.error ?? generate.error ?? approve.error ?? (failed ? new Error(failed) : null)} />
255
252
  {editing ? <StepEditor api={api} program={program} index={index} onDone={() => setEditing(false)} /> : null}
256
- {previewing && preview.data ? <EmailPreview email={preview.data} /> : null}
257
253
  </li>
258
254
  );
259
255
  }
@@ -2,6 +2,7 @@ export * from './pages/CustomerEmailsPage';
2
2
  export * from './ProgramToggles';
3
3
  export * from './SequenceSettings';
4
4
  export * from './EmailPreview';
5
+ export * from './EmailPreviewPage';
5
6
  export * from './ApprovalModeSetting';
6
7
  export * from './VoiceSettings';
7
8
  export * from './DefaultTimeZoneSetting';
@@ -21,6 +21,7 @@ import type { CommsApi } from '../../api/comms';
21
21
  import { DEFAULT_POLL_MS, useCommsSettings, usePrograms } from '../../hooks/index';
22
22
  import { CommsApiError } from '../../types/index';
23
23
  import { AnnouncementComposer } from '../AnnouncementComposer';
24
+ import { ViewerLinksProvider } from '../EmailPreviewPage';
24
25
  import { ApprovalModeSetting } from '../ApprovalModeSetting';
25
26
  import { DefaultTimeZoneSetting } from '../DefaultTimeZoneSetting';
26
27
  import { ProductUpdates } from '../ProductUpdates';
@@ -39,6 +40,15 @@ export interface CustomerEmailsPageProps {
39
40
  sendLogPageSize?: number;
40
41
  /** How often background work (AI writing) is re-checked. Default 2s. */
41
42
  pollIntervalMs?: number;
43
+ /** The foundry's own name: the sender shown in the viewer when none is configured. Default the slug. */
44
+ foundryName?: string;
45
+ /**
46
+ * Where the email viewer lives for an item id (a draft id, or `step.<program>.<index>`), when the
47
+ * host routes to it. Without it, previews open the same viewer over this page.
48
+ */
49
+ viewerHref?: (itemId: string) => string;
50
+ /** Follow a viewer href in the host (client navigation) rather than a full page load. */
51
+ onOpenViewer?: (href: string) => void;
42
52
  }
43
53
 
44
54
  function Fold({ value, title, children }: { value: string; title: string; children: ReactNode }) {
@@ -55,6 +65,9 @@ export function CustomerEmailsPage({
55
65
  foundrySlug,
56
66
  sendLogPageSize = 25,
57
67
  pollIntervalMs = DEFAULT_POLL_MS,
68
+ foundryName,
69
+ viewerHref,
70
+ onOpenViewer,
58
71
  }: CustomerEmailsPageProps): ReactElement {
59
72
  const settings = useCommsSettings(api);
60
73
  const programs = usePrograms(api);
@@ -114,7 +127,9 @@ export function CustomerEmailsPage({
114
127
  return (
115
128
  <section className="mx-auto w-full max-w-4xl space-y-4">
116
129
  <h2 className="text-2xl font-semibold tracking-tight">Customer emails</h2>
117
- {body}
130
+ <ViewerLinksProvider value={{ href: viewerHref, open: onOpenViewer, foundryName: foundryName || foundrySlug }}>
131
+ {body}
132
+ </ViewerLinksProvider>
118
133
  </section>
119
134
  );
120
135
  }
@@ -75,6 +75,33 @@ export function useCommsSettings(api: CommsApi): UseQueryResult<CommsSettings> {
75
75
  return useQuery({ queryKey: commsKeys.settings(api.slug), queryFn: () => api.getSettings() });
76
76
  }
77
77
 
78
+ export interface Sender {
79
+ /** What an inbox lists as the sender. Never empty. */
80
+ name: string;
81
+ address?: string;
82
+ }
83
+
84
+ /** `Name <address>`, a bare address, or a bare name -> its parts (either may be empty). */
85
+ export function parseFromLine(from?: string | null): { name: string; address: string } {
86
+ const raw = (from ?? '').trim();
87
+ const m = raw.match(/^(.*?)\s*<([^>]+)>$/);
88
+ if (m) return { name: m[1].replace(/^"|"$/g, '').trim(), address: m[2] };
89
+ return raw.includes('@') ? { name: '', address: raw } : { name: raw, address: '' };
90
+ }
91
+
92
+ /**
93
+ * Who the email is from, as recipients see it: the configured sender name, else the name in the
94
+ * From line, else `fallbackName` (the foundry's own name). Fetched only while `enabled`.
95
+ */
96
+ export function useSender(api: CommsApi, enabled: boolean, fallbackName: string): Sender {
97
+ const q = useQuery({ queryKey: commsKeys.settings(api.slug), queryFn: () => api.getSettings(), enabled });
98
+ const from = parseFromLine(q.data?.from_address);
99
+ return {
100
+ name: q.data?.sender_name?.trim() || from.name || fallbackName,
101
+ ...(from.address ? { address: from.address } : {}),
102
+ };
103
+ }
104
+
78
105
  function useSettingsWrite<V>(api: CommsApi, fn: (v: V) => Promise<CommsSettings>) {
79
106
  const qc = useQueryClient();
80
107
  return useMutation<CommsSettings, Error, V>({