box.js 147 KB

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