| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978 |
- /**
- * box.js — 3D 云设计编辑器(纸盒)主逻辑
- * 全面对标包小盒设计器:盒型库 / 模板 / 素材 / 文字 / 工具(条码·二维码) / 上传 / 图层 / 帮助
- * 2D刀版画布 + 3D预览动效 / 智能参数宝 / 导出(设计文件·效果图·视频) / 印刷下单
- */
- (function () {
- const D = window.PL.data;
- const R = window.PL.render;
- const UI = window.PL.ui;
- const h = UI.h;
- const A = UI.antd;
- const LB = window.PL.boxlib;
- const QR = window.PL.qrcode;
- const KEY = 'pouchlab.box.v2';
- const LIST_KEY = 'pouchlab.box.plans';
- const HIST_KEY = 'pouchlab.box.history';
- const $ = function (sel) { return document.querySelector(sel); };
- const clamp = function (v, a, b) { return Math.min(b, Math.max(a, v)); };
- function BoxTextField(props) {
- const [val, setVal] = React.useState(props.value == null ? '' : String(props.value));
- React.useEffect(function () { setVal(props.value == null ? '' : String(props.value)); }, [props.value]);
- return h(A.Input, {
- value: val,
- placeholder: props.placeholder,
- onChange: function (e) { setVal(e.target.value); if (props.onInput) props.onInput(e.target.value); },
- onBlur: function () { if (props.onCommit) props.onCommit(); }
- });
- }
- const FACES = [
- { id: 'front', name: '前面' }, { id: 'right', name: '右面' }, { id: 'back', name: '背面' },
- { id: 'left', name: '左面' }, { id: 'top', name: '顶面' }, { id: 'bottom', name: '底面' }
- ];
- /* 材质(对标包小盒「350g白卡(0.5mm)」命名) */
- const MATERIALS = [
- { id: 'card', name: '350g白卡(0.5mm)', thickness: 0.5, rate: 2.1, desc: '挺括细腻,适合彩印', paper: '#fbf7ee', paperEdge: '#e6ddcc', edgeW: 1, matte: false, grain: '', grainOpacity: 0, flute: '#e2d8c5' },
- { id: 'grey', name: '灰板2mm', thickness: 2.0, rate: 5.4, desc: '硬挺,适合精装礼盒', paper: '#c9c1b2', paperEdge: '#8f877a', edgeW: 4, matte: true, grainOpacity: 0.5, grain: '', flute: '#b3aa9a' },
- { id: 'kraft', name: '牛皮纸(0.4mm)', thickness: 0.4, rate: 2.6, desc: '自然原色,环保质感', paper: '#d7b17c', paperEdge: '#a97c4e', edgeW: 2, matte: true, grainOpacity: 0.75, grain: '', flute: '#b98a56' },
- { id: 'corrugated', name: 'E楞瓦楞(1.5mm)', thickness: 1.5, rate: 3.4, desc: '缓冲抗压,电商发货', paper: '#d3aa74', paperEdge: '#a97c4e', edgeW: 3, matte: true, grainOpacity: 0.85, grain: '', flute: '#a97c4e', edgePattern: true }
- ];
- /* 印色(对标包小盒印刷报价:四色/四色+1专/四色+2专/不印刷) */
- const PRINTS = [
- { id: 'cmyk', name: '四色', factor: 1 },
- { id: 'cmyk1', name: '四色+1专', factor: 1.18 },
- { id: 'cmyk2', name: '四色+2专', factor: 1.36 },
- { id: 'none', name: '不印刷', factor: 0.34 }
- ];
- const PRINT_WAYS = ['胶印合版', '胶印专版', '数码印刷'];
- /* 结构元数据 + 智能参数宝高级参数 */
- const STRUCTS = {
- carton: { name: '卡纸折叠盒', en: 'FOLDING CARTON', fee: 0.35, advanced: ['glue'] },
- rsc: { name: '平口箱', en: 'REGULAR SLOTTED CONTAINER', fee: 0.3, advanced: ['glue'] },
- tuck: { name: '反向插锁盒', en: 'REVERSE TUCK END', fee: 0.5, advanced: ['glue', 'tuckH', 'cornerR'] },
- straight: { name: '直插盒', en: 'STRAIGHT TUCK END', fee: 0.5, advanced: ['glue', 'tuckH', 'cornerR'] },
- autobottom: { name: '扣底盒', en: 'AUTO-LOCK BOTTOM', fee: 0.55, advanced: ['glue', 'cornerR'] },
- mailbox: { name: '磁吸书型盒', en: 'MAGNETIC BOOK BOX', fee: 1.6, advanced: ['lipW'] },
- mailer: { name: '飞机盒', en: 'MAILER BOX', fee: 0.7, advanced: ['tuckH', 'dustW'] },
- drawer: { name: '抽屉盒', en: 'DRAWER BOX', fee: 1.1, advanced: [] },
- bag: { name: '手提袋', en: 'PAPER BAG', fee: 0.9, advanced: ['topFold', 'holeR'] },
- sleeve: { name: '封套', en: 'SLEEVE', fee: 0.4, advanced: ['glue'] },
- card: { name: '卡牌/吊牌/标签', en: 'CARD & TAG', fee: 0.12, advanced: ['cornerR', 'holeR'] }
- };
- const ADV_FIELDS = {
- glue: { key: 'glue', code: 'G', name: '糊口长', unit: 'mm', min: 8, max: 40 },
- tuckH: { key: 'tuckH', code: 'C', name: '插舌长', unit: 'mm', min: 6, max: 24 },
- cornerR: { key: 'cornerR', code: 'R', name: '倒角', unit: 'mm', min: 0, max: 8, step: 0.1 },
- dustW: { key: 'dustW', code: 'AX', name: '槽口宽', unit: 'mm', min: 8, max: 24 },
- lipW: { key: 'lipW', code: 'OF', name: '沿口宽', unit: 'mm', min: 8, max: 30 },
- topFold: { key: 'topFold', code: 'A', name: '顶折边', unit: 'mm', min: 12, max: 40 },
- holeR: { key: 'holeR', code: 'E', name: '孔半径', unit: 'mm', min: 2, max: 8, step: 0.5 }
- };
- /* ---------------- 状态 ---------------- */
- function blankFaces() {
- const o = {};
- ['outer', 'inner'].forEach(function (side) {
- o[side] = {};
- FACES.forEach(function (f) { o[side][f.id] = { color: '', texture: null, items: [] }; });
- });
- return o;
- }
- const state = {
- planId: 'p' + Date.now().toString(36),
- name: '未命名纸盒',
- boxNo: '100010',
- structure: 'tuck',
- material: 'card',
- print: 'cmyk',
- printWay: '胶印合版',
- w: 120, d: 80, h: 180,
- qty: 1000,
- smart: { bleed: 3, glue: 15, tuckH: 12, cornerR: 1.5, dustW: 14, lipW: 16, topFold: 22, holeR: 4 },
- side: 'outer',
- faces: blankFaces(),
- selectedFace: 'front',
- selectedItemId: null,
- mode: '2d',
- showLines: true,
- autoRotate: false,
- uploads: [],
- view2d: { zoom: 0.6, panX: 0, panY: 0, preview: false }
- };
- try {
- const saved = JSON.parse(localStorage.getItem(KEY) || 'null');
- if (saved && saved.faces) {
- Object.assign(state, saved);
- const f = blankFaces();
- ['outer', 'inner'].forEach(function (side) {
- FACES.forEach(function (face) {
- const src = (saved.faces[side] && saved.faces[side][face.id]) || (side === 'outer' && saved.faces[face.id]) || {};
- const dst = f[side][face.id];
- dst.color = src.color || '';
- dst.texture = src.texture || null;
- let items = Array.isArray(src.items) ? src.items.slice() : [];
- (src.texts || []).forEach(function (t) { items.push(Object.assign({ type: 'text' }, t)); });
- if (src.image) items.push(Object.assign({ type: 'image' }, src.image));
- dst.items = items;
- });
- });
- state.faces = f;
- if (!Array.isArray(state.uploads)) state.uploads = [];
- }
- } catch (e) {}
- /* AI 设计师(首页 Agent)交接:应用其生成的盒子方案(外侧 6 面) */
- try {
- const rawH = localStorage.getItem('pouchlab.agent.handoff');
- if (rawH) {
- localStorage.removeItem('pouchlab.agent.handoff');
- const h = JSON.parse(rawH);
- const s = h && h.state;
- if (s && s.kind === 'box' && s.box) {
- const b = s.box;
- if (b.structure && STRUCTS[b.structure]) state.structure = b.structure;
- if (b.w) { state.w = b.w; state.d = b.d; state.h = b.h; }
- if (b.material) state.material = b.material;
- if (b.qty) state.qty = b.qty;
- state.side = 'outer';
- if (b.faces) {
- FACES.forEach(function (face) {
- const rd = b.faces[face.id];
- const fd = state.faces.outer[face.id];
- if (!rd) return;
- fd.color = rd.color || fd.color;
- fd.items = (rd.items || []).map(function (it) {
- it.id = 'i' + Date.now().toString(36) + Math.random().toString(36).slice(2, 5);
- return it;
- });
- });
- }
- setTimeout(function () { UI.message.success('已载入 AI 设计师整套方案,可继续微调'); }, 700);
- }
- }
- } catch (e) {}
- function material() { return MATERIALS.find(function (m) { return m.id === state.material; }) || MATERIALS[0]; }
- function print() { return PRINTS.find(function (p) { return p.id === state.print; }) || PRINTS[0]; }
- function struct() { return STRUCTS[state.structure] || STRUCTS.tuck; }
- function libEntry() { return LB.boxById(state.boxNo) || LB.BOXLIB[0]; }
- function curFaces() { return state.faces[state.side]; }
- function curFace() { return curFaces()[state.selectedFace]; }
- /* ---------------- 撤销 / 重做 ---------------- */
- const undoStack = [], redoStack = [];
- let suspending = false;
- function snapshot() { return JSON.stringify({ name: state.name, boxNo: state.boxNo, structure: state.structure, material: state.material, print: state.print, printWay: state.printWay, w: state.w, d: state.d, h: state.h, qty: state.qty, smart: state.smart, faces: state.faces }); }
- function pushUndo() {
- if (suspending) return;
- undoStack.push(snapshot());
- if (undoStack.length > 60) undoStack.shift();
- redoStack.length = 0;
- updateHistoryBtns();
- }
- function restore(str) {
- suspending = true;
- const data = JSON.parse(str);
- Object.assign(state, data);
- const f = blankFaces();
- ['outer', 'inner'].forEach(function (side) {
- FACES.forEach(function (face) {
- const src = (data.faces[side] && data.faces[side][face.id]) || {};
- f[side][face.id] = { color: src.color || '', texture: src.texture || null, items: src.items || [] };
- });
- });
- state.faces = f;
- suspending = false;
- commit(false);
- }
- function undo() {
- if (!undoStack.length) return;
- redoStack.push(snapshot());
- restore(undoStack.pop());
- updateHistoryBtns();
- }
- function redo() {
- if (!redoStack.length) return;
- undoStack.push(snapshot());
- restore(redoStack.pop());
- updateHistoryBtns();
- }
- function updateHistoryBtns() {
- $('#bxUndoBtn').disabled = !undoStack.length;
- $('#bxRedoBtn').disabled = !redoStack.length;
- }
- /* ---------------- 刀版生成 ---------------- */
- function rect(x, y, w, hh, face, kind) { return { x: x, y: y, w: w, h: hh, face: face, kind: kind || 'body' }; }
- function poly(points, face, kind) {
- return { poly: points, face: face, kind: kind || 'flap', x: Math.min.apply(null, points.map(function (p) { return p[0]; })), y: Math.min.apply(null, points.map(function (p) { return p[1]; })), w: 0, h: 0 };
- }
- function panelBounds(p) {
- if (!p.poly) return { x: p.x, y: p.y, w: p.w, h: p.h };
- const xs = p.poly.map(function (pt) { return pt[0]; });
- const ys = p.poly.map(function (pt) { return pt[1]; });
- const x = Math.min.apply(null, xs), y = Math.min.apply(null, ys);
- return { x: x, y: y, w: Math.max.apply(null, xs) - x, h: Math.max.apply(null, ys) - y };
- }
- const ACCESSORY = { glue: 1, flap: 1, dust: 1, tuck: 1, lip: 1 };
- function isBodyKind(k) { return !ACCESSORY[k]; }
- function panelEdges(p) {
- const pts = p.poly || [[p.x, p.y], [p.x + p.w, p.y], [p.x + p.w, p.y + p.h], [p.x, p.y + p.h]];
- const out = [];
- for (let i = 0; i < pts.length; i += 1) {
- const a = pts[i], b = pts[(i + 1) % pts.length];
- if (Math.abs(a[0] - b[0]) < 0.05) out.push({ axis: 'v', c: a[0], lo: Math.min(a[1], b[1]), hi: Math.max(a[1], b[1]) });
- else if (Math.abs(a[1] - b[1]) < 0.05) out.push({ axis: 'h', c: a[1], lo: Math.min(a[0], b[0]), hi: Math.max(a[0], b[0]) });
- }
- return out;
- }
- function sharedEdge(a, b) {
- let best = null;
- panelEdges(a).forEach(function (ea) {
- panelEdges(b).forEach(function (eb) {
- if (ea.axis !== eb.axis || Math.abs(ea.c - eb.c) > 0.6) return;
- const lo = Math.max(ea.lo, eb.lo), hi = Math.min(ea.hi, eb.hi), len = hi - lo;
- if (len <= 2) return;
- if (!best || len > best.len) best = { axis: ea.axis, c: ea.c, lo: lo, hi: hi, len: len };
- });
- });
- return best;
- }
- function canHinge(a, b) {
- const ka = a.kind || 'body', kb = b.kind || 'body';
- if (isBodyKind(ka) !== isBodyKind(kb)) return true;
- if (isBodyKind(ka) && isBodyKind(kb)) return true;
- return (ka === 'tuck' && kb === 'flap') || (ka === 'flap' && kb === 'tuck');
- }
- function autoFolds(panels) {
- const out = [];
- for (let i = 0; i < panels.length; i += 1) for (let j = i + 1; j < panels.length; j += 1) {
- if (!canHinge(panels[i], panels[j])) continue;
- const e = sharedEdge(panels[i], panels[j]);
- if (!e) continue;
- if (e.axis === 'v') out.push({ x1: e.c, y1: e.lo, x2: e.c, y2: e.hi });
- else out.push({ x1: e.lo, y1: e.c, x2: e.hi, y2: e.c });
- }
- return out;
- }
- function finishDieline(panels) {
- let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity;
- panels.forEach(function (p) {
- const b = panelBounds(p);
- minX = Math.min(minX, b.x); minY = Math.min(minY, b.y);
- maxX = Math.max(maxX, b.x + b.w); maxY = Math.max(maxY, b.y + b.h);
- });
- return { panels: panels, folds: autoFolds(panels), size: { w: maxX - minX, h: maxY - minY }, minX: minX, minY: minY, bounds: { w: maxX - minX, h: maxY - minY, minX: minX, minY: minY } };
- }
- function roundedRectPoly(x, y, w, hh, r) {
- r = Math.min(r, w / 2, hh / 2);
- if (r <= 0.05) return [[x, y], [x + w, y], [x + w, y + hh], [x, y + hh]];
- const pts = [];
- const arc = function (cx, cy, a0, a1) {
- for (let i = 0; i <= 6; i += 1) {
- const a = a0 + (a1 - a0) * i / 6;
- pts.push([cx + r * Math.cos(a), cy + r * Math.sin(a)]);
- }
- };
- arc(x + w - r, y + r, -Math.PI / 2, 0);
- arc(x + w - r, y + hh - r, 0, Math.PI / 2);
- arc(x + r, y + hh - r, Math.PI / 2, Math.PI);
- arc(x + r, y + r, Math.PI, Math.PI * 1.5);
- return pts;
- }
- function circlePoly(cx, cy, r) {
- const pts = [];
- for (let i = 0; i < 36; i += 1) {
- const a = i / 36 * Math.PI * 2;
- pts.push([cx + r * Math.cos(a), cy + r * Math.sin(a)]);
- }
- return pts;
- }
- function buildDieline(type, w, d, hh, params) {
- const t = material().thickness;
- const W = w + t * 2, D2 = d + t * 2, H = hh + t * 2;
- const P = params || state.smart;
- const panels = [];
- if (type === 'card') {
- const isRound = state.boxNo === '260040' || state.boxNo === '270020' || state.boxNo === '261002';
- const hole = P.holeR || 0;
- const p1 = isRound
- ? poly(circlePoly(W / 2, H / 2, Math.min(W, H) / 2), 'front', 'body')
- : poly(roundedRectPoly(0, 0, W, H, P.cornerR || 0), 'front', 'body');
- if (hole && !isRound) {
- p1.holes = [{ x: W / 2, y: hole + 4, r: hole }];
- p1.holeH = hole * 2 + 8;
- }
- panels.push(p1);
- const back = isRound
- ? poly(circlePoly(W / 2, H / 2, Math.min(W, H) / 2), 'back', 'body')
- : poly(roundedRectPoly(W + 10, 0, W, H, P.cornerR || 0), 'back', 'body');
- panels.push(back);
- return finishDieline(panels);
- }
- if (type === 'sleeve') {
- const glue = P.glue;
- let x = 0;
- panels.push(rect(x, 0, glue, H, null, 'glue')); x += glue;
- panels.push(rect(x, 0, W, H, 'front', 'body')); x += W;
- panels.push(rect(x, 0, D2, H, null, 'flap')); x += D2;
- panels.push(rect(x, 0, W, H, 'back', 'body')); x += W;
- panels.push(rect(x, 0, D2, H, null, 'flap'));
- return finishDieline(panels);
- }
- if (type === 'bag') {
- const tf = P.topFold || 20;
- const holeR = P.holeR || 4;
- const gus = D2 / 2;
- let x = 0;
- panels.push(rect(x, 0, W, H, 'front', 'body'));
- panels.push(rect(x, -tf, W, tf, null, 'flap'));
- const fP = panels[0], fT = panels[1];
- fP.holes = []; fT.holes = [{ x: x + W * 0.22, y: -tf + tf / 2, r: holeR }, { x: x + W * 0.78, y: -tf + tf / 2, r: holeR }];
- x += W;
- panels.push(rect(x, 0, gus, H, null, 'body')); x += gus;
- panels.push(rect(x, 0, gus, H, null, 'body')); x += gus;
- panels.push(rect(x, 0, W, H, 'back', 'body'));
- panels.push(rect(x, -tf, W, tf, null, 'flap'));
- panels[panels.length - 1].holes = [{ x: x + W * 0.22, y: -tf + tf / 2, r: holeR }, { x: x + W * 0.78, y: -tf + tf / 2, r: holeR }];
- x += W;
- panels.push(rect(x, 0, gus, H, null, 'body')); x += gus;
- panels.push(rect(x, 0, gus, H, null, 'body'));
- panels.push(rect(0, H, W, D2, 'bottom', 'body'));
- return finishDieline(panels);
- }
- // 管式盒族
- const glue = P.glue;
- const ch = Math.max(3, Math.min(8, D2 * 0.06)) * (1 - Math.min(1, (P.cornerR || 0) / 8) * 0.5);
- const half = D2 / 2;
- const xF = glue, xR = xF + W, xB = xR + D2, xL = xB + W;
- panels.push(rect(0, 0, glue, H, null, 'glue'));
- panels.push(rect(xF, 0, W, H, 'front', 'body'));
- panels.push(rect(xR, 0, D2, H, 'right', 'body'));
- panels.push(rect(xB, 0, W, H, 'back', 'body'));
- panels.push(rect(xL, 0, D2, H, 'left', 'body'));
- const big = function (x, y, face, dir) {
- const yy = dir * (half + 2);
- return poly([[x, y], [x + ch, y + yy], [x + W - ch, y + yy], [x + W, y]], face, 'flap');
- };
- const dust = function (x, y, dir) {
- const yy = dir * (half - 2);
- return poly([[x, y], [x + ch, y + yy], [x + D2 - ch, y + yy], [x + D2, y]], null, 'dust');
- };
- const tuckH = P.tuckH;
- if (type === 'rsc') {
- [[xF, W, 'top', true], [xR, D2, null, false], [xB, W, null, false], [xL, D2, null, false]].forEach(function (f) {
- const top = rect(f[0], -half, f[1], half, f[2], 'flap');
- if (!f[2]) top.paint = 'top';
- panels.push(top);
- const bottom = rect(f[0], H, f[1], half, f[3] ? 'bottom' : null, 'flap');
- if (!f[3]) bottom.paint = 'bottom';
- panels.push(bottom);
- });
- } else if (type === 'carton') {
- panels.push(big(xF, 0, 'top', -1));
- const topBack = big(xB, 0, null, -1);
- topBack.paint = 'top';
- panels.push(topBack);
- panels.push(dust(xR, 0, -1));
- panels.push(dust(xL, 0, -1));
- panels.push(big(xF, H, 'bottom', 1));
- const bottomBack = big(xB, H, null, 1);
- bottomBack.paint = 'bottom';
- panels.push(bottomBack);
- panels.push(dust(xR, H, 1));
- panels.push(dust(xL, H, 1));
- } else if (type === 'mailer') {
- const dustW = P.dustW;
- panels.push(poly([[xB, 0], [xB + ch, -(D2 + 2)], [xB + W - ch, -(D2 + 2)], [xB + W, 0]], 'top', 'flap'));
- const mt = rect(xB + dustW, -(D2 + 2) - tuckH, W - dustW * 2, tuckH, null, 'tuck');
- if ((P.holeR || 0) > 1 && tuckH > (P.holeR || 4) * 2 + 1) {
- mt.holes = [{ x: xB + dustW + (W - dustW * 2) / 2, y: -(D2 + 2) - tuckH / 2, r: P.holeR }];
- }
- panels.push(mt);
- panels.push(rect(xB - dustW, -(D2 + 2), dustW, D2, null, 'dust'));
- panels.push(rect(xB + W, -(D2 + 2), dustW, D2, null, 'dust'));
- panels.push(poly([[xF, H], [xF + ch, H + D2 + 2], [xF + W - ch, H + D2 + 2], [xF + W, H]], 'bottom', 'flap'));
- const mb = rect(xF + dustW, H + D2 + 2, W - dustW * 2, tuckH, null, 'tuck');
- if ((P.holeR || 0) > 1 && tuckH > (P.holeR || 4) * 2 + 1) {
- mb.holes = [{ x: xF + dustW + (W - dustW * 2) / 2, y: H + D2 + 2 + tuckH / 2, r: P.holeR }];
- }
- panels.push(mb);
- panels.push(rect(xF - dustW, H + D2 + 2, dustW, D2, null, 'dust'));
- panels.push(rect(xF + W, H + D2 + 2, dustW, D2, null, 'dust'));
- } else {
- // tuck / straight / autobottom:上盖挂后板
- const lidD = D2 + 2;
- panels.push(poly([[xB, 0], [xB + ch, -lidD], [xB + W - ch, -lidD], [xB + W, 0]], 'top', 'flap'));
- const tuckTop = rect(xB + 18, -lidD - tuckH, W - 36, tuckH, null, 'tuck');
- if ((P.holeR || 0) > 1 && tuckH > (P.holeR || 4) * 2 + 1) {
- tuckTop.holes = [{ x: xB + W / 2, y: -lidD - tuckH / 2, r: P.holeR }];
- }
- panels.push(tuckTop);
- panels.push(dust(xR, 0, -1));
- panels.push(dust(xL, 0, -1));
- if (type === 'straight') {
- panels.push(poly([[xB, H], [xB + ch, H + lidD], [xB + W - ch, H + lidD], [xB + W, H]], 'bottom', 'flap'));
- const tuckBot = rect(xB + 18, H + lidD, W - 36, tuckH, null, 'tuck');
- if ((P.holeR || 0) > 1 && tuckH > (P.holeR || 4) * 2 + 1) {
- tuckBot.holes = [{ x: xB + W / 2, y: H + lidD + tuckH / 2, r: P.holeR }];
- }
- panels.push(tuckBot);
- panels.push(dust(xR, H, 1));
- panels.push(dust(xL, H, 1));
- } else if (type === 'autobottom') {
- const d1 = half + 5, d2 = half + 2, c2 = ch * 0.6;
- panels.push(poly([
- [xF, H], [xF + c2, H + d1], [xF + W * 0.32, H + d1], [xF + W * 0.32, H + d1 - 4],
- [xF + W * 0.68, H + d1 - 4], [xF + W * 0.68, H + d1], [xF + W - c2, H + d1], [xF + W, H]
- ], 'bottom', 'flap'));
- const bottomBack = poly([[xB, H], [xB + c2, H + d2], [xB + W - c2, H + d2], [xB + W, H]], null, 'flap');
- bottomBack.paint = 'bottom';
- panels.push(bottomBack);
- const bottomR = poly([[xR, H], [xR + D2, H], [xR + D2 / 2, H + half + 3]], null, 'dust');
- bottomR.paint = 'bottom';
- panels.push(bottomR);
- const bottomL = poly([[xL, H], [xL + D2, H], [xL + D2 / 2, H + half + 3]], null, 'dust');
- bottomL.paint = 'bottom';
- panels.push(bottomL);
- } else {
- // tuck 反向插锁:下盖挂前板
- panels.push(poly([[xF, H], [xF + ch, H + lidD], [xF + W - ch, H + lidD], [xF + W, H]], 'bottom', 'flap'));
- panels.push(rect(xF + 18, H + lidD, W - 36, tuckH, null, 'tuck'));
- panels.push(dust(xR, H, 1));
- panels.push(dust(xL, H, 1));
- }
- }
- return finishDieline(panels);
- }
- if (state.structure === 'mailbox') {
- // mailbox 在 buildDieline 主流程外定义,包装一次
- }
- const _buildDielineBase = buildDieline;
- buildDieline = function (type, w, d, hh, params) {
- if (type === 'mailbox') {
- const t = material().thickness;
- const W = w + t * 2, D2 = d + t * 2, H = hh + t * 2;
- const P = params || state.smart;
- const lipW = P.lipW;
- const xRw = 0, xB = D2, xSpine = xB + W, xF = xSpine + D2;
- const panels = [
- rect(xRw, 0, D2, H, 'right', 'body'),
- rect(xB, 0, W, H, 'back', 'body'),
- rect(xSpine, 0, D2, H, 'left', 'body'),
- rect(xF, 0, W, H, 'front', 'body'),
- rect(xF + W, 0, lipW, H, null, 'lip'),
- rect(xB, -D2, W, D2, 'top', 'body'),
- rect(xB, H, W, D2, 'bottom', 'body')
- ];
- return finishDieline(panels);
- }
- if (type === 'drawer') {
- const t = material().thickness;
- const W = w + t * 2, D2 = d + t * 2, H = hh + t * 2;
- const glue = (params || state.smart).glue;
- const xF = glue, xR = xF + W, xB = xR + D2, xL = xB + W;
- const panels = [
- rect(0, 0, glue, H, null, 'glue'),
- rect(xF, 0, W, H, 'front', 'body'),
- rect(xR, 0, D2, H, 'right', 'body'),
- rect(xB, 0, W, H, 'back', 'body'),
- rect(xL, 0, D2, H, 'left', 'body')
- ];
- const W2 = Math.max(10, W - 2), D3 = Math.max(10, D2 - 2), TH = Math.max(10, H - 8);
- const ty = H + 26, tx0 = 24, txF = tx0 + glue, txR = txF + W2, txB = txR + D3, txL = txB + W2;
- panels.push(rect(tx0, ty, glue, TH, null, 'glue'));
- panels.push(rect(txF, ty, W2, TH, 'front', 'tray'));
- panels.push(rect(txR, ty, D3, TH, null, 'tray'));
- panels.push(rect(txB, ty, W2, TH, null, 'tray'));
- panels.push(rect(txL, ty, D3, TH, null, 'tray'));
- panels.push(rect(txF, ty + TH, W2, D3, null, 'bottom'));
- return finishDieline(panels);
- }
- return _buildDielineBase(type, w, d, hh, params);
- };
- function dieline() { return buildDieline(state.structure, state.w, state.d, state.h); }
- function outerSize() {
- const t = material().thickness;
- return { w: state.w + t * 2, d: state.d + t * 2, h: state.h + t * 2 };
- }
- /* ---------------- 报价 ---------------- */
- function priceInfo() {
- const dl = dieline();
- const area = (dl.size.w * dl.size.h) / 1000000;
- const mat = material(), pr = print();
- const base = area * mat.rate * pr.factor + struct().fee;
- const qty = state.qty;
- const disc = qty >= 10000 ? 0.72 : qty >= 5000 ? 0.78 : qty >= 2000 ? 0.84 : qty >= 1000 ? 0.9 : qty >= 500 ? 0.95 : 1;
- const unit = base * disc;
- return { area: area, unit: unit, total: unit * qty, disc: disc, dl: dl };
- }
- /* ---------------- 刀版 SVG ---------------- */
- function faceName(id) {
- const f = FACES.find(function (x) { return x.id === id; });
- return f ? f.name : '';
- }
- function itemSvg(it, bx, by, bw, bh, mm2px) {
- const cx = bx + (it.x / 100) * bw, cy = by + (it.y / 100) * bh;
- if (it.hidden) return { art: '', hit: '' };
- // 内侧版面整体镜像(相当于从背面看印刷面),元素随之翻转
- function hitRect(x, y, w, h) {
- return '<rect class="bx-item-hit" data-item-id="' + it.id + '" data-item-face="' + (it._face || '') + '" x="' + (x - 3).toFixed(2) + '" y="' + (y - 3).toFixed(2) + '" width="' + (w + 6).toFixed(2) + '" height="' + (h + 6).toFixed(2) + '" fill="transparent" pointer-events="all"/>';
- }
- if (it.type === 'text') {
- const anchor = it.align === 'center' ? 'middle' : it.align === 'right' ? 'end' : 'start';
- const lines = String(it.text || '').split('\n');
- const fs = it.size * mm2px;
- const lh = (it.lineHeight || 1.25) * fs;
- let out = '', maxW = 0;
- lines.forEach(function (line, li) {
- const tw = String(line).split('').reduce(function (s, ch) { return s + (/[\x00-\xff]/.test(ch) ? 0.56 : 1) * fs; }, 0);
- if (tw > maxW) maxW = tw;
- out += '<text x="' + cx.toFixed(2) + '" y="' + (cy + (li - (lines.length - 1) / 2) * lh).toFixed(2) + '" text-anchor="' + anchor + '" dominant-baseline="middle" font-size="' + fs.toFixed(2) + '" fill="' + (it.color || '#17140f') + '" font-family="Helvetica Neue, PingFang SC, sans-serif" font-weight="' + (it.weight || 400) + '"' + (it.italic ? ' font-style="italic"' : '') + '>' + R.esc(line) + '</text>';
- });
- maxW = Math.max(maxW, fs * 2);
- const totalH = Math.max(lines.length * lh, fs);
- const left = anchor === 'start' ? cx : anchor === 'end' ? cx - maxW : cx - maxW / 2;
- return { art: out, hit: hitRect(left, cy - totalH / 2, maxW, totalH) };
- }
- if (it.type === 'image' || it.type === 'asset') {
- const iw = ((it.w == null ? 60 : it.w) / 100) * bw;
- return { art: '<image href="' + it.src + '" x="' + (cx - iw / 2).toFixed(2) + '" y="' + (cy - iw / 2).toFixed(2) + '" width="' + iw.toFixed(2) + '" height="' + iw.toFixed(2) + '" preserveAspectRatio="xMidYMid meet"/>', hit: hitRect(cx - iw / 2, cy - iw / 2, iw, iw) };
- }
- if (it.type === 'barcode') {
- const iw = ((it.w || 40) / 100) * bw;
- const ih = iw * 0.84;
- return { art: '<image href="' + it.src + '" x="' + (cx - iw / 2).toFixed(2) + '" y="' + (cy - ih / 2).toFixed(2) + '" width="' + iw.toFixed(2) + '" height="' + ih.toFixed(2) + '"/>', hit: hitRect(cx - iw / 2, cy - ih / 2, iw, ih) };
- }
- return { art: '', hit: '' };
- }
- function dielineSVG(opts) {
- opts = opts || {};
- const dl = dieline();
- const mat = material();
- const pad = 30;
- const bleed = state.smart.bleed || 0;
- const inner = state.side === 'inner';
- const uid = opts.idPrefix || 'dl';
- const vbW = dl.size.w + pad * 2 + bleed * 2;
- const vbH = dl.size.h + pad * 2 + bleed * 2 + (opts.noLegend ? 0 : 56);
- const off = function (x, y) { return [x - dl.minX + pad + bleed, y - dl.minY + pad + bleed]; };
- let body = '', defs = '', art = '', hit = '', itemHits = '', notes = '';
- const useMatPattern = state.material === 'corrugated' || state.material === 'kraft';
- if (useMatPattern) {
- defs += '<pattern id="' + uid + '-mat" width="5" height="5" patternUnits="userSpaceOnUse">' +
- '<rect width="5" height="5" fill="' + mat.paper + '"/>' +
- '<line x1="0.6" y1="0" x2="0.6" y2="5" stroke="' + mat.flute + '" stroke-width="1" opacity="0.55"/></pattern>';
- }
- const matFill = useMatPattern ? 'url(#' + uid + '-mat)' : mat.paper;
- // 结构件(防尘翼/插舌/糊口等)不印刷:素纸色 + 45° 斜线纹理,与印刷面区分
- defs += '<pattern id="' + uid + '-acc" width="7" height="7" patternUnits="userSpaceOnUse" patternTransform="rotate(45)">' +
- '<rect width="7" height="7" fill="' + mat.paper + '"/>' +
- '<line x1="0" y1="0" x2="0" y2="7" stroke="' + mat.flute + '" stroke-width="1.4" opacity="0.5"/></pattern>';
- dl.panels.forEach(function (p, i) {
- const pts = p.poly ? p.poly.map(function (pt) { return off(pt[0], pt[1]); }) : [off(p.x, p.y), off(p.x + p.w, p.y), off(p.x + p.w, p.y + p.h), off(p.x, p.y + p.h)];
- const cid = uid + '-p' + i;
- const f = p.face ? curFaces()[p.face] : null;
- const plain = curFaces()._plain || {};
- const isAcc = ACCESSORY[p.kind] && !p.face; // 有 face 的面(如飞机盒顶/底盖)可印刷,不算结构件
- let panelFill;
- if (isAcc) {
- panelFill = 'url(#' + uid + '-acc)';
- } else if (f) {
- panelFill = f.color || (f.texture ? 'url(#' + uid + '-tex' + i + ')' : matFill);
- } else {
- panelFill = plain.color || matFill;
- }
- if (f && f.texture) {
- defs += '<pattern id="' + uid + '-tex' + i + '" width="60" height="60" patternUnits="userSpaceOnUse"><image href="' + f.texture + '" width="60" height="60"/></pattern>';
- }
- const points = pts.map(function (pt) { return pt[0].toFixed(2) + ',' + pt[1].toFixed(2); }).join(' ');
- const shape = p.poly ? '<polygon points="' + points + '"/>' : '<rect x="' + pts[0][0] + '" y="' + pts[0][1] + '" width="' + (p.w || 0) + '" height="' + (p.h || 0) + '"/>';
- defs += '<clipPath id="' + cid + '">' + shape + '</clipPath>';
- const picked = p.face && p.face === state.selectedFace ? ' is-picked' : '';
- body += '<polygon class="dieline-panel' + picked + '" data-face="' + (p.face || '') + '" data-panel="' + i + '" fill="' + panelFill + '" points="' + points + '"/>';
- if (p.holes) {
- p.holes.forEach(function (ho, hi) {
- const c = off(ho.x, ho.y);
- art += '<circle cx="' + c[0].toFixed(2) + '" cy="' + c[1].toFixed(2) + '" r="' + ho.r + '" fill="#fff" stroke="#c2451f" stroke-width="0.5"/>';
- if (!opts.clean) {
- // 圆心十字定位线(超出孔径 2.5mm)+ 孔径标注;标注放在镜像组外,避免文字反写
- const ext = ho.r + 2.5;
- const mx = inner ? vbW - c[0] : c[0];
- notes += '<g class="dieline-dim">' +
- '<path d="M' + (mx - ext).toFixed(2) + ' ' + c[1].toFixed(2) + 'H' + (mx + ext).toFixed(2) + '"/>' +
- '<path d="M' + mx.toFixed(2) + ' ' + (c[1] - ext).toFixed(2) + 'V' + (c[1] + ext).toFixed(2) + '"/>' +
- '<circle cx="' + mx.toFixed(2) + '" cy="' + c[1].toFixed(2) + '" r="0.5" fill="#c2451f" stroke="none"/>' +
- '</g>' +
- '<text data-ui="1" class="dieline-dim" x="' + (inner ? mx - ext - 1.2 : mx + ext + 1.2).toFixed(2) + '" y="' + (c[1] - 0.8).toFixed(2) + '" text-anchor="' + (inner ? 'end' : 'start') + '" font-size="' + Math.max(4, Math.min(6, ho.r * 1.1)) + '" fill="#c2451f">Ø' + (ho.r * 2).toFixed(1) + ' 开孔</text>';
- }
- });
- }
- if (p.face && f) {
- const b = panelBounds(p);
- (f.items || []).forEach(function (it) {
- it._face = p.face;
- const r = itemSvg(it, b.x, b.y, b.w, b.h, 1);
- const tx = 'translate(' + (pad + bleed - dl.minX) + ',' + (pad + bleed - dl.minY) + ')';
- art += '<g clip-path="url(#' + cid + ')"><g transform="' + tx + '">' + r.art + '</g></g>';
- itemHits += '<g clip-path="url(#' + cid + ')"><g transform="' + tx + '">' + r.hit + '</g></g>';
- });
- const cx = off(b.x + b.w / 2, b.y + b.h / 2);
- if (state.showLines && !opts.clean) notes += '<text data-ui="1" class="dieline-face-label" x="' + (inner ? vbW - cx[0] : cx[0]) + '" y="' + (cx[1] + 1) + '" text-anchor="middle">' + faceName(p.face) + '</text>';
- hit += '<polygon class="dieline-hit" data-face="' + p.face + '" points="' + points + '" fill="transparent"/>';
- }
- });
- let foldBody = '';
- if (state.showLines && !opts.clean) {
- dl.folds.forEach(function (f) {
- const a = off(f.x1, f.y1), b = off(f.x2, f.y2);
- foldBody += '<line class="dieline-fold" x1="' + a[0].toFixed(2) + '" y1="' + a[1].toFixed(2) + '" x2="' + b[0].toFixed(2) + '" y2="' + b[1].toFixed(2) + '"/>';
- });
- }
- let dims = '';
- if (!opts.clean) {
- const dimTop = pad, dimBottom = pad + dl.size.h;
- dims =
- '<g class="dieline-dim"><path d="M' + (pad - 8) + ' ' + dimTop + 'V' + dimBottom + '"/><path d="M' + (pad - 11) + ' ' + dimTop + 'h6M' + (pad - 11) + ' ' + dimBottom + 'h6"/></g>' +
- '<text data-ui="1" class="dieline-label" x="' + (pad - 14) + '" y="' + ((dimTop + dimBottom) / 2) + '" text-anchor="middle" transform="rotate(-90 ' + (pad - 14) + ' ' + ((dimTop + dimBottom) / 2) + ')">' + Math.round(dl.size.h) + ' mm</text>' +
- '<g class="dieline-dim"><path d="M' + pad + ' ' + (dimBottom + 10) + 'H' + (pad + dl.size.w) + '"/><path d="M' + pad + ' ' + (dimBottom + 7) + 'v6M' + (pad + dl.size.w) + ' ' + (dimBottom + 7) + 'v6"/></g>' +
- '<text data-ui="1" class="dieline-label" x="' + (pad + dl.size.w / 2) + '" y="' + (dimBottom + 22) + '" text-anchor="middle">' + Math.round(dl.size.w) + ' mm</text>';
- // 每个印刷面内标注该面的宽 × 高(mm);poly 面(梯形盖等)动态算外接框、文字置于底部
- const FACE_NAMES = { front: '正面', back: '背面', left: '左', right: '右', top: '顶', bottom: '底' };
- dl.panels.forEach(function (p) {
- if (!p.face) return;
- let bw = p.w, bh = p.h, bx = p.x, by = p.y;
- if (p.poly) { // poly() 构造的 w/h 为 0,动态求外接框
- let minX = 1e9, minY = 1e9, maxX = -1e9, maxY = -1e9;
- p.poly.forEach(function (pt) {
- minX = Math.min(minX, pt[0]); maxX = Math.max(maxX, pt[0]);
- minY = Math.min(minY, pt[1]); maxY = Math.max(maxY, pt[1]);
- });
- bx = minX; by = minY; bw = maxX - minX; bh = maxY - minY;
- }
- if (!bw || !bh) return;
- const cx = bx + bw / 2;
- const isPoly = !!p.poly;
- const fs = Math.max(4.2, Math.min(8, bw / 9));
- const label = FACE_NAMES[p.face] ? FACE_NAMES[p.face] + ' ' : '';
- const cy = isPoly ? by + bh - fs * 0.9 : by + bh / 2;
- dims += '<text data-ui="1" class="dieline-dim" x="' + (inner ? vbW - cx : cx).toFixed(1) + '" y="' + cy.toFixed(1) + '" text-anchor="middle" font-size="' + fs.toFixed(1) + '" fill="#6f6a5e" opacity="0.9">' + label + Math.round(bw) + ' × ' + Math.round(bh) + '</text>';
- });
- if (bleed) {
- dims += '<rect class="dieline-bleed" x="' + (pad - bleed) + '" y="' + (pad - bleed) + '" width="' + (dl.size.w + bleed * 2) + '" height="' + (dl.size.h + bleed * 2) + '"/>';
- }
- }
- const legend = opts.clean ? '' : '<g><line x1="' + (pad + 70) + '" y1="' + (pad + dl.size.h + 32) + '" x2="' + (pad + 94) + '" y2="' + (pad + dl.size.h + 32) + '" stroke="#c2451f" stroke-width="0.6"/><text data-ui="1" class="dieline-cut-label" x="' + (pad + 100) + '" y="' + (pad + dl.size.h + 33) + '">裁切线</text></g>' +
- '<g><line class="dieline-fold" x1="' + (pad + 6) + '" y1="' + (pad + dl.size.h + 32) + '" x2="' + (pad + 30) + '" y2="' + (pad + dl.size.h + 32) + '"/><text data-ui="1" class="dieline-cut-label" x="' + (pad + 36) + '" y="' + (pad + dl.size.h + 33) + '">折叠线</text></g>' +
- '<g><rect x="' + (pad + 170) + '" y="' + (pad + dl.size.h + 27) + '" width="24" height="10" fill="url(#' + uid + '-acc)" stroke="#c9bfae" stroke-width="0.5"/><text data-ui="1" class="dieline-cut-label" x="' + (pad + 200) + '" y="' + (pad + dl.size.h + 33) + '">防尘翼/插舌(不印刷)</text></g>' +
- '<text data-ui="1" class="dieline-cut-label" x="' + (pad + 330) + '" y="' + (pad + dl.size.h + 33) + '">' + (inner ? '内侧设计 · 镜像' : '外侧设计') + ' · 模型ID ' + state.boxNo + '</text>';
- const mirror = inner ? ' transform="translate(' + vbW + ',0) scale(-1,1)"' : '';
- // 只有几何与画面内容参与镜像;文字标注、尺寸、图例放在镜像组外,保持可读
- return '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ' + vbW + ' ' + vbH + '"><defs>' + defs + '</defs>' +
- '<g' + mirror + '>' + body + foldBody + art + hit + itemHits + '</g>' +
- notes + dims + legend + '</svg>';
- }
- /* ---------------- 保存 / 方案 ---------------- */
- function save(quiet) {
- try {
- localStorage.setItem(KEY, JSON.stringify(state));
- if (!quiet) {
- const el = $('#bxSaveState');
- }
- } catch (e) {
- UI.message.warning('本地保存空间不足');
- }
- }
- function plansList() {
- try { return JSON.parse(localStorage.getItem(LIST_KEY) || '[]'); } catch (e) { return []; }
- }
- function savePlanToLibrary() {
- const list = plansList().filter(function (p) { return p.id !== state.planId; });
- list.unshift({ id: state.planId, name: state.name, time: Date.now(), boxNo: state.boxNo });
- try { localStorage.setItem(LIST_KEY, JSON.stringify(list.slice(0, 30))); } catch (e) {}
- }
- function planDataKey(id) { return 'pouchlab.box.plan.' + id; }
- function commit(pushHistory) {
- if (pushHistory !== false) pushUndo();
- save(true);
- savePlanToLibrary();
- try { localStorage.setItem(planDataKey(state.planId), JSON.stringify(state)); } catch (e) {}
- // 历史版本
- try {
- const hk = HIST_KEY + '.' + state.planId;
- const hist = JSON.parse(localStorage.getItem(hk) || '[]');
- hist.unshift({ time: Date.now(), snap: snapshot() });
- localStorage.setItem(hk, JSON.stringify(hist.slice(0, 20)));
- } catch (e) {}
- renderAll();
- }
- /* ---------------- 3D 实例 ---------------- */
- let main3d = null, mini3d = null;
- let foldValue = 0, foldAnim = null;
- function currentPanels() { return dieline().panels; }
- function render3d() {
- if (main3d && main3d.ready()) {
- main3d.render(state, material(), currentPanels());
- main3d.setFold(foldValue / 100);
- return;
- }
- render3dCss();
- }
- /* CSS 3D 降级(无 Three.js 时) */
- function render3dCss() {
- const box = document.getElementById('box3d');
- if (!box) return;
- const t = material().thickness;
- const W = state.w + t * 2, D2 = state.d + t * 2, H = state.h + t * 2;
- const s = Math.min(360 / (state.w + state.d), 400 / (state.h + state.d));
- box.style.width = W * s + 'px';
- box.style.height = H * s + 'px';
- box.style.transform = 'rotateX(-18deg) rotateY(-32deg)';
- let html = '';
- const t2 = material().thickness;
- const faceT = {
- front: 'translateZ(' + D2 * s / 2 + 'px)',
- back: 'rotateY(180deg) translateZ(' + D2 * s / 2 + 'px)',
- right: 'rotateY(90deg) translateZ(' + W * s / 2 + 'px)',
- left: 'rotateY(-90deg) translateZ(' + W * s / 2 + 'px)',
- top: 'rotateX(90deg) translateZ(' + H * s / 2 + 'px)',
- bottom: 'rotateX(-90deg) translateZ(' + H * s / 2 + 'px)'
- };
- FACES.forEach(function (f) {
- const data = curFaces()[f.id];
- const size = (f.id === 'front' || f.id === 'back') ? { w: W, h: H } : (f.id === 'left' || f.id === 'right') ? { w: D2, h: H } : { w: W, h: D2 };
- const bg = 'background-color:' + (data.color || material().paper);
- html += '<div class="bface" data-face="' + f.id + '" style="width:' + size.w * s + 'px;height:' + size.h * s + 'px;margin-left:' + -size.w * s / 2 + 'px;margin-top:' + -size.h * s / 2 + 'px;' + bg + ';transform:' + faceT[f.id] + '"></div>';
- });
- box.innerHTML = html;
- }
- function renderMini() {
- if (mini3d && mini3d.ready() && state.mode === '2d') {
- mini3d.render(state, material(), currentPanels());
- mini3d.setFold(foldValue / 100);
- }
- }
- /* ---------------- 视图切换 ---------------- */
- function setMode(mode) {
- state.mode = mode;
- document.querySelectorAll('#bxModeSwitch button').forEach(function (b) {
- b.classList.toggle('on', b.dataset.mode === mode);
- });
- $('#bxFlat').hidden = mode !== '2d';
- $('#bx3dView').hidden = mode !== '3d';
- renderAll();
- }
- /* ---------------- 2D 画布 ---------------- */
- let panMode = false;
- let panDrag = null;
- function renderDieline() {
- const wrap = document.getElementById('boxDieline');
- if (!wrap) return;
- wrap.innerHTML = dielineSVG();
- const svg = wrap.querySelector('svg');
- if (!svg) return;
- const vb = svg.viewBox.baseVal;
- svg.style.width = vb.width + 'px';
- svg.style.height = vb.height + 'px';
- svg.style.display = 'block';
- const z = state.view2d.zoom;
- wrap.style.transform = 'translate(' + state.view2d.panX + 'px,' + state.view2d.panY + 'px) scale(' + z + ')';
- $('#bxZoom2dLabel').textContent = Math.round(z * 100) + ' %';
- }
- function fit2d() {
- const stage = $('#bxFlat');
- const dl = dieline();
- // 窄屏下左右面板改为悬浮覆盖,需按可视区(扣除面板遮挡)居中,避免刀版被面板盖住
- const stageRect = stage.getBoundingClientRect();
- let occlL = 0, occlR = 0;
- const panelEl = document.querySelector('.bx-panel');
- const propsEl = document.querySelector('.bx-props');
- if (panelEl && getComputedStyle(panelEl).position === 'absolute') {
- occlL = Math.max(0, Math.min(stage.clientWidth, panelEl.getBoundingClientRect().right - stageRect.left));
- }
- if (propsEl && getComputedStyle(propsEl).position === 'absolute') {
- occlR = Math.max(0, Math.min(stage.clientWidth - occlL, stageRect.right - propsEl.getBoundingClientRect().left));
- }
- const availW = Math.max(160, stage.clientWidth - occlL - occlR - 80);
- const availH = Math.max(200, stage.clientHeight - 120);
- state.view2d.zoom = clamp(Math.min(availW / dl.size.w, availH / dl.size.h), 0.1, 2.4);
- state.view2d.panX = Math.round((occlL - occlR) / 2);
- state.view2d.panY = 0;
- renderDieline();
- }
- /* ---------------- 工具栏 / 面板 ---------------- */
- let currentTab = 'box';
- function assetThumb(a, color) {
- if (a.svgDef) return '<svg viewBox="0 0 24 24" fill="none">' + a.svgDef.replace(/currentColor/g, color) + '</svg>';
- if (a.draw) return '<img src="' + LB.shapeDataUrl(a.draw, color, 120) + '" alt="">';
- return '';
- }
- function assetFillSrc(item, color) {
- if (item.draw) return LB.shapeDataUrl(item.draw, color, 160);
- if (item.svgDef) return 'data:image/svg+xml;utf8,' + encodeURIComponent('<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">' + item.svgDef.replace(/currentColor/g, color) + '</svg>');
- const id = String(item.assetId || '').replace(/^icon:/, '');
- const svg = id ? LB.assetSvg(id, color) : null;
- return svg ? 'data:image/svg+xml;utf8,' + encodeURIComponent(svg) : null;
- }
- function addAssetToFace(item) {
- const face = curFace();
- face.items = face.items || [];
- const it = Object.assign({ id: 'i' + Date.now().toString(36) + Math.random().toString(36).slice(2, 5), x: 50, y: 50, w: 45 }, item);
- face.items.push(it);
- state.selectedItemId = it.id;
- UI.message.success('素材已添加到「' + faceName(state.selectedFace) + '」');
- commit();
- }
- function panelBox() {
- const tab = currentTab;
- if (tab === 'box') return boxPanel();
- if (tab === 'template') return templatePanel();
- if (tab === 'asset') return assetPanel();
- if (tab === 'text') return textPanel();
- if (tab === 'tool') return toolPanel();
- if (tab === 'upload') return uploadPanel();
- if (tab === 'layers') return layersPanel();
- if (tab === 'help') return helpPanel();
- return null;
- }
- /* ---- 盒型面板 ---- */
- let boxSearch = '', boxCat = '热门', boxMine = false;
- function boxPanel() {
- const cats = LB.BOX_CATS;
- const list = LB.BOXLIB.filter(function (b) {
- if (boxMine) return true;
- if (boxSearch && b.name.indexOf(boxSearch) < 0 && b.no.indexOf(boxSearch) < 0) return false;
- if (boxCat === '热门') return b.hot >= 3;
- if (boxCat === '更多') return ['纸箱'].indexOf(b.cat) >= 0;
- return b.cat === boxCat;
- });
- return h('div', null,
- h('div', { className: 'bx-import-cad', onClick: function () { showImportCad(); } },
- h('span', { className: 'cad-ic' }, 'DXF'),
- h('div', null, h('b', null, '导入 CAD', h('i', { className: 'q', title: '上传盒型结构个性化设计' })), h('span', null, '上传盒型结构个性化设计'))
- ),
- h(A.Input, {
- prefix: h('span', { className: 'anticon' }, '🔍'),
- placeholder: '输入盒型关键字', value: boxSearch, allowClear: true,
- onChange: function (e) { boxSearch = e.target.value; renderTool(); }
- }),
- h('div', { className: 'bx-sub-tabs' },
- h('button', { className: boxMine ? '' : 'on', onClick: function () { boxMine = false; renderTool(); } }, '推荐盒型'),
- h('button', { className: boxMine ? 'on' : '', onClick: function () { boxMine = true; renderTool(); } }, '我的盒型')
- ),
- boxMine
- ? h('div', { className: 'p-hint', style: { padding: '18px 0' } }, '我的盒型(导入的 CAD 结构会保存在这里)' + (plansList().length ? '' : ' · 暂无'))
- : h('div', { className: 'bx-chips' }, cats.map(function (c) {
- return h('button', { key: c, className: boxCat === c ? 'on' : '', onClick: function () { boxCat = c; renderTool(); } }, c);
- })),
- !boxMine && h('div', { className: 'bx-box-grid' }, list.map(function (b) {
- return h('button', {
- key: b.no, className: 'bx-box-card' + (state.boxNo === b.no ? ' on' : ''),
- title: b.name,
- onClick: function () { applyLibBox(b); }
- },
- h('span', { className: 'thumb', dangerouslySetInnerHTML: { __html: structThumbSvg(b.gen, b.no) } }),
- h('span', { className: 'meta' },
- h('b', null, b.name),
- h('span', { className: 'no' }, b.no)
- ),
- b.sizes
- ? h('span', { className: 'flag sizes' }, b.sizes.length + '种固定尺寸')
- : h('span', { className: 'flag' }, '可改尺寸'),
- b.printable ? null : h('span', { className: 'flag off' }, '不可印刷')
- );
- })),
- !boxMine && !list.length && h(A.Empty, { description: '找不到盒型' })
- );
- }
- function structThumbSvg(gen, no) {
- const keep = { w: state.w, d: state.d, h: state.h, boxNo: state.boxNo, structure: state.structure };
- const preview = no === '260030' ? [90, 54] : no === '260040' ? [80, 80] : no === '261010' ? [50, 90] : no === '261002' ? [60, 95] : no === '270010' ? [60, 40] : no === '270020' ? [50, 50] : null;
- const keepMat = state.material;
- state.material = 'card';
- let dl;
- try {
- if (preview) {
- state.boxNo = no; state.structure = 'card';
- dl = buildDieline('card', preview[0], preview[1], preview[1]);
- } else {
- state.structure = gen;
- dl = buildDieline(gen, 60, 40, 90);
- }
- } catch (e) { dl = null; }
- state.boxNo = keep.boxNo; state.structure = keep.structure; state.material = keepMat;
- if (!dl) return '';
- const pad = 4;
- let body = '';
- dl.panels.forEach(function (p) {
- const b = panelBounds(p);
- const pts = p.poly ? p.poly : [[b.x, b.y], [b.x + b.w, b.y], [b.x + b.w, b.y + b.h], [b.x, b.y + b.h]];
- body += '<polygon points="' + pts.map(function (pt) { return (pt[0] - dl.minX + pad) + ',' + (pt[1] - dl.minY + pad); }).join(' ') + '" fill="#f7f4ec" stroke="#8a8478" stroke-width="0.8"/>';
- });
- dl.folds.forEach(function (f) {
- body += '<line x1="' + (f.x1 - dl.minX + pad) + '" y1="' + (f.y1 - dl.minY + pad) + '" x2="' + (f.x2 - dl.minX + pad) + '" y2="' + (f.y2 - dl.minY + pad) + '" stroke="#9db4d8" stroke-width="0.6" stroke-dasharray="2 1.5"/>';
- });
- return '<svg viewBox="0 0 ' + (dl.size.w + pad * 2) + ' ' + (dl.size.h + pad * 2) + '" preserveAspectRatio="xMidYMid meet">' + body + '</svg>';
- }
- function applyLibBox(entry) {
- if (state.boxNo === entry.no) return;
- pushUndo();
- state.boxNo = entry.no;
- state.structure = entry.gen;
- if (entry.sizes && entry.sizes.length) {
- const s = entry.sizes[0];
- state.w = s[0];
- if (entry.gen === 'card') {
- // 卡牌尺寸为 [长, 高],无厚度维度
- state.h = s[1];
- } else {
- state.d = s[1];
- state.h = s[2] || state.h;
- }
- }
- commit();
- UI.message.success('已切换到「' + entry.name + '」');
- }
- /* ---- 模板面板 ---- */
- let tplSearch = '', tplCat = '热门';
- function templatePanel() {
- const list = LB.TEMPLATES.filter(function (t) {
- if (tplSearch && t.name.indexOf(tplSearch) < 0) return false;
- if (tplCat === '热门') return true;
- return t.cat === tplCat;
- });
- return h('div', null,
- h(A.Input, { placeholder: '输入模板关键字', value: tplSearch, allowClear: true, onChange: function (e) { tplSearch = e.target.value; renderTool(); } }),
- h('div', { className: 'bx-chips' }, LB.TEMPLATE_CATS.map(function (c) {
- return h('button', { key: c, className: tplCat === c ? 'on' : '', onClick: function () { tplCat = c; renderTool(); } }, c);
- })),
- h('div', { className: 'bx-tpl-grid' }, list.map(function (t) {
- return h('button', {
- key: t.id, className: 'bx-tpl-card',
- style: { background: t.color },
- onClick: function () { applyTemplate(t); }
- },
- h('b', { style: { color: /^#([0-9a-f]{6})$/i.test(t.color) && luminance(t.color) < 0.5 ? '#fff' : '#17140f' } }, t.texts[0].text),
- h('span', { className: 'nm', style: { color: luminance(t.color) < 0.5 ? 'rgba(255,255,255,.75)' : 'rgba(23,20,15,.6)' } }, t.name)
- );
- }))
- );
- }
- function luminance(hex) {
- const c = hex.replace('#', '');
- const r = parseInt(c.substr(0, 2), 16), g = parseInt(c.substr(2, 2), 16), b = parseInt(c.substr(4, 2), 16);
- return (0.299 * r + 0.587 * g + 0.114 * b) / 255;
- }
- function applyTemplate(t) {
- pushUndo();
- const face = curFaces()[t.face];
- if (!face) return;
- face.color = t.color;
- face.items = face.items || [];
- t.texts.forEach(function (tx) {
- face.items.push(Object.assign({ id: 'i' + Date.now().toString(36) + Math.random().toString(36).slice(2, 5), type: 'text', italic: false, lineHeight: 1.25 }, tx));
- });
- if (t.asset && LB.ICONS[t.asset.id]) {
- face.items.push({
- id: 'i' + Date.now().toString(36) + Math.random().toString(36).slice(2, 5),
- type: 'asset', assetId: t.asset.id, src: 'data:image/svg+xml;utf8,' + encodeURIComponent(LB.assetSvg(t.asset.id, '#c2451f')), color: '#c2451f', x: 50, y: 68, w: 26
- });
- }
- UI.message.success('模板「' + t.name + '」已套用到' + faceName(t.face));
- commit();
- }
- /* ---- 素材面板 ---- */
- let assetSearch = '', assetCat = '全部', assetTab = '分类';
- const favKey = 'pouchlab.box.favs';
- function favs() { try { return JSON.parse(localStorage.getItem(favKey) || '[]'); } catch (e) { return []; } }
- function assetPanel() {
- const favsList = favs();
- const shapeDefs = Object.keys(LB.SHAPES).map(function (k) { return Object.assign({ id: 'shape:' + k, cat: '形状' }, LB.SHAPES[k]); });
- const iconDefs = Object.keys(LB.ICONS).map(function (k) { return Object.assign({ id: 'icon:' + k, cat: '图标', svgDef: LB.ICONS[k].svg, name: LB.ICONS[k].name }, {}); });
- const extra = [
- { id: 'illu:gift', name: '礼盒插画', cat: '插画', svgDef: '<path d="M5 10h14v10H5z" fill="currentColor" opacity=".85"/><path d="M4 6.5h16V10H4zM12 3.2c1.8 0 3 1.4 3 3.3H9c0-1.9 1.2-3.3 3-3.3Z" fill="currentColor"/><path d="M12 6.5V20" stroke="#fff" stroke-width="1"/>' },
- { id: 'illu:cup', name: '咖啡杯插画', cat: '插画', svgDef: '<path d="M7 8h10l-1.2 12H8.2L7 8Z" fill="currentColor"/><path d="M17 9.5h2a2 2 0 0 1 0 4h-2.4" fill="none" stroke="currentColor" stroke-width="1.6"/><path d="M6 5.5h12" stroke="currentColor" stroke-width="1.6"/>' },
- { id: 'cutout:badge', name: '透明徽章', cat: '抠图', svgDef: '<circle cx="12" cy="12" r="8.6" fill="none" stroke="currentColor" stroke-width="1.4"/><circle cx="12" cy="12" r="5.4" fill="none" stroke="currentColor" stroke-width="1.1" stroke-dasharray="2 1.6"/>' },
- { id: 'cutout:arrow', name: '透明箭头', cat: '抠图', svgDef: '<path d="M12 3.5 19 12h-4.4V20H9.4v-8H5L12 3.5Z" fill="currentColor"/>' }
- ];
- const all = shapeDefs.concat(iconDefs, extra);
- const list = all.filter(function (a) {
- if (assetTab === '收藏') return favsList.indexOf(a.id) >= 0;
- if (assetTab === '已购') return false;
- if (assetSearch && a.name.indexOf(assetSearch) < 0) return false;
- if (assetCat === '全部') return true;
- return a.cat === assetCat;
- });
- return h('div', null,
- h(A.Input, { placeholder: '输入素材关键字', value: assetSearch, allowClear: true, onChange: function (e) { assetSearch = e.target.value; renderTool(); } }),
- h('div', { className: 'bx-sub-tabs' },
- ['分类', '收藏', '已购'].map(function (t) {
- return h('button', { key: t, className: assetTab === t ? 'on' : '', onClick: function () { assetTab = t; renderTool(); } }, t === '分类' ? '素材分类' : t);
- })
- ),
- assetTab === '分类' && h('div', { className: 'bx-chips' }, LB.ASSET_CATS.map(function (c) {
- return h('button', { key: c, className: assetCat === c ? 'on' : '', onClick: function () { assetCat = c; renderTool(); } }, c);
- })),
- h('div', { className: 'bx-asset-grid' }, list.map(function (a) {
- return h('div', { key: a.id, className: 'bx-asset-card', title: a.name },
- h('button', {
- className: 'thumb', onClick: function () { addAssetFromDef(a); }
- }, h('span', { dangerouslySetInnerHTML: { __html: assetThumb(a, '#17140f') } })),
- h('span', { className: 'nm' }, a.name),
- h('button', {
- className: 'fav' + (favsList.indexOf(a.id) >= 0 ? ' on' : ''),
- onClick: function () { toggleFav(a.id); }
- }, favsList.indexOf(a.id) >= 0 ? '★' : '☆')
- );
- })),
- !list.length && h(A.Empty, { description: assetTab === '已购' ? '暂无购买记录' : '没找到你想要的结果' }),
- h('div', { className: 'p-hint', style: { marginTop: '12px' } }, '素材点击即添加到当前选中的面,可于图层面板调整。')
- );
- }
- function toggleFav(id) {
- const list = favs();
- const i = list.indexOf(id);
- if (i >= 0) list.splice(i, 1); else list.push(id);
- localStorage.setItem(favKey, JSON.stringify(list));
- renderTool();
- }
- function addAssetFromDef(a) {
- let src;
- if (a.svgDef) src = 'data:image/svg+xml;utf8,' + encodeURIComponent('<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">' + a.svgDef.replace(/currentColor/g, '#17140f') + '</svg>');
- else src = LB.shapeDataUrl(a.draw, '#17140f', 160);
- addAssetToFace({ type: 'asset', assetId: a.id, name: a.name, src: src, color: '#17140f', svgDef: a.svgDef || null, draw: a.draw || null });
- }
- /* ---- 文字面板 ---- */
- function textPanel() {
- const basics = [
- { id: 'b1', label: '标准', style: { fontWeight: 600 }, size: 10, weight: 600 },
- { id: 'b2', label: '描边', style: { WebkitTextStroke: '1px #17140f', color: '#fff' }, size: 11, weight: 800 },
- { id: 'b3', label: '阴影', style: { textShadow: '2px 2px 0 rgba(23,20,15,.55)' }, size: 11, weight: 800 },
- { id: 'b4', label: '斜体', style: { fontStyle: 'italic' }, size: 10, weight: 500 },
- { id: 'b5', label: '衬线', style: { fontFamily: 'Georgia, serif' }, size: 11, weight: 700 },
- { id: 'b6', label: '圆润', style: { fontFamily: '"PingFang SC", sans-serif', fontWeight: 800, letterSpacing: '1px' }, size: 10, weight: 800 }
- ];
- const combos = [
- { name: '品牌 + 品类', texts: [{ text: '品牌名称', size: 11, weight: 800, y: 40 }, { text: 'PRODUCT NAME', size: 4, weight: 400, y: 52 }] },
- { name: '日期 + 系列', texts: [{ text: 'BAOXIAOHE', size: 8, weight: 800, y: 38 }, { text: '2026.10.24', size: 5, weight: 600, y: 48 }, { text: 'SERIES NO.01', size: 3.4, weight: 400, y: 56 }] },
- { name: '主标题 + 卖点', texts: [{ text: '大促特惠', size: 13, weight: 800, y: 40, color: '#c2451f' }, { text: '买二送一 · 限时', size: 4.5, weight: 400, y: 52 }] },
- { name: '竖排签名', texts: [{ text: '袋研\n社制', size: 9, weight: 700, y: 42, lineHeight: 1.1 }] }
- ];
- return h('div', null,
- h('button', { className: 'bx-primary-btn', onClick: addBasicText }, '点击添加文字'),
- h('div', { className: 'bx-sec-title' }, '基础文字'),
- h('div', { className: 'bx-basic-texts' }, basics.map(function (b) {
- return h('button', { key: b.id, className: 'bx-basic-text', style: b.style, onClick: function () { addTextPreset({ text: '输入文字', size: b.size, weight: b.weight, italic: b.id === 'b4' }); } }, '输入文字');
- })),
- h('div', { className: 'bx-sec-title' }, '文字组合'),
- h('div', { className: 'bx-combo-grid' }, combos.map(function (c) {
- return h('button', { key: c.name, className: 'bx-combo-card', onClick: function () {
- pushUndo();
- const face = curFace();
- c.texts.forEach(function (tx) {
- face.items.push(Object.assign({ id: 'i' + Date.now().toString(36) + Math.random().toString(36).slice(2, 5), type: 'text', x: 50, color: '#17140f', align: 'center', italic: false, lineHeight: 1.25 }, tx));
- });
- commit();
- UI.message.success('文字组合已添加');
- } },
- h('b', null, c.texts[0].text),
- h('span', null, c.texts.slice(1).map(function (t) { return t.text; }).join(' · ')),
- h('em', null, c.name)
- );
- }))
- );
- }
- /* ---------------- AI 面排版(登录后可用) ---------------- */
- function aiFaceModal() {
- if (window.PL.auth && !PL.auth.user()) {
- PL.auth.require(function () { aiFaceModal(); });
- return;
- }
- if (!window.PL || !PL.api) { UI.message.info('AI 需要联网登录后使用'); return; }
- const faceName = { front: '正面', back: '背面', left: '左面', right: '右面', top: '顶面', bottom: '底面' }[state.selectedFace] || state.selectedFace;
- const div = document.createElement('div');
- $('#bxModals').appendChild(div);
- let brief = '';
- let busy = false;
- let full = false; // 整套 6 面设计
- function renderModal(msg, left) {
- UI.render(div, h(A.Modal, { open: true, width: 460, footer: null,
- title: '✨ AI 排版 · ' + (full ? '整套 6 面' : faceName + '(' + (state.side === 'outer' ? '外' : '内') + '侧)'),
- onCancel: function () { UI.reset(div); div.remove(); } },
- h(A.Segmented, {
- block: true, value: full ? 'full' : 'one',
- options: [{ value: 'one', label: '仅当前面(' + faceName + ')' }, { value: 'full', label: '整套 6 面' }],
- onChange: function (v) { full = v === 'full'; renderModal(); }
- }),
- h('p', { style: { fontSize: 12, color: '#7d7466', margin: '10px 0 8px' } },
- '描述这个面的排版需求;生成后再说"文字再大点/换个位置"可继续调整。' + (left != null ? ' 剩余 ' + left + ' 次' : '')),
- h(A.Input.TextArea, {
- rows: 3, placeholder: '如:极简茶叶礼盒,居中大字品牌名,下方一行英文,底部小字净含量',
- onChange: function (e) { brief = e.target.value; }
- }),
- msg ? h('p', { style: { fontSize: 12, color: msg.ok ? '#4f9d69' : '#e64718', margin: '8px 0 0' } }, msg.text) : null,
- h('div', { style: { display: 'flex', gap: 8, marginTop: 10, justifyContent: 'flex-end' } },
- h(A.Popconfirm, {
- title: '清空本面', description: '将清除' + faceName + '的全部文字与图形(含背景色),可撤销',
- onConfirm: function () {
- pushUndo();
- const f = curFace();
- f.items = [];
- f.color = '';
- commit(); renderAll();
- UI.reset(div); div.remove();
- UI.message.success(faceName + '已清空(可 ⌘Z 撤销)');
- }
- }, h(A.Button, { danger: true }, '清空本面')),
- h(A.Button, { onClick: function () { UI.reset(div); div.remove(); } }, '关闭'),
- h(A.Button, { type: 'primary', loading: busy, onClick: generate }, '生成并应用'))
- ));
- }
- function generate() {
- if (!brief.trim()) { renderModal({ ok: false, text: '请先描述需求' }); return; }
- if (busy) return;
- busy = true; renderModal({ ok: true, text: 'AI 正在设计中,通常 10~60 秒,请勿关闭弹窗…' });
- const face = curFace();
- const ctx = full
- ? { faces: FACES.reduce(function (acc, f) {
- const fd = state.faces[state.side][f.id] || {};
- acc[f.id] = { color: fd.color || '', items: (fd.items || []).filter(function (i) { return i.type === 'text'; }) };
- return acc;
- }, {}) }
- : (face && (face.items || []).length ? { color: face.color || '', items: face.items.filter(function (i) { return i.type === 'text'; }) } : null);
- PL.api.post('/ai/layout', {
- type: 'box', brief: brief,
- meta: full ? { full: true } : { face: state.selectedFace },
- context: ctx
- }, { timeout: 180000 }).then(function (r) {
- busy = false;
- if (full) {
- const faces = r.result.faces || {};
- const filled = Object.keys(faces).filter(function (k) { return (faces[k].items || []).length; });
- if (filled.length < 2) {
- renderModal({ ok: false, text: 'AI 这次没能生成有效成套设计(未扣次数),换个说法再试' });
- return;
- }
- pushUndo();
- FACES.forEach(function (f) {
- const fd = state.faces[state.side][f.id];
- const rd = faces[f.id];
- if (!fd || !rd) return;
- fd.color = rd.color || fd.color;
- fd.items = (rd.items || []).map(function (it) {
- it.id = 'i' + Date.now().toString(36) + Math.random().toString(36).slice(2, 5);
- it.lineHeight = 1.25;
- return it;
- });
- });
- commit(); renderAll();
- UI.reset(div); div.remove();
- UI.message.success('AI 已完成整套 6 面设计(剩余 ' + r.left + ' 次),可撤销');
- return;
- }
- if (!(r.result.items || []).length) {
- renderModal({ ok: false, text: 'AI 这次没能生成有效排版(未扣次数),换个说法再试' });
- return;
- }
- pushUndo();
- const f = curFace();
- f.color = r.result.color || f.color;
- f.items = (r.result.items || []).map(function (it) {
- it.id = 'i' + Date.now().toString(36) + Math.random().toString(36).slice(2, 5);
- it.lineHeight = 1.25;
- return it;
- });
- commit(); renderAll();
- UI.reset(div); div.remove();
- UI.message.success('AI 排版已应用到' + faceName + '(剩余 ' + r.left + ' 次),可撤销');
- }, function (err) {
- busy = false;
- if (err.status === 401) {
- UI.reset(div); div.remove();
- PL.auth.require(function () { aiFaceModal(); });
- return;
- }
- renderModal({ ok: false, text: err.message || 'AI 生成失败' });
- });
- }
- renderModal();
- }
- function addBasicText() { addTextPreset({ text: '输入文字', size: 10, weight: 600 }); }
- function addTextPreset(preset) {
- pushUndo();
- const face = curFace();
- const it = {
- id: 'i' + Date.now().toString(36) + Math.random().toString(36).slice(2, 5),
- type: 'text', text: preset.text || '输入文字',
- size: preset.size || 10, weight: preset.weight || 600, italic: !!preset.italic,
- color: '#17140f', align: 'center', lineHeight: preset.lineHeight || 1.25,
- x: 50, y: preset.y || 40
- };
- face.items = face.items || [];
- face.items.push(it);
- state.selectedItemId = it.id;
- commit();
- }
- /* ---- 工具面板(条码 + 二维码) ---- */
- function toolPanel() {
- return h('div', null,
- h('div', { className: 'bx-tool-card', onClick: addBarcode },
- h('span', { className: 'ic' }, ' II·II '),
- h('div', null, h('b', null, '条形码'), h('span', null, '快速生成一堆码支持4种码制'))
- ),
- h('div', { className: 'bx-tool-card', onClick: addQrcode },
- h('span', { className: 'ic qr' }, '▦'),
- h('div', null, h('b', null, '二维码'), h('span', null, '快速生成二维码设计使用'))
- )
- );
- }
- function barcodeSvg(kind, value) {
- if (kind === 'code128') {
- const TBL = ('212222 222122 222221 121223 121322 131222 122213 122312 132212 221213 221312 231212 112232 122132 122231 113222 123122 123221 223211 221132 221231 213212 223112 312131 311222 321122 321221 312212 322112 322211 212123 212321 232121 111323 131123 131321 112313 132113 132311 211313 231113 231311 112133 112331 132131 113123 113321 133121 313121 211331 231131 213113 213311 213131 311123 311321 331121 312113 312311 332111 314111 221411 431111 111224 111422 121124 121421 141122 141221 112214 112412 122114 122411 142112 142211 241211 221114 413111 241112 134111 111242 121142 121241 114212 124112 124211 411212 421112 421211 212141 214121 412121 111143 111341 131141 114113 114311 411113 411311 113141 114131 311141 411131 211412 211214 211232 2331112').split(' ');
- const text = String(value || 'POUCHLAB').replace(/[^\x20-\x7e]/g, '').slice(0, 20) || 'BOX';
- const codes = [104];
- for (let i = 0; i < text.length; i += 1) codes.push(text.charCodeAt(i) - 32);
- let sum = 104;
- for (let i = 1; i < codes.length; i += 1) sum += codes[i] * i;
- codes.push(sum % 103);
- codes.push(106);
- let bits = '';
- codes.forEach(function (c) { bits += TBL[c]; });
- let x = 0, rects = '';
- const unit = 2;
- for (let i = 0; i < bits.length; i += 1) {
- const wdt = Number(bits[i]) * unit;
- if (i % 2 === 0) rects += '<rect x="' + x + '" width="' + wdt + '" height="60" fill="#17140f"/>';
- x += wdt;
- }
- const totalW = x + 40;
- return 'data:image/svg+xml;utf8,' + encodeURIComponent('<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ' + totalW + ' 74"><rect width="' + totalW + '" height="74" fill="#fff"/>' + rects + '<text x="' + (totalW / 2) + '" y="72" text-anchor="middle" font-size="9" font-family="monospace" fill="#17140f">' + text + '</text></svg>');
- }
- // EAN-13 / EAN-8 / UPC-A 共用 PL.render.barcodeBits(EAN-13 逻辑,UPC-A 加 0 前缀)
- let val = String(value || '').replace(/\D/g, '');
- if (kind === 'ean8') val = val.slice(0, 7).padEnd(7, '0');
- else if (kind === 'upca') val = val.slice(0, 11).padEnd(11, '0');
- else val = val.slice(0, 12).padEnd(12, '0');
- const bars = R.barcodeBits(kind === 'upca' ? '0' + val : val);
- const label = kind === 'upca' ? '0' + bars.code : bars.code;
- const rects = [];
- let x = 0;
- const unit = 2;
- for (let i = 0; i < bars.bits.length; i += 1) {
- if (bars.bits[i] === '1') rects.push('<rect x="' + x + '" width="' + unit + '" height="56" fill="#17140f"/>');
- x += unit;
- }
- return 'data:image/svg+xml;utf8,' + encodeURIComponent('<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ' + (x + 6) + ' 72"><rect width="' + (x + 6) + '" height="72" fill="#fff"/>' + rects.join('') + '<text x="' + (x / 2) + '" y="69" text-anchor="middle" font-size="9" font-family="monospace" fill="#17140f">' + label + '</text></svg>');
- }
- function addBarcode() {
- let kind = 'ean13';
- const content = h('div', null,
- h('div', { className: 'p-field' },
- h('label', null, '码制'),
- h(A.Select, {
- defaultValue: 'ean13', style: { width: '100%' },
- onChange: function (v) { kind = v; },
- options: [
- { value: 'ean13', label: 'EAN-13 商品码' },
- { value: 'ean8', label: 'EAN-8 短码' },
- { value: 'upca', label: 'UPC-A' },
- { value: 'code128', label: 'Code128' }
- ]
- })
- ),
- h('div', { className: 'p-field' },
- h('label', null, '内容'),
- h(A.Input, { id: 'bxBarcodeValue', defaultValue: '6971234567890', placeholder: '条码内容' })
- )
- );
- modalConfirm('生成条形码', content, function () {
- const value = document.getElementById('bxBarcodeValue').value;
- const src = barcodeSvg(kind, value);
- addAssetToFace({ type: 'barcode', codeType: kind, value: value, src: src, w: 40 });
- });
- }
- function addQrcode() {
- const content = h('div', null,
- h('div', { className: 'p-field' },
- h('label', null, '二维码内容(网址或文字)'),
- h(A.Input, { id: 'bxQrValue', defaultValue: 'https://pouchlab.design', placeholder: '请输入内容' })
- )
- );
- modalConfirm('生成二维码', content, function () {
- const value = document.getElementById('bxQrValue').value || ' ';
- let src;
- try { src = QR.toDataURL(value, { scale: 6, margin: 1 }); }
- catch (e) { UI.message.error(e.message || '内容过长'); return; }
- addAssetToFace({ type: 'barcode', codeType: 'qrcode', value: value, src: src, w: 32 });
- });
- }
- /* ---- 上传面板 ---- */
- function storageUsed() {
- let total = 0;
- try {
- for (const k in localStorage) {
- if (Object.prototype.hasOwnProperty.call(localStorage, k) && k.indexOf('pouchlab') === 0) {
- total += (localStorage[k] || '').length * 2;
- }
- }
- } catch (e) {}
- return total;
- }
- function uploadPanel() {
- const used = storageUsed();
- const pct = Math.min(100, used / (100 * 1024 * 1024) * 100);
- const uploads = state.uploads || [];
- return h('div', null,
- h(A.Upload, {
- accept: 'image/*', showUploadList: false, customRequest: uploadToFace,
- children: h('button', { className: 'bx-primary-btn' }, '上传图片')
- }),
- h('div', { className: 'p-hint' }, '支持上传JPG/PNG/SVG等格式文件'),
- uploads.length ? h('div', { className: 'bx-upload-grid' }, uploads.map(function (u) {
- return h('div', { key: u.id, className: 'bx-upload-card' },
- h('button', {
- className: 'thumb', title: '添加到当前面',
- onClick: function () { addAssetToFace({ type: 'image', name: u.name, src: u.src, w: 70 }); }
- }, h('img', { src: u.src, alt: u.name })),
- h('span', { className: 'nm', title: u.name }, u.name),
- h('button', {
- className: 'del', title: '从上传记录中移除',
- onClick: function () {
- state.uploads = (state.uploads || []).filter(function (x) { return x.id !== u.id; });
- commit();
- }
- }, '✕')
- );
- })) : h('div', { className: 'bx-upload-empty' },
- h('div', { className: 'box-illus' }),
- h('span', null, '上传的稿件会放置到当前选中的面')
- ),
- h('div', { className: 'bx-capacity' },
- h('span', null, '个人已使用 ' + (used / 1024 / 1024).toFixed(1) + 'M/100M'),
- h('a', { onClick: function () { UI.message.info('演示环境:容量为本地浏览器存储模拟'); } }, '扩充容量')
- ),
- h('div', { className: 'bx-cap-bar' }, h('i', { style: { width: Math.max(1, pct) + '%' } }))
- );
- }
- function uploadToFace(options) {
- const file = options.file;
- if (!file || file.type.indexOf('image') !== 0) {
- UI.message.warning('请选择图片文件');
- return;
- }
- const reader = new FileReader();
- reader.onload = function () {
- const img = new Image();
- img.onload = function () {
- const max = 900;
- let w = img.width, hh = img.height;
- if (Math.max(w, hh) > max) {
- const k = max / Math.max(w, hh);
- w = Math.round(w * k); hh = Math.round(hh * k);
- }
- const canvas = document.createElement('canvas');
- canvas.width = w; canvas.height = hh;
- canvas.getContext('2d').drawImage(img, 0, 0, w, hh);
- const src = canvas.toDataURL(file.type === 'image/png' ? 'image/png' : 'image/jpeg', 0.84);
- // 保留上传记录,便于重复使用;最多保留 8 张,避免 localStorage 超限
- const up = { id: 'u' + Date.now().toString(36) + Math.random().toString(36).slice(2, 5), name: file.name, src: src, time: Date.now() };
- state.uploads = [up].concat(state.uploads || []).slice(0, 8);
- addAssetToFace({ type: 'image', name: file.name, src: src, w: 70 });
- if (currentTab === 'upload') renderTool();
- };
- img.src = reader.result;
- };
- reader.readAsDataURL(file);
- }
- /* ---- 图层面板 ---- */
- function layersPanel() {
- const face = curFace();
- const items = (face.items || []).slice().reverse();
- return h('div', null,
- h('div', { className: 'bx-layer-head' },
- h('div', { className: 'bx-sec-title' }, faceName(state.selectedFace) + ' · ' + items.length + ' 个图层'),
- items.length ? h('button', { className: 'bx-layer-clear', onClick: clearLayers }, '一键清空') : null
- ),
- items.length ? h('div', { className: 'bx-layer-list' }, items.map(function (it) {
- const typeNames = { text: '文字', image: '图片', asset: '素材', barcode: it.codeType === 'qrcode' ? '二维码' : '条形码' };
- return h('div', { key: it.id, className: 'bx-layer-row' + (state.selectedItemId === it.id ? ' on' : ''), 'data-layer-id': it.id },
- h('span', { className: 't', onClick: function () { state.selectedItemId = it.id; renderTool(); renderProps(); } },
- typeNames[it.type] || '元素', ' · ', it.type === 'text' ? String(it.text || '').split('\n')[0] : (it.name || '')),
- h('button', { title: it.hidden ? '显示' : '隐藏', onClick: function () { it.hidden = !it.hidden; commit(); } }, it.hidden ? '🚫' : '👁'),
- h('button', { title: '移到最顶层', onClick: function () { moveItem(it.id, 'top'); } }, '⤒'),
- h('button', { title: '上移一层', onClick: function () { moveItem(it.id, 1); } }, '↑'),
- h('button', { title: '下移一层', onClick: function () { moveItem(it.id, -1); } }, '↓'),
- h('button', { title: '移到最底层', onClick: function () { moveItem(it.id, 'bottom'); } }, '⤓'),
- h('button', { className: 'del', title: '删除', onClick: function () { removeItem(it.id); } }, '✕')
- );
- })) : h('div', { className: 'bx-layer-empty' },
- h('span', { className: 'stack' }), '图层为空'
- )
- );
- }
- function clearLayers() {
- const face = curFace();
- const count = (face.items || []).length;
- let total = 0;
- FACES.forEach(function (ff) { total += (curFaces()[ff.id].items || []).length; });
- if (!total) return;
- let close;
- close = mountModal(h(A.Modal, {
- title: '清空图层', open: true, footer: null, onCancel: function () { close(); }
- }, h('div', null,
- h('p', null, '当前面有 ' + count + ' 个图层,全部面共 ' + total + ' 个图层。'),
- h('div', { className: 'bx-clear-actions' },
- h('button', {
- className: 'bx-clear-opt', disabled: !count,
- onClick: function () {
- pushUndo();
- face.items = [];
- state.selectedItemId = null;
- commit();
- close();
- UI.message.success('已清空「' + faceName(state.selectedFace) + '」图层');
- }
- }, '清空当前面(' + count + ')'),
- h('button', {
- className: 'bx-clear-opt danger',
- onClick: function () {
- pushUndo();
- FACES.forEach(function (ff) { curFaces()[ff.id].items = []; });
- state.selectedItemId = null;
- commit();
- close();
- UI.message.success('已清空全部面图层');
- }
- }, '清空全部面(' + total + ')')
- ),
- h('div', { className: 'p-hint', style: { marginTop: '10px' } }, '清空后可通过 Ctrl+Z 撤销。')
- )));
- }
- function findItem(id) {
- const face = curFace();
- return (face.items || []).find(function (x) { return x.id === id; }) || null;
- }
- function removeItem(id) {
- pushUndo();
- const face = curFace();
- face.items = (face.items || []).filter(function (x) { return x.id !== id; });
- if (state.selectedItemId === id) state.selectedItemId = null;
- commit();
- }
- function moveItem(id, dir) {
- const face = curFace();
- const arr = face.items || [];
- const i = arr.findIndex(function (x) { return x.id === id; });
- if (i < 0) return;
- let j;
- if (dir === 'top') j = arr.length - 1;
- else if (dir === 'bottom') j = 0;
- else j = i + dir;
- if (j < 0 || j >= arr.length || j === i) return;
- pushUndo();
- const it = arr.splice(i, 1)[0];
- arr.splice(j, 0, it);
- commit();
- }
- /* 拖拽排序:把 fromId 移动到 toId 的上/下(above=true 为更高层) */
- function reorderLayer(fromId, toId, above) {
- if (!fromId || !toId || fromId === toId) return;
- const face = curFace();
- const arr = face.items || [];
- const rv = arr.slice().reverse();
- const si = rv.findIndex(function (x) { return x.id === fromId; });
- const ti = rv.findIndex(function (x) { return x.id === toId; });
- if (si < 0 || ti < 0) return;
- pushUndo();
- const it = rv.splice(si, 1)[0];
- let ins = ti > si ? ti - 1 : ti;
- if (!above) ins += 1;
- rv.splice(ins, 0, it);
- face.items = rv.reverse();
- commit();
- }
- /* ---- 帮助面板 ---- */
- function helpPanel() {
- return h('div', null,
- h('div', { className: 'bx-tool-card', onClick: function () { UI.message.info('演示环境:可发送邮件至 support@pouchlab.design'); } },
- h('span', { className: 'ic' }, '☎'), h('div', null, h('b', null, '咨询客服'), h('span', null, '工作日 9:00-18:00'))
- ),
- h('div', { className: 'bx-tool-card', onClick: showQuickStart },
- h('span', { className: 'ic' }, '📖'), h('div', null, h('b', null, '快速上手'), h('span', null, '3 步完成盒子设计'))
- ),
- h('div', { className: 'bx-tool-card', onClick: showShortcuts },
- h('span', { className: 'ic' }, '⌨'), h('div', null, h('b', null, '快捷键'), h('span', null, '常用操作快捷键列表'))
- )
- );
- }
- function showQuickStart() {
- modalInfo('快速上手', h('div', { className: 'bx-help-steps' },
- h('p', null, '1. 在「盒型」面板选择盒型与尺寸,或点「编辑」打开智能参数宝精确调参;'),
- h('p', null, '2. 在 2D 设计里点选面,用「文字 / 素材 / 上传」添加内容,右侧换颜色与纹理;'),
- h('p', null, '3. 切到「3D预览」拖拽查看,播放动效,最后「导出」或「印刷下单」。')
- ));
- }
- function showShortcuts() {
- modalInfo('快捷键', h('div', { className: 'bx-help-steps' },
- h('p', null, 'Ctrl/⌘ + Z 撤销'), h('p', null, 'Ctrl/⌘ + Shift + Z 重做'),
- h('p', null, 'Ctrl/⌘ + S 保存'), h('p', null, 'Delete 删除选中元素'),
- h('p', null, 'Tab 切换外侧 / 内侧'), h('p', null, '空格拖拽 平移画布')
- ));
- }
- /* ---------------- 右侧属性面板 ---------------- */
- function propsPanel() {
- if (state.mode === '3d') return animsPanel();
- const face = curFace();
- const item = state.selectedItemId ? findItem(state.selectedItemId) : null;
- const out = outerSize();
- const dl = dieline();
- const children = [];
- // 迷你 3D 挂载于右侧面板顶部(2D 模式显示)
- children.push(h('div', { className: 'bx-props-sec' },
- h('div', { className: 'bx-props-head-row' },
- h('b', null, '尺寸/材质', h('i', { className: 'q', title: '内尺寸为盒体内部净尺寸' }))),
- h('button', { className: 'bx-edit-btn', onClick: openSmartParams }, '编辑'),
- h('div', { className: 'bx-kv' }, h('span', null, '内尺寸(mm)'), h('b', null, 'L:' + state.w + ' W:' + state.d + ' H:' + state.h)),
- h('div', { className: 'bx-kv' }, h('span', null, '材质'), h('b', null, material().name)),
- h('div', { className: 'bx-kv' }, h('span', null, '厚度'), h('b', null, material().thickness + 'mm'))
- ));
- children.push(h('div', { className: 'bx-props-sec' },
- h('div', { className: 'bx-props-head-row' }, h('b', null, '颜色 / 背景')),
- h('div', { className: 'bx-color-tabs' },
- h('button', { className: colorTab === 'color' ? 'on' : '', onClick: function () { colorTab = 'color'; renderProps(); } }, '颜色'),
- h('button', { className: colorTab === 'texture' ? 'on' : '', onClick: function () { colorTab = 'texture'; renderProps(); } }, '纹理')
- ),
- colorTab === 'color' ? h('div', null,
- h('div', { className: 'bx-swatch-grid' },
- h('label', { className: 'bx-swatch picker', title: '自定义颜色' },
- h('input', { type: 'color', value: face.color || '#fbf7ee', onInput: function (e) { setFaceColor(e.target.value); } }),
- h('span', { className: 'grad' })
- ),
- h('button', { className: 'bx-swatch', title: '清空颜色', onClick: function () { setFaceColor(''); } }, h('i', { className: 'none' })),
- LB.FACE_COLORS.map(function (c) {
- return h('button', { key: c, className: 'bx-swatch' + (face.color === c ? ' on' : ''), style: { background: c }, onClick: function () { setFaceColor(c); } });
- })
- ),
- h('div', { className: 'bx-pms-title' }, '参考潘通色'),
- h('div', { className: 'bx-pms-grid' }, (window.PL.pantone ? window.PL.pantone.list : []).map(function (c) {
- return h('button', {
- key: c.code,
- className: 'bx-pms-dot' + (face.color && face.color.toLowerCase() === c.hex.toLowerCase() ? ' on' : ''),
- title: '参考潘通色 ' + c.code + ' ' + c.name,
- style: { background: c.hex },
- onClick: function () { setFaceColor(c.hex); }
- });
- })),
- h('div', { className: 'bx-pms-note' }, window.PL.pantone ? window.PL.pantone.note : '')
- ) : h('div', { className: 'bx-tex-grid' },
- h('button', { className: 'bx-tex clear', onClick: function () { setFaceTexture(null); } }, h('i', { className: 'none' }), h('span', null, '清空纹理')),
- LB.TEXTURES.map(function (t) {
- return h('button', {
- key: t.id, className: 'bx-tex' + (face.textureId === t.id ? ' on' : ''),
- onClick: function () { setFaceTexture(t.id); }
- }, h('img', { src: LB.textureDataUrl(t.id), alt: t.name }), h('span', null, t.name));
- })
- )
- ));
- children.push(h('div', { className: 'bx-props-sec' },
- h('div', { className: 'bx-props-head-row' }, h('b', null, '画布'),
- h('span', { className: 'dim' }, '展开 ' + Math.round(dl.size.w) + ' × ' + Math.round(dl.size.h) + ' mm')),
- h('div', { className: 'bx-kv' }, h('span', null, '外侧尺寸'), h('b', null, Math.round(out.w) + ' × ' + Math.round(out.d) + ' × ' + Math.round(out.h) + ' mm')),
- h('div', { className: 'bx-kv' }, h('span', null, '当前设计'), h('b', null, state.side === 'outer' ? '外侧' : '内侧')),
- h('div', { className: 'bx-kv' }, h('span', null, '元素'), h('b', null, ((face.items || []).length) + ' 个'))
- ));
- if (item) children.push(itemPropsPanel(item));
- return h('div', null, children);
- }
- let colorTab = 'color';
- function itemPropsPanel(item) {
- const typeNames = { text: '文字属性', image: '图片属性', asset: '素材属性', barcode: item.codeType === 'qrcode' ? '二维码属性' : '条形码属性' };
- const rows = [];
- rows.push(h('div', { className: 'bx-props-sec' },
- h('div', { className: 'bx-props-head-row' }, h('b', null, typeNames[item.type] || '元素属性'),
- h('button', { onClick: function () { state.selectedItemId = null; renderProps(); } }, '完成选择'))
- ));
- if (item.type === 'text') {
- rows.push(h('div', { className: 'bx-props-sec' },
- h(BoxTextField, {
- value: item.text, placeholder: '文字内容',
- onInput: function (v) { item.text = v; save(true); renderDieline(); render3d(); renderMini(); },
- onCommit: function () { commit(); }
- }),
- h('div', { className: 'bx-row2' },
- h('div', { className: 'p-field' }, h('label', null, '字号 (mm)'), h(A.InputNumber, { value: item.size, min: 2, max: 120, style: { width: '100%' }, onChange: function (v) { if (v) { item.size = v; commit(); } } })),
- h('div', { className: 'p-field' }, h('label', null, '颜色'), h(A.ColorPicker, {
- key: 'tc-' + item.id,
- defaultValue: item.color || '#17140f',
- showText: true,
- onChange: function (c) { item.color = c.toHexString(); save(true); renderDieline(); render3d(); renderMini(); },
- onChangeComplete: function (c) { item.color = c.toHexString(); commit(); }
- }))
- ),
- h('div', { className: 'bx-row2' },
- h('div', { className: 'p-field' }, h('label', null, '对齐'), h(A.Segmented, { value: item.align || 'center', block: true, options: [{ label: '左', value: 'left' }, { label: '中', value: 'center' }, { label: '右', value: 'right' }], onChange: function (v) { item.align = v; commit(); } })),
- h('div', { className: 'p-field' }, h('label', null, '字重'), h(A.Segmented, { value: String(item.weight || 400), block: true, options: [{ label: '常规', value: '400' }, { label: '中', value: '600' }, { label: '粗', value: '800' }], onChange: function (v) { item.weight = Number(v); commit(); } }))
- ),
- h('div', { className: 'p-field', style: { marginTop: '6px' } },
- h('label', null, '样式'),
- h('div', { className: 'bx-row2' },
- h(A.Checkbox, { checked: !!item.italic, onChange: function (e) { item.italic = e.target.checked; commit(); } }, '斜体'),
- h(A.Checkbox, { checked: !!item.hidden, onChange: function (e) { item.hidden = e.target.checked; commit(); } }, '隐藏')
- )
- )
- ));
- } else {
- const colorable = item.type === 'asset' && !!assetFillSrc(item, '#17140f');
- rows.push(h('div', { className: 'bx-props-sec' },
- h('img', { className: 'bx-item-preview', src: item.src, alt: '' }),
- colorable && h('div', { className: 'p-field' }, h('label', null, '颜色'), h(A.ColorPicker, {
- key: 'ac-' + item.id,
- defaultValue: item.color || '#17140f',
- showText: true,
- onChange: function (c) {
- const hex = c.toHexString();
- const next = assetFillSrc(item, hex);
- if (!next) return;
- item.color = hex;
- item.src = next;
- save(true); renderDieline(); render3d(); renderMini();
- },
- onChangeComplete: function (c) {
- const hex = c.toHexString();
- const next = assetFillSrc(item, hex);
- if (!next) return;
- item.color = hex;
- item.src = next;
- commit();
- }
- })),
- h('div', { className: 'p-field' }, h('label', null, '宽度 ' + (item.w == null ? 60 : item.w) + '%'), h(A.Slider, { value: item.w == null ? 60 : item.w, min: 8, max: 100, onChange: function (v) { item.w = v; renderDieline(); render3d(); renderMini(); }, onAfterChange: function () { commit(); } }))
- ));
- }
- rows.push(h('div', { className: 'bx-row2', style: { marginBottom: '12px' } },
- h('div', { className: 'p-field' }, h('label', null, '水平 ' + item.x + '%'), h(A.Slider, { value: item.x, min: 0, max: 100, onChange: function (v) { item.x = v; renderDieline(); render3d(); renderMini(); }, onAfterChange: function () { commit(); } })),
- h('div', { className: 'p-field' }, h('label', null, '垂直 ' + item.y + '%'), h(A.Slider, { value: item.y, min: 0, max: 100, onChange: function (v) { item.y = v; renderDieline(); render3d(); renderMini(); }, onAfterChange: function () { commit(); } }))
- ));
- rows.push(h('div', { className: 'bx-props-sec' },
- h('div', { className: 'bx-props-head-row' }, h('b', null, '图层顺序')),
- h('div', { className: 'bx-order-grid' },
- h('button', { className: 'bx-ghost-btn', onClick: function () { moveItem(item.id, 'top'); } }, '⤒ 置顶'),
- h('button', { className: 'bx-ghost-btn', onClick: function () { moveItem(item.id, 1); } }, '↑ 上移'),
- h('button', { className: 'bx-ghost-btn', onClick: function () { moveItem(item.id, -1); } }, '↓ 下移'),
- h('button', { className: 'bx-ghost-btn', onClick: function () { moveItem(item.id, 'bottom'); } }, '⤓ 置底')
- )
- ));
- return h('div', null, rows);
- }
- function setFaceColor(c) {
- pushUndo();
- curFace().color = c;
- commit();
- }
- function setFaceTexture(id) {
- pushUndo();
- const face = curFace();
- if (id) {
- face.textureId = id;
- face.texture = LB.textureDataUrl(id);
- } else {
- face.textureId = null;
- face.texture = null;
- }
- commit();
- }
- /* 3D 模式右侧:动效面板 */
- function animsPanel() {
- return h('div', null,
- h('div', { className: 'bx-props-sec' },
- h('div', { className: 'bx-props-head-row' }, h('b', null, '动效'), h('span', { className: 'dim' }, '点击预览'))
- ),
- h('div', { className: 'bx-anim-list' }, LB.ANIMS.map(function (a) {
- const playing = main3d && main3d.ready() && main3d.animating() && playingAnimId === a.id;
- return h('div', { key: a.id, className: 'bx-anim-card' + (playing ? ' on' : '') },
- h('button', {
- className: 'bx-anim-play',
- onClick: function () { playAnim(a); }
- },
- h('span', { className: 'dur' }, a.dur + 's'),
- h('span', { className: 'anim-illus ' + a.id })
- ),
- h('div', { className: 'bx-anim-meta' },
- h('b', null, a.name),
- h('button', { onClick: function () { playAnim(a); } }, playing ? '停止' + a.dur + 's' : (a.id === 'fromLeft' ? '预览' : '停止' + a.dur + 's'))
- )
- );
- })),
- h('div', { className: 'bx-props-sec' },
- h('div', { className: 'bx-props-head-row' }, h('b', null, '视角')),
- h('div', { className: 'bx-row2' },
- h('button', { className: 'bx-ghost-btn', onClick: function () { if (main3d) main3d.resetView(); } }, '重置视角'),
- h('button', { className: 'bx-ghost-btn', onClick: function () { const t = !state.autoRotate; state.autoRotate = t; if (main3d) main3d.setAutoRotate(t); } }, '自动旋转')
- )
- )
- );
- }
- let playingAnimId = null;
- function playAnim(a) {
- if (!main3d || !main3d.ready()) return;
- if (playingAnimId === a.id && main3d.animating()) {
- main3d.stopAnim();
- playingAnimId = null;
- renderProps();
- return;
- }
- stopFoldAnim();
- playingAnimId = a.id;
- main3d.playAnim(a.id, a.dur, function () {
- playingAnimId = null;
- renderProps();
- });
- renderProps();
- }
- /* ---------------- 弹窗基建 ---------------- */
- function mountModal(node) {
- const div = document.createElement('div');
- $('#bxModals').appendChild(div);
- let closed = false;
- const close = function () {
- if (closed) return;
- closed = true;
- try { UI.reset(div); } catch (e) {}
- if (div.parentNode) div.parentNode.removeChild(div);
- };
- UI.render(div, node);
- return close;
- }
- function modalConfirm(title, content, onOk, okText, width) {
- let close;
- close = mountModal(h(A.Modal, {
- title: title, open: true, onCancel: function () { close(); },
- width: width || undefined,
- okText: okText || '确认调整',
- onOk: function () { if (onOk) onOk(); close(); },
- okButtonProps: { style: { background: '#ff6a00', borderColor: '#ff6a00' } }
- }, content));
- return close;
- }
- function modalInfo(title, content) {
- let close;
- close = mountModal(h(A.Modal, {
- title: title, open: true, onCancel: function () { close(); },
- footer: h(A.Button, { type: 'primary', onClick: function () { close(); }, style: { background: '#ff6a00', borderColor: '#ff6a00' } }, '我知道了')
- }, content));
- return close;
- }
- /* ---------------- 智能参数宝 ---------------- */
- function openSmartParams() {
- const params = Object.assign({ _labels: true }, state.smart);
- const dims = { w: state.w, d: state.d, h: state.h };
- let baseSize = '内尺寸', outSize = '内尺寸';
- const adv = struct().advanced || [];
- const advRows = adv.map(function (key) {
- const f = ADV_FIELDS[key];
- if (!f) return null;
- return h('div', { className: 'sp-row', key: key },
- h('label', { title: f.name }, f.name + ' (' + f.code + ')'),
- h(A.InputNumber, {
- value: params[key], min: f.min, max: f.max, step: f.step || 1,
- onChange: function (v) { if (v != null) params[key] = v; renderSmart(); }
- }),
- h('span', { className: 'unit' }, f.unit)
- );
- });
- const content = h('div', { className: 'sp-wrap' },
- h('div', { className: 'sp-left' }, h('div', { id: 'spDieline', className: 'sp-dieline' })),
- h('div', { className: 'sp-right' },
- h('div', { className: 'sp-row' },
- h('label', null, '标注方式'),
- h(A.Select, { defaultValue: '数值', style: { flex: 1 }, options: [{ value: '数值' }, { value: '无标注' }], onChange: function (v) { params._labels = v === '数值'; renderSmart(); } })
- ),
- h('div', { className: 'sp-group-title' }, '基础参数'),
- h('div', { className: 'sp-row' },
- h('label', { title: '以内尺寸或外尺寸为基准调整' }, '基准尺寸'),
- h(A.Select, { defaultValue: '内尺寸', style: { flex: 1 }, options: [{ value: '内尺寸' }, { value: '外尺寸' }], onChange: function (v) { baseSize = v; } })
- ),
- h('div', { className: 'sp-row' },
- h('label', { title: '输出制造尺寸口径' }, '输出尺寸'),
- h(A.Select, { defaultValue: '内尺寸', style: { flex: 1 }, options: [{ value: '内尺寸' }, { value: '外尺寸' }], onChange: function (v) { outSize = v; } })
- ),
- ['w', 'd', 'h'].map(function (k, i) {
- return h('div', { className: 'sp-row', key: k },
- h('label', null, ['长 (L)', '宽 (W)', '高 (H)'][i]),
- h(A.InputNumber, { value: dims[k], min: 10, max: 2000, style: { flex: 1 }, onChange: function (v) { if (v) dims[k] = v; renderSmart(); } }),
- h('span', { className: 'unit' }, 'mm')
- );
- }),
- h('div', { className: 'sp-row' },
- h('label', null, '出血线 (BL)'),
- h(A.InputNumber, { value: params.bleed, min: 0, max: 6, step: 0.5, style: { flex: 1 }, onChange: function (v) { if (v != null) params.bleed = v; renderSmart(); } }),
- h('span', { className: 'unit' }, 'mm')
- ),
- h('div', { className: 'sp-row' },
- h('label', null, '厚度(0.2~3mm)'),
- h(A.InputNumber, { value: material().thickness, min: 0.2, max: 3, step: 0.1, style: { flex: 1 }, onChange: function (v) { /* 材质决定厚度 */ } }),
- h('span', { className: 'unit' }, 'mm')
- ),
- h('div', { className: 'sp-row' },
- h('label', null, '材质'),
- h(A.Select, { value: state.material, style: { flex: 1 }, options: MATERIALS.map(function (m) { return { value: m.id, label: m.name }; }), onChange: function (v) { state.material = v; renderSmart(); } })
- ),
- advRows.length ? h('div', { className: 'sp-group-title' }, '高级参数') : null,
- advRows
- )
- );
- const close = modalConfirm('智能参数宝', content, function () {
- pushUndo();
- state.w = dims.w; state.d = dims.d; state.h = dims.h;
- Object.assign(state.smart, params);
- commit();
- UI.message.success('参数已调整,刀版与 3D 已更新');
- }, '确认调整', 980);
- function renderSmart() {
- const keep = { w: state.w, d: state.d, h: state.h, smart: state.smart };
- state.w = dims.w; state.d = dims.d; state.h = dims.h;
- const merged = Object.assign({}, state.smart, params);
- state.smart = merged;
- const svg = dielineSVG({ noLegend: true, clean: !params._labels });
- state.w = keep.w; state.d = keep.d; state.h = keep.h; state.smart = keep.smart;
- const el = document.getElementById('spDieline');
- if (el) {
- el.innerHTML = svg;
- const s = el.querySelector('svg');
- if (s) { s.style.width = '100%'; s.style.height = 'auto'; }
- }
- }
- setTimeout(renderSmart, 60);
- }
- function showImportCad() {
- modalInfo('导入 CAD', h('div', { className: 'bx-help-steps' },
- h('p', null, '支持 DXF 盒型结构文件上传,上传后在「我的盒型」中管理。'),
- h('p', null, '演示环境:本版本以内置参数化盒型库代替 CAD 解析,选择盒型后可在智能参数宝中精调结构参数。')
- ));
- }
- /* ---------------- 导出弹窗 ---------------- */
- let exportTab = 'file', exportRes = '2k', exportRatio = '16:9', exportBg = 'scene', exportSide = 'outer';
- const EXPORT_LOG_KEY = 'pouchlab.box.exports';
- function exportLog() { try { return JSON.parse(localStorage.getItem(EXPORT_LOG_KEY) || '[]'); } catch (e) { return []; } }
- function logExport(type, name) {
- const list = exportLog();
- list.unshift({ time: Date.now(), type: type, name: name });
- try { localStorage.setItem(EXPORT_LOG_KEY, JSON.stringify(list.slice(0, 40))); } catch (e) {}
- }
- function downloadBlob(blob, filename) {
- const a = document.createElement('a');
- a.href = URL.createObjectURL(blob);
- a.download = filename;
- a.click();
- setTimeout(function () { URL.revokeObjectURL(a.href); }, 2000);
- }
- function openExport() {
- const div = document.createElement('div');
- $('#bxModals').appendChild(div);
- const close = function () { UI.reset(div); div.remove(); renderAll(); };
- let snapRaf = null;
- // 导出弹窗内的静态 3D 快照;用当前设计实时渲染,避免预览空白
- function snapSrc(w, h) {
- if (!main3d || !main3d.ready()) return '';
- try {
- main3d.render(state, material(), currentPanels());
- main3d.setFold(foldValue / 100);
- return main3d.snapshot(w, h, exportBg === 'transparent');
- } catch (e) { return ''; }
- }
- function refreshSnap() {
- if (snapRaf) return;
- snapRaf = requestAnimationFrame(function () {
- snapRaf = null;
- const im = div.querySelector('.ex-preview.3d .ex-snap');
- if (im) im.src = snapSrc(760, 480);
- });
- }
- function renderExport() {
- let body;
- if (exportTab === 'file') {
- body = h('div', { className: 'ex-file-body' },
- h('div', { className: 'ex-preview', dangerouslySetInnerHTML: { __html: dielineSVG({ noLegend: true }) } }),
- h('div', { className: 'ex-side' },
- h('div', { className: 'ex-label' }, '文件类型'),
- h('div', { className: 'ex-type-grid' },
- h('button', { onClick: exportPrintPdf }, '印刷PDF', h('em', null, 'pdf')),
- h('button', { onClick: function () { UI.message.info('AI 源文件暂不支持,可导出 PDF / DXF / SVG 矢量文件'); } }, '印刷AI', h('em', null, 'ai')),
- h('button', { onClick: exportDielinePdf }, '刀版PDF', h('em', null, 'pdf')),
- h('button', { onClick: exportDxf }, '刀版DXF', h('em', null, 'dxf')),
- h('button', { onClick: exportPreviewJpg }, '预览JPG', h('em', null, 'jpg'))
- ),
- h('div', { className: 'ex-label' }, '色彩模式'),
- h('div', { className: 'ex-mode-row' },
- h('button', { className: 'on' }, 'CMYK模式'),
- h('button', { onClick: function () { UI.message.info('屏幕预览为 RGB,交付印刷文件请选 CMYK'); } }, 'RGB模式')
- ),
- h('p', { className: 'ex-note' }, '刀线和设计元素独立分层'),
- h('p', { className: 'ex-note' }, '导出即视为已阅读并同意《授权许可协议》')
- )
- );
- } else if (exportTab === 'image') {
- const dims = { '2k': [1920, 1080], '3k': [2560, 1440], '4k': [3840, 2160] }[exportRes];
- const ratio = { '16:9': 16 / 9, '4:3': 4 / 3, '1:1': 1 }[exportRatio];
- const rw = Math.round(Math.min(dims[0], dims[1] * ratio));
- const rh = Math.round(rw / ratio);
- const pv = snapSrc(760, 480);
- body = h('div', { className: 'ex-file-body' },
- h('div', { className: 'ex-preview 3d' },
- pv ? h('img', { className: 'ex-snap', src: pv, alt: '' }) : h('div', { className: 'ex-preview-empty' }, '3D 预览加载中…'),
- h('div', { className: 'ex-fold-row' },
- h('span', null, '开'), h('input', { type: 'range', min: 0, max: 100, value: Math.round(foldValue), onInput: function (e) { setFold(Number(e.target.value)); refreshSnap(); } }), h('span', null, '合')
- )
- ),
- h('div', { className: 'ex-side' },
- [['2k', '2K', '1920*1080', '高清'], ['3k', '3K', '2560*1440', '超清'], ['4k', '4K', '3840*2160', '超高清']].map(function (r) {
- return h('button', { key: r[0], className: 'ex-res' + (exportRes === r[0] ? ' on' : ''), onClick: function () { exportRes = r[0]; renderExport(); } },
- h('b', null, r[1]), h('span', null, r[2]), h('em', null, r[3]));
- }),
- h('div', { className: 'ex-label' }, '构图比例'),
- h(A.Select, { value: exportRatio, style: { width: '100%' }, options: [{ value: '16:9' }, { value: '4:3' }, { value: '1:1' }], onChange: function (v) { exportRatio = v; renderExport(); } }),
- h('div', { className: 'ex-label' }, '背景'),
- h(A.Radio.Group, { value: exportBg, onChange: function (e) { exportBg = e.target.value; renderExport(); }, options: [{ value: 'scene', label: '场景' }, { value: 'transparent', label: '透明' }] }),
- h('button', { className: 'ex-primary', onClick: exportHdImage }, '导出效果图')
- )
- );
- } else {
- const pvVid = snapSrc(760, 480);
- body = h('div', { className: 'ex-file-body' },
- h('div', { className: 'ex-preview 3d' }, pvVid ? h('img', { className: 'ex-snap', src: pvVid, alt: '' }) : null),
- h('div', { className: 'ex-side' },
- h('div', { className: 'ex-anim-grid' }, LB.ANIMS.map(function (a) {
- return h('button', { key: a.id, className: 'ex-anim' + (exportAnim === a.id ? ' on' : ''), onClick: function () { exportAnim = a.id; renderExport(); } },
- h('em', null, a.dur + 's'), h('span', { className: 'anim-illus ' + a.id }));
- })),
- h('button', { className: 'ex-primary', onClick: exportVideo }, '导出视频')
- )
- );
- }
- UI.render(div, h(A.Modal, {
- open: true, onCancel: close, footer: null, width: 940, title: null,
- },
- h('div', { className: 'ex-wrap' },
- h('div', { className: 'ex-tabs' },
- [['file', '设计文件'], ['image', '效果图'], ['video', '视频']].map(function (t) {
- return h('button', { key: t[0], className: exportTab === t[0] ? 'on' : '', onClick: function () { exportTab = t[0]; renderExport(); } }, t[1]);
- }),
- h('button', { className: 'ex-log-btn', onClick: showExportLog }, '⏱ 导出记录')
- ),
- body
- )
- ));
- }
- renderExport();
- }
- let exportAnim = 'fold';
- function printSvgWindow(svgStr, title) {
- const win = window.open('', '_blank');
- if (!win) { UI.message.warning('浏览器拦截了新窗口,请允许弹窗'); return; }
- win.document.write('<html><head><title>' + title + '</title><style>body{margin:0;display:flex;align-items:center;justify-content:center;height:100vh}svg{max-width:96vw;max-height:96vh}</style></head><body>' + svgStr + '<script>window.onload=function(){setTimeout(function(){window.print()},300)}<\/script></body></html>');
- win.document.close();
- }
- function exportPrintPdf() {
- printSvgWindow(dielineSVG(), state.name + ' 印刷文件');
- logExport('印刷PDF', state.name);
- }
- function exportDielinePdf() {
- printSvgWindow(dielineSVG({ clean: true, noLegend: false }), state.name + ' 刀版');
- logExport('刀版PDF', state.name);
- }
- function exportPreviewJpg() {
- const svgStr = dielineSVG();
- const img = new Image();
- img.onload = function () {
- const scale = 2;
- const c = document.createElement('canvas');
- c.width = img.width * scale;
- c.height = img.height * scale;
- const ctx = c.getContext('2d');
- ctx.fillStyle = '#fff';
- ctx.fillRect(0, 0, c.width, c.height);
- ctx.drawImage(img, 0, 0, c.width, c.height);
- c.toBlob(function (b) {
- downloadBlob(b, state.name + '-dieline.jpg');
- logExport('预览JPG', state.name);
- UI.message.success('预览 JPG 已下载');
- }, 'image/jpeg', 0.92);
- };
- img.src = 'data:image/svg+xml;charset=utf-8,' + encodeURIComponent(svgStr);
- }
- function exportDxf() {
- const dl = dieline();
- const ox = -dl.minX, oy = -dl.minY;
- let out = '0\nSECTION\n2\nENTITIES\n';
- dl.panels.forEach(function (p) {
- const pts = p.poly ? p.poly : [[p.x, p.y], [p.x + p.w, p.y], [p.x + p.w, p.y + p.h], [p.x, p.y + p.h]];
- for (let i = 0; i < pts.length; i += 1) {
- const a = pts[i], b = pts[(i + 1) % pts.length];
- out += '0\nLINE\n8\nCUT\n10\n' + (a[0] + ox).toFixed(3) + '\n20\n' + (a[1] + oy).toFixed(3) + '\n11\n' + (b[0] + ox).toFixed(3) + '\n21\n' + (b[1] + oy).toFixed(3) + '\n';
- }
- (p.holes || []).forEach(function (ho) {
- for (let i = 0; i < 24; i += 1) {
- const a0 = i / 24 * Math.PI * 2, a1 = (i + 1) / 24 * Math.PI * 2;
- out += '0\nLINE\n8\nCUT\n10\n' + (ho.x + ox + ho.r * Math.cos(a0)).toFixed(3) + '\n20\n' + (ho.y + oy + ho.r * Math.sin(a0)).toFixed(3) + '\n11\n' + (ho.x + ox + ho.r * Math.cos(a1)).toFixed(3) + '\n21\n' + (ho.y + oy + ho.r * Math.sin(a1)).toFixed(3) + '\n';
- }
- });
- });
- dl.folds.forEach(function (f) {
- out += '0\nLINE\n8\nFOLD\n10\n' + (f.x1 + ox).toFixed(3) + '\n20\n' + (f.y1 + oy).toFixed(3) + '\n11\n' + (f.x2 + ox).toFixed(3) + '\n21\n' + (f.y2 + oy).toFixed(3) + '\n';
- });
- out += '0\nENDSEC\n0\nEOF\n';
- downloadBlob(new Blob([out], { type: 'application/dxf' }), state.name + '-dieline.dxf');
- logExport('刀版DXF', state.name);
- UI.message.success('刀版 DXF 已下载');
- }
- function exportHdImage() {
- if (!main3d || !main3d.ready()) { UI.message.warning('3D 渲染器未就绪'); return; }
- const dims = { '2k': [1920, 1080], '3k': [2560, 1440], '4k': [3840, 2160] }[exportRes];
- const ratio = { '16:9': 16 / 9, '4:3': 4 / 3, '1:1': 1 }[exportRatio];
- const rw = Math.round(Math.min(dims[0], dims[1] * ratio));
- const rh = Math.round(rw / ratio);
- const wasMode = state.mode;
- if (wasMode !== '3d') setMode('3d');
- main3d.render(state, material(), currentPanels());
- main3d.setFold(foldValue / 100);
- if (UI.message.loading) UI.message.loading({ content: '正在渲染 ' + exportRes.toUpperCase() + ' 效果图…', key: 'boxhd', duration: 0 });
- const grab = function () {
- const url = main3d.snapshot(rw, rh, exportBg === 'transparent');
- if (!url || url.length < 1000) {
- setTimeout(grab, 220);
- return;
- }
- const img = new Image();
- img.onload = function () {
- const c = document.createElement('canvas');
- c.width = rw; c.height = rh;
- const ctx = c.getContext('2d');
- if (exportBg !== 'transparent') {
- const g = ctx.createLinearGradient(0, 0, 0, rh);
- g.addColorStop(0, '#f3f1ec'); g.addColorStop(1, '#e7e4dd');
- ctx.fillStyle = g; ctx.fillRect(0, 0, rw, rh);
- }
- ctx.drawImage(img, 0, 0, rw, rh);
- c.toBlob(function (b) {
- downloadBlob(b, state.name + '-' + exportRes.toUpperCase() + '.png');
- logExport('效果图', state.name + ' ' + exportRes.toUpperCase());
- UI.message.success({ content: exportRes.toUpperCase() + ' 效果图已下载', key: 'boxhd' });
- }, 'image/png');
- };
- img.src = url;
- };
- // 等贴图/字体加载完成后再截图,避免 4K 图空白
- setTimeout(function () { requestAnimationFrame(function () { requestAnimationFrame(grab); }); }, 320);
- }
- function exportVideo() {
- if (!main3d || !main3d.ready()) { UI.message.warning('3D 渲染器未就绪'); return; }
- if (typeof MediaRecorder === 'undefined') { UI.message.error('当前浏览器不支持视频录制'); return; }
- if (state.mode !== '3d') setMode('3d');
- const def = LB.ANIMS.find(function (a) { return a.id === exportAnim; });
- UI.message.info('正在录制「' + def.name + '」' + def.dur + 's…');
- const canvas = $('#boxScene canvas');
- const stream = canvas.captureStream(30);
- const rec = new MediaRecorder(stream, { mimeType: MediaRecorder.isTypeSupported('video/webm;codecs=vp9') ? 'video/webm;codecs=vp9' : 'video/webm' });
- const chunks = [];
- rec.ondataavailable = function (e) { if (e.data.size) chunks.push(e.data); };
- rec.onstop = function () {
- const blob = new Blob(chunks, { type: 'video/webm' });
- downloadBlob(blob, state.name + '-' + def.name + '.webm');
- logExport('视频', def.name);
- UI.message.success('动效视频已下载');
- };
- main3d.playAnim(def.id, def.dur, function () { setTimeout(function () { rec.stop(); }, 300); });
- rec.start();
- }
- function showExportLog() {
- const list = exportLog();
- modalInfo('导出记录', list.length
- ? h('div', { className: 'bx-export-log' }, list.map(function (e, i) {
- return h('p', { key: i }, new Date(e.time).toLocaleString() + ' · ' + e.type + ' · ' + e.name);
- }))
- : h(A.Empty, { description: '暂无导出记录' }));
- }
- /* ---------------- 印刷下单 ---------------- */
- function openPrintFlow() {
- const div = document.createElement('div');
- $('#bxModals').appendChild(div);
- let pct = 0;
- const checks = [];
- // 印前检测(本地规则)
- function precheck() {
- checks.length = 0;
- checks.push({ ok: true, text: '刀版结构完整(' + struct().name + ')' });
- checks.push({ ok: (state.smart.bleed || 0) >= 3, text: '出血线 ' + (state.smart.bleed || 0) + 'mm' + ((state.smart.bleed || 0) >= 3 ? '' : '(建议 ≥3mm)') });
- let imgWarn = false, txtWarn = false;
- ['outer', 'inner'].forEach(function (side) {
- FACES.forEach(function (f) {
- (state.faces[side][f.id].items || []).forEach(function (it) {
- if (it.type === 'text' && it.size < 2) txtWarn = true;
- if ((it.type === 'image' || it.type === 'asset') && it.src && it.src.indexOf('data:image/svg') < 0) {
- const m = it.src.match(/^data:image\/(\w+);base64,/);
- if (m && m[1] !== 'svg+xml') {
- const b64 = it.src.split(',')[1] || '';
- const px = b64.length * 0.75;
- if (px < 20000) imgWarn = true;
- }
- }
- });
- });
- });
- checks.push({ ok: !imgWarn, text: '图片清晰度' + (imgWarn ? '(检测到低分辨率图片,印刷可能模糊)' : '') });
- checks.push({ ok: !txtWarn, text: '最小字号' + (txtWarn ? '(有 <2mm 文字,印刷可能不清晰)' : '') });
- checks.push({ ok: true, text: '色彩模式:CMYK 印刷色域' });
- }
- precheck();
- let quoteState = { qty: state.qty, contact: { name: '', phone: '', address: '', note: '' }, submitting: false };
- let stage = 'check';
- function renderFlow() {
- if (stage === 'check') {
- UI.render(div, h(A.Modal, { open: true, footer: null, width: 480, onCancel: function () { UI.reset(div); div.remove(); renderAll(); } },
- h('div', { className: 'pc-wrap' },
- h('div', { className: 'pc-title' }, '印前检测 ', h('em', { className: 'free' }, '限免'), h('i', { className: 'q', title: '智能印刷引擎在您检测设计问题' })),
- h('div', { className: 'pc-ring', style: { '--p': pct } }, h('b', null, pct + '%')),
- h('p', { className: 'pc-sub' }, '智能印刷引擎正在为您检测中…'),
- h('div', { className: 'pc-checks' }, checks.map(function (c, i) {
- return h('p', { key: i, className: c.ok ? 'ok' : 'warn' }, (c.ok ? '✓ ' : '⚠ ') + c.text);
- }))
- )
- ));
- } else {
- const price = priceInfo();
- UI.render(div, h(A.Modal, { open: true, footer: null, width: 1000, onCancel: function () { UI.reset(div); div.remove(); renderAll(); } },
- h('div', { className: 'pq-wrap' },
- h('div', { className: 'pq-head' },
- h('b', null, '印刷报价'),
- h('span', null, '确认印刷配置,沿用原设计与刀版'),
- h('button', { className: 'pq-back', onClick: function () { UI.reset(div); div.remove(); renderAll(); } }, '返回继续编辑 ⇱')
- ),
- h('div', { className: 'pq-cols' },
- h('div', { className: 'pq-left' },
- h('div', { className: 'pq-thumb', dangerouslySetInnerHTML: { __html: dielineSVG({ clean: true, noLegend: true }) } }),
- h('b', { className: 'pq-name' }, libEntry().name),
- h('div', { className: 'pq-kv' }, '盒型 ' + state.boxNo),
- h('div', { className: 'pq-kv' }, '制造尺寸 ' + Math.round(state.w) + ' × ' + Math.round(state.d) + ' × ' + Math.round(state.h) + ' mm'),
- h('div', { className: 'pq-kv' }, '生产主材 ' + material().name),
- h('div', { className: 'pq-kv' }, '印面 ' + (state.side === 'outer' ? '单面(外)' : '单面(内)'))
- ),
- h('div', { className: 'pq-right' },
- h('div', { className: 'pq-sec' }, h('b', null, '订购数量 ⇱')),
- h('div', { className: 'pq-qty-grid' }, [1, 10, 500, 1000, 2000, 5000, 10000, 20000].map(function (v) {
- return h('button', { key: v, className: quoteState.qty === v ? 'on' : '', onClick: function () { state.qty = v; quoteState.qty = v; renderFlow(); } }, v.toLocaleString());
- })),
- h('div', { className: 'pq-custom' },
- h('span', null, '自定义数量'),
- h(A.InputNumber, { value: quoteState.qty, min: 1, style: { width: 130 }, onChange: function (v) { if (v) { state.qty = v; quoteState.qty = v; renderFlow(); } } })
- ),
- h('div', { className: 'pq-sec' }, h('b', null, '印刷配置')),
- h('div', { className: 'pq-kv row' }, h('span', null, '材质'), h('b', null, material().name)),
- h('div', { className: 'pq-kv row' }, h('span', null, '印色')),
- h('div', { className: 'pq-chip-row' }, PRINTS.map(function (p) {
- return h('button', { key: p.id, className: state.print === p.id ? 'on' : '', onClick: function () { state.print = p.id; renderFlow(); } }, p.name);
- })),
- h('div', { className: 'pq-kv row' }, h('span', null, '印刷方式')),
- h(A.Select, { value: state.printWay, style: { width: '100%' }, options: PRINT_WAYS.map(function (w) { return { value: w }; }), onChange: function (v) { state.printWay = v; renderFlow(); } }),
- h('div', { className: 'pq-sec' }, h('b', null, '收货信息')),
- h('div', { className: 'pq-contact' },
- h(A.Input, { placeholder: '联系人', onChange: function (e) { quoteState.contact.name = e.target.value; } }),
- h(A.Input, { placeholder: '手机号', onChange: function (e) { quoteState.contact.phone = e.target.value; } }),
- h(A.Input, { placeholder: '收货地址(省市区 + 详细地址)', onChange: function (e) { quoteState.contact.address = e.target.value; } }),
- h(A.Input, { placeholder: '备注(选填)', onChange: function (e) { quoteState.contact.note = e.target.value; } })
- )
- )
- ),
- h('div', { className: 'pq-foot' },
- h('button', { className: 'pq-service', onClick: function () { UI.message.info('演示环境:400-000-0000'); } }, '🎧 人工咨询'),
- h('span', { className: 'pq-lead' }, '预计加工时间:4 个工作日'),
- h('b', { className: 'pq-price' }, '印刷费 ¥' + price.total.toFixed(2), h('span', null, '(运费待计算)')),
- h('button', { className: 'pq-detail', onClick: function () {
- modalInfo('报价明细', h('div', { className: 'bx-help-steps' },
- h('p', null, '展开面积:' + price.area.toFixed(3) + ' m²'),
- h('p', null, '材质单价:' + material().name + ' × ' + material().rate.toFixed(2) + ' 元/m²'),
- h('p', null, '印色系数:' + print().name + ' × ' + print().factor),
- h('p', null, '结构费:' + struct().name + ' ¥' + struct().fee.toFixed(2)),
- h('p', null, '数量折扣:' + Math.round(price.disc * 100) + '%'),
- h('p', null, '单价:¥' + price.unit.toFixed(2) + ' × ' + state.qty + ' 个')
- ));
- } }, '报价明细'),
- h('button', { className: 'pq-order', disabled: quoteState.submitting, onClick: function () {
- if (window.PL && PL.auth && !PL.auth.user()) {
- PL.auth.require(function () { /* 登录后再次点击即可下单 */ });
- return;
- }
- if (!window.PL || !PL.api) return;
- const c = quoteState.contact;
- if (!c.name || !c.phone || !c.address) {
- UI.message.warning('请完整填写联系人、手机号和收货地址');
- return;
- }
- if (quoteState.submitting) return;
- quoteState.submitting = true;
- renderFlow();
- const dl = dieline();
- const dlJson = JSON.parse(JSON.stringify(dl));
- dlJson.kind = 'box';
- dlJson.meta = {
- boxNo: state.boxNo, boxName: libEntry().name, structure: state.structure,
- inner: { w: Math.round(state.w), d: Math.round(state.d), h: Math.round(state.h) },
- material: material().name, thickness: String(material().thickness), qty: state.qty
- };
- let design = null;
- try { design = JSON.parse(snapshot()); } catch (err) {}
- const payload = {
- type: 'box',
- contact: { name: c.name, phone: c.phone, email: '', address: c.address, note: c.note },
- spec: {
- boxNo: state.boxNo, boxName: libEntry().name, structure: state.structure,
- w: Math.round(state.w), d: Math.round(state.d), h: Math.round(state.h),
- material: state.material, materialName: material().name,
- thickness: material().thickness, print: state.print, printName: print().name,
- printWay: state.printWay, qty: state.qty, smart: state.smart
- },
- quote: { unit: price.unit, total: price.total, area: price.area, disc: price.disc },
- summary: libEntry().name + ' ' + Math.round(state.w) + '×' + Math.round(state.d) + '×' + Math.round(state.h) + 'mm · ' + material().name + ' · ' + state.qty + ' 个',
- design: design,
- dieline: dlJson,
- previews: {}
- };
- // 3D 效果图随订单一起提交,订单列表/详情可直接看到设计效果
- let boxShot = '';
- if (main3d && main3d.ready()) {
- try {
- main3d.render(state, material(), currentPanels());
- main3d.setFold(foldValue / 100);
- boxShot = main3d.snapshot(1200, 900, false);
- } catch (e) { boxShot = ''; }
- }
- PL.api.svgToPng(dielineSVG({ clean: true, noLegend: true }), 1200).then(function (png) {
- payload.previews = { dieline: png };
- if (boxShot) payload.previews.box3d = boxShot;
- }, function () {
- if (boxShot) payload.previews.box3d = boxShot;
- }).then(function () {
- return PL.api.post('/orders', payload, { timeout: 60000 });
- }).then(function (r) {
- const orders = JSON.parse(localStorage.getItem('pouchlab.box.orders') || '[]');
- orders.unshift({ no: r.orderNo, time: Date.now(), name: state.name, qty: state.qty, total: price.total, boxNo: state.boxNo, type: 'box', summary: payload.summary, previews: payload.previews });
- localStorage.setItem('pouchlab.box.orders', JSON.stringify(orders.slice(0, 30)));
- UI.reset(div); div.remove();
- modalInfo('下单成功', h('div', { className: 'bx-help-steps' },
- h('p', null, '订单号:' + r.orderNo),
- h('p', null, '数量:' + state.qty + ' 个 · 金额:¥' + price.total.toFixed(2)),
- h('p', null, '支付与生产进度请在「我的订单」查看'),
- h('p', null, h('a', { href: 'orders.html', style: { color: '#ff5c2b', fontWeight: 600 } }, '前往我的订单 →'))
- ));
- renderAll();
- }, function (err) {
- quoteState.submitting = false;
- renderFlow();
- if (err && err.network) {
- // 离线回退:沿用旧的本地保存
- const orderNo = 'PL' + Date.now().toString().slice(-10);
- const orders = JSON.parse(localStorage.getItem('pouchlab.box.orders') || '[]');
- orders.unshift({ no: orderNo, time: Date.now(), name: state.name, qty: state.qty, total: price.total, boxNo: state.boxNo, type: 'box', summary: payload.summary, previews: payload.previews, offline: true });
- localStorage.setItem('pouchlab.box.orders', JSON.stringify(orders.slice(0, 30)));
- UI.reset(div); div.remove();
- modalInfo('下单成功(离线保存)', h('div', { className: 'bx-help-steps' },
- h('p', null, '订单号:' + orderNo),
- h('p', null, '服务器暂不可达,订单已保存在本地,联网后请重新提交。')
- ));
- renderAll();
- return;
- }
- UI.message.error(err.message || '下单失败,请重试');
- });
- } }, quoteState.submitting ? '正在提交…' : '立即下单')
- )
- )
- ));
- }
- }
- // 检测进度动画
- const timer = setInterval(function () {
- pct = Math.min(100, pct + Math.ceil(Math.random() * 22));
- if (pct >= 100) {
- clearInterval(timer);
- setTimeout(function () { stage = 'quote'; renderFlow(); }, 500);
- } else renderFlow();
- }, 320);
- renderFlow();
- }
- /* ---------------- 文件菜单 ---------------- */
- function newPlan() {
- modalConfirm('新建设计方案', h('p', null, '当前方案已自动保存到「我的设计方案」,新建后将开始一个空白方案。'), function () {
- savePlanToLibrary();
- pushUndo();
- state.planId = 'p' + Date.now().toString(36);
- state.name = '未命名纸盒';
- state.faces = blankFaces();
- state.selectedItemId = null;
- commit();
- UI.message.success('已新建设计方案');
- }, '新建');
- }
- function copyPlan() {
- pushUndo();
- state.planId = 'p' + Date.now().toString(36);
- state.name = state.name + ' 副本';
- commit();
- UI.message.success('已创建副本:' + state.name);
- }
- function openMyPlans() {
- const list = plansList();
- modalInfo('我的设计方案', list.length
- ? h('div', { className: 'bx-plan-list' }, list.map(function (p) {
- return h('div', { key: p.id, className: 'bx-plan-row' },
- h('span', { className: 't' }, h('b', null, p.name), h('em', null, new Date(p.time).toLocaleString() + ' · ' + p.boxNo)),
- h('button', { onClick: function () { openPlanData(p.id); } }, '打开'),
- h('button', { className: 'del', onClick: function () {
- const l = plansList().filter(function (x) { return x.id !== p.id; });
- localStorage.setItem(LIST_KEY, JSON.stringify(l));
- localStorage.removeItem(planDataKey(p.id));
- UI.message.success('已删除');
- $('#bxFileMenu').hidden = true;
- } }, '删除')
- );
- }))
- : h(A.Empty, { description: '暂无保存的方案' }));
- }
- function openPlanData(id) {
- try {
- const data = JSON.parse(localStorage.getItem(planDataKey(id)) || 'null');
- if (!data) { UI.message.warning('方案数据缺失'); return; }
- pushUndo();
- Object.assign(state, data);
- state.planId = id;
- const f = blankFaces();
- ['outer', 'inner'].forEach(function (side) {
- FACES.forEach(function (face) {
- const src = (data.faces[side] && data.faces[side][face.id]) || {};
- f[side][face.id] = { color: src.color || '', texture: src.texture || null, items: src.items || [] };
- });
- });
- state.faces = f;
- commit(false);
- UI.message.success('已打开「' + state.name + '」');
- } catch (e) { UI.message.error('方案打开失败'); }
- }
- function openHistory() {
- const hist = JSON.parse(localStorage.getItem(HIST_KEY + '.' + state.planId) || '[]');
- modalInfo('历史版本记录', hist.length
- ? h('div', { className: 'bx-plan-list' }, hist.slice(0, 15).map(function (hh, i) {
- return h('div', { key: i, className: 'bx-plan-row' },
- h('span', { className: 't' }, h('b', null, '版本 ' + (hist.length - i)), h('em', null, new Date(hh.time).toLocaleString())),
- h('button', { onClick: function () { restore(hh.snap); UI.message.success('已恢复历史版本'); } }, '恢复')
- );
- }))
- : h(A.Empty, { description: '暂无历史版本' }));
- }
- /* ---------------- 渲染总入口 ---------------- */
- function renderTool() {
- UI.render($('#bxPanelBody'), panelBox());
- document.querySelectorAll('#bxRail button').forEach(function (b) {
- b.classList.toggle('on', b.dataset.tab === currentTab);
- });
- }
- function renderProps() {
- UI.render($('#bxPropsBody'), propsPanel());
- }
- function renderSideThumb() {
- const el = $('#bxSideThumb');
- if (el) {
- // 使用真实设计稿缩略图,与 2D/3D 画面保持一致,并支持点击选面
- el.innerHTML = '<div class="side-thumb-svg">' + dielineSVG({ clean: true, noLegend: true, idPrefix: 'side' }) + '</div>';
- }
- const mid = $('#bxModelId');
- if (mid) mid.textContent = '模型ID: ' + state.boxNo;
- }
- function renderAll() {
- $('#bxFileName').textContent = state.name;
- document.title = state.name + ' — 3D云设计编辑器 · 袋研社';
- renderDieline();
- renderSideThumb();
- renderTool();
- renderProps();
- $('#bxMini3d').hidden = state.mode !== '2d';
- if (state.mode === '2d') {
- renderMini();
- } else {
- render3d();
- $('#boxFoldRange').value = Math.round(foldValue);
- }
- $('#bxColorCur').style.background = (curFaces()._plain && curFaces()._plain.color) || material().paper;
- }
- /* ---------------- 折叠动画 ---------------- */
- function stopFoldAnim() {
- if (foldAnim) {
- if (main3d && main3d.stopAnim) main3d.stopAnim(); // 音频心跳补间由 box3d 停止
- if (foldAnim && foldAnim !== 'audio') cancelAnimationFrame(foldAnim);
- foldAnim = null;
- }
- const play = $('#bxFoldPlay');
- if (play) play.textContent = '▶';
- const miniPlay = $('#bxMiniPlay');
- if (miniPlay) miniPlay.textContent = '▶';
- }
- function animateFoldTo(to, mini) {
- stopFoldAnim();
- const from = foldValue;
- if (Math.abs(to - from) < 0.5) { setFold(to); return; }
- // 音频线程心跳补间:页面时钟/rAF 被冻结时依然流畅
- if (main3d && main3d.ready && main3d.ready() && main3d.tween) {
- foldAnim = 'audio';
- main3d.tween(1.1, function (p) {
- const eased = p < 0.5 ? 2 * p * p : 1 - Math.pow(-2 * p + 2, 2) / 2;
- setFold(from + (to - from) * eased, mini);
- }, function () {
- foldAnim = null;
- setFold(to);
- });
- return;
- }
- // 无 3D 时 rAF 降级
- const start = performance.now();
- const dur = 1100;
- function step(now) {
- const t = Math.min(1, (now - start) / dur);
- const eased = t < 0.5 ? 2 * t * t : 1 - Math.pow(-2 * t + 2, 2) / 2;
- setFold(from + (to - from) * eased, mini);
- if (t < 1) foldAnim = requestAnimationFrame(step);
- else { foldAnim = null; setFold(to); }
- }
- foldAnim = requestAnimationFrame(step);
- }
- function setFold(v, mini) {
- foldValue = clamp(Number(v) || 0, 0, 100);
- if (main3d && main3d.ready()) main3d.setFold(foldValue / 100);
- if (mini3d && mini3d.ready()) mini3d.setFold(foldValue / 100);
- const range = $('#boxFoldRange');
- if (range && !mini) range.value = String(Math.round(foldValue));
- const miniRange = $('#bxMiniFold');
- if (miniRange && mini) miniRange.value = String(Math.round(foldValue));
- const play = $('#bxFoldPlay');
- if (play) play.textContent = foldAnim ? '❚❚' : '▶';
- }
- /* ---------------- 迷你 3D 自动播放(CSS 合成器动画) ---------------- */
- let miniAuto = true;
- function setMiniAuto(on) {
- miniAuto = !!on;
- const stage = document.getElementById('bxMiniStage');
- if (stage) stage.classList.toggle('autoplay', miniAuto);
- // CSS 动画接管旋转时,停掉 Three 的 JS 自转,避免叠加
- // mini 的旋转只由 CSS 动画或手动拖拽负责,Three 的 JS 自转恒定关闭
- if (mini3d && mini3d.setAutoRotate) mini3d.setAutoRotate(false);
- if (!miniAuto && mini3d && mini3d.resetView) {
- // 退出 CSS 旋转时把视角归位,保证手动拖拽从标准角度开始
- mini3d.resetView();
- }
- updateMiniAutoBtn();
- }
- function updateMiniAutoBtn() {
- const btn = document.getElementById('bxMiniAuto');
- if (btn) btn.classList.toggle('on', miniAuto);
- }
- /* ---------------- 事件绑定 ---------------- */
- function setTab(tab) {
- currentTab = tab;
- renderTool();
- }
- function bind() {
- // 模式切换
- $('#bxModeSwitch').addEventListener('click', function (e) {
- const b = e.target.closest('[data-mode]');
- if (b) setMode(b.dataset.mode);
- });
- // 左栏
- $('#bxRail').addEventListener('click', function (e) {
- const b = e.target.closest('[data-tab]');
- if (!b) return;
- setTab(b.dataset.tab);
- });
- // 文件菜单
- const fileMenu = $('#bxFileMenu');
- $('#bxFileBtn').addEventListener('click', function (e) {
- e.stopPropagation();
- fileMenu.hidden = !fileMenu.hidden;
- });
- document.addEventListener('click', function (e) {
- if (!fileMenu.hidden && !e.target.closest('.bx-file-menu-wrap')) fileMenu.hidden = true;
- });
- fileMenu.addEventListener('click', function (e) {
- const b = e.target.closest('[data-file]');
- if (!b) return;
- fileMenu.hidden = true;
- const act = b.dataset.file;
- if (act === 'new') newPlan();
- if (act === 'copy') copyPlan();
- if (act === 'mine') openMyPlans();
- if (act === 'history') openHistory();
- if (act === 'save') { savePlanToLibrary(); try { localStorage.setItem(planDataKey(state.planId), JSON.stringify(state)); } catch (err) {} UI.message.success('方案已保存'); }
- if (act === 'import-art') UI.message.info('演示环境:支持上传 JPG/PNG/SVG(上传面板)');
- if (act === 'import-cad') showImportCad();
- if (act === 'submit') UI.message.info('演示环境:投稿至模板中心需要登录账号');
- });
- $('#bxFileNameWrap').addEventListener('click', function () {
- const input = document.createElement('div');
- document.body.appendChild(input);
- const close = modalConfirm('重命名方案', h(A.Input, { id: 'bxRenameInput', defaultValue: state.name, maxLength: 30 }), function () {
- const v = document.getElementById('bxRenameInput').value;
- if (v) { state.name = v; commit(); }
- }, '确定');
- });
- // 顶部工具
- $('#bxShareBtn').addEventListener('click', function () {
- const url = location.href.split('#')[0] + '#' + state.planId;
- try { navigator.clipboard.writeText(url); UI.message.success('分享链接已复制'); }
- catch (e) { UI.message.info('分享链接:' + url); }
- });
- $('#bxSaveBtn').addEventListener('click', function () {
- savePlanToLibrary();
- try { localStorage.setItem(planDataKey(state.planId), JSON.stringify(state)); } catch (e) {}
- UI.message.success('方案已保存');
- });
- $('#bxUndoBtn').addEventListener('click', undo);
- $('#bxRedoBtn').addEventListener('click', redo);
- $('#bxPrintBtn').addEventListener('click', openPrintFlow);
- $('#bxAiBtn').addEventListener('click', aiFaceModal);
- $('#bxRenderBtn').addEventListener('click', function () {
- setMode('3d');
- if (main3d && main3d.ready()) {
- playAnim(LB.ANIMS[0]);
- UI.message.success('本地实时渲染:正在播放「折叠展开」动效');
- }
- });
- $('#bxExportBtn').addEventListener('click', openExport);
- $('#bxAvatar').addEventListener('click', function () {
- if (window.PL && PL.auth) PL.auth.open();
- });
- // 2D 画布
- $('#bxZoomIn2d').addEventListener('click', function () { state.view2d.zoom = clamp(state.view2d.zoom * 1.15, 0.1, 3); renderDieline(); });
- $('#bxZoomOut2d').addEventListener('click', function () { state.view2d.zoom = clamp(state.view2d.zoom / 1.15, 0.1, 3); renderDieline(); });
- $('#bxFit2d').addEventListener('click', fit2d);
- $('#bxPreviewToggle').addEventListener('click', function () {
- state.showLines = !state.showLines;
- this.classList.toggle('on', !state.showLines);
- renderDieline();
- });
- $('#bxPanToggle').addEventListener('click', function () {
- panMode = !panMode;
- this.classList.toggle('on', panMode);
- $('#bxFlat').style.cursor = panMode ? 'grab' : '';
- });
- // 外侧/内侧
- $('#bxSideFloat').addEventListener('click', function (e) {
- const b = e.target.closest('[data-side]');
- if (!b || b.dataset.side === state.side) return;
- state.side = b.dataset.side;
- state.selectedItemId = null;
- document.querySelectorAll('#bxSideFloat [data-side]').forEach(function (x) {
- x.classList.toggle('on', x.dataset.side === state.side);
- });
- commit();
- });
- // 迷你 3D
- $('#bxMiniPlay').addEventListener('click', function () {
- if (foldAnim) { stopFoldAnim(); return; }
- animateFoldTo(foldValue >= 99 ? 0 : 100, true);
- this.textContent = '❚❚';
- });
- $('#bxMiniFold').addEventListener('input', function () { stopFoldAnim(); setFold(this.value, true); });
- $('#bxMiniReset').addEventListener('click', function () { if (mini3d) mini3d.resetView(); });
- $('#bxMiniZoom').addEventListener('click', function () { if (mini3d) mini3d.setZoom(1.4); });
- $('#bxMiniAuto').addEventListener('click', function () {
- setMiniAuto(!miniAuto);
- });
- // 3D 控件
- $('#bxFoldPlay').addEventListener('click', function () {
- if (foldAnim) { stopFoldAnim(); return; }
- animateFoldTo(foldValue >= 99 ? 0 : 100);
- this.textContent = '❚❚';
- });
- $('#boxFoldRange').addEventListener('input', function () { stopFoldAnim(); setFold(this.value); });
- $('#bxFoldReset').addEventListener('click', function () { if (main3d) main3d.resetView(); });
- $('#bx4kBtn').addEventListener('click', function () { exportRes = '4k'; exportTab = 'image'; openExport(); });
- // 3D 快捷颜色
- const pop = $('#bxColorPop');
- $('#bxColorBtn').addEventListener('click', function (e) {
- e.stopPropagation();
- pop.hidden = !pop.hidden;
- });
- document.addEventListener('click', function (e) {
- if (!pop.hidden && !e.target.closest('#bxColorQuick')) pop.hidden = true;
- });
- $('#bxColorInput').addEventListener('input', function () {
- setPlainColor(this.value);
- });
- $('#bxColorGrid').innerHTML = LB.SWATCHES.map(function (c) {
- return '<span class="cc-swatch" data-cc="' + c + '" style="background:' + c + '"></span>';
- }).join('') + (window.PL.pantone ? '<div class="cc-pms-note">' + window.PL.pantone.note + '</div>' : '');
- $('#bxColorQuick').addEventListener('click', function (e) {
- const sw = e.target.closest('[data-cc]');
- if (!sw) return;
- setPlainColor(sw.dataset.cc === 'none' ? '' : sw.dataset.cc);
- if (sw.dataset.cc !== 'none') $('#bxColorCur').style.background = sw.dataset.cc;
- });
- function setPlainColor(c) {
- pushUndo();
- ['outer', 'inner'].forEach(function (side) {
- state.faces[side]._plain = { color: c };
- FACES.forEach(function (f) {
- const face = state.faces[side][f.id];
- if (!c || !face.color || face.color === '#fbf7ee') face.color = c;
- });
- });
- commit();
- }
- // 2D 画布拖拽 / 点选
- const flat = $('#bxFlat');
- flat.addEventListener('pointerdown', function (e) {
- if (e.target.closest('.bx-canvas-corner, .bx-side-float, .bx-mini3d, .dieline-hit')) return;
- if (!panMode && !e.shiftKey) return;
- panDrag = { x: e.clientX, y: e.clientY, px: state.view2d.panX, py: state.view2d.panY };
- flat.setPointerCapture(e.pointerId);
- });
- flat.addEventListener('pointermove', function (e) {
- if (!panDrag) return;
- state.view2d.panX = panDrag.px + (e.clientX - panDrag.x);
- state.view2d.panY = panDrag.py + (e.clientY - panDrag.y);
- renderDieline();
- });
- flat.addEventListener('pointerup', function () { panDrag = null; });
- // 图层面板拖拽排序(按住行上下拖,松手落位;兼容 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 layerDragCleanup() {
- document.querySelectorAll('.bx-layer-row').forEach(function (r) {
- r.classList.remove('dragging', 'drop-above', 'drop-below');
- });
- }
- function layerDragStartListen(e) {
- if (layerDrag) { layerDragCleanup(); layerDrag = null; }
- const row = e.target.closest && e.target.closest('.bx-layer-row');
- layerDragStart(row, e);
- }
- function layerDragMoveListen(e) {
- if (!layerDrag && (e.buttons & 1) === 1) layerDragStart(e.target.closest && e.target.closest('.bx-layer-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('.bx-layer-list');
- if (!list) return;
- const rows = [...list.querySelectorAll('.bx-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;
- reorderLayer(layerDrag.id, tid, target.above);
- layerDragCleanup();
- layerDrag.row = document.querySelector('.bx-layer-row[data-layer-id="' + layerDrag.id + '"]');
- } else if (!target) {
- layerDrag.lastTargetId = null;
- }
- }
- function layerDragEndListen() {
- if (!layerDrag) return;
- layerDrag = null;
- layerDragCleanup();
- }
- document.addEventListener('pointerdown', layerDragStartListen);
- document.addEventListener('mousedown', layerDragStartListen);
- document.addEventListener('pointermove', layerDragMoveListen, { passive: false });
- document.addEventListener('mousemove', layerDragMoveListen, { passive: false });
- document.addEventListener('pointerup', layerDragEndListen);
- document.addEventListener('mouseup', layerDragEndListen);
- // 2D 刀版元素拖拽(编辑在 2D 平铺上完成,迷你 3D 实时预览)
- const dielineEl = $('#boxDieline');
- let itemDrag = null, lastDragAt = 0;
- function svgLoc(svg, e) {
- if (!svg) return null;
- const ctm = svg.getScreenCTM();
- if (!ctm) return null;
- const pt = svg.createSVGPoint();
- pt.x = e.clientX;
- pt.y = e.clientY;
- return pt.matrixTransform(ctm.inverse());
- }
- function locToPct(svg, loc, face) {
- const dl = dieline();
- const panel = dl.panels.find(function (p) { return p.face === face; });
- if (!panel) return null;
- const fb = panelBounds(panel);
- const pad = 30 + (state.smart.bleed || 0);
- const lx = state.side === 'inner' ? svg.viewBox.baseVal.width - loc.x : loc.x;
- return {
- x: (lx - pad + dl.minX - fb.x) / fb.w * 100,
- y: (loc.y - pad + dl.minY - fb.y) / fb.h * 100
- };
- }
- dielineEl.addEventListener('pointerdown', function (e) {
- const hitEl = e.target.closest('.bx-item-hit');
- if (!hitEl) return;
- e.preventDefault();
- const face = hitEl.dataset.itemFace || state.selectedFace;
- // 元素可能位于未选中的面,按命中面查找,避免必须先点面再点文字
- const faceObj = state.faces[state.side] && state.faces[state.side][face];
- const it = faceObj && (faceObj.items || []).find(function (x) { return x.id === hitEl.dataset.itemId; });
- if (!it) return;
- const svg = dielineEl.querySelector('svg');
- const loc = svgLoc(svg, e);
- const pct = loc && locToPct(svg, loc, face);
- pushUndo();
- state.selectedItemId = it.id;
- state.selectedFace = face;
- renderProps();
- itemDrag = {
- id: it.id,
- face: face,
- // 记录抓取点相对元素中心的偏移,拖动时不再让元素跳到指针下
- ox: pct ? pct.x - it.x : 0,
- oy: pct ? pct.y - it.y : 0,
- moved: false,
- pointerId: e.pointerId
- };
- try { dielineEl.setPointerCapture(e.pointerId); } catch (err) {}
- });
- dielineEl.addEventListener('pointermove', function (e) {
- if (!itemDrag) return;
- e.preventDefault();
- const svg = dielineEl.querySelector('svg');
- const loc = svgLoc(svg, e);
- if (!loc) return;
- const pct = locToPct(svg, loc, itemDrag.face);
- const it = findItem(itemDrag.id);
- if (!pct || !it) return;
- const nx = clamp(pct.x - itemDrag.ox, 0, 100);
- const ny = clamp(pct.y - itemDrag.oy, 0, 100);
- if (Math.abs(nx - it.x) < 0.05 && Math.abs(ny - it.y) < 0.05) return;
- it.x = Math.round(nx * 10) / 10;
- it.y = Math.round(ny * 10) / 10;
- itemDrag.moved = true;
- renderDieline();
- if (mini3d && mini3d.ready()) { mini3d.render(state, material(), currentPanels()); mini3d.setFold(foldValue / 100); }
- if (main3d && main3d.ready()) { main3d.render(state, material(), currentPanels()); main3d.setFold(foldValue / 100); }
- });
- dielineEl.addEventListener('pointerup', function (e) {
- if (!itemDrag) return;
- const wasMoved = itemDrag.moved;
- try { dielineEl.releasePointerCapture(itemDrag.pointerId); } catch (err) {}
- itemDrag = null;
- if (wasMoved) {
- lastDragAt = Date.now();
- commit(false);
- renderProps();
- renderSideThumb();
- }
- });
- dielineEl.addEventListener('pointercancel', function () {
- if (itemDrag) {
- try { dielineEl.releasePointerCapture(itemDrag.pointerId); } catch (err) {}
- itemDrag = null;
- }
- });
- dielineEl.addEventListener('click', function (e) {
- if (Date.now() - lastDragAt < 300) return;
- if (e.target.closest('.bx-item-hit')) return;
- const f = e.target.closest('[data-face]');
- if (!f || !f.dataset.face) return;
- state.selectedFace = f.dataset.face;
- state.selectedItemId = null;
- commit(false);
- // 选中面后让迷你 3D 自动转向该面,保持 2D/3D 视角一致
- if (state.mode === '2d') {
- if (miniAuto) setMiniAuto(false);
- if (mini3d && mini3d.focusFace) mini3d.focusFace(f.dataset.face);
- }
- });
- // 缩略图选面:与 2D 刀版同步
- const sideThumbEl = $('#bxSideThumb');
- sideThumbEl.addEventListener('click', function (e) {
- const f = e.target.closest('[data-face]');
- if (!f || !f.dataset.face) return;
- state.selectedFace = f.dataset.face;
- state.selectedItemId = null;
- commit(false);
- if (state.mode === '2d') {
- if (miniAuto) setMiniAuto(false);
- if (mini3d && mini3d.focusFace) mini3d.focusFace(f.dataset.face);
- }
- });
- // 滚轮缩放 2D
- flat.addEventListener('wheel', function (e) {
- if (state.mode !== '2d') return;
- e.preventDefault();
- state.view2d.zoom = clamp(state.view2d.zoom * (e.deltaY > 0 ? 0.92 : 1.08), 0.1, 3);
- renderDieline();
- }, { passive: false });
- // 键盘
- document.addEventListener('keydown', function (e) {
- const tag = (document.activeElement && document.activeElement.tagName) || '';
- if (tag === 'INPUT' || tag === 'TEXTAREA') return;
- if ((e.ctrlKey || e.metaKey) && e.key.toLowerCase() === 'z') {
- e.preventDefault();
- if (e.shiftKey) redo(); else undo();
- } else if ((e.ctrlKey || e.metaKey) && e.key.toLowerCase() === 's') {
- e.preventDefault();
- savePlanToLibrary();
- UI.message.success('方案已保存');
- } else if (e.key === 'Delete' || e.key === 'Backspace') {
- if (state.selectedItemId) { e.preventDefault(); removeItem(state.selectedItemId); }
- } else if (e.key === 'Tab') {
- e.preventDefault();
- state.side = state.side === 'outer' ? 'inner' : 'outer';
- document.querySelectorAll('#bxSideFloat [data-side]').forEach(function (x) {
- x.classList.toggle('on', x.dataset.side === state.side);
- });
- commit();
- }
- });
- let resizeTimer = null;
- window.addEventListener('resize', function () {
- clearTimeout(resizeTimer);
- resizeTimer = setTimeout(function () { renderDieline(); }, 150);
- });
- }
- /* ---------------- 初始化 ---------------- */
- function init() {
- document.body.setAttribute('data-build', '1.2.0');
- window.__PL_BUILD = '1.2.0';
- if (window.PL.box3d) {
- main3d = window.PL.box3d.create($('#boxScene'), {
- onFacePick: function (face) {
- state.selectedFace = face;
- state.selectedItemId = null;
- commit(false);
- renderSideThumb();
- setMode('2d');
- }
- });
- mini3d = window.PL.box3d.create($('#bxMiniStage'), {
- mini: true,
- onInteract: function () { setMiniAuto(false); }
- });
- // 迷你 3D 默认自动播放(CSS 合成器动画,不受 JS 节流影响),拖拽后停止,点按钮恢复
- setMiniAuto(true);
- }
- window.__boxDebug = {
- get main3d() { return main3d; },
- get mini3d() { return mini3d; },
- state: state,
- dieline: dieline,
- renderAll: renderAll
- };
- // 默认外观:正面放一个示例文字
- if (!(curFaces().front.items || []).length && !(curFaces().front.color)) {
- curFaces().front.items = [{
- id: 'demo1', type: 'text', text: 'POUCHLAB', size: 12, weight: 800,
- color: '#17140f', align: 'center', x: 50, y: 42, lineHeight: 1.2
- }, {
- id: 'demo2', type: 'text', text: '反向插锁盒 · 120×80×180mm', size: 4, weight: 400,
- color: '#8a8478', align: 'center', x: 50, y: 52
- }];
- }
- bind();
- fit2d();
- setMode('2d');
- setTab('box');
- commit(false);
- updateHistoryBtns();
- setTimeout(function () { fit2d(); renderMini(); }, 150);
- }
- init();
- })();
|