app.tsx
12.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
import { useEffect, useMemo, useRef, useState, type CSSProperties, type ReactNode } from 'react';
import { parseSopPreviewAllowedOrigins } from '@single-pages/config';
import type {
MaterialItem,
SopMaterialPreviewModel,
SopMaterialPreviewReadyMessage,
} from '@single-pages/contracts';
import { fetchSopMaterialPreview, SopMaterialPreviewRequestError } from './api';
const FALLBACK_TITLE = 'SOP 素材展示/预览';
const INIT_MESSAGE_TYPE = 'SOP_MATERIAL_PREVIEW_INIT';
const READY_MESSAGE_TYPE = 'SOP_MATERIAL_PREVIEW_READY';
type PageStatus = 'idle' | 'loading' | 'ready' | 'empty';
type SlotStatus = 'loading' | 'success' | 'error' | 'unsupported';
interface PreviewState {
pageStatus: PageStatus;
model: SopMaterialPreviewModel | null;
}
interface MaterialSlotProps {
item: MaterialItem;
status: SlotStatus;
onStatusChange: (status: Exclude<SlotStatus, 'unsupported'>) => void;
className?: string;
style?: CSSProperties;
}
function isRecord(value: unknown): value is Record<string, unknown> {
return Boolean(value) && typeof value === 'object' && !Array.isArray(value);
}
function normalizeText(value: unknown, fallback = ''): string {
if (typeof value === 'string') {
return value.trim();
}
if (typeof value === 'number' && Number.isFinite(value)) {
return String(value);
}
return fallback;
}
function isValidColor(value: string): boolean {
return Boolean(
/^#(?:[0-9a-fA-F]{3,4}|[0-9a-fA-F]{6}|[0-9a-fA-F]{8})$/.test(value) ||
/^rgba?\(\s*\d+\s*,\s*\d+\s*,\s*\d+(?:\s*,\s*(?:0|1|0?\.\d+))?\s*\)$/i.test(value) ||
/^hsla?\(\s*\d+\s*,\s*\d+%?\s*,\s*\d+%?(?:\s*,\s*(?:0|1|0?\.\d+))?\s*\)$/i.test(value),
);
}
function normalizeBgColor(value: unknown): string {
const text = normalizeText(value);
if (!text) {
return '#ffffff';
}
return isValidColor(text) ? text : '#ffffff';
}
function normalizeIntervalPx(value: unknown): number {
const parsed = typeof value === 'number' ? value : Number.parseFloat(normalizeText(value));
if (!Number.isFinite(parsed) || parsed < 0) {
return 0;
}
return Math.floor(parsed);
}
function normalizeMaterials(value: unknown): MaterialItem[] | null {
if (!Array.isArray(value)) {
return null;
}
const items = value.map((item) => {
if (!isRecord(item)) {
return null;
}
if (typeof item.type !== 'string' || typeof item.url !== 'string') {
return null;
}
return {
type: item.type.trim(),
url: item.url.trim(),
};
});
return items.includes(null) ? null : (items as MaterialItem[]);
}
function isSupportedType(type: string): boolean {
return type === 'image' || type === 'video';
}
function isRenderableUrl(url: string): boolean {
if (url.trim().length === 0) {
return false;
}
try {
const resolved = new URL(url, window.location.href);
return resolved.protocol === 'http:' || resolved.protocol === 'https:';
} catch {
return false;
}
}
function normalizePreviewModel(value: unknown): SopMaterialPreviewModel | null {
if (!isRecord(value)) {
return null;
}
const content = normalizeText(value.content, FALLBACK_TITLE) || FALLBACK_TITLE;
const materials = normalizeMaterials(value.materials);
if (!materials) {
return null;
}
return {
id: typeof value.id === 'number' && Number.isFinite(value.id) ? value.id : undefined,
content,
bgColor: normalizeBgColor(value.bgColor),
intervalPx: normalizeIntervalPx(value.intervalPx),
materials,
};
}
function normalizeMessagePayload(value: unknown): SopMaterialPreviewModel | null {
if (!isRecord(value)) {
return null;
}
if (typeof value.type !== 'string' || value.type !== INIT_MESSAGE_TYPE) {
return null;
}
return normalizePreviewModel(value.payload);
}
function getQueryActionParams(): { actionId: string; queryParams: URLSearchParams } | null {
const searchParams = new URLSearchParams(window.location.search);
const actionId = searchParams.get('actionId');
if (!actionId || actionId.trim().length === 0) {
return null;
}
const normalizedActionId = actionId.trim();
searchParams.set('actionId', normalizedActionId);
return {
actionId: normalizedActionId,
queryParams: searchParams,
};
}
function getAllowedOrigins(): string[] | '*' {
return parseSopPreviewAllowedOrigins(
(import.meta as ImportMeta & { env: { VITE_SOP_PREVIEW_ALLOWED_ORIGINS?: string } }).env
.VITE_SOP_PREVIEW_ALLOWED_ORIGINS,
);
}
function isAllowedOrigin(origin: string, allowedOrigins: string[] | '*'): boolean {
if (allowedOrigins === '*') {
return true;
}
return allowedOrigins.includes(origin);
}
function StatusBlock({
title,
description,
className = '',
}: {
title: string;
description: string;
className?: string;
}) {
return (
<section className={`rounded-2xl border border-slate-200 bg-white px-6 py-5 shadow-sm ${className}`}>
<p className="text-base font-semibold text-slate-900">{title}</p>
<p className="mt-1 text-sm leading-6 text-slate-600">{description}</p>
</section>
);
}
function getMaterialSlotClassName(): string {
const base = 'overflow-hidden bg-white shadow-sm';
return `${base} rounded-none`;
}
function getMaterialSlotStyle(index: number, intervalPx: number): CSSProperties {
return index === 0 ? {} : { marginTop: `${intervalPx}px` };
}
function MaterialSlot({
item,
status,
onStatusChange,
className = '',
style,
}: MaterialSlotProps) {
if (status === 'unsupported' || status === 'error') {
return <section aria-hidden="true" className={className} style={style} />;
}
if (!isSupportedType(item.type) || !isRenderableUrl(item.url)) {
return <section aria-hidden="true" className={className} style={style} />;
}
if (item.type === 'image') {
return (
<section className={className} style={style}>
<img
alt=""
className="block h-auto w-full"
src={item.url}
onLoad={() => onStatusChange('success')}
onError={() => onStatusChange('error')}
/>
</section>
);
}
return (
<section className={className} style={style}>
<video
className="block h-auto w-full"
controls
playsInline
preload="metadata"
src={item.url}
onLoadedData={() => onStatusChange('success')}
onError={() => onStatusChange('error')}
/>
</section>
);
}
function normalizePreviewStateFromResponse(raw: unknown): SopMaterialPreviewModel | null {
if (!isRecord(raw)) {
return null;
}
const id = typeof raw.id === 'number' && Number.isFinite(raw.id) ? raw.id : undefined;
const content = normalizeText(raw.content, FALLBACK_TITLE) || FALLBACK_TITLE;
const materials = normalizeMaterials(raw.materials);
if (!materials) {
return null;
}
return {
id,
content,
bgColor: normalizeBgColor(raw.bgColor),
intervalPx: normalizeIntervalPx(raw.intervalPx),
materials,
};
}
function renderBlankPage() {
return <div aria-hidden="true" className="min-h-screen w-full" />;
}
export function SopMaterialPreviewApp() {
const [state, setState] = useState<PreviewState>({
pageStatus: 'idle',
model: null,
});
const [slotStatuses, setSlotStatuses] = useState<Record<number, SlotStatus>>({});
const requestSeqRef = useRef(0);
const allowedOrigins = useMemo(() => getAllowedOrigins(), []);
useEffect(() => {
const actionParams = getQueryActionParams();
if (!actionParams) {
return;
}
const requestSeq = ++requestSeqRef.current;
setState({
pageStatus: 'loading',
model: null,
});
fetchSopMaterialPreview(actionParams.actionId, actionParams.queryParams)
.then((response) => {
if (requestSeq !== requestSeqRef.current) {
return;
}
const model = normalizePreviewStateFromResponse(response);
if (!model) {
setState({
pageStatus: 'empty',
model: null,
});
return;
}
setState({
pageStatus: 'ready',
model,
});
})
.catch((error) => {
if (requestSeq !== requestSeqRef.current) {
return;
}
if (error instanceof SopMaterialPreviewRequestError) {
setState({
pageStatus: 'empty',
model: null,
});
return;
}
setState({
pageStatus: 'empty',
model: null,
});
});
}, []);
useEffect(() => {
const handleMessage = (event: MessageEvent<unknown>) => {
if (!isAllowedOrigin(event.origin, allowedOrigins)) {
return;
}
const nextModel = normalizeMessagePayload(event.data);
if (!nextModel) {
return;
}
requestSeqRef.current += 1;
setState({
pageStatus: 'ready',
model: nextModel,
});
};
window.addEventListener('message', handleMessage);
return () => {
window.removeEventListener('message', handleMessage);
};
}, [allowedOrigins]);
useEffect(() => {
if (window.parent !== window) {
const readyMessage: SopMaterialPreviewReadyMessage = {
type: READY_MESSAGE_TYPE,
};
window.parent.postMessage(readyMessage, '*');
}
}, []);
useEffect(() => {
if (!state.model) {
setSlotStatuses({});
return;
}
setSlotStatuses(
Object.fromEntries(
state.model.materials.map((item, index) => [
index,
isSupportedType(item.type) && isRenderableUrl(item.url) ? 'loading' : 'unsupported',
]),
) as Record<number, SlotStatus>,
);
}, [state.model]);
useEffect(() => {
if (!state.model) {
document.title = FALLBACK_TITLE;
return;
}
document.title = state.model.content || FALLBACK_TITLE;
}, [state.model]);
const backgroundColor = state.model?.bgColor || '#ffffff';
useEffect(() => {
const previousHtmlBackground = document.documentElement.style.backgroundColor;
const previousBodyBackground = document.body.style.backgroundColor;
document.documentElement.style.backgroundColor = backgroundColor;
document.body.style.backgroundColor = backgroundColor;
return () => {
document.documentElement.style.backgroundColor = previousHtmlBackground;
document.body.style.backgroundColor = previousBodyBackground;
};
}, [backgroundColor]);
useEffect(() => {
if (!state.model) {
return;
}
if (state.model.materials.length === 0) {
setState((current) =>
current.pageStatus === 'empty' && current.model === state.model
? current
: {
pageStatus: 'empty',
model: state.model,
},
);
return;
}
const statuses = state.model.materials.map((_, index) => slotStatuses[index] ?? 'loading');
const hasSuccess = statuses.includes('success');
const hasLoading = statuses.includes('loading');
const hasRenderableCandidate = statuses.some((status) => status !== 'unsupported');
if (!hasSuccess && !hasLoading && hasRenderableCandidate) {
setState((current) =>
current.pageStatus === 'empty' && current.model === state.model
? current
: {
pageStatus: 'empty',
model: state.model,
},
);
}
}, [slotStatuses, state.model]);
const model = state.model;
let body: ReactNode;
if (state.pageStatus === 'empty') {
body = renderBlankPage();
} else if (state.pageStatus === 'loading') {
body = <StatusBlock title="正在加载素材" description="正在根据 ID 获取素材配置。" />;
} else if (state.pageStatus === 'idle' && !state.model) {
body = renderBlankPage();
} else if (model) {
const previewModel = model;
const intervalPx = previewModel.intervalPx;
body = (
<section className="min-h-full w-full">
{previewModel.materials.map((item, index) => (
<MaterialSlot
key={`${index}-${item.type}-${item.url}`}
item={item}
status={slotStatuses[index] ?? 'loading'}
className={getMaterialSlotClassName()}
onStatusChange={(nextStatus) => {
setSlotStatuses((current) => ({ ...current, [index]: nextStatus }));
}}
style={getMaterialSlotStyle(index, intervalPx)}
/>
))}
</section>
);
} else {
body = renderBlankPage();
}
return (
<main className="min-h-screen w-full text-slate-900" style={{ backgroundColor }}>
<div className="flex min-h-screen w-full flex-col">
{body}
</div>
</main>
);
}