box.js 135 KB

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