/**
* box.js — 3D 云设计编辑器(纸盒)主逻辑
* 全面对标包小盒设计器:盒型库 / 模板 / 素材 / 文字 / 工具(条码·二维码) / 上传 / 图层 / 帮助
* 2D刀版画布 + 3D预览动效 / 智能参数宝 / 导出(设计文件·效果图·视频) / 印刷下单
*/
(function () {
const D = window.PL.data;
const R = window.PL.render;
const UI = window.PL.ui;
const h = UI.h;
const A = UI.antd;
const LB = window.PL.boxlib;
const QR = window.PL.qrcode;
const KEY = 'pouchlab.box.v2';
const LIST_KEY = 'pouchlab.box.plans';
const HIST_KEY = 'pouchlab.box.history';
const $ = function (sel) { return document.querySelector(sel); };
const clamp = function (v, a, b) { return Math.min(b, Math.max(a, v)); };
function BoxTextField(props) {
const [val, setVal] = React.useState(props.value == null ? '' : String(props.value));
React.useEffect(function () { setVal(props.value == null ? '' : String(props.value)); }, [props.value]);
return h(A.Input, {
value: val,
placeholder: props.placeholder,
onChange: function (e) { setVal(e.target.value); if (props.onInput) props.onInput(e.target.value); },
onBlur: function () { if (props.onCommit) props.onCommit(); }
});
}
const FACES = [
{ id: 'front', name: '前面' }, { id: 'right', name: '右面' }, { id: 'back', name: '背面' },
{ id: 'left', name: '左面' }, { id: 'top', name: '顶面' }, { id: 'bottom', name: '底面' }
];
/* 材质(对标包小盒「350g白卡(0.5mm)」命名) */
const MATERIALS = [
{ id: 'card', name: '350g白卡(0.5mm)', thickness: 0.5, rate: 2.1, desc: '挺括细腻,适合彩印', paper: '#fbf7ee', paperEdge: '#e6ddcc', edgeW: 1, matte: false, grain: '', grainOpacity: 0, flute: '#e2d8c5' },
{ id: 'grey', name: '灰板2mm', thickness: 2.0, rate: 5.4, desc: '硬挺,适合精装礼盒', paper: '#c9c1b2', paperEdge: '#8f877a', edgeW: 4, matte: true, grainOpacity: 0.5, grain: '', flute: '#b3aa9a' },
{ id: 'kraft', name: '牛皮纸(0.4mm)', thickness: 0.4, rate: 2.6, desc: '自然原色,环保质感', paper: '#d7b17c', paperEdge: '#a97c4e', edgeW: 2, matte: true, grainOpacity: 0.75, grain: '', flute: '#b98a56' },
{ id: 'corrugated', name: 'E楞瓦楞(1.5mm)', thickness: 1.5, rate: 3.4, desc: '缓冲抗压,电商发货', paper: '#d3aa74', paperEdge: '#a97c4e', edgeW: 3, matte: true, grainOpacity: 0.85, grain: '', flute: '#a97c4e', edgePattern: true }
];
/* 印色(对标包小盒印刷报价:四色/四色+1专/四色+2专/不印刷) */
const PRINTS = [
{ id: 'cmyk', name: '四色', factor: 1 },
{ id: 'cmyk1', name: '四色+1专', factor: 1.18 },
{ id: 'cmyk2', name: '四色+2专', factor: 1.36 },
{ id: 'none', name: '不印刷', factor: 0.34 }
];
const PRINT_WAYS = ['胶印合版', '胶印专版', '数码印刷'];
/* 结构元数据 + 智能参数宝高级参数 */
const STRUCTS = {
carton: { name: '卡纸折叠盒', en: 'FOLDING CARTON', fee: 0.35, advanced: ['glue'] },
rsc: { name: '平口箱', en: 'REGULAR SLOTTED CONTAINER', fee: 0.3, advanced: ['glue'] },
tuck: { name: '反向插锁盒', en: 'REVERSE TUCK END', fee: 0.5, advanced: ['glue', 'tuckH', 'cornerR'] },
straight: { name: '直插盒', en: 'STRAIGHT TUCK END', fee: 0.5, advanced: ['glue', 'tuckH', 'cornerR'] },
autobottom: { name: '扣底盒', en: 'AUTO-LOCK BOTTOM', fee: 0.55, advanced: ['glue', 'cornerR'] },
mailbox: { name: '磁吸书型盒', en: 'MAGNETIC BOOK BOX', fee: 1.6, advanced: ['lipW'] },
mailer: { name: '飞机盒', en: 'MAILER BOX', fee: 0.7, advanced: ['tuckH', 'dustW'] },
drawer: { name: '抽屉盒', en: 'DRAWER BOX', fee: 1.1, advanced: [] },
bag: { name: '手提袋', en: 'PAPER BAG', fee: 0.9, advanced: ['topFold', 'holeR'] },
sleeve: { name: '封套', en: 'SLEEVE', fee: 0.4, advanced: ['glue'] },
card: { name: '卡牌/吊牌/标签', en: 'CARD & TAG', fee: 0.12, advanced: ['cornerR', 'holeR'] }
};
const ADV_FIELDS = {
glue: { key: 'glue', code: 'G', name: '糊口长', unit: 'mm', min: 8, max: 40 },
tuckH: { key: 'tuckH', code: 'C', name: '插舌长', unit: 'mm', min: 6, max: 24 },
cornerR: { key: 'cornerR', code: 'R', name: '倒角', unit: 'mm', min: 0, max: 8, step: 0.1 },
dustW: { key: 'dustW', code: 'AX', name: '槽口宽', unit: 'mm', min: 8, max: 24 },
lipW: { key: 'lipW', code: 'OF', name: '沿口宽', unit: 'mm', min: 8, max: 30 },
topFold: { key: 'topFold', code: 'A', name: '顶折边', unit: 'mm', min: 12, max: 40 },
holeR: { key: 'holeR', code: 'E', name: '孔半径', unit: 'mm', min: 2, max: 8, step: 0.5 }
};
/* ---------------- 状态 ---------------- */
function blankFaces() {
const o = {};
['outer', 'inner'].forEach(function (side) {
o[side] = {};
FACES.forEach(function (f) { o[side][f.id] = { color: '', texture: null, items: [] }; });
});
return o;
}
const state = {
planId: 'p' + Date.now().toString(36),
name: '未命名纸盒',
boxNo: '100010',
structure: 'tuck',
material: 'card',
print: 'cmyk',
printWay: '胶印合版',
w: 120, d: 80, h: 180,
qty: 1000,
smart: { bleed: 3, glue: 15, tuckH: 12, cornerR: 1.5, dustW: 14, lipW: 16, topFold: 22, holeR: 4 },
side: 'outer',
faces: blankFaces(),
selectedFace: 'front',
selectedItemId: null,
mode: '2d',
showLines: true,
autoRotate: false,
uploads: [],
view2d: { zoom: 0.6, panX: 0, panY: 0, preview: false }
};
try {
const saved = JSON.parse(localStorage.getItem(KEY) || 'null');
if (saved && saved.faces) {
Object.assign(state, saved);
const f = blankFaces();
['outer', 'inner'].forEach(function (side) {
FACES.forEach(function (face) {
const src = (saved.faces[side] && saved.faces[side][face.id]) || (side === 'outer' && saved.faces[face.id]) || {};
const dst = f[side][face.id];
dst.color = src.color || '';
dst.texture = src.texture || null;
let items = Array.isArray(src.items) ? src.items.slice() : [];
(src.texts || []).forEach(function (t) { items.push(Object.assign({ type: 'text' }, t)); });
if (src.image) items.push(Object.assign({ type: 'image' }, src.image));
dst.items = items;
});
});
state.faces = f;
if (!Array.isArray(state.uploads)) state.uploads = [];
}
} catch (e) {}
/* AI 设计师(首页 Agent)交接:应用其生成的盒子方案(外侧 6 面) */
try {
const rawH = localStorage.getItem('pouchlab.agent.handoff');
if (rawH) {
localStorage.removeItem('pouchlab.agent.handoff');
const h = JSON.parse(rawH);
const s = h && h.state;
if (s && s.kind === 'box' && s.box) {
const b = s.box;
if (b.structure && STRUCTS[b.structure]) state.structure = b.structure;
if (b.w) { state.w = b.w; state.d = b.d; state.h = b.h; }
if (b.material) state.material = b.material;
if (b.qty) state.qty = b.qty;
state.side = 'outer';
if (b.faces) {
FACES.forEach(function (face) {
const rd = b.faces[face.id];
const fd = state.faces.outer[face.id];
if (!rd) return;
fd.color = rd.color || fd.color;
fd.items = (rd.items || []).map(function (it) {
it.id = 'i' + Date.now().toString(36) + Math.random().toString(36).slice(2, 5);
return it;
});
});
}
setTimeout(function () { UI.message.success('已载入 AI 设计师整套方案,可继续微调'); }, 700);
}
}
} catch (e) {}
function material() { return MATERIALS.find(function (m) { return m.id === state.material; }) || MATERIALS[0]; }
function print() { return PRINTS.find(function (p) { return p.id === state.print; }) || PRINTS[0]; }
function struct() { return STRUCTS[state.structure] || STRUCTS.tuck; }
function libEntry() { return LB.boxById(state.boxNo) || LB.BOXLIB[0]; }
function curFaces() { return state.faces[state.side]; }
function curFace() { return curFaces()[state.selectedFace]; }
/* ---------------- 撤销 / 重做 ---------------- */
const undoStack = [], redoStack = [];
let suspending = false;
function snapshot() { return JSON.stringify({ name: state.name, boxNo: state.boxNo, structure: state.structure, material: state.material, print: state.print, printWay: state.printWay, w: state.w, d: state.d, h: state.h, qty: state.qty, smart: state.smart, faces: state.faces }); }
function pushUndo() {
if (suspending) return;
undoStack.push(snapshot());
if (undoStack.length > 60) undoStack.shift();
redoStack.length = 0;
updateHistoryBtns();
}
function restore(str) {
suspending = true;
const data = JSON.parse(str);
Object.assign(state, data);
const f = blankFaces();
['outer', 'inner'].forEach(function (side) {
FACES.forEach(function (face) {
const src = (data.faces[side] && data.faces[side][face.id]) || {};
f[side][face.id] = { color: src.color || '', texture: src.texture || null, items: src.items || [] };
});
});
state.faces = f;
suspending = false;
commit(false);
}
function undo() {
if (!undoStack.length) return;
redoStack.push(snapshot());
restore(undoStack.pop());
updateHistoryBtns();
}
function redo() {
if (!redoStack.length) return;
undoStack.push(snapshot());
restore(redoStack.pop());
updateHistoryBtns();
}
function updateHistoryBtns() {
$('#bxUndoBtn').disabled = !undoStack.length;
$('#bxRedoBtn').disabled = !redoStack.length;
}
/* ---------------- 刀版生成 ---------------- */
function rect(x, y, w, hh, face, kind) { return { x: x, y: y, w: w, h: hh, face: face, kind: kind || 'body' }; }
function poly(points, face, kind) {
return { poly: points, face: face, kind: kind || 'flap', x: Math.min.apply(null, points.map(function (p) { return p[0]; })), y: Math.min.apply(null, points.map(function (p) { return p[1]; })), w: 0, h: 0 };
}
function panelBounds(p) {
if (!p.poly) return { x: p.x, y: p.y, w: p.w, h: p.h };
const xs = p.poly.map(function (pt) { return pt[0]; });
const ys = p.poly.map(function (pt) { return pt[1]; });
const x = Math.min.apply(null, xs), y = Math.min.apply(null, ys);
return { x: x, y: y, w: Math.max.apply(null, xs) - x, h: Math.max.apply(null, ys) - y };
}
const ACCESSORY = { glue: 1, flap: 1, dust: 1, tuck: 1, lip: 1 };
function isBodyKind(k) { return !ACCESSORY[k]; }
function panelEdges(p) {
const pts = p.poly || [[p.x, p.y], [p.x + p.w, p.y], [p.x + p.w, p.y + p.h], [p.x, p.y + p.h]];
const out = [];
for (let i = 0; i < pts.length; i += 1) {
const a = pts[i], b = pts[(i + 1) % pts.length];
if (Math.abs(a[0] - b[0]) < 0.05) out.push({ axis: 'v', c: a[0], lo: Math.min(a[1], b[1]), hi: Math.max(a[1], b[1]) });
else if (Math.abs(a[1] - b[1]) < 0.05) out.push({ axis: 'h', c: a[1], lo: Math.min(a[0], b[0]), hi: Math.max(a[0], b[0]) });
}
return out;
}
function sharedEdge(a, b) {
let best = null;
panelEdges(a).forEach(function (ea) {
panelEdges(b).forEach(function (eb) {
if (ea.axis !== eb.axis || Math.abs(ea.c - eb.c) > 0.6) return;
const lo = Math.max(ea.lo, eb.lo), hi = Math.min(ea.hi, eb.hi), len = hi - lo;
if (len <= 2) return;
if (!best || len > best.len) best = { axis: ea.axis, c: ea.c, lo: lo, hi: hi, len: len };
});
});
return best;
}
function canHinge(a, b) {
const ka = a.kind || 'body', kb = b.kind || 'body';
if (isBodyKind(ka) !== isBodyKind(kb)) return true;
if (isBodyKind(ka) && isBodyKind(kb)) return true;
return (ka === 'tuck' && kb === 'flap') || (ka === 'flap' && kb === 'tuck');
}
function autoFolds(panels) {
const out = [];
for (let i = 0; i < panels.length; i += 1) for (let j = i + 1; j < panels.length; j += 1) {
if (!canHinge(panels[i], panels[j])) continue;
const e = sharedEdge(panels[i], panels[j]);
if (!e) continue;
if (e.axis === 'v') out.push({ x1: e.c, y1: e.lo, x2: e.c, y2: e.hi });
else out.push({ x1: e.lo, y1: e.c, x2: e.hi, y2: e.c });
}
return out;
}
function finishDieline(panels) {
let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity;
panels.forEach(function (p) {
const b = panelBounds(p);
minX = Math.min(minX, b.x); minY = Math.min(minY, b.y);
maxX = Math.max(maxX, b.x + b.w); maxY = Math.max(maxY, b.y + b.h);
});
return { panels: panels, folds: autoFolds(panels), size: { w: maxX - minX, h: maxY - minY }, minX: minX, minY: minY, bounds: { w: maxX - minX, h: maxY - minY, minX: minX, minY: minY } };
}
function roundedRectPoly(x, y, w, hh, r) {
r = Math.min(r, w / 2, hh / 2);
if (r <= 0.05) return [[x, y], [x + w, y], [x + w, y + hh], [x, y + hh]];
const pts = [];
const arc = function (cx, cy, a0, a1) {
for (let i = 0; i <= 6; i += 1) {
const a = a0 + (a1 - a0) * i / 6;
pts.push([cx + r * Math.cos(a), cy + r * Math.sin(a)]);
}
};
arc(x + w - r, y + r, -Math.PI / 2, 0);
arc(x + w - r, y + hh - r, 0, Math.PI / 2);
arc(x + r, y + hh - r, Math.PI / 2, Math.PI);
arc(x + r, y + r, Math.PI, Math.PI * 1.5);
return pts;
}
function circlePoly(cx, cy, r) {
const pts = [];
for (let i = 0; i < 36; i += 1) {
const a = i / 36 * Math.PI * 2;
pts.push([cx + r * Math.cos(a), cy + r * Math.sin(a)]);
}
return pts;
}
/* 刀版几何构建:共享 assets/js/boxdieline.js(与手机端 3D 预览同源,避免两份几何漂移) */
function buildDieline(type, w, d, hh, params) {
const P = Object.assign({ boxNo: state.boxNo }, params || state.smart);
return PL.boxDieline.build(type, w, d, hh, P, material());
}
function dieline() { return buildDieline(state.structure, state.w, state.d, state.h); }
function outerSize() {
const t = material().thickness;
return { w: state.w + t * 2, d: state.d + t * 2, h: state.h + t * 2 };
}
/* ---------------- 报价 ---------------- */
function priceInfo() {
const dl = dieline();
const area = (dl.size.w * dl.size.h) / 1000000;
const mat = material(), pr = print();
const base = area * mat.rate * pr.factor + struct().fee;
const qty = state.qty;
const disc = qty >= 10000 ? 0.72 : qty >= 5000 ? 0.78 : qty >= 2000 ? 0.84 : qty >= 1000 ? 0.9 : qty >= 500 ? 0.95 : 1;
const unit = base * disc;
return { area: area, unit: unit, total: unit * qty, disc: disc, dl: dl };
}
/* ---------------- 刀版 SVG ---------------- */
function faceName(id) {
const f = FACES.find(function (x) { return x.id === id; });
return f ? f.name : '';
}
function itemSvg(it, bx, by, bw, bh, mm2px) {
const cx = bx + (it.x / 100) * bw, cy = by + (it.y / 100) * bh;
if (it.hidden) return { art: '', hit: '' };
// 内侧版面整体镜像(相当于从背面看印刷面),元素随之翻转
function hitRect(x, y, w, h) {
return '';
}
if (it.type === 'text') {
const anchor = it.align === 'center' ? 'middle' : it.align === 'right' ? 'end' : 'start';
const lines = String(it.text || '').split('\n');
const fs = it.size * mm2px;
const lh = (it.lineHeight || 1.25) * fs;
let out = '', maxW = 0;
lines.forEach(function (line, li) {
const tw = String(line).split('').reduce(function (s, ch) { return s + (/[\x00-\xff]/.test(ch) ? 0.56 : 1) * fs; }, 0);
if (tw > maxW) maxW = tw;
out += '' + R.esc(line) + '';
});
maxW = Math.max(maxW, fs * 2);
const totalH = Math.max(lines.length * lh, fs);
const left = anchor === 'start' ? cx : anchor === 'end' ? cx - maxW : cx - maxW / 2;
return { art: out, hit: hitRect(left, cy - totalH / 2, maxW, totalH) };
}
if (it.type === 'image' || it.type === 'asset') {
const iw = ((it.w == null ? 60 : it.w) / 100) * bw;
return { art: '', hit: hitRect(cx - iw / 2, cy - iw / 2, iw, iw) };
}
if (it.type === 'barcode') {
const iw = ((it.w || 40) / 100) * bw;
const ih = iw * 0.84;
return { art: '', hit: hitRect(cx - iw / 2, cy - ih / 2, iw, ih) };
}
return { art: '', hit: '' };
}
function dielineSVG(opts) {
opts = opts || {};
const dl = dieline();
const mat = material();
const pad = 30;
const bleed = state.smart.bleed || 0;
const inner = state.side === 'inner';
const uid = opts.idPrefix || 'dl';
const vbW = dl.size.w + pad * 2 + bleed * 2;
const vbH = dl.size.h + pad * 2 + bleed * 2 + (opts.noLegend ? 0 : 56);
const off = function (x, y) { return [x - dl.minX + pad + bleed, y - dl.minY + pad + bleed]; };
let body = '', defs = '', art = '', hit = '', itemHits = '', notes = '';
const useMatPattern = state.material === 'corrugated' || state.material === 'kraft';
if (useMatPattern) {
defs += '' +
'' +
'';
}
const matFill = useMatPattern ? 'url(#' + uid + '-mat)' : mat.paper;
// 结构件(防尘翼/插舌/糊口等)不印刷:素纸色 + 45° 斜线纹理,与印刷面区分
defs += '' +
'' +
'';
dl.panels.forEach(function (p, i) {
const pts = p.poly ? p.poly.map(function (pt) { return off(pt[0], pt[1]); }) : [off(p.x, p.y), off(p.x + p.w, p.y), off(p.x + p.w, p.y + p.h), off(p.x, p.y + p.h)];
const cid = uid + '-p' + i;
const f = p.face ? curFaces()[p.face] : null;
const plain = curFaces()._plain || {};
const isAcc = ACCESSORY[p.kind] && !p.face; // 有 face 的面(如飞机盒顶/底盖)可印刷,不算结构件
let panelFill;
if (isAcc) {
panelFill = 'url(#' + uid + '-acc)';
} else if (f) {
panelFill = f.color || (f.texture ? 'url(#' + uid + '-tex' + i + ')' : matFill);
} else {
panelFill = plain.color || matFill;
}
if (f && f.texture) {
defs += '';
}
const points = pts.map(function (pt) { return pt[0].toFixed(2) + ',' + pt[1].toFixed(2); }).join(' ');
const shape = p.poly ? '' : '';
defs += '' + shape + '';
const picked = p.face && p.face === state.selectedFace ? ' is-picked' : '';
body += '';
if (p.holes) {
p.holes.forEach(function (ho, hi) {
const c = off(ho.x, ho.y);
art += '';
if (!opts.clean) {
// 圆心十字定位线(超出孔径 2.5mm)+ 孔径标注;标注放在镜像组外,避免文字反写
const ext = ho.r + 2.5;
const mx = inner ? vbW - c[0] : c[0];
notes += '' +
'' +
'' +
'' +
'' +
'Ø' + (ho.r * 2).toFixed(1) + ' 开孔';
}
});
}
if (p.face && f) {
const b = panelBounds(p);
(f.items || []).forEach(function (it) {
it._face = p.face;
const r = itemSvg(it, b.x, b.y, b.w, b.h, 1);
const tx = 'translate(' + (pad + bleed - dl.minX) + ',' + (pad + bleed - dl.minY) + ')';
art += '' + r.art + '';
itemHits += '' + r.hit + '';
});
const cx = off(b.x + b.w / 2, b.y + b.h / 2);
if (state.showLines && !opts.clean) notes += '' + faceName(p.face) + '';
hit += '';
}
});
let foldBody = '';
if (state.showLines && !opts.clean) {
dl.folds.forEach(function (f) {
const a = off(f.x1, f.y1), b = off(f.x2, f.y2);
foldBody += '';
});
}
let dims = '';
if (!opts.clean) {
const dimTop = pad, dimBottom = pad + dl.size.h;
dims =
'' +
'' + Math.round(dl.size.h) + ' mm' +
'' +
'' + Math.round(dl.size.w) + ' mm';
// 每个印刷面内标注该面的宽 × 高(mm);poly 面(梯形盖等)动态算外接框、文字置于底部
const FACE_NAMES = { front: '正面', back: '背面', left: '左', right: '右', top: '顶', bottom: '底' };
dl.panels.forEach(function (p) {
if (!p.face) return;
let bw = p.w, bh = p.h, bx = p.x, by = p.y;
if (p.poly) { // poly() 构造的 w/h 为 0,动态求外接框
let minX = 1e9, minY = 1e9, maxX = -1e9, maxY = -1e9;
p.poly.forEach(function (pt) {
minX = Math.min(minX, pt[0]); maxX = Math.max(maxX, pt[0]);
minY = Math.min(minY, pt[1]); maxY = Math.max(maxY, pt[1]);
});
bx = minX; by = minY; bw = maxX - minX; bh = maxY - minY;
}
if (!bw || !bh) return;
const cx = bx + bw / 2;
const isPoly = !!p.poly;
const fs = Math.max(4.2, Math.min(8, bw / 9));
const label = FACE_NAMES[p.face] ? FACE_NAMES[p.face] + ' ' : '';
const cy = isPoly ? by + bh - fs * 0.9 : by + bh / 2;
dims += '' + label + Math.round(bw) + ' × ' + Math.round(bh) + '';
});
if (bleed) {
dims += '';
}
}
const legend = opts.clean ? '' : '裁切线' +
'折叠线' +
'防尘翼/插舌(不印刷)' +
'' + (inner ? '内侧设计 · 镜像' : '外侧设计') + ' · 模型ID ' + state.boxNo + '';
const mirror = inner ? ' transform="translate(' + vbW + ',0) scale(-1,1)"' : '';
// 只有几何与画面内容参与镜像;文字标注、尺寸、图例放在镜像组外,保持可读
return '';
}
/* ---------------- 保存 / 方案 ---------------- */
function save(quiet) {
try {
localStorage.setItem(KEY, JSON.stringify(state));
if (!quiet) {
const el = $('#bxSaveState');
}
} catch (e) {
UI.message.warning('本地保存空间不足');
}
}
function plansList() {
try { return JSON.parse(localStorage.getItem(LIST_KEY) || '[]'); } catch (e) { return []; }
}
function savePlanToLibrary() {
const list = plansList().filter(function (p) { return p.id !== state.planId; });
list.unshift({ id: state.planId, name: state.name, time: Date.now(), boxNo: state.boxNo });
try { localStorage.setItem(LIST_KEY, JSON.stringify(list.slice(0, 30))); } catch (e) {}
}
function planDataKey(id) { return 'pouchlab.box.plan.' + id; }
function commit(pushHistory) {
if (pushHistory !== false) pushUndo();
save(true);
savePlanToLibrary();
try { localStorage.setItem(planDataKey(state.planId), JSON.stringify(state)); } catch (e) {}
// 历史版本
try {
const hk = HIST_KEY + '.' + state.planId;
const hist = JSON.parse(localStorage.getItem(hk) || '[]');
hist.unshift({ time: Date.now(), snap: snapshot() });
localStorage.setItem(hk, JSON.stringify(hist.slice(0, 20)));
} catch (e) {}
renderAll();
}
/* ---------------- 3D 实例 ---------------- */
let main3d = null, mini3d = null;
let foldValue = 0, foldAnim = null;
function currentPanels() { return dieline().panels; }
function render3d() {
if (main3d && main3d.ready()) {
main3d.render(state, material(), currentPanels());
main3d.setFold(foldValue / 100);
return;
}
render3dCss();
}
/* CSS 3D 降级(无 Three.js 时) */
function render3dCss() {
const box = document.getElementById('box3d');
if (!box) return;
const t = material().thickness;
const W = state.w + t * 2, D2 = state.d + t * 2, H = state.h + t * 2;
const s = Math.min(360 / (state.w + state.d), 400 / (state.h + state.d));
box.style.width = W * s + 'px';
box.style.height = H * s + 'px';
box.style.transform = 'rotateX(-18deg) rotateY(-32deg)';
let html = '';
const t2 = material().thickness;
const faceT = {
front: 'translateZ(' + D2 * s / 2 + 'px)',
back: 'rotateY(180deg) translateZ(' + D2 * s / 2 + 'px)',
right: 'rotateY(90deg) translateZ(' + W * s / 2 + 'px)',
left: 'rotateY(-90deg) translateZ(' + W * s / 2 + 'px)',
top: 'rotateX(90deg) translateZ(' + H * s / 2 + 'px)',
bottom: 'rotateX(-90deg) translateZ(' + H * s / 2 + 'px)'
};
FACES.forEach(function (f) {
const data = curFaces()[f.id];
const size = (f.id === 'front' || f.id === 'back') ? { w: W, h: H } : (f.id === 'left' || f.id === 'right') ? { w: D2, h: H } : { w: W, h: D2 };
const bg = 'background-color:' + (data.color || material().paper);
html += '
';
});
box.innerHTML = html;
}
function renderMini() {
if (mini3d && mini3d.ready() && state.mode === '2d') {
mini3d.render(state, material(), currentPanels());
mini3d.setFold(foldValue / 100);
}
}
/* ---------------- 视图切换 ---------------- */
function setMode(mode) {
state.mode = mode;
document.querySelectorAll('#bxModeSwitch button').forEach(function (b) {
b.classList.toggle('on', b.dataset.mode === mode);
});
$('#bxFlat').hidden = mode !== '2d';
$('#bx3dView').hidden = mode !== '3d';
renderAll();
}
/* ---------------- 2D 画布 ---------------- */
let panMode = false;
let panDrag = null;
function renderDieline() {
const wrap = document.getElementById('boxDieline');
if (!wrap) return;
wrap.innerHTML = dielineSVG();
const svg = wrap.querySelector('svg');
if (!svg) return;
const vb = svg.viewBox.baseVal;
svg.style.width = vb.width + 'px';
svg.style.height = vb.height + 'px';
svg.style.display = 'block';
const z = state.view2d.zoom;
wrap.style.transform = 'translate(' + state.view2d.panX + 'px,' + state.view2d.panY + 'px) scale(' + z + ')';
$('#bxZoom2dLabel').textContent = Math.round(z * 100) + ' %';
}
function fit2d() {
const stage = $('#bxFlat');
const dl = dieline();
// 窄屏下左右面板改为悬浮覆盖,需按可视区(扣除面板遮挡)居中,避免刀版被面板盖住
const stageRect = stage.getBoundingClientRect();
let occlL = 0, occlR = 0;
const panelEl = document.querySelector('.bx-panel');
const propsEl = document.querySelector('.bx-props');
if (panelEl && getComputedStyle(panelEl).position === 'absolute') {
occlL = Math.max(0, Math.min(stage.clientWidth, panelEl.getBoundingClientRect().right - stageRect.left));
}
if (propsEl && getComputedStyle(propsEl).position === 'absolute') {
occlR = Math.max(0, Math.min(stage.clientWidth - occlL, stageRect.right - propsEl.getBoundingClientRect().left));
}
const availW = Math.max(160, stage.clientWidth - occlL - occlR - 80);
const availH = Math.max(200, stage.clientHeight - 120);
state.view2d.zoom = clamp(Math.min(availW / dl.size.w, availH / dl.size.h), 0.1, 2.4);
state.view2d.panX = Math.round((occlL - occlR) / 2);
state.view2d.panY = 0;
renderDieline();
}
/* ---------------- 工具栏 / 面板 ---------------- */
let currentTab = 'box';
function assetThumb(a, color) {
if (a.svgDef) return '';
if (a.draw) return '
';
return '';
}
function assetFillSrc(item, color) {
if (item.draw) return LB.shapeDataUrl(item.draw, color, 160);
if (item.svgDef) return 'data:image/svg+xml;utf8,' + encodeURIComponent('');
const id = String(item.assetId || '').replace(/^icon:/, '');
const svg = id ? LB.assetSvg(id, color) : null;
return svg ? 'data:image/svg+xml;utf8,' + encodeURIComponent(svg) : null;
}
function addAssetToFace(item) {
const face = curFace();
face.items = face.items || [];
const it = Object.assign({ id: 'i' + Date.now().toString(36) + Math.random().toString(36).slice(2, 5), x: 50, y: 50, w: 45 }, item);
face.items.push(it);
state.selectedItemId = it.id;
UI.message.success('素材已添加到「' + faceName(state.selectedFace) + '」');
commit();
}
function panelBox() {
const tab = currentTab;
if (tab === 'box') return boxPanel();
if (tab === 'template') return templatePanel();
if (tab === 'asset') return assetPanel();
if (tab === 'text') return textPanel();
if (tab === 'tool') return toolPanel();
if (tab === 'upload') return uploadPanel();
if (tab === 'layers') return layersPanel();
if (tab === 'help') return helpPanel();
return null;
}
/* ---- 盒型面板 ---- */
let boxSearch = '', boxCat = '热门', boxMine = false;
function boxPanel() {
const cats = LB.BOX_CATS;
const list = LB.BOXLIB.filter(function (b) {
if (boxMine) return true;
if (boxSearch && b.name.indexOf(boxSearch) < 0 && b.no.indexOf(boxSearch) < 0) return false;
if (boxCat === '热门') return b.hot >= 3;
if (boxCat === '更多') return ['纸箱'].indexOf(b.cat) >= 0;
return b.cat === boxCat;
});
return h('div', null,
h('div', { className: 'bx-import-cad', onClick: function () { showImportCad(); } },
h('span', { className: 'cad-ic' }, 'DXF'),
h('div', null, h('b', null, '导入 CAD', h('i', { className: 'q', title: '上传盒型结构个性化设计' })), h('span', null, '上传盒型结构个性化设计'))
),
h(A.Input, {
prefix: h('span', { className: 'anticon' }, '🔍'),
placeholder: '输入盒型关键字', value: boxSearch, allowClear: true,
onChange: function (e) { boxSearch = e.target.value; renderTool(); }
}),
h('div', { className: 'bx-sub-tabs' },
h('button', { className: boxMine ? '' : 'on', onClick: function () { boxMine = false; renderTool(); } }, '推荐盒型'),
h('button', { className: boxMine ? 'on' : '', onClick: function () { boxMine = true; renderTool(); } }, '我的盒型')
),
boxMine
? h('div', { className: 'p-hint', style: { padding: '18px 0' } }, '我的盒型(导入的 CAD 结构会保存在这里)' + (plansList().length ? '' : ' · 暂无'))
: h('div', { className: 'bx-chips' }, cats.map(function (c) {
return h('button', { key: c, className: boxCat === c ? 'on' : '', onClick: function () { boxCat = c; renderTool(); } }, c);
})),
!boxMine && h('div', { className: 'bx-box-grid' }, list.map(function (b) {
return h('button', {
key: b.no, className: 'bx-box-card' + (state.boxNo === b.no ? ' on' : ''),
title: b.name,
onClick: function () { applyLibBox(b); }
},
h('span', { className: 'thumb', dangerouslySetInnerHTML: { __html: structThumbSvg(b.gen, b.no) } }),
h('span', { className: 'meta' },
h('b', null, b.name),
h('span', { className: 'no' }, b.no)
),
b.sizes
? h('span', { className: 'flag sizes' }, b.sizes.length + '种固定尺寸')
: h('span', { className: 'flag' }, '可改尺寸'),
b.printable ? null : h('span', { className: 'flag off' }, '不可印刷')
);
})),
!boxMine && !list.length && h(A.Empty, { description: '找不到盒型' })
);
}
function structThumbSvg(gen, no) {
const keep = { w: state.w, d: state.d, h: state.h, boxNo: state.boxNo, structure: state.structure };
const preview = no === '260030' ? [90, 54] : no === '260040' ? [80, 80] : no === '261010' ? [50, 90] : no === '261002' ? [60, 95] : no === '270010' ? [60, 40] : no === '270020' ? [50, 50] : null;
const keepMat = state.material;
state.material = 'card';
let dl;
try {
if (preview) {
state.boxNo = no; state.structure = 'card';
dl = buildDieline('card', preview[0], preview[1], preview[1]);
} else {
state.structure = gen;
dl = buildDieline(gen, 60, 40, 90);
}
} catch (e) { dl = null; }
state.boxNo = keep.boxNo; state.structure = keep.structure; state.material = keepMat;
if (!dl) return '';
const pad = 4;
let body = '';
dl.panels.forEach(function (p) {
const b = panelBounds(p);
const pts = p.poly ? p.poly : [[b.x, b.y], [b.x + b.w, b.y], [b.x + b.w, b.y + b.h], [b.x, b.y + b.h]];
body += '';
});
dl.folds.forEach(function (f) {
body += '';
});
return '';
}
function applyLibBox(entry) {
if (state.boxNo === entry.no) return;
pushUndo();
state.boxNo = entry.no;
state.structure = entry.gen;
if (entry.sizes && entry.sizes.length) {
const s = entry.sizes[0];
state.w = s[0];
if (entry.gen === 'card') {
// 卡牌尺寸为 [长, 高],无厚度维度
state.h = s[1];
} else {
state.d = s[1];
state.h = s[2] || state.h;
}
}
commit();
UI.message.success('已切换到「' + entry.name + '」');
}
/* ---- 模板面板 ---- */
let tplSearch = '', tplCat = '热门';
function templatePanel() {
const list = LB.TEMPLATES.filter(function (t) {
if (tplSearch && t.name.indexOf(tplSearch) < 0) return false;
if (tplCat === '热门') return true;
return t.cat === tplCat;
});
return h('div', null,
h(A.Input, { placeholder: '输入模板关键字', value: tplSearch, allowClear: true, onChange: function (e) { tplSearch = e.target.value; renderTool(); } }),
h('div', { className: 'bx-chips' }, LB.TEMPLATE_CATS.map(function (c) {
return h('button', { key: c, className: tplCat === c ? 'on' : '', onClick: function () { tplCat = c; renderTool(); } }, c);
})),
h('div', { className: 'bx-tpl-grid' }, list.map(function (t) {
return h('button', {
key: t.id, className: 'bx-tpl-card',
style: { background: t.color },
onClick: function () { applyTemplate(t); }
},
h('b', { style: { color: /^#([0-9a-f]{6})$/i.test(t.color) && luminance(t.color) < 0.5 ? '#fff' : '#17140f' } }, t.texts[0].text),
h('span', { className: 'nm', style: { color: luminance(t.color) < 0.5 ? 'rgba(255,255,255,.75)' : 'rgba(23,20,15,.6)' } }, t.name)
);
}))
);
}
function luminance(hex) {
const c = hex.replace('#', '');
const r = parseInt(c.substr(0, 2), 16), g = parseInt(c.substr(2, 2), 16), b = parseInt(c.substr(4, 2), 16);
return (0.299 * r + 0.587 * g + 0.114 * b) / 255;
}
function applyTemplate(t) {
pushUndo();
const face = curFaces()[t.face];
if (!face) return;
face.color = t.color;
face.items = face.items || [];
t.texts.forEach(function (tx) {
face.items.push(Object.assign({ id: 'i' + Date.now().toString(36) + Math.random().toString(36).slice(2, 5), type: 'text', italic: false, lineHeight: 1.25 }, tx));
});
if (t.asset && LB.ICONS[t.asset.id]) {
face.items.push({
id: 'i' + Date.now().toString(36) + Math.random().toString(36).slice(2, 5),
type: 'asset', assetId: t.asset.id, src: 'data:image/svg+xml;utf8,' + encodeURIComponent(LB.assetSvg(t.asset.id, '#c2451f')), color: '#c2451f', x: 50, y: 68, w: 26
});
}
UI.message.success('模板「' + t.name + '」已套用到' + faceName(t.face));
commit();
}
/* ---- 素材面板 ---- */
let assetSearch = '', assetCat = '全部', assetTab = '分类';
const favKey = 'pouchlab.box.favs';
function favs() { try { return JSON.parse(localStorage.getItem(favKey) || '[]'); } catch (e) { return []; } }
function assetPanel() {
const favsList = favs();
const shapeDefs = Object.keys(LB.SHAPES).map(function (k) { return Object.assign({ id: 'shape:' + k, cat: '形状' }, LB.SHAPES[k]); });
const iconDefs = Object.keys(LB.ICONS).map(function (k) { return Object.assign({ id: 'icon:' + k, cat: '图标', svgDef: LB.ICONS[k].svg, name: LB.ICONS[k].name }, {}); });
const extra = [
{ id: 'illu:gift', name: '礼盒插画', cat: '插画', svgDef: '' },
{ id: 'illu:cup', name: '咖啡杯插画', cat: '插画', svgDef: '' },
{ id: 'cutout:badge', name: '透明徽章', cat: '抠图', svgDef: '' },
{ id: 'cutout:arrow', name: '透明箭头', cat: '抠图', svgDef: '' }
];
const all = shapeDefs.concat(iconDefs, extra);
const list = all.filter(function (a) {
if (assetTab === '收藏') return favsList.indexOf(a.id) >= 0;
if (assetTab === '已购') return false;
if (assetSearch && a.name.indexOf(assetSearch) < 0) return false;
if (assetCat === '全部') return true;
return a.cat === assetCat;
});
return h('div', null,
h(A.Input, { placeholder: '输入素材关键字', value: assetSearch, allowClear: true, onChange: function (e) { assetSearch = e.target.value; renderTool(); } }),
h('div', { className: 'bx-sub-tabs' },
['分类', '收藏', '已购'].map(function (t) {
return h('button', { key: t, className: assetTab === t ? 'on' : '', onClick: function () { assetTab = t; renderTool(); } }, t === '分类' ? '素材分类' : t);
})
),
assetTab === '分类' && h('div', { className: 'bx-chips' }, LB.ASSET_CATS.map(function (c) {
return h('button', { key: c, className: assetCat === c ? 'on' : '', onClick: function () { assetCat = c; renderTool(); } }, c);
})),
h('div', { className: 'bx-asset-grid' }, list.map(function (a) {
return h('div', { key: a.id, className: 'bx-asset-card', title: a.name },
h('button', {
className: 'thumb', onClick: function () { addAssetFromDef(a); }
}, h('span', { dangerouslySetInnerHTML: { __html: assetThumb(a, '#17140f') } })),
h('span', { className: 'nm' }, a.name),
h('button', {
className: 'fav' + (favsList.indexOf(a.id) >= 0 ? ' on' : ''),
onClick: function () { toggleFav(a.id); }
}, favsList.indexOf(a.id) >= 0 ? '★' : '☆')
);
})),
!list.length && h(A.Empty, { description: assetTab === '已购' ? '暂无购买记录' : '没找到你想要的结果' }),
h('div', { className: 'p-hint', style: { marginTop: '12px' } }, '素材点击即添加到当前选中的面,可于图层面板调整。')
);
}
function toggleFav(id) {
const list = favs();
const i = list.indexOf(id);
if (i >= 0) list.splice(i, 1); else list.push(id);
localStorage.setItem(favKey, JSON.stringify(list));
renderTool();
}
function addAssetFromDef(a) {
let src;
if (a.svgDef) src = 'data:image/svg+xml;utf8,' + encodeURIComponent('');
else src = LB.shapeDataUrl(a.draw, '#17140f', 160);
addAssetToFace({ type: 'asset', assetId: a.id, name: a.name, src: src, color: '#17140f', svgDef: a.svgDef || null, draw: a.draw || null });
}
/* ---- 文字面板 ---- */
function textPanel() {
const basics = [
{ id: 'b1', label: '标准', style: { fontWeight: 600 }, size: 10, weight: 600 },
{ id: 'b2', label: '描边', style: { WebkitTextStroke: '1px #17140f', color: '#fff' }, size: 11, weight: 800 },
{ id: 'b3', label: '阴影', style: { textShadow: '2px 2px 0 rgba(23,20,15,.55)' }, size: 11, weight: 800 },
{ id: 'b4', label: '斜体', style: { fontStyle: 'italic' }, size: 10, weight: 500 },
{ id: 'b5', label: '衬线', style: { fontFamily: 'Georgia, serif' }, size: 11, weight: 700 },
{ id: 'b6', label: '圆润', style: { fontFamily: '"PingFang SC", sans-serif', fontWeight: 800, letterSpacing: '1px' }, size: 10, weight: 800 }
];
const combos = [
{ name: '品牌 + 品类', texts: [{ text: '品牌名称', size: 11, weight: 800, y: 40 }, { text: 'PRODUCT NAME', size: 4, weight: 400, y: 52 }] },
{ name: '日期 + 系列', texts: [{ text: 'BAOXIAOHE', size: 8, weight: 800, y: 38 }, { text: '2026.10.24', size: 5, weight: 600, y: 48 }, { text: 'SERIES NO.01', size: 3.4, weight: 400, y: 56 }] },
{ name: '主标题 + 卖点', texts: [{ text: '大促特惠', size: 13, weight: 800, y: 40, color: '#c2451f' }, { text: '买二送一 · 限时', size: 4.5, weight: 400, y: 52 }] },
{ name: '竖排签名', texts: [{ text: '袋研\n社制', size: 9, weight: 700, y: 42, lineHeight: 1.1 }] }
];
return h('div', null,
h('button', { className: 'bx-primary-btn', onClick: addBasicText }, '点击添加文字'),
h('div', { className: 'bx-sec-title' }, '基础文字'),
h('div', { className: 'bx-basic-texts' }, basics.map(function (b) {
return h('button', { key: b.id, className: 'bx-basic-text', style: b.style, onClick: function () { addTextPreset({ text: '输入文字', size: b.size, weight: b.weight, italic: b.id === 'b4' }); } }, '输入文字');
})),
h('div', { className: 'bx-sec-title' }, '文字组合'),
h('div', { className: 'bx-combo-grid' }, combos.map(function (c) {
return h('button', { key: c.name, className: 'bx-combo-card', onClick: function () {
pushUndo();
const face = curFace();
c.texts.forEach(function (tx) {
face.items.push(Object.assign({ id: 'i' + Date.now().toString(36) + Math.random().toString(36).slice(2, 5), type: 'text', x: 50, color: '#17140f', align: 'center', italic: false, lineHeight: 1.25 }, tx));
});
commit();
UI.message.success('文字组合已添加');
} },
h('b', null, c.texts[0].text),
h('span', null, c.texts.slice(1).map(function (t) { return t.text; }).join(' · ')),
h('em', null, c.name)
);
}))
);
}
/* ---------------- AI 面排版(登录后可用) ---------------- */
function aiFaceModal() {
if (window.PL.auth && !PL.auth.user()) {
PL.auth.require(function () { aiFaceModal(); });
return;
}
if (!window.PL || !PL.api) { UI.message.info('AI 需要联网登录后使用'); return; }
const faceName = { front: '正面', back: '背面', left: '左面', right: '右面', top: '顶面', bottom: '底面' }[state.selectedFace] || state.selectedFace;
const div = document.createElement('div');
$('#bxModals').appendChild(div);
let brief = '';
let busy = false;
let full = false; // 整套 6 面设计
function renderModal(msg, left) {
UI.render(div, h(A.Modal, { open: true, width: 460, footer: null,
title: '✨ AI 排版 · ' + (full ? '整套 6 面' : faceName + '(' + (state.side === 'outer' ? '外' : '内') + '侧)'),
onCancel: function () { UI.reset(div); div.remove(); } },
h(A.Segmented, {
block: true, value: full ? 'full' : 'one',
options: [{ value: 'one', label: '仅当前面(' + faceName + ')' }, { value: 'full', label: '整套 6 面' }],
onChange: function (v) { full = v === 'full'; renderModal(); }
}),
h('p', { style: { fontSize: 12, color: '#7d7466', margin: '10px 0 8px' } },
'描述这个面的排版需求;生成后再说"文字再大点/换个位置"可继续调整。' + (left != null ? ' 剩余 ' + left + ' 次' : '')),
h(A.Input.TextArea, {
rows: 3, placeholder: '如:极简茶叶礼盒,居中大字品牌名,下方一行英文,底部小字净含量',
onChange: function (e) { brief = e.target.value; }
}),
msg ? h('p', { style: { fontSize: 12, color: msg.ok ? '#4f9d69' : '#e64718', margin: '8px 0 0' } }, msg.text) : null,
h('div', { style: { display: 'flex', gap: 8, marginTop: 10, justifyContent: 'flex-end' } },
h(A.Popconfirm, {
title: '清空本面', description: '将清除' + faceName + '的全部文字与图形(含背景色),可撤销',
onConfirm: function () {
pushUndo();
const f = curFace();
f.items = [];
f.color = '';
commit(); renderAll();
UI.reset(div); div.remove();
UI.message.success(faceName + '已清空(可 ⌘Z 撤销)');
}
}, h(A.Button, { danger: true }, '清空本面')),
h(A.Button, { onClick: function () { UI.reset(div); div.remove(); } }, '关闭'),
h(A.Button, { type: 'primary', loading: busy, onClick: generate }, '生成并应用'))
));
}
function generate() {
if (!brief.trim()) { renderModal({ ok: false, text: '请先描述需求' }); return; }
if (busy) return;
busy = true; renderModal({ ok: true, text: 'AI 正在设计中,通常 10~60 秒,请勿关闭弹窗…' });
const face = curFace();
const ctx = full
? { faces: FACES.reduce(function (acc, f) {
const fd = state.faces[state.side][f.id] || {};
acc[f.id] = { color: fd.color || '', items: (fd.items || []).filter(function (i) { return i.type === 'text'; }) };
return acc;
}, {}) }
: (face && (face.items || []).length ? { color: face.color || '', items: face.items.filter(function (i) { return i.type === 'text'; }) } : null);
PL.api.post('/ai/layout', {
type: 'box', brief: brief,
meta: full ? { full: true } : { face: state.selectedFace },
context: ctx
}, { timeout: 180000 }).then(function (r) {
busy = false;
if (full) {
const faces = r.result.faces || {};
const filled = Object.keys(faces).filter(function (k) { return (faces[k].items || []).length; });
if (filled.length < 2) {
renderModal({ ok: false, text: 'AI 这次没能生成有效成套设计(未扣次数),换个说法再试' });
return;
}
pushUndo();
FACES.forEach(function (f) {
const fd = state.faces[state.side][f.id];
const rd = faces[f.id];
if (!fd || !rd) return;
fd.color = rd.color || fd.color;
fd.items = (rd.items || []).map(function (it) {
it.id = 'i' + Date.now().toString(36) + Math.random().toString(36).slice(2, 5);
it.lineHeight = 1.25;
return it;
});
});
commit(); renderAll();
UI.reset(div); div.remove();
UI.message.success('AI 已完成整套 6 面设计(剩余 ' + r.left + ' 次),可撤销');
return;
}
if (!(r.result.items || []).length) {
renderModal({ ok: false, text: 'AI 这次没能生成有效排版(未扣次数),换个说法再试' });
return;
}
pushUndo();
const f = curFace();
f.color = r.result.color || f.color;
f.items = (r.result.items || []).map(function (it) {
it.id = 'i' + Date.now().toString(36) + Math.random().toString(36).slice(2, 5);
it.lineHeight = 1.25;
return it;
});
commit(); renderAll();
UI.reset(div); div.remove();
UI.message.success('AI 排版已应用到' + faceName + '(剩余 ' + r.left + ' 次),可撤销');
}, function (err) {
busy = false;
if (err.status === 401) {
UI.reset(div); div.remove();
PL.auth.require(function () { aiFaceModal(); });
return;
}
renderModal({ ok: false, text: err.message || 'AI 生成失败' });
});
}
renderModal();
}
function addBasicText() { addTextPreset({ text: '输入文字', size: 10, weight: 600 }); }
function addTextPreset(preset) {
pushUndo();
const face = curFace();
const it = {
id: 'i' + Date.now().toString(36) + Math.random().toString(36).slice(2, 5),
type: 'text', text: preset.text || '输入文字',
size: preset.size || 10, weight: preset.weight || 600, italic: !!preset.italic,
color: '#17140f', align: 'center', lineHeight: preset.lineHeight || 1.25,
x: 50, y: preset.y || 40
};
face.items = face.items || [];
face.items.push(it);
state.selectedItemId = it.id;
commit();
}
/* ---- 工具面板(条码 + 二维码) ---- */
function toolPanel() {
return h('div', null,
h('div', { className: 'bx-tool-card', onClick: addBarcode },
h('span', { className: 'ic' }, ' II·II '),
h('div', null, h('b', null, '条形码'), h('span', null, '快速生成一堆码支持4种码制'))
),
h('div', { className: 'bx-tool-card', onClick: addQrcode },
h('span', { className: 'ic qr' }, '▦'),
h('div', null, h('b', null, '二维码'), h('span', null, '快速生成二维码设计使用'))
)
);
}
function barcodeSvg(kind, value) {
if (kind === 'code128') {
const TBL = ('212222 222122 222221 121223 121322 131222 122213 122312 132212 221213 221312 231212 112232 122132 122231 113222 123122 123221 223211 221132 221231 213212 223112 312131 311222 321122 321221 312212 322112 322211 212123 212321 232121 111323 131123 131321 112313 132113 132311 211313 231113 231311 112133 112331 132131 113123 113321 133121 313121 211331 231131 213113 213311 213131 311123 311321 331121 312113 312311 332111 314111 221411 431111 111224 111422 121124 121421 141122 141221 112214 112412 122114 122411 142112 142211 241211 221114 413111 241112 134111 111242 121142 121241 114212 124112 124211 411212 421112 421211 212141 214121 412121 111143 111341 131141 114113 114311 411113 411311 113141 114131 311141 411131 211412 211214 211232 2331112').split(' ');
const text = String(value || 'POUCHLAB').replace(/[^\x20-\x7e]/g, '').slice(0, 20) || 'BOX';
const codes = [104];
for (let i = 0; i < text.length; i += 1) codes.push(text.charCodeAt(i) - 32);
let sum = 104;
for (let i = 1; i < codes.length; i += 1) sum += codes[i] * i;
codes.push(sum % 103);
codes.push(106);
let bits = '';
codes.forEach(function (c) { bits += TBL[c]; });
let x = 0, rects = '';
const unit = 2;
for (let i = 0; i < bits.length; i += 1) {
const wdt = Number(bits[i]) * unit;
if (i % 2 === 0) rects += '';
x += wdt;
}
const totalW = x + 40;
return 'data:image/svg+xml;utf8,' + encodeURIComponent('');
}
// EAN-13 / EAN-8 / UPC-A 共用 PL.render.barcodeBits(EAN-13 逻辑,UPC-A 加 0 前缀)
let val = String(value || '').replace(/\D/g, '');
if (kind === 'ean8') val = val.slice(0, 7).padEnd(7, '0');
else if (kind === 'upca') val = val.slice(0, 11).padEnd(11, '0');
else val = val.slice(0, 12).padEnd(12, '0');
const bars = R.barcodeBits(kind === 'upca' ? '0' + val : val);
const label = kind === 'upca' ? '0' + bars.code : bars.code;
const rects = [];
let x = 0;
const unit = 2;
for (let i = 0; i < bars.bits.length; i += 1) {
if (bars.bits[i] === '1') rects.push('');
x += unit;
}
return 'data:image/svg+xml;utf8,' + encodeURIComponent('');
}
function addBarcode() {
let kind = 'ean13';
const content = h('div', null,
h('div', { className: 'p-field' },
h('label', null, '码制'),
h(A.Select, {
defaultValue: 'ean13', style: { width: '100%' },
onChange: function (v) { kind = v; },
options: [
{ value: 'ean13', label: 'EAN-13 商品码' },
{ value: 'ean8', label: 'EAN-8 短码' },
{ value: 'upca', label: 'UPC-A' },
{ value: 'code128', label: 'Code128' }
]
})
),
h('div', { className: 'p-field' },
h('label', null, '内容'),
h(A.Input, { id: 'bxBarcodeValue', defaultValue: '6971234567890', placeholder: '条码内容' })
)
);
modalConfirm('生成条形码', content, function () {
const value = document.getElementById('bxBarcodeValue').value;
const src = barcodeSvg(kind, value);
addAssetToFace({ type: 'barcode', codeType: kind, value: value, src: src, w: 40 });
});
}
function addQrcode() {
const content = h('div', null,
h('div', { className: 'p-field' },
h('label', null, '二维码内容(网址或文字)'),
h(A.Input, { id: 'bxQrValue', defaultValue: 'https://pouchlab.design', placeholder: '请输入内容' })
)
);
modalConfirm('生成二维码', content, function () {
const value = document.getElementById('bxQrValue').value || ' ';
let src;
try { src = QR.toDataURL(value, { scale: 6, margin: 1 }); }
catch (e) { UI.message.error(e.message || '内容过长'); return; }
addAssetToFace({ type: 'barcode', codeType: 'qrcode', value: value, src: src, w: 32 });
});
}
/* ---- 上传面板 ---- */
function storageUsed() {
let total = 0;
try {
for (const k in localStorage) {
if (Object.prototype.hasOwnProperty.call(localStorage, k) && k.indexOf('pouchlab') === 0) {
total += (localStorage[k] || '').length * 2;
}
}
} catch (e) {}
return total;
}
function uploadPanel() {
const used = storageUsed();
const pct = Math.min(100, used / (100 * 1024 * 1024) * 100);
const uploads = state.uploads || [];
return h('div', null,
h(A.Upload, {
accept: 'image/*', showUploadList: false, customRequest: uploadToFace,
children: h('button', { className: 'bx-primary-btn' }, '上传图片')
}),
h('div', { className: 'p-hint' }, '支持上传JPG/PNG/SVG等格式文件'),
uploads.length ? h('div', { className: 'bx-upload-grid' }, uploads.map(function (u) {
return h('div', { key: u.id, className: 'bx-upload-card' },
h('button', {
className: 'thumb', title: '添加到当前面',
onClick: function () { addAssetToFace({ type: 'image', name: u.name, src: u.src, w: 70 }); }
}, h('img', { src: u.src, alt: u.name })),
h('span', { className: 'nm', title: u.name }, u.name),
h('button', {
className: 'del', title: '从上传记录中移除',
onClick: function () {
state.uploads = (state.uploads || []).filter(function (x) { return x.id !== u.id; });
commit();
}
}, '✕')
);
})) : h('div', { className: 'bx-upload-empty' },
h('div', { className: 'box-illus' }),
h('span', null, '上传的稿件会放置到当前选中的面')
),
h('div', { className: 'bx-capacity' },
h('span', null, '个人已使用 ' + (used / 1024 / 1024).toFixed(1) + 'M/100M'),
h('a', { onClick: function () { UI.message.info('演示环境:容量为本地浏览器存储模拟'); } }, '扩充容量')
),
h('div', { className: 'bx-cap-bar' }, h('i', { style: { width: Math.max(1, pct) + '%' } }))
);
}
function uploadToFace(options) {
const file = options.file;
if (!file || file.type.indexOf('image') !== 0) {
UI.message.warning('请选择图片文件');
return;
}
const reader = new FileReader();
reader.onload = function () {
const img = new Image();
img.onload = function () {
const max = 900;
let w = img.width, hh = img.height;
if (Math.max(w, hh) > max) {
const k = max / Math.max(w, hh);
w = Math.round(w * k); hh = Math.round(hh * k);
}
const canvas = document.createElement('canvas');
canvas.width = w; canvas.height = hh;
canvas.getContext('2d').drawImage(img, 0, 0, w, hh);
const src = canvas.toDataURL(file.type === 'image/png' ? 'image/png' : 'image/jpeg', 0.84);
// 保留上传记录,便于重复使用;最多保留 8 张,避免 localStorage 超限
const up = { id: 'u' + Date.now().toString(36) + Math.random().toString(36).slice(2, 5), name: file.name, src: src, time: Date.now() };
state.uploads = [up].concat(state.uploads || []).slice(0, 8);
addAssetToFace({ type: 'image', name: file.name, src: src, w: 70 });
if (currentTab === 'upload') renderTool();
};
img.src = reader.result;
};
reader.readAsDataURL(file);
}
/* ---- 图层面板 ---- */
function layersPanel() {
const face = curFace();
const items = (face.items || []).slice().reverse();
return h('div', null,
h('div', { className: 'bx-layer-head' },
h('div', { className: 'bx-sec-title' }, faceName(state.selectedFace) + ' · ' + items.length + ' 个图层'),
items.length ? h('button', { className: 'bx-layer-clear', onClick: clearLayers }, '一键清空') : null
),
items.length ? h('div', { className: 'bx-layer-list' }, items.map(function (it) {
const typeNames = { text: '文字', image: '图片', asset: '素材', barcode: it.codeType === 'qrcode' ? '二维码' : '条形码' };
return h('div', { key: it.id, className: 'bx-layer-row' + (state.selectedItemId === it.id ? ' on' : ''), 'data-layer-id': it.id },
h('span', { className: 't', onClick: function () { state.selectedItemId = it.id; renderTool(); renderProps(); } },
typeNames[it.type] || '元素', ' · ', it.type === 'text' ? String(it.text || '').split('\n')[0] : (it.name || '')),
h('button', { title: it.hidden ? '显示' : '隐藏', onClick: function () { it.hidden = !it.hidden; commit(); } }, it.hidden ? '🚫' : '👁'),
h('button', { title: '移到最顶层', onClick: function () { moveItem(it.id, 'top'); } }, '⤒'),
h('button', { title: '上移一层', onClick: function () { moveItem(it.id, 1); } }, '↑'),
h('button', { title: '下移一层', onClick: function () { moveItem(it.id, -1); } }, '↓'),
h('button', { title: '移到最底层', onClick: function () { moveItem(it.id, 'bottom'); } }, '⤓'),
h('button', { className: 'del', title: '删除', onClick: function () { removeItem(it.id); } }, '✕')
);
})) : h('div', { className: 'bx-layer-empty' },
h('span', { className: 'stack' }), '图层为空'
)
);
}
function clearLayers() {
const face = curFace();
const count = (face.items || []).length;
let total = 0;
FACES.forEach(function (ff) { total += (curFaces()[ff.id].items || []).length; });
if (!total) return;
let close;
close = mountModal(h(A.Modal, {
title: '清空图层', open: true, footer: null, onCancel: function () { close(); }
}, h('div', null,
h('p', null, '当前面有 ' + count + ' 个图层,全部面共 ' + total + ' 个图层。'),
h('div', { className: 'bx-clear-actions' },
h('button', {
className: 'bx-clear-opt', disabled: !count,
onClick: function () {
pushUndo();
face.items = [];
state.selectedItemId = null;
commit();
close();
UI.message.success('已清空「' + faceName(state.selectedFace) + '」图层');
}
}, '清空当前面(' + count + ')'),
h('button', {
className: 'bx-clear-opt danger',
onClick: function () {
pushUndo();
FACES.forEach(function (ff) { curFaces()[ff.id].items = []; });
state.selectedItemId = null;
commit();
close();
UI.message.success('已清空全部面图层');
}
}, '清空全部面(' + total + ')')
),
h('div', { className: 'p-hint', style: { marginTop: '10px' } }, '清空后可通过 Ctrl+Z 撤销。')
)));
}
function findItem(id) {
const face = curFace();
return (face.items || []).find(function (x) { return x.id === id; }) || null;
}
function removeItem(id) {
pushUndo();
const face = curFace();
face.items = (face.items || []).filter(function (x) { return x.id !== id; });
if (state.selectedItemId === id) state.selectedItemId = null;
commit();
}
function moveItem(id, dir) {
const face = curFace();
const arr = face.items || [];
const i = arr.findIndex(function (x) { return x.id === id; });
if (i < 0) return;
let j;
if (dir === 'top') j = arr.length - 1;
else if (dir === 'bottom') j = 0;
else j = i + dir;
if (j < 0 || j >= arr.length || j === i) return;
pushUndo();
const it = arr.splice(i, 1)[0];
arr.splice(j, 0, it);
commit();
}
/* 拖拽排序:把 fromId 移动到 toId 的上/下(above=true 为更高层) */
function reorderLayer(fromId, toId, above) {
if (!fromId || !toId || fromId === toId) return;
const face = curFace();
const arr = face.items || [];
const rv = arr.slice().reverse();
const si = rv.findIndex(function (x) { return x.id === fromId; });
const ti = rv.findIndex(function (x) { return x.id === toId; });
if (si < 0 || ti < 0) return;
pushUndo();
const it = rv.splice(si, 1)[0];
let ins = ti > si ? ti - 1 : ti;
if (!above) ins += 1;
rv.splice(ins, 0, it);
face.items = rv.reverse();
commit();
}
/* ---- 帮助面板 ---- */
function helpPanel() {
return h('div', null,
h('div', { className: 'bx-tool-card', onClick: function () { UI.message.info('演示环境:可发送邮件至 support@pouchlab.design'); } },
h('span', { className: 'ic' }, '☎'), h('div', null, h('b', null, '咨询客服'), h('span', null, '工作日 9:00-18:00'))
),
h('div', { className: 'bx-tool-card', onClick: showQuickStart },
h('span', { className: 'ic' }, '📖'), h('div', null, h('b', null, '快速上手'), h('span', null, '3 步完成盒子设计'))
),
h('div', { className: 'bx-tool-card', onClick: showShortcuts },
h('span', { className: 'ic' }, '⌨'), h('div', null, h('b', null, '快捷键'), h('span', null, '常用操作快捷键列表'))
)
);
}
function showQuickStart() {
modalInfo('快速上手', h('div', { className: 'bx-help-steps' },
h('p', null, '1. 在「盒型」面板选择盒型与尺寸,或点「编辑」打开智能参数宝精确调参;'),
h('p', null, '2. 在 2D 设计里点选面,用「文字 / 素材 / 上传」添加内容,右侧换颜色与纹理;'),
h('p', null, '3. 切到「3D预览」拖拽查看,播放动效,最后「导出」或「印刷下单」。')
));
}
function showShortcuts() {
modalInfo('快捷键', h('div', { className: 'bx-help-steps' },
h('p', null, 'Ctrl/⌘ + Z 撤销'), h('p', null, 'Ctrl/⌘ + Shift + Z 重做'),
h('p', null, 'Ctrl/⌘ + S 保存'), h('p', null, 'Delete 删除选中元素'),
h('p', null, 'Tab 切换外侧 / 内侧'), h('p', null, '空格拖拽 平移画布')
));
}
/* ---------------- 右侧属性面板 ---------------- */
function propsPanel() {
if (state.mode === '3d') return animsPanel();
const face = curFace();
const item = state.selectedItemId ? findItem(state.selectedItemId) : null;
const out = outerSize();
const dl = dieline();
const children = [];
// 迷你 3D 挂载于右侧面板顶部(2D 模式显示)
children.push(h('div', { className: 'bx-props-sec' },
h('div', { className: 'bx-props-head-row' },
h('b', null, '尺寸/材质', h('i', { className: 'q', title: '内尺寸为盒体内部净尺寸' }))),
h('button', { className: 'bx-edit-btn', onClick: openSmartParams }, '编辑'),
h('div', { className: 'bx-kv' }, h('span', null, '内尺寸(mm)'), h('b', null, 'L:' + state.w + ' W:' + state.d + ' H:' + state.h)),
h('div', { className: 'bx-kv' }, h('span', null, '材质'), h('b', null, material().name)),
h('div', { className: 'bx-kv' }, h('span', null, '厚度'), h('b', null, material().thickness + 'mm'))
));
children.push(h('div', { className: 'bx-props-sec' },
h('div', { className: 'bx-props-head-row' }, h('b', null, '颜色 / 背景')),
h('div', { className: 'bx-color-tabs' },
h('button', { className: colorTab === 'color' ? 'on' : '', onClick: function () { colorTab = 'color'; renderProps(); } }, '颜色'),
h('button', { className: colorTab === 'texture' ? 'on' : '', onClick: function () { colorTab = 'texture'; renderProps(); } }, '纹理')
),
colorTab === 'color' ? h('div', null,
h('div', { className: 'bx-swatch-grid' },
h('label', { className: 'bx-swatch picker', title: '自定义颜色' },
h('input', { type: 'color', value: face.color || '#fbf7ee', onInput: function (e) { setFaceColor(e.target.value); } }),
h('span', { className: 'grad' })
),
h('button', { className: 'bx-swatch', title: '清空颜色', onClick: function () { setFaceColor(''); } }, h('i', { className: 'none' })),
LB.FACE_COLORS.map(function (c) {
return h('button', { key: c, className: 'bx-swatch' + (face.color === c ? ' on' : ''), style: { background: c }, onClick: function () { setFaceColor(c); } });
})
),
h('div', { className: 'bx-pms-title' }, '参考潘通色'),
h('div', { className: 'bx-pms-grid' }, (window.PL.pantone ? window.PL.pantone.list : []).map(function (c) {
return h('button', {
key: c.code,
className: 'bx-pms-dot' + (face.color && face.color.toLowerCase() === c.hex.toLowerCase() ? ' on' : ''),
title: '参考潘通色 ' + c.code + ' ' + c.name,
style: { background: c.hex },
onClick: function () { setFaceColor(c.hex); }
});
})),
h('div', { className: 'bx-pms-note' }, window.PL.pantone ? window.PL.pantone.note : '')
) : h('div', { className: 'bx-tex-grid' },
h('button', { className: 'bx-tex clear', onClick: function () { setFaceTexture(null); } }, h('i', { className: 'none' }), h('span', null, '清空纹理')),
LB.TEXTURES.map(function (t) {
return h('button', {
key: t.id, className: 'bx-tex' + (face.textureId === t.id ? ' on' : ''),
onClick: function () { setFaceTexture(t.id); }
}, h('img', { src: LB.textureDataUrl(t.id), alt: t.name }), h('span', null, t.name));
})
)
));
children.push(h('div', { className: 'bx-props-sec' },
h('div', { className: 'bx-props-head-row' }, h('b', null, '画布'),
h('span', { className: 'dim' }, '展开 ' + Math.round(dl.size.w) + ' × ' + Math.round(dl.size.h) + ' mm')),
h('div', { className: 'bx-kv' }, h('span', null, '外侧尺寸'), h('b', null, Math.round(out.w) + ' × ' + Math.round(out.d) + ' × ' + Math.round(out.h) + ' mm')),
h('div', { className: 'bx-kv' }, h('span', null, '当前设计'), h('b', null, state.side === 'outer' ? '外侧' : '内侧')),
h('div', { className: 'bx-kv' }, h('span', null, '元素'), h('b', null, ((face.items || []).length) + ' 个'))
));
if (item) children.push(itemPropsPanel(item));
return h('div', null, children);
}
let colorTab = 'color';
function itemPropsPanel(item) {
const typeNames = { text: '文字属性', image: '图片属性', asset: '素材属性', barcode: item.codeType === 'qrcode' ? '二维码属性' : '条形码属性' };
const rows = [];
rows.push(h('div', { className: 'bx-props-sec' },
h('div', { className: 'bx-props-head-row' }, h('b', null, typeNames[item.type] || '元素属性'),
h('button', { onClick: function () { state.selectedItemId = null; renderProps(); } }, '完成选择'))
));
if (item.type === 'text') {
rows.push(h('div', { className: 'bx-props-sec' },
h(BoxTextField, {
value: item.text, placeholder: '文字内容',
onInput: function (v) { item.text = v; save(true); renderDieline(); render3d(); renderMini(); },
onCommit: function () { commit(); }
}),
h('div', { className: 'bx-row2' },
h('div', { className: 'p-field' }, h('label', null, '字号 (mm)'), h(A.InputNumber, { value: item.size, min: 2, max: 120, style: { width: '100%' }, onChange: function (v) { if (v) { item.size = v; commit(); } } })),
h('div', { className: 'p-field' }, h('label', null, '颜色'), h(A.ColorPicker, {
key: 'tc-' + item.id,
defaultValue: item.color || '#17140f',
showText: true,
onChange: function (c) { item.color = c.toHexString(); save(true); renderDieline(); render3d(); renderMini(); },
onChangeComplete: function (c) { item.color = c.toHexString(); commit(); }
}))
),
h('div', { className: 'bx-row2' },
h('div', { className: 'p-field' }, h('label', null, '对齐'), h(A.Segmented, { value: item.align || 'center', block: true, options: [{ label: '左', value: 'left' }, { label: '中', value: 'center' }, { label: '右', value: 'right' }], onChange: function (v) { item.align = v; commit(); } })),
h('div', { className: 'p-field' }, h('label', null, '字重'), h(A.Segmented, { value: String(item.weight || 400), block: true, options: [{ label: '常规', value: '400' }, { label: '中', value: '600' }, { label: '粗', value: '800' }], onChange: function (v) { item.weight = Number(v); commit(); } }))
),
h('div', { className: 'p-field', style: { marginTop: '6px' } },
h('label', null, '样式'),
h('div', { className: 'bx-row2' },
h(A.Checkbox, { checked: !!item.italic, onChange: function (e) { item.italic = e.target.checked; commit(); } }, '斜体'),
h(A.Checkbox, { checked: !!item.hidden, onChange: function (e) { item.hidden = e.target.checked; commit(); } }, '隐藏')
)
)
));
} else {
const colorable = item.type === 'asset' && !!assetFillSrc(item, '#17140f');
rows.push(h('div', { className: 'bx-props-sec' },
h('img', { className: 'bx-item-preview', src: item.src, alt: '' }),
colorable && h('div', { className: 'p-field' }, h('label', null, '颜色'), h(A.ColorPicker, {
key: 'ac-' + item.id,
defaultValue: item.color || '#17140f',
showText: true,
onChange: function (c) {
const hex = c.toHexString();
const next = assetFillSrc(item, hex);
if (!next) return;
item.color = hex;
item.src = next;
save(true); renderDieline(); render3d(); renderMini();
},
onChangeComplete: function (c) {
const hex = c.toHexString();
const next = assetFillSrc(item, hex);
if (!next) return;
item.color = hex;
item.src = next;
commit();
}
})),
h('div', { className: 'p-field' }, h('label', null, '宽度 ' + (item.w == null ? 60 : item.w) + '%'), h(A.Slider, { value: item.w == null ? 60 : item.w, min: 8, max: 100, onChange: function (v) { item.w = v; renderDieline(); render3d(); renderMini(); }, onAfterChange: function () { commit(); } }))
));
}
rows.push(h('div', { className: 'bx-row2', style: { marginBottom: '12px' } },
h('div', { className: 'p-field' }, h('label', null, '水平 ' + item.x + '%'), h(A.Slider, { value: item.x, min: 0, max: 100, onChange: function (v) { item.x = v; renderDieline(); render3d(); renderMini(); }, onAfterChange: function () { commit(); } })),
h('div', { className: 'p-field' }, h('label', null, '垂直 ' + item.y + '%'), h(A.Slider, { value: item.y, min: 0, max: 100, onChange: function (v) { item.y = v; renderDieline(); render3d(); renderMini(); }, onAfterChange: function () { commit(); } }))
));
rows.push(h('div', { className: 'bx-props-sec' },
h('div', { className: 'bx-props-head-row' }, h('b', null, '图层顺序')),
h('div', { className: 'bx-order-grid' },
h('button', { className: 'bx-ghost-btn', onClick: function () { moveItem(item.id, 'top'); } }, '⤒ 置顶'),
h('button', { className: 'bx-ghost-btn', onClick: function () { moveItem(item.id, 1); } }, '↑ 上移'),
h('button', { className: 'bx-ghost-btn', onClick: function () { moveItem(item.id, -1); } }, '↓ 下移'),
h('button', { className: 'bx-ghost-btn', onClick: function () { moveItem(item.id, 'bottom'); } }, '⤓ 置底')
)
));
return h('div', null, rows);
}
function setFaceColor(c) {
pushUndo();
curFace().color = c;
commit();
}
function setFaceTexture(id) {
pushUndo();
const face = curFace();
if (id) {
face.textureId = id;
face.texture = LB.textureDataUrl(id);
} else {
face.textureId = null;
face.texture = null;
}
commit();
}
/* 3D 模式右侧:动效面板 */
function animsPanel() {
return h('div', null,
h('div', { className: 'bx-props-sec' },
h('div', { className: 'bx-props-head-row' }, h('b', null, '动效'), h('span', { className: 'dim' }, '点击预览'))
),
h('div', { className: 'bx-anim-list' }, LB.ANIMS.map(function (a) {
const playing = main3d && main3d.ready() && main3d.animating() && playingAnimId === a.id;
return h('div', { key: a.id, className: 'bx-anim-card' + (playing ? ' on' : '') },
h('button', {
className: 'bx-anim-play',
onClick: function () { playAnim(a); }
},
h('span', { className: 'dur' }, a.dur + 's'),
h('span', { className: 'anim-illus ' + a.id })
),
h('div', { className: 'bx-anim-meta' },
h('b', null, a.name),
h('button', { onClick: function () { playAnim(a); } }, playing ? '停止' + a.dur + 's' : (a.id === 'fromLeft' ? '预览' : '停止' + a.dur + 's'))
)
);
})),
h('div', { className: 'bx-props-sec' },
h('div', { className: 'bx-props-head-row' }, h('b', null, '视角')),
h('div', { className: 'bx-row2' },
h('button', { className: 'bx-ghost-btn', onClick: function () { if (main3d) main3d.resetView(); } }, '重置视角'),
h('button', { className: 'bx-ghost-btn', onClick: function () { const t = !state.autoRotate; state.autoRotate = t; if (main3d) main3d.setAutoRotate(t); } }, '自动旋转')
)
)
);
}
let playingAnimId = null;
function playAnim(a) {
if (!main3d || !main3d.ready()) return;
if (playingAnimId === a.id && main3d.animating()) {
main3d.stopAnim();
playingAnimId = null;
renderProps();
return;
}
stopFoldAnim();
playingAnimId = a.id;
main3d.playAnim(a.id, a.dur, function () {
playingAnimId = null;
renderProps();
});
renderProps();
}
/* ---------------- 弹窗基建 ---------------- */
function mountModal(node) {
const div = document.createElement('div');
$('#bxModals').appendChild(div);
let closed = false;
const close = function () {
if (closed) return;
closed = true;
try { UI.reset(div); } catch (e) {}
if (div.parentNode) div.parentNode.removeChild(div);
};
UI.render(div, node);
return close;
}
function modalConfirm(title, content, onOk, okText, width) {
let close;
close = mountModal(h(A.Modal, {
title: title, open: true, onCancel: function () { close(); },
width: width || undefined,
okText: okText || '确认调整',
onOk: function () { if (onOk) onOk(); close(); },
okButtonProps: { style: { background: '#ff6a00', borderColor: '#ff6a00' } }
}, content));
return close;
}
function modalInfo(title, content) {
let close;
close = mountModal(h(A.Modal, {
title: title, open: true, onCancel: function () { close(); },
footer: h(A.Button, { type: 'primary', onClick: function () { close(); }, style: { background: '#ff6a00', borderColor: '#ff6a00' } }, '我知道了')
}, content));
return close;
}
/* ---------------- 智能参数宝 ---------------- */
function openSmartParams() {
const params = Object.assign({ _labels: true }, state.smart);
const dims = { w: state.w, d: state.d, h: state.h };
let baseSize = '内尺寸', outSize = '内尺寸';
const adv = struct().advanced || [];
const advRows = adv.map(function (key) {
const f = ADV_FIELDS[key];
if (!f) return null;
return h('div', { className: 'sp-row', key: key },
h('label', { title: f.name }, f.name + ' (' + f.code + ')'),
h(A.InputNumber, {
value: params[key], min: f.min, max: f.max, step: f.step || 1,
onChange: function (v) { if (v != null) params[key] = v; renderSmart(); }
}),
h('span', { className: 'unit' }, f.unit)
);
});
const content = h('div', { className: 'sp-wrap' },
h('div', { className: 'sp-left' }, h('div', { id: 'spDieline', className: 'sp-dieline' })),
h('div', { className: 'sp-right' },
h('div', { className: 'sp-row' },
h('label', null, '标注方式'),
h(A.Select, { defaultValue: '数值', style: { flex: 1 }, options: [{ value: '数值' }, { value: '无标注' }], onChange: function (v) { params._labels = v === '数值'; renderSmart(); } })
),
h('div', { className: 'sp-group-title' }, '基础参数'),
h('div', { className: 'sp-row' },
h('label', { title: '以内尺寸或外尺寸为基准调整' }, '基准尺寸'),
h(A.Select, { defaultValue: '内尺寸', style: { flex: 1 }, options: [{ value: '内尺寸' }, { value: '外尺寸' }], onChange: function (v) { baseSize = v; } })
),
h('div', { className: 'sp-row' },
h('label', { title: '输出制造尺寸口径' }, '输出尺寸'),
h(A.Select, { defaultValue: '内尺寸', style: { flex: 1 }, options: [{ value: '内尺寸' }, { value: '外尺寸' }], onChange: function (v) { outSize = v; } })
),
['w', 'd', 'h'].map(function (k, i) {
return h('div', { className: 'sp-row', key: k },
h('label', null, ['长 (L)', '宽 (W)', '高 (H)'][i]),
h(A.InputNumber, { value: dims[k], min: 10, max: 2000, style: { flex: 1 }, onChange: function (v) { if (v) dims[k] = v; renderSmart(); } }),
h('span', { className: 'unit' }, 'mm')
);
}),
h('div', { className: 'sp-row' },
h('label', null, '出血线 (BL)'),
h(A.InputNumber, { value: params.bleed, min: 0, max: 6, step: 0.5, style: { flex: 1 }, onChange: function (v) { if (v != null) params.bleed = v; renderSmart(); } }),
h('span', { className: 'unit' }, 'mm')
),
h('div', { className: 'sp-row' },
h('label', null, '厚度(0.2~3mm)'),
h(A.InputNumber, { value: material().thickness, min: 0.2, max: 3, step: 0.1, style: { flex: 1 }, onChange: function (v) { /* 材质决定厚度 */ } }),
h('span', { className: 'unit' }, 'mm')
),
h('div', { className: 'sp-row' },
h('label', null, '材质'),
h(A.Select, { value: state.material, style: { flex: 1 }, options: MATERIALS.map(function (m) { return { value: m.id, label: m.name }; }), onChange: function (v) { state.material = v; renderSmart(); } })
),
advRows.length ? h('div', { className: 'sp-group-title' }, '高级参数') : null,
advRows
)
);
const close = modalConfirm('智能参数宝', content, function () {
pushUndo();
state.w = dims.w; state.d = dims.d; state.h = dims.h;
Object.assign(state.smart, params);
commit();
UI.message.success('参数已调整,刀版与 3D 已更新');
}, '确认调整', 980);
function renderSmart() {
const keep = { w: state.w, d: state.d, h: state.h, smart: state.smart };
state.w = dims.w; state.d = dims.d; state.h = dims.h;
const merged = Object.assign({}, state.smart, params);
state.smart = merged;
const svg = dielineSVG({ noLegend: true, clean: !params._labels });
state.w = keep.w; state.d = keep.d; state.h = keep.h; state.smart = keep.smart;
const el = document.getElementById('spDieline');
if (el) {
el.innerHTML = svg;
const s = el.querySelector('svg');
if (s) { s.style.width = '100%'; s.style.height = 'auto'; }
}
}
setTimeout(renderSmart, 60);
}
function showImportCad() {
modalInfo('导入 CAD', h('div', { className: 'bx-help-steps' },
h('p', null, '支持 DXF 盒型结构文件上传,上传后在「我的盒型」中管理。'),
h('p', null, '演示环境:本版本以内置参数化盒型库代替 CAD 解析,选择盒型后可在智能参数宝中精调结构参数。')
));
}
/* ---------------- 导出弹窗 ---------------- */
let exportTab = 'file', exportRes = '2k', exportRatio = '16:9', exportBg = 'scene', exportSide = 'outer';
const EXPORT_LOG_KEY = 'pouchlab.box.exports';
function exportLog() { try { return JSON.parse(localStorage.getItem(EXPORT_LOG_KEY) || '[]'); } catch (e) { return []; } }
function logExport(type, name) {
const list = exportLog();
list.unshift({ time: Date.now(), type: type, name: name });
try { localStorage.setItem(EXPORT_LOG_KEY, JSON.stringify(list.slice(0, 40))); } catch (e) {}
}
function downloadBlob(blob, filename) {
const a = document.createElement('a');
a.href = URL.createObjectURL(blob);
a.download = filename;
a.click();
setTimeout(function () { URL.revokeObjectURL(a.href); }, 2000);
}
function openExport() {
const div = document.createElement('div');
$('#bxModals').appendChild(div);
const close = function () { UI.reset(div); div.remove(); renderAll(); };
let snapRaf = null;
// 导出弹窗内的静态 3D 快照;用当前设计实时渲染,避免预览空白
function snapSrc(w, h) {
if (!main3d || !main3d.ready()) return '';
try {
main3d.render(state, material(), currentPanels());
main3d.setFold(foldValue / 100);
return main3d.snapshot(w, h, exportBg === 'transparent');
} catch (e) { return ''; }
}
function refreshSnap() {
if (snapRaf) return;
snapRaf = requestAnimationFrame(function () {
snapRaf = null;
const im = div.querySelector('.ex-preview.3d .ex-snap');
if (im) im.src = snapSrc(760, 480);
});
}
function renderExport() {
let body;
if (exportTab === 'file') {
body = h('div', { className: 'ex-file-body' },
h('div', { className: 'ex-preview', dangerouslySetInnerHTML: { __html: dielineSVG({ noLegend: true }) } }),
h('div', { className: 'ex-side' },
h('div', { className: 'ex-label' }, '文件类型'),
h('div', { className: 'ex-type-grid' },
h('button', { onClick: exportPrintPdf }, '印刷PDF', h('em', null, 'pdf')),
h('button', { onClick: function () { UI.message.info('AI 源文件暂不支持,可导出 PDF / DXF / SVG 矢量文件'); } }, '印刷AI', h('em', null, 'ai')),
h('button', { onClick: exportDielinePdf }, '刀版PDF', h('em', null, 'pdf')),
h('button', { onClick: exportDxf }, '刀版DXF', h('em', null, 'dxf')),
h('button', { onClick: exportPreviewJpg }, '预览JPG', h('em', null, 'jpg'))
),
h('div', { className: 'ex-label' }, '色彩模式'),
h('div', { className: 'ex-mode-row' },
h('button', { className: 'on' }, 'CMYK模式'),
h('button', { onClick: function () { UI.message.info('屏幕预览为 RGB,交付印刷文件请选 CMYK'); } }, 'RGB模式')
),
h('p', { className: 'ex-note' }, '刀线和设计元素独立分层'),
h('p', { className: 'ex-note' }, '导出即视为已阅读并同意《授权许可协议》')
)
);
} else if (exportTab === 'image') {
const dims = { '2k': [1920, 1080], '3k': [2560, 1440], '4k': [3840, 2160] }[exportRes];
const ratio = { '16:9': 16 / 9, '4:3': 4 / 3, '1:1': 1 }[exportRatio];
const rw = Math.round(Math.min(dims[0], dims[1] * ratio));
const rh = Math.round(rw / ratio);
const pv = snapSrc(760, 480);
body = h('div', { className: 'ex-file-body' },
h('div', { className: 'ex-preview 3d' },
pv ? h('img', { className: 'ex-snap', src: pv, alt: '' }) : h('div', { className: 'ex-preview-empty' }, '3D 预览加载中…'),
h('div', { className: 'ex-fold-row' },
h('span', null, '开'), h('input', { type: 'range', min: 0, max: 100, value: Math.round(foldValue), onInput: function (e) { setFold(Number(e.target.value)); refreshSnap(); } }), h('span', null, '合')
)
),
h('div', { className: 'ex-side' },
[['2k', '2K', '1920*1080', '高清'], ['3k', '3K', '2560*1440', '超清'], ['4k', '4K', '3840*2160', '超高清']].map(function (r) {
return h('button', { key: r[0], className: 'ex-res' + (exportRes === r[0] ? ' on' : ''), onClick: function () { exportRes = r[0]; renderExport(); } },
h('b', null, r[1]), h('span', null, r[2]), h('em', null, r[3]));
}),
h('div', { className: 'ex-label' }, '构图比例'),
h(A.Select, { value: exportRatio, style: { width: '100%' }, options: [{ value: '16:9' }, { value: '4:3' }, { value: '1:1' }], onChange: function (v) { exportRatio = v; renderExport(); } }),
h('div', { className: 'ex-label' }, '背景'),
h(A.Radio.Group, { value: exportBg, onChange: function (e) { exportBg = e.target.value; renderExport(); }, options: [{ value: 'scene', label: '场景' }, { value: 'transparent', label: '透明' }] }),
h('button', { className: 'ex-primary', onClick: exportHdImage }, '导出效果图')
)
);
} else {
const pvVid = snapSrc(760, 480);
body = h('div', { className: 'ex-file-body' },
h('div', { className: 'ex-preview 3d' }, pvVid ? h('img', { className: 'ex-snap', src: pvVid, alt: '' }) : null),
h('div', { className: 'ex-side' },
h('div', { className: 'ex-anim-grid' }, LB.ANIMS.map(function (a) {
return h('button', { key: a.id, className: 'ex-anim' + (exportAnim === a.id ? ' on' : ''), onClick: function () { exportAnim = a.id; renderExport(); } },
h('em', null, a.dur + 's'), h('span', { className: 'anim-illus ' + a.id }));
})),
h('button', { className: 'ex-primary', onClick: exportVideo }, '导出视频')
)
);
}
UI.render(div, h(A.Modal, {
open: true, onCancel: close, footer: null, width: 940, title: null,
},
h('div', { className: 'ex-wrap' },
h('div', { className: 'ex-tabs' },
[['file', '设计文件'], ['image', '效果图'], ['video', '视频']].map(function (t) {
return h('button', { key: t[0], className: exportTab === t[0] ? 'on' : '', onClick: function () { exportTab = t[0]; renderExport(); } }, t[1]);
}),
h('button', { className: 'ex-log-btn', onClick: showExportLog }, '⏱ 导出记录')
),
body
)
));
}
renderExport();
}
let exportAnim = 'fold';
function printSvgWindow(svgStr, title) {
const win = window.open('', '_blank');
if (!win) { UI.message.warning('浏览器拦截了新窗口,请允许弹窗'); return; }
win.document.write('' + title + '' + svgStr + '