Files
it-tools-pro/src/tools/poster/poster.vue
T
jinghui 3c126277eb feat: 历史记录100条上限 + 后台文件管理升级收口
- 所有功能历史最多显示100条:relay img-history vis[:150]→[:100]、mcp-usage 流水 LIMIT 300→100
- 前端三处兜底:loadImgHist/ai-gen/poster slice(0,100)
- 上轮遗留收口:后台文件管理全量视图/50条分页/100x100缩略图/下载/三类删除、图片历史铁规则 ImgHist 共享层接入7工具
- Home NEW_FEATURES 与 README 同步
2026-11-14 18:58:48 +08:00

755 lines
34 KiB
Vue
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<script setup lang="ts">
import { ref, computed, onMounted, onBeforeUnmount } from 'vue';
import { getMachineId, licenseHeaders } from '@/tools/license/license';
import { authHdr } from '@/tools/img-hist/img-hist';
import {
POSTER_TEMPLATES, POSTER_CATS, BG_PRESETS, POSTER_W, POSTER_H,
type PosterTemplate, type PosterBg, type PosterImageLayer,
} from './templates';
type L = any; // 图层运行时对象(text / image / shape 联合,编辑期动态增删)
const FONT_STACK = '"PingFang SC","Hiragino Sans GB","Microsoft YaHei","Noto Sans CJK SC",sans-serif';
const MINI_W = 116;
const cat = ref('hot');
const cur = ref<PosterTemplate | null>(null);
const tplId = ref('');
const layers = ref<L[]>([]);
const bg = ref<PosterBg>({});
const selId = ref('');
const scale = ref(0.5);
const stageEl = ref<HTMLElement | null>(null);
const pmRoot = ref<HTMLElement | null>(null);
const pmH = ref(0); // 视口自适应高度:根不滚动,滚动只发生在内部区域
const fileEl = ref<HTMLInputElement | null>(null);
const pmError = ref('');
const models = ref<{ id: string; name?: string }[]>([]);
const model = ref('');
const genBusy = ref(false);
const bgPrompt = ref('');
const exporting = ref(false);
// ---------- 生成历史(服务端落盘,右侧 50×50 缩略图竖排) ----------
const hist = ref<{ id: string; img_url: string; prompt?: string; kind?: string; at?: number }[]>([]);
const histBusy = ref(false);
const histView = ref(''); // 大图查看(点击缩略图打开,点空白关闭)
async function loadHist() {
histBusy.value = true;
try {
const res = await fetch(`/relay/ai/img-history?machine=${encodeURIComponent(getMachineId())}&kind=poster`, {
headers: { ...licenseHeaders('poster-maker'), ...authHdr() },
});
const j = await res.json().catch(() => ({}) as any);
// 铁规则:所有功能历史最多显示 100 条
if (res.ok && j.code === 200 && Array.isArray(j.data)) hist.value = j.data.slice(0, 100);
} catch { /* 历史拉取失败静默,不影响编辑 */ } finally { histBusy.value = false; }
}
let uid = 0;
let ro: ResizeObserver | null = null;
let scRO: ResizeObserver | null = null;
const filtered = computed(() =>
cat.value === 'hot' ? POSTER_TEMPLATES : POSTER_TEMPLATES.filter((t) => t.category === cat.value));
const sel = computed(() => layers.value.find((l) => l.id === selId.value) || null);
const selName = computed(() => {
const l = sel.value; if (!l) return '';
if (l.type === 'text') return (l.text || '文字').slice(0, 10);
if (l.type === 'image') return '图片';
return l.shape === 'ellipse' ? '圆形色块' : '矩形色块';
});
// ---------- 换模板 ----------
function selectTemplate(t: PosterTemplate) {
tplId.value = t.id;
cur.value = t;
bg.value = JSON.parse(JSON.stringify(t.bg));
layers.value = JSON.parse(JSON.stringify(t.layers)).map((l: L) => ({ ...l, id: 'l' + ++uid }));
selId.value = '';
pmError.value = '';
}
function resetTpl() {
const t = POSTER_TEMPLATES.find((x) => x.id === tplId.value);
if (t) selectTemplate(t);
}
// ---------- 文字排版(预览与导出共用,保证换行一致) ----------
const mc = document.createElement('canvas');
const mctx = mc.getContext('2d')!;
const wrapCache = new Map<string, string[]>();
const CLOSE_PUNCT = ',。、!?:;)】」』,.!?;:)';
function fontStr(l: L) {
return `${l.italic ? 'italic ' : ''}${l.weight ?? 700} ${l.size}px ${FONT_STACK}`;
}
function linesOf(l: L): string[] {
const key = `${l.text}|${l.w}|${fontStr(l)}`;
const hit = wrapCache.get(key);
if (hit) return hit;
mctx.font = fontStr(l);
const out: string[] = [];
for (const para of String(l.text ?? '').split('\n')) {
if (!para) { out.push(''); continue; }
let line = '';
for (const ch of para) {
const test = line + ch;
if (line && mctx.measureText(test).width > l.w && !CLOSE_PUNCT.includes(ch)) {
out.push(line); line = ch;
} else line = test;
}
out.push(line);
}
const res = out.length ? out : [''];
wrapCache.set(key, res);
return res;
}
// ---------- 样式 ----------
function bgCss(b: PosterBg): string {
if (b.color) return b.color;
if (b.stops?.length) {
const stops = b.stops.map((s) => `${s.c} ${Math.round(s.p * 100)}%`).join(', ');
return `linear-gradient(${b.angle ?? 135}deg, ${stops})`;
}
return '#ffffff';
}
function boxStyle(l: L) {
return {
left: l.x + 'px', top: l.y + 'px', width: l.w + 'px',
height: l.type === 'text' ? 'auto' : l.h + 'px',
transform: l.rot ? `rotate(${l.rot}deg)` : undefined,
};
}
function fontStyle(l: L) {
return {
fontFamily: FONT_STACK,
fontSize: l.size + 'px',
fontWeight: String(l.weight ?? 700),
color: l.color,
textAlign: l.align ?? 'center',
lineHeight: l.size * (l.lineHeight ?? 1.25) + 'px',
fontStyle: l.italic ? 'italic' : 'normal',
textShadow: l.shadow ? `0 ${l.shadow.y}px ${l.shadow.blur}px ${l.shadow.color}` : 'none',
};
}
function shapeStyle(l: L) {
return {
background: l.fill,
borderRadius: l.shape === 'ellipse' ? '50%' : (l.radius ?? 0) + 'px',
opacity: l.opacity ?? 1,
};
}
function miniBoxStyle(l: L) { return boxStyle(l); }
const tplLayers = (t: PosterTemplate): L[] => t.layers as any;
function onFill(e: Event) { const l = sel.value; if (l) l.fill = (e.target as HTMLInputElement).value; }
function onRot(e: Event) { const l = sel.value; if (l) l.rot = Number((e.target as HTMLInputElement).value); }
// ---------- 选中 / 拖动 ----------
function onDown(e: PointerEvent, l: L) {
selId.value = l.id;
drag = { l, sx: e.clientX, sy: e.clientY, lx: l.x, ly: l.y };
window.addEventListener('pointermove', onMove);
window.addEventListener('pointerup', onUp);
e.preventDefault();
}
let drag: { l: L; sx: number; sy: number; lx: number; ly: number } | null = null;
function onMove(e: PointerEvent) {
if (!drag) return;
const s = scale.value || 1;
const l = drag.l;
let nx = drag.lx + (e.clientX - drag.sx) / s;
let ny = drag.ly + (e.clientY - drag.sy) / s;
const maxX = POSTER_W - l.w;
const maxY = POSTER_H - (l.type === 'text' ? l.size : l.h);
l.x = Math.min(Math.max(nx, 0), Math.max(maxX, 0));
l.y = Math.min(Math.max(ny, 0), Math.max(maxY, 0));
}
function onUp() {
drag = null;
window.removeEventListener('pointermove', onMove);
window.removeEventListener('pointerup', onUp);
}
// ---------- 图层增删 ----------
function addText() {
const l = { id: 'l' + ++uid, type: 'text', text: '点击右侧修改文字', x: 140, y: 660, w: 800, size: 80, color: '#111111', weight: 700, align: 'center', lineHeight: 1.25 };
layers.value.push(l); selId.value = l.id;
}
function addImage() {
const l = { id: 'l' + ++uid, type: 'image', x: 190, y: 500, w: 700, h: 520, radius: 24, src: '', prompt: '' };
layers.value.push(l); selId.value = l.id;
}
function delSel() {
const i = layers.value.findIndex((l) => l.id === selId.value);
if (i >= 0) layers.value.splice(i, 1);
selId.value = '';
}
function moveLayer(dz: number) {
const i = layers.value.findIndex((l) => l.id === selId.value);
const j = i + dz;
if (i < 0 || j < 0 || j >= layers.value.length) return;
const [l] = layers.value.splice(i, 1);
layers.value.splice(j, 0, l);
}
function pickFile() { fileEl.value?.click(); }
function onFile(e: Event) {
const f = (e.target as HTMLInputElement).files?.[0];
const l = sel.value;
if (f && l && l.type === 'image') l.src = URL.createObjectURL(f);
(e.target as HTMLInputElement).value = '';
}
function clearImg() { const l = sel.value; if (l && l.type === 'image') l.src = ''; }
// ---------- AI 生图(复用 relay /ai/gen-image + 每日免费额度) ----------
function b64DataUrl(b64: string) {
let mime = 'image/png';
if (b64.startsWith('/9j/')) mime = 'image/jpeg';
else if (b64.startsWith('UklGR')) mime = 'image/webp';
return `data:${mime};base64,${b64}`;
}
async function genFor(l: PosterImageLayer) {
const prompt = String(l.prompt ?? '').trim();
if (!prompt) { pmError.value = '请先填写图片描述'; return; }
genBusy.value = true; pmError.value = '';
try {
// 上游生图模型只接受固定尺寸档位(如 dall-e-3 仅 1024²/1792×1024/1024×1792),
// 按图框宽高比映射到三档,出图后由 CSS object-fit:cover 裁切填充
const ar = l.w / Math.max(1, l.h);
let width = 1024, height = 1024;
if (ar > 1.25) { width = 1792; height = 1024; }
else if (ar < 0.8) { width = 1024; height = 1792; }
const res = await fetch('/relay/ai/gen-image', {
method: 'POST',
headers: { 'Content-Type': 'application/json', ...licenseHeaders('poster-maker'), ...authHdr() },
body: JSON.stringify({ machine: getMachineId(), prompt, model: model.value, width, height, kind: 'poster' }),
});
const j = await res.json().catch(() => ({}) as any);
if (!res.ok || j.code !== 200) throw new Error(j.message || `HTTP ${res.status}`);
const url = j.data?.img_url || (j.data?.b64 ? b64DataUrl(j.data.b64) : '') || j.data?.url || '';
if (!url) throw new Error('未返回图片');
l.src = url;
loadHist(); // 服务端已落盘,刷新右侧历史
} catch (err: any) {
pmError.value = 'AI 生成失败:' + (err?.message || String(err));
} finally {
genBusy.value = false;
}
}
async function genBg() {
const l = {
id: 'l' + ++uid, type: 'image', x: 0, y: 0, w: POSTER_W, h: POSTER_H, radius: 0,
src: '', prompt: bgPrompt.value.trim() || '高级感海报背景图,留白构图,杂志风',
};
layers.value.unshift(l);
selId.value = '';
await genFor(l);
if (!l.src) layers.value = layers.value.filter((x) => x !== l);
}
// ---------- 缩放 ----------
// 宽高双向适配:画布始终完整落在舞台内,舞台自身不出滚动条
function fit() {
measure(); // 舞台尺寸一变就顺带复测根高度(仅值变化才写,稳定后自收敛)
const el = stageEl.value;
const w = Math.max((el?.clientWidth || 600) - 20, 120);
const h = Math.max((el?.clientHeight || 760) - 20, 160);
scale.value = Math.min(Math.max(Math.min(w / POSTER_W, h / POSTER_H), 0.1), 0.85);
}
// 测量所在滚动容器:根高度 = 容器可视高 - 上方占用,页面级永不出现滚动条
function measure() {
const el = pmRoot.value;
if (!el) return;
// 必须取最内层滚动容器:外层是套壳,高度口径不同,用外层算出来的值会错
const sc = el.closest('.n-layout-scroll-container') as HTMLElement | null;
if (!sc) return;
const above = el.getBoundingClientRect().top - sc.getBoundingClientRect().top + sc.scrollTop;
const h = Math.floor(sc.clientHeight - above - 18);
if (h >= 160 && h !== pmH.value) pmH.value = h;
}
// ---------- 导出 PNG ----------
function rrPath(ctx: CanvasRenderingContext2D, x: number, y: number, w: number, h: number, r: number) {
r = Math.min(r, w / 2, h / 2);
ctx.beginPath();
ctx.moveTo(x + r, y);
ctx.lineTo(x + w - r, y);
ctx.quadraticCurveTo(x + w, y, x + w, y + r);
ctx.lineTo(x + w, y + h - r);
ctx.quadraticCurveTo(x + w, y + h, x + w - r, y + h);
ctx.lineTo(x + r, y + h);
ctx.quadraticCurveTo(x, y + h, x, y + h - r);
ctx.lineTo(x, y + r);
ctx.quadraticCurveTo(x, y, x + r, y);
ctx.closePath();
}
function drawBg(ctx: CanvasRenderingContext2D, b: PosterBg) {
if (b.color) { ctx.fillStyle = b.color; ctx.fillRect(0, 0, POSTER_W, POSTER_H); return; }
if (!b.stops?.length) { ctx.fillStyle = '#fff'; ctx.fillRect(0, 0, POSTER_W, POSTER_H); return; }
const a = (b.angle ?? 135) * Math.PI / 180;
const len = Math.abs(POSTER_W * Math.sin(a)) + Math.abs(POSTER_H * Math.cos(a));
const cx = POSTER_W / 2, cy = POSTER_H / 2;
const dx = Math.sin(a), dy = -Math.cos(a);
const g = ctx.createLinearGradient(cx - dx * len / 2, cy - dy * len / 2, cx + dx * len / 2, cy + dy * len / 2);
for (const s of b.stops) g.addColorStop(Math.min(Math.max(s.p, 0), 1), s.c);
ctx.fillStyle = g;
ctx.fillRect(0, 0, POSTER_W, POSTER_H);
}
function loadImg(src: string): Promise<HTMLImageElement | null> {
return new Promise((res) => {
const i = new Image();
i.onload = () => res(i);
i.onerror = () => res(null);
i.src = src;
});
}
// 绕 (cx, cy) 旋转画布坐标系:预览走 CSS transform、导出走 canvas,中心一致才不跑位
function rotAround(ctx: CanvasRenderingContext2D, cx: number, cy: number, deg: number) {
ctx.translate(cx, cy);
ctx.rotate((deg * Math.PI) / 180);
ctx.translate(-cx, -cy);
}
async function drawLayer(ctx: CanvasRenderingContext2D, l: L) {
if (l.type === 'shape') {
ctx.save();
if (l.rot) rotAround(ctx, l.x + l.w / 2, l.y + l.h / 2, l.rot);
ctx.globalAlpha = l.opacity ?? 1;
ctx.fillStyle = l.fill;
if (l.shape === 'ellipse') {
ctx.beginPath();
ctx.ellipse(l.x + l.w / 2, l.y + l.h / 2, l.w / 2, l.h / 2, 0, 0, Math.PI * 2);
ctx.fill();
} else {
rrPath(ctx, l.x, l.y, l.w, l.h, l.radius ?? 0);
ctx.fill();
}
ctx.restore();
return;
}
if (l.type === 'image') {
ctx.save();
if (l.rot) rotAround(ctx, l.x + l.w / 2, l.y + l.h / 2, l.rot);
rrPath(ctx, l.x, l.y, l.w, l.h, l.radius ?? 0);
ctx.clip();
const img = l.src ? await loadImg(l.src) : null;
if (img && img.naturalWidth) {
const s = Math.max(l.w / img.naturalWidth, l.h / img.naturalHeight);
const dw = img.naturalWidth * s, dh = img.naturalHeight * s;
ctx.drawImage(img, l.x + (l.w - dw) / 2, l.y + (l.h - dh) / 2, dw, dh);
} else {
ctx.fillStyle = '#ececec';
ctx.fillRect(l.x, l.y, l.w, l.h);
ctx.fillStyle = '#999999';
ctx.font = `400 ${Math.max(24, Math.round(l.h * 0.06))}px ${FONT_STACK}`;
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
ctx.fillText('图片位', l.x + l.w / 2, l.y + l.h / 2);
ctx.textBaseline = 'alphabetic';
}
ctx.restore();
return;
}
// 文字
ctx.font = fontStr(l);
ctx.fillStyle = l.color;
const lh = l.size * (l.lineHeight ?? 1.25);
const m = ctx.measureText('字');
const asc = (m as any).fontBoundingBoxAscent ?? l.size * 0.8;
const desc = (m as any).fontBoundingBoxDescent ?? l.size * 0.2;
const lines = linesOf(l);
ctx.save();
if (l.rot) rotAround(ctx, l.x + l.w / 2, l.y + (lines.length * lh) / 2, l.rot);
ctx.textAlign = l.align === 'center' ? 'center' : l.align === 'right' ? 'right' : 'left';
const tx = l.align === 'center' ? l.x + l.w / 2 : l.align === 'right' ? l.x + l.w : l.x;
for (let i = 0; i < lines.length; i++) {
const y = l.y + i * lh + (lh - (asc + desc)) / 2 + asc;
if (l.shadow) {
ctx.shadowColor = l.shadow.color; ctx.shadowBlur = l.shadow.blur; ctx.shadowOffsetY = l.shadow.y;
} else {
ctx.shadowColor = 'transparent'; ctx.shadowBlur = 0; ctx.shadowOffsetY = 0;
}
ctx.fillText(lines[i], tx, y);
}
ctx.restore();
}
async function exportPng() {
exporting.value = true; pmError.value = '';
try {
const c = document.createElement('canvas');
c.width = POSTER_W; c.height = POSTER_H;
const ctx = c.getContext('2d')!;
drawBg(ctx, bg.value);
for (const l of layers.value) await drawLayer(ctx, l);
const blob: Blob | null = await new Promise((res) => c.toBlob(res, 'image/png'));
if (!blob) throw new Error('画布导出失败');
const a = document.createElement('a');
a.href = URL.createObjectURL(blob);
a.download = `${cur.value?.name || '海报'}.png`;
a.click();
setTimeout(() => URL.revokeObjectURL(a.href), 8000);
// 同步保存到服务器后台存储目录(后台「存储设置」的 gen_images),失败不阻断下载
try {
const b64 = await new Promise<string>((res, rej) => {
const fr = new FileReader();
fr.onload = () => res(String(fr.result || ''));
fr.onerror = () => rej(new Error('读取失败'));
fr.readAsDataURL(blob);
});
await fetch('/relay/ai/img-save', {
method: 'POST',
headers: { 'Content-Type': 'application/json', ...licenseHeaders('poster-maker'), ...authHdr() },
body: JSON.stringify({ machine: getMachineId(), b64, kind: 'poster', model: 'AI海报', prompt: cur.value?.name || '海报导出' }),
});
loadHist();
} catch { /* 保存失败不影响本地下载 */ }
} catch (err: any) {
pmError.value = '导出失败:' + (err?.message || String(err));
} finally {
exporting.value = false;
}
}
onMounted(async () => {
selectTemplate(POSTER_TEMPLATES[0]);
loadHist();
measure();
fit();
ro = new ResizeObserver(fit);
if (stageEl.value) ro.observe(stageEl.value);
const sc = pmRoot.value?.closest('.n-layout-scroll-container');
if (sc) { scRO = new ResizeObserver(measure); scRO.observe(sc); }
window.addEventListener('resize', measure);
window.addEventListener('focus', measure);
document.addEventListener('visibilitychange', measure);
// 头部字体/公告条加载完高度会微变,延迟复测两次
setTimeout(measure, 400);
setTimeout(measure, 1500);
try {
const res = await fetch('/relay/ai/image-models', { headers: licenseHeaders('poster-maker') });
const j = await res.json().catch(() => ({}) as any);
if (res.ok && j.code === 200 && Array.isArray(j.data)) {
models.value = j.data;
model.value = j.data[0]?.id ?? '';
}
} catch { /* 模型列表拉取失败时用默认空值 */ }
});
onBeforeUnmount(() => {
ro?.disconnect();
scRO?.disconnect();
window.removeEventListener('resize', measure);
window.removeEventListener('focus', measure);
document.removeEventListener('visibilitychange', measure);
onUp();
});
</script>
<template>
<div ref="pmRoot" class="pm-root" :style="pmH ? { height: pmH + 'px' } : undefined">
<div class="pm-top">
<div class="pm-cats">
<button
v-for="c in POSTER_CATS" :key="c.id"
class="pm-cat" :class="{ on: cat === c.id }"
@click="cat = c.id"
>{{ c.name }}</button>
</div>
<div class="pm-actions">
<button class="pm-btn" @click="addText">+ 文字</button>
<button class="pm-btn" @click="addImage">+ 图片框</button>
<button class="pm-btn" @click="resetTpl">重置模板</button>
<button class="pm-btn primary" :disabled="exporting" @click="exportPng">
{{ exporting ? '导出中…' : '⬇ 下载 PNG' }}
</button>
</div>
</div>
<div v-if="pmError" class="pm-error">{{ pmError }}</div>
<div class="pm-main">
<!-- 左:模板库 -->
<aside class="pm-tpls">
<div class="pm-sec-title">海报模板({{ filtered.length }})</div>
<div class="pm-tpl-grid">
<div
v-for="t in filtered" :key="t.id"
class="pm-tpl-card" :class="{ on: tplId === t.id }"
@click="selectTemplate(t)"
>
<div class="pm-mini" :style="{ width: MINI_W + 'px', height: Math.round(MINI_W * POSTER_H / POSTER_W) + 'px' }">
<div
class="pm-mini-in"
:style="{ width: POSTER_W + 'px', height: POSTER_H + 'px', transform: `scale(${MINI_W / POSTER_W})`, background: bgCss(t.bg) }"
>
<template v-for="(l, i) in tplLayers(t)" :key="i">
<div v-if="l.type === 'shape'" class="pm-layer" :style="miniBoxStyle(l)">
<div class="pm-shape" :style="shapeStyle(l)"></div>
</div>
<div v-else-if="l.type === 'image'" class="pm-layer" :style="miniBoxStyle(l)">
<img v-if="l.src" :src="l.src" class="pm-img" draggable="false" />
<div v-else class="pm-img pm-ph">📷</div>
</div>
<div v-else class="pm-layer" :style="miniBoxStyle(l)">
<div :style="fontStyle(l)"><div v-for="(ln, li) in linesOf(l)" :key="li">{{ ln || '\u00a0' }}</div></div>
</div>
</template>
</div>
</div>
<div class="pm-tpl-name">{{ t.name }}</div>
</div>
</div>
</aside>
<!-- 中:画布 -->
<section class="pm-stage" ref="stageEl" @click.self="selId = ''">
<div
class="pm-frame"
:style="{ width: POSTER_W * scale + 'px', height: POSTER_H * scale + 'px' }"
>
<div
class="pm-canvas"
:style="{ width: POSTER_W + 'px', height: POSTER_H + 'px', transform: `scale(${scale})`, background: bgCss(bg) }"
@click.self="selId = ''"
>
<div
v-for="l in layers" :key="l.id"
class="pm-layer" :class="{ sel: selId === l.id }"
:style="boxStyle(l)"
@pointerdown.stop="onDown($event, l)"
>
<div v-if="l.type === 'text'" :style="fontStyle(l)">
<div v-for="(ln, i) in linesOf(l)" :key="i">{{ ln || '\u00a0' }}</div>
</div>
<template v-else-if="l.type === 'image'">
<img v-if="l.src" :src="l.src" class="pm-img" draggable="false" />
<div v-else class="pm-img pm-ph">📷 点击右侧替换图片</div>
</template>
<div v-else class="pm-shape" :style="shapeStyle(l)"></div>
</div>
</div>
</div>
</section>
<!-- 右:编辑面板 -->
<aside class="pm-panel">
<div class="pm-sec">
<div class="pm-sec-title">背景</div>
<div class="pm-bgs">
<button
v-for="p in BG_PRESETS" :key="p.name"
class="pm-bg-sw" :style="{ background: bgCss(p.bg) }"
:title="p.name"
@click="bg = JSON.parse(JSON.stringify(p.bg))"
></button>
</div>
<div class="pm-row">
<input v-model="bgPrompt" class="pm-input" placeholder="AI 背景描述,如:蓝色科技感海报背景" />
</div>
<button class="pm-btn wide" :disabled="genBusy" @click="genBg">
{{ genBusy ? '生成中…' : '✨ AI 生成背景' }}
</button>
</div>
<div class="pm-sec">
<div class="pm-sec-title">图层(上层在前)</div>
<div class="pm-layers">
<div
v-for="l in [...layers].reverse()" :key="l.id"
class="pm-li" :class="{ on: selId === l.id }"
@click="selId = l.id"
>
<span class="pm-li-ico">{{ l.type === 'text' ? 'T' : l.type === 'image' ? '🖼' : '■' }}</span>
<span class="pm-li-name">{{ l.type === 'text' ? (l.text || '文字').slice(0, 10) : l.type === 'image' ? '图片' : (l.shape === 'ellipse' ? '圆形色块' : '矩形色块') }}</span>
<span class="pm-li-ops" @click.stop>
<button title="上移" @click.stop="selId = l.id; moveLayer(1)">▲</button>
<button title="下移" @click.stop="selId = l.id; moveLayer(-1)">▼</button>
<button title="删除" @click.stop="selId = l.id; delSel()">✕</button>
</span>
</div>
</div>
</div>
<div v-if="sel" class="pm-sec">
<div class="pm-sec-title">编辑「{{ selName }}」</div>
<div class="pm-row">
<label>旋转</label>
<input :value="sel.rot ?? 0" type="range" min="-180" max="180" step="1" @input="onRot" />
<span>{{ sel.rot ?? 0 }}°</span>
<button class="pm-mini-btn" @click="sel.rot = 0">复位</button>
</div>
<template v-if="sel.type === 'text'">
<textarea v-model="sel.text" class="pm-input ta" rows="3" placeholder="文字内容,支持换行"></textarea>
<div class="pm-row">
<label>字号</label>
<input v-model.number="sel.size" type="range" min="20" max="240" />
<span>{{ sel.size }}</span>
</div>
<div class="pm-row">
<label>颜色</label>
<input v-model="sel.color" type="color" class="pm-color" />
<label class="chk"><input v-model="sel.italic" type="checkbox" /> 斜体</label>
</div>
<div class="pm-row">
<label>粗细</label>
<select v-model.number="sel.weight" class="pm-sel">
<option :value="400">常规</option>
<option :value="700">加粗</option>
<option :value="900">特粗</option>
</select>
<label>行高</label>
<input v-model.number="sel.lineHeight" type="range" min="1" max="2" step="0.05" />
</div>
<div class="pm-row">
<label>对齐</label>
<button class="pm-mini-btn" :class="{ on: sel.align === 'left' }" @click="sel.align = 'left'">左</button>
<button class="pm-mini-btn" :class="{ on: sel.align === 'center' }" @click="sel.align = 'center'">中</button>
<button class="pm-mini-btn" :class="{ on: sel.align === 'right' }" @click="sel.align = 'right'">右</button>
</div>
</template>
<template v-else-if="sel.type === 'image'">
<textarea v-model="sel.prompt" class="pm-input ta" rows="3" placeholder="AI 生成的图片描述"></textarea>
<div class="pm-row" v-if="models.length">
<label>模型</label>
<select v-model="model" class="pm-sel">
<option v-for="m in models" :key="m.id" :value="m.id">{{ m.name || m.id }}</option>
</select>
</div>
<button class="pm-btn wide" :disabled="genBusy" @click="genFor(sel)">
{{ genBusy ? '生成中…(约 10-30 秒)' : '✨ AI 生成图片' }}
</button>
<div class="pm-row gap">
<button class="pm-btn" @click="pickFile">📁 上传图片</button>
<button class="pm-btn" :disabled="!sel.src" @click="clearImg">清除图片</button>
</div>
<div class="pm-row">
<label>圆角</label>
<input v-model.number="sel.radius" type="range" min="0" max="360" />
</div>
<input ref="fileEl" type="file" accept="image/*" class="pm-hidden" @change="onFile" />
</template>
<template v-else>
<div class="pm-row">
<label>颜色</label>
<input :value="sel.fill" type="color" class="pm-color" @input="onFill" />
<label class="chk"><input v-model.number="sel.opacity" type="range" min="0.1" max="1" step="0.05" /> 透明</label>
</div>
<div class="pm-row" v-if="sel.shape === 'rect'">
<label>圆角</label>
<input v-model.number="sel.radius" type="range" min="0" :max="Math.min(sel.w, sel.h) / 2" />
</div>
</template>
</div>
<div v-else class="pm-tip">点击画布中的元素进行编辑,拖动可移动位置;右侧图层可排序、删除。</div>
</aside>
<!-- 最右:生成历史(50×50 缩略图竖排,点击查看大图) -->
<aside class="pm-hist">
<div class="pm-hist-t">历史<em v-if="hist.length">{{ hist.length }}</em></div>
<div v-if="hist.length" class="pm-hist-list">
<img
v-for="it in hist" :key="it.id"
class="pm-hist-thumb"
:src="it.img_url"
:title="it.prompt || '点击查看大图'"
@click="histView = it.img_url"
/>
</div>
<div v-else class="pm-hist-empty">还没有<br />生成记录</div>
</aside>
</div>
<!-- 大图查看 -->
<div v-if="histView" class="pm-hist-view" @click="histView = ''">
<img :src="histView" alt="生成图片大图" />
</div>
</div>
</template>
<style scoped>
.pm-root { display: flex; flex-direction: column; gap: 10px; padding: 12px; box-sizing: border-box; height: 100%; overflow: hidden; }
.pm-top { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; justify-content: space-between; flex-shrink: 0; }
.pm-cats { display: flex; flex-wrap: wrap; gap: 6px; }
.pm-cat { padding: 5px 12px; border-radius: 14px; border: 1px solid var(--n-border-color, #d9d9d9); background: transparent; color: inherit; cursor: pointer; font-size: 13px; }
.pm-cat.on { background: #3b82f6; border-color: #3b82f6; color: #fff; }
.pm-actions { display: flex; gap: 6px; flex-wrap: wrap; }
.pm-btn { padding: 6px 12px; border-radius: 8px; border: 1px solid var(--n-border-color, #d9d9d9); background: var(--n-action-color, #fff); color: inherit; cursor: pointer; font-size: 13px; }
.pm-btn:hover { border-color: #3b82f6; color: #3b82f6; }
.pm-btn.primary { background: #3b82f6; border-color: #3b82f6; color: #fff; }
.pm-btn.primary:hover { background: #2563eb; color: #fff; }
.pm-btn.wide { width: 100%; margin-top: 6px; }
.pm-btn:disabled { opacity: .55; cursor: not-allowed; }
.pm-error { flex-shrink: 0; padding: 8px 12px; border-radius: 8px; background: #fef2f2; border: 1px solid #fecaca; color: #dc2626; font-size: 13px; }
.pm-main { display: flex; gap: 12px; align-items: stretch; flex: 1; min-height: 0; }
/* 模板库 */
.pm-tpls { width: 292px; flex-shrink: 0; min-height: 0; overflow-y: auto; overflow-x: hidden; }
.pm-sec-title { font-size: 13px; font-weight: 700; opacity: .75; margin-bottom: 8px; }
.pm-tpl-grid { display: grid; grid-template-columns: repeat(2, 1fr); gap: 10px; }
.pm-tpl-card { border: 2px solid transparent; border-radius: 10px; padding: 6px; cursor: pointer; background: rgba(127,127,127,.07); }
.pm-tpl-card:hover { border-color: rgba(59,130,246,.4); }
.pm-tpl-card.on { border-color: #3b82f6; background: rgba(59,130,246,.10); }
.pm-mini { position: relative; overflow: hidden; border-radius: 6px; margin: 0 auto; }
.pm-mini-in { position: relative; transform-origin: 0 0; }
.pm-tpl-name { font-size: 12px; text-align: center; margin-top: 4px; }
/* 画布 */
.pm-stage { flex: 1; min-width: 0; min-height: 0; display: flex; justify-content: center; overflow: auto; padding-bottom: 8px; }
.pm-frame { position: relative; flex-shrink: 0; box-shadow: 0 6px 24px rgba(0,0,0,.18); border-radius: 4px; overflow: hidden; }
.pm-canvas { position: absolute; left: 0; top: 0; transform-origin: 0 0; overflow: hidden; }
.pm-layer { position: absolute; box-sizing: border-box; user-select: none; -webkit-user-select: none; touch-action: none; }
.pm-layer.sel { outline: 3px dashed #3b82f6; outline-offset: 2px; }
.pm-img { width: 100%; height: 100%; object-fit: cover; display: block; pointer-events: none; }
.pm-ph { display: flex; align-items: center; justify-content: center; background: rgba(127,127,127,.14); border: 2px dashed rgba(127,127,127,.5); color: rgba(127,127,127,.9); font-size: 26px; text-align: center; box-sizing: border-box; }
.pm-shape { width: 100%; height: 100%; pointer-events: none; }
.pm-mini .pm-ph { font-size: 40px; }
/* 面板 */
.pm-panel { width: 316px; flex-shrink: 0; min-height: 0; overflow-y: auto; display: flex; flex-direction: column; gap: 14px; }
/* 生成历史(右栏 76px,50×50 缩略图竖排) */
.pm-hist { width: 76px; flex-shrink: 0; min-height: 0; display: flex; flex-direction: column; gap: 6px; }
.pm-hist-t { font-size: 12px; font-weight: 700; opacity: .75; text-align: center; }
.pm-hist-t em { font-style: normal; color: #3b82f6; margin-left: 3px; }
.pm-hist-list { flex: 1; min-height: 0; overflow-y: auto; display: flex; flex-direction: column; align-items: center; gap: 6px; padding-bottom: 8px; }
.pm-hist-thumb { width: 50px; height: 50px; object-fit: cover; border-radius: 8px; cursor: zoom-in; border: 2px solid transparent; background: rgba(127,127,127,.12); flex-shrink: 0; transition: border-color .15s; }
.pm-hist-thumb:hover { border-color: #3b82f6; }
.pm-hist-empty { font-size: 11px; opacity: .55; text-align: center; line-height: 1.6; padding-top: 10px; }
.pm-hist-view { position: fixed; inset: 0; z-index: 9999; background: rgba(0,0,0,.78); display: flex; align-items: center; justify-content: center; cursor: zoom-out; padding: 24px; }
.pm-hist-view img { max-width: 92vw; max-height: 92vh; object-fit: contain; border-radius: 8px; background: #fff; box-shadow: 0 10px 40px rgba(0,0,0,.4); }
.pm-sec { padding: 10px 12px; border: 1px solid var(--n-border-color, #e5e5e5); border-radius: 10px; background: rgba(127,127,127,.04); }
.pm-bgs { display: grid; grid-template-columns: repeat(8, 1fr); gap: 6px; }
.pm-bg-sw { height: 26px; border-radius: 6px; border: 1px solid rgba(127,127,127,.35); cursor: pointer; }
.pm-row { display: flex; align-items: center; gap: 8px; margin-top: 8px; font-size: 13px; flex-wrap: wrap; }
.pm-row.gap { gap: 10px; }
.pm-row label { opacity: .8; white-space: nowrap; }
.pm-input { width: 100%; box-sizing: border-box; margin-top: 8px; padding: 6px 8px; border-radius: 6px; border: 1px solid var(--n-border-color, #d9d9d9); background: var(--n-action-color, #fff); color: inherit; font-size: 13px; }
.pm-input.ta { resize: vertical; font-family: inherit; }
.pm-input:focus { outline: none; border-color: #3b82f6; }
.pm-color { width: 44px; height: 28px; padding: 0; border: 1px solid rgba(127,127,127,.35); border-radius: 6px; background: transparent; cursor: pointer; }
.pm-sel { padding: 4px 6px; border-radius: 6px; border: 1px solid var(--n-border-color, #d9d9d9); background: var(--n-action-color, #fff); color: inherit; font-size: 13px; }
.pm-mini-btn { padding: 3px 10px; border-radius: 6px; border: 1px solid var(--n-border-color, #d9d9d9); background: transparent; color: inherit; cursor: pointer; font-size: 13px; }
.pm-mini-btn.on { background: #3b82f6; border-color: #3b82f6; color: #fff; }
.chk { display: inline-flex; align-items: center; gap: 4px; }
.pm-layers { display: flex; flex-direction: column; gap: 4px; max-height: 190px; overflow: auto; }
.pm-li { display: flex; align-items: center; gap: 6px; padding: 5px 8px; border-radius: 6px; border: 1px solid transparent; cursor: pointer; font-size: 13px; background: rgba(127,127,127,.06); }
.pm-li.on { border-color: #3b82f6; background: rgba(59,130,246,.12); }
.pm-li-name { flex: 1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.pm-li-ops { display: inline-flex; gap: 2px; }
.pm-li-ops button { border: none; background: transparent; cursor: pointer; color: inherit; padding: 2px 4px; font-size: 12px; border-radius: 4px; }
.pm-li-ops button:hover { background: rgba(127,127,127,.2); }
.pm-tip { font-size: 13px; opacity: .65; line-height: 1.7; padding: 8px 4px; }
.pm-hidden { display: none; }
@media (max-width: 1180px) {
.pm-main { flex-direction: column; overflow-y: auto; }
.pm-tpls, .pm-panel { width: 100%; max-height: none; overflow: visible; }
.pm-stage { flex: none; height: 56vh; }
.pm-tpl-grid { grid-template-columns: repeat(4, 1fr); }
/* 窄屏:历史栏改为横排(缩略图仍 50×50) */
.pm-hist { width: 100%; flex-direction: row; align-items: center; gap: 8px; }
.pm-hist-t { flex-shrink: 0; }
.pm-hist-list { flex-direction: row; overflow-x: auto; overflow-y: hidden; padding-bottom: 0; }
}
</style>