Update App.jsx via upload script - 2026-10-31 01:39:00

This commit is contained in:
mike 2026-10-31 01:39:19 +08:00
parent ee8731c4b2
commit 9e180a09bd
1 changed files with 151 additions and 5 deletions

154
App.jsx
View File

@ -7340,32 +7340,171 @@ function TemplateProductMatcher({ tpl, products, setProducts, onNotify }) {
}
// ---- HTML 片段里的图片:压缩后直接嵌进 HTML(data URI),网站和预览都不用另外存图片 ----
// 最长边缩到 1200px,转 WebP(浏览器不支持时:有透明的用 PNG,没有的用 JPEG)。
// removeWhite:从图片四边开始,把连在一起的白色 / 近白色背景变透明(产品内部的白色不受影响)。
async function imageFileToDataUrl(file, { removeWhite = false, maxSide = 1200 } = {}) {
const url = URL.createObjectURL(file);
try {
const img = await new Promise((ok, bad) => { const i = new Image(); i.onload = () => ok(i); i.onerror = () => bad(new Error(`${file.name} 读取失败,不是图片或格式不支持`)); i.src = url; });
const k = Math.min(1, maxSide / Math.max(img.naturalWidth, img.naturalHeight));
const w = Math.max(1, Math.round(img.naturalWidth * k)), h = Math.max(1, Math.round(img.naturalHeight * k));
const c = document.createElement('canvas'); c.width = w; c.height = h;
const ctx = c.getContext('2d');
ctx.drawImage(img, 0, 0, w, h);
const data = ctx.getImageData(0, 0, w, h), d = data.data;
if (removeWhite) {
const seen = new Uint8Array(w * h), stack = [];
const white = (p) => d[p * 4 + 3] > 0 && d[p * 4] >= 232 && d[p * 4 + 1] >= 232 && d[p * 4 + 2] >= 232;
for (let x = 0; x < w; x++) stack.push(x, (h - 1) * w + x);
for (let y = 0; y < h; y++) stack.push(y * w, y * w + w - 1);
while (stack.length) {
const p = stack.pop();
if (seen[p]) continue;
seen[p] = 1;
if (d[p * 4 + 3] === 0) { /* 已经透明:继续往里找 */ } else if (white(p)) d[p * 4 + 3] = 0; else continue;
const x = p % w, y = (p - x) / w;
if (x > 0) stack.push(p - 1); if (x < w - 1) stack.push(p + 1);
if (y > 0) stack.push(p - w); if (y < h - 1) stack.push(p + w);
}
// 边缘一圈浅色像素做半透明,免得留白边
for (let p = 0; p < w * h; p++) {
if (seen[p] || d[p * 4 + 3] === 0) continue;
const x = p % w, y = (p - x) / w;
const near = (x > 0 && seen[p - 1] && !d[(p - 1) * 4 + 3]) || (x < w - 1 && seen[p + 1] && !d[(p + 1) * 4 + 3]) || (y > 0 && seen[p - w] && !d[(p - w) * 4 + 3]) || (y < h - 1 && seen[p + w] && !d[(p + w) * 4 + 3]);
if (near) { const lum = (d[p * 4] + d[p * 4 + 1] + d[p * 4 + 2]) / 3; if (lum > 200) d[p * 4 + 3] = Math.round(d[p * 4 + 3] * (255 - lum) / 55); }
}
ctx.putImageData(data, 0, 0);
}
let alpha = false;
for (let i = 3; i < d.length; i += 4) if (d[i] < 250) { alpha = true; break; }
let src = c.toDataURL('image/webp', 0.82);
if (!src.startsWith('data:image/webp')) src = alpha ? c.toDataURL('image/png') : c.toDataURL('image/jpeg', 0.85);
return { src, w, h, alpha, kb: Math.round(src.length * 3 / 4 / 1024) };
} finally { URL.revokeObjectURL(url); }
}
// HTML 里"可以替换的图":<img> 和最外层的 <svg>(svg 里面套的不算)。预览里的点选和替换用同一套规则,序号才对得上。
const HTML_VISUALS = (doc) => [...doc.querySelectorAll('img, svg')].filter(el => !(el.parentElement && el.parentElement.closest('svg')));
// 预览里点选模式:给每张图加红色虚线框,点哪张就把序号发给 CRM 页面
const pickScript = (tok) => `<script>(function(){var els=[].filter.call(document.querySelectorAll('img, svg'),function(e){return !(e.parentElement&&e.parentElement.closest('svg'))});
var st=document.createElement('style');st.textContent='[data-pk]{outline:2px dashed #e11d48!important;outline-offset:2px;cursor:crosshair!important}[data-pk]:hover{outline:3px solid #e11d48!important;opacity:.75}';(document.head||document.documentElement).appendChild(st);
els.forEach(function(e,i){e.setAttribute('data-pk',i);e.addEventListener('click',function(ev){ev.preventDefault();ev.stopPropagation();parent.postMessage({__pickImg:1,idx:i,tok:${JSON.stringify(tok)}},'*')},true)});})();<\/script>`;
// 把第 idx 张图换成新图片:<img> 只换 src;<svg> 换成 <img>,沿用它的 class / 宽高,排版不变
function replaceHtmlVisual(html, idx, img) {
const src = String(html || '');
const full = /<html[\s>]/i.test(src);
const doctype = (src.match(/^\s*(<!doctype[^>]*>)/i) || [])[1] || '';
const doc = new DOMParser().parseFromString(src, 'text/html');
const el = HTML_VISUALS(doc)[idx];
if (!el) return null;
if (el.tagName.toLowerCase() === 'img') {
el.setAttribute('src', img.src);
el.removeAttribute('srcset');
if (el.hasAttribute('width') && el.hasAttribute('height')) { el.setAttribute('width', img.w); el.setAttribute('height', img.h); }
} else {
const n = doc.createElement('img');
n.setAttribute('src', img.src);
n.setAttribute('alt', el.getAttribute('aria-label') || '');
const cls = el.getAttribute('class');
if (cls) n.setAttribute('class', cls);
for (const a of ['width', 'height']) if (el.hasAttribute(a) && !/%/.test(el.getAttribute(a))) n.setAttribute(a, el.getAttribute(a));
const keep = el.getAttribute('style') || '';
n.setAttribute('style', (cls || el.hasAttribute('width') ? 'max-width:100%;object-fit:contain;' : 'display:block;width:100%;height:auto;') + keep);
el.replaceWith(n);
}
return full ? (doctype ? doctype + '\n' : '') + doc.documentElement.outerHTML : doc.body.innerHTML;
}
const imgTag = (img) => `<img src="${img.src}" alt="" width="${img.w}" height="${img.h}" style="display:block;max-width:100%;height:auto;margin:0 auto">`;
// 详情图片里的 HTML 片段:原样显示(保留自己的排版、颜色、字体),穿插在详情图片之间。
// 存在模板的 detailHtml:[{ id, html, pos }],pos = 排在第几张图后面(0 = 最上面)。网站上放在隔离的 iframe 里,英文以外的语言自动翻译文字。
function DetailHtmlBlocks({ tpl, update }) {
const blocks = Array.isArray(tpl.detailHtml) ? tpl.detailHtml : [];
const n = (tpl.images || []).length;
const [preview, setPreview] = useState('');
const [removeWhite, setRemoveWhite] = useState(false);
const [picking, setPicking] = useState(null); // { id, img }:已选好图片,等在预览里点要换的那张
const [busy, setBusy] = useState('');
const [msg, setMsg] = useState({}); // { 片段id: 提示文字 }
const cursor = useRef({}); // { 片段id: 光标位置 }
const fileRef = useRef(null);
const action = useRef(null); // { id, mode: 'insert' | 'replace' }
const blocksRef = useRef(blocks); blocksRef.current = blocks;
const set = (list) => update({ detailHtml: list });
const patch = (id, p) => set(blocks.map(b => (b.id === id ? { ...b, ...p } : b)));
const patch = (id, p) => set(blocksRef.current.map(b => (b.id === id ? { ...b, ...p } : b)));
const add = () => set([...blocks, { id: 'dh_' + Date.now().toString(36) + Math.random().toString(36).slice(2, 6), html: '', pos: n }]);
const posLabel = (i) => (i === 0 ? '最上面(第 1 张图前面)' : i >= n ? `最下面(第 ${n} 张图后面)` : `第 ${i} 张图后面`);
const note = (id, t) => setMsg(m => ({ ...m, [id]: t }));
async function pickFile(id, file) {
if (!file) return;
const text = await file.text();
patch(id, { html: text });
}
const countVisuals = (html) => { try { return HTML_VISUALS(new DOMParser().parseFromString(String(html || ''), 'text/html')).length; } catch { return 0; } };
function chooseImages(id, mode) {
action.current = { id, mode };
if (fileRef.current) { fileRef.current.multiple = mode === 'insert'; fileRef.current.value = ''; fileRef.current.click(); }
}
async function onImages(files) {
const act = action.current;
if (!act || !files.length) return;
setBusy(act.id);
try {
const imgs = [];
for (const f of files) imgs.push(await imageFileToDataUrl(f, { removeWhite }));
const kb = imgs.reduce((s, x) => s + x.kb, 0);
if (act.mode === 'insert') {
const b = blocksRef.current.find(x => x.id === act.id);
const html = String((b && b.html) || '');
let at = cursor.current[act.id];
if (!Number.isFinite(at) || at > html.length) { const m = html.search(/<\/body>/i); at = m >= 0 ? m : html.length; }
const snippet = imgs.map(imgTag).join('\n');
patch(act.id, { html: html.slice(0, at) + snippet + html.slice(at) });
cursor.current[act.id] = at + snippet.length;
note(act.id, `已插入 ${imgs.length} 张图片(约 ${kb} KB)`);
} else {
if (!countVisuals((blocksRef.current.find(x => x.id === act.id) || {}).html)) { note(act.id, '这个片段里没有图片可以替换,请用"插入图片"'); return; }
setPicking({ id: act.id, img: imgs[0] });
setPreview(act.id);
note(act.id, `新图片已就绪(约 ${kb} KB):在下面预览里点一下要换掉的那张图(红框),按"取消替换"放弃`);
}
} catch (e) { note(act.id, '图片处理失败:' + e.message); }
finally { setBusy(''); action.current = null; }
}
useEffect(() => {
if (!picking) return undefined;
const on = (e) => {
const d = e.data;
if (!d || !d.__pickImg || d.tok !== picking.id) return;
const b = blocksRef.current.find(x => x.id === picking.id);
const out = b && replaceHtmlVisual(b.html, d.idx, picking.img);
if (out == null) { note(picking.id, '没找到这张图,请重新点选'); return; }
patch(picking.id, { html: out });
note(picking.id, `已替换第 ${d.idx + 1} 张图`);
setPicking(null);
};
window.addEventListener('message', on);
return () => window.removeEventListener('message', on);
}, [picking]);
return (
<div className="field" style={{ border: '1px solid var(--line)', borderRadius: 10, padding: 12, margin: '0 0 10px' }}>
<input ref={fileRef} type="file" accept="image/*" style={{ display: 'none' }} onChange={e => onImages([...(e.target.files || [])])} />
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 8, flexWrap: 'wrap' }}>
<span className="field-label" style={{ margin: 0 }}>详情 HTML 片段({blocks.length})</span>
<div style={{ display: 'flex', gap: 10, alignItems: 'center', flexWrap: 'wrap' }}>
<label style={{ fontSize: 12.5, display: 'flex', gap: 4, alignItems: 'center', cursor: 'pointer' }} title="从图片四边开始,把连着边的白色背景变透明;产品内部的白色不受影响。图片本来就是透明底的不用勾">
<input type="checkbox" checked={removeWhite} onChange={e => setRemoveWhite(e.target.checked)} />插入 / 替换图片时去掉白色背景
</label>
<button type="button" className="btn btn-sm" onClick={add}><Plus size={12} />添加 HTML 片段</button>
</div>
</div>
<div style={{ fontSize: 12, color: 'var(--ink-soft)', margin: '6px 0 8px' }}>
粘贴 HTML 代码或上传 .html 文件(比如用 Gemini 做的图文详情页),网站上原样显示:保留自己的排版、颜色和字体,像一张长图一样插在详情图片之间。英文写的文字会自动翻译成西语、俄语。
<br />图片:「替换图片」= 先选新图片,再在预览里点要换掉的那张(示意图、SVG 插画、原有图片都可以换,大小和排版沿用原来的);「插入图片」= 插到下面代码框里光标所在的位置(没点过代码框就放在最后)。JPG / PNG / WebP 都可以,自动压缩后嵌进 HTML。
</div>
{blocks.map((b, k) => {
const len = String(b.html || '').trim().length;
const isPicking = picking && picking.id === b.id;
return (
<div key={b.id} style={{ borderTop: '1px dashed var(--line)', padding: '10px 0', display: 'grid', gap: 8 }}>
<div style={{ display: 'flex', gap: 8, alignItems: 'center', flexWrap: 'wrap' }}>
@ -7378,14 +7517,21 @@ function DetailHtmlBlocks({ tpl, update }) {
<input type="file" accept=".html,.htm,text/html" style={{ display: 'none' }} onChange={e => { pickFile(b.id, e.target.files && e.target.files[0]); e.target.value = ''; }} />
上传 .html
</label>
<button type="button" className="btn btn-sm" disabled={!len} onClick={() => setPreview(preview === b.id ? '' : b.id)}>{preview === b.id ? '收起预览' : '预览'}</button>
<button type="button" className="btn btn-sm" disabled={!len || !!busy} onClick={() => chooseImages(b.id, 'replace')}><ImageIcon size={12} />替换图片</button>
<button type="button" className="btn btn-sm" disabled={!!busy} onClick={() => chooseImages(b.id, 'insert')}><Plus size={12} />插入图片</button>
{isPicking
? <button type="button" className="btn btn-sm btn-danger" onClick={() => { setPicking(null); note(b.id, '已取消替换'); }}>取消替换</button>
: <button type="button" className="btn btn-sm" disabled={!len} onClick={() => setPreview(preview === b.id ? '' : b.id)}>{preview === b.id ? '收起预览' : '预览'}</button>}
<button type="button" className="btn btn-sm btn-ghost btn-danger" onClick={() => { if (!len || window.confirm('删除这个 HTML 片段?')) set(blocks.filter(x => x.id !== b.id)); }}><Trash2 size={12} /></button>
<span style={{ fontSize: 12, color: 'var(--ink-soft)' }}>{len ? `${len.toLocaleString()} 字符` : '空'}</span>
<span style={{ fontSize: 12, color: len > 600000 ? 'var(--led-red)' : 'var(--ink-soft)' }}>{len ? `${len.toLocaleString()} 字符(约 ${Math.round(len / 1024)} KB)` : '空'}</span>
</div>
{(busy === b.id || msg[b.id]) && <div style={{ fontSize: 12.5, color: isPicking ? '#e11d48' : 'var(--ink-soft)' }}>{busy === b.id ? '正在处理图片…' : msg[b.id]}</div>}
<textarea className="input" rows={6} value={b.html || ''} onChange={e => patch(b.id, { html: e.target.value })}
onSelect={e => { cursor.current[b.id] = e.target.selectionStart; }}
placeholder="<div>…</div> 或完整的 <html>…</html>" style={{ fontFamily: 'var(--mono, monospace)', fontSize: 12, resize: 'vertical', width: '100%', boxSizing: 'border-box' }} />
{preview === b.id && len > 0 && (
<iframe title="预览" sandbox="allow-scripts" srcDoc={b.html} style={{ width: '100%', height: 480, border: '1px solid var(--line)', borderRadius: 8, background: '#fff' }} />
<iframe title="预览" sandbox="allow-scripts" srcDoc={isPicking ? String(b.html) + pickScript(b.id) : b.html}
style={{ width: '100%', height: 480, border: isPicking ? '2px solid #e11d48' : '1px solid var(--line)', borderRadius: 8, background: '#fff' }} />
)}
</div>
);