@startsimpli/integrations 0.2.50 → 0.2.52
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 +3 -3
- package/src/__tests__/voice-notes-page.test.tsx +103 -0
- package/src/__tests__/voice.test.ts +211 -0
- package/src/comms/__tests__/announcement-composer.test.tsx +56 -0
- package/src/comms/__tests__/customer-emails-page.test.tsx +48 -4
- package/src/comms/__tests__/email-viewer.test.tsx +233 -0
- package/src/comms/components/AnnouncementComposer.tsx +51 -1
- package/src/comms/components/DraftReview.tsx +10 -9
- package/src/comms/components/EmailPreview.tsx +155 -12
- package/src/comms/components/EmailPreviewPage.tsx +161 -0
- package/src/comms/components/SequenceSettings.tsx +3 -7
- package/src/comms/components/index.ts +1 -0
- package/src/comms/components/pages/CustomerEmailsPage.tsx +16 -1
- package/src/comms/hooks/index.ts +27 -0
- package/src/components/index.ts +3 -0
- package/src/components/pages/VoiceNotesPage.tsx +227 -0
- package/src/corpus/index.ts +28 -0
- package/src/corpus/llm.ts +91 -0
- package/src/corpus/voice.ts +354 -0
|
@@ -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, '&').replace(/</g, '<').replace(/>/g, '>');
|
|
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' : ''}`);
|
|
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 {
|
|
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
|
-
<
|
|
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
|
|
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
|
-
*
|
|
3
|
-
*
|
|
4
|
-
*
|
|
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
|
|
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
|
-
|
|
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="
|
|
17
|
-
<div className="
|
|
18
|
-
<
|
|
19
|
-
|
|
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
|
}
|