(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 KEY = 'pouchlab.design.v1';
const PLANS_KEY = 'pouchlab.bag.plans.v1';
const $ = function (s, root) { return (root || document).querySelector(s); };
const $$ = function (s, root) { return Array.prototype.slice.call((root || document).querySelectorAll(s)); };
const sampleMap = { standup: 'citrus', flatbottom: 'glow', coffee: 'morning', kraft: 'sunday', mailer: 'noir', garment: 'bloom' };
const bagPalette = ['#efe7d6', '#171513', '#f4eee3', '#c49a68', '#8a9f76', '#ff7a45', '#bfe3f2', '#d9f07c'];
function defaults() {
return {
version: 1,
name: '未命名设计',
productId: 'standup',
sizeId: 'm',
customSize: { w: 140, h: 210 },
material: 'matte',
finish: 'none',
qty: 100,
bagColor: null,
sides: { front: { bg: null, elements: [] }, back: { bg: null, elements: [] } },
uploads: [],
sampleApplied: false
};
}
let state = defaults();
try {
const saved = JSON.parse(localStorage.getItem(KEY) || 'null');
if (saved && saved.sides) state = Object.assign(defaults(), saved);
} catch (e) {}
if (!state.sides.front) state.sides.front = { bg: null, elements: [] };
if (!state.sides.back) state.sides.back = { bg: null, elements: [] };
if (!Array.isArray(state.uploads)) state.uploads = [];
if (!state.customSize || !state.customSize.w || !state.customSize.h) {
const savedSize = D.sizeOf(D.productById(state.productId), state.sizeId);
state.customSize = { w: savedSize.w, h: savedSize.h };
}
let plans = [];
try {
const savedPlans = JSON.parse(localStorage.getItem(PLANS_KEY) || '[]');
if (Array.isArray(savedPlans)) plans = savedPlans.filter(function (p) { return p && p.id && p.snap; });
} catch (e) { plans = []; }
let planName = state.name;
/* AI 设计师(首页 Agent)交接:应用其生成的袋子方案 */
(function applyAgentHandoff() {
try {
const raw = localStorage.getItem('pouchlab.agent.handoff');
if (!raw) return;
const h = JSON.parse(raw);
localStorage.removeItem('pouchlab.agent.handoff');
const s = h && h.state;
if (!s || s.kind !== 'bag' || !s.bag) return;
const b = s.bag;
if (b.productId && D.productById(b.productId)) {
state.productId = b.productId;
state.sizeId = 'custom';
}
if (b.customSize && b.customSize.w) {
state.customSize = { w: b.customSize.w, h: b.customSize.h };
state.sizeId = 'custom';
}
if (b.material) state.material = b.material;
if (b.finish) state.finish = b.finish;
if (b.qty) state.qty = b.qty;
['front', 'back'].forEach(function (k) {
const d = (b.design || {})[k];
if (d && (d.elements || []).length) {
state.sides[k] = {
bg: d.bg || null,
elements: d.elements.map(function (el) {
el.id = R.uid('el');
el.opacity = el.opacity == null ? 1 : el.opacity;
return el;
})
};
}
});
setTimeout(function () { toast('已载入 AI 设计师方案,可继续微调'); }, 600);
} catch (e) {}
})();
let mode = 'settings';
let tool = 'product';
let activeSide = 'front';
let selectedId = null;
let zoom = 1;
let summarySide = 'front';
let showGuides = true;
let lastFont = 'sans';
let history = [];
let hIndex = -1;
let dragGuides = null;
let inlineTarget = null;
let saveTimer = null;
let renderFrame = null;
let three = { rot: -18, side: 'front', modelMode: null };
let isDragging = false;
const els = {
settingsView: $('#settingsView'),
designView: $('#designView'),
summaryView: $('#summaryView'),
settingsColors: $('#settingsColors'),
settingsPreview: $('#settingsPreview'),
settingsPreviewNote: $('#settingsPreviewNote'),
studioSteps: $('#studioSteps'),
saveState: $('#saveState'),
undoBtn: $('#undoBtn'),
redoBtn: $('#redoBtn'),
continueBtn: $('#continueBtn'),
designName: $('#designName'),
designMeta: $('#designMeta'),
toolRail: $('#toolRail'),
toolKicker: $('#toolKicker'),
toolTitle: $('#toolTitle'),
toolDesc: $('#toolDesc'),
toolBody: $('#toolBody'),
sideSwitch: $('#sideSwitch'),
guidesToggle: $('#guidesToggle'),
zoomLabel: $('#zoomLabel'),
canvasShell: $('#canvasShell'),
canvasStage: $('#canvasStage'),
canvasEmpty: $('#canvasEmpty'),
printInfo: $('#printInfo'),
elementCount: $('#elementCount'),
propsChip: $('#propsChip'),
propsBody: $('#propsBody'),
propsClose: $('#propsClose'),
summaryPreview: $('#summaryPreview'),
summaryThumbs: $('#summaryThumbs'),
summaryOrder: $('#summaryOrder'),
summarySideSwitch: $('#summarySideSwitch'),
modal3d: $('#modal3d'),
pouch3d: $('#pouch3d'),
faceFront: $('#faceFront'),
faceBack: $('#faceBack'),
faceSide: $('#faceSide'),
faceSideLeft: $('#faceSideLeft'),
rotateRange: $('#rotateRange'),
previewSideSwitch: $('#previewSideSwitch'),
inlineText: $('#inlineText'),
inlineTextArea: $('#inlineTextArea'),
inlineTextDone: $('#inlineTextDone'),
successView: $('#successView'),
orderNumber: $('#orderNumber'),
toast: $('#toast'),
toastText: $('#toastText')
};
function product() { return D.productById(state.productId); }
function size() {
if (D.resolveSize) return D.resolveSize(product(), state);
return D.sizeOf(product(), state.sizeId);
}
function renderProduct() {
const p = product();
return state.bagColor ? Object.assign({}, p, { mockColor: state.bagColor }) : p;
}
function sideData(side) { return state.sides[side || activeSide]; }
function selectedEl() {
return sideData().elements.find(function (e) { return e.id === selectedId; }) || null;
}
function allElements() {
return sideData().elements;
}
function esc(s) { return R.esc(s); }
function num(v, fallback) {
const n = parseFloat(v);
return isNaN(n) ? fallback : n;
}
function clamp(v, min, max) { return Math.min(max, Math.max(min, v)); }
function mm(v) { return (Math.round(v * 10) / 10).toString(); }
function inputVal(v) { return v && v.target && 'value' in v.target ? v.target.value : v; }
function InlineNumber(props) {
const [val, setVal] = React.useState(String(props.value));
React.useEffect(function () { setVal(String(props.value)); }, [props.value]);
return h('input', {
type: 'number',
min: props.min,
max: props.max,
step: props.step || 1,
className: 's-inline-input',
value: val,
onChange: function (e) {
setVal(e.target.value);
if (props.onInput) props.onInput(e.target.value);
},
onBlur: function (e) { if (props.onCommit) props.onCommit(e.target.value); },
onKeyDown: function (e) { if (e.key === 'Enter') e.currentTarget.blur(); }
});
}
function TextField(props) {
const [val, setVal] = React.useState(props.value == null ? '' : String(props.value));
React.useEffect(function () { setVal(props.value == null ? '' : String(props.value)); }, [props.value]);
const Comp = props.multiline ? A.Input.TextArea : A.Input;
return h(Comp, Object.assign({}, props.extra || {}, {
value: val,
placeholder: props.placeholder,
onChange: function (e) {
const v = inputVal(e);
setVal(v);
if (props.onInput) props.onInput(v);
},
onBlur: function () { if (props.onCommit) props.onCommit(); }
}));
}
function toast(msg, kind) {
if (window.PL && PL.ui && PL.ui.message) {
if (kind === 'warn') PL.ui.message.warning(msg);
else PL.ui.message.success(msg);
return;
}
els.toastText.textContent = msg;
els.toast.classList.add('show');
clearTimeout(toast.timer);
toast.timer = setTimeout(function () { els.toast.classList.remove('show'); }, 2600);
}
function snapshot() {
return JSON.stringify({
name: state.name, productId: state.productId, sizeId: state.sizeId, customSize: state.customSize,
material: state.material, finish: state.finish, qty: state.qty,
bagColor: state.bagColor, sides: state.sides, sampleApplied: state.sampleApplied
});
}
function applySnapshot(str) {
const s = JSON.parse(str);
state.name = s.name;
state.productId = s.productId;
state.sizeId = s.sizeId;
state.customSize = s.customSize || state.customSize;
state.material = s.material;
state.finish = s.finish;
state.qty = s.qty;
state.bagColor = s.bagColor;
state.sides = s.sides;
state.sampleApplied = s.sampleApplied;
selectedId = null;
}
function persistPlans() {
try {
localStorage.setItem(PLANS_KEY, JSON.stringify(plans));
return true;
} catch (e) {
toast('本地空间不足,请先删除旧方案');
return false;
}
}
function planThumb(plan) {
try {
const s = JSON.parse(plan.snap);
const prod = D.productById(s.productId);
const size = s.sizeId === 'custom' && s.customSize
? { id: 'custom', label: '自定义', w: s.customSize.w, h: s.customSize.h }
: D.sizeOf(prod, s.sizeId);
const design = (s.sides && s.sides.front) || { bg: null, elements: [] };
return R.bagSVG(prod, 'front', design, { size: size, card: true, material: s.material, finish: s.finish });
} catch (e) {
return '';
}
}
function savePlan() {
const name = (planName || state.name || '未命名方案').trim().slice(0, 30) || '未命名方案';
const plan = { id: R.uid('plan'), name: name, savedAt: Date.now(), snap: snapshot() };
const same = plans.findIndex(function (p) { return p.name === name; });
if (same >= 0) plan.id = plans[same].id;
plans = plans.filter(function (p) { return p.name !== name; });
plans.unshift(plan);
if (plans.length > 12) plans = plans.slice(0, 12);
if (!persistPlans()) return;
state.name = name;
planName = name;
if (els.designName) els.designName.value = name;
updateMeta();
renderTool();
toast('方案已保存 · ' + name);
}
function loadPlan(id) {
const plan = plans.find(function (p) { return p.id === id; });
if (!plan) return;
try {
applySnapshot(plan.snap);
} catch (e) {
toast('方案数据已损坏');
return;
}
state.name = plan.name;
planName = plan.name;
if (els.designName) els.designName.value = plan.name;
selectedId = null;
commit();
if (mode === 'design') renderDesign();
else renderSettings();
toast('已载入方案 · ' + plan.name);
}
function removePlan(id) {
plans = plans.filter(function (p) { return p.id !== id; });
if (!persistPlans()) return;
renderTool();
toast('方案已删除');
}
function pushHistory() {
const snap = snapshot();
if (history[hIndex] === snap) return;
history = history.slice(0, hIndex + 1);
history.push(snap);
if (history.length > 70) history.shift();
hIndex = history.length - 1;
updateUndoButtons();
}
function updateUndoButtons() {
els.undoBtn.disabled = hIndex <= 0;
els.redoBtn.disabled = hIndex >= history.length - 1;
}
let stateDirty = false;
let stateSaveTimer = null;
function writeStateNow(silent) {
try {
const payload = {
version: 1, name: state.name, productId: state.productId, sizeId: state.sizeId, customSize: state.customSize,
material: state.material, finish: state.finish, qty: state.qty, bagColor: state.bagColor,
sides: state.sides, uploads: state.uploads.slice(0, 12), sampleApplied: state.sampleApplied,
savedAt: Date.now()
};
localStorage.setItem(KEY, JSON.stringify(payload));
if (!silent) {
els.saveState.classList.add('saving');
els.saveState.querySelector('span').textContent = '保存中…';
clearTimeout(saveTimer);
saveTimer = setTimeout(function () {
els.saveState.classList.remove('saving');
const d = new Date();
els.saveState.querySelector('span').textContent = '已保存 ' + String(d.getHours()).padStart(2, '0') + ':' + String(d.getMinutes()).padStart(2, '0');
}, 420);
}
} catch (e) {
toast('本地存储空间不足,建议下载效果图备份');
}
}
// 合并短时间内的多次保存,避免大图 dataURL 同步写 localStorage 卡住删除/拖动
function saveState(silent) {
stateDirty = true;
clearTimeout(stateSaveTimer);
stateSaveTimer = setTimeout(function () {
if (!stateDirty) return;
stateDirty = false;
writeStateNow(silent);
}, 160);
}
function flushStateSave() {
if (!stateDirty) return;
clearTimeout(stateSaveTimer);
stateDirty = false;
writeStateNow(true);
}
window.addEventListener('beforeunload', flushStateSave);
window.addEventListener('pagehide', flushStateSave);
function commit(message) {
pushHistory();
saveState();
updateMeta();
if (message) toast(message);
}
function updateMeta() {
const p = product();
const s = size();
const price = D.price(state);
const sizeLabel = state.sizeId === 'custom' ? s.w + '×' + s.h + ' mm' : s.label;
els.designMeta.textContent = p.name + ' · ' + sizeLabel + ' · ' + state.qty + ' 个';
if (mode === 'settings') els.continueBtn.innerHTML = '开始设计 →';
else if (mode === 'design') els.continueBtn.innerHTML = '下一步 · ¥' + price.total.toFixed(2);
else els.continueBtn.innerHTML = '提交订单 · ¥' + price.total.toFixed(2);
els.studioSteps.querySelectorAll('.step').forEach(function (btn) {
const step = btn.dataset.step;
btn.classList.toggle('active', step === mode);
const order = ['settings', 'design', 'summary'];
btn.classList.toggle('done', order.indexOf(step) < order.indexOf(mode));
});
els.undoBtn.disabled = hIndex <= 0;
els.redoBtn.disabled = hIndex >= history.length - 1;
document.title = state.name + ' — 袋研社 POUCHLAB';
}
function priceLines() {
const price = D.price(state);
return [
['袋型', price.product.name],
['尺寸', price.size.label + ' · ' + price.size.w + '×' + price.size.h + ' mm'],
['材质', price.material.name],
['工艺', price.finish.name],
['数量', price.quantity.value + ' 个'],
['单价', '¥' + price.unit.toFixed(2) + ' / 个']
];
}
function sampleDesignFor(p, w, h) {
const t = D.templateById(sampleMap[p.id] || 'citrus');
return { template: t, design: R.designFromTemplate(t.id, w, h, 'front') };
}
function currentPreviewDesign() {
const s = size();
if (sideData('front').elements.length) return sideData('front');
return sampleDesignFor(product(), s.w, s.h).design;
}
function renderSettings() {
const p = product();
const s = size();
const price = D.price(state);
const productCards = D.products.map(function (item) {
const smp = sampleDesignFor(item, item.sizes[0].w, item.sizes[0].h);
const svg = R.bagSVG(item, 'front', smp.design, { size: item.sizes[0], card: true });
return h(A.Card, {
key: item.id,
hoverable: true,
bordered: false,
className: 's-choice' + (item.id === state.productId ? ' on' : ''),
onClick: function () { changeProduct(item.id); }
},
h('div', { className: 's-choice-thumb', dangerouslySetInnerHTML: { __html: svg } }),
h('div', { className: 's-choice-name' }, h('b', null, item.name), h('em', null, item.en))
);
});
const sizeRadios = p.sizes.map(function (item) {
const unit = D.price(Object.assign({}, state, { sizeId: item.id })).unit;
return h(A.Radio, { key: item.id, value: item.id }, h('span', { className: 's-size-opt' },
h('b', null, item.label),
h('em', null, item.w + '×' + item.h + ' mm'),
h('i', null, '¥' + unit.toFixed(2))
));
});
sizeRadios.push(h(A.Radio, { key: 'custom', value: 'custom' }, h('span', { className: 's-size-opt' },
h('b', null, '自定义'),
h('em', null, s.w + '×' + s.h + ' mm'),
h('i', null, '可调尺寸')
)));
const sizeInput = function (key, labelText) {
return h('div', { className: 's-inline-field' },
h('label', null, labelText),
h(InlineNumber, {
value: size()[key],
min: 30,
max: key === 'w' ? 1200 : 1600,
step: 5,
onInput: function (v) { applyCustomSize(key, v, false); },
onCommit: function (v) { applyCustomSize(key, v, true); }
})
);
};
const panel = h('div', { className: 's-panel' },
h('span', { className: 'step-kicker' }, 'STEP 01 / PRODUCT'),
h('h1', null, '选择你的袋子'),
h('p', null, '袋型、尺寸、材质与数量都会影响最终报价。'),
h('div', { className: 's-field' },
h('div', { className: 's-label' }, '袋型', h('span', null, '6 种可选')),
h('div', { className: 's-choices' }, productCards)
),
h('div', { className: 's-field' },
h('div', { className: 's-label' }, '尺寸', h('span', null, s.w + ' × ' + s.h + ' mm')),
h(A.Radio.Group, { className: 's-size-group', value: state.sizeId, onChange: function (e) { changeSize(e.target.value); } }, sizeRadios),
h('div', { className: 's-custom-size' + (state.sizeId === 'custom' ? ' on' : '') },
h('div', { className: 's-custom-title' }, '自定义尺寸', h('span', null, 'mm')),
h('div', { className: 's-custom-inputs' }, sizeInput('w', '宽'), h('span', { className: 's-times' }, '×'), sizeInput('h', '高')),
h('div', { className: 'p-hint' }, '宽 30–1200 mm,高 30–1600 mm,按面积计价。')
)
),
h('div', { className: 's-field' },
h('div', { className: 's-label' }, '材质与工艺'),
h('div', { className: 's-two' },
h('div', null, h('label', null, '材质'), h(A.Select, {
value: state.material,
onChange: function (v) { changeSetting('material', v); },
options: D.materials.map(function (m) { return { value: m.id, label: m.name }; })
})),
h('div', null, h('label', null, '工艺'), h(A.Select, {
value: state.finish,
onChange: function (v) { changeSetting('finish', v); },
options: D.finishes.map(function (f) { return { value: f.id, label: f.name }; })
}))
)
),
h('div', { className: 's-field' },
h('div', { className: 's-label' }, '数量', h('span', null, '100 个起订')),
h(A.Radio.Group, {
className: 's-qty-group',
optionType: 'button',
buttonStyle: 'solid',
value: String(state.qty),
onChange: function (e) { changeSetting('qty', e.target.value); },
options: D.quantities.map(function (q) { return { label: String(q.value), value: String(q.value) }; })
}),
h('div', { className: 's-qty-custom' },
h('label', null, '自定义数量'),
h(InlineNumber, {
value: state.qty,
min: 100,
max: 100000,
step: 50,
onInput: function (v) { setQty(v, false); },
onCommit: function (v) { setQty(v, true); }
}),
h('span', null, '个 · 100 起订')
)
),
h('div', { className: 's-link' },
'需要纸盒?',
h('a', { href: 'box.html' }, '打开纸盒设计器 →')
)
);
const order = h('div', { className: 'order-card' },
h('span', { className: 'eyebrow' }, 'YOUR QUOTE'),
h('h2', null, '实时报价'),
h('div', { className: 'order-lines' }, priceLines().map(function (row, i) {
return h('div', { className: 'order-line', key: i }, h('span', null, row[0]), h('b', null, row[1]));
})),
h('div', { className: 'order-total' },
h('span', null, '预计总价', h('br'), h('small', null, '含税,不含运费')),
h('b', null, '¥' + price.total.toFixed(2), h('small', null, ' / ' + state.qty + ' 个'))
),
h(A.Button, { type: 'primary', size: 'large', block: true, onClick: enterDesign }, '开始设计 →'),
h('p', { className: 'micro' }, '免费设计 · 免费刀版 · 不满意随时修改')
);
UI.render(document.getElementById('settingsPanel'), panel);
UI.render(document.getElementById('settingsOrderCard'), order);
UI.hydrate(document.getElementById('settingsView'));
els.settingsPreviewNote.textContent = s.w + ' × ' + s.h + ' mm · 正面预览';
els.settingsPreview.innerHTML = R.bagSVG(renderProduct(), 'front', currentPreviewDesign(), { size: s, card: true, material: state.material, finish: state.finish });
const colors = [p.mockColor].concat(bagPalette).filter(function (c, i, a) { return a.indexOf(c) === i; });
els.settingsColors.innerHTML = colors.map(function (c) {
const on = (state.bagColor || p.mockColor).toLowerCase() === c.toLowerCase();
return '';
}).join('');
}
function scaleSides(oldSize, newSize) {
const sx = newSize.w / oldSize.w;
const sy = newSize.h / oldSize.h;
const sm = Math.min(sx, sy);
['front', 'back'].forEach(function (side) {
sideData(side).elements.forEach(function (el) {
el.x *= sx;
el.y *= sy;
el.w *= sx;
if (el.h != null) el.h *= sy;
if (el.type === 'text') {
el.size *= sm;
if (el.strokeWidth) el.strokeWidth *= sm;
}
if (el.type === 'badge') {
el.size *= sm;
el.h = el.w;
}
if (el.type === 'sticker') el.h = el.w;
if (el.strokeWidth) el.strokeWidth *= sm;
if (el.radius) el.radius *= sm;
});
});
}
function changeProduct(id) {
const oldP = product();
const oldS = size();
const newP = D.productById(id);
if (newP.id === oldP.id) return;
const newS = D.sizeOf(newP, newP.sizes[Math.floor(newP.sizes.length / 2)].id);
const hasElements = state.sides.front.elements.length || state.sides.back.elements.length;
if (hasElements) scaleSides(oldS, newS);
state.productId = newP.id;
state.sizeId = newS.id;
state.bagColor = null;
selectedId = null;
commit();
renderSettings();
renderDesign();
if (mode === 'summary') renderSummary();
toast(hasElements ? '已切换袋型,设计已等比适配' : '已选择「' + newP.name + '」');
}
function changeSize(id) {
const oldS = size();
if (id === 'custom') {
if (state.sizeId !== 'custom') state.customSize = { w: oldS.w, h: oldS.h };
state.sizeId = 'custom';
} else {
if (state.sizeId === id) return;
state.sizeId = id;
}
const newS = size();
if (newS.w !== oldS.w || newS.h !== oldS.h) scaleSides(oldS, newS);
selectedId = null;
commit();
renderSettings();
renderDesign();
if (mode === 'summary') renderSummary();
}
function refreshSettingsPreview() {
if (mode !== 'settings') return;
const s = size();
els.settingsPreviewNote.textContent = s.w + ' × ' + s.h + ' mm · 正面预览';
els.settingsPreview.innerHTML = R.bagSVG(renderProduct(), 'front', currentPreviewDesign(), {
size: s, card: true, material: state.material, finish: state.finish
});
}
function applyCustomSize(key, raw, commitNow) {
const p = product();
const base = D.sizeOf(p, p.sizes[Math.floor(p.sizes.length / 2)].id);
const oldS = size();
const dims = {
w: state.sizeId === 'custom' ? state.customSize.w : oldS.w,
h: state.sizeId === 'custom' ? state.customSize.h : oldS.h
};
const fallback = key === 'w' ? base.w : base.h;
dims[key] = clamp(Math.round(num(raw, fallback)), 30, key === 'w' ? 1200 : 1600);
state.customSize = dims;
state.sizeId = 'custom';
const newS = size();
if (newS.w !== oldS.w || newS.h !== oldS.h) scaleSides(oldS, newS);
updateMeta();
refreshSettingsPreview();
if (mode === 'design') scheduleRenderCanvas();
if (mode === 'summary') renderSummary();
if (commitNow) {
commit();
renderSettings();
if (mode === 'design') renderTool();
}
}
function setQty(raw, commitNow) {
const v = clamp(Math.round(num(raw, 100)), 100, 100000);
if (v === state.qty) {
if (commitNow) {
commit();
renderSettings();
if (mode === 'design') renderTool();
}
return;
}
state.qty = v;
updateMeta();
if (mode === 'settings') refreshSettingsPreview();
if (mode === 'summary') renderSummary();
if (commitNow) {
commit();
renderSettings();
if (mode === 'design') renderTool();
}
}
function changeSetting(key, value) {
if (key === 'material') state.material = value;
if (key === 'finish') state.finish = value;
if (key === 'qty') { setQty(value, true); return; }
commit();
renderSettings();
if (mode === 'design') { renderCanvas(); renderTool(); }
if (mode === 'summary') renderSummary();
}
function changeBagColor(color) {
state.bagColor = color;
commit();
renderSettings();
renderDesign();
if (mode === 'summary') renderSummary();
}
function applyTemplate(id, opts) {
const t = D.templateById(id);
if (!t) return;
const s = size();
state.sides.front = R.designFromTemplate(id, s.w, s.h, 'front');
const back = R.designFromTemplate(id, s.w, s.h, 'back');
state.sides.back = back;
state.sampleApplied = true;
activeSide = 'front';
selectedId = null;
commit();
renderSettings();
renderDesign();
if (!opts || !opts.silent) toast('已套用模板「' + t.name + '」· 可撤销');
}
function ensureSample() {
if (state.sampleApplied) return;
if (state.sides.front.elements.length || state.sides.back.elements.length) return;
const s = size();
const t = D.templateById(sampleMap[product().id] || 'citrus');
state.sides.front = R.designFromTemplate(t.id, s.w, s.h, 'front');
state.sides.back = R.designFromTemplate(t.id, s.w, s.h, 'back');
state.sampleApplied = true;
saveState(true);
pushHistory();
}
function setMode(next) {
mode = next;
els.settingsView.hidden = next !== 'settings';
els.designView.hidden = next !== 'design';
els.summaryView.hidden = next !== 'summary';
hideInlineText();
if (next === 'settings') {
renderSettings();
} else if (next === 'design') {
if (!skipSample) ensureSample();
skipSample = false;
renderDesign();
requestAnimationFrame(function () { renderCanvas(); });
} else if (next === 'summary') {
renderSummary();
}
updateMeta();
}
let skipSample = false;
function enterDesign() {
setMode('design');
}
function renderDesign() {
if (mode !== 'design') return;
els.sideSwitch.querySelectorAll('button').forEach(function (b) {
b.classList.toggle('on', b.dataset.side === activeSide);
});
els.guidesToggle.checked = showGuides;
const s = size();
els.printInfo.textContent = '印刷区 ' + s.w + ' × ' + s.h + ' mm';
renderCanvas();
renderProps();
renderTool();
updateMeta();
}
function editorViewBox() {
const p = product().pad;
const s = size();
return { x: -p.l - 18, y: -p.t - 12, w: s.w + p.l + p.r + 30, h: s.h + p.t + p.b + 34 };
}
function computeScale() {
const vb = editorViewBox();
const availW = Math.max(220, els.canvasShell.clientWidth - 68);
const availH = Math.max(220, els.canvasShell.clientHeight - 52);
const fit = Math.min(availW / vb.w, availH / vb.h);
return { vb: vb, fit: fit, scale: fit * zoom };
}
function renderCanvas() {
if (mode !== 'design') return;
if (selectedId && !selectedEl()) selectedId = null;
const p = renderProduct();
const s = size();
const total = state.sides.front.elements.length + state.sides.back.elements.length;
els.elementCount.textContent = total + ' 个图层';
els.canvasEmpty.hidden = sideData().elements.length > 0;
els.printInfo.textContent = '印刷区 ' + s.w + ' × ' + s.h + ' mm';
const cs = computeScale();
els.canvasStage.style.width = (cs.vb.w * cs.scale) + 'px';
els.canvasStage.style.height = (cs.vb.h * cs.scale) + 'px';
els.zoomLabel.textContent = zoom === 1 ? '适应' : Math.round(zoom * 100) + '%';
const scrollLeft = els.canvasShell.scrollLeft;
const scrollTop = els.canvasShell.scrollTop;
els.canvasStage.innerHTML = R.bagSVG(p, activeSide, sideData(), {
size: s, ui: true, selectedId: selectedId, showGuides: showGuides,
showDims: true, pxPerMm: cs.scale, guides: dragGuides,
material: state.material, finish: state.finish
});
els.canvasShell.scrollLeft = scrollLeft;
els.canvasShell.scrollTop = scrollTop;
}
function scheduleRenderCanvas() {
if (renderFrame) return;
renderFrame = requestAnimationFrame(function () {
renderFrame = null;
renderCanvas();
});
}
function updateZoom(next) {
zoom = clamp(next, 0.45, 2.6);
renderCanvas();
}
function elementLabel(el) {
if (el.type === 'text') return (el.text || '文字').slice(0, 16);
if (el.type === 'image') return el.name || '图片';
if (el.type === 'shape') return { rect: '矩形', circle: '圆形', triangle: '三角形', line: '线条' }[el.shape] || '图形';
if (el.type === 'sticker') return '贴纸 · ' + el.sticker;
if (el.type === 'badge') return '圆形徽章';
if (el.type === 'barcode') return '条码 · ' + (el.value || '');
if (el.type === 'qr') return '二维码 · ' + (el.value || '');
if (el.type === 'asset') return '素材 · ' + (el.name || el.asset || '');
return '图层';
}
function elementIcon(el) {
const icons = {
text: '',
image: '',
shape: '',
sticker: '',
badge: '',
barcode: '',
qr: '',
asset: ''
};
return '';
}
function renderTool() {
const meta = {
product: ['PRODUCT', '产品设置', '当前袋型、尺寸与印刷信息'],
templates: ['TEMPLATES', '模板库', '套用后可继续自由修改'],
upload: ['UPLOAD', '上传素材', '建议使用透明背景 PNG 或 SVG'],
text: ['TYPOGRAPHY', '文字工具', '标题、正文与字体选择'],
shapes: ['GRAPHICS', '图形与贴纸', '用图形建立视觉层次'],
layers: ['LAYERS', '图层管理', '从上到下即前后顺序']
}[tool] || ['TOOL', '工具', ''];
els.toolKicker.textContent = meta[0];
els.toolTitle.textContent = meta[1];
els.toolDesc.textContent = meta[2];
els.toolRail.querySelectorAll('button[data-tool]').forEach(function (b) {
b.classList.toggle('active', b.dataset.tool === tool);
});
UI.render(els.toolBody, toolPanelReact());
}
const barcodeIcon = h('span', { dangerouslySetInnerHTML: { __html: '' } });
const qrIcon = h('span', { dangerouslySetInnerHTML: { __html: '' } });
const copyIcon = h('span', { dangerouslySetInnerHTML: { __html: '' } });
function eyeIcon(hidden) {
return h('span', {
dangerouslySetInnerHTML: {
__html: hidden
? ''
: ''
}
});
}
function applyFont(key) {
const el = selectedEl();
if (el && el.type === 'text') {
el.font = key;
lastFont = key;
commit();
renderCanvas();
renderProps();
return;
}
addTextPreset('body', key);
}
function toolPanelReact() {
if (tool === 'templates') {
return h('div', null,
h('div', { className: 'p-hint', style: { marginBottom: '12px' } }, '点击套用 · 会覆盖当前画布,可用撤销恢复。'),
h('div', { className: 'tpl-grid' }, D.templates.map(function (t) {
return h(A.Card, {
key: t.id,
hoverable: true,
bordered: false,
className: 'tpl-card',
bodyStyle: { padding: 0 },
onClick: function () { applyTemplate(t.id); }
},
h('div', { className: 'tpl-thumb', style: { background: t.tint }, dangerouslySetInnerHTML: { __html: R.templatePreview(t) } }),
h('div', { className: 'tpl-name' }, t.name, h(A.Tag, { bordered: false, className: 'tpl-tag' }, t.category))
);
}))
);
}
if (tool === 'upload') {
return h('div', null,
h('div', { className: 'tool-section' },
h('div', { className: 'tool-section-title' }, '上传素材'),
h(A.Upload.Dragger, {
accept: 'image/*',
showUploadList: false,
customRequest: function (options) { addUploadedFile(options.file); },
children: h('div', { className: 'upload-zone' },
h('div', { className: 'icon-box' }, h('span', { className: 'icon', style: { width: '18px', height: '18px' } })),
h('b', null, '点击上传,或拖入图片'),
h('span', null, 'PNG · JPG · SVG · 建议 ≥ 1000px')
)
})
),
state.uploads.length ? h('div', { className: 'tool-section' },
h('div', { className: 'tool-section-title' }, '最近上传', h('span', null, state.uploads.length + '')),
h('div', { className: 'uploaded-grid' }, state.uploads.map(function (up) {
return h('div', {
className: 'uploaded-item', key: up.id, title: '点击放置到画布',
onClick: function (e) {
if (e.target.closest('button')) return;
addImageFromUpload(up);
}
},
h('img', { src: up.src, alt: up.name }),
h('button', {
onClick: function (e) {
e.stopPropagation();
state.uploads = state.uploads.filter(function (x) { return x.id !== up.id; });
commit();
renderTool();
}
}, '✕')
);
}))
) : null,
h('div', { className: 'tool-section' },
h('div', { className: 'tool-section-title' }, '使用建议'),
h('div', { className: 'p-hint' }, 'Logo 请使用 1 色或透明背景 PNG;图片会自动等比缩放。上传后可在右侧属性面板调整「填满 / 完整显示」与单色印刷。')
)
);
}
if (tool === 'text') {
const presets = [
{ id: 'title', name: '大标题', desc: '适合品牌名 / 产品名', cls: 'big' },
{ id: 'subtitle', name: '副标题', desc: '补充口味或卖点', cls: 'mid' },
{ id: 'body', name: '正文', desc: '配料、说明与信息', cls: 'sm' },
{ id: 'latin', name: '英文标题', desc: '无衬线大写字母', cls: 'en' }
];
return h('div', null,
h('div', { className: 'tool-section' },
h('div', { className: 'tool-section-title' }, '添加文字'),
presets.map(function (p) {
return h('button', { key: p.id, className: 'text-preset', onClick: function () { addTextPreset(p.id); } },
h('span', null, h('b', null, p.name), h('span', null, p.desc)),
h('span', { className: 't-label ' + p.cls }, p.cls === 'en' ? 'EN' : 'Aa')
);
})
),
h('div', { className: 'tool-section' },
h('div', { className: 'tool-section-title' }, '字体', h('span', null, '点击应用或新建')),
h('div', { className: 'font-grid' }, Object.keys(D.fonts).map(function (k) {
return h('button', { key: k, className: 'font-item', onClick: function () { applyFont(k); } },
h('span', { style: { fontFamily: D.fonts[k].stack } }, '字体 Aa'),
h('span', null, D.fonts[k].label)
);
}))
)
);
}
if (tool === 'shapes') {
const shapes = [
{ id: 'rect', name: '矩形' },
{ id: 'circle', name: '圆形' },
{ id: 'triangle', name: '三角形' },
{ id: 'line', name: '线条' }
];
const lib = window.PL && window.PL.boxlib;
const icons = lib && lib.ICONS ? lib.ICONS : {};
return h('div', null,
h('div', { className: 'tool-section' },
h('div', { className: 'tool-section-title' }, '基础图形'),
h('div', { className: 'shape-grid' }, shapes.map(function (s) {
return h('button', { key: s.id, className: 'shape-btn', title: s.name, onClick: function () { addShape(s.id); } },
h('span', { className: 'shape-ico ' + s.id })
);
})),
h('div', { className: 'p-actions', style: { marginTop: '8px' } },
h(A.Button, { block: true, icon: barcodeIcon, onClick: function () { addShape('barcode'); } }, '添加条码'),
h(A.Button, { block: true, icon: qrIcon, onClick: function () { addShape('qr'); } }, '添加二维码')
)
),
Object.keys(icons).length ? h('div', { className: 'tool-section' },
h('div', { className: 'tool-section-title' }, '平台素材', h('span', null, Object.keys(icons).length + '')),
h('div', { className: 'asset-grid' }, Object.keys(icons).map(function (id) {
return h('button', {
key: id, className: 'asset-btn', title: icons[id].name,
onClick: function () { addAsset(id); },
dangerouslySetInnerHTML: { __html: lib.assetSvg(id, '#17140f') }
});
}))
) : null,
h('div', { className: 'tool-section' },
h('div', { className: 'tool-section-title' }, '贴纸库', h('span', null, Object.keys(D.stickers).length + '')),
h('div', { className: 'sticker-grid' }, Object.keys(D.stickers).map(function (k) {
return h('button', { key: k, className: 'sticker-btn', title: k, onClick: function () { addSticker(k); } },
h('span', {
dangerouslySetInnerHTML: {
__html: ''
}
})
);
}))
)
);
}
if (tool === 'layers') {
const list = allElements();
return h('div', null,
h('div', { className: 'tool-section' },
h('div', { className: 'tool-section-title' }, '图层 · ' + (activeSide === 'front' ? '正面' : '背面'), h('span', null, list.length + ' 个')),
list.length ? h(A.List, {
className: 'layer-list ant-list',
dataSource: list.slice().reverse(),
renderItem: function (item) {
return h(A.List.Item, {
key: item.id,
className: 'layer-row' + (item.id === selectedId ? ' on' : ''),
'data-layer-id': item.id,
onClick: function () { selectedId = item.id; renderCanvas(); renderProps(); renderTool(); }
},
h('span', { className: 'layer-icon', dangerouslySetInnerHTML: { __html: elementIcon(item) } }),
h('span', { className: 'layer-name' }, elementLabel(item), h('small', null, item.type)),
h('button', {
className: 'layer-eye',
title: item.hidden ? '显示图层' : '隐藏图层',
onClick: function (e) { e.stopPropagation(); item.hidden = !item.hidden; commit(); renderCanvas(); renderTool(); }
}, eyeIcon(item.hidden)),
h('button', {
className: 'layer-order',
title: '移到最顶层',
onClick: function (e) { e.stopPropagation(); selectedId = item.id; frontElement(); }
}, '⤒'),
h('button', {
className: 'layer-order',
title: '移到最底层',
onClick: function (e) { e.stopPropagation(); selectedId = item.id; backElement(); }
}, '⤓'),
h('button', {
className: 'layer-del',
title: '删除图层',
onClick: function (e) { e.stopPropagation(); deleteElementById(item.id); }
}, '✕')
);
}
}) : h(A.Empty, { description: '这一面还没有图层', image: A.Empty.PRESENTED_IMAGE_SIMPLE })
),
h('div', { className: 'p-actions' },
h(A.Button, { block: true, icon: copyIcon, onClick: duplicateSide }, '复制到另一面'),
h(A.Button, { block: true, danger: true, onClick: function () { clearSide(); } }, '清空本面'),
h(A.Button, { block: true, danger: true, onClick: clearAllSides }, '一键清空全部')
)
);
}
const s = size();
const p = product();
const price = D.price(state);
return h('div', null,
h('div', { className: 'tool-section' },
h('div', { className: 'tool-section-title' }, '当前袋型'),
h('div', { className: 's-current' },
h('div', { className: 's-current-thumb', dangerouslySetInnerHTML: { __html: R.bagSVG(renderProduct(), 'front', currentPreviewDesign(), { size: s, card: true, material: state.material, finish: state.finish }) } }),
h('div', null, h('b', null, p.name), h('em', null, p.en), h('span', null, s.w + ' × ' + s.h + ' mm'))
)
),
h('div', { className: 'tool-section' },
h('div', { className: 'tool-section-title' }, '尺寸'),
h(A.Radio.Group, {
className: 's-size-group',
value: state.sizeId,
onChange: function (e) { changeSize(e.target.value); },
options: p.sizes.map(function (item) { return { label: item.label, value: item.id }; }).concat([{ label: '自定义', value: 'custom' }])
}),
h('div', { className: 's-custom-inputs', style: { marginTop: '10px' } },
h('div', { className: 's-inline-field' }, h('label', null, '宽'),
h(InlineNumber, {
value: size().w, min: 30, max: 1200, step: 5,
onInput: function (v) { applyCustomSize('w', v, false); },
onCommit: function (v) { applyCustomSize('w', v, true); }
})
),
h('span', { className: 's-times' }, '×'),
h('div', { className: 's-inline-field' }, h('label', null, '高'),
h(InlineNumber, {
value: size().h, min: 30, max: 1600, step: 5,
onInput: function (v) { applyCustomSize('h', v, false); },
onCommit: function (v) { applyCustomSize('h', v, true); }
})
)
)
),
h('div', { className: 'tool-section' },
h('div', { className: 'tool-section-title' }, '材质与工艺'),
h('div', { className: 's-two' },
h('div', null, h('label', null, '材质'), h(A.Select, {
value: state.material,
onChange: function (v) { changeSetting('material', v); },
options: D.materials.map(function (m) { return { value: m.id, label: m.name }; })
})),
h('div', null, h('label', null, '工艺'), h(A.Select, {
value: state.finish,
onChange: function (v) { changeSetting('finish', v); },
options: D.finishes.map(function (f) { return { value: f.id, label: f.name }; })
}))
)
),
h('div', { className: 'tool-section' },
h('div', { className: 'tool-section-title' }, '数量'),
h(A.Radio.Group, {
className: 's-qty-group',
optionType: 'button',
buttonStyle: 'solid',
value: String(state.qty),
onChange: function (e) { changeSetting('qty', e.target.value); },
options: D.quantities.map(function (q) { return { label: String(q.value), value: String(q.value) }; })
}),
h('div', { className: 's-qty-custom' },
h('label', null, '自定义数量'),
h(InlineNumber, {
value: state.qty, min: 100, max: 100000, step: 50,
onInput: function (v) { setQty(v, false); },
onCommit: function (v) { setQty(v, true); }
}),
h('span', null, '个 · 100 起订')
)
),
h('div', { className: 'tool-section' },
h('div', { className: 'tool-section-title' }, '袋身颜色'),
h('div', { className: 'p-swatches' }, [p.mockColor].concat(bagPalette).filter(function (c, i, a) { return a.indexOf(c) === i; }).map(function (c) {
const on = (state.bagColor || p.mockColor).toLowerCase() === c.toLowerCase();
return h('button', { key: c, className: 'p-swatch' + (on ? ' on' : ''), style: { background: c }, onClick: function () { changeBagColor(c); } });
})),
h('div', { className: 'pms-title' }, '参考潘通色'),
pmsGrid(function (c) { changeBagColor(c.hex); }, state.bagColor || p.mockColor)
),
h('div', { className: 'p-price-card' },
h('div', { className: 'p-price-line' }, h('span', null, '单价'), h('b', null, '¥' + price.unit.toFixed(2) + ' / 个')),
h('div', { className: 'p-price-line' }, h('span', null, '合计 · ' + state.qty + ' 个'), h('b', null, '¥' + price.total.toFixed(2)))
),
h('div', { className: 'tool-section' },
h('div', { className: 'tool-section-title' }, '我的方案', h('span', null, plans.length + ' 个')),
h('div', { className: 'plan-save' },
h(A.Input, {
defaultValue: planName,
placeholder: '给当前设计起个名字',
maxLength: 30,
onChange: function (e) { planName = e.target.value; },
onPressEnter: savePlan
}),
h(A.Button, { type: 'primary', onClick: savePlan }, '保存')
),
plans.length ? h('div', { className: 'plan-list' }, plans.map(function (plan) {
return h('div', { className: 'plan-item', key: plan.id },
h('div', { className: 'plan-thumb', dangerouslySetInnerHTML: { __html: planThumb(plan) } }),
h('div', { className: 'plan-meta' },
h('b', null, plan.name),
h('span', null, new Date(plan.savedAt).toLocaleString('zh-CN', { month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit' }))
),
h('div', { className: 'plan-actions' },
h('button', { onClick: function () { loadPlan(plan.id); }, title: '载入方案' }, '载入'),
h('button', { className: 'del', onClick: function () { removePlan(plan.id); }, title: '删除方案' }, '✕')
)
);
})) : h('div', { className: 'p-hint' }, '保存后可随时切换不同设计方案,最多 12 个。')
),
h('div', { className: 'p-actions', style: { marginTop: '12px' } },
h(A.Button, { block: true, onClick: function () { setMode('settings'); } }, '返回设置'),
h(A.Button, { block: true, danger: true, onClick: function () { clearSide(); } }, '清空本面')
)
);
}
function renderProps() {
UI.render(els.propsBody, propsTree());
document.body.classList.toggle('props-open', !!selectedEl());
}
function propsTree() {
const el = selectedEl();
if (!el) {
const s = size();
const p = product();
const side = sideData();
const price = D.price(state);
els.propsChip.textContent = 'CANVAS';
const bgColors = ['#f7f2e7', '#ffffff', '#17140f', '#ff5c2b', '#d9f07c', '#1e3a2c', '#bfe3f2', '#e8d5b8', '#f3d9d3'];
return h('div', null,
h('div', { className: 'p-section' },
h('div', { className: 'p-section-title' }, '印刷画布'),
h('div', { className: 'p-row' },
h('div', { className: 'p-field' }, h('label', null, '宽度'), h(A.Input, { value: s.w + ' mm', readOnly: true })),
h('div', { className: 'p-field' }, h('label', null, '高度'), h(A.Input, { value: s.h + ' mm', readOnly: true }))
),
h('div', { className: 'p-row' },
h('div', { className: 'p-field' }, h('label', null, '当前面'),
h(A.Segmented, {
value: activeSide,
block: true,
onChange: function (v) { changeSide(v); },
options: [{ label: '正面', value: 'front' }, { label: '背面', value: 'back' }]
})
)
),
h('div', { className: 'p-hint' }, '刀版线外 3mm 为出血位,重要文字请放在安全区内。')
),
h('div', { className: 'p-section' },
h('div', { className: 'p-section-title' }, '印刷底色'),
h('div', { className: 'p-swatches' },
h('button', { className: 'p-swatch' + (!side.bg ? ' on' : ''), style: { background: 'linear-gradient(135deg,#fff 45%,#ffd0c0 55%)' }, title: '无底色', onClick: function () { side.bg = null; commit(); renderCanvas(); renderProps(); } }),
bgColors.map(function (c) {
return h('button', { key: c, className: 'p-swatch' + (side.bg === c ? ' on' : ''), style: { background: c }, onClick: function () { side.bg = c; commit(); renderCanvas(); renderProps(); } });
})
),
h('div', { className: 'p-row', style: { marginTop: '10px' } },
h('div', { className: 'p-field' }, h('label', null, '自定义底色'),
h(A.ColorPicker, {
key: 'bg-' + activeSide + '-' + (side.bg || 'none'),
defaultValue: side.bg || '#f7f2e7',
showText: true,
onChange: function (c) { side.bg = c.toHexString(); renderCanvas(); },
onChangeComplete: function (c) { side.bg = c.toHexString(); commit(); renderCanvas(); }
})
)
),
h('div', { className: 'pms-title' }, '参考潘通色'),
pmsGrid(function (c) { side.bg = c.hex; commit(); renderCanvas(); renderProps(); }, side.bg)
),
h('div', { className: 'p-section' },
h('div', { className: 'p-section-title' }, '袋身颜色'),
h('div', { className: 'p-swatches' }, [p.mockColor].concat(bagPalette).filter(function (c, i, a) { return a.indexOf(c) === i; }).map(function (c) {
const on = (state.bagColor || p.mockColor).toLowerCase() === c.toLowerCase();
return h('button', { key: c, className: 'p-swatch' + (on ? ' on' : ''), style: { background: c }, onClick: function () { changeBagColor(c); renderProps(); } });
}))
),
h('div', { className: 'p-section' },
h('div', { className: 'p-section-title' }, '画布工具'),
h('label', { className: 'p-check' }, '显示刀版线',
h(A.Switch, { size: 'small', checked: showGuides, onChange: function (v) { showGuides = v; renderCanvas(); } })
),
h('div', { className: 'p-actions', style: { marginTop: '10px' } },
h(A.Button, { block: true, onClick: duplicateSide }, '复制到' + (activeSide === 'front' ? '背面' : '正面')),
h(A.Button, { block: true, danger: true, onClick: function () { clearSide(); } }, '清空本面')
)
),
h('div', { className: 'p-section' },
h('div', { className: 'p-section-title' }, '报价'),
h('div', { className: 'p-price-card' },
h('div', { className: 'p-price-line' }, h('span', null, p.name + ' · ' + s.label + ' · ' + state.qty + ' 个'), h('b', null, '¥' + price.total.toFixed(2)))
),
h('div', { className: 'p-hint' }, '切换尺寸或数量后价格会实时更新。')
)
);
}
els.propsChip.textContent = el.type.toUpperCase();
const box = R.elementBox(el);
const numField = function (label, prop, value, min, max, step) {
const rounded = typeof value === 'number' ? Math.round(value * 100) / 100 : value;
return h('div', { className: 'p-field' }, h('label', null, label),
h(A.InputNumber, {
value: rounded,
min: min,
max: max,
step: step || 0.5,
style: { width: '100%' },
onChange: function (v) { if (v != null) { updateSelected(prop, v); commit(); renderCanvas(); } }
})
);
};
const colorField = function (label, prop, value) {
const hex = value && value !== 'none' ? value : '#17140f';
return h('div', { className: 'p-field' }, h('label', null, label),
h(A.ColorPicker, {
// 非受控:拖动色相时由组件自身维护 HSV,避免每次 onChange 重建导致色相回弹
key: 'cp-' + prop + '-' + (selectedId || '') + '-' + hex,
defaultValue: hex,
showText: true,
onChange: function (c) { updateSelected(prop, c.toHexString()); renderCanvas(); },
// 提交时不再 renderProps,避免重建 ColorPicker 导致取色面板关闭
onChangeComplete: function (c) { updateSelected(prop, c.toHexString()); commit(); renderCanvas(); }
})
);
};
let specific = null;
if (el.type === 'text') {
specific = h('div', { className: 'p-section' },
h('div', { className: 'p-section-title' }, '文字内容'),
h(TextField, {
multiline: true,
value: el.text,
extra: { autoSize: { minRows: 2, maxRows: 5 } },
onInput: function (v) { updateSelected('text', v); renderCanvas(); },
onCommit: function () { commit(); renderTool(); }
}),
h('div', { className: 'p-section-title', style: { marginTop: '16px' } }, '字体'),
h(A.Select, {
value: el.font || 'sans',
style: { width: '100%' },
onChange: function (v) { updateSelected('font', v); commit(); renderCanvas(); renderProps(); },
options: Object.keys(D.fonts).map(function (k) { return { value: k, label: D.fonts[k].label }; })
}),
h('div', { className: 'p-row', style: { marginTop: '9px' } },
numField('字号 mm', 'size', el.size, 2, 120, 0.5),
numField('字距', 'spacing', el.spacing || 0, -0.2, 0.4, 0.01)
),
h('div', { className: 'p-row' },
numField('行高', 'lineHeight', el.lineHeight || 1.25, 0.7, 3, 0.05),
colorField('颜色', 'color', el.color)
),
h('div', { className: 'p-row' },
h('div', { className: 'p-field' }, h('label', null, '字重'),
h(A.Segmented, {
value: String(el.weight || 400),
block: true,
onChange: function (v) { updateSelected('weight', Number(v)); commit(); renderCanvas(); renderProps(); },
options: [{ label: '400', value: '400' }, { label: '600', value: '600' }, { label: '800', value: '800' }]
})
)
),
h('div', { className: 'p-row' },
h('div', { className: 'p-field' }, h('label', null, '对齐'),
h(A.Segmented, {
value: el.align || 'left',
block: true,
onChange: function (v) { updateSelected('align', v); commit(); renderCanvas(); renderProps(); },
options: [{ label: '左', value: 'left' }, { label: '中', value: 'center' }, { label: '右', value: 'right' }]
})
),
h('div', { className: 'p-field' }, h('label', null, '斜体'),
h('div', { className: 'p-check p-check-box' }, h('span', { style: { fontFamily: 'Georgia' } }, 'I'),
h(A.Switch, { size: 'small', checked: !!el.italic, onChange: function (v) { updateSelected('italic', v); commit(); renderCanvas(); renderProps(); } })
)
)
)
);
} else if (el.type === 'image') {
specific = h('div', { className: 'p-section' },
h('div', { className: 'p-section-title' }, '图片'),
h('div', { className: 'p-row' },
h('div', { className: 'p-field' }, h('label', null, '填充方式'),
h(A.Segmented, {
value: el.fit || 'contain',
block: true,
onChange: function (v) { updateSelected('fit', v); commit(); renderCanvas(); renderProps(); },
options: [{ label: '完整显示', value: 'contain' }, { label: '填满裁切', value: 'cover' }]
})
)
),
h('label', { className: 'p-check' }, '单色印刷',
h(A.Switch, { size: 'small', checked: !!el.mono, onChange: function (v) { updateSelected('mono', v); commit(); renderCanvas(); renderProps(); } })
),
h('div', { className: 'p-actions', style: { marginTop: '10px' } },
h(A.Button, { block: true, onClick: function () { pickUpload(true); } }, '替换图片')
)
);
} else if (el.type === 'shape') {
specific = h('div', { className: 'p-section' },
h('div', { className: 'p-section-title' }, el.shape === 'line' ? '线条' : '外观'),
el.shape !== 'line' ? h('div', { className: 'p-row' },
colorField('填充', 'fill', el.fill),
el.shape === 'rect' ? numField('圆角', 'radius', el.radius || 0, 0, 80, 0.5) : null
) : null,
h('div', { className: 'p-row' },
colorField('描边', 'stroke', el.stroke),
numField('描边宽', 'strokeWidth', el.strokeWidth || 0, 0, 20, 0.1)
)
);
} else if (el.type === 'sticker') {
specific = h('div', { className: 'p-section' },
h('div', { className: 'p-section-title' }, '贴纸'),
h('div', { className: 'p-row' }, colorField('颜色', 'color', el.color)),
h('div', { className: 'p-hint' }, '拖动四角可等比缩放。')
);
} else if (el.type === 'badge') {
specific = h('div', { className: 'p-section' },
h('div', { className: 'p-section-title' }, '圆形徽章'),
h(TextField, {
multiline: true,
value: el.text || '',
extra: { autoSize: { minRows: 2, maxRows: 3 } },
onInput: function (v) { updateSelected('text', v); renderCanvas(); },
onCommit: function () { commit(); renderTool(); }
}),
h('div', { className: 'p-row', style: { marginTop: '9px' } },
numField('环文字号', 'size', el.size || 3, 1, 40, 0.2),
colorField('颜色', 'color', el.color)
)
);
} else if (el.type === 'barcode') {
specific = h('div', { className: 'p-section' },
h('div', { className: 'p-section-title' }, '条码 / SKU'),
h(TextField, {
value: el.value || '',
onInput: function (v) { updateSelected('value', v); renderCanvas(); },
onCommit: function () { commit(); renderTool(); }
}),
h('label', { className: 'p-check', style: { marginTop: '9px' } }, '显示数字',
h(A.Switch, { size: 'small', checked: el.showText !== false, onChange: function (v) { updateSelected('showText', v); commit(); renderCanvas(); renderProps(); } })
),
h('div', { className: 'p-row' }, colorField('颜色', 'color', el.color)),
h('div', { className: 'p-hint' }, '输入 12–13 位数字会生成真实 EAN-13 校验位;输入链接或文字会生成稳定条码。')
);
} else if (el.type === 'qr') {
specific = h('div', { className: 'p-section' },
h('div', { className: 'p-section-title' }, '二维码'),
h(TextField, {
multiline: true,
value: el.value || '',
extra: { autoSize: { minRows: 2, maxRows: 4 } },
onInput: function (v) { updateSelected('value', v); renderCanvas(); },
onCommit: function () { commit(); renderTool(); }
}),
h('div', { className: 'p-row', style: { marginTop: '9px' } },
colorField('码点颜色', 'color', el.color),
h('div', { className: 'p-field' }, h('label', null, '浅色底'),
h(A.Switch, { size: 'small', checked: el.light !== 'none', onChange: function (v) { updateSelected('light', v ? '#ffffff' : 'none'); commit(); renderCanvas(); renderProps(); } })
)
),
h('div', { className: 'p-hint' }, '填写网址、微信号或任意文字即可生成二维码;保留浅色底可提高扫码成功率。')
);
} else if (el.type === 'asset') {
specific = h('div', { className: 'p-section' },
h('div', { className: 'p-section-title' }, '平台素材'),
h('div', { className: 'p-row' }, colorField('颜色', 'color', el.color)),
h('div', { className: 'p-hint' }, '素材为矢量图标,可任意缩放;拖动四角等比调整大小。')
);
}
return h('div', null,
specific,
h('div', { className: 'p-section' },
h('div', { className: 'p-section-title' }, '位置与尺寸'),
h('div', { className: 'p-row' },
numField('X (mm)', 'x', el.x, -9999, 9999),
numField('Y (mm)', 'y', el.y, -9999, 9999)
),
h('div', { className: 'p-row' },
numField('宽度', 'w', el.w, 2, 9999),
(el.type === 'text' || el.type === 'qr' || el.type === 'badge' || el.type === 'asset')
? h('div', { className: 'p-field' }, h('label', null, '高度(自动)'), h(A.Input, { value: box.h.toFixed(1) + ' mm', readOnly: true }))
: numField('高度', 'h', el.h, 1, 9999)
),
h('div', { className: 'p-row' },
numField('旋转 °', 'rotation', el.rotation || 0, -180, 180, 1),
h('div', { className: 'p-field' }, h('label', null, '不透明度 ' + Math.round((el.opacity == null ? 1 : el.opacity) * 100) + '%'),
h(A.Slider, {
value: (el.opacity == null ? 1 : el.opacity) * 100,
min: 0,
max: 100,
onChange: function (v) { updateSelected('opacity', v); renderCanvas(); },
onAfterChange: function () { commit(); renderProps(); }
})
)
)
),
h('div', { className: 'p-section' },
h('div', { className: 'p-section-title' }, '图层顺序'),
h('div', { className: 'p-actions order-actions' },
h(A.Button, { block: true, onClick: frontElement }, '⤒ 置顶'),
h(A.Button, { block: true, onClick: raiseElement }, '↑ 上移'),
h(A.Button, { block: true, onClick: lowerElement }, '↓ 下移'),
h(A.Button, { block: true, onClick: backElement }, '⤓ 置底'),
h(A.Button, { block: true, onClick: duplicateElement }, '复制'),
h(A.Button, { block: true, danger: true, onClick: deleteElement }, '删除')
)
)
);
}
/* ---------------- AI 交互式排版(登录后可用,后台控额度) ---------------- */
const ai = { open: false, side: 'front', brief: '', busy: false, last: null, quota: null };
function aiPanelEnsure() {
if (document.getElementById('plAiPanel')) return;
const wrap = document.createElement('div');
wrap.id = 'plAiPanel';
wrap.className = 'pl-ai-panel';
wrap.hidden = true;
wrap.innerHTML =
'
AI 排版' +
'
' +
'' +
'' +
'' +
'
' +
'' +
'' +
'' +
'
' +
'AI 结果直接应用到画布,可随时撤销(⌘Z)。每次生成消耗 1 次额度。
';
document.body.appendChild(wrap);
(function makePanelDraggable() {
const head = wrap.querySelector('.pl-ai-head');
let drag = null;
head.style.touchAction = 'none';
head.addEventListener('pointerdown', function (e) {
if (e.target.closest('button')) return;
const r = wrap.getBoundingClientRect();
drag = { dx: e.clientX - r.left, dy: e.clientY - r.top };
wrap.style.left = r.left + 'px';
wrap.style.top = r.top + 'px';
wrap.style.right = 'auto';
wrap.style.bottom = 'auto';
if (head.setPointerCapture) head.setPointerCapture(e.pointerId);
e.preventDefault();
});
head.addEventListener('pointermove', function (e) {
if (!drag) return;
const maxX = Math.max(6, window.innerWidth - 100);
const maxY = Math.max(6, window.innerHeight - 60);
wrap.style.left = clamp(e.clientX - drag.dx, 6, maxX) + 'px';
wrap.style.top = clamp(e.clientY - drag.dy, 6, maxY) + 'px';
});
head.addEventListener('pointerup', function () { drag = null; });
head.addEventListener('pointercancel', function () { drag = null; });
})();
wrap.querySelector('#plAiClose').addEventListener('click', function () { aiPanelToggle(false); });
wrap.querySelector('#plAiSides').addEventListener('click', function (e) {
const b = e.target.closest('[data-ai-side]');
if (!b) return;
ai.side = b.dataset.aiSide;
wrap.querySelectorAll('#plAiSides button').forEach(function (x) { x.classList.toggle('on', x === b); });
});
wrap.querySelector('#plAiGen').addEventListener('click', aiGenerate);
wrap.querySelector('#plAiClear').addEventListener('click', function () {
const targets = ai.side === 'both' ? ['front', 'back'] : [ai.side === 'back' ? 'back' : 'front'];
targets.forEach(function (k) { state.sides[k] = { bg: null, elements: [] }; });
selectedId = null;
commit(); renderCanvas(); renderSummarySafe(); renderProps();
});
}
function renderSummarySafe() { try { renderSummary(); } catch (e) {} }
function aiPanelToggle(open) {
aiPanelEnsure();
if (open !== undefined) ai.open = open; else ai.open = !ai.open;
document.getElementById('plAiPanel').hidden = !ai.open;
if (ai.open) {
if (window.PL.auth && !PL.auth.user()) {
PL.auth.require(function () { aiRefreshQuota(); });
toast('登录后可用 AI 排版');
} else {
aiRefreshQuota();
}
}
}
function aiRefreshQuota() {
if (!window.PL || !PL.api || !PL.api.token()) return;
PL.api.get('/ai/quota').then(function (q) {
ai.quota = q;
const el = document.getElementById('plAiQuota');
if (!el) return;
el.textContent = q.configured ? ('剩余 ' + q.left + ' 次') : 'AI 未配置';
document.getElementById('plAiGen').disabled = !q.configured;
}, function () {});
}
function clampElementToCanvas(el, s) {
const square = el.type === 'qr' || el.type === 'asset' || el.type === 'badge';
let box = R.elementBox(el);
let w = box.w;
let h = box.h;
const maxW = Math.max(6, s.w);
const maxH = Math.max(6, s.h);
if (w > maxW) {
const k = maxW / w;
w = maxW;
if (!square && el.type !== 'text') h = Math.max(4, h * k);
}
if (h > maxH) {
const k = maxH / h;
h = maxH;
if (!square) w = Math.max(4, w * k);
}
if (square) h = w;
if (el.type === 'text') {
el.w = Math.round(w * 10) / 10;
h = R.elementBox(el).h;
} else if (square) {
el.w = Math.round(w * 10) / 10;
} else {
el.w = Math.round(w * 10) / 10;
el.h = Math.round(h * 10) / 10;
}
const rot = ((num(el.rotation, 0) % 360) + 360) % 360;
const rad = rot * Math.PI / 180;
const bw = Math.abs(w * Math.cos(rad)) + Math.abs(h * Math.sin(rad));
const bh = Math.abs(w * Math.sin(rad)) + Math.abs(h * Math.cos(rad));
const halfW = Math.min(bw, s.w) / 2;
const halfH = Math.min(bh, s.h) / 2;
const cx = num(el.x, 0) + w / 2;
const cy = num(el.y, 0) + h / 2;
const ncx = Math.min(Math.max(cx, halfW), Math.max(halfW, s.w - halfW));
const ncy = Math.min(Math.max(cy, halfH), Math.max(halfH, s.h - halfH));
el.x = Math.round((ncx - w / 2) * 10) / 10;
el.y = Math.round((ncy - h / 2) * 10) / 10;
return el;
}
function aiApplyTo(sideKey, result) {
const sd = state.sides[sideKey];
if (!sd) return;
const s = size();
sd.elements = (result.elements || []).map(function (el) {
el.id = R.uid('el');
el.opacity = el.opacity == null ? 1 : el.opacity;
return clampElementToCanvas(el, s);
});
sd.bg = result.bg || null;
}
function aiGenerate() {
if (window.PL.auth && !PL.auth.user()) {
PL.auth.require(function () { aiGenerate(); });
return;
}
if (!window.PL || !PL.api) { toast('AI 需要联网登录后使用'); return; }
const brief = (document.getElementById('plAiBrief').value || '').trim();
if (!brief) { toast('先描述一下排版需求'); return; }
if (ai.busy) return;
ai.busy = true;
const btn = document.getElementById('plAiGen');
btn.disabled = true;
const t0 = Date.now();
btn.textContent = 'AI 生成中… 0s';
const timer = setInterval(function () {
btn.textContent = 'AI 生成中… ' + Math.round((Date.now() - t0) / 1000) + 's';
}, 1000);
const tip = document.querySelector('.pl-ai-tip');
if (tip) tip.textContent = 'AI 正在设计中,通常 10~60 秒,请勿关闭面板或刷新页面…';
const s = size();
const applySide = ai.side === 'back' ? 'back' : 'front';
const contextEl = document.getElementById('plAiQuota');
PL.api.post('/ai/layout', {
type: 'bag',
brief: brief,
meta: { w: s.w, h: s.h, product: product().name },
context: ai.last && ai.last.side === applySide ? { bg: state.sides[applySide].bg, elements: state.sides[applySide].elements } : null
}, { timeout: 150000 }).then(function (r) {
ai.busy = false; clearInterval(timer);
btn.disabled = false; btn.textContent = '生成排版';
if (tip) tip.textContent = 'AI 结果已应用到画布,可继续提修改意见(每次生成消耗 1 次额度)。';
if (!(r.result.elements || []).length) {
toast('AI 这次没能生成有效排版(未扣次数),换个说法再试');
if (contextEl) contextEl.textContent = '剩余 ' + r.left + ' 次';
return;
}
ai.last = { side: applySide, result: r.result };
aiApplyTo(applySide, r.result);
if (ai.side === 'both') aiApplyTo('back', r.result);
commit(); renderCanvas(); renderSummarySafe();
selectedId = null;
if (contextEl) contextEl.textContent = '剩余 ' + r.left + ' 次';
toast('AI 排版已应用,可继续提修改意见');
}, function (err) {
ai.busy = false; clearInterval(timer);
btn.disabled = false; btn.textContent = '生成排版';
if (tip) tip.textContent = 'AI 结果直接应用到画布,可随时撤销(⌘Z)。每次生成消耗 1 次额度。';
if (err.status === 401) {
PL.auth.require(function () { aiGenerate(); });
} else {
toast(err.message || 'AI 生成失败');
}
});
}
function addElement(el) {
const s = size();
const box = R.elementBox(el);
if (el.x == null) el.x = (s.w - box.w) / 2;
if (el.y == null) el.y = (s.h - box.h) / 2;
el.id = R.uid('el');
sideData().elements.push(el);
selectedId = el.id;
commit();
renderCanvas();
renderProps();
renderTool();
return el;
}
function addTextPreset(kind, fontOverride) {
const s = size();
const presets = {
title: { text: '你的标题', size: s.w * 0.15, weight: 800, font: 'sans', align: 'left' },
subtitle: { text: '一句打动人的副标题', size: s.w * 0.052, weight: 600, font: 'sans', align: 'left' },
body: { text: '在这里输入产品说明、配料或品牌故事。', size: s.w * 0.03, weight: 400, font: 'sans', align: 'left' },
latin: { text: 'YOUR BRAND', size: s.w * 0.11, weight: 800, font: 'latin', align: 'left', spacing: 0.02 }
};
const p = Object.assign({}, presets[kind] || presets.body);
p.font = fontOverride || p.font || lastFont;
lastFont = p.font;
p.type = 'text';
p.w = s.w * 0.8;
p.color = '#17140f';
p.spacing = p.spacing || 0;
p.lineHeight = 1.2;
p.strokeWidth = 0;
p.rotation = 0;
p.opacity = 1;
const textCount = allElements().filter(function (e) { return e.type === 'text'; }).length;
const step = Math.max(6, Math.min(14, s.h * 0.035));
p.x = clamp(s.w * 0.1 + (textCount % 5) * step * 0.7, 2, Math.max(2, s.w * 0.18));
p.y = clamp(s.h * 0.3 + (textCount % 7) * step, 2, Math.max(2, s.h - 24));
addElement(p);
toast('已添加文字 · 双击画布可直接编辑');
}
function addShape(kind) {
const s = size();
const base = { type: 'shape', rotation: 0, opacity: 1, fill: '#ff5c2b', stroke: 'none', strokeWidth: 0, radius: 0 };
let el;
if (kind === 'circle') {
el = Object.assign(base, { shape: 'circle', w: s.w * 0.36, h: s.w * 0.36, fill: '#d9f07c' });
} else if (kind === 'line') {
el = Object.assign(base, { shape: 'line', w: s.w * 0.7, h: 4, fill: 'none', stroke: '#17140f', strokeWidth: 1 });
} else if (kind === 'triangle') {
el = Object.assign(base, { shape: 'triangle', w: s.w * 0.36, h: s.w * 0.32, fill: '#ff5c2b' });
} else if (kind === 'badge') {
el = { type: 'badge', w: s.w * 0.34, text: 'SMALL BATCH · POUCHLAB · ', color: '#17140f', size: s.w * 0.028, rotation: 0, opacity: 1 };
} else if (kind === 'barcode') {
el = { type: 'barcode', w: s.w * 0.5, h: s.h * 0.12, value: '6971234567890', color: '#17140f', showText: true, rotation: 0, opacity: 1 };
} else if (kind === 'qr') {
el = { type: 'qr', w: s.w * 0.34, value: 'https://pouchlab.cn', color: '#17140f', light: '#ffffff', rotation: 0, opacity: 1 };
} else {
el = Object.assign(base, { shape: 'rect', w: s.w * 0.44, h: s.h * 0.22, fill: '#ff5c2b' });
}
addElement(el);
toast('已添加' + (kind === 'barcode' ? '条码' : kind === 'qr' ? '二维码' : kind === 'badge' ? '徽章' : '图形'));
}
function addAsset(id) {
const s = size();
const lib = window.PL && window.PL.boxlib;
const def = lib && lib.ICONS ? lib.ICONS[id] : null;
addElement({
type: 'asset', asset: id, name: def ? def.name : id,
w: s.w * 0.2, h: s.w * 0.2, color: '#17140f', rotation: 0, opacity: 1
});
toast('已添加素材 · ' + (def ? def.name : id));
}
function addSticker(name) {
const s = size();
addElement({ type: 'sticker', sticker: name, w: s.w * 0.2, h: s.w * 0.2, color: '#ff5c2b', rotation: 0, opacity: 1 });
}
function addImageFromUpload(up) {
const s = size();
const ratio = up.w && up.h ? up.h / up.w : 1;
let w = s.w * 0.55;
let h = w * ratio;
if (h > s.h * 0.7) {
h = s.h * 0.7;
w = h / ratio;
}
addElement({ type: 'image', src: up.src, name: up.name, w: w, h: h, fit: 'contain', mono: false, rotation: 0, opacity: 1 });
toast('图片已放置到画布');
}
function clearSide(side) {
const target = side || activeSide;
state.sides[target] = { bg: null, elements: [] };
selectedId = null;
commit();
renderDesign();
renderSettings();
toast('已清空' + (target === 'front' ? '正面' : '背面') + ' · 可撤销');
}
function clearAllSides() {
state.sides = { front: { bg: null, elements: [] }, back: { bg: null, elements: [] } };
selectedId = null;
commit();
renderDesign();
renderSettings();
toast('已清空全部设计 · 可撤销');
}
function duplicateSide() {
const from = activeSide;
const to = from === 'front' ? 'back' : 'front';
const src = sideData(from);
const copy = {
bg: src.bg,
elements: src.elements.map(function (el) {
const c = JSON.parse(JSON.stringify(el));
c.id = R.uid('el');
return c;
})
};
state.sides[to] = copy;
activeSide = to;
selectedId = null;
commit();
renderDesign();
toast('已复制到' + (to === 'front' ? '正面' : '背面'));
}
function selectedIndex() {
return allElements().findIndex(function (e) { return e.id === selectedId; });
}
function raiseElement() {
const i = selectedIndex();
if (i < 0 || i >= allElements().length - 1) return;
const arr = allElements();
const tmp = arr[i];
arr[i] = arr[i + 1];
arr[i + 1] = tmp;
commit();
renderCanvas();
renderTool();
}
function lowerElement() {
const i = selectedIndex();
if (i <= 0) return;
const arr = allElements();
const tmp = arr[i];
arr[i] = arr[i - 1];
arr[i - 1] = tmp;
commit();
renderCanvas();
renderTool();
}
function frontElement() {
const i = selectedIndex();
if (i < 0 || i >= allElements().length - 1) return;
const arr = allElements();
arr.push(arr.splice(i, 1)[0]);
commit();
renderCanvas();
renderTool();
}
function backElement() {
const i = selectedIndex();
if (i <= 0) return;
const arr = allElements();
arr.unshift(arr.splice(i, 1)[0]);
commit();
renderCanvas();
renderTool();
}
/* 拖拽排序:把 fromId 移动到 toId 的上/下(above=true 为更高层) */
function reorderElement(fromId, toId, above) {
if (!fromId || !toId || fromId === toId) return;
const arr = allElements();
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;
const it = rv.splice(si, 1)[0];
let ins = ti > si ? ti - 1 : ti;
if (!above) ins += 1;
rv.splice(ins, 0, it);
arr.splice.apply(arr, [0, arr.length].concat(rv.reverse()));
selectedId = fromId;
commit();
renderCanvas();
renderTool();
renderProps();
}
function duplicateElement() {
const el = selectedEl();
if (!el) return;
const copy = JSON.parse(JSON.stringify(el));
copy.id = R.uid('el');
copy.x += 4;
copy.y += 4;
allElements().push(copy);
selectedId = copy.id;
commit();
renderCanvas();
renderProps();
renderTool();
}
function deleteElementById(id) {
const arr = allElements();
const i = arr.findIndex(function (e) { return e.id === id; });
if (i < 0) return;
arr.splice(i, 1);
if (selectedId === id) selectedId = null;
commit();
renderCanvas();
renderProps();
renderTool();
toast('已删除 · 可撤销');
}
function deleteElement() {
const i = selectedIndex();
if (i < 0) return;
allElements().splice(i, 1);
selectedId = null;
commit();
renderCanvas();
renderProps();
renderTool();
toast('已删除 · 可撤销');
}
function updateSelected(prop, value) {
const el = selectedEl();
if (!el) return;
if (prop === 'x' || prop === 'y' || prop === 'w' || prop === 'h' || prop === 'rotation' || prop === 'opacity' || prop === 'size' || prop === 'spacing' || prop === 'lineHeight' || prop === 'strokeWidth' || prop === 'radius') {
const n = Number(value);
if (isNaN(n)) return;
if (prop === 'opacity') el.opacity = clamp(n / 100, 0, 1);
else if (prop === 'size') el.size = Math.max(2, n);
else if (prop === 'w') el.w = Math.max(2, n);
else if (prop === 'h') el.h = Math.max(1, n);
else if (prop === 'lineHeight') el.lineHeight = Math.max(0.7, n);
else el[prop] = n;
if (el.type === 'badge' && prop === 'w') el.h = el.w;
if (el.type === 'sticker' && prop === 'w') el.h = el.w;
} else if (prop === 'italic' || prop === 'mono' || prop === 'showText') {
el[prop] = !!value;
} else {
el[prop] = value;
}
if (el.type === 'text' && prop === 'text') {
el.w = el.w || size().w * 0.6;
}
if (el.type === 'badge' && prop === 'size') el.h = el.w;
scheduleRenderCanvas();
}
function openInlineText(el) {
if (!el || el.type !== 'text') return;
inlineTarget = el;
const g = els.canvasStage.querySelector('.sel-overlay');
let rect = g ? g.getBoundingClientRect() : { left: innerWidth / 2 - 150, bottom: innerHeight / 2, top: innerHeight / 2 };
const width = 300;
const left = clamp(rect.left, 12, innerWidth - width - 12);
let top = rect.bottom + 10;
if (top + 160 > innerHeight) top = Math.max(12, rect.top - 158);
els.inlineText.style.left = left + 'px';
els.inlineText.style.top = top + 'px';
els.inlineTextArea.value = el.text || '';
els.inlineText.hidden = false;
setTimeout(function () { els.inlineTextArea.focus(); els.inlineTextArea.select(); }, 20);
}
function hideInlineText() {
if (!els.inlineText.hidden) els.inlineText.hidden = true;
inlineTarget = null;
}
function commitInlineText() {
if (!inlineTarget) return;
const el = inlineTarget;
el.text = els.inlineTextArea.value;
hideInlineText();
commit();
renderCanvas();
renderProps();
renderTool();
}
function changeSide(side) {
if (side === activeSide) return;
activeSide = side;
selectedId = null;
hideInlineText();
renderDesign();
}
function doUndo() {
if (hIndex <= 0) return;
hIndex -= 1;
applySnapshot(history[hIndex]);
selectedId = null;
saveState();
renderSettings();
if (mode === 'design') renderDesign();
if (mode === 'summary') renderSummary();
updateMeta();
toast('已撤销');
}
function doRedo() {
if (hIndex >= history.length - 1) return;
hIndex += 1;
applySnapshot(history[hIndex]);
selectedId = null;
saveState();
renderSettings();
if (mode === 'design') renderDesign();
if (mode === 'summary') renderSummary();
updateMeta();
toast('已重做');
}
function renderSummary() {
const p = renderProduct();
const s = size();
const design = sideData(summarySide);
els.summarySideSwitch.querySelectorAll('button').forEach(function (b) {
b.classList.toggle('on', b.dataset.side === summarySide);
});
els.summaryPreview.innerHTML = '' + R.bagSVG(p, summarySide, design, { size: s, card: true, material: state.material, finish: state.finish }) + '
';
els.summaryThumbs.innerHTML = ['front', 'back'].map(function (side) {
return '';
}).join('');
const price = D.price(state);
els.summaryOrder.innerHTML =
'' +
priceLines().map(function (row) { return '
' + row[0] + '' + row[1] + '
'; }).join('') +
'
设计名称' + esc(state.name) + '
' +
'合计¥' + price.total.toFixed(2) + ' / ' + state.qty + ' 个
';
const submit = $('#submitOrder');
if (submit) submit.textContent = '提交订单 · ¥' + price.total.toFixed(2);
updateMeta();
}
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); }, 1500);
}
function roundedRectSegments(x, y, w, h, r, seg) {
r = Math.max(0, Math.min(r, w / 2, h / 2));
seg = seg || 8;
const pts = [];
function arc(cx, cy, a0, a1) {
for (let i = 0; i <= seg; i += 1) {
const a = a0 + (a1 - a0) * i / seg;
pts.push([cx + Math.cos(a) * r, cy + Math.sin(a) * r]);
}
}
pts.push([x + r, y]);
pts.push([x + w - r, y]);
arc(x + w - r, y + r, -Math.PI / 2, 0);
pts.push([x + w, y + h - r]);
arc(x + w - r, y + h - r, 0, Math.PI / 2);
pts.push([x + r, y + h]);
arc(x + r, y + h - r, Math.PI / 2, Math.PI);
pts.push([x, y + r]);
arc(x + r, y + r, Math.PI, Math.PI * 1.5);
const segs = [];
for (let i = 0; i < pts.length; i += 1) {
const a = pts[i];
const b = pts[(i + 1) % pts.length];
if (Math.abs(a[0] - b[0]) < 1e-6 && Math.abs(a[1] - b[1]) < 1e-6) continue;
segs.push([a[0], a[1], b[0], b[1]]);
}
return segs;
}
function exportBagDxf() {
const p = product();
const s = size();
const pad = p.pad || { l: 12, r: 12, t: 34, b: 18 };
const bleed = 3;
const ox = pad.l + bleed;
const oy = pad.t + bleed;
let out = '0\nSECTION\n2\nENTITIES\n';
function line(layer, x1, y1, x2, y2) {
out += '0\nLINE\n8\n' + layer + '\n10\n' + (x1 + ox).toFixed(3) + '\n20\n' + (y1 + oy).toFixed(3) + '\n11\n' + (x2 + ox).toFixed(3) + '\n21\n' + (y2 + oy).toFixed(3) + '\n';
}
function add(layer, segs) { segs.forEach(function (g) { line(layer, g[0], g[1], g[2], g[3]); }); }
const w = s.w + pad.l + pad.r;
const h = s.h + pad.t + pad.b;
add('CUT', roundedRectSegments(-pad.l, -pad.t, w, h, 6));
add('BLEED', roundedRectSegments(-pad.l - bleed, -pad.t - bleed, w + bleed * 2, h + bleed * 2, 6 + bleed));
line('PRINT', 0, 0, s.w, 0);
line('PRINT', s.w, 0, s.w, s.h);
line('PRINT', s.w, s.h, 0, s.h);
line('PRINT', 0, s.h, 0, 0);
line('FOLD', 0, -pad.t, 0, s.h + pad.b);
line('FOLD', s.w, -pad.t, s.w, s.h + pad.b);
line('FOLD', -pad.l, 0, s.w + pad.r, 0);
line('FOLD', -pad.l, s.h, s.w + pad.r, s.h);
out += '0\nENDSEC\n0\nEOF\n';
downloadBlob(new Blob([out], { type: 'application/dxf' }), 'pouchlab-' + p.id + '-dieline.dxf');
toast('刀版 DXF 已导出 · CUT/FOLD/BLEED');
}
function exportCurrent(opts) {
opts = opts || {};
const svgWidth = opts.width || 1400;
const outWidth = opts.outWidth || 0;
const p = renderProduct();
const s = size();
const side = mode === 'summary' ? summarySide : activeSide;
const svg = R.bagSVG(p, side, sideData(side), { size: s, card: true, width: svgWidth, material: state.material, finish: state.finish });
const blob = new Blob([svg], { type: 'image/svg+xml;charset=utf-8' });
const url = URL.createObjectURL(blob);
const img = new Image();
img.onload = function () {
const ratio = svgWidth / 1400;
const pad = Math.round(90 * ratio);
const footer = Math.round(150 * ratio);
const baseW = img.width + pad * 2;
const scale = outWidth ? outWidth / baseW : 1;
const canvas = document.createElement('canvas');
canvas.width = Math.round(baseW * scale);
canvas.height = Math.round((img.height + pad + footer) * scale);
const ctx = canvas.getContext('2d');
ctx.scale(scale, scale);
ctx.fillStyle = '#f6f2e9';
ctx.fillRect(0, 0, canvas.width / scale, canvas.height / scale);
ctx.drawImage(img, pad, pad, img.width, img.height);
ctx.fillStyle = '#17140f';
ctx.font = '700 24px "PingFang SC", "Helvetica Neue", sans-serif';
ctx.fillText(state.name, pad, img.height + pad + 46);
ctx.fillStyle = '#7d7466';
ctx.font = '400 15px "PingFang SC", "Helvetica Neue", sans-serif';
ctx.fillText(p.name + ' · ' + s.label + ' · ' + s.w + '×' + s.h + ' mm · ' + state.qty + ' 个 · ' + (side === 'front' ? '正面' : '背面'), pad, img.height + pad + 74);
ctx.fillStyle = '#a79d8d';
ctx.font = '400 12px "SF Mono", Menlo, monospace';
ctx.fillText('POUCHLAB DESIGN STUDIO · 300 DPI · ' + new Date().toLocaleDateString('zh-CN'), pad, img.height + pad + 100);
URL.revokeObjectURL(url);
canvas.toBlob(function (b) {
downloadBlob(b, 'pouchlab-' + p.id + '-' + side + (opts.suffix || '') + '.png');
toast(opts.label ? opts.label + '已下载' : '效果图已下载');
}, 'image/png');
};
img.onerror = function () {
URL.revokeObjectURL(url);
downloadBlob(blob, 'pouchlab-' + p.id + '-' + side + '.svg');
toast('已下载 SVG 文件');
};
img.src = url;
}
function open3d() {
three.side = mode === 'summary' ? summarySide : activeSide;
three.rot = three.side === 'front' ? -18 : 162;
els.rotateRange.value = three.rot;
els.modal3d.hidden = false;
if (ensurePouchGL()) {
updatePouchGL();
return;
}
render3d();
}
/* ---- FBX 真实模型 3D 预览(pouch3d) ---- */
let pouchGL = null;
function ensurePouchGL() {
if (!window.PL || !PL.pouch3d) return false;
if (!pouchGL) {
const stage = document.createElement('div');
stage.id = 'pouchGL';
stage.style.cssText = 'position:absolute;inset:0;z-index:2;';
$('#scene3d').appendChild(stage);
pouchGL = PL.pouch3d.create(stage, {
onLoadError: function () {
// GL 失败 → 回退 CSS 3D
try { stage.remove(); } catch (e) {}
pouchGL = null;
if (els.pouch3d) els.pouch3d.style.display = '';
render3d();
}
});
}
if (els.pouch3d) els.pouch3d.style.display = 'none';
return true;
}
function updatePouchGL() {
if (!pouchGL) return;
const p = renderProduct();
const s = size();
const color = (state.bagColor || p.mockColor || '#e8e2d4');
const shape = p.shape || 'standup';
// 用户显式选择 open/closed 优先;未选择时按袋型默认(邮封袋→开口,其余→封口)
const eff = three.modelMode || (shape === 'mailer' ? 'open' : 'closed');
const sw = document.getElementById('pouchModelSwitch');
if (sw) sw.querySelectorAll('button').forEach(function (x) {
x.classList.toggle('on', x.dataset.model === eff);
});
pouchGL.load(eff, function () {
pouchGL.applyDesign({
color: color,
frontDesign: previewDesignFor('front'),
backDesign: previewDesignFor('back'),
frontBg: previewDesignFor('front').bg || color,
backBg: previewDesignFor('back').bg || color,
W: s.w, H: s.h
});
pouchGL.setRotation(three.rot);
});
}
function previewDesignFor(side) {
const sd = sideData(side);
if (sd.elements.length) return sd;
const s = size();
const t = D.templateById(sampleMap[product().id] || 'citrus');
return R.designFromTemplate(t.id, s.w, s.h, side);
}
function render3d() {
if (pouchGL && pouchGL.ready()) {
updatePouchGL();
els.rotateRange.value = three.rot;
els.previewSideSwitch.querySelectorAll('button').forEach(function (b) {
b.classList.toggle('on', (b.dataset.side === 'front' && three.rot > -90 && three.rot < 90) || (b.dataset.side === 'back' && (three.rot > 90 || three.rot < -90)));
});
return;
}
const p = renderProduct();
const s = size();
const front = R.bagSVG(p, 'front', previewDesignFor('front'), { size: s, tight: true, material: state.material, finish: state.finish });
const back = R.bagSVG(p, 'back', previewDesignFor('back'), { size: s, tight: true, material: state.material, finish: state.finish });
els.faceFront.innerHTML = front || '';
els.faceBack.innerHTML = back || '';
window.__r3d.push('written');
const pad = p.pad;
const aspect = (s.w + pad.l + pad.r) / (s.h + pad.t + pad.b);
const sceneH = $('.scene').clientHeight || 440;
const h = Math.min(400, Math.max(260, sceneH - 80));
const w = clamp(h * aspect, 150, 360);
els.pouch3d.style.height = h + 'px';
els.pouch3d.style.width = w + 'px';
// 侧面体积渐变:顶部封口薄暗 → 中下鼓面高光(膨鼓最饱满处 ~74%)→ 底部承重微暗,基色跟随袋色
const sideVolume = function (lightPos) {
return [
'radial-gradient(ellipse 120% 60% at 50% 74%, rgba(255,255,255,0.30), transparent 58%)',
'linear-gradient(180deg, rgba(0,0,0,0.34) 0%, rgba(0,0,0,0.08) 22%, transparent 42%, rgba(0,0,0,0.10) 92%)',
'linear-gradient(90deg,' + R.shade(p.mockColor, -0.30) + ',' + R.shade(p.mockColor, 0.14) + ' ' + lightPos + '%,' + R.shade(p.mockColor, -0.34) + ')'
].join(',');
};
els.faceSide.style.transform = 'rotateY(90deg) translateZ(' + (w / 2) + 'px)';
els.faceSide.style.background = sideVolume(46);
if (els.faceSideLeft) {
els.faceSideLeft.style.transform = 'rotateY(-90deg) translateZ(' + (w / 2) + 'px)';
els.faceSideLeft.style.background = sideVolume(54);
}
apply3dRotation();
els.previewSideSwitch.querySelectorAll('button').forEach(function (b) {
b.classList.toggle('on', (b.dataset.side === 'front' && three.rot > -90 && three.rot < 90) || (b.dataset.side === 'back' && (three.rot > 90 || three.rot < -90)));
});
}
function apply3dRotation() {
els.pouch3d.style.transform = 'rotateX(4deg) rotateY(' + three.rot + 'deg)';
els.rotateRange.value = three.rot;
}
function close3d() {
els.modal3d.hidden = true;
}
function goSummary() {
if (!state.sides.front.elements.length && !state.sides.back.elements.length) {
toast('先添加一些内容,再确认订单');
return;
}
setMode('summary');
}
function nextStep() {
if (mode === 'settings') enterDesign();
else if (mode === 'design') goSummary();
else {
const form = $('#orderForm');
if (form) {
if (form.reportValidity()) form.requestSubmit();
}
}
}
function addUploadedFile(file) {
if (!file || file.type.indexOf('image') !== 0) {
toast('请选择图片文件');
return;
}
if (file.size > 12 * 1024 * 1024) {
toast('图片过大,请使用 12MB 以内的文件');
return;
}
const reader = new FileReader();
reader.onload = function () {
const img = new Image();
img.onload = function () {
const max = 1400;
let w = img.naturalWidth || img.width || 1000;
let h = img.naturalHeight || img.height || 1000;
if (!w || !h) { w = 1000; h = 1000; }
if (Math.max(w, h) > max) {
const k = max / Math.max(w, h);
w = Math.round(w * k);
h = Math.round(h * k);
}
const canvas = document.createElement('canvas');
canvas.width = w;
canvas.height = h;
const ctx = canvas.getContext('2d');
ctx.drawImage(img, 0, 0, w, h);
const isPng = file.type === 'image/png' || file.type === 'image/svg+xml';
const src = canvas.toDataURL(isPng ? 'image/png' : 'image/jpeg', 0.9);
const up = { id: R.uid('up'), name: file.name, src: src, w: w, h: h };
state.uploads.unshift(up);
if (state.uploads.length > 12) state.uploads = state.uploads.slice(0, 12);
addImageFromUpload(up);
saveState(true);
renderTool();
};
img.src = reader.result;
};
reader.readAsDataURL(file);
}
function pickUpload(replace) {
const input = document.createElement('input');
input.type = 'file';
input.accept = 'image/png,image/jpeg,image/svg+xml,image/webp';
input.onchange = function () {
const file = input.files && input.files[0];
if (!file) return;
if (replace) {
const el = selectedEl();
if (!el) return;
const reader = new FileReader();
reader.onload = function () {
el.src = reader.result;
el.name = file.name;
const img = new Image();
img.onload = function () {
el.h = el.w * (img.height / img.width);
commit();
renderCanvas();
renderProps();
};
img.src = reader.result;
};
reader.readAsDataURL(file);
} else {
addUploadedFile(file);
}
};
input.click();
}
function bindSettings() {
els.settingsView.addEventListener('click', function (e) {
const color = e.target.closest('[data-color]');
if (color) { changeBagColor(color.dataset.color); }
});
}
function bindTopbar() {
els.continueBtn.addEventListener('click', nextStep);
els.undoBtn.addEventListener('click', doUndo);
els.redoBtn.addEventListener('click', doRedo);
els.studioSteps.addEventListener('click', function (e) {
const btn = e.target.closest('[data-step]');
if (!btn) return;
if (btn.dataset.step === 'summary' && mode !== 'summary') {
if (!state.sides.front.elements.length && !state.sides.back.elements.length) {
ensureSample();
}
setMode('summary');
return;
}
setMode(btn.dataset.step);
});
els.designName.addEventListener('input', function () {
state.name = this.value || '未命名设计';
saveState(true);
updateMeta();
if (mode === 'summary') renderSummary();
});
els.designName.addEventListener('change', function () { commit(); });
$('#preview3dBtn').addEventListener('click', open3d);
}
function bindDesign() {
els.toolRail.addEventListener('click', function (e) {
const btn = e.target.closest('[data-tool]');
if (!btn) return;
tool = btn.dataset.tool;
renderTool();
els.designView.classList.remove('panel-collapsed');
els.designView.classList.add('panel-open');
});
els.sideSwitch.addEventListener('click', function (e) {
const btn = e.target.closest('[data-side]');
if (btn) changeSide(btn.dataset.side);
});
els.guidesToggle.addEventListener('change', function () {
showGuides = this.checked;
renderCanvas();
});
$('#zoomIn').addEventListener('click', function () { updateZoom(zoom * 1.18); });
$('#zoomOut').addEventListener('click', function () { updateZoom(zoom / 1.18); });
$('#zoomFit').addEventListener('click', function () { zoom = 1; renderCanvas(); });
$('#downloadBtn').addEventListener('click', exportCurrent);
const d4 = $('#download4kBtn');
if (d4) d4.addEventListener('click', function () { exportCurrent({ width: 3600, outWidth: 3840, suffix: '-4k', label: '4K 效果图' }); });
const ddxf = $('#downloadDxfBtn');
if (ddxf) ddxf.addEventListener('click', exportBagDxf);
$('#toolPanelClose').addEventListener('click', function () {
els.designView.classList.remove('panel-open');
els.designView.classList.add('panel-collapsed');
});
els.canvasEmpty.addEventListener('click', function (e) {
const btn = e.target.closest('[data-empty-action]');
if (!btn) return;
tool = btn.dataset.emptyAction === 'upload' ? 'upload' : 'templates';
renderTool();
});
els.toolBody.addEventListener('click', function (e) {
const tpl = e.target.closest('[data-template]');
if (tpl) { applyTemplate(tpl.dataset.template); return; }
const preset = e.target.closest('[data-preset]');
if (preset) { addTextPreset(preset.dataset.preset); return; }
const font = e.target.closest('[data-font]');
if (font) {
const el = selectedEl();
if (el && el.type === 'text') {
el.font = font.dataset.font;
lastFont = el.font;
commit();
renderCanvas();
renderProps();
} else {
addTextPreset('body', font.dataset.font);
}
return;
}
const shape = e.target.closest('[data-shape]');
if (shape) { addShape(shape.dataset.shape); return; }
const sticker = e.target.closest('[data-sticker]');
if (sticker) { addSticker(sticker.dataset.sticker); return; }
const layer = e.target.closest('[data-layer]');
if (layer && !e.target.closest('[data-eye]')) {
selectedId = layer.dataset.layer;
renderCanvas();
renderProps();
renderTool();
return;
}
const eye = e.target.closest('[data-eye]');
if (eye) {
const el = allElements().find(function (x) { return x.id === eye.dataset.eye; });
if (el) { el.hidden = !el.hidden; commit(); renderCanvas(); renderTool(); }
return;
}
const rm = e.target.closest('[data-remove-upload]');
if (rm) {
state.uploads = state.uploads.filter(function (u) { return u.id !== rm.dataset.removeUpload; });
commit();
renderTool();
return;
}
const uploadZone = e.target.closest('[data-action="pick-upload"]');
if (uploadZone) { pickUpload(false); return; }
const ins = e.target.closest('[data-size]');
if (ins) { changeSize(ins.dataset.size); renderTool(); return; }
const qty = e.target.closest('[data-qty]');
if (qty) { changeSetting('qty', qty.dataset.qty); renderTool(); return; }
const bagColor = e.target.closest('[data-bag-color]');
if (bagColor) { changeBagColor(bagColor.dataset.bagColor); renderTool(); return; }
const action = e.target.closest('[data-action]');
if (action) {
const a = action.dataset.action;
if (a === 'settings') setMode('settings');
if (a === 'clear-side') clearSide();
if (a === 'dup-side') duplicateSide();
}
});
els.toolBody.addEventListener('change', function (e) {
if (e.target.id === 'toolMaterial') { changeSetting('material', e.target.value); renderTool(); }
if (e.target.id === 'toolFinish') { changeSetting('finish', e.target.value); renderTool(); }
});
els.toolBody.addEventListener('dragover', function (e) {
const zone = e.target.closest('.upload-zone');
if (!zone) return;
e.preventDefault();
zone.classList.add('drag');
});
els.toolBody.addEventListener('dragleave', function (e) {
const zone = e.target.closest('.upload-zone');
if (zone) zone.classList.remove('drag');
});
els.toolBody.addEventListener('drop', function (e) {
const zone = e.target.closest('.upload-zone');
if (!zone) return;
e.preventDefault();
zone.classList.remove('drag');
Array.from(e.dataTransfer.files).slice(0, 4).forEach(addUploadedFile);
});
els.propsClose.addEventListener('click', function () {
selectedId = null;
renderCanvas();
renderProps();
});
els.propsBody.addEventListener('input', function (e) {
const t = e.target;
if (t.hasAttribute('data-toggle-guides')) {
showGuides = t.checked;
renderCanvas();
return;
}
const bgCustom = t.closest('[data-bg-custom]');
if (bgCustom) {
sideData().bg = bgCustom.value;
scheduleRenderCanvas();
return;
}
const prop = t.dataset.prop;
if (!prop) return;
let v;
if (t.type === 'checkbox') v = t.checked;
else if (t.hasAttribute('data-num')) v = num(t.value, 0);
else v = t.value;
if (t.dataset.scale) v = Number(v);
updateSelected(prop, v);
const colorSpan = t.parentElement && t.parentElement.querySelector('span');
if (t.type === 'color' && colorSpan) colorSpan.textContent = String(t.value).replace('#', '');
});
els.propsBody.addEventListener('change', function (e) {
const t = e.target;
if (t.hasAttribute('data-toggle-guides')) return;
const bgCustom = t.closest('[data-bg-custom]');
if (bgCustom) {
sideData().bg = bgCustom.value;
commit();
renderCanvas();
renderProps();
return;
}
if (t.dataset.prop || t.type === 'color') {
commit();
renderTool();
}
});
els.propsBody.addEventListener('click', function (e) {
const prop = e.target.closest('[data-prop]');
if (prop && (prop.type === 'color')) return;
const weight = e.target.closest('[data-weight]');
if (weight) { const el = selectedEl(); if (el) { el.weight = Number(weight.dataset.weight); commit(); renderCanvas(); renderProps(); } return; }
const align = e.target.closest('[data-align]');
if (align) { const el = selectedEl(); if (el) { el.align = align.dataset.align; commit(); renderCanvas(); renderProps(); } return; }
const fit = e.target.closest('[data-fit]');
if (fit) { const el = selectedEl(); if (el) { el.fit = fit.dataset.fit; commit(); renderCanvas(); renderProps(); } return; }
const bg = e.target.closest('[data-bg]');
if (bg) { sideData().bg = bg.dataset.bg || null; commit(); renderCanvas(); renderProps(); return; }
const bagColor = e.target.closest('[data-bag-color]');
if (bagColor) { changeBagColor(bagColor.dataset.bagColor); renderProps(); return; }
const sideJump = e.target.closest('[data-side-jump]');
if (sideJump) { changeSide(sideJump.dataset.sideJump); return; }
const action = e.target.closest('[data-action]');
if (action) {
const a = action.dataset.action;
if (a === 'raise') raiseElement();
if (a === 'lower') lowerElement();
if (a === 'duplicate') duplicateElement();
if (a === 'delete') deleteElement();
if (a === 'replace-image') pickUpload(true);
if (a === 'clear-side') clearSide();
if (a === 'dup-side') duplicateSide();
}
});
els.canvasStage.addEventListener('pointerdown', onCanvasPointerDown);
els.canvasStage.addEventListener('dblclick', function (e) {
const g = e.target.closest('[data-id]');
if (!g) return;
const el = allElements().find(function (x) { return x.id === g.dataset.id; });
if (el && el.type === 'text') {
selectedId = el.id;
renderCanvas();
renderProps();
openInlineText(el);
}
});
els.inlineTextDone.addEventListener('click', commitInlineText);
els.inlineTextArea.addEventListener('keydown', function (e) {
if ((e.metaKey || e.ctrlKey) && e.key === 'Enter') { e.preventDefault(); commitInlineText(); }
e.stopPropagation();
});
els.inlineTextArea.addEventListener('blur', function () {
setTimeout(function () {
if (document.activeElement !== els.inlineTextDone && document.activeElement !== els.inlineTextArea) commitInlineText();
}, 120);
});
$('#summarySideSwitch').addEventListener('click', function (e) {
const b = e.target.closest('[data-side]');
if (!b) return;
summarySide = b.dataset.side;
renderSummary();
});
els.summaryThumbs.addEventListener('click', function (e) {
const b = e.target.closest('[data-summary-side]');
if (!b) return;
summarySide = b.dataset.summarySide;
renderSummary();
});
$('#backToDesign').addEventListener('click', function () { setMode('design'); });
$('#summaryDownload').addEventListener('click', exportCurrent);
const s4 = $('#summaryDownload4k');
if (s4) s4.addEventListener('click', function () { exportCurrent({ width: 3600, outWidth: 3840, suffix: '-4k', label: '4K 效果图' }); });
const sdxf = $('#summaryDownloadDxf');
if (sdxf) sdxf.addEventListener('click', exportBagDxf);
$('#summaryPreview3d').addEventListener('click', open3d);
let orderSubmitting = false;
function buildOrderPayload(data) {
const p = product();
const s = size();
const mat = D.materialById(state.material);
const fin = D.finishById(state.finish);
const price = D.price(state);
let design = null;
try { design = JSON.parse(snapshot()); } catch (err) { design = null; }
const payload = {
type: 'bag',
contact: {
name: data.get('name') || '',
phone: data.get('phone') || '',
email: data.get('email') || '',
address: data.get('address') || '',
note: data.get('note') || ''
},
spec: {
productId: p.id, productName: p.name,
sizeId: state.sizeId, sizeLabel: s.label, w: s.w, h: s.h,
material: state.material, materialName: mat ? mat.name : state.material,
finish: state.finish, finishName: fin ? fin.name : state.finish,
qty: state.qty
},
quote: { unit: price.unit, total: price.total },
summary: p.name + ' ' + s.w + '×' + s.h + 'mm · ' + (mat ? mat.name : '') + ' · ' + state.qty + ' 只',
design: design,
dieline: {
kind: 'bag', bleed: 3,
faces: [{ key: 'front', w: s.w, h: s.h }, { key: 'back', w: s.w, h: s.h }],
meta: { productName: p.name, material: mat ? mat.name : '', finish: fin ? fin.name : '', qty: state.qty }
},
previews: {}
};
return Promise.all(['front', 'back'].map(function (side) {
const svg = R.bagSVG(renderProduct(), side, sideData(side), { size: s, card: true, width: 900, material: state.material, finish: state.finish });
return PL.api.svgToPng(svg, 900);
})).then(function (pngs) {
payload.previews = { front: pngs[0], back: pngs[1] };
return payload;
}, function () {
return payload; // 预览图失败不阻塞下单
});
}
function finishSubmit(orderNo, offline) {
orderSubmitting = false;
const btn = $('#submitOrder');
btn.disabled = false;
btn.textContent = '提交订单';
els.orderNumber.textContent = orderNo;
const tip = document.getElementById('successTip');
if (tip) tip.hidden = !offline;
els.successView.hidden = false;
toast(offline ? '订单已离线保存(服务器不可达)' : '订单已提交,可前往「我的订单」支付');
}
$('#orderForm').addEventListener('submit', function (e) {
e.preventDefault();
if (window.PL.auth && !window.PL.auth.user()) {
window.PL.auth.require(function () { $('#orderForm').requestSubmit(); });
return;
}
const form = this;
const data = new FormData(form);
if (!data.get('name') || !data.get('phone') || !data.get('address')) {
form.reportValidity();
return;
}
if (orderSubmitting) return;
if (!window.PL || !PL.api) return;
orderSubmitting = true;
const btn = $('#submitOrder');
btn.disabled = true;
btn.textContent = '正在提交订单…';
let orderPayload = null;
buildOrderPayload(data).then(function (payload) {
orderPayload = payload;
return PL.api.post('/orders', payload, { timeout: 60000 });
}).then(function (r) {
finishSubmit(r.orderNo, false);
}, function (err) {
if (err && err.network) {
// 离线回退:本地保存完整订单信息,联网后可在「我的订单」查看
const n = 'PL-' + String(new Date().getFullYear()) + String(Date.now()).slice(-6);
try {
localStorage.setItem('pouchlab.order.' + n, JSON.stringify({
name: data.get('name'), phone: data.get('phone'), email: data.get('email'),
address: data.get('address') || '', note: data.get('note'),
order: n, total: D.price(state).total, qty: state.qty,
summary: orderPayload ? orderPayload.summary : '',
spec: orderPayload ? orderPayload.spec : null,
previews: orderPayload ? orderPayload.previews : {},
design: snapshot(), at: Date.now()
}));
} catch (e2) {}
finishSubmit(n, true);
return;
}
orderSubmitting = false;
btn.disabled = false;
btn.textContent = '提交订单';
toast(err.message || '订单提交失败,请重试');
});
});
$('#successBack').addEventListener('click', function () { location.href = 'index.html'; });
els.modal3d.addEventListener('click', function (e) {
if (e.target.closest('[data-close="3d"]')) close3d();
});
$('#pouchModelSwitch').addEventListener('click', function (e) {
const b = e.target.closest('[data-model]');
if (!b) return;
three.modelMode = b.dataset.model;
this.querySelectorAll('button').forEach(function (x) {
x.classList.toggle('on', x === b);
});
if (pouchGL && pouchGL.ready()) updatePouchGL();
});
$('#previewSideSwitch').addEventListener('click', function (e) {
const b = e.target.closest('[data-side]');
if (!b) return;
three.rot = b.dataset.side === 'front' ? -18 : 162;
if (pouchGL && pouchGL.ready()) {
pouchGL.setRotation(three.rot);
els.previewSideSwitch.querySelectorAll('button').forEach(function (x) {
x.classList.toggle('on', x.dataset.side === b.dataset.side);
});
return;
}
apply3dRotation();
render3d();
});
els.rotateRange.addEventListener('input', function () {
three.rot = Number(this.value);
if (pouchGL && pouchGL.ready()) {
pouchGL.setRotation(three.rot);
els.previewSideSwitch.querySelectorAll('button').forEach(function (b) {
b.classList.toggle('on', (b.dataset.side === 'front' && three.rot > -90 && three.rot < 90) || (b.dataset.side === 'back' && (three.rot > 90 || three.rot < -90)));
});
return;
}
apply3dRotation();
els.previewSideSwitch.querySelectorAll('button').forEach(function (b) {
b.classList.toggle('on', (b.dataset.side === 'front' && three.rot > -90 && three.rot < 90) || (b.dataset.side === 'back' && (three.rot > 90 || three.rot < -90)));
});
});
const scene = $('#scene3d');
let rotDrag = null;
scene.addEventListener('pointerdown', function (e) {
if (pouchGL && pouchGL.ready()) return; // GL 模式由模型画布自行处理拖拽
rotDrag = { x: e.clientX, rot: three.rot };
scene.setPointerCapture(e.pointerId);
});
scene.addEventListener('pointermove', function (e) {
if (!rotDrag) return;
three.rot = clamp(rotDrag.rot + (e.clientX - rotDrag.x) * 0.45, -180, 180);
apply3dRotation();
});
scene.addEventListener('pointerup', function () { rotDrag = null; });
scene.addEventListener('pointercancel', function () { rotDrag = null; });
}
/* 参考潘通色网格(防侵权叫法:不称潘通色;实际以打样效果为准) */
function pmsGrid(onPick, currentHex) {
const P = window.PL.pantone;
const cur = (currentHex || '').toLowerCase();
return [
h('div', { className: 'pms-grid' }, P.list.map(function (c) {
return h('button', {
key: c.code, type: 'button',
className: 'pms-dot' + (cur === c.hex.toLowerCase() ? ' on' : ''),
title: '参考潘通色 ' + c.code + ' ' + c.name,
style: { background: c.hex },
onClick: function () { onPick(c); }
});
})),
h('div', { className: 'pms-note' }, P.note)
];
}
function pointInElement(el, pt) {
const box = R.elementBox(el);
const rot = -(el.rotation || 0) * Math.PI / 180;
const cx = box.w / 2;
const cy = box.h / 2;
const dx = pt.x - el.x - cx;
const dy = pt.y - el.y - cy;
const rx = Math.cos(rot) * dx - Math.sin(rot) * dy + cx;
const ry = Math.sin(rot) * dx + Math.cos(rot) * dy + cy;
return rx >= 0 && rx <= box.w && ry >= 0 && ry <= box.h;
}
function onCanvasPointerDown(e) {
if (e.button !== 0) return;
const svg = els.canvasStage.querySelector('svg');
if (!svg) return;
const handle = e.target.closest('[data-handle]');
if (handle && selectedId) {
e.preventDefault();
startTransform(e, svg, handle.dataset.handle);
return;
}
const group = e.target.closest('[data-id]');
if (group) {
let id = group.dataset.id;
if (e.altKey && selectedId) {
const pt = svgPoint(e, svg);
const hits = allElements().filter(function (el) { return !el.hidden && pointInElement(el, pt); });
if (hits.length > 1) {
const idx = hits.findIndex(function (x) { return x.id === selectedId; });
id = hits[(idx + 1) % hits.length].id;
}
}
if (selectedId !== id) {
selectedId = id;
renderCanvas();
renderProps();
renderTool();
}
const el = selectedEl();
if (!el) return;
const liveSvg = els.canvasStage.querySelector('svg');
startDrag(e, liveSvg, el);
return;
}
selectedId = null;
renderCanvas();
renderProps();
renderTool();
}
function svgPoint(e, svg) {
const pt = svg.createSVGPoint();
pt.x = e.clientX;
pt.y = e.clientY;
const m = svg.getScreenCTM();
if (!m) return { x: 0, y: 0 };
return pt.matrixTransform(m.inverse());
}
function setElementTransform(el) {
const g = els.canvasStage.querySelector('[data-id="' + el.id + '"]');
if (!g) return;
const box = R.elementBox(el);
g.setAttribute('transform', 'translate(' + el.x + ' ' + el.y + ') rotate(' + (el.rotation || 0) + ' ' + (box.w / 2) + ' ' + (box.h / 2) + ')');
const sel = els.canvasStage.querySelector('.sel-overlay');
if (sel) sel.setAttribute('transform', 'translate(' + el.x + ' ' + el.y + ') rotate(' + (el.rotation || 0) + ' ' + (box.w / 2) + ' ' + (box.h / 2) + ')');
}
function setDragGuides(gx, gy) {
const svg = els.canvasStage.querySelector('svg');
if (!svg) return;
svg.querySelectorAll('.drag-guide').forEach(function (n) { n.remove(); });
const p = product().pad;
const s = size();
const NS = 'http://www.w3.org/2000/svg';
if (gx != null) {
const l = document.createElementNS(NS, 'line');
l.setAttribute('class', 'drag-guide');
l.setAttribute('x1', gx); l.setAttribute('x2', gx);
l.setAttribute('y1', -p.t - 6); l.setAttribute('y2', s.h + p.b + 6);
l.setAttribute('stroke', '#ff5c2b');
l.setAttribute('stroke-width', '0.5');
l.setAttribute('stroke-dasharray', '2 2');
l.setAttribute('data-ui', '1');
svg.appendChild(l);
}
if (gy != null) {
const l = document.createElementNS(NS, 'line');
l.setAttribute('class', 'drag-guide');
l.setAttribute('y1', gy); l.setAttribute('y2', gy);
l.setAttribute('x1', -p.l - 6); l.setAttribute('x2', s.w + p.r + 6);
l.setAttribute('stroke', '#ff5c2b');
l.setAttribute('stroke-width', '0.5');
l.setAttribute('stroke-dasharray', '2 2');
l.setAttribute('data-ui', '1');
svg.appendChild(l);
}
}
function startDrag(e, svg, el) {
isDragging = true;
const liveSvg = function () { return els.canvasStage.querySelector('svg') || svg; };
const start = svgPoint(e, liveSvg());
const orig = { x: el.x, y: el.y };
const box = R.elementBox(el);
const s = size();
let moved = false;
let lastGx = null;
let lastGy = null;
function move(ev) {
const p = svgPoint(ev, liveSvg());
let dx = p.x - start.x;
let dy = p.y - start.y;
if (ev.shiftKey) {
if (Math.abs(dx) > Math.abs(dy)) dy = 0; else dx = 0;
}
let x = orig.x + dx;
let y = orig.y + dy;
let gx = null;
let gy = null;
const tol = 2.2;
const cx = x + box.w / 2;
const cy = y + box.h / 2;
if (Math.abs(cx - s.w / 2) < tol) { x = s.w / 2 - box.w / 2; gx = s.w / 2; }
if (Math.abs(y) < tol) { y = 0; gy = 0; }
if (Math.abs(x) < tol) { x = 0; gx = 0; }
if (Math.abs(x + box.w - s.w) < tol) { x = s.w - box.w; gx = s.w; }
if (Math.abs(cy - s.h / 2) < tol) { y = s.h / 2 - box.h / 2; gy = s.h / 2; }
if (Math.abs(y + box.h - s.h) < tol) { y = s.h - box.h; gy = s.h; }
if (x !== el.x || y !== el.y) moved = true;
el.x = x; el.y = y;
setElementTransform(el);
if (gx !== lastGx || gy !== lastGy) {
lastGx = gx; lastGy = gy;
setDragGuides(gx, gy);
}
}
function up() {
document.removeEventListener('pointermove', move);
document.removeEventListener('pointerup', up);
isDragging = false;
setDragGuides(null, null);
if (moved) {
commit();
const xIn = els.propsBody.querySelector('[data-prop="x"]');
const yIn = els.propsBody.querySelector('[data-prop="y"]');
if (xIn) xIn.value = mm(el.x);
if (yIn) yIn.value = mm(el.y);
renderTool();
}
}
document.addEventListener('pointermove', move);
document.addEventListener('pointerup', up);
e.preventDefault();
}
function startTransform(e, svg, handle) {
const el = selectedEl();
if (!el) return;
isDragging = true;
const box = R.elementBox(el);
const start = svgPoint(e, svg);
const orig = {
x: el.x, y: el.y, w: el.w, h: el.h, size: el.size || 0,
rotation: el.rotation || 0, cx: el.x + box.w / 2, cy: el.y + box.h / 2
};
const s = size();
const rot = orig.rotation * Math.PI / 180;
let moved = false;
function move(ev) {
const p = svgPoint(ev, els.canvasStage.querySelector('svg'));
const dx = p.x - start.x;
const dy = p.y - start.y;
moved = true;
if (handle === 'rot') {
const ang = Math.atan2(p.y - orig.cy, p.x - orig.cx) * 180 / Math.PI;
let next = ang - Math.atan2(start.y - orig.cy, start.x - orig.cx) * 180 / Math.PI + orig.rotation;
if (ev.shiftKey) next = Math.round(next / 15) * 15;
el.rotation = next;
setElementTransform(el);
return;
}
const lx = dx * Math.cos(rot) + dy * Math.sin(rot);
const ly = -dx * Math.sin(rot) + dy * Math.cos(rot);
if (el.type === 'text' && (handle === 'w' || handle === 'e')) {
const nw = Math.max(4, orig.w + (handle === 'e' ? lx : -lx));
el.w = nw;
if (handle === 'w') el.x = orig.x + (orig.w - nw);
renderCanvas();
return;
}
if (el.type === 'text') {
const factor = clamp((orig.w + (handle === 'w' || handle === 'nw' || handle === 'sw' ? -lx : lx)) / Math.max(4, orig.w), 0.2, 6);
el.w = Math.max(4, orig.w * factor);
el.size = Math.max(2, orig.size * factor);
if (handle === 'w' || handle === 'nw' || handle === 'sw') el.x = orig.x + orig.w - el.w;
renderCanvas();
return;
}
let nw = orig.w;
let nh = orig.h;
let nx = orig.x;
let ny = orig.y;
if (handle === 'e' || handle === 'ne' || handle === 'se') nw = orig.w + lx;
if (handle === 'w' || handle === 'nw' || handle === 'sw') { nw = orig.w - lx; nx = orig.x + lx; }
if (handle === 's' || handle === 'se' || handle === 'sw') nh = orig.h + ly;
if (handle === 'n' || handle === 'ne' || handle === 'nw') { nh = orig.h - ly; ny = orig.y + ly; }
nw = Math.max(3, nw);
nh = Math.max(3, nh);
if (ev.shiftKey && (handle === 'nw' || handle === 'ne' || handle === 'sw' || handle === 'se')) {
const aspect = orig.w / Math.max(0.1, orig.h);
if (nw / nh > aspect) nw = nh * aspect; else nh = nw / aspect;
if (handle === 'nw' || handle === 'sw') nx = orig.x + orig.w - nw;
if (handle === 'nw' || handle === 'ne') ny = orig.y + orig.h - nh;
}
if (el.type === 'sticker' || el.type === 'badge' || el.type === 'qr' || el.type === 'asset') {
nh = nw;
if (handle === 'nw' || handle === 'ne') ny = orig.y + orig.h - nh;
}
if (el.type === 'shape' && el.shape === 'line') nh = Math.max(3, orig.h);
el.w = nw;
if (el.type !== 'badge' && el.type !== 'qr') el.h = nh;
el.x = nx;
el.y = ny;
renderCanvas();
}
function up() {
document.removeEventListener('pointermove', move);
document.removeEventListener('pointerup', up);
isDragging = false;
if (moved) {
commit();
renderProps();
renderTool();
}
}
document.addEventListener('pointermove', move);
document.addEventListener('pointerup', up);
e.preventDefault();
e.stopPropagation();
}
function bindKeys() {
// 图层面板拖拽排序(按住行上下拖,松手落位;兼容 pointer / mouse / 合成拖拽)
let layerDrag = null;
function layerDragStart(row, e) {
if (!row || !row.dataset.layerId || layerDrag) return;
if (e.target && e.target.closest && e.target.closest('button')) return;
layerDrag = { id: row.dataset.layerId, row: row, startY: e.clientY, moved: false, target: null };
}
function layerDragMoveListen(e) {
if (!layerDrag && (e.buttons & 1) === 1) {
const row = e.target.closest && e.target.closest('.layer-row');
layerDragStart(row, e);
}
if (!layerDrag) return;
if (!layerDrag.moved && Math.abs(e.clientY - layerDrag.startY) <= 4) return;
if (!layerDrag.moved) layerDrag.row.classList.add('dragging');
layerDrag.moved = true;
if (e.cancelable) e.preventDefault();
const list = document.querySelector('.layer-list');
if (!list) return;
const rows = [...list.querySelectorAll('.layer-row')];
rows.forEach(function (r) { r.classList.remove('drop-above', 'drop-below'); });
let target = null;
for (let i = 0; i < rows.length; i += 1) {
const r = rows[i];
if (r === layerDrag.row || !r.dataset.layerId) continue;
const rc = r.getBoundingClientRect();
if (e.clientY >= rc.top && e.clientY <= rc.bottom) {
target = { row: r, above: e.clientY < rc.top + rc.height / 2 };
break;
}
}
if (target) target.row.classList.add(target.above ? 'drop-above' : 'drop-below');
// 即时落位:跨过插入线立即排序(无需等待松手)
const tid = target ? target.row.dataset.layerId : null;
if (target && (layerDrag.lastTargetId !== tid || layerDrag.lastAbove !== target.above)) {
layerDrag.lastTargetId = tid;
layerDrag.lastAbove = target.above;
reorderElement(layerDrag.id, tid, target.above);
layerDragCleanupS();
layerDrag.row = document.querySelector('.layer-row[data-layer-id="' + layerDrag.id + '"]');
} else if (!target) {
layerDrag.lastTargetId = null;
}
}
function layerDragEndListen() {
if (!layerDrag) return;
layerDrag = null;
document.querySelectorAll('.layer-row').forEach(function (r) {
r.classList.remove('dragging', 'drop-above', 'drop-below');
});
}
function layerDragCleanupS() {
document.querySelectorAll('.layer-row').forEach(function (r) {
r.classList.remove('dragging', 'drop-above', 'drop-below');
});
}
document.addEventListener('pointerdown', function (e) {
if (layerDrag) { layerDragCleanupS(); layerDrag = null; }
const row = e.target.closest && e.target.closest('.layer-row');
layerDragStart(row, e);
});
document.addEventListener('mousedown', function (e) {
if (layerDrag) { layerDragCleanupS(); layerDrag = null; }
const row = e.target.closest && e.target.closest('.layer-row');
layerDragStart(row, e);
});
document.addEventListener('pointermove', layerDragMoveListen, { passive: false });
document.addEventListener('mousemove', layerDragMoveListen, { passive: false });
document.addEventListener('pointerup', layerDragEndListen);
document.addEventListener('mouseup', layerDragEndListen);
// AI 排版悬浮入口
const aiFab = document.createElement('button');
aiFab.id = 'plAiFab';
aiFab.type = 'button';
aiFab.title = 'AI 排版(登录后可用)';
aiFab.innerHTML = '✨AI 排版';
document.body.appendChild(aiFab);
aiFab.addEventListener('click', function () { aiPanelToggle(); });
document.addEventListener('keydown', function (e) {
const tag = (document.activeElement && document.activeElement.tagName) || '';
const typing = tag === 'INPUT' || tag === 'TEXTAREA' || tag === 'SELECT' || document.activeElement.isContentEditable;
if (e.key === 'Escape') {
if (!els.modal3d.hidden) { close3d(); return; }
hideInlineText();
selectedId = null;
if (mode === 'design') { renderCanvas(); renderProps(); renderTool(); }
return;
}
if (typing && !((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === 's')) return;
if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === 'z') {
e.preventDefault();
if (e.shiftKey) doRedo(); else doUndo();
return;
}
if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === 's') {
e.preventDefault();
saveState();
toast('设计已保存到本地');
return;
}
if (mode !== 'design') return;
if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === 'd') {
e.preventDefault();
duplicateElement();
return;
}
if (e.key === 'Delete' || e.key === 'Backspace') {
if (selectedId) { e.preventDefault(); deleteElement(); }
return;
}
if (e.key.indexOf('Arrow') === 0 && selectedId) {
e.preventDefault();
const el = selectedEl();
if (!el) return;
const step = e.shiftKey ? 10 : 1;
if (e.key === 'ArrowLeft') el.x -= step;
if (e.key === 'ArrowRight') el.x += step;
if (e.key === 'ArrowUp') el.y -= step;
if (e.key === 'ArrowDown') el.y += step;
saveState();
renderCanvas();
const xIn = els.propsBody.querySelector('[data-prop="x"]');
const yIn = els.propsBody.querySelector('[data-prop="y"]');
if (xIn) xIn.value = mm(el.x);
if (yIn) yIn.value = mm(el.y);
return;
}
if (e.key === 'Enter' && selectedId) {
const el = selectedEl();
if (el && el.type === 'text') { e.preventDefault(); openInlineText(el); }
}
});
document.addEventListener('paste', function (e) {
if (mode !== 'design') return;
const items = e.clipboardData && e.clipboardData.items;
if (!items) return;
for (let i = 0; i < items.length; i += 1) {
if (items[i].type.indexOf('image') === 0) {
const file = items[i].getAsFile();
if (file) { addUploadedFile(file); e.preventDefault(); break; }
}
}
});
let resizeTimer;
window.addEventListener('resize', function () {
clearTimeout(resizeTimer);
resizeTimer = setTimeout(function () {
if (mode === 'design' && !isDragging) renderCanvas();
if (!els.modal3d.hidden) render3d();
}, 160);
});
}
function initFromURL() {
const params = new URLSearchParams(location.search);
const templateId = params.get('template');
const productId = params.get('product');
const toolParam = params.get('tool');
const modeParam = params.get('mode');
if (templateId) {
const t = D.templateById(templateId);
if (t) {
state.productId = t.product;
const p = product();
state.sizeId = p.sizes[Math.floor((p.sizes.length - 1) / 2)].id;
state.sampleApplied = true;
applyTemplate(templateId, { silent: true });
state.name = t.name + ' 设计';
els.designName.value = state.name;
mode = 'design';
skipSample = true;
return;
}
}
if (productId) {
const p = D.productById(productId);
if (p) {
const oldS = size();
const oldP = product();
const newS = D.sizeOf(p, p.sizes[Math.floor((p.sizes.length - 1) / 2)].id);
if (p.id !== oldP.id) {
if (state.sides.front.elements.length || state.sides.back.elements.length) scaleSides(oldS, newS);
state.productId = p.id;
state.sizeId = newS.id;
state.bagColor = null;
}
}
}
if (toolParam) {
tool = ['product', 'templates', 'upload', 'text', 'shapes', 'layers'].indexOf(toolParam) >= 0 ? toolParam : 'product';
mode = 'design';
skipSample = toolParam === 'upload';
return;
}
if (modeParam && ['settings', 'design', 'summary'].indexOf(modeParam) >= 0) {
mode = modeParam;
return;
}
mode = 'settings';
}
function init() {
els.designName.value = state.name;
initFromURL();
if (mode === 'design' && !state.sampleApplied && !skipSample) ensureSample();
history = [snapshot()];
hIndex = 0;
bindSettings();
bindTopbar();
bindDesign();
bindKeys();
renderSettings();
if (mode === 'design') {
setMode('design');
} else if (mode === 'summary') {
setMode('summary');
} else {
setMode('settings');
}
updateMeta();
saveState(true);
}
init();
})();