import React, { type ButtonHTMLAttributes, type FormEvent, type ReactNode, type RefObject, type SVGProps, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react'; import ReactDOM from 'react-dom/client'; import { createPortal } from 'react-dom'; import { createRoot } from 'react-dom/client'; import type { ShikiTransformer } from 'shiki'; import { Check, Copy, Download, FolderMinus, FolderPlus, HalfMoon, MailOut, Minus, NavArrowDown, NavArrowLeft, NavArrowRight, NavArrowUp, Page, Plus, Prohibition, Refresh, Send, SmartphoneDevice, WarningTriangle, Xmark } from 'iconoir-react'; import beautify from 'js-beautify'; import { scan, type CanispamClassification, type CanispamClassifierResult, type CanispamFinding, type CanispamScoreBreakdown } from 'canispam'; import { toEml } from '../eml/index.js'; import type { Props } from 'tippy.js'; import { createHighlighterCoreSync } from 'shiki/core'; import { createJavaScriptRegexEngine } from 'shiki/engine/javascript'; import shikiHtmlLang from 'shiki/langs/html.mjs'; import shikiJsLang from 'shiki/langs/javascript.mjs'; import shikiTsxLang from 'shiki/langs/tsx.mjs'; import shikiGithubDarkHighContrastTheme from 'shiki/themes/github-dark-high-contrast.mjs'; import shikiGithubLightTheme from 'shiki/themes/github-light.mjs'; import tippy from 'tippy.js'; import { clsx, type ClassValue } from 'clsx'; import { twMerge } from 'tailwind-merge'; import { create } from 'zustand'; // src/types/lab.ts interface LabState { colorScheme: boolean; invertColors: boolean; preset: string; sendEmail: string; sendError: string | null; sendState: 'idle' | 'sending' | 'sent' | 'error'; } interface CardState { id: string; templateId: string; } // src/types/templates.ts interface PreviewImportContent { html: string; plain: string; source: string; sourceFile: string; sourcePath?: string; templateName?: string; } type TemplateTab = 'preview' | 'jsx' | 'html' | 'plain'; interface TemplateData { fileExtension: string; fileName: string; html: string; id: string; path: string; plain: string; source: string; sourceFile: string; sourcePath: string; templateName: string; } interface FileTreeNode { children: FileTreeNode[]; name: string; path: string; template?: TemplateData; type: 'folder' | 'file'; } interface PreviewPreset { height?: number; label: string; name: string; width: number | null; } // src/helpers/file.ts function normalizePath(path: string) { return path.replaceAll('\\', '/'); } function stripExtension(path: string) { return path.replace(/\.[^/.]+$/, ''); } function fileName(path: string) { return normalizePath(path).split('/').at(-1) || path; } function sortByName(items: T[]) { return [...items].sort((a, b) => a.name.localeCompare(b.name, undefined, { numeric: true })); } // src/helpers/zoom.ts const minZoom = 25; const maxZoom = 130; const zoomStep = 10; function nextZoom(value: number, direction: number) { if (direction > 0) { const next = Math.ceil((value + 1) / zoomStep) * zoomStep; return Math.min(maxZoom, Math.max(minZoom, next)); } const next = Math.floor((value - 1) / zoomStep) * zoomStep; return Math.max(minZoom, Math.min(maxZoom, next)); } function isZoomKey(event: KeyboardEvent | React.KeyboardEvent) { return event.code === 'KeyZ' || event.key.toLowerCase() === 'z'; } // src/helpers/consts.ts // Warning: This API key was provided by plunk strictly for sending test emails from the jsx.email user interface, // do not use for commercial purposes, do not send any personal details or sensitive data, // you are not permitted to copy paste the API key, or to use it outside of the UI provided by jsx.email. const plunkApiBearerTokenProvidedOnlyForJsxEmailUiDoNotUseElsewhere = 'sk_dbed12137c418c4b2d278d84a634394b2209931a4a239b6f'; // src/helpers/presets.ts const previewPresets: PreviewPreset[] = [ { label: '100%', name: 'Full Width', width: null }, { label: '430px', name: 'iPhone 15 Pro Max', width: 430 }, { label: '393px', name: 'iPhone 15 Pro', width: 393 }, { label: '375px', name: 'iPhone 13 mini', width: 375 }, { label: '360px', name: 'Gmail Mobile', width: 360 }, { height: 1180, label: '820x1180', name: 'iPad Air 4', width: 820 }, { height: 1112, label: '834x1112', name: 'iPad Pro 10.5"', width: 834 }, { height: 1024, label: '768x1024', name: 'iPad Mini 4', width: 768 } ]; // src/helpers/gmail-color.ts interface RgbColor { a?: number; b: number; g: number; r: number; } interface HslColor { a?: number; h: number; l: number; s: number; } const roleAliases: Record = { background: 'background-color', bg: 'background-color', border: 'border-color', 'border-bottom-color': 'border-color', 'border-left-color': 'border-color', 'border-right-color': 'border-color', 'border-top-color': 'border-color', color: 'text', foreground: 'text', 'text-color': 'text' }; /* * Background-image handling is intentionally absent from this helper. * * The original canvas preview prototype accepted roles like `background-image`, * `gradient`, `image`, and `img`, and preserved background-image colors instead * of applying the Gmail iOS foreground transform. That behavior was removed when * this logic moved from the standalone prototype into the app helper because the * current `applyGmailInversion` path only transforms concrete CSS color * declarations such as `color`, `background-color`, and `border-color`. * * Do not re-add `background-image` to `colorProperties` in `color-inversion.ts` * unless there is a real parser for full CSS image values. `parseCssColor` only * accepts named colors, hex, rgb, and rgba values; it does not parse * `url(...)`, `linear-gradient(...)`, `radial-gradient(...)`, or color stops * inside those functions. * * If a future caller extracts individual color tokens from a background image * value and needs to preserve them, reintroduce support here, where the color * approximation lives: * * 1. Add role aliases: * * 'background-image': 'background-image', * gradient: 'background-image', * * 2. Normalize the role once in `approximateGmailIosCssColor`: * * const normalizedRole = normalizeRole(role); * * 3. Preserve extracted background-image color tokens before the foreground / * background transform: * * if (normalizedRole === 'background-image') { * return rgbToCssColor(clampRgb(rgb)); * } * * 4. Use `normalizedRole` for the existing background-color / border-color * branch, and add tests showing that full gradient strings remain unchanged * while separately extracted color tokens are preserved. */ const namedColors: Record = { black: '#000000', blue: '#0000ff', green: '#008000', red: '#ff0000', transparent: '#00000000', white: '#ffffff' }; function approximateGmailIosCssColor(input: string, role: string) { const rgb = parseCssColor(input); if (!rgb) return input; const output = transformDarkModeLightness( rgb, normalizeRole(role) === 'background-color' || normalizeRole(role) === 'border-color' ? 'background' : 'foreground' ); return rgbToCssColor(output); } function transformDarkModeLightness(rgb: RgbColor, role: 'background' | 'foreground') { const hsl = rgbToHsl(rgb); const isNeutral = hsl.s < 0.12; if (role === 'background') { if (hsl.l >= 0.5) { hsl.l = 0.875 - hsl.l * 0.75; } } else if (isNeutral && hsl.l < 0.5) { hsl.l = 0.95 - hsl.l * 0.75; } else if (!isNeutral && hsl.l <= 0.52) { hsl.l = 0.92 - hsl.l * 0.56; } else if (isNeutral && hsl.l < 0.7) { hsl.l += 0.1; } hsl.s -= hsl.s * 0.2; return hslToRgb(hsl); } function normalizeRole(role: string) { const key = String(role || '') .toLowerCase() .trim(); return roleAliases[key] || key; } function parseCssColor(input: string) { const value = input.trim().toLowerCase(); if (namedColors[value]) return parseCssColor(namedColors[value]); const hex = value.match(/^#([0-9a-f]{3,8})$/i); if (hex) return parseHexColor(hex[1]); const rgb = value.match(/^rgba?\((.+)\)$/i); if (rgb) return parseRgbFunction(rgb[1]); return null; } function parseHexColor(raw: string) { let hex = raw; if (hex.length === 3 || hex.length === 4) { hex = hex .split('') .map((char) => char + char) .join(''); } if (hex.length !== 6 && hex.length !== 8) return null; return { a: hex.length === 8 ? parseInt(hex.slice(6, 8), 16) / 255 : 1, b: parseInt(hex.slice(4, 6), 16), g: parseInt(hex.slice(2, 4), 16), r: parseInt(hex.slice(0, 2), 16) }; } function parseRgbFunction(raw: string) { const parts = raw .replace(/\s*\/\s*/g, ',') .split(',') .map((part) => part.trim()) .filter(Boolean); if (parts.length < 3) return null; const color = { a: parts[3] == null ? 1 : parseAlpha(parts[3]), b: parseCssChannel(parts[2]), g: parseCssChannel(parts[1]), r: parseCssChannel(parts[0]) }; if (Object.values(color).some((value) => Number.isNaN(value))) return null; return clampRgb(color); } function parseCssChannel(value: string) { if (value.endsWith('%')) return (parseFloat(value) / 100) * 255; return parseFloat(value); } function parseAlpha(value: string) { if (value.endsWith('%')) return clamp(parseFloat(value) / 100, 0, 1); return clamp(parseFloat(value), 0, 1); } function rgbToCssColor(rgb: RgbColor) { const color = clampRgb(rgb); if (color.a < 1) { return `rgba(${Math.round(color.r)}, ${Math.round(color.g)}, ${Math.round(color.b)}, ${formatAlpha(color.a)})`; } return `#${toHex(color.r)}${toHex(color.g)}${toHex(color.b)}`; } function formatAlpha(value: number) { return String(Math.round(clamp(value, 0, 1) * 1000) / 1000); } function toHex(value: number) { return Math.round(clamp(value, 0, 255)) .toString(16) .padStart(2, '0'); } function clampRgb(rgb: RgbColor): Required { return { a: rgb.a == null ? 1 : clamp(Number(rgb.a), 0, 1), b: clamp(Number(rgb.b), 0, 255), g: clamp(Number(rgb.g), 0, 255), r: clamp(Number(rgb.r), 0, 255) }; } function clamp(value: number, min: number, max: number) { if (Number.isNaN(value)) return min; return Math.min(max, Math.max(min, value)); } function rgbToHsl(rgb: RgbColor): HslColor { const color = clampRgb(rgb); const r = color.r / 255; const g = color.g / 255; const b = color.b / 255; const max = Math.max(r, g, b); const min = Math.min(r, g, b); const delta = max - min; let h = 0; let s = 0; const l = (max + min) / 2; if (delta !== 0) { s = delta / (1 - Math.abs(2 * l - 1)); if (max === r) h = 60 * (((g - b) / delta) % 6); else if (max === g) h = 60 * ((b - r) / delta + 2); else h = 60 * ((r - g) / delta + 4); } if (h < 0) h += 360; return { a: color.a, h, l, s }; } function hslToRgb(hsl: HslColor) { const h = ((hsl.h % 360) + 360) % 360; const s = clamp(hsl.s, 0, 1); const l = clamp(hsl.l, 0, 1); const c = (1 - Math.abs(2 * l - 1)) * s; const x = c * (1 - Math.abs(((h / 60) % 2) - 1)); const m = l - c / 2; let r = 0; let g = 0; let b = 0; if (h < 60) [r, g, b] = [c, x, 0]; else if (h < 120) [r, g, b] = [x, c, 0]; else if (h < 180) [r, g, b] = [0, c, x]; else if (h < 240) [r, g, b] = [0, x, c]; else if (h < 300) [r, g, b] = [x, 0, c]; else [r, g, b] = [c, 0, x]; return clampRgb({ a: hsl.a == null ? 1 : hsl.a, b: (b + m) * 255, g: (g + m) * 255, r: (r + m) * 255 }); } // src/helpers/cn.ts function cn(...inputs: ClassValue[]) { return twMerge(clsx(inputs)); } // src/helpers/file-tree.ts function buildFileTree(templates: TemplateData[]) { const root: FileTreeNode[] = []; for (const template of templates) { const parts = template.path.split('/'); let branch = root; parts.forEach((part, index) => { const isFile = index === parts.length - 1; const path = parts.slice(0, index + 1).join('/'); let node = branch.find((item) => item.path === path); if (!node) { node = { children: [], name: isFile ? template.templateName : part, path, type: isFile ? 'file' : 'folder' }; branch.push(node); } if (isFile) node.template = template; branch = node.children; }); } return sortTree(root); } function sortTree(nodes: FileTreeNode[]): FileTreeNode[] { const folders = sortByName(nodes.filter((node) => node.type === 'folder')); const files = sortByName(nodes.filter((node) => node.type === 'file')); return [...folders, ...files].map((node) => ({ ...node, children: sortTree(node.children) })); } // src/helpers/template-routing.ts type RoutedTemplateData = TemplateData & { slug: string; }; function getTemplateSlug(fileName: string) { return fileName .normalize('NFKD') .replace(/[\u0300-\u036f]/g, '') .toLowerCase() .replace(/[^a-z0-9]+/g, '-') .replace(/^-+|-+$/g, ''); } function addTemplateSlugs(templates: TemplateData[]): RoutedTemplateData[] { return templates.map((template) => ({ ...template, slug: getTemplateSlug(template.fileName) })); } function getHashRouteSlug(hash = typeof window === 'undefined' ? '' : window.location.hash) { const match = hash.match(/^#\/([^/?#]+)/); if (!match) return null; try { return decodeURIComponent(match[1]); } catch { return null; } } function updateTemplateHash(slug: string) { if (!slug || typeof window === 'undefined') return; if (getHashRouteSlug(window.location.hash) === slug) return; window.history.replaceState( window.history.state, '', `${window.location.pathname}${window.location.search}#/${encodeURIComponent(slug)}` ); } function clearTemplateHash() { if (typeof window === 'undefined' || !getHashRouteSlug(window.location.hash)) return; window.history.replaceState( window.history.state, '', `${window.location.pathname}${window.location.search}` ); } // src/helpers/templates.ts const imports = import.meta.glob('@jsxemailbuild/**/*.js', { eager: true, import: 'default' }); const previewAssetBaseUrl = `${(import.meta.env.VITE_JSXEMAIL_BASE_PATH || '/').replace(/\/?$/, '/')}static/`; function parseTemplateName(path: string) { return stripExtension(path) .split('/') .at(-1)! .replace(/[-_]+/g, ' ') .replace(/\b\w/g, (match) => match.toUpperCase()); } function toRelativePath(file: PreviewImportContent, targetPath: string) { const sourcePath = normalizePath(file.sourcePath || file.sourceFile); const normalizedTarget = normalizePath(targetPath); if (sourcePath.startsWith(`${normalizedTarget}/`)) { return sourcePath.slice(normalizedTarget.length + 1); } const sourceFile = normalizePath(file.sourceFile); if (!sourceFile.startsWith('/')) { return sourceFile.replace(/^emails\//, ''); } return sourcePath; } function normalizePreviewAssetUrls(value: string) { return value.replaceAll(/(["'(])\/static\//g, `$1${previewAssetBaseUrl}`); } function gatherTemplates() { const targetPath = import.meta.env.VITE_JSXEMAIL_TARGET_PATH; if (!targetPath) { throw new TypeError('VITE_JSXEMAIL_TARGET_PATH is not set.'); } return Object.values(imports) .map((file): TemplateData => { const relativePath = toRelativePath(file, targetPath); const routePath = stripExtension(relativePath); return { fileExtension: relativePath.match(/\.[^/.]+$/)?.[0] || '', fileName: routePath, html: normalizePreviewAssetUrls(file.html), id: `emails/${routePath}`, path: routePath, plain: file.plain, source: normalizePreviewAssetUrls(file.source), sourceFile: file.sourceFile, sourcePath: file.sourcePath || file.sourceFile, templateName: file.templateName || parseTemplateName(routePath) }; }) .sort((a, b) => a.path.localeCompare(b.path, undefined, { numeric: true })); } // src/helpers/color-inversion.ts const colorProperties = [ 'color', 'background-color', 'border-color', 'border-top-color', 'border-right-color', 'border-bottom-color', 'border-left-color', 'outline-color', 'text-decoration-color', 'caret-color', 'column-rule-color' ]; function transformColorDeclaration(style: CSSStyleDeclaration, property: string) { const value = style.getPropertyValue(property); if (!value) return; const transformed = approximateGmailIosCssColor(value, property); if (transformed === value) return; style.setProperty(property, transformed, style.getPropertyPriority(property)); } function transformStyleDeclaration(style: CSSStyleDeclaration) { colorProperties.forEach((property) => transformColorDeclaration(style, property)); } function transformCssRules(rules: CSSRuleList) { Array.from(rules).forEach((rule) => { if ('style' in rule && rule.style) { transformStyleDeclaration(rule.style as CSSStyleDeclaration); } try { if ('cssRules' in rule && rule.cssRules) { transformCssRules(rule.cssRules as CSSRuleList); } } catch { // Some grouping rules can reject cssRules access; leave them unchanged. } }); } function transformStyleBlock(css: string) { if (!window.CSSStyleSheet) return css; try { const sheet = new CSSStyleSheet(); sheet.replaceSync(css); transformCssRules(sheet.cssRules); return Array.from(sheet.cssRules) .map((rule) => rule.cssText) .join('\n'); } catch { return css; } } function applyGmailInversion(html: string) { try { const doc = new DOMParser().parseFromString(html, 'text/html'); if (doc.body) { if (!doc.body.style.color) doc.body.style.color = '#000000'; if (!doc.body.style.background && !doc.body.style.backgroundColor) { doc.body.style.backgroundColor = '#ffffff'; } } doc.querySelectorAll('[style]').forEach((element) => { transformStyleDeclaration(element.style); }); doc.querySelectorAll('style').forEach((styleElement) => { styleElement.textContent = transformStyleBlock(styleElement.textContent || ''); }); return `\n${doc.documentElement.outerHTML}`; } catch { return html; } } // src/helpers/canvas-positioning.ts const canvasOrigin = 50000; const floatingPanelInset = 12; const fileSystemPanelWidth = 288; const collapsedLabPanelWidth = 48; const canvasPaddingX = 32; const cardAlignmentAdjustment = 6; const initialCardOffset = floatingPanelInset + fileSystemPanelWidth + (496 - floatingPanelInset - fileSystemPanelWidth - collapsedLabPanelWidth) / 2 - canvasPaddingX - cardAlignmentAdjustment; function getWorkspaceCenter(canvasRect: DOMRect) { const explorerRect = document.getElementById('templates-window')?.getBoundingClientRect(); const leftEdge = explorerRect ? explorerRect.right : canvasRect.left + floatingPanelInset + fileSystemPanelWidth; const collapsedLabLeftEdge = canvasRect.right - floatingPanelInset - collapsedLabPanelWidth; return collapsedLabLeftEdge > leftEdge ? leftEdge + (collapsedLabLeftEdge - leftEdge) / 2 : canvasRect.left + canvasRect.width / 2; } function isZoomExcludedTarget(target: EventTarget | null) { return Boolean( target instanceof Element && target.closest('#templates-window, #tool-panel') ); } // src/helpers/spam-analysis.ts type SpamAnalysisStatus = 'error' | 'fail' | 'idle' | 'pass' | 'scanning' | 'warn'; interface SpamAnalysisState { classification?: CanispamClassification; classifier?: CanispamClassifierResult; findings?: CanispamFinding[]; message?: string; score?: number; scoreBreakdown?: CanispamScoreBreakdown; status: SpamAnalysisStatus; } type SpamLabelVariant = 'green' | 'grey' | 'red' | 'yellow'; const getTemplateSpamKey = ( template: Pick ) => `${template.templateName}\n${template.html}\n${template.plain}`; const getSpamLabelVariant = (state?: SpamAnalysisState): SpamLabelVariant => { if (state?.status === 'fail') return 'red'; if (state?.status === 'warn') return 'yellow'; if (state?.status === 'pass') return 'green'; return 'grey'; }; const getSpamLabelTitle = (state?: SpamAnalysisState) => { if (!state || state.status === 'idle') return 'Spam analysis pending'; if (state.status === 'scanning') return 'Spam analysis running'; if (state.status === 'error') return state.message || 'Spam analysis failed'; return `Spam ${state.classification || state.status}; score ${state.score ?? 0}`; }; const analyzeTemplateSpam = async ( template: Pick ): Promise => { try { const eml = toEml({ html: template.html, plain: template.plain, subject: template.templateName }); const result = await scan(eml); return { classification: result.classification, classifier: result.classifier, findings: result.findings, score: result.score, scoreBreakdown: result.scoreBreakdown, status: result.classification }; } catch (error) { return { message: error instanceof Error ? error.message : 'Spam analysis failed', status: 'error' }; } }; // src/helpers/tippy.ts const previewTippyProps: Partial = { arrow: false, hideOnClick: true, offset: [0, 8], placement: 'bottom', theme: 'jsx-email', trigger: 'mouseenter focus' }; // src/stores/preview-store.ts const defaultLabState = (): LabState => ({ colorScheme: false, invertColors: false, preset: previewPresets[0].name, sendEmail: '', sendError: null, sendState: 'idle' }); const waitForIdle = () => new Promise((resolve) => { if (typeof window.requestIdleCallback === 'function') { window.requestIdleCallback(() => resolve(), { timeout: 750 }); } else { globalThis.setTimeout(resolve, 0); } }); interface PreviewStore { cards: CardState[]; focusRequest: { id: string; sequence: number } | null; labs: Record; panelCollapsed: boolean; selectedId: string | null; spamAnalysisStarted: boolean; spamByTemplateId: Record; templates: RoutedTemplateData[]; zoom: number; addOrFocusTemplate: (templateId: string) => string; addOrFocusTemplateBySlug: (slug: string) => string | null; closeCard: (cardId: string) => void; ensureLab: (cardId: string) => void; focusCard: (cardId: string | null) => void; setPanelCollapsed: (value: boolean) => void; setTemplates: (templates: TemplateData[]) => void; setZoom: (value: number) => void; startSpamAnalysis: () => void; updateLab: (cardId: string, patch: Partial) => void; } const usePreviewStore = create((set, get) => ({ cards: [], focusRequest: null, labs: {}, panelCollapsed: true, selectedId: null, spamAnalysisStarted: false, spamByTemplateId: {}, templates: addTemplateSlugs(gatherTemplates()), zoom: 100, addOrFocusTemplate(templateId) { const template = get().templates.find((item) => item.id === templateId); const existing = get().cards.find((card) => card.templateId === templateId); if (existing) { if (template) updateTemplateHash(template.slug); set((state) => ({ focusRequest: { id: existing.id, sequence: (state.focusRequest?.sequence || 0) + 1 }, selectedId: existing.id })); return existing.id; } const id = `${templateId}-${Date.now()}-${Math.random().toString(16).slice(2)}`; if (template) updateTemplateHash(template.slug); set((state) => ({ cards: [...state.cards, { id, templateId }], focusRequest: { id, sequence: (state.focusRequest?.sequence || 0) + 1 }, labs: { ...state.labs, [id]: defaultLabState() }, selectedId: id })); return id; }, addOrFocusTemplateBySlug(slug) { const template = get().templates.find((item) => item.slug === slug); return template ? get().addOrFocusTemplate(template.id) : null; }, closeCard(cardId) { const state = get(); const labs = { ...state.labs }; delete labs[cardId]; const cards = state.cards.filter((card) => card.id !== cardId); const selectedId = state.selectedId === cardId ? cards.at(-1)?.id || null : state.selectedId; const selectedTemplate = state.templates.find( (template) => template.id === cards.find((card) => card.id === selectedId)?.templateId ); if (selectedTemplate) updateTemplateHash(selectedTemplate.slug); else if (!selectedId) clearTemplateHash(); set({ cards, focusRequest: selectedId && state.selectedId === cardId ? { id: selectedId, sequence: (state.focusRequest?.sequence || 0) + 1 } : state.focusRequest, labs, selectedId }); }, ensureLab(cardId) { set((state) => state.labs[cardId] ? state : { labs: { ...state.labs, [cardId]: defaultLabState() } } ); }, focusCard(cardId) { const template = get().templates.find( (item) => item.id === get().cards.find((card) => card.id === cardId)?.templateId ); if (template) updateTemplateHash(template.slug); set((state) => ({ focusRequest: cardId ? { id: cardId, sequence: (state.focusRequest?.sequence || 0) + 1 } : state.focusRequest, selectedId: cardId })); }, setPanelCollapsed(value) { set({ panelCollapsed: value }); }, setTemplates(templates) { set({ spamAnalysisStarted: false, spamByTemplateId: {}, templates: addTemplateSlugs(templates) }); }, setZoom(value) { set({ zoom: value }); }, startSpamAnalysis() { if (get().spamAnalysisStarted) return; const templates = get().templates.map((template) => ({ ...template, spamKey: getTemplateSpamKey(template) })); set((state) => ({ spamAnalysisStarted: true, spamByTemplateId: templates.reduce>( (next, template) => ({ ...next, [template.id]: state.spamByTemplateId[template.id] || { status: 'scanning' } }), {} ) })); const scanNext = async (index: number): Promise => { const template = templates[index]; if (!template) return; await waitForIdle(); set((state) => ({ spamByTemplateId: { ...state.spamByTemplateId, [template.id]: { status: 'scanning' } } })); const result = await analyzeTemplateSpam(template); const current = get().templates.find((item) => item.id === template.id); if (current && getTemplateSpamKey(current) === template.spamKey) { set((state) => ({ spamByTemplateId: { ...state.spamByTemplateId, [template.id]: result } })); } await scanNext(index + 1); }; void scanNext(0); }, updateLab(cardId, patch) { set((state) => { const previous = state.labs[cardId] || defaultLabState(); return { labs: { ...state.labs, [cardId]: { ...previous, ...patch } } }; }); } })); function getLab(cardId: string | null) { if (!cardId) return defaultLabState(); return usePreviewStore.getState().labs[cardId] || defaultLabState(); } // src/components/ui/button.tsx interface ButtonProps extends ButtonHTMLAttributes { children: ReactNode; size?: 'sm' | 'icon' | 'default'; variant?: 'default' | 'outline' | 'ghost'; } function Button({ children, className, size: _size, variant = 'default', ...props }: ButtonProps) { void _size; return ( ); } // src/components/plunk-logo.tsx function PlunkLogo(props: SVGProps) { return ( ); } // src/components/code/code-block.tsx const shiki = createHighlighterCoreSync({ engine: createJavaScriptRegexEngine(), langs: [shikiHtmlLang, shikiJsLang, shikiTsxLang], themes: [shikiGithubLightTheme, shikiGithubDarkHighContrastTheme] }); const lineNumberTransformer: ShikiTransformer = { name: 'jsx-email-preview-line-numbers', line(node, line) { const { children } = node; node.children = [ { type: 'element', tagName: 'span', properties: { ariaHidden: 'true', className: ['code-line-number'], dataLineNumber: String(line) }, children: [{ type: 'text', value: String(line) }] }, { type: 'element', tagName: 'span', properties: { className: ['code-line-content'] }, children } ]; } }; interface CodeBlockProps { code: string; fileName: string; lang: 'tsx' | 'html' | 'text'; } function formatCode(code: string, lang: CodeBlockProps['lang']) { if (lang === 'html') return beautify.html(code, { indent_size: 2 }); return code; } function codeToLineNumberedHtml( code: string, lang: CodeBlockProps['lang'], theme: 'github-light' | 'github-dark-high-contrast' ) { if (lang === 'text') return escapeHtml(code); return shiki.codeToHtml(code, { lang, theme, transformers: [lineNumberTransformer] }); } function CodeBlock({ code, fileName, lang }: CodeBlockProps) { const [copied, setCopied] = useState(false); const visibleCode = useMemo(() => formatCode(code, lang), [code, lang]); const html = useMemo(() => { const theme = document.documentElement.classList.contains('dark') ? 'github-dark-high-contrast' : 'github-light'; return codeToLineNumberedHtml(visibleCode, lang, theme); }, [lang, visibleCode]); async function copy() { await navigator.clipboard.writeText(visibleCode); setCopied(true); window.setTimeout(() => setCopied(false), 1400); } return (
); } function escapeHtml(value: string) { const lines = value.split('\n'); return `
${lines
    .map((line, index) => {
      const lineNumber = index + 1;
      return `${line
        .replaceAll('&', '&')
        .replaceAll('<', '<')
        .replaceAll('>', '>')}`;
    })
    .join('')}
`; } // src/components/canvas/preview-iframe.tsx interface PreviewIframeProps { html: string; title: string; } function PreviewIframe({ html, title }: PreviewIframeProps) { const [renderedHtml, setRenderedHtml] = useState(html); const iframeRef = useRef(null); const pendingScroll = useRef<{ x: number; y: number } | null>(null); useLayoutEffect(() => { if (html === renderedHtml) return; const frame = iframeRef.current; pendingScroll.current = { x: frame?.contentWindow?.scrollX || 0, y: frame?.contentWindow?.scrollY || 0 }; setRenderedHtml(html); }, [html, renderedHtml]); return (