box.js 145 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930
  1. /**
  2. * box.js — 3D 云设计编辑器(纸盒)主逻辑
  3. * 全面对标包小盒设计器:盒型库 / 模板 / 素材 / 文字 / 工具(条码·二维码) / 上传 / 图层 / 帮助
  4. * 2D刀版画布 + 3D预览动效 / 智能参数宝 / 导出(设计文件·效果图·视频) / 印刷下单
  5. */
  6. (function () {
  7. const D = window.PL.data;
  8. const R = window.PL.render;
  9. const UI = window.PL.ui;
  10. const h = UI.h;
  11. const A = UI.antd;
  12. const LB = window.PL.boxlib;
  13. const QR = window.PL.qrcode;
  14. const KEY = 'pouchlab.box.v2';
  15. const LIST_KEY = 'pouchlab.box.plans';
  16. const HIST_KEY = 'pouchlab.box.history';
  17. const $ = function (sel) { return document.querySelector(sel); };
  18. const clamp = function (v, a, b) { return Math.min(b, Math.max(a, v)); };
  19. function BoxTextField(props) {
  20. const [val, setVal] = React.useState(props.value == null ? '' : String(props.value));
  21. React.useEffect(function () { setVal(props.value == null ? '' : String(props.value)); }, [props.value]);
  22. return h(A.Input, {
  23. value: val,
  24. placeholder: props.placeholder,
  25. onChange: function (e) { setVal(e.target.value); if (props.onInput) props.onInput(e.target.value); },
  26. onBlur: function () { if (props.onCommit) props.onCommit(); }
  27. });
  28. }
  29. const FACES = [
  30. { id: 'front', name: '前面' }, { id: 'right', name: '右面' }, { id: 'back', name: '背面' },
  31. { id: 'left', name: '左面' }, { id: 'top', name: '顶面' }, { id: 'bottom', name: '底面' }
  32. ];
  33. /* 材质(对标包小盒「350g白卡(0.5mm)」命名) */
  34. const MATERIALS = [
  35. { 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' },
  36. { 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' },
  37. { 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' },
  38. { 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 }
  39. ];
  40. /* 印色(对标包小盒印刷报价:四色/四色+1专/四色+2专/不印刷) */
  41. const PRINTS = [
  42. { id: 'cmyk', name: '四色', factor: 1 },
  43. { id: 'cmyk1', name: '四色+1专', factor: 1.18 },
  44. { id: 'cmyk2', name: '四色+2专', factor: 1.36 },
  45. { id: 'none', name: '不印刷', factor: 0.34 }
  46. ];
  47. const PRINT_WAYS = ['胶印合版', '胶印专版', '数码印刷'];
  48. /* 结构元数据 + 智能参数宝高级参数 */
  49. const STRUCTS = {
  50. carton: { name: '卡纸折叠盒', en: 'FOLDING CARTON', fee: 0.35, advanced: ['glue'] },
  51. rsc: { name: '平口箱', en: 'REGULAR SLOTTED CONTAINER', fee: 0.3, advanced: ['glue'] },
  52. tuck: { name: '反向插锁盒', en: 'REVERSE TUCK END', fee: 0.5, advanced: ['glue', 'tuckH', 'cornerR'] },
  53. straight: { name: '直插盒', en: 'STRAIGHT TUCK END', fee: 0.5, advanced: ['glue', 'tuckH', 'cornerR'] },
  54. autobottom: { name: '扣底盒', en: 'AUTO-LOCK BOTTOM', fee: 0.55, advanced: ['glue', 'cornerR'] },
  55. mailbox: { name: '磁吸书型盒', en: 'MAGNETIC BOOK BOX', fee: 1.6, advanced: ['lipW'] },
  56. mailer: { name: '飞机盒', en: 'MAILER BOX', fee: 0.7, advanced: ['tuckH', 'dustW'] },
  57. drawer: { name: '抽屉盒', en: 'DRAWER BOX', fee: 1.1, advanced: [] },
  58. bag: { name: '手提袋', en: 'PAPER BAG', fee: 0.9, advanced: ['topFold', 'holeR'] },
  59. sleeve: { name: '封套', en: 'SLEEVE', fee: 0.4, advanced: ['glue'] },
  60. card: { name: '卡牌/吊牌/标签', en: 'CARD & TAG', fee: 0.12, advanced: ['cornerR', 'holeR'] }
  61. };
  62. const ADV_FIELDS = {
  63. glue: { key: 'glue', code: 'G', name: '糊口长', unit: 'mm', min: 8, max: 40 },
  64. tuckH: { key: 'tuckH', code: 'C', name: '插舌长', unit: 'mm', min: 6, max: 24 },
  65. cornerR: { key: 'cornerR', code: 'R', name: '倒角', unit: 'mm', min: 0, max: 8, step: 0.1 },
  66. dustW: { key: 'dustW', code: 'AX', name: '槽口宽', unit: 'mm', min: 8, max: 24 },
  67. lipW: { key: 'lipW', code: 'OF', name: '沿口宽', unit: 'mm', min: 8, max: 30 },
  68. topFold: { key: 'topFold', code: 'A', name: '顶折边', unit: 'mm', min: 12, max: 40 },
  69. holeR: { key: 'holeR', code: 'E', name: '孔半径', unit: 'mm', min: 2, max: 8, step: 0.5 }
  70. };
  71. /* ---------------- 状态 ---------------- */
  72. function blankFaces() {
  73. const o = {};
  74. ['outer', 'inner'].forEach(function (side) {
  75. o[side] = {};
  76. FACES.forEach(function (f) { o[side][f.id] = { color: '', texture: null, items: [] }; });
  77. });
  78. return o;
  79. }
  80. const state = {
  81. planId: 'p' + Date.now().toString(36),
  82. name: '未命名纸盒',
  83. boxNo: '100010',
  84. structure: 'tuck',
  85. material: 'card',
  86. print: 'cmyk',
  87. printWay: '胶印合版',
  88. w: 120, d: 80, h: 180,
  89. qty: 1000,
  90. smart: { bleed: 3, glue: 15, tuckH: 12, cornerR: 1.5, dustW: 14, lipW: 16, topFold: 22, holeR: 4 },
  91. side: 'outer',
  92. faces: blankFaces(),
  93. selectedFace: 'front',
  94. selectedItemId: null,
  95. mode: '2d',
  96. showLines: true,
  97. autoRotate: false,
  98. uploads: [],
  99. view2d: { zoom: 0.6, panX: 0, panY: 0, preview: false }
  100. };
  101. try {
  102. const saved = JSON.parse(localStorage.getItem(KEY) || 'null');
  103. if (saved && saved.faces) {
  104. Object.assign(state, saved);
  105. const f = blankFaces();
  106. ['outer', 'inner'].forEach(function (side) {
  107. FACES.forEach(function (face) {
  108. const src = (saved.faces[side] && saved.faces[side][face.id]) || (side === 'outer' && saved.faces[face.id]) || {};
  109. const dst = f[side][face.id];
  110. dst.color = src.color || '';
  111. dst.texture = src.texture || null;
  112. let items = Array.isArray(src.items) ? src.items.slice() : [];
  113. (src.texts || []).forEach(function (t) { items.push(Object.assign({ type: 'text' }, t)); });
  114. if (src.image) items.push(Object.assign({ type: 'image' }, src.image));
  115. dst.items = items;
  116. });
  117. });
  118. state.faces = f;
  119. if (!Array.isArray(state.uploads)) state.uploads = [];
  120. }
  121. } catch (e) {}
  122. /* AI 设计师(首页 Agent)交接:应用其生成的盒子方案(外侧 6 面) */
  123. try {
  124. const rawH = localStorage.getItem('pouchlab.agent.handoff');
  125. if (rawH) {
  126. localStorage.removeItem('pouchlab.agent.handoff');
  127. const h = JSON.parse(rawH);
  128. const s = h && h.state;
  129. if (s && s.kind === 'box' && s.box) {
  130. const b = s.box;
  131. if (b.structure && STRUCTS[b.structure]) state.structure = b.structure;
  132. if (b.w) { state.w = b.w; state.d = b.d; state.h = b.h; }
  133. if (b.material) state.material = b.material;
  134. if (b.qty) state.qty = b.qty;
  135. state.side = 'outer';
  136. if (b.faces) {
  137. FACES.forEach(function (face) {
  138. const rd = b.faces[face.id];
  139. const fd = state.faces.outer[face.id];
  140. if (!rd) return;
  141. fd.color = rd.color || fd.color;
  142. fd.items = (rd.items || []).map(function (it) {
  143. it.id = 'i' + Date.now().toString(36) + Math.random().toString(36).slice(2, 5);
  144. return it;
  145. });
  146. });
  147. }
  148. setTimeout(function () { UI.message.success('已载入 AI 设计师整套方案,可继续微调'); }, 700);
  149. }
  150. }
  151. } catch (e) {}
  152. function material() { return MATERIALS.find(function (m) { return m.id === state.material; }) || MATERIALS[0]; }
  153. function print() { return PRINTS.find(function (p) { return p.id === state.print; }) || PRINTS[0]; }
  154. function struct() { return STRUCTS[state.structure] || STRUCTS.tuck; }
  155. function libEntry() { return LB.boxById(state.boxNo) || LB.BOXLIB[0]; }
  156. function curFaces() { return state.faces[state.side]; }
  157. function curFace() { return curFaces()[state.selectedFace]; }
  158. /* ---------------- 撤销 / 重做 ---------------- */
  159. const undoStack = [], redoStack = [];
  160. let suspending = false;
  161. 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 }); }
  162. function pushUndo() {
  163. if (suspending) return;
  164. undoStack.push(snapshot());
  165. if (undoStack.length > 60) undoStack.shift();
  166. redoStack.length = 0;
  167. updateHistoryBtns();
  168. }
  169. function restore(str) {
  170. suspending = true;
  171. const data = JSON.parse(str);
  172. Object.assign(state, data);
  173. const f = blankFaces();
  174. ['outer', 'inner'].forEach(function (side) {
  175. FACES.forEach(function (face) {
  176. const src = (data.faces[side] && data.faces[side][face.id]) || {};
  177. f[side][face.id] = { color: src.color || '', texture: src.texture || null, items: src.items || [] };
  178. });
  179. });
  180. state.faces = f;
  181. suspending = false;
  182. commit(false);
  183. }
  184. function undo() {
  185. if (!undoStack.length) return;
  186. redoStack.push(snapshot());
  187. restore(undoStack.pop());
  188. updateHistoryBtns();
  189. }
  190. function redo() {
  191. if (!redoStack.length) return;
  192. undoStack.push(snapshot());
  193. restore(redoStack.pop());
  194. updateHistoryBtns();
  195. }
  196. function updateHistoryBtns() {
  197. $('#bxUndoBtn').disabled = !undoStack.length;
  198. $('#bxRedoBtn').disabled = !redoStack.length;
  199. }
  200. /* ---------------- 刀版生成 ---------------- */
  201. function rect(x, y, w, hh, face, kind) { return { x: x, y: y, w: w, h: hh, face: face, kind: kind || 'body' }; }
  202. function poly(points, face, kind) {
  203. 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 };
  204. }
  205. function panelBounds(p) {
  206. if (!p.poly) return { x: p.x, y: p.y, w: p.w, h: p.h };
  207. const xs = p.poly.map(function (pt) { return pt[0]; });
  208. const ys = p.poly.map(function (pt) { return pt[1]; });
  209. const x = Math.min.apply(null, xs), y = Math.min.apply(null, ys);
  210. return { x: x, y: y, w: Math.max.apply(null, xs) - x, h: Math.max.apply(null, ys) - y };
  211. }
  212. const ACCESSORY = { glue: 1, flap: 1, dust: 1, tuck: 1, lip: 1 };
  213. function isBodyKind(k) { return !ACCESSORY[k]; }
  214. function panelEdges(p) {
  215. 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]];
  216. const out = [];
  217. for (let i = 0; i < pts.length; i += 1) {
  218. const a = pts[i], b = pts[(i + 1) % pts.length];
  219. 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]) });
  220. 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]) });
  221. }
  222. return out;
  223. }
  224. function sharedEdge(a, b) {
  225. let best = null;
  226. panelEdges(a).forEach(function (ea) {
  227. panelEdges(b).forEach(function (eb) {
  228. if (ea.axis !== eb.axis || Math.abs(ea.c - eb.c) > 0.6) return;
  229. const lo = Math.max(ea.lo, eb.lo), hi = Math.min(ea.hi, eb.hi), len = hi - lo;
  230. if (len <= 2) return;
  231. if (!best || len > best.len) best = { axis: ea.axis, c: ea.c, lo: lo, hi: hi, len: len };
  232. });
  233. });
  234. return best;
  235. }
  236. function canHinge(a, b) {
  237. const ka = a.kind || 'body', kb = b.kind || 'body';
  238. if (isBodyKind(ka) !== isBodyKind(kb)) return true;
  239. if (isBodyKind(ka) && isBodyKind(kb)) return true;
  240. return (ka === 'tuck' && kb === 'flap') || (ka === 'flap' && kb === 'tuck');
  241. }
  242. function autoFolds(panels) {
  243. const out = [];
  244. for (let i = 0; i < panels.length; i += 1) for (let j = i + 1; j < panels.length; j += 1) {
  245. if (!canHinge(panels[i], panels[j])) continue;
  246. const e = sharedEdge(panels[i], panels[j]);
  247. if (!e) continue;
  248. if (e.axis === 'v') out.push({ x1: e.c, y1: e.lo, x2: e.c, y2: e.hi });
  249. else out.push({ x1: e.lo, y1: e.c, x2: e.hi, y2: e.c });
  250. }
  251. return out;
  252. }
  253. function finishDieline(panels) {
  254. let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity;
  255. panels.forEach(function (p) {
  256. const b = panelBounds(p);
  257. minX = Math.min(minX, b.x); minY = Math.min(minY, b.y);
  258. maxX = Math.max(maxX, b.x + b.w); maxY = Math.max(maxY, b.y + b.h);
  259. });
  260. 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 } };
  261. }
  262. function roundedRectPoly(x, y, w, hh, r) {
  263. r = Math.min(r, w / 2, hh / 2);
  264. if (r <= 0.05) return [[x, y], [x + w, y], [x + w, y + hh], [x, y + hh]];
  265. const pts = [];
  266. const arc = function (cx, cy, a0, a1) {
  267. for (let i = 0; i <= 6; i += 1) {
  268. const a = a0 + (a1 - a0) * i / 6;
  269. pts.push([cx + r * Math.cos(a), cy + r * Math.sin(a)]);
  270. }
  271. };
  272. arc(x + w - r, y + r, -Math.PI / 2, 0);
  273. arc(x + w - r, y + hh - r, 0, Math.PI / 2);
  274. arc(x + r, y + hh - r, Math.PI / 2, Math.PI);
  275. arc(x + r, y + r, Math.PI, Math.PI * 1.5);
  276. return pts;
  277. }
  278. function circlePoly(cx, cy, r) {
  279. const pts = [];
  280. for (let i = 0; i < 36; i += 1) {
  281. const a = i / 36 * Math.PI * 2;
  282. pts.push([cx + r * Math.cos(a), cy + r * Math.sin(a)]);
  283. }
  284. return pts;
  285. }
  286. function buildDieline(type, w, d, hh, params) {
  287. const t = material().thickness;
  288. const W = w + t * 2, D2 = d + t * 2, H = hh + t * 2;
  289. const P = params || state.smart;
  290. const panels = [];
  291. if (type === 'card') {
  292. const isRound = state.boxNo === '260040' || state.boxNo === '270020' || state.boxNo === '261002';
  293. const hole = P.holeR || 0;
  294. const p1 = isRound
  295. ? poly(circlePoly(W / 2, H / 2, Math.min(W, H) / 2), 'front', 'body')
  296. : poly(roundedRectPoly(0, 0, W, H, P.cornerR || 0), 'front', 'body');
  297. if (hole && !isRound) {
  298. p1.holes = [{ x: W / 2, y: hole + 4, r: hole }];
  299. p1.holeH = hole * 2 + 8;
  300. }
  301. panels.push(p1);
  302. const back = isRound
  303. ? poly(circlePoly(W / 2, H / 2, Math.min(W, H) / 2), 'back', 'body')
  304. : poly(roundedRectPoly(W + 10, 0, W, H, P.cornerR || 0), 'back', 'body');
  305. panels.push(back);
  306. return finishDieline(panels);
  307. }
  308. if (type === 'sleeve') {
  309. const glue = P.glue;
  310. let x = 0;
  311. panels.push(rect(x, 0, glue, H, null, 'glue')); x += glue;
  312. panels.push(rect(x, 0, W, H, 'front', 'body')); x += W;
  313. panels.push(rect(x, 0, D2, H, null, 'flap')); x += D2;
  314. panels.push(rect(x, 0, W, H, 'back', 'body')); x += W;
  315. panels.push(rect(x, 0, D2, H, null, 'flap'));
  316. return finishDieline(panels);
  317. }
  318. if (type === 'bag') {
  319. const tf = P.topFold || 20;
  320. const holeR = P.holeR || 4;
  321. const gus = D2 / 2;
  322. let x = 0;
  323. panels.push(rect(x, 0, W, H, 'front', 'body'));
  324. panels.push(rect(x, -tf, W, tf, null, 'flap'));
  325. const fP = panels[0], fT = panels[1];
  326. 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 }];
  327. x += W;
  328. panels.push(rect(x, 0, gus, H, null, 'body')); x += gus;
  329. panels.push(rect(x, 0, gus, H, null, 'body')); x += gus;
  330. panels.push(rect(x, 0, W, H, 'back', 'body'));
  331. panels.push(rect(x, -tf, W, tf, null, 'flap'));
  332. 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 }];
  333. x += W;
  334. panels.push(rect(x, 0, gus, H, null, 'body')); x += gus;
  335. panels.push(rect(x, 0, gus, H, null, 'body'));
  336. panels.push(rect(0, H, W, D2, 'bottom', 'body'));
  337. return finishDieline(panels);
  338. }
  339. // 管式盒族
  340. const glue = P.glue;
  341. const ch = Math.max(3, Math.min(8, D2 * 0.06)) * (1 - Math.min(1, (P.cornerR || 0) / 8) * 0.5);
  342. const half = D2 / 2;
  343. const xF = glue, xR = xF + W, xB = xR + D2, xL = xB + W;
  344. panels.push(rect(0, 0, glue, H, null, 'glue'));
  345. panels.push(rect(xF, 0, W, H, 'front', 'body'));
  346. panels.push(rect(xR, 0, D2, H, 'right', 'body'));
  347. panels.push(rect(xB, 0, W, H, 'back', 'body'));
  348. panels.push(rect(xL, 0, D2, H, 'left', 'body'));
  349. const big = function (x, y, face, dir) {
  350. const yy = dir * (half + 2);
  351. return poly([[x, y], [x + ch, y + yy], [x + W - ch, y + yy], [x + W, y]], face, 'flap');
  352. };
  353. const dust = function (x, y, dir) {
  354. const yy = dir * (half - 2);
  355. return poly([[x, y], [x + ch, y + yy], [x + D2 - ch, y + yy], [x + D2, y]], null, 'dust');
  356. };
  357. const tuckH = P.tuckH;
  358. if (type === 'rsc') {
  359. [[xF, W, 'top', true], [xR, D2, null, false], [xB, W, null, false], [xL, D2, null, false]].forEach(function (f) {
  360. panels.push(rect(f[0], -half, f[1], half, f[2], 'flap'));
  361. panels.push(rect(f[0], H, f[1], half, f[3] ? 'bottom' : null, 'flap'));
  362. });
  363. } else if (type === 'carton') {
  364. panels.push(big(xF, 0, 'top', -1));
  365. panels.push(big(xB, 0, null, -1));
  366. panels.push(dust(xR, 0, -1));
  367. panels.push(dust(xL, 0, -1));
  368. panels.push(big(xF, H, 'bottom', 1));
  369. panels.push(big(xB, H, null, 1));
  370. panels.push(dust(xR, H, 1));
  371. panels.push(dust(xL, H, 1));
  372. } else if (type === 'mailer') {
  373. const dustW = P.dustW;
  374. panels.push(poly([[xB, 0], [xB + ch, -(D2 + 2)], [xB + W - ch, -(D2 + 2)], [xB + W, 0]], 'top', 'flap'));
  375. const mt = rect(xB + dustW, -(D2 + 2) - tuckH, W - dustW * 2, tuckH, null, 'tuck');
  376. if ((P.holeR || 0) > 1 && tuckH > (P.holeR || 4) * 2 + 1) {
  377. mt.holes = [{ x: xB + dustW + (W - dustW * 2) / 2, y: -(D2 + 2) - tuckH / 2, r: P.holeR }];
  378. }
  379. panels.push(mt);
  380. panels.push(rect(xB - dustW, -(D2 + 2), dustW, D2, null, 'dust'));
  381. panels.push(rect(xB + W, -(D2 + 2), dustW, D2, null, 'dust'));
  382. panels.push(poly([[xF, H], [xF + ch, H + D2 + 2], [xF + W - ch, H + D2 + 2], [xF + W, H]], 'bottom', 'flap'));
  383. const mb = rect(xF + dustW, H + D2 + 2, W - dustW * 2, tuckH, null, 'tuck');
  384. if ((P.holeR || 0) > 1 && tuckH > (P.holeR || 4) * 2 + 1) {
  385. mb.holes = [{ x: xF + dustW + (W - dustW * 2) / 2, y: H + D2 + 2 + tuckH / 2, r: P.holeR }];
  386. }
  387. panels.push(mb);
  388. panels.push(rect(xF - dustW, H + D2 + 2, dustW, D2, null, 'dust'));
  389. panels.push(rect(xF + W, H + D2 + 2, dustW, D2, null, 'dust'));
  390. } else {
  391. // tuck / straight / autobottom:上盖挂后板
  392. const lidD = D2 + 2;
  393. panels.push(poly([[xB, 0], [xB + ch, -lidD], [xB + W - ch, -lidD], [xB + W, 0]], 'top', 'flap'));
  394. const tuckTop = rect(xB + 18, -lidD - tuckH, W - 36, tuckH, null, 'tuck');
  395. if ((P.holeR || 0) > 1 && tuckH > (P.holeR || 4) * 2 + 1) {
  396. tuckTop.holes = [{ x: xB + W / 2, y: -lidD - tuckH / 2, r: P.holeR }];
  397. }
  398. panels.push(tuckTop);
  399. panels.push(dust(xR, 0, -1));
  400. panels.push(dust(xL, 0, -1));
  401. if (type === 'straight') {
  402. panels.push(poly([[xB, H], [xB + ch, H + lidD], [xB + W - ch, H + lidD], [xB + W, H]], 'bottom', 'flap'));
  403. const tuckBot = rect(xB + 18, H + lidD, W - 36, tuckH, null, 'tuck');
  404. if ((P.holeR || 0) > 1 && tuckH > (P.holeR || 4) * 2 + 1) {
  405. tuckBot.holes = [{ x: xB + W / 2, y: H + lidD + tuckH / 2, r: P.holeR }];
  406. }
  407. panels.push(tuckBot);
  408. panels.push(dust(xR, H, 1));
  409. panels.push(dust(xL, H, 1));
  410. } else if (type === 'autobottom') {
  411. const d1 = half + 5, d2 = half + 2, c2 = ch * 0.6;
  412. panels.push(poly([
  413. [xF, H], [xF + c2, H + d1], [xF + W * 0.32, H + d1], [xF + W * 0.32, H + d1 - 4],
  414. [xF + W * 0.68, H + d1 - 4], [xF + W * 0.68, H + d1], [xF + W - c2, H + d1], [xF + W, H]
  415. ], 'bottom', 'flap'));
  416. panels.push(poly([[xB, H], [xB + c2, H + d2], [xB + W - c2, H + d2], [xB + W, H]], null, 'flap'));
  417. panels.push(poly([[xR, H], [xR + D2, H], [xR + D2 / 2, H + half + 3]], null, 'dust'));
  418. panels.push(poly([[xL, H], [xL + D2, H], [xL + D2 / 2, H + half + 3]], null, 'dust'));
  419. } else {
  420. // tuck 反向插锁:下盖挂前板
  421. panels.push(poly([[xF, H], [xF + ch, H + lidD], [xF + W - ch, H + lidD], [xF + W, H]], 'bottom', 'flap'));
  422. panels.push(rect(xF + 18, H + lidD, W - 36, tuckH, null, 'tuck'));
  423. panels.push(dust(xR, H, 1));
  424. panels.push(dust(xL, H, 1));
  425. }
  426. }
  427. return finishDieline(panels);
  428. }
  429. if (state.structure === 'mailbox') {
  430. // mailbox 在 buildDieline 主流程外定义,包装一次
  431. }
  432. const _buildDielineBase = buildDieline;
  433. buildDieline = function (type, w, d, hh, params) {
  434. if (type === 'mailbox') {
  435. const t = material().thickness;
  436. const W = w + t * 2, D2 = d + t * 2, H = hh + t * 2;
  437. const P = params || state.smart;
  438. const lipW = P.lipW;
  439. const xRw = 0, xB = D2, xSpine = xB + W, xF = xSpine + D2;
  440. const panels = [
  441. rect(xRw, 0, D2, H, 'right', 'body'),
  442. rect(xB, 0, W, H, 'back', 'body'),
  443. rect(xSpine, 0, D2, H, 'left', 'body'),
  444. rect(xF, 0, W, H, 'front', 'body'),
  445. rect(xF + W, 0, lipW, H, null, 'lip'),
  446. rect(xB, -D2, W, D2, 'top', 'body'),
  447. rect(xB, H, W, D2, 'bottom', 'body')
  448. ];
  449. return finishDieline(panels);
  450. }
  451. if (type === 'drawer') {
  452. const t = material().thickness;
  453. const W = w + t * 2, D2 = d + t * 2, H = hh + t * 2;
  454. const glue = (params || state.smart).glue;
  455. const xF = glue, xR = xF + W, xB = xR + D2, xL = xB + W;
  456. const panels = [
  457. rect(0, 0, glue, H, null, 'glue'),
  458. rect(xF, 0, W, H, 'front', 'body'),
  459. rect(xR, 0, D2, H, 'right', 'body'),
  460. rect(xB, 0, W, H, 'back', 'body'),
  461. rect(xL, 0, D2, H, 'left', 'body')
  462. ];
  463. const W2 = Math.max(10, W - 2), D3 = Math.max(10, D2 - 2), TH = Math.max(10, H - 8);
  464. const ty = H + 26, tx0 = 24, txF = tx0 + glue, txR = txF + W2, txB = txR + D3, txL = txB + W2;
  465. panels.push(rect(tx0, ty, glue, TH, null, 'glue'));
  466. panels.push(rect(txF, ty, W2, TH, 'front', 'tray'));
  467. panels.push(rect(txR, ty, D3, TH, null, 'tray'));
  468. panels.push(rect(txB, ty, W2, TH, null, 'tray'));
  469. panels.push(rect(txL, ty, D3, TH, null, 'tray'));
  470. panels.push(rect(txF, ty + TH, W2, D3, null, 'bottom'));
  471. return finishDieline(panels);
  472. }
  473. return _buildDielineBase(type, w, d, hh, params);
  474. };
  475. function dieline() { return buildDieline(state.structure, state.w, state.d, state.h); }
  476. function outerSize() {
  477. const t = material().thickness;
  478. return { w: state.w + t * 2, d: state.d + t * 2, h: state.h + t * 2 };
  479. }
  480. /* ---------------- 报价 ---------------- */
  481. function priceInfo() {
  482. const dl = dieline();
  483. const area = (dl.size.w * dl.size.h) / 1000000;
  484. const mat = material(), pr = print();
  485. const base = area * mat.rate * pr.factor + struct().fee;
  486. const qty = state.qty;
  487. const disc = qty >= 10000 ? 0.72 : qty >= 5000 ? 0.78 : qty >= 2000 ? 0.84 : qty >= 1000 ? 0.9 : qty >= 500 ? 0.95 : 1;
  488. const unit = base * disc;
  489. return { area: area, unit: unit, total: unit * qty, disc: disc, dl: dl };
  490. }
  491. /* ---------------- 刀版 SVG ---------------- */
  492. function faceName(id) {
  493. const f = FACES.find(function (x) { return x.id === id; });
  494. return f ? f.name : '';
  495. }
  496. function itemSvg(it, bx, by, bw, bh, mm2px) {
  497. const cx = bx + (it.x / 100) * bw, cy = by + (it.y / 100) * bh;
  498. if (it.hidden) return { art: '', hit: '' };
  499. // 内侧版面整体镜像(相当于从背面看印刷面),元素随之翻转
  500. function hitRect(x, y, w, h) {
  501. 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"/>';
  502. }
  503. if (it.type === 'text') {
  504. const anchor = it.align === 'center' ? 'middle' : it.align === 'right' ? 'end' : 'start';
  505. const lines = String(it.text || '').split('\n');
  506. const fs = it.size * mm2px;
  507. const lh = (it.lineHeight || 1.25) * fs;
  508. let out = '', maxW = 0;
  509. lines.forEach(function (line, li) {
  510. const tw = String(line).split('').reduce(function (s, ch) { return s + (/[\x00-\xff]/.test(ch) ? 0.56 : 1) * fs; }, 0);
  511. if (tw > maxW) maxW = tw;
  512. 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>';
  513. });
  514. maxW = Math.max(maxW, fs * 2);
  515. const totalH = Math.max(lines.length * lh, fs);
  516. const left = anchor === 'start' ? cx : anchor === 'end' ? cx - maxW : cx - maxW / 2;
  517. return { art: out, hit: hitRect(left, cy - totalH / 2, maxW, totalH) };
  518. }
  519. if (it.type === 'image' || it.type === 'asset') {
  520. const iw = ((it.w == null ? 60 : it.w) / 100) * bw;
  521. 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) };
  522. }
  523. if (it.type === 'barcode') {
  524. const iw = ((it.w || 40) / 100) * bw;
  525. const ih = iw * 0.84;
  526. 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) };
  527. }
  528. return { art: '', hit: '' };
  529. }
  530. function dielineSVG(opts) {
  531. opts = opts || {};
  532. const dl = dieline();
  533. const mat = material();
  534. const pad = 30;
  535. const bleed = state.smart.bleed || 0;
  536. const inner = state.side === 'inner';
  537. const uid = opts.idPrefix || 'dl';
  538. const vbW = dl.size.w + pad * 2 + bleed * 2;
  539. const vbH = dl.size.h + pad * 2 + bleed * 2 + (opts.noLegend ? 0 : 56);
  540. const off = function (x, y) { return [x - dl.minX + pad + bleed, y - dl.minY + pad + bleed]; };
  541. let body = '', defs = '', art = '', hit = '', itemHits = '', notes = '';
  542. const useMatPattern = state.material === 'corrugated' || state.material === 'kraft';
  543. if (useMatPattern) {
  544. defs += '<pattern id="' + uid + '-mat" width="5" height="5" patternUnits="userSpaceOnUse">' +
  545. '<rect width="5" height="5" fill="' + mat.paper + '"/>' +
  546. '<line x1="0.6" y1="0" x2="0.6" y2="5" stroke="' + mat.flute + '" stroke-width="1" opacity="0.55"/></pattern>';
  547. }
  548. const matFill = useMatPattern ? 'url(#' + uid + '-mat)' : mat.paper;
  549. // 结构件(防尘翼/插舌/糊口等)不印刷:素纸色 + 45° 斜线纹理,与印刷面区分
  550. defs += '<pattern id="' + uid + '-acc" width="7" height="7" patternUnits="userSpaceOnUse" patternTransform="rotate(45)">' +
  551. '<rect width="7" height="7" fill="' + mat.paper + '"/>' +
  552. '<line x1="0" y1="0" x2="0" y2="7" stroke="' + mat.flute + '" stroke-width="1.4" opacity="0.5"/></pattern>';
  553. dl.panels.forEach(function (p, i) {
  554. 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)];
  555. const cid = uid + '-p' + i;
  556. const f = p.face ? curFaces()[p.face] : null;
  557. const plain = curFaces()._plain || {};
  558. const isAcc = ACCESSORY[p.kind] && !p.face; // 有 face 的面(如飞机盒顶/底盖)可印刷,不算结构件
  559. let panelFill;
  560. if (isAcc) {
  561. panelFill = 'url(#' + uid + '-acc)';
  562. } else if (f) {
  563. panelFill = f.color || (f.texture ? 'url(#' + uid + '-tex' + i + ')' : matFill);
  564. } else {
  565. panelFill = plain.color || matFill;
  566. }
  567. if (f && f.texture) {
  568. defs += '<pattern id="' + uid + '-tex' + i + '" width="60" height="60" patternUnits="userSpaceOnUse"><image href="' + f.texture + '" width="60" height="60"/></pattern>';
  569. }
  570. const points = pts.map(function (pt) { return pt[0].toFixed(2) + ',' + pt[1].toFixed(2); }).join(' ');
  571. const shape = p.poly ? '<polygon points="' + points + '"/>' : '<rect x="' + pts[0][0] + '" y="' + pts[0][1] + '" width="' + (p.w || 0) + '" height="' + (p.h || 0) + '"/>';
  572. defs += '<clipPath id="' + cid + '">' + shape + '</clipPath>';
  573. const picked = p.face && p.face === state.selectedFace ? ' is-picked' : '';
  574. body += '<polygon class="dieline-panel' + picked + '" data-face="' + (p.face || '') + '" data-panel="' + i + '" fill="' + panelFill + '" points="' + points + '"/>';
  575. if (p.holes) {
  576. p.holes.forEach(function (ho, hi) {
  577. const c = off(ho.x, ho.y);
  578. art += '<circle cx="' + c[0].toFixed(2) + '" cy="' + c[1].toFixed(2) + '" r="' + ho.r + '" fill="#fff" stroke="#c2451f" stroke-width="0.5"/>';
  579. if (!opts.clean) {
  580. // 圆心十字定位线(超出孔径 2.5mm)+ 孔径标注;标注放在镜像组外,避免文字反写
  581. const ext = ho.r + 2.5;
  582. const mx = inner ? vbW - c[0] : c[0];
  583. notes += '<g class="dieline-dim">' +
  584. '<path d="M' + (mx - ext).toFixed(2) + ' ' + c[1].toFixed(2) + 'H' + (mx + ext).toFixed(2) + '"/>' +
  585. '<path d="M' + mx.toFixed(2) + ' ' + (c[1] - ext).toFixed(2) + 'V' + (c[1] + ext).toFixed(2) + '"/>' +
  586. '<circle cx="' + mx.toFixed(2) + '" cy="' + c[1].toFixed(2) + '" r="0.5" fill="#c2451f" stroke="none"/>' +
  587. '</g>' +
  588. '<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>';
  589. }
  590. });
  591. }
  592. if (p.face && f) {
  593. const b = panelBounds(p);
  594. (f.items || []).forEach(function (it) {
  595. it._face = p.face;
  596. const r = itemSvg(it, b.x, b.y, b.w, b.h, 1);
  597. const tx = 'translate(' + (pad + bleed - dl.minX) + ',' + (pad + bleed - dl.minY) + ')';
  598. art += '<g clip-path="url(#' + cid + ')"><g transform="' + tx + '">' + r.art + '</g></g>';
  599. itemHits += '<g clip-path="url(#' + cid + ')"><g transform="' + tx + '">' + r.hit + '</g></g>';
  600. });
  601. const cx = off(b.x + b.w / 2, b.y + b.h / 2);
  602. 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>';
  603. hit += '<polygon class="dieline-hit" data-face="' + p.face + '" points="' + points + '" fill="transparent"/>';
  604. }
  605. });
  606. let foldBody = '';
  607. if (state.showLines && !opts.clean) {
  608. dl.folds.forEach(function (f) {
  609. const a = off(f.x1, f.y1), b = off(f.x2, f.y2);
  610. 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) + '"/>';
  611. });
  612. }
  613. let dims = '';
  614. if (!opts.clean) {
  615. const dimTop = pad, dimBottom = pad + dl.size.h;
  616. dims =
  617. '<g class="dieline-dim"><path d="M' + (pad - 8) + ' ' + dimTop + 'V' + dimBottom + '"/><path d="M' + (pad - 11) + ' ' + dimTop + 'h6M' + (pad - 11) + ' ' + dimBottom + 'h6"/></g>' +
  618. '<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>' +
  619. '<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>' +
  620. '<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>';
  621. // 每个印刷面内标注该面的宽 × 高(mm);poly 面(梯形盖等)动态算外接框、文字置于底部
  622. const FACE_NAMES = { front: '正面', back: '背面', left: '左', right: '右', top: '顶', bottom: '底' };
  623. dl.panels.forEach(function (p) {
  624. if (!p.face) return;
  625. let bw = p.w, bh = p.h, bx = p.x, by = p.y;
  626. if (p.poly) { // poly() 构造的 w/h 为 0,动态求外接框
  627. let minX = 1e9, minY = 1e9, maxX = -1e9, maxY = -1e9;
  628. p.poly.forEach(function (pt) {
  629. minX = Math.min(minX, pt[0]); maxX = Math.max(maxX, pt[0]);
  630. minY = Math.min(minY, pt[1]); maxY = Math.max(maxY, pt[1]);
  631. });
  632. bx = minX; by = minY; bw = maxX - minX; bh = maxY - minY;
  633. }
  634. if (!bw || !bh) return;
  635. const cx = bx + bw / 2;
  636. const isPoly = !!p.poly;
  637. const fs = Math.max(4.2, Math.min(8, bw / 9));
  638. const label = FACE_NAMES[p.face] ? FACE_NAMES[p.face] + ' ' : '';
  639. const cy = isPoly ? by + bh - fs * 0.9 : by + bh / 2;
  640. 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>';
  641. });
  642. if (bleed) {
  643. dims += '<rect class="dieline-bleed" x="' + (pad - bleed) + '" y="' + (pad - bleed) + '" width="' + (dl.size.w + bleed * 2) + '" height="' + (dl.size.h + bleed * 2) + '"/>';
  644. }
  645. }
  646. 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>' +
  647. '<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>' +
  648. '<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>' +
  649. '<text data-ui="1" class="dieline-cut-label" x="' + (pad + 330) + '" y="' + (pad + dl.size.h + 33) + '">' + (inner ? '内侧设计 · 镜像' : '外侧设计') + ' · 模型ID ' + state.boxNo + '</text>';
  650. const mirror = inner ? ' transform="translate(' + vbW + ',0) scale(-1,1)"' : '';
  651. // 只有几何与画面内容参与镜像;文字标注、尺寸、图例放在镜像组外,保持可读
  652. return '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ' + vbW + ' ' + vbH + '"><defs>' + defs + '</defs>' +
  653. '<g' + mirror + '>' + body + foldBody + art + hit + itemHits + '</g>' +
  654. notes + dims + legend + '</svg>';
  655. }
  656. /* ---------------- 保存 / 方案 ---------------- */
  657. function save(quiet) {
  658. try {
  659. localStorage.setItem(KEY, JSON.stringify(state));
  660. if (!quiet) {
  661. const el = $('#bxSaveState');
  662. }
  663. } catch (e) {
  664. UI.message.warning('本地保存空间不足');
  665. }
  666. }
  667. function plansList() {
  668. try { return JSON.parse(localStorage.getItem(LIST_KEY) || '[]'); } catch (e) { return []; }
  669. }
  670. function savePlanToLibrary() {
  671. const list = plansList().filter(function (p) { return p.id !== state.planId; });
  672. list.unshift({ id: state.planId, name: state.name, time: Date.now(), boxNo: state.boxNo });
  673. try { localStorage.setItem(LIST_KEY, JSON.stringify(list.slice(0, 30))); } catch (e) {}
  674. }
  675. function planDataKey(id) { return 'pouchlab.box.plan.' + id; }
  676. function commit(pushHistory) {
  677. if (pushHistory !== false) pushUndo();
  678. save(true);
  679. savePlanToLibrary();
  680. try { localStorage.setItem(planDataKey(state.planId), JSON.stringify(state)); } catch (e) {}
  681. // 历史版本
  682. try {
  683. const hk = HIST_KEY + '.' + state.planId;
  684. const hist = JSON.parse(localStorage.getItem(hk) || '[]');
  685. hist.unshift({ time: Date.now(), snap: snapshot() });
  686. localStorage.setItem(hk, JSON.stringify(hist.slice(0, 20)));
  687. } catch (e) {}
  688. renderAll();
  689. }
  690. /* ---------------- 3D 实例 ---------------- */
  691. let main3d = null, mini3d = null;
  692. let foldValue = 0, foldAnim = null;
  693. function currentPanels() { return dieline().panels; }
  694. function render3d() {
  695. if (main3d && main3d.ready()) {
  696. main3d.render(state, material(), currentPanels());
  697. main3d.setFold(foldValue / 100);
  698. return;
  699. }
  700. render3dCss();
  701. }
  702. /* CSS 3D 降级(无 Three.js 时) */
  703. function render3dCss() {
  704. const box = document.getElementById('box3d');
  705. if (!box) return;
  706. const t = material().thickness;
  707. const W = state.w + t * 2, D2 = state.d + t * 2, H = state.h + t * 2;
  708. const s = Math.min(360 / (state.w + state.d), 400 / (state.h + state.d));
  709. box.style.width = W * s + 'px';
  710. box.style.height = H * s + 'px';
  711. box.style.transform = 'rotateX(-18deg) rotateY(-32deg)';
  712. let html = '';
  713. const t2 = material().thickness;
  714. const faceT = {
  715. front: 'translateZ(' + D2 * s / 2 + 'px)',
  716. back: 'rotateY(180deg) translateZ(' + D2 * s / 2 + 'px)',
  717. right: 'rotateY(90deg) translateZ(' + W * s / 2 + 'px)',
  718. left: 'rotateY(-90deg) translateZ(' + W * s / 2 + 'px)',
  719. top: 'rotateX(90deg) translateZ(' + H * s / 2 + 'px)',
  720. bottom: 'rotateX(-90deg) translateZ(' + H * s / 2 + 'px)'
  721. };
  722. FACES.forEach(function (f) {
  723. const data = curFaces()[f.id];
  724. 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 };
  725. const bg = 'background-color:' + (data.color || material().paper);
  726. 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>';
  727. });
  728. box.innerHTML = html;
  729. }
  730. function renderMini() {
  731. if (mini3d && mini3d.ready() && state.mode === '2d') {
  732. mini3d.render(state, material(), currentPanels());
  733. mini3d.setFold(foldValue / 100);
  734. }
  735. }
  736. /* ---------------- 视图切换 ---------------- */
  737. function setMode(mode) {
  738. state.mode = mode;
  739. document.querySelectorAll('#bxModeSwitch button').forEach(function (b) {
  740. b.classList.toggle('on', b.dataset.mode === mode);
  741. });
  742. $('#bxFlat').hidden = mode !== '2d';
  743. $('#bx3dView').hidden = mode !== '3d';
  744. renderAll();
  745. }
  746. /* ---------------- 2D 画布 ---------------- */
  747. let panMode = false;
  748. let panDrag = null;
  749. function renderDieline() {
  750. const wrap = document.getElementById('boxDieline');
  751. if (!wrap) return;
  752. wrap.innerHTML = dielineSVG();
  753. const svg = wrap.querySelector('svg');
  754. if (!svg) return;
  755. const vb = svg.viewBox.baseVal;
  756. svg.style.width = vb.width + 'px';
  757. svg.style.height = vb.height + 'px';
  758. svg.style.display = 'block';
  759. const z = state.view2d.zoom;
  760. wrap.style.transform = 'translate(' + state.view2d.panX + 'px,' + state.view2d.panY + 'px) scale(' + z + ')';
  761. $('#bxZoom2dLabel').textContent = Math.round(z * 100) + ' %';
  762. }
  763. function fit2d() {
  764. const stage = $('#bxFlat');
  765. const dl = dieline();
  766. // 窄屏下左右面板改为悬浮覆盖,需按可视区(扣除面板遮挡)居中,避免刀版被面板盖住
  767. const stageRect = stage.getBoundingClientRect();
  768. let occlL = 0, occlR = 0;
  769. const panelEl = document.querySelector('.bx-panel');
  770. const propsEl = document.querySelector('.bx-props');
  771. if (panelEl && getComputedStyle(panelEl).position === 'absolute') {
  772. occlL = Math.max(0, Math.min(stage.clientWidth, panelEl.getBoundingClientRect().right - stageRect.left));
  773. }
  774. if (propsEl && getComputedStyle(propsEl).position === 'absolute') {
  775. occlR = Math.max(0, Math.min(stage.clientWidth - occlL, stageRect.right - propsEl.getBoundingClientRect().left));
  776. }
  777. const availW = Math.max(160, stage.clientWidth - occlL - occlR - 80);
  778. const availH = Math.max(200, stage.clientHeight - 120);
  779. state.view2d.zoom = clamp(Math.min(availW / dl.size.w, availH / dl.size.h), 0.1, 2.4);
  780. state.view2d.panX = Math.round((occlL - occlR) / 2);
  781. state.view2d.panY = 0;
  782. renderDieline();
  783. }
  784. /* ---------------- 工具栏 / 面板 ---------------- */
  785. let currentTab = 'box';
  786. function assetThumb(a, color) {
  787. if (a.svgDef) return '<svg viewBox="0 0 24 24" fill="none">' + a.svgDef.replace(/currentColor/g, color) + '</svg>';
  788. if (a.draw) return '<img src="' + LB.shapeDataUrl(a.draw, color, 120) + '" alt="">';
  789. return '';
  790. }
  791. function addAssetToFace(item) {
  792. const face = curFace();
  793. face.items = face.items || [];
  794. const it = Object.assign({ id: 'i' + Date.now().toString(36) + Math.random().toString(36).slice(2, 5), x: 50, y: 50, w: 45 }, item);
  795. face.items.push(it);
  796. state.selectedItemId = it.id;
  797. UI.message.success('素材已添加到「' + faceName(state.selectedFace) + '」');
  798. commit();
  799. }
  800. function panelBox() {
  801. const tab = currentTab;
  802. if (tab === 'box') return boxPanel();
  803. if (tab === 'template') return templatePanel();
  804. if (tab === 'asset') return assetPanel();
  805. if (tab === 'text') return textPanel();
  806. if (tab === 'tool') return toolPanel();
  807. if (tab === 'upload') return uploadPanel();
  808. if (tab === 'layers') return layersPanel();
  809. if (tab === 'help') return helpPanel();
  810. return null;
  811. }
  812. /* ---- 盒型面板 ---- */
  813. let boxSearch = '', boxCat = '热门', boxMine = false;
  814. function boxPanel() {
  815. const cats = LB.BOX_CATS;
  816. const list = LB.BOXLIB.filter(function (b) {
  817. if (boxMine) return true;
  818. if (boxSearch && b.name.indexOf(boxSearch) < 0 && b.no.indexOf(boxSearch) < 0) return false;
  819. if (boxCat === '热门') return b.hot >= 3;
  820. if (boxCat === '更多') return ['纸箱'].indexOf(b.cat) >= 0;
  821. return b.cat === boxCat;
  822. });
  823. return h('div', null,
  824. h('div', { className: 'bx-import-cad', onClick: function () { showImportCad(); } },
  825. h('span', { className: 'cad-ic' }, 'DXF'),
  826. h('div', null, h('b', null, '导入 CAD', h('i', { className: 'q', title: '上传盒型结构个性化设计' })), h('span', null, '上传盒型结构个性化设计'))
  827. ),
  828. h(A.Input, {
  829. prefix: h('span', { className: 'anticon' }, '🔍'),
  830. placeholder: '输入盒型关键字', value: boxSearch, allowClear: true,
  831. onChange: function (e) { boxSearch = e.target.value; renderTool(); }
  832. }),
  833. h('div', { className: 'bx-sub-tabs' },
  834. h('button', { className: boxMine ? '' : 'on', onClick: function () { boxMine = false; renderTool(); } }, '推荐盒型'),
  835. h('button', { className: boxMine ? 'on' : '', onClick: function () { boxMine = true; renderTool(); } }, '我的盒型')
  836. ),
  837. boxMine
  838. ? h('div', { className: 'p-hint', style: { padding: '18px 0' } }, '我的盒型(导入的 CAD 结构会保存在这里)' + (plansList().length ? '' : ' · 暂无'))
  839. : h('div', { className: 'bx-chips' }, cats.map(function (c) {
  840. return h('button', { key: c, className: boxCat === c ? 'on' : '', onClick: function () { boxCat = c; renderTool(); } }, c);
  841. })),
  842. !boxMine && h('div', { className: 'bx-box-grid' }, list.map(function (b) {
  843. return h('button', {
  844. key: b.no, className: 'bx-box-card' + (state.boxNo === b.no ? ' on' : ''),
  845. onClick: function () { applyLibBox(b); }
  846. },
  847. h('span', { className: 'thumb', dangerouslySetInnerHTML: { __html: structThumbSvg(b.gen, b.no) } }),
  848. h('span', { className: 'meta' },
  849. h('b', null, b.name),
  850. h('span', { className: 'no' }, b.no)
  851. ),
  852. b.sizes
  853. ? h('span', { className: 'flag sizes' }, b.sizes.length + '种固定尺寸')
  854. : h('span', { className: 'flag' }, '可改尺寸'),
  855. b.printable ? null : h('span', { className: 'flag off' }, '不可印刷')
  856. );
  857. })),
  858. !boxMine && !list.length && h(A.Empty, { description: '找不到盒型' })
  859. );
  860. }
  861. function structThumbSvg(gen, no) {
  862. const keep = { w: state.w, d: state.d, h: state.h, boxNo: state.boxNo, structure: state.structure };
  863. 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;
  864. const keepMat = state.material;
  865. state.material = 'card';
  866. let dl;
  867. try {
  868. if (preview) {
  869. state.boxNo = no; state.structure = 'card';
  870. dl = buildDieline('card', preview[0], preview[1], preview[1]);
  871. } else {
  872. state.structure = gen;
  873. dl = buildDieline(gen, 60, 40, 90);
  874. }
  875. } catch (e) { dl = null; }
  876. state.boxNo = keep.boxNo; state.structure = keep.structure; state.material = keepMat;
  877. if (!dl) return '';
  878. const pad = 4;
  879. let body = '';
  880. dl.panels.forEach(function (p) {
  881. const b = panelBounds(p);
  882. 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]];
  883. 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"/>';
  884. });
  885. dl.folds.forEach(function (f) {
  886. 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"/>';
  887. });
  888. return '<svg viewBox="0 0 ' + (dl.size.w + pad * 2) + ' ' + (dl.size.h + pad * 2) + '" preserveAspectRatio="xMidYMid meet">' + body + '</svg>';
  889. }
  890. function applyLibBox(entry) {
  891. if (state.boxNo === entry.no) return;
  892. pushUndo();
  893. state.boxNo = entry.no;
  894. state.structure = entry.gen;
  895. if (entry.sizes && entry.sizes.length) {
  896. state.w = entry.sizes[0][0];
  897. state.d = entry.sizes[0][1];
  898. state.h = entry.sizes[0][2] || state.h;
  899. }
  900. if (entry.gen === 'card') {
  901. state.h = state.h;
  902. }
  903. commit();
  904. UI.message.success('已切换到「' + entry.name + '」');
  905. }
  906. /* ---- 模板面板 ---- */
  907. let tplSearch = '', tplCat = '热门';
  908. function templatePanel() {
  909. const list = LB.TEMPLATES.filter(function (t) {
  910. if (tplSearch && t.name.indexOf(tplSearch) < 0) return false;
  911. if (tplCat === '热门') return true;
  912. return t.cat === tplCat;
  913. });
  914. return h('div', null,
  915. h(A.Input, { placeholder: '输入模板关键字', value: tplSearch, allowClear: true, onChange: function (e) { tplSearch = e.target.value; renderTool(); } }),
  916. h('div', { className: 'bx-chips' }, LB.TEMPLATE_CATS.map(function (c) {
  917. return h('button', { key: c, className: tplCat === c ? 'on' : '', onClick: function () { tplCat = c; renderTool(); } }, c);
  918. })),
  919. h('div', { className: 'bx-tpl-grid' }, list.map(function (t) {
  920. return h('button', {
  921. key: t.id, className: 'bx-tpl-card',
  922. style: { background: t.color },
  923. onClick: function () { applyTemplate(t); }
  924. },
  925. h('b', { style: { color: /^#([0-9a-f]{6})$/i.test(t.color) && luminance(t.color) < 0.5 ? '#fff' : '#17140f' } }, t.texts[0].text),
  926. h('span', { className: 'nm', style: { color: luminance(t.color) < 0.5 ? 'rgba(255,255,255,.75)' : 'rgba(23,20,15,.6)' } }, t.name)
  927. );
  928. }))
  929. );
  930. }
  931. function luminance(hex) {
  932. const c = hex.replace('#', '');
  933. const r = parseInt(c.substr(0, 2), 16), g = parseInt(c.substr(2, 2), 16), b = parseInt(c.substr(4, 2), 16);
  934. return (0.299 * r + 0.587 * g + 0.114 * b) / 255;
  935. }
  936. function applyTemplate(t) {
  937. pushUndo();
  938. const face = curFaces()[t.face];
  939. if (!face) return;
  940. face.color = t.color;
  941. face.items = face.items || [];
  942. t.texts.forEach(function (tx) {
  943. 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));
  944. });
  945. if (t.asset && LB.ICONS[t.asset.id]) {
  946. face.items.push({
  947. id: 'i' + Date.now().toString(36) + Math.random().toString(36).slice(2, 5),
  948. type: 'asset', assetId: t.asset.id, src: 'data:image/svg+xml;utf8,' + encodeURIComponent(LB.assetSvg(t.asset.id, '#c2451f')), x: 50, y: 68, w: 26
  949. });
  950. }
  951. UI.message.success('模板「' + t.name + '」已套用到' + faceName(t.face));
  952. commit();
  953. }
  954. /* ---- 素材面板 ---- */
  955. let assetSearch = '', assetCat = '全部', assetTab = '分类';
  956. const favKey = 'pouchlab.box.favs';
  957. function favs() { try { return JSON.parse(localStorage.getItem(favKey) || '[]'); } catch (e) { return []; } }
  958. function assetPanel() {
  959. const favsList = favs();
  960. const shapeDefs = Object.keys(LB.SHAPES).map(function (k) { return Object.assign({ id: 'shape:' + k, cat: '形状' }, LB.SHAPES[k]); });
  961. 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 }, {}); });
  962. const extra = [
  963. { 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"/>' },
  964. { 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"/>' },
  965. { 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"/>' },
  966. { id: 'cutout:arrow', name: '透明箭头', cat: '抠图', svgDef: '<path d="M12 3.5 19 12h-4.4V20H9.4v-8H5L12 3.5Z" fill="currentColor"/>' }
  967. ];
  968. const all = shapeDefs.concat(iconDefs, extra);
  969. const list = all.filter(function (a) {
  970. if (assetTab === '收藏') return favsList.indexOf(a.id) >= 0;
  971. if (assetTab === '已购') return false;
  972. if (assetSearch && a.name.indexOf(assetSearch) < 0) return false;
  973. if (assetCat === '全部') return true;
  974. return a.cat === assetCat;
  975. });
  976. return h('div', null,
  977. h(A.Input, { placeholder: '输入素材关键字', value: assetSearch, allowClear: true, onChange: function (e) { assetSearch = e.target.value; renderTool(); } }),
  978. h('div', { className: 'bx-sub-tabs' },
  979. ['分类', '收藏', '已购'].map(function (t) {
  980. return h('button', { key: t, className: assetTab === t ? 'on' : '', onClick: function () { assetTab = t; renderTool(); } }, t === '分类' ? '素材分类' : t);
  981. })
  982. ),
  983. assetTab === '分类' && h('div', { className: 'bx-chips' }, LB.ASSET_CATS.map(function (c) {
  984. return h('button', { key: c, className: assetCat === c ? 'on' : '', onClick: function () { assetCat = c; renderTool(); } }, c);
  985. })),
  986. h('div', { className: 'bx-asset-grid' }, list.map(function (a) {
  987. return h('div', { key: a.id, className: 'bx-asset-card', title: a.name },
  988. h('button', {
  989. className: 'thumb', onClick: function () { addAssetFromDef(a); }
  990. }, h('span', { dangerouslySetInnerHTML: { __html: assetThumb(a, '#17140f') } })),
  991. h('span', { className: 'nm' }, a.name),
  992. h('button', {
  993. className: 'fav' + (favsList.indexOf(a.id) >= 0 ? ' on' : ''),
  994. onClick: function () { toggleFav(a.id); }
  995. }, favsList.indexOf(a.id) >= 0 ? '★' : '☆')
  996. );
  997. })),
  998. !list.length && h(A.Empty, { description: assetTab === '已购' ? '暂无购买记录' : '没找到你想要的结果' }),
  999. h('div', { className: 'p-hint', style: { marginTop: '12px' } }, '素材点击即添加到当前选中的面,可于图层面板调整。')
  1000. );
  1001. }
  1002. function toggleFav(id) {
  1003. const list = favs();
  1004. const i = list.indexOf(id);
  1005. if (i >= 0) list.splice(i, 1); else list.push(id);
  1006. localStorage.setItem(favKey, JSON.stringify(list));
  1007. renderTool();
  1008. }
  1009. function addAssetFromDef(a) {
  1010. let src;
  1011. 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>');
  1012. else src = LB.shapeDataUrl(a.draw, '#17140f', 160);
  1013. addAssetToFace({ type: 'asset', assetId: a.id, name: a.name, src: src });
  1014. }
  1015. /* ---- 文字面板 ---- */
  1016. function textPanel() {
  1017. const basics = [
  1018. { id: 'b1', label: '标准', style: { fontWeight: 600 }, size: 10, weight: 600 },
  1019. { id: 'b2', label: '描边', style: { WebkitTextStroke: '1px #17140f', color: '#fff' }, size: 11, weight: 800 },
  1020. { id: 'b3', label: '阴影', style: { textShadow: '2px 2px 0 rgba(23,20,15,.55)' }, size: 11, weight: 800 },
  1021. { id: 'b4', label: '斜体', style: { fontStyle: 'italic' }, size: 10, weight: 500 },
  1022. { id: 'b5', label: '衬线', style: { fontFamily: 'Georgia, serif' }, size: 11, weight: 700 },
  1023. { id: 'b6', label: '圆润', style: { fontFamily: '"PingFang SC", sans-serif', fontWeight: 800, letterSpacing: '1px' }, size: 10, weight: 800 }
  1024. ];
  1025. const combos = [
  1026. { name: '品牌 + 品类', texts: [{ text: '品牌名称', size: 11, weight: 800, y: 40 }, { text: 'PRODUCT NAME', size: 4, weight: 400, y: 52 }] },
  1027. { 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 }] },
  1028. { name: '主标题 + 卖点', texts: [{ text: '大促特惠', size: 13, weight: 800, y: 40, color: '#c2451f' }, { text: '买二送一 · 限时', size: 4.5, weight: 400, y: 52 }] },
  1029. { name: '竖排签名', texts: [{ text: '袋研\n社制', size: 9, weight: 700, y: 42, lineHeight: 1.1 }] }
  1030. ];
  1031. return h('div', null,
  1032. h('button', { className: 'bx-primary-btn', onClick: addBasicText }, '点击添加文字'),
  1033. h('div', { className: 'bx-sec-title' }, '基础文字'),
  1034. h('div', { className: 'bx-basic-texts' }, basics.map(function (b) {
  1035. 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' }); } }, '输入文字');
  1036. })),
  1037. h('div', { className: 'bx-sec-title' }, '文字组合'),
  1038. h('div', { className: 'bx-combo-grid' }, combos.map(function (c) {
  1039. return h('button', { key: c.name, className: 'bx-combo-card', onClick: function () {
  1040. pushUndo();
  1041. const face = curFace();
  1042. c.texts.forEach(function (tx) {
  1043. 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));
  1044. });
  1045. commit();
  1046. UI.message.success('文字组合已添加');
  1047. } },
  1048. h('b', null, c.texts[0].text),
  1049. h('span', null, c.texts.slice(1).map(function (t) { return t.text; }).join(' · ')),
  1050. h('em', null, c.name)
  1051. );
  1052. }))
  1053. );
  1054. }
  1055. /* ---------------- AI 面排版(登录后可用) ---------------- */
  1056. function aiFaceModal() {
  1057. if (window.PL.auth && !PL.auth.user()) {
  1058. PL.auth.require(function () { aiFaceModal(); });
  1059. return;
  1060. }
  1061. if (!window.PL || !PL.api) { UI.message.info('AI 需要联网登录后使用'); return; }
  1062. const faceName = { front: '正面', back: '背面', left: '左面', right: '右面', top: '顶面', bottom: '底面' }[state.selectedFace] || state.selectedFace;
  1063. const div = document.createElement('div');
  1064. $('#bxModals').appendChild(div);
  1065. let brief = '';
  1066. let busy = false;
  1067. let full = false; // 整套 6 面设计
  1068. function renderModal(msg, left) {
  1069. UI.render(div, h(A.Modal, { open: true, width: 460, footer: null,
  1070. title: '✨ AI 排版 · ' + (full ? '整套 6 面' : faceName + '(' + (state.side === 'outer' ? '外' : '内') + '侧)'),
  1071. onCancel: function () { UI.reset(div); div.remove(); } },
  1072. h(A.Segmented, {
  1073. block: true, value: full ? 'full' : 'one',
  1074. options: [{ value: 'one', label: '仅当前面(' + faceName + ')' }, { value: 'full', label: '整套 6 面' }],
  1075. onChange: function (v) { full = v === 'full'; renderModal(); }
  1076. }),
  1077. h('p', { style: { fontSize: 12, color: '#7d7466', margin: '10px 0 8px' } },
  1078. '描述这个面的排版需求;生成后再说"文字再大点/换个位置"可继续调整。' + (left != null ? ' 剩余 ' + left + ' 次' : '')),
  1079. h(A.Input.TextArea, {
  1080. rows: 3, placeholder: '如:极简茶叶礼盒,居中大字品牌名,下方一行英文,底部小字净含量',
  1081. onChange: function (e) { brief = e.target.value; }
  1082. }),
  1083. msg ? h('p', { style: { fontSize: 12, color: msg.ok ? '#4f9d69' : '#e64718', margin: '8px 0 0' } }, msg.text) : null,
  1084. h('div', { style: { display: 'flex', gap: 8, marginTop: 10, justifyContent: 'flex-end' } },
  1085. h(A.Popconfirm, {
  1086. title: '清空本面', description: '将清除' + faceName + '的全部文字与图形(含背景色),可撤销',
  1087. onConfirm: function () {
  1088. pushUndo();
  1089. const f = curFace();
  1090. f.items = [];
  1091. f.color = '';
  1092. commit(); renderAll();
  1093. UI.reset(div); div.remove();
  1094. UI.message.success(faceName + '已清空(可 ⌘Z 撤销)');
  1095. }
  1096. }, h(A.Button, { danger: true }, '清空本面')),
  1097. h(A.Button, { onClick: function () { UI.reset(div); div.remove(); } }, '关闭'),
  1098. h(A.Button, { type: 'primary', loading: busy, onClick: generate }, '生成并应用'))
  1099. ));
  1100. }
  1101. function generate() {
  1102. if (!brief.trim()) { renderModal({ ok: false, text: '请先描述需求' }); return; }
  1103. if (busy) return;
  1104. busy = true; renderModal({ ok: true, text: 'AI 正在设计中,通常 10~60 秒,请勿关闭弹窗…' });
  1105. const face = curFace();
  1106. const ctx = full
  1107. ? { faces: FACES.reduce(function (acc, f) {
  1108. const fd = state.faces[state.side][f.id] || {};
  1109. acc[f.id] = { color: fd.color || '', items: (fd.items || []).filter(function (i) { return i.type === 'text'; }) };
  1110. return acc;
  1111. }, {}) }
  1112. : (face && (face.items || []).length ? { color: face.color || '', items: face.items.filter(function (i) { return i.type === 'text'; }) } : null);
  1113. PL.api.post('/ai/layout', {
  1114. type: 'box', brief: brief,
  1115. meta: full ? { full: true } : { face: state.selectedFace },
  1116. context: ctx
  1117. }, { timeout: 180000 }).then(function (r) {
  1118. busy = false;
  1119. if (full) {
  1120. const faces = r.result.faces || {};
  1121. const filled = Object.keys(faces).filter(function (k) { return (faces[k].items || []).length; });
  1122. if (filled.length < 2) {
  1123. renderModal({ ok: false, text: 'AI 这次没能生成有效成套设计(未扣次数),换个说法再试' });
  1124. return;
  1125. }
  1126. pushUndo();
  1127. FACES.forEach(function (f) {
  1128. const fd = state.faces[state.side][f.id];
  1129. const rd = faces[f.id];
  1130. if (!fd || !rd) return;
  1131. fd.color = rd.color || fd.color;
  1132. fd.items = (rd.items || []).map(function (it) {
  1133. it.id = 'i' + Date.now().toString(36) + Math.random().toString(36).slice(2, 5);
  1134. it.lineHeight = 1.25;
  1135. return it;
  1136. });
  1137. });
  1138. commit(); renderAll();
  1139. UI.reset(div); div.remove();
  1140. UI.message.success('AI 已完成整套 6 面设计(剩余 ' + r.left + ' 次),可撤销');
  1141. return;
  1142. }
  1143. if (!(r.result.items || []).length) {
  1144. renderModal({ ok: false, text: 'AI 这次没能生成有效排版(未扣次数),换个说法再试' });
  1145. return;
  1146. }
  1147. pushUndo();
  1148. const f = curFace();
  1149. f.color = r.result.color || f.color;
  1150. f.items = (r.result.items || []).map(function (it) {
  1151. it.id = 'i' + Date.now().toString(36) + Math.random().toString(36).slice(2, 5);
  1152. it.lineHeight = 1.25;
  1153. return it;
  1154. });
  1155. commit(); renderAll();
  1156. UI.reset(div); div.remove();
  1157. UI.message.success('AI 排版已应用到' + faceName + '(剩余 ' + r.left + ' 次),可撤销');
  1158. }, function (err) {
  1159. busy = false;
  1160. if (err.status === 401) {
  1161. UI.reset(div); div.remove();
  1162. PL.auth.require(function () { aiFaceModal(); });
  1163. return;
  1164. }
  1165. renderModal({ ok: false, text: err.message || 'AI 生成失败' });
  1166. });
  1167. }
  1168. renderModal();
  1169. }
  1170. function addBasicText() { addTextPreset({ text: '输入文字', size: 10, weight: 600 }); }
  1171. function addTextPreset(preset) {
  1172. pushUndo();
  1173. const face = curFace();
  1174. const it = {
  1175. id: 'i' + Date.now().toString(36) + Math.random().toString(36).slice(2, 5),
  1176. type: 'text', text: preset.text || '输入文字',
  1177. size: preset.size || 10, weight: preset.weight || 600, italic: !!preset.italic,
  1178. color: '#17140f', align: 'center', lineHeight: preset.lineHeight || 1.25,
  1179. x: 50, y: preset.y || 40
  1180. };
  1181. face.items = face.items || [];
  1182. face.items.push(it);
  1183. state.selectedItemId = it.id;
  1184. commit();
  1185. }
  1186. /* ---- 工具面板(条码 + 二维码) ---- */
  1187. function toolPanel() {
  1188. return h('div', null,
  1189. h('div', { className: 'bx-tool-card', onClick: addBarcode },
  1190. h('span', { className: 'ic' }, ' II·II '),
  1191. h('div', null, h('b', null, '条形码'), h('span', null, '快速生成一堆码支持4种码制'))
  1192. ),
  1193. h('div', { className: 'bx-tool-card', onClick: addQrcode },
  1194. h('span', { className: 'ic qr' }, '▦'),
  1195. h('div', null, h('b', null, '二维码'), h('span', null, '快速生成二维码设计使用'))
  1196. )
  1197. );
  1198. }
  1199. function barcodeSvg(kind, value) {
  1200. if (kind === 'code128') {
  1201. 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(' ');
  1202. const text = String(value || 'POUCHLAB').replace(/[^\x20-\x7e]/g, '').slice(0, 20) || 'BOX';
  1203. const codes = [104];
  1204. for (let i = 0; i < text.length; i += 1) codes.push(text.charCodeAt(i) - 32);
  1205. let sum = 104;
  1206. for (let i = 1; i < codes.length; i += 1) sum += codes[i] * i;
  1207. codes.push(sum % 103);
  1208. codes.push(106);
  1209. let bits = '';
  1210. codes.forEach(function (c) { bits += TBL[c]; });
  1211. let x = 0, rects = '';
  1212. const unit = 2;
  1213. for (let i = 0; i < bits.length; i += 1) {
  1214. const wdt = Number(bits[i]) * unit;
  1215. if (i % 2 === 0) rects += '<rect x="' + x + '" width="' + wdt + '" height="60" fill="#17140f"/>';
  1216. x += wdt;
  1217. }
  1218. const totalW = x + 40;
  1219. 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>');
  1220. }
  1221. // EAN-13 / EAN-8 / UPC-A 共用 PL.render.barcodeBits(EAN-13 逻辑,UPC-A 加 0 前缀)
  1222. let val = String(value || '').replace(/\D/g, '');
  1223. if (kind === 'ean8') val = val.slice(0, 7).padEnd(7, '0');
  1224. else if (kind === 'upca') val = val.slice(0, 11).padEnd(11, '0');
  1225. else val = val.slice(0, 12).padEnd(12, '0');
  1226. const bars = R.barcodeBits(kind === 'upca' ? '0' + val : val);
  1227. const label = kind === 'upca' ? '0' + bars.code : bars.code;
  1228. const rects = [];
  1229. let x = 0;
  1230. const unit = 2;
  1231. for (let i = 0; i < bars.bits.length; i += 1) {
  1232. if (bars.bits[i] === '1') rects.push('<rect x="' + x + '" width="' + unit + '" height="56" fill="#17140f"/>');
  1233. x += unit;
  1234. }
  1235. 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>');
  1236. }
  1237. function addBarcode() {
  1238. let kind = 'ean13';
  1239. const content = h('div', null,
  1240. h('div', { className: 'p-field' },
  1241. h('label', null, '码制'),
  1242. h(A.Select, {
  1243. defaultValue: 'ean13', style: { width: '100%' },
  1244. onChange: function (v) { kind = v; },
  1245. options: [
  1246. { value: 'ean13', label: 'EAN-13 商品码' },
  1247. { value: 'ean8', label: 'EAN-8 短码' },
  1248. { value: 'upca', label: 'UPC-A' },
  1249. { value: 'code128', label: 'Code128' }
  1250. ]
  1251. })
  1252. ),
  1253. h('div', { className: 'p-field' },
  1254. h('label', null, '内容'),
  1255. h(A.Input, { id: 'bxBarcodeValue', defaultValue: '6971234567890', placeholder: '条码内容' })
  1256. )
  1257. );
  1258. modalConfirm('生成条形码', content, function () {
  1259. const value = document.getElementById('bxBarcodeValue').value;
  1260. const src = barcodeSvg(kind, value);
  1261. addAssetToFace({ type: 'barcode', codeType: kind, value: value, src: src, w: 40 });
  1262. });
  1263. }
  1264. function addQrcode() {
  1265. const content = h('div', null,
  1266. h('div', { className: 'p-field' },
  1267. h('label', null, '二维码内容(网址或文字)'),
  1268. h(A.Input, { id: 'bxQrValue', defaultValue: 'https://pouchlab.design', placeholder: '请输入内容' })
  1269. )
  1270. );
  1271. modalConfirm('生成二维码', content, function () {
  1272. const value = document.getElementById('bxQrValue').value || ' ';
  1273. let src;
  1274. try { src = QR.toDataURL(value, { scale: 6, margin: 1 }); }
  1275. catch (e) { UI.message.error(e.message || '内容过长'); return; }
  1276. addAssetToFace({ type: 'barcode', codeType: 'qrcode', value: value, src: src, w: 32 });
  1277. });
  1278. }
  1279. /* ---- 上传面板 ---- */
  1280. function storageUsed() {
  1281. let total = 0;
  1282. try {
  1283. for (const k in localStorage) {
  1284. if (Object.prototype.hasOwnProperty.call(localStorage, k) && k.indexOf('pouchlab') === 0) {
  1285. total += (localStorage[k] || '').length * 2;
  1286. }
  1287. }
  1288. } catch (e) {}
  1289. return total;
  1290. }
  1291. function uploadPanel() {
  1292. const used = storageUsed();
  1293. const pct = Math.min(100, used / (100 * 1024 * 1024) * 100);
  1294. const uploads = state.uploads || [];
  1295. return h('div', null,
  1296. h(A.Upload, {
  1297. accept: 'image/*', showUploadList: false, customRequest: uploadToFace,
  1298. children: h('button', { className: 'bx-primary-btn' }, '上传图片')
  1299. }),
  1300. h('div', { className: 'p-hint' }, '支持上传JPG/PNG/SVG等格式文件'),
  1301. uploads.length ? h('div', { className: 'bx-upload-grid' }, uploads.map(function (u) {
  1302. return h('div', { key: u.id, className: 'bx-upload-card' },
  1303. h('button', {
  1304. className: 'thumb', title: '添加到当前面',
  1305. onClick: function () { addAssetToFace({ type: 'image', name: u.name, src: u.src, w: 70 }); }
  1306. }, h('img', { src: u.src, alt: u.name })),
  1307. h('span', { className: 'nm', title: u.name }, u.name),
  1308. h('button', {
  1309. className: 'del', title: '从上传记录中移除',
  1310. onClick: function () {
  1311. state.uploads = (state.uploads || []).filter(function (x) { return x.id !== u.id; });
  1312. commit();
  1313. }
  1314. }, '✕')
  1315. );
  1316. })) : h('div', { className: 'bx-upload-empty' },
  1317. h('div', { className: 'box-illus' }),
  1318. h('span', null, '上传的稿件会放置到当前选中的面')
  1319. ),
  1320. h('div', { className: 'bx-capacity' },
  1321. h('span', null, '个人已使用 ' + (used / 1024 / 1024).toFixed(1) + 'M/100M'),
  1322. h('a', { onClick: function () { UI.message.info('演示环境:容量为本地浏览器存储模拟'); } }, '扩充容量')
  1323. ),
  1324. h('div', { className: 'bx-cap-bar' }, h('i', { style: { width: Math.max(1, pct) + '%' } }))
  1325. );
  1326. }
  1327. function uploadToFace(options) {
  1328. const file = options.file;
  1329. if (!file || file.type.indexOf('image') !== 0) {
  1330. UI.message.warning('请选择图片文件');
  1331. return;
  1332. }
  1333. const reader = new FileReader();
  1334. reader.onload = function () {
  1335. const img = new Image();
  1336. img.onload = function () {
  1337. const max = 900;
  1338. let w = img.width, hh = img.height;
  1339. if (Math.max(w, hh) > max) {
  1340. const k = max / Math.max(w, hh);
  1341. w = Math.round(w * k); hh = Math.round(hh * k);
  1342. }
  1343. const canvas = document.createElement('canvas');
  1344. canvas.width = w; canvas.height = hh;
  1345. canvas.getContext('2d').drawImage(img, 0, 0, w, hh);
  1346. const src = canvas.toDataURL(file.type === 'image/png' ? 'image/png' : 'image/jpeg', 0.84);
  1347. // 保留上传记录,便于重复使用;最多保留 8 张,避免 localStorage 超限
  1348. const up = { id: 'u' + Date.now().toString(36) + Math.random().toString(36).slice(2, 5), name: file.name, src: src, time: Date.now() };
  1349. state.uploads = [up].concat(state.uploads || []).slice(0, 8);
  1350. addAssetToFace({ type: 'image', name: file.name, src: src, w: 70 });
  1351. if (currentTab === 'upload') renderTool();
  1352. };
  1353. img.src = reader.result;
  1354. };
  1355. reader.readAsDataURL(file);
  1356. }
  1357. /* ---- 图层面板 ---- */
  1358. function layersPanel() {
  1359. const face = curFace();
  1360. const items = (face.items || []).slice().reverse();
  1361. return h('div', null,
  1362. h('div', { className: 'bx-layer-head' },
  1363. h('div', { className: 'bx-sec-title' }, faceName(state.selectedFace) + ' · ' + items.length + ' 个图层'),
  1364. items.length ? h('button', { className: 'bx-layer-clear', onClick: clearLayers }, '一键清空') : null
  1365. ),
  1366. items.length ? h('div', { className: 'bx-layer-list' }, items.map(function (it) {
  1367. const typeNames = { text: '文字', image: '图片', asset: '素材', barcode: it.codeType === 'qrcode' ? '二维码' : '条形码' };
  1368. return h('div', { key: it.id, className: 'bx-layer-row' + (state.selectedItemId === it.id ? ' on' : ''), 'data-layer-id': it.id },
  1369. h('span', { className: 't', onClick: function () { state.selectedItemId = it.id; renderTool(); renderProps(); } },
  1370. typeNames[it.type] || '元素', ' · ', it.type === 'text' ? String(it.text || '').split('\n')[0] : (it.name || '')),
  1371. h('button', { title: it.hidden ? '显示' : '隐藏', onClick: function () { it.hidden = !it.hidden; commit(); } }, it.hidden ? '🚫' : '👁'),
  1372. h('button', { title: '移到最顶层', onClick: function () { moveItem(it.id, 'top'); } }, '⤒'),
  1373. h('button', { title: '上移一层', onClick: function () { moveItem(it.id, 1); } }, '↑'),
  1374. h('button', { title: '下移一层', onClick: function () { moveItem(it.id, -1); } }, '↓'),
  1375. h('button', { title: '移到最底层', onClick: function () { moveItem(it.id, 'bottom'); } }, '⤓'),
  1376. h('button', { className: 'del', title: '删除', onClick: function () { removeItem(it.id); } }, '✕')
  1377. );
  1378. })) : h('div', { className: 'bx-layer-empty' },
  1379. h('span', { className: 'stack' }), '图层为空'
  1380. )
  1381. );
  1382. }
  1383. function clearLayers() {
  1384. const face = curFace();
  1385. const count = (face.items || []).length;
  1386. let total = 0;
  1387. FACES.forEach(function (ff) { total += (curFaces()[ff.id].items || []).length; });
  1388. if (!total) return;
  1389. let close;
  1390. close = mountModal(h(A.Modal, {
  1391. title: '清空图层', open: true, footer: null, onCancel: function () { close(); }
  1392. }, h('div', null,
  1393. h('p', null, '当前面有 ' + count + ' 个图层,全部面共 ' + total + ' 个图层。'),
  1394. h('div', { className: 'bx-clear-actions' },
  1395. h('button', {
  1396. className: 'bx-clear-opt', disabled: !count,
  1397. onClick: function () {
  1398. pushUndo();
  1399. face.items = [];
  1400. state.selectedItemId = null;
  1401. commit();
  1402. close();
  1403. UI.message.success('已清空「' + faceName(state.selectedFace) + '」图层');
  1404. }
  1405. }, '清空当前面(' + count + ')'),
  1406. h('button', {
  1407. className: 'bx-clear-opt danger',
  1408. onClick: function () {
  1409. pushUndo();
  1410. FACES.forEach(function (ff) { curFaces()[ff.id].items = []; });
  1411. state.selectedItemId = null;
  1412. commit();
  1413. close();
  1414. UI.message.success('已清空全部面图层');
  1415. }
  1416. }, '清空全部面(' + total + ')')
  1417. ),
  1418. h('div', { className: 'p-hint', style: { marginTop: '10px' } }, '清空后可通过 Ctrl+Z 撤销。')
  1419. )));
  1420. }
  1421. function findItem(id) {
  1422. const face = curFace();
  1423. return (face.items || []).find(function (x) { return x.id === id; }) || null;
  1424. }
  1425. function removeItem(id) {
  1426. pushUndo();
  1427. const face = curFace();
  1428. face.items = (face.items || []).filter(function (x) { return x.id !== id; });
  1429. if (state.selectedItemId === id) state.selectedItemId = null;
  1430. commit();
  1431. }
  1432. function moveItem(id, dir) {
  1433. const face = curFace();
  1434. const arr = face.items || [];
  1435. const i = arr.findIndex(function (x) { return x.id === id; });
  1436. if (i < 0) return;
  1437. let j;
  1438. if (dir === 'top') j = arr.length - 1;
  1439. else if (dir === 'bottom') j = 0;
  1440. else j = i + dir;
  1441. if (j < 0 || j >= arr.length || j === i) return;
  1442. pushUndo();
  1443. const it = arr.splice(i, 1)[0];
  1444. arr.splice(j, 0, it);
  1445. commit();
  1446. }
  1447. /* 拖拽排序:把 fromId 移动到 toId 的上/下(above=true 为更高层) */
  1448. function reorderLayer(fromId, toId, above) {
  1449. if (!fromId || !toId || fromId === toId) return;
  1450. const face = curFace();
  1451. const arr = face.items || [];
  1452. const rv = arr.slice().reverse();
  1453. const si = rv.findIndex(function (x) { return x.id === fromId; });
  1454. const ti = rv.findIndex(function (x) { return x.id === toId; });
  1455. if (si < 0 || ti < 0) return;
  1456. pushUndo();
  1457. const it = rv.splice(si, 1)[0];
  1458. let ins = ti > si ? ti - 1 : ti;
  1459. if (!above) ins += 1;
  1460. rv.splice(ins, 0, it);
  1461. face.items = rv.reverse();
  1462. commit();
  1463. }
  1464. /* ---- 帮助面板 ---- */
  1465. function helpPanel() {
  1466. return h('div', null,
  1467. h('div', { className: 'bx-tool-card', onClick: function () { UI.message.info('演示环境:可发送邮件至 support@pouchlab.design'); } },
  1468. h('span', { className: 'ic' }, '☎'), h('div', null, h('b', null, '咨询客服'), h('span', null, '工作日 9:00-18:00'))
  1469. ),
  1470. h('div', { className: 'bx-tool-card', onClick: showQuickStart },
  1471. h('span', { className: 'ic' }, '📖'), h('div', null, h('b', null, '快速上手'), h('span', null, '3 步完成盒子设计'))
  1472. ),
  1473. h('div', { className: 'bx-tool-card', onClick: showShortcuts },
  1474. h('span', { className: 'ic' }, '⌨'), h('div', null, h('b', null, '快捷键'), h('span', null, '常用操作快捷键列表'))
  1475. )
  1476. );
  1477. }
  1478. function showQuickStart() {
  1479. modalInfo('快速上手', h('div', { className: 'bx-help-steps' },
  1480. h('p', null, '1. 在「盒型」面板选择盒型与尺寸,或点「编辑」打开智能参数宝精确调参;'),
  1481. h('p', null, '2. 在 2D 设计里点选面,用「文字 / 素材 / 上传」添加内容,右侧换颜色与纹理;'),
  1482. h('p', null, '3. 切到「3D预览」拖拽查看,播放动效,最后「导出」或「印刷下单」。')
  1483. ));
  1484. }
  1485. function showShortcuts() {
  1486. modalInfo('快捷键', h('div', { className: 'bx-help-steps' },
  1487. h('p', null, 'Ctrl/⌘ + Z 撤销'), h('p', null, 'Ctrl/⌘ + Shift + Z 重做'),
  1488. h('p', null, 'Ctrl/⌘ + S 保存'), h('p', null, 'Delete 删除选中元素'),
  1489. h('p', null, 'Tab 切换外侧 / 内侧'), h('p', null, '空格拖拽 平移画布')
  1490. ));
  1491. }
  1492. /* ---------------- 右侧属性面板 ---------------- */
  1493. function propsPanel() {
  1494. if (state.mode === '3d') return animsPanel();
  1495. const face = curFace();
  1496. const item = state.selectedItemId ? findItem(state.selectedItemId) : null;
  1497. const out = outerSize();
  1498. const dl = dieline();
  1499. const children = [];
  1500. // 迷你 3D 挂载于右侧面板顶部(2D 模式显示)
  1501. children.push(h('div', { className: 'bx-props-sec' },
  1502. h('div', { className: 'bx-props-head-row' },
  1503. h('b', null, '尺寸/材质', h('i', { className: 'q', title: '内尺寸为盒体内部净尺寸' }))),
  1504. h('button', { className: 'bx-edit-btn', onClick: openSmartParams }, '编辑'),
  1505. h('div', { className: 'bx-kv' }, h('span', null, '内尺寸(mm)'), h('b', null, 'L:' + state.w + ' W:' + state.d + ' H:' + state.h)),
  1506. h('div', { className: 'bx-kv' }, h('span', null, '材质'), h('b', null, material().name)),
  1507. h('div', { className: 'bx-kv' }, h('span', null, '厚度'), h('b', null, material().thickness + 'mm'))
  1508. ));
  1509. children.push(h('div', { className: 'bx-props-sec' },
  1510. h('div', { className: 'bx-props-head-row' }, h('b', null, '颜色 / 背景')),
  1511. h('div', { className: 'bx-color-tabs' },
  1512. h('button', { className: colorTab === 'color' ? 'on' : '', onClick: function () { colorTab = 'color'; renderProps(); } }, '颜色'),
  1513. h('button', { className: colorTab === 'texture' ? 'on' : '', onClick: function () { colorTab = 'texture'; renderProps(); } }, '纹理')
  1514. ),
  1515. colorTab === 'color' ? h('div', null,
  1516. h('div', { className: 'bx-swatch-grid' },
  1517. h('label', { className: 'bx-swatch picker', title: '自定义颜色' },
  1518. h('input', { type: 'color', value: face.color || '#fbf7ee', onInput: function (e) { setFaceColor(e.target.value); } }),
  1519. h('span', { className: 'grad' })
  1520. ),
  1521. h('button', { className: 'bx-swatch', title: '清空颜色', onClick: function () { setFaceColor(''); } }, h('i', { className: 'none' })),
  1522. LB.FACE_COLORS.map(function (c) {
  1523. return h('button', { key: c, className: 'bx-swatch' + (face.color === c ? ' on' : ''), style: { background: c }, onClick: function () { setFaceColor(c); } });
  1524. })
  1525. ),
  1526. h('div', { className: 'bx-pms-title' }, '参考潘通色'),
  1527. h('div', { className: 'bx-pms-grid' }, (window.PL.pantone ? window.PL.pantone.list : []).map(function (c) {
  1528. return h('button', {
  1529. key: c.code,
  1530. className: 'bx-pms-dot' + (face.color && face.color.toLowerCase() === c.hex.toLowerCase() ? ' on' : ''),
  1531. title: '参考潘通色 ' + c.code + ' ' + c.name,
  1532. style: { background: c.hex },
  1533. onClick: function () { setFaceColor(c.hex); }
  1534. });
  1535. })),
  1536. h('div', { className: 'bx-pms-note' }, window.PL.pantone ? window.PL.pantone.note : '')
  1537. ) : h('div', { className: 'bx-tex-grid' },
  1538. h('button', { className: 'bx-tex clear', onClick: function () { setFaceTexture(null); } }, h('i', { className: 'none' }), h('span', null, '清空纹理')),
  1539. LB.TEXTURES.map(function (t) {
  1540. return h('button', {
  1541. key: t.id, className: 'bx-tex' + (face.textureId === t.id ? ' on' : ''),
  1542. onClick: function () { setFaceTexture(t.id); }
  1543. }, h('img', { src: LB.textureDataUrl(t.id), alt: t.name }), h('span', null, t.name));
  1544. })
  1545. )
  1546. ));
  1547. children.push(h('div', { className: 'bx-props-sec' },
  1548. h('div', { className: 'bx-props-head-row' }, h('b', null, '画布'),
  1549. h('span', { className: 'dim' }, '展开 ' + Math.round(dl.size.w) + ' × ' + Math.round(dl.size.h) + ' mm')),
  1550. h('div', { className: 'bx-kv' }, h('span', null, '外侧尺寸'), h('b', null, Math.round(out.w) + ' × ' + Math.round(out.d) + ' × ' + Math.round(out.h) + ' mm')),
  1551. h('div', { className: 'bx-kv' }, h('span', null, '当前设计'), h('b', null, state.side === 'outer' ? '外侧' : '内侧')),
  1552. h('div', { className: 'bx-kv' }, h('span', null, '元素'), h('b', null, ((face.items || []).length) + ' 个'))
  1553. ));
  1554. if (item) children.push(itemPropsPanel(item));
  1555. return h('div', null, children);
  1556. }
  1557. let colorTab = 'color';
  1558. function itemPropsPanel(item) {
  1559. const typeNames = { text: '文字属性', image: '图片属性', asset: '素材属性', barcode: item.codeType === 'qrcode' ? '二维码属性' : '条形码属性' };
  1560. const rows = [];
  1561. rows.push(h('div', { className: 'bx-props-sec' },
  1562. h('div', { className: 'bx-props-head-row' }, h('b', null, typeNames[item.type] || '元素属性'),
  1563. h('button', { onClick: function () { state.selectedItemId = null; renderProps(); } }, '完成选择'))
  1564. ));
  1565. if (item.type === 'text') {
  1566. rows.push(h('div', { className: 'bx-props-sec' },
  1567. h(BoxTextField, {
  1568. value: item.text, placeholder: '文字内容',
  1569. onInput: function (v) { item.text = v; save(true); renderDieline(); render3d(); renderMini(); },
  1570. onCommit: function () { commit(); }
  1571. }),
  1572. h('div', { className: 'bx-row2' },
  1573. 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(); } } })),
  1574. h('div', { className: 'p-field' }, h('label', null, '颜色'), h(A.ColorPicker, {
  1575. key: 'tc-' + item.id,
  1576. defaultValue: item.color || '#17140f',
  1577. showText: true,
  1578. onChange: function (c) { item.color = c.toHexString(); save(true); renderDieline(); render3d(); renderMini(); },
  1579. onChangeComplete: function (c) { item.color = c.toHexString(); commit(); }
  1580. }))
  1581. ),
  1582. h('div', { className: 'bx-row2' },
  1583. 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(); } })),
  1584. 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(); } }))
  1585. ),
  1586. h('div', { className: 'p-field', style: { marginTop: '6px' } },
  1587. h('label', null, '样式'),
  1588. h('div', { className: 'bx-row2' },
  1589. h(A.Checkbox, { checked: !!item.italic, onChange: function (e) { item.italic = e.target.checked; commit(); } }, '斜体'),
  1590. h(A.Checkbox, { checked: !!item.hidden, onChange: function (e) { item.hidden = e.target.checked; commit(); } }, '隐藏')
  1591. )
  1592. )
  1593. ));
  1594. } else {
  1595. rows.push(h('div', { className: 'bx-props-sec' },
  1596. h('img', { className: 'bx-item-preview', src: item.src, alt: '' }),
  1597. 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(); } }))
  1598. ));
  1599. }
  1600. rows.push(h('div', { className: 'bx-row2', style: { marginBottom: '12px' } },
  1601. 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(); } })),
  1602. 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(); } }))
  1603. ));
  1604. rows.push(h('div', { className: 'bx-props-sec' },
  1605. h('div', { className: 'bx-props-head-row' }, h('b', null, '图层顺序')),
  1606. h('div', { className: 'bx-order-grid' },
  1607. h('button', { className: 'bx-ghost-btn', onClick: function () { moveItem(item.id, 'top'); } }, '⤒ 置顶'),
  1608. h('button', { className: 'bx-ghost-btn', onClick: function () { moveItem(item.id, 1); } }, '↑ 上移'),
  1609. h('button', { className: 'bx-ghost-btn', onClick: function () { moveItem(item.id, -1); } }, '↓ 下移'),
  1610. h('button', { className: 'bx-ghost-btn', onClick: function () { moveItem(item.id, 'bottom'); } }, '⤓ 置底')
  1611. )
  1612. ));
  1613. return h('div', null, rows);
  1614. }
  1615. function setFaceColor(c) {
  1616. pushUndo();
  1617. curFace().color = c;
  1618. commit();
  1619. }
  1620. function setFaceTexture(id) {
  1621. pushUndo();
  1622. const face = curFace();
  1623. if (id) {
  1624. face.textureId = id;
  1625. face.texture = LB.textureDataUrl(id);
  1626. } else {
  1627. face.textureId = null;
  1628. face.texture = null;
  1629. }
  1630. commit();
  1631. }
  1632. /* 3D 模式右侧:动效面板 */
  1633. function animsPanel() {
  1634. return h('div', null,
  1635. h('div', { className: 'bx-props-sec' },
  1636. h('div', { className: 'bx-props-head-row' }, h('b', null, '动效'), h('span', { className: 'dim' }, '点击预览'))
  1637. ),
  1638. h('div', { className: 'bx-anim-list' }, LB.ANIMS.map(function (a) {
  1639. const playing = main3d && main3d.ready() && main3d.animating() && playingAnimId === a.id;
  1640. return h('div', { key: a.id, className: 'bx-anim-card' + (playing ? ' on' : '') },
  1641. h('button', {
  1642. className: 'bx-anim-play',
  1643. onClick: function () { playAnim(a); }
  1644. },
  1645. h('span', { className: 'dur' }, a.dur + 's'),
  1646. h('span', { className: 'anim-illus ' + a.id })
  1647. ),
  1648. h('div', { className: 'bx-anim-meta' },
  1649. h('b', null, a.name),
  1650. h('button', { onClick: function () { playAnim(a); } }, playing ? '停止' + a.dur + 's' : (a.id === 'fromLeft' ? '预览' : '停止' + a.dur + 's'))
  1651. )
  1652. );
  1653. })),
  1654. h('div', { className: 'bx-props-sec' },
  1655. h('div', { className: 'bx-props-head-row' }, h('b', null, '视角')),
  1656. h('div', { className: 'bx-row2' },
  1657. h('button', { className: 'bx-ghost-btn', onClick: function () { if (main3d) main3d.resetView(); } }, '重置视角'),
  1658. h('button', { className: 'bx-ghost-btn', onClick: function () { const t = !state.autoRotate; state.autoRotate = t; if (main3d) main3d.setAutoRotate(t); } }, '自动旋转')
  1659. )
  1660. )
  1661. );
  1662. }
  1663. let playingAnimId = null;
  1664. function playAnim(a) {
  1665. if (!main3d || !main3d.ready()) return;
  1666. if (playingAnimId === a.id && main3d.animating()) {
  1667. main3d.stopAnim();
  1668. playingAnimId = null;
  1669. renderProps();
  1670. return;
  1671. }
  1672. stopFoldAnim();
  1673. playingAnimId = a.id;
  1674. main3d.playAnim(a.id, a.dur, function () {
  1675. playingAnimId = null;
  1676. renderProps();
  1677. });
  1678. renderProps();
  1679. }
  1680. /* ---------------- 弹窗基建 ---------------- */
  1681. function mountModal(node) {
  1682. const div = document.createElement('div');
  1683. $('#bxModals').appendChild(div);
  1684. let closed = false;
  1685. const close = function () {
  1686. if (closed) return;
  1687. closed = true;
  1688. try { UI.reset(div); } catch (e) {}
  1689. if (div.parentNode) div.parentNode.removeChild(div);
  1690. };
  1691. UI.render(div, node);
  1692. return close;
  1693. }
  1694. function modalConfirm(title, content, onOk, okText, width) {
  1695. let close;
  1696. close = mountModal(h(A.Modal, {
  1697. title: title, open: true, onCancel: function () { close(); },
  1698. width: width || undefined,
  1699. okText: okText || '确认调整',
  1700. onOk: function () { if (onOk) onOk(); close(); },
  1701. okButtonProps: { style: { background: '#ff6a00', borderColor: '#ff6a00' } }
  1702. }, content));
  1703. return close;
  1704. }
  1705. function modalInfo(title, content) {
  1706. let close;
  1707. close = mountModal(h(A.Modal, {
  1708. title: title, open: true, onCancel: function () { close(); },
  1709. footer: h(A.Button, { type: 'primary', onClick: function () { close(); }, style: { background: '#ff6a00', borderColor: '#ff6a00' } }, '我知道了')
  1710. }, content));
  1711. return close;
  1712. }
  1713. /* ---------------- 智能参数宝 ---------------- */
  1714. function openSmartParams() {
  1715. const params = Object.assign({ _labels: true }, state.smart);
  1716. const dims = { w: state.w, d: state.d, h: state.h };
  1717. let baseSize = '内尺寸', outSize = '内尺寸';
  1718. const adv = struct().advanced || [];
  1719. const advRows = adv.map(function (key) {
  1720. const f = ADV_FIELDS[key];
  1721. if (!f) return null;
  1722. return h('div', { className: 'sp-row', key: key },
  1723. h('label', { title: f.name }, f.name + ' (' + f.code + ')'),
  1724. h(A.InputNumber, {
  1725. value: params[key], min: f.min, max: f.max, step: f.step || 1,
  1726. onChange: function (v) { if (v != null) params[key] = v; renderSmart(); }
  1727. }),
  1728. h('span', { className: 'unit' }, f.unit)
  1729. );
  1730. });
  1731. const content = h('div', { className: 'sp-wrap' },
  1732. h('div', { className: 'sp-left' }, h('div', { id: 'spDieline', className: 'sp-dieline' })),
  1733. h('div', { className: 'sp-right' },
  1734. h('div', { className: 'sp-row' },
  1735. h('label', null, '标注方式'),
  1736. h(A.Select, { defaultValue: '数值', style: { flex: 1 }, options: [{ value: '数值' }, { value: '无标注' }], onChange: function (v) { params._labels = v === '数值'; renderSmart(); } })
  1737. ),
  1738. h('div', { className: 'sp-group-title' }, '基础参数'),
  1739. h('div', { className: 'sp-row' },
  1740. h('label', { title: '以内尺寸或外尺寸为基准调整' }, '基准尺寸'),
  1741. h(A.Select, { defaultValue: '内尺寸', style: { flex: 1 }, options: [{ value: '内尺寸' }, { value: '外尺寸' }], onChange: function (v) { baseSize = v; } })
  1742. ),
  1743. h('div', { className: 'sp-row' },
  1744. h('label', { title: '输出制造尺寸口径' }, '输出尺寸'),
  1745. h(A.Select, { defaultValue: '内尺寸', style: { flex: 1 }, options: [{ value: '内尺寸' }, { value: '外尺寸' }], onChange: function (v) { outSize = v; } })
  1746. ),
  1747. ['w', 'd', 'h'].map(function (k, i) {
  1748. return h('div', { className: 'sp-row', key: k },
  1749. h('label', null, ['长 (L)', '宽 (W)', '高 (H)'][i]),
  1750. h(A.InputNumber, { value: dims[k], min: 10, max: 2000, style: { flex: 1 }, onChange: function (v) { if (v) dims[k] = v; renderSmart(); } }),
  1751. h('span', { className: 'unit' }, 'mm')
  1752. );
  1753. }),
  1754. h('div', { className: 'sp-row' },
  1755. h('label', null, '出血线 (BL)'),
  1756. 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(); } }),
  1757. h('span', { className: 'unit' }, 'mm')
  1758. ),
  1759. h('div', { className: 'sp-row' },
  1760. h('label', null, '厚度(0.2~3mm)'),
  1761. h(A.InputNumber, { value: material().thickness, min: 0.2, max: 3, step: 0.1, style: { flex: 1 }, onChange: function (v) { /* 材质决定厚度 */ } }),
  1762. h('span', { className: 'unit' }, 'mm')
  1763. ),
  1764. h('div', { className: 'sp-row' },
  1765. h('label', null, '材质'),
  1766. 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(); } })
  1767. ),
  1768. advRows.length ? h('div', { className: 'sp-group-title' }, '高级参数') : null,
  1769. advRows
  1770. )
  1771. );
  1772. const close = modalConfirm('智能参数宝', content, function () {
  1773. pushUndo();
  1774. state.w = dims.w; state.d = dims.d; state.h = dims.h;
  1775. Object.assign(state.smart, params);
  1776. commit();
  1777. UI.message.success('参数已调整,刀版与 3D 已更新');
  1778. }, '确认调整', 980);
  1779. function renderSmart() {
  1780. const keep = { w: state.w, d: state.d, h: state.h, smart: state.smart };
  1781. state.w = dims.w; state.d = dims.d; state.h = dims.h;
  1782. const merged = Object.assign({}, state.smart, params);
  1783. state.smart = merged;
  1784. const svg = dielineSVG({ noLegend: true, clean: !params._labels });
  1785. state.w = keep.w; state.d = keep.d; state.h = keep.h; state.smart = keep.smart;
  1786. const el = document.getElementById('spDieline');
  1787. if (el) {
  1788. el.innerHTML = svg;
  1789. const s = el.querySelector('svg');
  1790. if (s) { s.style.width = '100%'; s.style.height = 'auto'; }
  1791. }
  1792. }
  1793. setTimeout(renderSmart, 60);
  1794. }
  1795. function showImportCad() {
  1796. modalInfo('导入 CAD', h('div', { className: 'bx-help-steps' },
  1797. h('p', null, '支持 DXF 盒型结构文件上传,上传后在「我的盒型」中管理。'),
  1798. h('p', null, '演示环境:本版本以内置参数化盒型库代替 CAD 解析,选择盒型后可在智能参数宝中精调结构参数。')
  1799. ));
  1800. }
  1801. /* ---------------- 导出弹窗 ---------------- */
  1802. let exportTab = 'file', exportRes = '2k', exportRatio = '16:9', exportBg = 'scene', exportSide = 'outer';
  1803. const EXPORT_LOG_KEY = 'pouchlab.box.exports';
  1804. function exportLog() { try { return JSON.parse(localStorage.getItem(EXPORT_LOG_KEY) || '[]'); } catch (e) { return []; } }
  1805. function logExport(type, name) {
  1806. const list = exportLog();
  1807. list.unshift({ time: Date.now(), type: type, name: name });
  1808. try { localStorage.setItem(EXPORT_LOG_KEY, JSON.stringify(list.slice(0, 40))); } catch (e) {}
  1809. }
  1810. function downloadBlob(blob, filename) {
  1811. const a = document.createElement('a');
  1812. a.href = URL.createObjectURL(blob);
  1813. a.download = filename;
  1814. a.click();
  1815. setTimeout(function () { URL.revokeObjectURL(a.href); }, 2000);
  1816. }
  1817. function openExport() {
  1818. const div = document.createElement('div');
  1819. $('#bxModals').appendChild(div);
  1820. const close = function () { UI.reset(div); div.remove(); renderAll(); };
  1821. let snapRaf = null;
  1822. // 导出弹窗内的静态 3D 快照;用当前设计实时渲染,避免预览空白
  1823. function snapSrc(w, h) {
  1824. if (!main3d || !main3d.ready()) return '';
  1825. try {
  1826. main3d.render(state, material(), currentPanels());
  1827. main3d.setFold(foldValue / 100);
  1828. return main3d.snapshot(w, h, exportBg === 'transparent');
  1829. } catch (e) { return ''; }
  1830. }
  1831. function refreshSnap() {
  1832. if (snapRaf) return;
  1833. snapRaf = requestAnimationFrame(function () {
  1834. snapRaf = null;
  1835. const im = div.querySelector('.ex-preview.3d .ex-snap');
  1836. if (im) im.src = snapSrc(760, 480);
  1837. });
  1838. }
  1839. function renderExport() {
  1840. let body;
  1841. if (exportTab === 'file') {
  1842. body = h('div', { className: 'ex-file-body' },
  1843. h('div', { className: 'ex-preview', dangerouslySetInnerHTML: { __html: dielineSVG({ noLegend: true }) } }),
  1844. h('div', { className: 'ex-side' },
  1845. h('div', { className: 'ex-label' }, '文件类型'),
  1846. h('div', { className: 'ex-type-grid' },
  1847. h('button', { onClick: exportPrintPdf }, '印刷PDF', h('em', null, 'pdf')),
  1848. h('button', { onClick: function () { UI.message.info('AI 源文件暂不支持,可导出 PDF / DXF / SVG 矢量文件'); } }, '印刷AI', h('em', null, 'ai')),
  1849. h('button', { onClick: exportDielinePdf }, '刀版PDF', h('em', null, 'pdf')),
  1850. h('button', { onClick: exportDxf }, '刀版DXF', h('em', null, 'dxf')),
  1851. h('button', { onClick: exportPreviewJpg }, '预览JPG', h('em', null, 'jpg'))
  1852. ),
  1853. h('div', { className: 'ex-label' }, '色彩模式'),
  1854. h('div', { className: 'ex-mode-row' },
  1855. h('button', { className: 'on' }, 'CMYK模式'),
  1856. h('button', { onClick: function () { UI.message.info('屏幕预览为 RGB,交付印刷文件请选 CMYK'); } }, 'RGB模式')
  1857. ),
  1858. h('p', { className: 'ex-note' }, '刀线和设计元素独立分层'),
  1859. h('p', { className: 'ex-note' }, '导出即视为已阅读并同意《授权许可协议》')
  1860. )
  1861. );
  1862. } else if (exportTab === 'image') {
  1863. const dims = { '2k': [1920, 1080], '3k': [2560, 1440], '4k': [3840, 2160] }[exportRes];
  1864. const ratio = { '16:9': 16 / 9, '4:3': 4 / 3, '1:1': 1 }[exportRatio];
  1865. const rw = Math.round(Math.min(dims[0], dims[1] * ratio));
  1866. const rh = Math.round(rw / ratio);
  1867. const pv = snapSrc(760, 480);
  1868. body = h('div', { className: 'ex-file-body' },
  1869. h('div', { className: 'ex-preview 3d' },
  1870. pv ? h('img', { className: 'ex-snap', src: pv, alt: '' }) : h('div', { className: 'ex-preview-empty' }, '3D 预览加载中…'),
  1871. h('div', { className: 'ex-fold-row' },
  1872. 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, '合')
  1873. )
  1874. ),
  1875. h('div', { className: 'ex-side' },
  1876. [['2k', '2K', '1920*1080', '高清'], ['3k', '3K', '2560*1440', '超清'], ['4k', '4K', '3840*2160', '超高清']].map(function (r) {
  1877. return h('button', { key: r[0], className: 'ex-res' + (exportRes === r[0] ? ' on' : ''), onClick: function () { exportRes = r[0]; renderExport(); } },
  1878. h('b', null, r[1]), h('span', null, r[2]), h('em', null, r[3]));
  1879. }),
  1880. h('div', { className: 'ex-label' }, '构图比例'),
  1881. h(A.Select, { value: exportRatio, style: { width: '100%' }, options: [{ value: '16:9' }, { value: '4:3' }, { value: '1:1' }], onChange: function (v) { exportRatio = v; renderExport(); } }),
  1882. h('div', { className: 'ex-label' }, '背景'),
  1883. h(A.Radio.Group, { value: exportBg, onChange: function (e) { exportBg = e.target.value; renderExport(); }, options: [{ value: 'scene', label: '场景' }, { value: 'transparent', label: '透明' }] }),
  1884. h('button', { className: 'ex-primary', onClick: exportHdImage }, '导出效果图')
  1885. )
  1886. );
  1887. } else {
  1888. const pvVid = snapSrc(760, 480);
  1889. body = h('div', { className: 'ex-file-body' },
  1890. h('div', { className: 'ex-preview 3d' }, pvVid ? h('img', { className: 'ex-snap', src: pvVid, alt: '' }) : null),
  1891. h('div', { className: 'ex-side' },
  1892. h('div', { className: 'ex-anim-grid' }, LB.ANIMS.map(function (a) {
  1893. return h('button', { key: a.id, className: 'ex-anim' + (exportAnim === a.id ? ' on' : ''), onClick: function () { exportAnim = a.id; renderExport(); } },
  1894. h('em', null, a.dur + 's'), h('span', { className: 'anim-illus ' + a.id }));
  1895. })),
  1896. h('button', { className: 'ex-primary', onClick: exportVideo }, '导出视频')
  1897. )
  1898. );
  1899. }
  1900. UI.render(div, h(A.Modal, {
  1901. open: true, onCancel: close, footer: null, width: 940, title: null,
  1902. },
  1903. h('div', { className: 'ex-wrap' },
  1904. h('div', { className: 'ex-tabs' },
  1905. [['file', '设计文件'], ['image', '效果图'], ['video', '视频']].map(function (t) {
  1906. return h('button', { key: t[0], className: exportTab === t[0] ? 'on' : '', onClick: function () { exportTab = t[0]; renderExport(); } }, t[1]);
  1907. }),
  1908. h('button', { className: 'ex-log-btn', onClick: showExportLog }, '⏱ 导出记录')
  1909. ),
  1910. body
  1911. )
  1912. ));
  1913. }
  1914. renderExport();
  1915. }
  1916. let exportAnim = 'fold';
  1917. function printSvgWindow(svgStr, title) {
  1918. const win = window.open('', '_blank');
  1919. if (!win) { UI.message.warning('浏览器拦截了新窗口,请允许弹窗'); return; }
  1920. 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>');
  1921. win.document.close();
  1922. }
  1923. function exportPrintPdf() {
  1924. printSvgWindow(dielineSVG(), state.name + ' 印刷文件');
  1925. logExport('印刷PDF', state.name);
  1926. }
  1927. function exportDielinePdf() {
  1928. printSvgWindow(dielineSVG({ clean: true, noLegend: false }), state.name + ' 刀版');
  1929. logExport('刀版PDF', state.name);
  1930. }
  1931. function exportPreviewJpg() {
  1932. const svgStr = dielineSVG();
  1933. const img = new Image();
  1934. img.onload = function () {
  1935. const scale = 2;
  1936. const c = document.createElement('canvas');
  1937. c.width = img.width * scale;
  1938. c.height = img.height * scale;
  1939. const ctx = c.getContext('2d');
  1940. ctx.fillStyle = '#fff';
  1941. ctx.fillRect(0, 0, c.width, c.height);
  1942. ctx.drawImage(img, 0, 0, c.width, c.height);
  1943. c.toBlob(function (b) {
  1944. downloadBlob(b, state.name + '-dieline.jpg');
  1945. logExport('预览JPG', state.name);
  1946. UI.message.success('预览 JPG 已下载');
  1947. }, 'image/jpeg', 0.92);
  1948. };
  1949. img.src = 'data:image/svg+xml;charset=utf-8,' + encodeURIComponent(svgStr);
  1950. }
  1951. function exportDxf() {
  1952. const dl = dieline();
  1953. const ox = -dl.minX, oy = -dl.minY;
  1954. let out = '0\nSECTION\n2\nENTITIES\n';
  1955. dl.panels.forEach(function (p) {
  1956. 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]];
  1957. for (let i = 0; i < pts.length; i += 1) {
  1958. const a = pts[i], b = pts[(i + 1) % pts.length];
  1959. 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';
  1960. }
  1961. (p.holes || []).forEach(function (ho) {
  1962. for (let i = 0; i < 24; i += 1) {
  1963. const a0 = i / 24 * Math.PI * 2, a1 = (i + 1) / 24 * Math.PI * 2;
  1964. 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';
  1965. }
  1966. });
  1967. });
  1968. dl.folds.forEach(function (f) {
  1969. 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';
  1970. });
  1971. out += '0\nENDSEC\n0\nEOF\n';
  1972. downloadBlob(new Blob([out], { type: 'application/dxf' }), state.name + '-dieline.dxf');
  1973. logExport('刀版DXF', state.name);
  1974. UI.message.success('刀版 DXF 已下载');
  1975. }
  1976. function exportHdImage() {
  1977. if (!main3d || !main3d.ready()) { UI.message.warning('3D 渲染器未就绪'); return; }
  1978. const dims = { '2k': [1920, 1080], '3k': [2560, 1440], '4k': [3840, 2160] }[exportRes];
  1979. const ratio = { '16:9': 16 / 9, '4:3': 4 / 3, '1:1': 1 }[exportRatio];
  1980. const rw = Math.round(Math.min(dims[0], dims[1] * ratio));
  1981. const rh = Math.round(rw / ratio);
  1982. const wasMode = state.mode;
  1983. if (wasMode !== '3d') setMode('3d');
  1984. main3d.render(state, material(), currentPanels());
  1985. main3d.setFold(foldValue / 100);
  1986. if (UI.message.loading) UI.message.loading({ content: '正在渲染 ' + exportRes.toUpperCase() + ' 效果图…', key: 'boxhd', duration: 0 });
  1987. const grab = function () {
  1988. const url = main3d.snapshot(rw, rh, exportBg === 'transparent');
  1989. if (!url || url.length < 1000) {
  1990. setTimeout(grab, 220);
  1991. return;
  1992. }
  1993. const img = new Image();
  1994. img.onload = function () {
  1995. const c = document.createElement('canvas');
  1996. c.width = rw; c.height = rh;
  1997. const ctx = c.getContext('2d');
  1998. if (exportBg !== 'transparent') {
  1999. const g = ctx.createLinearGradient(0, 0, 0, rh);
  2000. g.addColorStop(0, '#f3f1ec'); g.addColorStop(1, '#e7e4dd');
  2001. ctx.fillStyle = g; ctx.fillRect(0, 0, rw, rh);
  2002. }
  2003. ctx.drawImage(img, 0, 0, rw, rh);
  2004. c.toBlob(function (b) {
  2005. downloadBlob(b, state.name + '-' + exportRes.toUpperCase() + '.png');
  2006. logExport('效果图', state.name + ' ' + exportRes.toUpperCase());
  2007. UI.message.success({ content: exportRes.toUpperCase() + ' 效果图已下载', key: 'boxhd' });
  2008. }, 'image/png');
  2009. };
  2010. img.src = url;
  2011. };
  2012. // 等贴图/字体加载完成后再截图,避免 4K 图空白
  2013. setTimeout(function () { requestAnimationFrame(function () { requestAnimationFrame(grab); }); }, 320);
  2014. }
  2015. function exportVideo() {
  2016. if (!main3d || !main3d.ready()) { UI.message.warning('3D 渲染器未就绪'); return; }
  2017. if (typeof MediaRecorder === 'undefined') { UI.message.error('当前浏览器不支持视频录制'); return; }
  2018. if (state.mode !== '3d') setMode('3d');
  2019. const def = LB.ANIMS.find(function (a) { return a.id === exportAnim; });
  2020. UI.message.info('正在录制「' + def.name + '」' + def.dur + 's…');
  2021. const canvas = $('#boxScene canvas');
  2022. const stream = canvas.captureStream(30);
  2023. const rec = new MediaRecorder(stream, { mimeType: MediaRecorder.isTypeSupported('video/webm;codecs=vp9') ? 'video/webm;codecs=vp9' : 'video/webm' });
  2024. const chunks = [];
  2025. rec.ondataavailable = function (e) { if (e.data.size) chunks.push(e.data); };
  2026. rec.onstop = function () {
  2027. const blob = new Blob(chunks, { type: 'video/webm' });
  2028. downloadBlob(blob, state.name + '-' + def.name + '.webm');
  2029. logExport('视频', def.name);
  2030. UI.message.success('动效视频已下载');
  2031. };
  2032. main3d.playAnim(def.id, def.dur, function () { setTimeout(function () { rec.stop(); }, 300); });
  2033. rec.start();
  2034. }
  2035. function showExportLog() {
  2036. const list = exportLog();
  2037. modalInfo('导出记录', list.length
  2038. ? h('div', { className: 'bx-export-log' }, list.map(function (e, i) {
  2039. return h('p', { key: i }, new Date(e.time).toLocaleString() + ' · ' + e.type + ' · ' + e.name);
  2040. }))
  2041. : h(A.Empty, { description: '暂无导出记录' }));
  2042. }
  2043. /* ---------------- 印刷下单 ---------------- */
  2044. function openPrintFlow() {
  2045. const div = document.createElement('div');
  2046. $('#bxModals').appendChild(div);
  2047. let pct = 0;
  2048. const checks = [];
  2049. // 印前检测(本地规则)
  2050. function precheck() {
  2051. checks.length = 0;
  2052. checks.push({ ok: true, text: '刀版结构完整(' + struct().name + ')' });
  2053. checks.push({ ok: (state.smart.bleed || 0) >= 3, text: '出血线 ' + (state.smart.bleed || 0) + 'mm' + ((state.smart.bleed || 0) >= 3 ? '' : '(建议 ≥3mm)') });
  2054. let imgWarn = false, txtWarn = false;
  2055. ['outer', 'inner'].forEach(function (side) {
  2056. FACES.forEach(function (f) {
  2057. (state.faces[side][f.id].items || []).forEach(function (it) {
  2058. if (it.type === 'text' && it.size < 2) txtWarn = true;
  2059. if ((it.type === 'image' || it.type === 'asset') && it.src && it.src.indexOf('data:image/svg') < 0) {
  2060. const m = it.src.match(/^data:image\/(\w+);base64,/);
  2061. if (m && m[1] !== 'svg+xml') {
  2062. const b64 = it.src.split(',')[1] || '';
  2063. const px = b64.length * 0.75;
  2064. if (px < 20000) imgWarn = true;
  2065. }
  2066. }
  2067. });
  2068. });
  2069. });
  2070. checks.push({ ok: !imgWarn, text: '图片清晰度' + (imgWarn ? '(检测到低分辨率图片,印刷可能模糊)' : '') });
  2071. checks.push({ ok: !txtWarn, text: '最小字号' + (txtWarn ? '(有 <2mm 文字,印刷可能不清晰)' : '') });
  2072. checks.push({ ok: true, text: '色彩模式:CMYK 印刷色域' });
  2073. }
  2074. precheck();
  2075. let quoteState = { qty: state.qty, contact: { name: '', phone: '', address: '', note: '' }, submitting: false };
  2076. let stage = 'check';
  2077. function renderFlow() {
  2078. if (stage === 'check') {
  2079. UI.render(div, h(A.Modal, { open: true, footer: null, width: 480, onCancel: function () { UI.reset(div); div.remove(); renderAll(); } },
  2080. h('div', { className: 'pc-wrap' },
  2081. h('div', { className: 'pc-title' }, '印前检测 ', h('em', { className: 'free' }, '限免'), h('i', { className: 'q', title: '智能印刷引擎在您检测设计问题' })),
  2082. h('div', { className: 'pc-ring', style: { '--p': pct } }, h('b', null, pct + '%')),
  2083. h('p', { className: 'pc-sub' }, '智能印刷引擎正在为您检测中…'),
  2084. h('div', { className: 'pc-checks' }, checks.map(function (c, i) {
  2085. return h('p', { key: i, className: c.ok ? 'ok' : 'warn' }, (c.ok ? '✓ ' : '⚠ ') + c.text);
  2086. }))
  2087. )
  2088. ));
  2089. } else {
  2090. const price = priceInfo();
  2091. UI.render(div, h(A.Modal, { open: true, footer: null, width: 1000, onCancel: function () { UI.reset(div); div.remove(); renderAll(); } },
  2092. h('div', { className: 'pq-wrap' },
  2093. h('div', { className: 'pq-head' },
  2094. h('b', null, '印刷报价'),
  2095. h('span', null, '确认印刷配置,沿用原设计与刀版'),
  2096. h('button', { className: 'pq-back', onClick: function () { UI.reset(div); div.remove(); renderAll(); } }, '返回继续编辑 ⇱')
  2097. ),
  2098. h('div', { className: 'pq-cols' },
  2099. h('div', { className: 'pq-left' },
  2100. h('div', { className: 'pq-thumb', dangerouslySetInnerHTML: { __html: dielineSVG({ clean: true, noLegend: true }) } }),
  2101. h('b', { className: 'pq-name' }, libEntry().name),
  2102. h('div', { className: 'pq-kv' }, '盒型 ' + state.boxNo),
  2103. h('div', { className: 'pq-kv' }, '制造尺寸 ' + Math.round(state.w) + ' × ' + Math.round(state.d) + ' × ' + Math.round(state.h) + ' mm'),
  2104. h('div', { className: 'pq-kv' }, '生产主材 ' + material().name),
  2105. h('div', { className: 'pq-kv' }, '印面 ' + (state.side === 'outer' ? '单面(外)' : '单面(内)'))
  2106. ),
  2107. h('div', { className: 'pq-right' },
  2108. h('div', { className: 'pq-sec' }, h('b', null, '订购数量 ⇱')),
  2109. h('div', { className: 'pq-qty-grid' }, [1, 10, 500, 1000, 2000, 5000, 10000, 20000].map(function (v) {
  2110. return h('button', { key: v, className: quoteState.qty === v ? 'on' : '', onClick: function () { state.qty = v; quoteState.qty = v; renderFlow(); } }, v.toLocaleString());
  2111. })),
  2112. h('div', { className: 'pq-custom' },
  2113. h('span', null, '自定义数量'),
  2114. h(A.InputNumber, { value: quoteState.qty, min: 1, style: { width: 130 }, onChange: function (v) { if (v) { state.qty = v; quoteState.qty = v; renderFlow(); } } })
  2115. ),
  2116. h('div', { className: 'pq-sec' }, h('b', null, '印刷配置')),
  2117. h('div', { className: 'pq-kv row' }, h('span', null, '材质'), h('b', null, material().name)),
  2118. h('div', { className: 'pq-kv row' }, h('span', null, '印色')),
  2119. h('div', { className: 'pq-chip-row' }, PRINTS.map(function (p) {
  2120. return h('button', { key: p.id, className: state.print === p.id ? 'on' : '', onClick: function () { state.print = p.id; renderFlow(); } }, p.name);
  2121. })),
  2122. h('div', { className: 'pq-kv row' }, h('span', null, '印刷方式')),
  2123. 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(); } }),
  2124. h('div', { className: 'pq-sec' }, h('b', null, '收货信息')),
  2125. h('div', { className: 'pq-contact' },
  2126. h(A.Input, { placeholder: '联系人', onChange: function (e) { quoteState.contact.name = e.target.value; } }),
  2127. h(A.Input, { placeholder: '手机号', onChange: function (e) { quoteState.contact.phone = e.target.value; } }),
  2128. h(A.Input, { placeholder: '收货地址(省市区 + 详细地址)', onChange: function (e) { quoteState.contact.address = e.target.value; } }),
  2129. h(A.Input, { placeholder: '备注(选填)', onChange: function (e) { quoteState.contact.note = e.target.value; } })
  2130. )
  2131. )
  2132. ),
  2133. h('div', { className: 'pq-foot' },
  2134. h('button', { className: 'pq-service', onClick: function () { UI.message.info('演示环境:400-000-0000'); } }, '🎧 人工咨询'),
  2135. h('span', { className: 'pq-lead' }, '预计加工时间:4 个工作日'),
  2136. h('b', { className: 'pq-price' }, '印刷费 ¥' + price.total.toFixed(2), h('span', null, '(运费待计算)')),
  2137. h('button', { className: 'pq-detail', onClick: function () {
  2138. modalInfo('报价明细', h('div', { className: 'bx-help-steps' },
  2139. h('p', null, '展开面积:' + price.area.toFixed(3) + ' m²'),
  2140. h('p', null, '材质单价:' + material().name + ' × ' + material().rate.toFixed(2) + ' 元/m²'),
  2141. h('p', null, '印色系数:' + print().name + ' × ' + print().factor),
  2142. h('p', null, '结构费:' + struct().name + ' ¥' + struct().fee.toFixed(2)),
  2143. h('p', null, '数量折扣:' + Math.round(price.disc * 100) + '%'),
  2144. h('p', null, '单价:¥' + price.unit.toFixed(2) + ' × ' + state.qty + ' 个')
  2145. ));
  2146. } }, '报价明细'),
  2147. h('button', { className: 'pq-order', disabled: quoteState.submitting, onClick: function () {
  2148. if (window.PL && PL.auth && !PL.auth.user()) {
  2149. PL.auth.require(function () { /* 登录后再次点击即可下单 */ });
  2150. return;
  2151. }
  2152. if (!window.PL || !PL.api) return;
  2153. const c = quoteState.contact;
  2154. if (!c.name || !c.phone || !c.address) {
  2155. UI.message.warning('请完整填写联系人、手机号和收货地址');
  2156. return;
  2157. }
  2158. if (quoteState.submitting) return;
  2159. quoteState.submitting = true;
  2160. renderFlow();
  2161. const dl = dieline();
  2162. const dlJson = JSON.parse(JSON.stringify(dl));
  2163. dlJson.kind = 'box';
  2164. dlJson.meta = {
  2165. boxNo: state.boxNo, boxName: libEntry().name, structure: state.structure,
  2166. inner: { w: Math.round(state.w), d: Math.round(state.d), h: Math.round(state.h) },
  2167. material: material().name, thickness: String(material().thickness), qty: state.qty
  2168. };
  2169. let design = null;
  2170. try { design = JSON.parse(snapshot()); } catch (err) {}
  2171. const payload = {
  2172. type: 'box',
  2173. contact: { name: c.name, phone: c.phone, email: '', address: c.address, note: c.note },
  2174. spec: {
  2175. boxNo: state.boxNo, boxName: libEntry().name, structure: state.structure,
  2176. w: Math.round(state.w), d: Math.round(state.d), h: Math.round(state.h),
  2177. material: state.material, materialName: material().name,
  2178. thickness: material().thickness, print: state.print, printName: print().name,
  2179. printWay: state.printWay, qty: state.qty, smart: state.smart
  2180. },
  2181. quote: { unit: price.unit, total: price.total, area: price.area, disc: price.disc },
  2182. summary: libEntry().name + ' ' + Math.round(state.w) + '×' + Math.round(state.d) + '×' + Math.round(state.h) + 'mm · ' + material().name + ' · ' + state.qty + ' 个',
  2183. design: design,
  2184. dieline: dlJson,
  2185. previews: {}
  2186. };
  2187. // 3D 效果图随订单一起提交,订单列表/详情可直接看到设计效果
  2188. let boxShot = '';
  2189. if (main3d && main3d.ready()) {
  2190. try {
  2191. main3d.render(state, material(), currentPanels());
  2192. main3d.setFold(foldValue / 100);
  2193. boxShot = main3d.snapshot(1200, 900, false);
  2194. } catch (e) { boxShot = ''; }
  2195. }
  2196. PL.api.svgToPng(dielineSVG({ clean: true, noLegend: true }), 1200).then(function (png) {
  2197. payload.previews = { dieline: png };
  2198. if (boxShot) payload.previews.box3d = boxShot;
  2199. }, function () {
  2200. if (boxShot) payload.previews.box3d = boxShot;
  2201. }).then(function () {
  2202. return PL.api.post('/orders', payload, { timeout: 60000 });
  2203. }).then(function (r) {
  2204. const orders = JSON.parse(localStorage.getItem('pouchlab.box.orders') || '[]');
  2205. 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 });
  2206. localStorage.setItem('pouchlab.box.orders', JSON.stringify(orders.slice(0, 30)));
  2207. UI.reset(div); div.remove();
  2208. modalInfo('下单成功', h('div', { className: 'bx-help-steps' },
  2209. h('p', null, '订单号:' + r.orderNo),
  2210. h('p', null, '数量:' + state.qty + ' 个 · 金额:¥' + price.total.toFixed(2)),
  2211. h('p', null, '支付与生产进度请在「我的订单」查看'),
  2212. h('p', null, h('a', { href: 'orders.html', style: { color: '#ff5c2b', fontWeight: 600 } }, '前往我的订单 →'))
  2213. ));
  2214. renderAll();
  2215. }, function (err) {
  2216. quoteState.submitting = false;
  2217. renderFlow();
  2218. if (err && err.network) {
  2219. // 离线回退:沿用旧的本地保存
  2220. const orderNo = 'PL' + Date.now().toString().slice(-10);
  2221. const orders = JSON.parse(localStorage.getItem('pouchlab.box.orders') || '[]');
  2222. 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 });
  2223. localStorage.setItem('pouchlab.box.orders', JSON.stringify(orders.slice(0, 30)));
  2224. UI.reset(div); div.remove();
  2225. modalInfo('下单成功(离线保存)', h('div', { className: 'bx-help-steps' },
  2226. h('p', null, '订单号:' + orderNo),
  2227. h('p', null, '服务器暂不可达,订单已保存在本地,联网后请重新提交。')
  2228. ));
  2229. renderAll();
  2230. return;
  2231. }
  2232. UI.message.error(err.message || '下单失败,请重试');
  2233. });
  2234. } }, quoteState.submitting ? '正在提交…' : '立即下单')
  2235. )
  2236. )
  2237. ));
  2238. }
  2239. }
  2240. // 检测进度动画
  2241. const timer = setInterval(function () {
  2242. pct = Math.min(100, pct + Math.ceil(Math.random() * 22));
  2243. if (pct >= 100) {
  2244. clearInterval(timer);
  2245. setTimeout(function () { stage = 'quote'; renderFlow(); }, 500);
  2246. } else renderFlow();
  2247. }, 320);
  2248. renderFlow();
  2249. }
  2250. /* ---------------- 文件菜单 ---------------- */
  2251. function newPlan() {
  2252. modalConfirm('新建设计方案', h('p', null, '当前方案已自动保存到「我的设计方案」,新建后将开始一个空白方案。'), function () {
  2253. savePlanToLibrary();
  2254. pushUndo();
  2255. state.planId = 'p' + Date.now().toString(36);
  2256. state.name = '未命名纸盒';
  2257. state.faces = blankFaces();
  2258. state.selectedItemId = null;
  2259. commit();
  2260. UI.message.success('已新建设计方案');
  2261. }, '新建');
  2262. }
  2263. function copyPlan() {
  2264. pushUndo();
  2265. state.planId = 'p' + Date.now().toString(36);
  2266. state.name = state.name + ' 副本';
  2267. commit();
  2268. UI.message.success('已创建副本:' + state.name);
  2269. }
  2270. function openMyPlans() {
  2271. const list = plansList();
  2272. modalInfo('我的设计方案', list.length
  2273. ? h('div', { className: 'bx-plan-list' }, list.map(function (p) {
  2274. return h('div', { key: p.id, className: 'bx-plan-row' },
  2275. h('span', { className: 't' }, h('b', null, p.name), h('em', null, new Date(p.time).toLocaleString() + ' · ' + p.boxNo)),
  2276. h('button', { onClick: function () { openPlanData(p.id); } }, '打开'),
  2277. h('button', { className: 'del', onClick: function () {
  2278. const l = plansList().filter(function (x) { return x.id !== p.id; });
  2279. localStorage.setItem(LIST_KEY, JSON.stringify(l));
  2280. localStorage.removeItem(planDataKey(p.id));
  2281. UI.message.success('已删除');
  2282. $('#bxFileMenu').hidden = true;
  2283. } }, '删除')
  2284. );
  2285. }))
  2286. : h(A.Empty, { description: '暂无保存的方案' }));
  2287. }
  2288. function openPlanData(id) {
  2289. try {
  2290. const data = JSON.parse(localStorage.getItem(planDataKey(id)) || 'null');
  2291. if (!data) { UI.message.warning('方案数据缺失'); return; }
  2292. pushUndo();
  2293. Object.assign(state, data);
  2294. state.planId = id;
  2295. const f = blankFaces();
  2296. ['outer', 'inner'].forEach(function (side) {
  2297. FACES.forEach(function (face) {
  2298. const src = (data.faces[side] && data.faces[side][face.id]) || {};
  2299. f[side][face.id] = { color: src.color || '', texture: src.texture || null, items: src.items || [] };
  2300. });
  2301. });
  2302. state.faces = f;
  2303. commit(false);
  2304. UI.message.success('已打开「' + state.name + '」');
  2305. } catch (e) { UI.message.error('方案打开失败'); }
  2306. }
  2307. function openHistory() {
  2308. const hist = JSON.parse(localStorage.getItem(HIST_KEY + '.' + state.planId) || '[]');
  2309. modalInfo('历史版本记录', hist.length
  2310. ? h('div', { className: 'bx-plan-list' }, hist.slice(0, 15).map(function (hh, i) {
  2311. return h('div', { key: i, className: 'bx-plan-row' },
  2312. h('span', { className: 't' }, h('b', null, '版本 ' + (hist.length - i)), h('em', null, new Date(hh.time).toLocaleString())),
  2313. h('button', { onClick: function () { restore(hh.snap); UI.message.success('已恢复历史版本'); } }, '恢复')
  2314. );
  2315. }))
  2316. : h(A.Empty, { description: '暂无历史版本' }));
  2317. }
  2318. /* ---------------- 渲染总入口 ---------------- */
  2319. function renderTool() {
  2320. UI.render($('#bxPanelBody'), panelBox());
  2321. document.querySelectorAll('#bxRail button').forEach(function (b) {
  2322. b.classList.toggle('on', b.dataset.tab === currentTab);
  2323. });
  2324. }
  2325. function renderProps() {
  2326. UI.render($('#bxPropsBody'), propsPanel());
  2327. }
  2328. function renderSideThumb() {
  2329. const el = $('#bxSideThumb');
  2330. if (el) {
  2331. // 使用真实设计稿缩略图,与 2D/3D 画面保持一致,并支持点击选面
  2332. el.innerHTML = '<div class="side-thumb-svg">' + dielineSVG({ clean: true, noLegend: true, idPrefix: 'side' }) + '</div>';
  2333. }
  2334. const mid = $('#bxModelId');
  2335. if (mid) mid.textContent = '模型ID: ' + state.boxNo;
  2336. }
  2337. function renderAll() {
  2338. $('#bxFileName').textContent = state.name;
  2339. document.title = state.name + ' — 3D云设计编辑器 · 袋研社';
  2340. renderDieline();
  2341. renderSideThumb();
  2342. renderTool();
  2343. renderProps();
  2344. $('#bxMini3d').hidden = state.mode !== '2d';
  2345. if (state.mode === '2d') {
  2346. renderMini();
  2347. } else {
  2348. render3d();
  2349. $('#boxFoldRange').value = Math.round(foldValue);
  2350. }
  2351. $('#bxColorCur').style.background = (curFaces()._plain && curFaces()._plain.color) || material().paper;
  2352. }
  2353. /* ---------------- 折叠动画 ---------------- */
  2354. function stopFoldAnim() {
  2355. if (foldAnim) {
  2356. if (main3d && main3d.stopAnim) main3d.stopAnim(); // 音频心跳补间由 box3d 停止
  2357. if (foldAnim && foldAnim !== 'audio') cancelAnimationFrame(foldAnim);
  2358. foldAnim = null;
  2359. }
  2360. const play = $('#bxFoldPlay');
  2361. if (play) play.textContent = '▶';
  2362. const miniPlay = $('#bxMiniPlay');
  2363. if (miniPlay) miniPlay.textContent = '▶';
  2364. }
  2365. function animateFoldTo(to, mini) {
  2366. stopFoldAnim();
  2367. const from = foldValue;
  2368. if (Math.abs(to - from) < 0.5) { setFold(to); return; }
  2369. // 音频线程心跳补间:页面时钟/rAF 被冻结时依然流畅
  2370. if (main3d && main3d.ready && main3d.ready() && main3d.tween) {
  2371. foldAnim = 'audio';
  2372. main3d.tween(1.1, function (p) {
  2373. const eased = p < 0.5 ? 2 * p * p : 1 - Math.pow(-2 * p + 2, 2) / 2;
  2374. setFold(from + (to - from) * eased, mini);
  2375. }, function () {
  2376. foldAnim = null;
  2377. setFold(to);
  2378. });
  2379. return;
  2380. }
  2381. // 无 3D 时 rAF 降级
  2382. const start = performance.now();
  2383. const dur = 1100;
  2384. function step(now) {
  2385. const t = Math.min(1, (now - start) / dur);
  2386. const eased = t < 0.5 ? 2 * t * t : 1 - Math.pow(-2 * t + 2, 2) / 2;
  2387. setFold(from + (to - from) * eased, mini);
  2388. if (t < 1) foldAnim = requestAnimationFrame(step);
  2389. else { foldAnim = null; setFold(to); }
  2390. }
  2391. foldAnim = requestAnimationFrame(step);
  2392. }
  2393. function setFold(v, mini) {
  2394. foldValue = clamp(Number(v) || 0, 0, 100);
  2395. if (main3d && main3d.ready()) main3d.setFold(foldValue / 100);
  2396. if (mini3d && mini3d.ready()) mini3d.setFold(foldValue / 100);
  2397. const range = $('#boxFoldRange');
  2398. if (range && !mini) range.value = String(Math.round(foldValue));
  2399. const miniRange = $('#bxMiniFold');
  2400. if (miniRange && mini) miniRange.value = String(Math.round(foldValue));
  2401. const play = $('#bxFoldPlay');
  2402. if (play) play.textContent = foldAnim ? '❚❚' : '▶';
  2403. }
  2404. /* ---------------- 迷你 3D 自动播放(CSS 合成器动画) ---------------- */
  2405. let miniAuto = true;
  2406. function setMiniAuto(on) {
  2407. miniAuto = !!on;
  2408. const stage = document.getElementById('bxMiniStage');
  2409. if (stage) stage.classList.toggle('autoplay', miniAuto);
  2410. // CSS 动画接管旋转时,停掉 Three 的 JS 自转,避免叠加
  2411. // mini 的旋转只由 CSS 动画或手动拖拽负责,Three 的 JS 自转恒定关闭
  2412. if (mini3d && mini3d.setAutoRotate) mini3d.setAutoRotate(false);
  2413. if (!miniAuto && mini3d && mini3d.resetView) {
  2414. // 退出 CSS 旋转时把视角归位,保证手动拖拽从标准角度开始
  2415. mini3d.resetView();
  2416. }
  2417. updateMiniAutoBtn();
  2418. }
  2419. function updateMiniAutoBtn() {
  2420. const btn = document.getElementById('bxMiniAuto');
  2421. if (btn) btn.classList.toggle('on', miniAuto);
  2422. }
  2423. /* ---------------- 事件绑定 ---------------- */
  2424. function setTab(tab) {
  2425. currentTab = tab;
  2426. renderTool();
  2427. }
  2428. function bind() {
  2429. // 模式切换
  2430. $('#bxModeSwitch').addEventListener('click', function (e) {
  2431. const b = e.target.closest('[data-mode]');
  2432. if (b) setMode(b.dataset.mode);
  2433. });
  2434. // 左栏
  2435. $('#bxRail').addEventListener('click', function (e) {
  2436. const b = e.target.closest('[data-tab]');
  2437. if (!b) return;
  2438. setTab(b.dataset.tab);
  2439. });
  2440. // 文件菜单
  2441. const fileMenu = $('#bxFileMenu');
  2442. $('#bxFileBtn').addEventListener('click', function (e) {
  2443. e.stopPropagation();
  2444. fileMenu.hidden = !fileMenu.hidden;
  2445. });
  2446. document.addEventListener('click', function (e) {
  2447. if (!fileMenu.hidden && !e.target.closest('.bx-file-menu-wrap')) fileMenu.hidden = true;
  2448. });
  2449. fileMenu.addEventListener('click', function (e) {
  2450. const b = e.target.closest('[data-file]');
  2451. if (!b) return;
  2452. fileMenu.hidden = true;
  2453. const act = b.dataset.file;
  2454. if (act === 'new') newPlan();
  2455. if (act === 'copy') copyPlan();
  2456. if (act === 'mine') openMyPlans();
  2457. if (act === 'history') openHistory();
  2458. if (act === 'save') { savePlanToLibrary(); try { localStorage.setItem(planDataKey(state.planId), JSON.stringify(state)); } catch (err) {} UI.message.success('方案已保存'); }
  2459. if (act === 'import-art') UI.message.info('演示环境:支持上传 JPG/PNG/SVG(上传面板)');
  2460. if (act === 'import-cad') showImportCad();
  2461. if (act === 'submit') UI.message.info('演示环境:投稿至模板中心需要登录账号');
  2462. });
  2463. $('#bxFileNameWrap').addEventListener('click', function () {
  2464. const input = document.createElement('div');
  2465. document.body.appendChild(input);
  2466. const close = modalConfirm('重命名方案', h(A.Input, { id: 'bxRenameInput', defaultValue: state.name, maxLength: 30 }), function () {
  2467. const v = document.getElementById('bxRenameInput').value;
  2468. if (v) { state.name = v; commit(); }
  2469. }, '确定');
  2470. });
  2471. // 顶部工具
  2472. $('#bxShareBtn').addEventListener('click', function () {
  2473. const url = location.href.split('#')[0] + '#' + state.planId;
  2474. try { navigator.clipboard.writeText(url); UI.message.success('分享链接已复制'); }
  2475. catch (e) { UI.message.info('分享链接:' + url); }
  2476. });
  2477. $('#bxSaveBtn').addEventListener('click', function () {
  2478. savePlanToLibrary();
  2479. try { localStorage.setItem(planDataKey(state.planId), JSON.stringify(state)); } catch (e) {}
  2480. UI.message.success('方案已保存');
  2481. });
  2482. $('#bxUndoBtn').addEventListener('click', undo);
  2483. $('#bxRedoBtn').addEventListener('click', redo);
  2484. $('#bxPrintBtn').addEventListener('click', openPrintFlow);
  2485. $('#bxAiBtn').addEventListener('click', aiFaceModal);
  2486. $('#bxRenderBtn').addEventListener('click', function () {
  2487. setMode('3d');
  2488. if (main3d && main3d.ready()) {
  2489. playAnim(LB.ANIMS[0]);
  2490. UI.message.success('本地实时渲染:正在播放「折叠展开」动效');
  2491. }
  2492. });
  2493. $('#bxExportBtn').addEventListener('click', openExport);
  2494. $('#bxAvatar').addEventListener('click', function () {
  2495. if (window.PL && PL.auth) PL.auth.open();
  2496. });
  2497. // 2D 画布
  2498. $('#bxZoomIn2d').addEventListener('click', function () { state.view2d.zoom = clamp(state.view2d.zoom * 1.15, 0.1, 3); renderDieline(); });
  2499. $('#bxZoomOut2d').addEventListener('click', function () { state.view2d.zoom = clamp(state.view2d.zoom / 1.15, 0.1, 3); renderDieline(); });
  2500. $('#bxFit2d').addEventListener('click', fit2d);
  2501. $('#bxPreviewToggle').addEventListener('click', function () {
  2502. state.showLines = !state.showLines;
  2503. this.classList.toggle('on', !state.showLines);
  2504. renderDieline();
  2505. });
  2506. $('#bxPanToggle').addEventListener('click', function () {
  2507. panMode = !panMode;
  2508. this.classList.toggle('on', panMode);
  2509. $('#bxFlat').style.cursor = panMode ? 'grab' : '';
  2510. });
  2511. // 外侧/内侧
  2512. $('#bxSideFloat').addEventListener('click', function (e) {
  2513. const b = e.target.closest('[data-side]');
  2514. if (!b || b.dataset.side === state.side) return;
  2515. state.side = b.dataset.side;
  2516. state.selectedItemId = null;
  2517. document.querySelectorAll('#bxSideFloat [data-side]').forEach(function (x) {
  2518. x.classList.toggle('on', x.dataset.side === state.side);
  2519. });
  2520. commit();
  2521. });
  2522. // 迷你 3D
  2523. $('#bxMiniPlay').addEventListener('click', function () {
  2524. if (foldAnim) { stopFoldAnim(); return; }
  2525. animateFoldTo(foldValue >= 99 ? 0 : 100, true);
  2526. this.textContent = '❚❚';
  2527. });
  2528. $('#bxMiniFold').addEventListener('input', function () { stopFoldAnim(); setFold(this.value, true); });
  2529. $('#bxMiniReset').addEventListener('click', function () { if (mini3d) mini3d.resetView(); });
  2530. $('#bxMiniZoom').addEventListener('click', function () { if (mini3d) mini3d.setZoom(1.4); });
  2531. $('#bxMiniAuto').addEventListener('click', function () {
  2532. setMiniAuto(!miniAuto);
  2533. });
  2534. // 3D 控件
  2535. $('#bxFoldPlay').addEventListener('click', function () {
  2536. if (foldAnim) { stopFoldAnim(); return; }
  2537. animateFoldTo(foldValue >= 99 ? 0 : 100);
  2538. this.textContent = '❚❚';
  2539. });
  2540. $('#boxFoldRange').addEventListener('input', function () { stopFoldAnim(); setFold(this.value); });
  2541. $('#bxFoldReset').addEventListener('click', function () { if (main3d) main3d.resetView(); });
  2542. $('#bx4kBtn').addEventListener('click', function () { exportRes = '4k'; exportTab = 'image'; openExport(); });
  2543. // 3D 快捷颜色
  2544. const pop = $('#bxColorPop');
  2545. $('#bxColorBtn').addEventListener('click', function (e) {
  2546. e.stopPropagation();
  2547. pop.hidden = !pop.hidden;
  2548. });
  2549. document.addEventListener('click', function (e) {
  2550. if (!pop.hidden && !e.target.closest('#bxColorQuick')) pop.hidden = true;
  2551. });
  2552. $('#bxColorInput').addEventListener('input', function () {
  2553. setPlainColor(this.value);
  2554. });
  2555. $('#bxColorGrid').innerHTML = LB.SWATCHES.map(function (c) {
  2556. return '<span class="cc-swatch" data-cc="' + c + '" style="background:' + c + '"></span>';
  2557. }).join('') + (window.PL.pantone ? '<div class="cc-pms-note">' + window.PL.pantone.note + '</div>' : '');
  2558. $('#bxColorQuick').addEventListener('click', function (e) {
  2559. const sw = e.target.closest('[data-cc]');
  2560. if (!sw) return;
  2561. setPlainColor(sw.dataset.cc === 'none' ? '' : sw.dataset.cc);
  2562. if (sw.dataset.cc !== 'none') $('#bxColorCur').style.background = sw.dataset.cc;
  2563. });
  2564. function setPlainColor(c) {
  2565. pushUndo();
  2566. ['outer', 'inner'].forEach(function (side) {
  2567. state.faces[side]._plain = { color: c };
  2568. FACES.forEach(function (f) {
  2569. const face = state.faces[side][f.id];
  2570. if (!c || !face.color || face.color === '#fbf7ee') face.color = c;
  2571. });
  2572. });
  2573. commit();
  2574. }
  2575. // 2D 画布拖拽 / 点选
  2576. const flat = $('#bxFlat');
  2577. flat.addEventListener('pointerdown', function (e) {
  2578. if (e.target.closest('.bx-canvas-corner, .bx-side-float, .bx-mini3d, .dieline-hit')) return;
  2579. if (!panMode && !e.shiftKey) return;
  2580. panDrag = { x: e.clientX, y: e.clientY, px: state.view2d.panX, py: state.view2d.panY };
  2581. flat.setPointerCapture(e.pointerId);
  2582. });
  2583. flat.addEventListener('pointermove', function (e) {
  2584. if (!panDrag) return;
  2585. state.view2d.panX = panDrag.px + (e.clientX - panDrag.x);
  2586. state.view2d.panY = panDrag.py + (e.clientY - panDrag.y);
  2587. renderDieline();
  2588. });
  2589. flat.addEventListener('pointerup', function () { panDrag = null; });
  2590. // 图层面板拖拽排序(按住行上下拖,松手落位;兼容 pointer / mouse / 合成拖拽)
  2591. let layerDrag = null;
  2592. function layerDragStart(row, e) {
  2593. if (!row || !row.dataset.layerId || layerDrag) return;
  2594. if (e.target && e.target.closest && e.target.closest('button')) return;
  2595. layerDrag = { id: row.dataset.layerId, row: row, startY: e.clientY, moved: false, target: null };
  2596. }
  2597. function layerDragCleanup() {
  2598. document.querySelectorAll('.bx-layer-row').forEach(function (r) {
  2599. r.classList.remove('dragging', 'drop-above', 'drop-below');
  2600. });
  2601. }
  2602. function layerDragStartListen(e) {
  2603. if (layerDrag) { layerDragCleanup(); layerDrag = null; }
  2604. const row = e.target.closest && e.target.closest('.bx-layer-row');
  2605. layerDragStart(row, e);
  2606. }
  2607. function layerDragMoveListen(e) {
  2608. if (!layerDrag && (e.buttons & 1) === 1) layerDragStart(e.target.closest && e.target.closest('.bx-layer-row'), e);
  2609. if (!layerDrag) return;
  2610. if (!layerDrag.moved && Math.abs(e.clientY - layerDrag.startY) <= 4) return;
  2611. if (!layerDrag.moved) layerDrag.row.classList.add('dragging');
  2612. layerDrag.moved = true;
  2613. if (e.cancelable) e.preventDefault();
  2614. const list = document.querySelector('.bx-layer-list');
  2615. if (!list) return;
  2616. const rows = [...list.querySelectorAll('.bx-layer-row')];
  2617. rows.forEach(function (r) { r.classList.remove('drop-above', 'drop-below'); });
  2618. let target = null;
  2619. for (let i = 0; i < rows.length; i += 1) {
  2620. const r = rows[i];
  2621. if (r === layerDrag.row || !r.dataset.layerId) continue;
  2622. const rc = r.getBoundingClientRect();
  2623. if (e.clientY >= rc.top && e.clientY <= rc.bottom) {
  2624. target = { row: r, above: e.clientY < rc.top + rc.height / 2 };
  2625. break;
  2626. }
  2627. }
  2628. if (target) target.row.classList.add(target.above ? 'drop-above' : 'drop-below');
  2629. // 即时落位:跨过插入线立即排序(无需等待松手)
  2630. const tid = target ? target.row.dataset.layerId : null;
  2631. if (target && (layerDrag.lastTargetId !== tid || layerDrag.lastAbove !== target.above)) {
  2632. layerDrag.lastTargetId = tid;
  2633. layerDrag.lastAbove = target.above;
  2634. reorderLayer(layerDrag.id, tid, target.above);
  2635. layerDragCleanup();
  2636. layerDrag.row = document.querySelector('.bx-layer-row[data-layer-id="' + layerDrag.id + '"]');
  2637. } else if (!target) {
  2638. layerDrag.lastTargetId = null;
  2639. }
  2640. }
  2641. function layerDragEndListen() {
  2642. if (!layerDrag) return;
  2643. layerDrag = null;
  2644. layerDragCleanup();
  2645. }
  2646. document.addEventListener('pointerdown', layerDragStartListen);
  2647. document.addEventListener('mousedown', layerDragStartListen);
  2648. document.addEventListener('pointermove', layerDragMoveListen, { passive: false });
  2649. document.addEventListener('mousemove', layerDragMoveListen, { passive: false });
  2650. document.addEventListener('pointerup', layerDragEndListen);
  2651. document.addEventListener('mouseup', layerDragEndListen);
  2652. // 2D 刀版元素拖拽(编辑在 2D 平铺上完成,迷你 3D 实时预览)
  2653. const dielineEl = $('#boxDieline');
  2654. let itemDrag = null, lastDragAt = 0;
  2655. function svgLoc(svg, e) {
  2656. if (!svg) return null;
  2657. const ctm = svg.getScreenCTM();
  2658. if (!ctm) return null;
  2659. const pt = svg.createSVGPoint();
  2660. pt.x = e.clientX;
  2661. pt.y = e.clientY;
  2662. return pt.matrixTransform(ctm.inverse());
  2663. }
  2664. function locToPct(svg, loc, face) {
  2665. const dl = dieline();
  2666. const panel = dl.panels.find(function (p) { return p.face === face; });
  2667. if (!panel) return null;
  2668. const fb = panelBounds(panel);
  2669. const pad = 30 + (state.smart.bleed || 0);
  2670. const lx = state.side === 'inner' ? svg.viewBox.baseVal.width - loc.x : loc.x;
  2671. return {
  2672. x: (lx - pad + dl.minX - fb.x) / fb.w * 100,
  2673. y: (loc.y - pad + dl.minY - fb.y) / fb.h * 100
  2674. };
  2675. }
  2676. dielineEl.addEventListener('pointerdown', function (e) {
  2677. const hitEl = e.target.closest('.bx-item-hit');
  2678. if (!hitEl) return;
  2679. e.preventDefault();
  2680. const face = hitEl.dataset.itemFace || state.selectedFace;
  2681. // 元素可能位于未选中的面,按命中面查找,避免必须先点面再点文字
  2682. const faceObj = state.faces[state.side] && state.faces[state.side][face];
  2683. const it = faceObj && (faceObj.items || []).find(function (x) { return x.id === hitEl.dataset.itemId; });
  2684. if (!it) return;
  2685. const svg = dielineEl.querySelector('svg');
  2686. const loc = svgLoc(svg, e);
  2687. const pct = loc && locToPct(svg, loc, face);
  2688. pushUndo();
  2689. state.selectedItemId = it.id;
  2690. state.selectedFace = face;
  2691. renderProps();
  2692. itemDrag = {
  2693. id: it.id,
  2694. face: face,
  2695. // 记录抓取点相对元素中心的偏移,拖动时不再让元素跳到指针下
  2696. ox: pct ? pct.x - it.x : 0,
  2697. oy: pct ? pct.y - it.y : 0,
  2698. moved: false,
  2699. pointerId: e.pointerId
  2700. };
  2701. try { dielineEl.setPointerCapture(e.pointerId); } catch (err) {}
  2702. });
  2703. dielineEl.addEventListener('pointermove', function (e) {
  2704. if (!itemDrag) return;
  2705. e.preventDefault();
  2706. const svg = dielineEl.querySelector('svg');
  2707. const loc = svgLoc(svg, e);
  2708. if (!loc) return;
  2709. const pct = locToPct(svg, loc, itemDrag.face);
  2710. const it = findItem(itemDrag.id);
  2711. if (!pct || !it) return;
  2712. const nx = clamp(pct.x - itemDrag.ox, 0, 100);
  2713. const ny = clamp(pct.y - itemDrag.oy, 0, 100);
  2714. if (Math.abs(nx - it.x) < 0.05 && Math.abs(ny - it.y) < 0.05) return;
  2715. it.x = Math.round(nx * 10) / 10;
  2716. it.y = Math.round(ny * 10) / 10;
  2717. itemDrag.moved = true;
  2718. renderDieline();
  2719. if (mini3d && mini3d.ready()) { mini3d.render(state, material(), currentPanels()); mini3d.setFold(foldValue / 100); }
  2720. if (main3d && main3d.ready()) { main3d.render(state, material(), currentPanels()); main3d.setFold(foldValue / 100); }
  2721. });
  2722. dielineEl.addEventListener('pointerup', function (e) {
  2723. if (!itemDrag) return;
  2724. const wasMoved = itemDrag.moved;
  2725. try { dielineEl.releasePointerCapture(itemDrag.pointerId); } catch (err) {}
  2726. itemDrag = null;
  2727. if (wasMoved) {
  2728. lastDragAt = Date.now();
  2729. commit(false);
  2730. renderProps();
  2731. renderSideThumb();
  2732. }
  2733. });
  2734. dielineEl.addEventListener('pointercancel', function () {
  2735. if (itemDrag) {
  2736. try { dielineEl.releasePointerCapture(itemDrag.pointerId); } catch (err) {}
  2737. itemDrag = null;
  2738. }
  2739. });
  2740. dielineEl.addEventListener('click', function (e) {
  2741. if (Date.now() - lastDragAt < 300) return;
  2742. if (e.target.closest('.bx-item-hit')) return;
  2743. const f = e.target.closest('[data-face]');
  2744. if (!f || !f.dataset.face) return;
  2745. state.selectedFace = f.dataset.face;
  2746. state.selectedItemId = null;
  2747. commit(false);
  2748. // 选中面后让迷你 3D 自动转向该面,保持 2D/3D 视角一致
  2749. if (state.mode === '2d') {
  2750. if (miniAuto) setMiniAuto(false);
  2751. if (mini3d && mini3d.focusFace) mini3d.focusFace(f.dataset.face);
  2752. }
  2753. });
  2754. // 缩略图选面:与 2D 刀版同步
  2755. const sideThumbEl = $('#bxSideThumb');
  2756. sideThumbEl.addEventListener('click', function (e) {
  2757. const f = e.target.closest('[data-face]');
  2758. if (!f || !f.dataset.face) return;
  2759. state.selectedFace = f.dataset.face;
  2760. state.selectedItemId = null;
  2761. commit(false);
  2762. if (state.mode === '2d') {
  2763. if (miniAuto) setMiniAuto(false);
  2764. if (mini3d && mini3d.focusFace) mini3d.focusFace(f.dataset.face);
  2765. }
  2766. });
  2767. // 滚轮缩放 2D
  2768. flat.addEventListener('wheel', function (e) {
  2769. if (state.mode !== '2d') return;
  2770. e.preventDefault();
  2771. state.view2d.zoom = clamp(state.view2d.zoom * (e.deltaY > 0 ? 0.92 : 1.08), 0.1, 3);
  2772. renderDieline();
  2773. }, { passive: false });
  2774. // 键盘
  2775. document.addEventListener('keydown', function (e) {
  2776. const tag = (document.activeElement && document.activeElement.tagName) || '';
  2777. if (tag === 'INPUT' || tag === 'TEXTAREA') return;
  2778. if ((e.ctrlKey || e.metaKey) && e.key.toLowerCase() === 'z') {
  2779. e.preventDefault();
  2780. if (e.shiftKey) redo(); else undo();
  2781. } else if ((e.ctrlKey || e.metaKey) && e.key.toLowerCase() === 's') {
  2782. e.preventDefault();
  2783. savePlanToLibrary();
  2784. UI.message.success('方案已保存');
  2785. } else if (e.key === 'Delete' || e.key === 'Backspace') {
  2786. if (state.selectedItemId) { e.preventDefault(); removeItem(state.selectedItemId); }
  2787. } else if (e.key === 'Tab') {
  2788. e.preventDefault();
  2789. state.side = state.side === 'outer' ? 'inner' : 'outer';
  2790. document.querySelectorAll('#bxSideFloat [data-side]').forEach(function (x) {
  2791. x.classList.toggle('on', x.dataset.side === state.side);
  2792. });
  2793. commit();
  2794. }
  2795. });
  2796. let resizeTimer = null;
  2797. window.addEventListener('resize', function () {
  2798. clearTimeout(resizeTimer);
  2799. resizeTimer = setTimeout(function () { renderDieline(); }, 150);
  2800. });
  2801. }
  2802. /* ---------------- 初始化 ---------------- */
  2803. function init() {
  2804. document.body.setAttribute('data-build', '1.2.0');
  2805. window.__PL_BUILD = '1.2.0';
  2806. if (window.PL.box3d) {
  2807. main3d = window.PL.box3d.create($('#boxScene'), {
  2808. onFacePick: function (face) {
  2809. state.selectedFace = face;
  2810. state.selectedItemId = null;
  2811. commit(false);
  2812. renderSideThumb();
  2813. setMode('2d');
  2814. }
  2815. });
  2816. mini3d = window.PL.box3d.create($('#bxMiniStage'), {
  2817. mini: true,
  2818. onInteract: function () { setMiniAuto(false); }
  2819. });
  2820. // 迷你 3D 默认自动播放(CSS 合成器动画,不受 JS 节流影响),拖拽后停止,点按钮恢复
  2821. setMiniAuto(true);
  2822. }
  2823. window.__boxDebug = {
  2824. get main3d() { return main3d; },
  2825. get mini3d() { return mini3d; },
  2826. state: state,
  2827. dieline: dieline,
  2828. renderAll: renderAll
  2829. };
  2830. // 默认外观:正面放一个示例文字
  2831. if (!(curFaces().front.items || []).length && !(curFaces().front.color)) {
  2832. curFaces().front.items = [{
  2833. id: 'demo1', type: 'text', text: 'POUCHLAB', size: 12, weight: 800,
  2834. color: '#17140f', align: 'center', x: 50, y: 42, lineHeight: 1.2
  2835. }, {
  2836. id: 'demo2', type: 'text', text: '反向插锁盒 · 120×80×180mm', size: 4, weight: 400,
  2837. color: '#8a8478', align: 'center', x: 50, y: 52
  2838. }];
  2839. }
  2840. bind();
  2841. fit2d();
  2842. setMode('2d');
  2843. setTab('box');
  2844. commit(false);
  2845. updateHistoryBtns();
  2846. setTimeout(function () { fit2d(); renderMini(); }, 150);
  2847. }
  2848. init();
  2849. })();