studio.js 116 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933
  1. (function () {
  2. const D = window.PL.data;
  3. const R = window.PL.render;
  4. const UI = window.PL.ui;
  5. const h = UI.h;
  6. const A = UI.antd;
  7. const KEY = 'pouchlab.design.v1';
  8. const $ = function (s, root) { return (root || document).querySelector(s); };
  9. const $$ = function (s, root) { return Array.prototype.slice.call((root || document).querySelectorAll(s)); };
  10. const sampleMap = { standup: 'citrus', flatbottom: 'glow', coffee: 'morning', kraft: 'sunday', mailer: 'noir', garment: 'bloom' };
  11. const bagPalette = ['#efe7d6', '#171513', '#f4eee3', '#c49a68', '#8a9f76', '#ff7a45', '#bfe3f2', '#d9f07c'];
  12. function defaults() {
  13. return {
  14. version: 1,
  15. name: '未命名设计',
  16. productId: 'standup',
  17. sizeId: 'm',
  18. customSize: { w: 140, h: 210 },
  19. material: 'matte',
  20. finish: 'none',
  21. qty: 100,
  22. bagColor: null,
  23. sides: { front: { bg: null, elements: [] }, back: { bg: null, elements: [] } },
  24. uploads: [],
  25. sampleApplied: false
  26. };
  27. }
  28. let state = defaults();
  29. try {
  30. const saved = JSON.parse(localStorage.getItem(KEY) || 'null');
  31. if (saved && saved.sides) state = Object.assign(defaults(), saved);
  32. } catch (e) {}
  33. if (!state.sides.front) state.sides.front = { bg: null, elements: [] };
  34. if (!state.sides.back) state.sides.back = { bg: null, elements: [] };
  35. if (!Array.isArray(state.uploads)) state.uploads = [];
  36. if (!state.customSize || !state.customSize.w || !state.customSize.h) {
  37. const savedSize = D.sizeOf(D.productById(state.productId), state.sizeId);
  38. state.customSize = { w: savedSize.w, h: savedSize.h };
  39. }
  40. /* AI 设计师(首页 Agent)交接:应用其生成的袋子方案 */
  41. (function applyAgentHandoff() {
  42. try {
  43. const raw = localStorage.getItem('pouchlab.agent.handoff');
  44. if (!raw) return;
  45. const h = JSON.parse(raw);
  46. localStorage.removeItem('pouchlab.agent.handoff');
  47. const s = h && h.state;
  48. if (!s || s.kind !== 'bag' || !s.bag) return;
  49. const b = s.bag;
  50. if (b.productId && D.productById(b.productId)) {
  51. state.productId = b.productId;
  52. state.sizeId = 'custom';
  53. }
  54. if (b.customSize && b.customSize.w) {
  55. state.customSize = { w: b.customSize.w, h: b.customSize.h };
  56. state.sizeId = 'custom';
  57. }
  58. if (b.material) state.material = b.material;
  59. if (b.finish) state.finish = b.finish;
  60. if (b.qty) state.qty = b.qty;
  61. ['front', 'back'].forEach(function (k) {
  62. const d = (b.design || {})[k];
  63. if (d && (d.elements || []).length) {
  64. state.sides[k] = {
  65. bg: d.bg || null,
  66. elements: d.elements.map(function (el) {
  67. el.id = R.uid('el');
  68. el.opacity = el.opacity == null ? 1 : el.opacity;
  69. return el;
  70. })
  71. };
  72. }
  73. });
  74. setTimeout(function () { toast('已载入 AI 设计师方案,可继续微调'); }, 600);
  75. } catch (e) {}
  76. })();
  77. let mode = 'settings';
  78. let tool = 'product';
  79. let activeSide = 'front';
  80. let selectedId = null;
  81. let zoom = 1;
  82. let summarySide = 'front';
  83. let showGuides = true;
  84. let lastFont = 'sans';
  85. let history = [];
  86. let hIndex = -1;
  87. let dragGuides = null;
  88. let inlineTarget = null;
  89. let saveTimer = null;
  90. let renderFrame = null;
  91. let three = { rot: -18, side: 'front', modelMode: null };
  92. let isDragging = false;
  93. const els = {
  94. settingsView: $('#settingsView'),
  95. designView: $('#designView'),
  96. summaryView: $('#summaryView'),
  97. settingsColors: $('#settingsColors'),
  98. settingsPreview: $('#settingsPreview'),
  99. settingsPreviewNote: $('#settingsPreviewNote'),
  100. studioSteps: $('#studioSteps'),
  101. saveState: $('#saveState'),
  102. undoBtn: $('#undoBtn'),
  103. redoBtn: $('#redoBtn'),
  104. continueBtn: $('#continueBtn'),
  105. designName: $('#designName'),
  106. designMeta: $('#designMeta'),
  107. toolRail: $('#toolRail'),
  108. toolKicker: $('#toolKicker'),
  109. toolTitle: $('#toolTitle'),
  110. toolDesc: $('#toolDesc'),
  111. toolBody: $('#toolBody'),
  112. sideSwitch: $('#sideSwitch'),
  113. guidesToggle: $('#guidesToggle'),
  114. zoomLabel: $('#zoomLabel'),
  115. canvasShell: $('#canvasShell'),
  116. canvasStage: $('#canvasStage'),
  117. canvasEmpty: $('#canvasEmpty'),
  118. printInfo: $('#printInfo'),
  119. elementCount: $('#elementCount'),
  120. propsChip: $('#propsChip'),
  121. propsBody: $('#propsBody'),
  122. summaryPreview: $('#summaryPreview'),
  123. summaryThumbs: $('#summaryThumbs'),
  124. summaryOrder: $('#summaryOrder'),
  125. summarySideSwitch: $('#summarySideSwitch'),
  126. modal3d: $('#modal3d'),
  127. pouch3d: $('#pouch3d'),
  128. faceFront: $('#faceFront'),
  129. faceBack: $('#faceBack'),
  130. faceSide: $('#faceSide'),
  131. faceSideLeft: $('#faceSideLeft'),
  132. rotateRange: $('#rotateRange'),
  133. previewSideSwitch: $('#previewSideSwitch'),
  134. inlineText: $('#inlineText'),
  135. inlineTextArea: $('#inlineTextArea'),
  136. inlineTextDone: $('#inlineTextDone'),
  137. successView: $('#successView'),
  138. orderNumber: $('#orderNumber'),
  139. toast: $('#toast'),
  140. toastText: $('#toastText')
  141. };
  142. function product() { return D.productById(state.productId); }
  143. function size() {
  144. if (D.resolveSize) return D.resolveSize(product(), state);
  145. return D.sizeOf(product(), state.sizeId);
  146. }
  147. function renderProduct() {
  148. const p = product();
  149. return state.bagColor ? Object.assign({}, p, { mockColor: state.bagColor }) : p;
  150. }
  151. function sideData(side) { return state.sides[side || activeSide]; }
  152. function selectedEl() {
  153. return sideData().elements.find(function (e) { return e.id === selectedId; }) || null;
  154. }
  155. function allElements() {
  156. return sideData().elements;
  157. }
  158. function esc(s) { return R.esc(s); }
  159. function num(v, fallback) {
  160. const n = parseFloat(v);
  161. return isNaN(n) ? fallback : n;
  162. }
  163. function clamp(v, min, max) { return Math.min(max, Math.max(min, v)); }
  164. function mm(v) { return (Math.round(v * 10) / 10).toString(); }
  165. function inputVal(v) { return v && v.target && 'value' in v.target ? v.target.value : v; }
  166. function InlineNumber(props) {
  167. const [val, setVal] = React.useState(String(props.value));
  168. React.useEffect(function () { setVal(String(props.value)); }, [props.value]);
  169. return h('input', {
  170. type: 'number',
  171. min: props.min,
  172. max: props.max,
  173. step: props.step || 1,
  174. className: 's-inline-input',
  175. value: val,
  176. onChange: function (e) {
  177. setVal(e.target.value);
  178. if (props.onInput) props.onInput(e.target.value);
  179. },
  180. onBlur: function (e) { if (props.onCommit) props.onCommit(e.target.value); },
  181. onKeyDown: function (e) { if (e.key === 'Enter') e.currentTarget.blur(); }
  182. });
  183. }
  184. function TextField(props) {
  185. const [val, setVal] = React.useState(props.value == null ? '' : String(props.value));
  186. React.useEffect(function () { setVal(props.value == null ? '' : String(props.value)); }, [props.value]);
  187. const Comp = props.multiline ? A.Input.TextArea : A.Input;
  188. return h(Comp, Object.assign({}, props.extra || {}, {
  189. value: val,
  190. placeholder: props.placeholder,
  191. onChange: function (e) {
  192. const v = inputVal(e);
  193. setVal(v);
  194. if (props.onInput) props.onInput(v);
  195. },
  196. onBlur: function () { if (props.onCommit) props.onCommit(); }
  197. }));
  198. }
  199. function toast(msg, kind) {
  200. if (window.PL && PL.ui && PL.ui.message) {
  201. if (kind === 'warn') PL.ui.message.warning(msg);
  202. else PL.ui.message.success(msg);
  203. return;
  204. }
  205. els.toastText.textContent = msg;
  206. els.toast.classList.add('show');
  207. clearTimeout(toast.timer);
  208. toast.timer = setTimeout(function () { els.toast.classList.remove('show'); }, 2600);
  209. }
  210. function snapshot() {
  211. return JSON.stringify({
  212. name: state.name, productId: state.productId, sizeId: state.sizeId, customSize: state.customSize,
  213. material: state.material, finish: state.finish, qty: state.qty,
  214. bagColor: state.bagColor, sides: state.sides, sampleApplied: state.sampleApplied
  215. });
  216. }
  217. function applySnapshot(str) {
  218. const s = JSON.parse(str);
  219. state.name = s.name;
  220. state.productId = s.productId;
  221. state.sizeId = s.sizeId;
  222. state.customSize = s.customSize || state.customSize;
  223. state.material = s.material;
  224. state.finish = s.finish;
  225. state.qty = s.qty;
  226. state.bagColor = s.bagColor;
  227. state.sides = s.sides;
  228. state.sampleApplied = s.sampleApplied;
  229. selectedId = null;
  230. }
  231. function pushHistory() {
  232. const snap = snapshot();
  233. if (history[hIndex] === snap) return;
  234. history = history.slice(0, hIndex + 1);
  235. history.push(snap);
  236. if (history.length > 70) history.shift();
  237. hIndex = history.length - 1;
  238. updateUndoButtons();
  239. }
  240. function updateUndoButtons() {
  241. els.undoBtn.disabled = hIndex <= 0;
  242. els.redoBtn.disabled = hIndex >= history.length - 1;
  243. }
  244. function saveState(silent) {
  245. try {
  246. const payload = {
  247. version: 1, name: state.name, productId: state.productId, sizeId: state.sizeId, customSize: state.customSize,
  248. material: state.material, finish: state.finish, qty: state.qty, bagColor: state.bagColor,
  249. sides: state.sides, uploads: state.uploads.slice(0, 12), sampleApplied: state.sampleApplied,
  250. savedAt: Date.now()
  251. };
  252. localStorage.setItem(KEY, JSON.stringify(payload));
  253. if (!silent) {
  254. els.saveState.classList.add('saving');
  255. els.saveState.querySelector('span').textContent = '保存中…';
  256. clearTimeout(saveTimer);
  257. saveTimer = setTimeout(function () {
  258. els.saveState.classList.remove('saving');
  259. const d = new Date();
  260. els.saveState.querySelector('span').textContent = '已保存 ' + String(d.getHours()).padStart(2, '0') + ':' + String(d.getMinutes()).padStart(2, '0');
  261. }, 420);
  262. }
  263. } catch (e) {
  264. toast('本地存储空间不足,建议下载效果图备份');
  265. }
  266. }
  267. function commit(message) {
  268. pushHistory();
  269. saveState();
  270. updateMeta();
  271. if (message) toast(message);
  272. }
  273. function updateMeta() {
  274. const p = product();
  275. const s = size();
  276. const price = D.price(state);
  277. const sizeLabel = state.sizeId === 'custom' ? s.w + '×' + s.h + ' mm' : s.label;
  278. els.designMeta.textContent = p.name + ' · ' + sizeLabel + ' · ' + state.qty + ' 个';
  279. if (mode === 'settings') els.continueBtn.innerHTML = '开始设计 →';
  280. else if (mode === 'design') els.continueBtn.innerHTML = '下一步 · ¥' + price.total.toFixed(2);
  281. else els.continueBtn.innerHTML = '提交订单 · ¥' + price.total.toFixed(2);
  282. els.studioSteps.querySelectorAll('.step').forEach(function (btn) {
  283. const step = btn.dataset.step;
  284. btn.classList.toggle('active', step === mode);
  285. const order = ['settings', 'design', 'summary'];
  286. btn.classList.toggle('done', order.indexOf(step) < order.indexOf(mode));
  287. });
  288. els.undoBtn.disabled = hIndex <= 0;
  289. els.redoBtn.disabled = hIndex >= history.length - 1;
  290. document.title = state.name + ' — 袋研社 POUCHLAB';
  291. }
  292. function priceLines() {
  293. const price = D.price(state);
  294. return [
  295. ['袋型', price.product.name],
  296. ['尺寸', price.size.label + ' · ' + price.size.w + '×' + price.size.h + ' mm'],
  297. ['材质', price.material.name],
  298. ['工艺', price.finish.name],
  299. ['数量', price.quantity.value + ' 个'],
  300. ['单价', '¥' + price.unit.toFixed(2) + ' / 个']
  301. ];
  302. }
  303. function sampleDesignFor(p, w, h) {
  304. const t = D.templateById(sampleMap[p.id] || 'citrus');
  305. return { template: t, design: R.designFromTemplate(t.id, w, h, 'front') };
  306. }
  307. function currentPreviewDesign() {
  308. const s = size();
  309. if (sideData('front').elements.length) return sideData('front');
  310. return sampleDesignFor(product(), s.w, s.h).design;
  311. }
  312. function renderSettings() {
  313. const p = product();
  314. const s = size();
  315. const price = D.price(state);
  316. const productCards = D.products.map(function (item) {
  317. const smp = sampleDesignFor(item, item.sizes[0].w, item.sizes[0].h);
  318. const svg = R.bagSVG(item, 'front', smp.design, { size: item.sizes[0], card: true });
  319. return h(A.Card, {
  320. key: item.id,
  321. hoverable: true,
  322. bordered: false,
  323. className: 's-choice' + (item.id === state.productId ? ' on' : ''),
  324. onClick: function () { changeProduct(item.id); }
  325. },
  326. h('div', { className: 's-choice-thumb', dangerouslySetInnerHTML: { __html: svg } }),
  327. h('div', { className: 's-choice-name' }, h('b', null, item.name), h('em', null, item.en))
  328. );
  329. });
  330. const sizeRadios = p.sizes.map(function (item) {
  331. const unit = D.price(Object.assign({}, state, { sizeId: item.id })).unit;
  332. return h(A.Radio, { key: item.id, value: item.id }, h('span', { className: 's-size-opt' },
  333. h('b', null, item.label),
  334. h('em', null, item.w + '×' + item.h + ' mm'),
  335. h('i', null, '¥' + unit.toFixed(2))
  336. ));
  337. });
  338. sizeRadios.push(h(A.Radio, { key: 'custom', value: 'custom' }, h('span', { className: 's-size-opt' },
  339. h('b', null, '自定义'),
  340. h('em', null, s.w + '×' + s.h + ' mm'),
  341. h('i', null, '可调尺寸')
  342. )));
  343. const sizeInput = function (key, labelText) {
  344. return h('div', { className: 's-inline-field' },
  345. h('label', null, labelText),
  346. h(InlineNumber, {
  347. value: size()[key],
  348. min: 30,
  349. max: key === 'w' ? 1200 : 1600,
  350. step: 5,
  351. onInput: function (v) { applyCustomSize(key, v, false); },
  352. onCommit: function (v) { applyCustomSize(key, v, true); }
  353. })
  354. );
  355. };
  356. const panel = h('div', { className: 's-panel' },
  357. h('span', { className: 'step-kicker' }, 'STEP 01 / PRODUCT'),
  358. h('h1', null, '选择你的袋子'),
  359. h('p', null, '袋型、尺寸、材质与数量都会影响最终报价。'),
  360. h('div', { className: 's-field' },
  361. h('div', { className: 's-label' }, '袋型', h('span', null, '6 种可选')),
  362. h('div', { className: 's-choices' }, productCards)
  363. ),
  364. h('div', { className: 's-field' },
  365. h('div', { className: 's-label' }, '尺寸', h('span', null, s.w + ' × ' + s.h + ' mm')),
  366. h(A.Radio.Group, { className: 's-size-group', value: state.sizeId, onChange: function (e) { changeSize(e.target.value); } }, sizeRadios),
  367. h('div', { className: 's-custom-size' + (state.sizeId === 'custom' ? ' on' : '') },
  368. h('div', { className: 's-custom-title' }, '自定义尺寸', h('span', null, 'mm')),
  369. h('div', { className: 's-custom-inputs' }, sizeInput('w', '宽'), h('span', { className: 's-times' }, '×'), sizeInput('h', '高')),
  370. h('div', { className: 'p-hint' }, '宽 30–1200 mm,高 30–1600 mm,按面积计价。')
  371. )
  372. ),
  373. h('div', { className: 's-field' },
  374. h('div', { className: 's-label' }, '材质与工艺'),
  375. h('div', { className: 's-two' },
  376. h('div', null, h('label', null, '材质'), h(A.Select, {
  377. value: state.material,
  378. onChange: function (v) { changeSetting('material', v); },
  379. options: D.materials.map(function (m) { return { value: m.id, label: m.name }; })
  380. })),
  381. h('div', null, h('label', null, '工艺'), h(A.Select, {
  382. value: state.finish,
  383. onChange: function (v) { changeSetting('finish', v); },
  384. options: D.finishes.map(function (f) { return { value: f.id, label: f.name }; })
  385. }))
  386. )
  387. ),
  388. h('div', { className: 's-field' },
  389. h('div', { className: 's-label' }, '数量', h('span', null, '100 个起订')),
  390. h(A.Radio.Group, {
  391. className: 's-qty-group',
  392. optionType: 'button',
  393. buttonStyle: 'solid',
  394. value: String(state.qty),
  395. onChange: function (e) { changeSetting('qty', e.target.value); },
  396. options: D.quantities.map(function (q) { return { label: String(q.value), value: String(q.value) }; })
  397. }),
  398. h('div', { className: 's-qty-custom' },
  399. h('label', null, '自定义数量'),
  400. h(InlineNumber, {
  401. value: state.qty,
  402. min: 100,
  403. max: 100000,
  404. step: 50,
  405. onInput: function (v) { setQty(v, false); },
  406. onCommit: function (v) { setQty(v, true); }
  407. }),
  408. h('span', null, '个 · 100 起订')
  409. )
  410. ),
  411. h('div', { className: 's-link' },
  412. '需要纸盒?',
  413. h('a', { href: 'box.html' }, '打开纸盒设计器 →')
  414. )
  415. );
  416. const order = h('div', { className: 'order-card' },
  417. h('span', { className: 'eyebrow' }, 'YOUR QUOTE'),
  418. h('h2', null, '实时报价'),
  419. h('div', { className: 'order-lines' }, priceLines().map(function (row, i) {
  420. return h('div', { className: 'order-line', key: i }, h('span', null, row[0]), h('b', null, row[1]));
  421. })),
  422. h('div', { className: 'order-total' },
  423. h('span', null, '预计总价', h('br'), h('small', null, '含税,不含运费')),
  424. h('b', null, '¥' + price.total.toFixed(2), h('small', null, ' / ' + state.qty + ' 个'))
  425. ),
  426. h(A.Button, { type: 'primary', size: 'large', block: true, onClick: enterDesign }, '开始设计 →'),
  427. h('p', { className: 'micro' }, '免费设计 · 免费刀版 · 不满意随时修改')
  428. );
  429. UI.render(document.getElementById('settingsPanel'), panel);
  430. UI.render(document.getElementById('settingsOrderCard'), order);
  431. UI.hydrate(document.getElementById('settingsView'));
  432. els.settingsPreviewNote.textContent = s.w + ' × ' + s.h + ' mm · 正面预览';
  433. els.settingsPreview.innerHTML = R.bagSVG(renderProduct(), 'front', currentPreviewDesign(), { size: s, card: true, material: state.material, finish: state.finish });
  434. const colors = [p.mockColor].concat(bagPalette).filter(function (c, i, a) { return a.indexOf(c) === i; });
  435. els.settingsColors.innerHTML = colors.map(function (c) {
  436. const on = (state.bagColor || p.mockColor).toLowerCase() === c.toLowerCase();
  437. return '<button class="color-dot ' + (on ? 'on' : '') + '" data-color="' + c + '" style="background:' + c + '" aria-label="' + c + '"></button>';
  438. }).join('');
  439. }
  440. function scaleSides(oldSize, newSize) {
  441. const sx = newSize.w / oldSize.w;
  442. const sy = newSize.h / oldSize.h;
  443. const sm = Math.min(sx, sy);
  444. ['front', 'back'].forEach(function (side) {
  445. sideData(side).elements.forEach(function (el) {
  446. el.x *= sx;
  447. el.y *= sy;
  448. el.w *= sx;
  449. if (el.h != null) el.h *= sy;
  450. if (el.type === 'text') {
  451. el.size *= sm;
  452. if (el.strokeWidth) el.strokeWidth *= sm;
  453. }
  454. if (el.type === 'badge') {
  455. el.size *= sm;
  456. el.h = el.w;
  457. }
  458. if (el.type === 'sticker') el.h = el.w;
  459. if (el.strokeWidth) el.strokeWidth *= sm;
  460. if (el.radius) el.radius *= sm;
  461. });
  462. });
  463. }
  464. function changeProduct(id) {
  465. const oldP = product();
  466. const oldS = size();
  467. const newP = D.productById(id);
  468. if (newP.id === oldP.id) return;
  469. const newS = D.sizeOf(newP, newP.sizes[Math.floor(newP.sizes.length / 2)].id);
  470. const hasElements = state.sides.front.elements.length || state.sides.back.elements.length;
  471. if (hasElements) scaleSides(oldS, newS);
  472. state.productId = newP.id;
  473. state.sizeId = newS.id;
  474. state.bagColor = null;
  475. selectedId = null;
  476. commit();
  477. renderSettings();
  478. renderDesign();
  479. if (mode === 'summary') renderSummary();
  480. toast(hasElements ? '已切换袋型,设计已等比适配' : '已选择「' + newP.name + '」');
  481. }
  482. function changeSize(id) {
  483. const oldS = size();
  484. if (id === 'custom') {
  485. if (state.sizeId !== 'custom') state.customSize = { w: oldS.w, h: oldS.h };
  486. state.sizeId = 'custom';
  487. } else {
  488. if (state.sizeId === id) return;
  489. state.sizeId = id;
  490. }
  491. const newS = size();
  492. if (newS.w !== oldS.w || newS.h !== oldS.h) scaleSides(oldS, newS);
  493. selectedId = null;
  494. commit();
  495. renderSettings();
  496. renderDesign();
  497. if (mode === 'summary') renderSummary();
  498. }
  499. function refreshSettingsPreview() {
  500. if (mode !== 'settings') return;
  501. const s = size();
  502. els.settingsPreviewNote.textContent = s.w + ' × ' + s.h + ' mm · 正面预览';
  503. els.settingsPreview.innerHTML = R.bagSVG(renderProduct(), 'front', currentPreviewDesign(), {
  504. size: s, card: true, material: state.material, finish: state.finish
  505. });
  506. }
  507. function applyCustomSize(key, raw, commitNow) {
  508. const p = product();
  509. const base = D.sizeOf(p, p.sizes[Math.floor(p.sizes.length / 2)].id);
  510. const oldS = size();
  511. const dims = {
  512. w: state.sizeId === 'custom' ? state.customSize.w : oldS.w,
  513. h: state.sizeId === 'custom' ? state.customSize.h : oldS.h
  514. };
  515. const fallback = key === 'w' ? base.w : base.h;
  516. dims[key] = clamp(Math.round(num(raw, fallback)), 30, key === 'w' ? 1200 : 1600);
  517. state.customSize = dims;
  518. state.sizeId = 'custom';
  519. const newS = size();
  520. if (newS.w !== oldS.w || newS.h !== oldS.h) scaleSides(oldS, newS);
  521. updateMeta();
  522. refreshSettingsPreview();
  523. if (mode === 'design') scheduleRenderCanvas();
  524. if (mode === 'summary') renderSummary();
  525. if (commitNow) {
  526. commit();
  527. renderSettings();
  528. if (mode === 'design') renderTool();
  529. }
  530. }
  531. function setQty(raw, commitNow) {
  532. const v = clamp(Math.round(num(raw, 100)), 100, 100000);
  533. if (v === state.qty) {
  534. if (commitNow) {
  535. commit();
  536. renderSettings();
  537. if (mode === 'design') renderTool();
  538. }
  539. return;
  540. }
  541. state.qty = v;
  542. updateMeta();
  543. if (mode === 'settings') refreshSettingsPreview();
  544. if (mode === 'summary') renderSummary();
  545. if (commitNow) {
  546. commit();
  547. renderSettings();
  548. if (mode === 'design') renderTool();
  549. }
  550. }
  551. function changeSetting(key, value) {
  552. if (key === 'material') state.material = value;
  553. if (key === 'finish') state.finish = value;
  554. if (key === 'qty') { setQty(value, true); return; }
  555. commit();
  556. renderSettings();
  557. if (mode === 'design') { renderCanvas(); renderTool(); }
  558. if (mode === 'summary') renderSummary();
  559. }
  560. function changeBagColor(color) {
  561. state.bagColor = color;
  562. commit();
  563. renderSettings();
  564. renderDesign();
  565. if (mode === 'summary') renderSummary();
  566. }
  567. function applyTemplate(id, opts) {
  568. const t = D.templateById(id);
  569. if (!t) return;
  570. const s = size();
  571. state.sides.front = R.designFromTemplate(id, s.w, s.h, 'front');
  572. const back = R.designFromTemplate(id, s.w, s.h, 'back');
  573. state.sides.back = back;
  574. state.sampleApplied = true;
  575. activeSide = 'front';
  576. selectedId = null;
  577. commit();
  578. renderSettings();
  579. renderDesign();
  580. if (!opts || !opts.silent) toast('已套用模板「' + t.name + '」· 可撤销');
  581. }
  582. function ensureSample() {
  583. if (state.sampleApplied) return;
  584. if (state.sides.front.elements.length || state.sides.back.elements.length) return;
  585. const s = size();
  586. const t = D.templateById(sampleMap[product().id] || 'citrus');
  587. state.sides.front = R.designFromTemplate(t.id, s.w, s.h, 'front');
  588. state.sides.back = R.designFromTemplate(t.id, s.w, s.h, 'back');
  589. state.sampleApplied = true;
  590. saveState(true);
  591. pushHistory();
  592. }
  593. function setMode(next) {
  594. mode = next;
  595. els.settingsView.hidden = next !== 'settings';
  596. els.designView.hidden = next !== 'design';
  597. els.summaryView.hidden = next !== 'summary';
  598. hideInlineText();
  599. if (next === 'settings') {
  600. renderSettings();
  601. } else if (next === 'design') {
  602. if (!skipSample) ensureSample();
  603. skipSample = false;
  604. renderDesign();
  605. requestAnimationFrame(function () { renderCanvas(); });
  606. } else if (next === 'summary') {
  607. renderSummary();
  608. }
  609. updateMeta();
  610. }
  611. let skipSample = false;
  612. function enterDesign() {
  613. setMode('design');
  614. }
  615. function renderDesign() {
  616. if (mode !== 'design') return;
  617. els.sideSwitch.querySelectorAll('button').forEach(function (b) {
  618. b.classList.toggle('on', b.dataset.side === activeSide);
  619. });
  620. els.guidesToggle.checked = showGuides;
  621. const s = size();
  622. els.printInfo.textContent = '印刷区 ' + s.w + ' × ' + s.h + ' mm';
  623. renderCanvas();
  624. renderProps();
  625. renderTool();
  626. updateMeta();
  627. }
  628. function editorViewBox() {
  629. const p = product().pad;
  630. const s = size();
  631. return { x: -p.l - 18, y: -p.t - 12, w: s.w + p.l + p.r + 30, h: s.h + p.t + p.b + 34 };
  632. }
  633. function computeScale() {
  634. const vb = editorViewBox();
  635. const availW = Math.max(220, els.canvasShell.clientWidth - 68);
  636. const availH = Math.max(220, els.canvasShell.clientHeight - 52);
  637. const fit = Math.min(availW / vb.w, availH / vb.h);
  638. return { vb: vb, fit: fit, scale: fit * zoom };
  639. }
  640. function renderCanvas() {
  641. if (mode !== 'design') return;
  642. if (selectedId && !selectedEl()) selectedId = null;
  643. const p = renderProduct();
  644. const s = size();
  645. const total = state.sides.front.elements.length + state.sides.back.elements.length;
  646. els.elementCount.textContent = total + ' 个图层';
  647. els.canvasEmpty.hidden = sideData().elements.length > 0;
  648. els.printInfo.textContent = '印刷区 ' + s.w + ' × ' + s.h + ' mm';
  649. const cs = computeScale();
  650. els.canvasStage.style.width = (cs.vb.w * cs.scale) + 'px';
  651. els.canvasStage.style.height = (cs.vb.h * cs.scale) + 'px';
  652. els.zoomLabel.textContent = zoom === 1 ? '适应' : Math.round(zoom * 100) + '%';
  653. const scrollLeft = els.canvasShell.scrollLeft;
  654. const scrollTop = els.canvasShell.scrollTop;
  655. els.canvasStage.innerHTML = R.bagSVG(p, activeSide, sideData(), {
  656. size: s, ui: true, selectedId: selectedId, showGuides: showGuides,
  657. showDims: true, pxPerMm: cs.scale, guides: dragGuides,
  658. material: state.material, finish: state.finish
  659. });
  660. els.canvasShell.scrollLeft = scrollLeft;
  661. els.canvasShell.scrollTop = scrollTop;
  662. }
  663. function scheduleRenderCanvas() {
  664. if (renderFrame) return;
  665. renderFrame = requestAnimationFrame(function () {
  666. renderFrame = null;
  667. renderCanvas();
  668. });
  669. }
  670. function updateZoom(next) {
  671. zoom = clamp(next, 0.45, 2.6);
  672. renderCanvas();
  673. }
  674. function elementLabel(el) {
  675. if (el.type === 'text') return (el.text || '文字').slice(0, 16);
  676. if (el.type === 'image') return el.name || '图片';
  677. if (el.type === 'shape') return { rect: '矩形', circle: '圆形', line: '线条' }[el.shape] || '图形';
  678. if (el.type === 'sticker') return '贴纸 · ' + el.sticker;
  679. if (el.type === 'badge') return '圆形徽章';
  680. if (el.type === 'barcode') return '条码 · ' + (el.value || '');
  681. return '图层';
  682. }
  683. function elementIcon(el) {
  684. const icons = {
  685. text: '<path d="M5 5h14M12 5v14M8 19h8"/>',
  686. image: '<rect x="3" y="4" width="18" height="16" rx="2"/><circle cx="9" cy="10" r="1.6"/><path d="m4 17 5-5 4 4 3-3 4 4"/>',
  687. shape: '<rect x="4" y="4" width="16" height="16" rx="3"/>',
  688. sticker: '<path d="M20 4C11 4 4 9 4 17c0 2 1 3 3 3 8 0 13-7 13-16Z"/>',
  689. badge: '<circle cx="12" cy="12" r="8" stroke-dasharray="2 2"/><circle cx="12" cy="12" r="3"/>',
  690. barcode: '<path d="M4 5v14M8 5v14M12 5v10M16 5v14M20 5v14"/>'
  691. };
  692. return '<svg class="icon" viewBox="0 0 24 24">' + (icons[el.type] || icons.shape) + '</svg>';
  693. }
  694. function renderTool() {
  695. const meta = {
  696. product: ['PRODUCT', '产品设置', '当前袋型、尺寸与印刷信息'],
  697. templates: ['TEMPLATES', '模板库', '套用后可继续自由修改'],
  698. upload: ['UPLOAD', '上传素材', '建议使用透明背景 PNG 或 SVG'],
  699. text: ['TYPOGRAPHY', '文字工具', '标题、正文与字体选择'],
  700. shapes: ['GRAPHICS', '图形与贴纸', '用图形建立视觉层次'],
  701. layers: ['LAYERS', '图层管理', '从上到下即前后顺序']
  702. }[tool] || ['TOOL', '工具', ''];
  703. els.toolKicker.textContent = meta[0];
  704. els.toolTitle.textContent = meta[1];
  705. els.toolDesc.textContent = meta[2];
  706. els.toolRail.querySelectorAll('button[data-tool]').forEach(function (b) {
  707. b.classList.toggle('active', b.dataset.tool === tool);
  708. });
  709. UI.render(els.toolBody, toolPanelReact());
  710. }
  711. const barcodeIcon = h('span', { dangerouslySetInnerHTML: { __html: '<svg class="icon" viewBox="0 0 24 24" style="width:13px;height:13px"><path d="M4 5v14M8 5v14M12 5v10M16 5v14M20 5v14"/></svg>' } });
  712. const copyIcon = h('span', { dangerouslySetInnerHTML: { __html: '<svg class="icon" viewBox="0 0 24 24" style="width:13px;height:13px"><rect x="8" y="8" width="12" height="12" rx="2"/><path d="M16 8V5a1 1 0 0 0-1-1H5a1 1 0 0 0-1 1v10a1 1 0 0 0 1 1h3"/></svg>' } });
  713. function eyeIcon(hidden) {
  714. return h('span', {
  715. dangerouslySetInnerHTML: {
  716. __html: hidden
  717. ? '<svg class="icon" viewBox="0 0 24 24" style="width:13px;height:13px"><path d="M3 3l18 18M10.6 10.7a2 2 0 0 0 2.8 2.8"/><path d="M9.4 5.2A9.5 9.5 0 0 1 12 5c5 0 9 5 9 7a11 11 0 0 1-2.2 3.2M6.2 6.4C3.8 8 2 10.4 2 12c0 2 4 7 10 7 1.4 0 2.7-.4 3.9-1"/></svg>'
  718. : '<svg class="icon" viewBox="0 0 24 24" style="width:13px;height:13px"><path d="M2 12s3.5-7 10-7 10 7 10 7-3.5 7-10 7S2 12 2 12Z"/><circle cx="12" cy="12" r="3"/></svg>'
  719. }
  720. });
  721. }
  722. function applyFont(key) {
  723. const el = selectedEl();
  724. if (el && el.type === 'text') {
  725. el.font = key;
  726. lastFont = key;
  727. commit();
  728. renderCanvas();
  729. renderProps();
  730. return;
  731. }
  732. addTextPreset('body', key);
  733. }
  734. function toolPanelReact() {
  735. if (tool === 'templates') {
  736. return h('div', null,
  737. h('div', { className: 'p-hint', style: { marginBottom: '12px' } }, '点击套用 · 会覆盖当前画布,可用撤销恢复。'),
  738. h('div', { className: 'tpl-grid' }, D.templates.map(function (t) {
  739. return h(A.Card, {
  740. key: t.id,
  741. hoverable: true,
  742. bordered: false,
  743. className: 'tpl-card',
  744. bodyStyle: { padding: 0 },
  745. onClick: function () { applyTemplate(t.id); }
  746. },
  747. h('div', { className: 'tpl-thumb', style: { background: t.tint }, dangerouslySetInnerHTML: { __html: R.templatePreview(t) } }),
  748. h('div', { className: 'tpl-name' }, t.name, h(A.Tag, { bordered: false, className: 'tpl-tag' }, t.category))
  749. );
  750. }))
  751. );
  752. }
  753. if (tool === 'upload') {
  754. return h('div', null,
  755. h('div', { className: 'tool-section' },
  756. h('div', { className: 'tool-section-title' }, '上传素材'),
  757. h(A.Upload.Dragger, {
  758. accept: 'image/*',
  759. showUploadList: false,
  760. customRequest: function (options) { addUploadedFile(options.file); },
  761. children: h('div', { className: 'upload-zone' },
  762. h('div', { className: 'icon-box' }, h('span', { className: 'icon', style: { width: '18px', height: '18px' } })),
  763. h('b', null, '点击上传,或拖入图片'),
  764. h('span', null, 'PNG · JPG · SVG · 建议 ≥ 1000px')
  765. )
  766. })
  767. ),
  768. state.uploads.length ? h('div', { className: 'tool-section' },
  769. h('div', { className: 'tool-section-title' }, '最近上传', h('span', null, state.uploads.length + '')),
  770. h('div', { className: 'uploaded-grid' }, state.uploads.map(function (up) {
  771. return h('div', { className: 'uploaded-item', key: up.id },
  772. h('img', { src: up.src, alt: up.name }),
  773. h('button', {
  774. onClick: function () {
  775. state.uploads = state.uploads.filter(function (x) { return x.id !== up.id; });
  776. commit();
  777. }
  778. }, '✕')
  779. );
  780. }))
  781. ) : null,
  782. h('div', { className: 'tool-section' },
  783. h('div', { className: 'tool-section-title' }, '使用建议'),
  784. h('div', { className: 'p-hint' }, 'Logo 请使用 1 色或透明背景 PNG;图片会自动等比缩放。上传后可在右侧属性面板调整「填满 / 完整显示」与单色印刷。')
  785. )
  786. );
  787. }
  788. if (tool === 'text') {
  789. const presets = [
  790. { id: 'title', name: '大标题', desc: '适合品牌名 / 产品名', cls: 'big' },
  791. { id: 'subtitle', name: '副标题', desc: '补充口味或卖点', cls: 'mid' },
  792. { id: 'body', name: '正文', desc: '配料、说明与信息', cls: 'sm' },
  793. { id: 'latin', name: '英文标题', desc: '无衬线大写字母', cls: 'en' }
  794. ];
  795. return h('div', null,
  796. h('div', { className: 'tool-section' },
  797. h('div', { className: 'tool-section-title' }, '添加文字'),
  798. presets.map(function (p) {
  799. return h('button', { key: p.id, className: 'text-preset', onClick: function () { addTextPreset(p.id); } },
  800. h('span', null, h('b', null, p.name), h('span', null, p.desc)),
  801. h('span', { className: 't-label ' + p.cls }, p.cls === 'en' ? 'EN' : 'Aa')
  802. );
  803. })
  804. ),
  805. h('div', { className: 'tool-section' },
  806. h('div', { className: 'tool-section-title' }, '字体', h('span', null, '点击应用或新建')),
  807. h('div', { className: 'font-grid' }, Object.keys(D.fonts).map(function (k) {
  808. return h('button', { key: k, className: 'font-item', onClick: function () { applyFont(k); } },
  809. h('span', { style: { fontFamily: D.fonts[k].stack } }, '字体 Aa'),
  810. h('span', null, D.fonts[k].label)
  811. );
  812. }))
  813. )
  814. );
  815. }
  816. if (tool === 'shapes') {
  817. const shapes = [
  818. { id: 'rect', name: '矩形' },
  819. { id: 'circle', name: '圆形' },
  820. { id: 'line', name: '线条' },
  821. { id: 'badge', name: '徽章' }
  822. ];
  823. return h('div', null,
  824. h('div', { className: 'tool-section' },
  825. h('div', { className: 'tool-section-title' }, '基础图形'),
  826. h('div', { className: 'shape-grid' }, shapes.map(function (s) {
  827. return h('button', { key: s.id, className: 'shape-btn', title: s.name, onClick: function () { addShape(s.id); } },
  828. h('span', { className: 'shape-ico ' + s.id })
  829. );
  830. })),
  831. h(A.Button, { block: true, style: { marginTop: '8px' }, icon: barcodeIcon, onClick: function () { addShape('barcode'); } }, '添加条码')
  832. ),
  833. h('div', { className: 'tool-section' },
  834. h('div', { className: 'tool-section-title' }, '贴纸库', h('span', null, Object.keys(D.stickers).length + '')),
  835. h('div', { className: 'sticker-grid' }, Object.keys(D.stickers).map(function (k) {
  836. return h('button', { key: k, className: 'sticker-btn', title: k, onClick: function () { addSticker(k); } },
  837. h('span', {
  838. dangerouslySetInnerHTML: {
  839. __html: '<svg viewBox="0 0 24 24" fill="none">' + D.stickers[k].paths.map(function (p) {
  840. return p.stroke
  841. ? '<path d="' + p.d + '" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round"/>'
  842. : '<path d="' + p.d + '" fill="currentColor"/>';
  843. }).join('') + '</svg>'
  844. }
  845. })
  846. );
  847. }))
  848. )
  849. );
  850. }
  851. if (tool === 'layers') {
  852. const list = allElements();
  853. return h('div', null,
  854. h('div', { className: 'tool-section' },
  855. h('div', { className: 'tool-section-title' }, '图层 · ' + (activeSide === 'front' ? '正面' : '背面'), h('span', null, list.length + ' 个')),
  856. list.length ? h(A.List, {
  857. className: 'layer-list ant-list',
  858. dataSource: list.slice().reverse(),
  859. renderItem: function (item) {
  860. return h(A.List.Item, {
  861. key: item.id,
  862. className: 'layer-row' + (item.id === selectedId ? ' on' : ''),
  863. 'data-layer-id': item.id,
  864. onClick: function () { selectedId = item.id; renderCanvas(); renderProps(); renderTool(); }
  865. },
  866. h('span', { className: 'layer-icon', dangerouslySetInnerHTML: { __html: elementIcon(item) } }),
  867. h('span', { className: 'layer-name' }, elementLabel(item), h('small', null, item.type)),
  868. h('button', {
  869. className: 'layer-eye',
  870. title: item.hidden ? '显示图层' : '隐藏图层',
  871. onClick: function (e) { e.stopPropagation(); item.hidden = !item.hidden; commit(); renderCanvas(); renderTool(); }
  872. }, eyeIcon(item.hidden)),
  873. h('button', {
  874. className: 'layer-order',
  875. title: '移到最顶层',
  876. onClick: function (e) { e.stopPropagation(); selectedId = item.id; frontElement(); }
  877. }, '⤒'),
  878. h('button', {
  879. className: 'layer-order',
  880. title: '移到最底层',
  881. onClick: function (e) { e.stopPropagation(); selectedId = item.id; backElement(); }
  882. }, '⤓'),
  883. h('button', {
  884. className: 'layer-del',
  885. title: '删除图层',
  886. onClick: function (e) { e.stopPropagation(); deleteElementById(item.id); }
  887. }, '✕')
  888. );
  889. }
  890. }) : h(A.Empty, { description: '这一面还没有图层', image: A.Empty.PRESENTED_IMAGE_SIMPLE })
  891. ),
  892. h('div', { className: 'p-actions' },
  893. h(A.Button, { block: true, icon: copyIcon, onClick: duplicateSide }, '复制到另一面')
  894. )
  895. );
  896. }
  897. const s = size();
  898. const p = product();
  899. const price = D.price(state);
  900. return h('div', null,
  901. h('div', { className: 'tool-section' },
  902. h('div', { className: 'tool-section-title' }, '当前袋型'),
  903. h('div', { className: 's-current' },
  904. h('div', { className: 's-current-thumb', dangerouslySetInnerHTML: { __html: R.bagSVG(renderProduct(), 'front', currentPreviewDesign(), { size: s, card: true, material: state.material, finish: state.finish }) } }),
  905. h('div', null, h('b', null, p.name), h('em', null, p.en), h('span', null, s.w + ' × ' + s.h + ' mm'))
  906. )
  907. ),
  908. h('div', { className: 'tool-section' },
  909. h('div', { className: 'tool-section-title' }, '尺寸'),
  910. h(A.Radio.Group, {
  911. className: 's-size-group',
  912. value: state.sizeId,
  913. onChange: function (e) { changeSize(e.target.value); },
  914. options: p.sizes.map(function (item) { return { label: item.label, value: item.id }; }).concat([{ label: '自定义', value: 'custom' }])
  915. }),
  916. h('div', { className: 's-custom-inputs', style: { marginTop: '10px' } },
  917. h('div', { className: 's-inline-field' }, h('label', null, '宽'),
  918. h(InlineNumber, {
  919. value: size().w, min: 30, max: 1200, step: 5,
  920. onInput: function (v) { applyCustomSize('w', v, false); },
  921. onCommit: function (v) { applyCustomSize('w', v, true); }
  922. })
  923. ),
  924. h('span', { className: 's-times' }, '×'),
  925. h('div', { className: 's-inline-field' }, h('label', null, '高'),
  926. h(InlineNumber, {
  927. value: size().h, min: 30, max: 1600, step: 5,
  928. onInput: function (v) { applyCustomSize('h', v, false); },
  929. onCommit: function (v) { applyCustomSize('h', v, true); }
  930. })
  931. )
  932. )
  933. ),
  934. h('div', { className: 'tool-section' },
  935. h('div', { className: 'tool-section-title' }, '材质与工艺'),
  936. h('div', { className: 's-two' },
  937. h('div', null, h('label', null, '材质'), h(A.Select, {
  938. value: state.material,
  939. onChange: function (v) { changeSetting('material', v); },
  940. options: D.materials.map(function (m) { return { value: m.id, label: m.name }; })
  941. })),
  942. h('div', null, h('label', null, '工艺'), h(A.Select, {
  943. value: state.finish,
  944. onChange: function (v) { changeSetting('finish', v); },
  945. options: D.finishes.map(function (f) { return { value: f.id, label: f.name }; })
  946. }))
  947. )
  948. ),
  949. h('div', { className: 'tool-section' },
  950. h('div', { className: 'tool-section-title' }, '数量'),
  951. h(A.Radio.Group, {
  952. className: 's-qty-group',
  953. optionType: 'button',
  954. buttonStyle: 'solid',
  955. value: String(state.qty),
  956. onChange: function (e) { changeSetting('qty', e.target.value); },
  957. options: D.quantities.map(function (q) { return { label: String(q.value), value: String(q.value) }; })
  958. }),
  959. h('div', { className: 's-qty-custom' },
  960. h('label', null, '自定义数量'),
  961. h(InlineNumber, {
  962. value: state.qty, min: 100, max: 100000, step: 50,
  963. onInput: function (v) { setQty(v, false); },
  964. onCommit: function (v) { setQty(v, true); }
  965. }),
  966. h('span', null, '个 · 100 起订')
  967. )
  968. ),
  969. h('div', { className: 'tool-section' },
  970. h('div', { className: 'tool-section-title' }, '袋身颜色'),
  971. h('div', { className: 'p-swatches' }, [p.mockColor].concat(bagPalette).filter(function (c, i, a) { return a.indexOf(c) === i; }).map(function (c) {
  972. const on = (state.bagColor || p.mockColor).toLowerCase() === c.toLowerCase();
  973. return h('button', { key: c, className: 'p-swatch' + (on ? ' on' : ''), style: { background: c }, onClick: function () { changeBagColor(c); } });
  974. })),
  975. h('div', { className: 'pms-title' }, '参考潘通色'),
  976. pmsGrid(function (c) { changeBagColor(c.hex); }, state.bagColor || p.mockColor)
  977. ),
  978. h('div', { className: 'p-price-card' },
  979. h('div', { className: 'p-price-line' }, h('span', null, '单价'), h('b', null, '¥' + price.unit.toFixed(2) + ' / 个')),
  980. h('div', { className: 'p-price-line' }, h('span', null, '合计 · ' + state.qty + ' 个'), h('b', null, '¥' + price.total.toFixed(2)))
  981. ),
  982. h('div', { className: 'p-actions', style: { marginTop: '12px' } },
  983. h(A.Button, { block: true, onClick: function () { setMode('settings'); } }, '返回设置'),
  984. h(A.Button, { block: true, danger: true, onClick: function () { clearSide(); } }, '清空本面')
  985. )
  986. );
  987. }
  988. function renderProps() {
  989. UI.render(els.propsBody, propsTree());
  990. }
  991. function propsTree() {
  992. const el = selectedEl();
  993. if (!el) {
  994. const s = size();
  995. const p = product();
  996. const side = sideData();
  997. const price = D.price(state);
  998. els.propsChip.textContent = 'CANVAS';
  999. const bgColors = ['#f7f2e7', '#ffffff', '#17140f', '#ff5c2b', '#d9f07c', '#1e3a2c', '#bfe3f2', '#e8d5b8', '#f3d9d3'];
  1000. return h('div', null,
  1001. h('div', { className: 'p-section' },
  1002. h('div', { className: 'p-section-title' }, '印刷画布'),
  1003. h('div', { className: 'p-row' },
  1004. h('div', { className: 'p-field' }, h('label', null, '宽度'), h(A.Input, { value: s.w + ' mm', readOnly: true })),
  1005. h('div', { className: 'p-field' }, h('label', null, '高度'), h(A.Input, { value: s.h + ' mm', readOnly: true }))
  1006. ),
  1007. h('div', { className: 'p-row' },
  1008. h('div', { className: 'p-field' }, h('label', null, '当前面'),
  1009. h(A.Segmented, {
  1010. value: activeSide,
  1011. block: true,
  1012. onChange: function (v) { changeSide(v); },
  1013. options: [{ label: '正面', value: 'front' }, { label: '背面', value: 'back' }]
  1014. })
  1015. )
  1016. ),
  1017. h('div', { className: 'p-hint' }, '刀版线外 3mm 为出血位,重要文字请放在安全区内。')
  1018. ),
  1019. h('div', { className: 'p-section' },
  1020. h('div', { className: 'p-section-title' }, '印刷底色'),
  1021. h('div', { className: 'p-swatches' },
  1022. h('button', { className: 'p-swatch' + (!side.bg ? ' on' : ''), style: { background: 'linear-gradient(135deg,#fff 45%,#ffd0c0 55%)' }, title: '无底色', onClick: function () { side.bg = null; commit(); renderCanvas(); renderProps(); } }),
  1023. bgColors.map(function (c) {
  1024. return h('button', { key: c, className: 'p-swatch' + (side.bg === c ? ' on' : ''), style: { background: c }, onClick: function () { side.bg = c; commit(); renderCanvas(); renderProps(); } });
  1025. })
  1026. ),
  1027. h('div', { className: 'p-row', style: { marginTop: '10px' } },
  1028. h('div', { className: 'p-field' }, h('label', null, '自定义底色'),
  1029. h(A.ColorPicker, {
  1030. value: side.bg || '#f7f2e7',
  1031. showText: true,
  1032. onChange: function (c) { side.bg = c.toHexString(); commit(); renderCanvas(); }
  1033. })
  1034. )
  1035. ),
  1036. h('div', { className: 'pms-title' }, '参考潘通色'),
  1037. pmsGrid(function (c) { side.bg = c.hex; commit(); renderCanvas(); renderProps(); }, side.bg)
  1038. ),
  1039. h('div', { className: 'p-section' },
  1040. h('div', { className: 'p-section-title' }, '袋身颜色'),
  1041. h('div', { className: 'p-swatches' }, [p.mockColor].concat(bagPalette).filter(function (c, i, a) { return a.indexOf(c) === i; }).map(function (c) {
  1042. const on = (state.bagColor || p.mockColor).toLowerCase() === c.toLowerCase();
  1043. return h('button', { key: c, className: 'p-swatch' + (on ? ' on' : ''), style: { background: c }, onClick: function () { changeBagColor(c); renderProps(); } });
  1044. }))
  1045. ),
  1046. h('div', { className: 'p-section' },
  1047. h('div', { className: 'p-section-title' }, '画布工具'),
  1048. h('label', { className: 'p-check' }, '显示刀版线',
  1049. h(A.Switch, { size: 'small', checked: showGuides, onChange: function (v) { showGuides = v; renderCanvas(); } })
  1050. ),
  1051. h('div', { className: 'p-actions', style: { marginTop: '10px' } },
  1052. h(A.Button, { block: true, onClick: duplicateSide }, '复制到' + (activeSide === 'front' ? '背面' : '正面')),
  1053. h(A.Button, { block: true, danger: true, onClick: function () { clearSide(); } }, '清空本面')
  1054. )
  1055. ),
  1056. h('div', { className: 'p-section' },
  1057. h('div', { className: 'p-section-title' }, '报价'),
  1058. h('div', { className: 'p-price-card' },
  1059. h('div', { className: 'p-price-line' }, h('span', null, p.name + ' · ' + s.label + ' · ' + state.qty + ' 个'), h('b', null, '¥' + price.total.toFixed(2)))
  1060. ),
  1061. h('div', { className: 'p-hint' }, '切换尺寸或数量后价格会实时更新。')
  1062. )
  1063. );
  1064. }
  1065. els.propsChip.textContent = el.type.toUpperCase();
  1066. const box = R.elementBox(el);
  1067. const numField = function (label, prop, value, min, max, step) {
  1068. const rounded = typeof value === 'number' ? Math.round(value * 100) / 100 : value;
  1069. return h('div', { className: 'p-field' }, h('label', null, label),
  1070. h(A.InputNumber, {
  1071. value: rounded,
  1072. min: min,
  1073. max: max,
  1074. step: step || 0.5,
  1075. style: { width: '100%' },
  1076. onChange: function (v) { if (v != null) { updateSelected(prop, v); commit(); renderCanvas(); } }
  1077. })
  1078. );
  1079. };
  1080. const colorField = function (label, prop, value) {
  1081. return h('div', { className: 'p-field' }, h('label', null, label),
  1082. h(A.ColorPicker, {
  1083. value: value && value !== 'none' ? value : '#17140f',
  1084. showText: true,
  1085. onChange: function (c) { updateSelected(prop, c.toHexString()); commit(); renderCanvas(); }
  1086. })
  1087. );
  1088. };
  1089. let specific = null;
  1090. if (el.type === 'text') {
  1091. specific = h('div', { className: 'p-section' },
  1092. h('div', { className: 'p-section-title' }, '文字内容'),
  1093. h(TextField, {
  1094. multiline: true,
  1095. value: el.text,
  1096. extra: { autoSize: { minRows: 2, maxRows: 5 } },
  1097. onInput: function (v) { updateSelected('text', v); renderCanvas(); },
  1098. onCommit: function () { commit(); renderTool(); }
  1099. }),
  1100. h('div', { className: 'p-section-title', style: { marginTop: '16px' } }, '字体'),
  1101. h(A.Select, {
  1102. value: el.font || 'sans',
  1103. style: { width: '100%' },
  1104. onChange: function (v) { updateSelected('font', v); commit(); renderCanvas(); renderProps(); },
  1105. options: Object.keys(D.fonts).map(function (k) { return { value: k, label: D.fonts[k].label }; })
  1106. }),
  1107. h('div', { className: 'p-row', style: { marginTop: '9px' } },
  1108. numField('字号 mm', 'size', el.size, 2, 120, 0.5),
  1109. numField('字距', 'spacing', el.spacing || 0, -0.2, 0.4, 0.01)
  1110. ),
  1111. h('div', { className: 'p-row' },
  1112. numField('行高', 'lineHeight', el.lineHeight || 1.25, 0.7, 3, 0.05),
  1113. colorField('颜色', 'color', el.color)
  1114. ),
  1115. h('div', { className: 'p-row' },
  1116. h('div', { className: 'p-field' }, h('label', null, '字重'),
  1117. h(A.Segmented, {
  1118. value: String(el.weight || 400),
  1119. block: true,
  1120. onChange: function (v) { updateSelected('weight', Number(v)); commit(); renderCanvas(); renderProps(); },
  1121. options: [{ label: '400', value: '400' }, { label: '600', value: '600' }, { label: '800', value: '800' }]
  1122. })
  1123. )
  1124. ),
  1125. h('div', { className: 'p-row' },
  1126. h('div', { className: 'p-field' }, h('label', null, '对齐'),
  1127. h(A.Segmented, {
  1128. value: el.align || 'left',
  1129. block: true,
  1130. onChange: function (v) { updateSelected('align', v); commit(); renderCanvas(); renderProps(); },
  1131. options: [{ label: '左', value: 'left' }, { label: '中', value: 'center' }, { label: '右', value: 'right' }]
  1132. })
  1133. ),
  1134. h('div', { className: 'p-field' }, h('label', null, '斜体'),
  1135. h('div', { className: 'p-check p-check-box' }, h('span', { style: { fontFamily: 'Georgia' } }, 'I'),
  1136. h(A.Switch, { size: 'small', checked: !!el.italic, onChange: function (v) { updateSelected('italic', v); commit(); renderCanvas(); renderProps(); } })
  1137. )
  1138. )
  1139. )
  1140. );
  1141. } else if (el.type === 'image') {
  1142. specific = h('div', { className: 'p-section' },
  1143. h('div', { className: 'p-section-title' }, '图片'),
  1144. h('div', { className: 'p-row' },
  1145. h('div', { className: 'p-field' }, h('label', null, '填充方式'),
  1146. h(A.Segmented, {
  1147. value: el.fit || 'contain',
  1148. block: true,
  1149. onChange: function (v) { updateSelected('fit', v); commit(); renderCanvas(); renderProps(); },
  1150. options: [{ label: '完整显示', value: 'contain' }, { label: '填满裁切', value: 'cover' }]
  1151. })
  1152. )
  1153. ),
  1154. h('label', { className: 'p-check' }, '单色印刷',
  1155. h(A.Switch, { size: 'small', checked: !!el.mono, onChange: function (v) { updateSelected('mono', v); commit(); renderCanvas(); renderProps(); } })
  1156. ),
  1157. h('div', { className: 'p-actions', style: { marginTop: '10px' } },
  1158. h(A.Button, { block: true, onClick: function () { pickUpload(true); } }, '替换图片')
  1159. )
  1160. );
  1161. } else if (el.type === 'shape') {
  1162. specific = h('div', { className: 'p-section' },
  1163. h('div', { className: 'p-section-title' }, el.shape === 'line' ? '线条' : '外观'),
  1164. el.shape !== 'line' ? h('div', { className: 'p-row' },
  1165. colorField('填充', 'fill', el.fill),
  1166. el.shape === 'rect' ? numField('圆角', 'radius', el.radius || 0, 0, 80, 0.5) : null
  1167. ) : null,
  1168. h('div', { className: 'p-row' },
  1169. colorField('描边', 'stroke', el.stroke),
  1170. numField('描边宽', 'strokeWidth', el.strokeWidth || 0, 0, 20, 0.1)
  1171. )
  1172. );
  1173. } else if (el.type === 'sticker') {
  1174. specific = h('div', { className: 'p-section' },
  1175. h('div', { className: 'p-section-title' }, '贴纸'),
  1176. h('div', { className: 'p-row' }, colorField('颜色', 'color', el.color)),
  1177. h('div', { className: 'p-hint' }, '拖动四角可等比缩放。')
  1178. );
  1179. } else if (el.type === 'badge') {
  1180. specific = h('div', { className: 'p-section' },
  1181. h('div', { className: 'p-section-title' }, '圆形徽章'),
  1182. h(TextField, {
  1183. multiline: true,
  1184. value: el.text || '',
  1185. extra: { autoSize: { minRows: 2, maxRows: 3 } },
  1186. onInput: function (v) { updateSelected('text', v); renderCanvas(); },
  1187. onCommit: function () { commit(); renderTool(); }
  1188. }),
  1189. h('div', { className: 'p-row', style: { marginTop: '9px' } },
  1190. numField('环文字号', 'size', el.size || 3, 1, 40, 0.2),
  1191. colorField('颜色', 'color', el.color)
  1192. )
  1193. );
  1194. } else if (el.type === 'barcode') {
  1195. specific = h('div', { className: 'p-section' },
  1196. h('div', { className: 'p-section-title' }, '条码 / SKU'),
  1197. h(TextField, {
  1198. value: el.value || '',
  1199. onInput: function (v) { updateSelected('value', v); renderCanvas(); },
  1200. onCommit: function () { commit(); renderTool(); }
  1201. }),
  1202. h('label', { className: 'p-check', style: { marginTop: '9px' } }, '显示数字',
  1203. h(A.Switch, { size: 'small', checked: el.showText !== false, onChange: function (v) { updateSelected('showText', v); commit(); renderCanvas(); renderProps(); } })
  1204. ),
  1205. h('div', { className: 'p-row' }, colorField('颜色', 'color', el.color)),
  1206. h('div', { className: 'p-hint' }, '输入 12–13 位数字会生成真实 EAN-13 校验位。')
  1207. );
  1208. }
  1209. return h('div', null,
  1210. specific,
  1211. h('div', { className: 'p-section' },
  1212. h('div', { className: 'p-section-title' }, '位置与尺寸'),
  1213. h('div', { className: 'p-row' },
  1214. numField('X (mm)', 'x', el.x, -9999, 9999),
  1215. numField('Y (mm)', 'y', el.y, -9999, 9999)
  1216. ),
  1217. h('div', { className: 'p-row' },
  1218. numField('宽度', 'w', el.w, 2, 9999),
  1219. el.type === 'text'
  1220. ? h('div', { className: 'p-field' }, h('label', null, '高度(自动)'), h(A.Input, { value: box.h.toFixed(1) + ' mm', readOnly: true }))
  1221. : numField('高度', 'h', el.h, 1, 9999)
  1222. ),
  1223. h('div', { className: 'p-row' },
  1224. numField('旋转 °', 'rotation', el.rotation || 0, -180, 180, 1),
  1225. h('div', { className: 'p-field' }, h('label', null, '不透明度 ' + Math.round((el.opacity == null ? 1 : el.opacity) * 100) + '%'),
  1226. h(A.Slider, {
  1227. value: (el.opacity == null ? 1 : el.opacity) * 100,
  1228. min: 10,
  1229. max: 100,
  1230. onChange: function (v) { updateSelected('opacity', v / 100); renderCanvas(); },
  1231. onAfterChange: function () { commit(); renderProps(); }
  1232. })
  1233. )
  1234. )
  1235. ),
  1236. h('div', { className: 'p-section' },
  1237. h('div', { className: 'p-section-title' }, '图层顺序'),
  1238. h('div', { className: 'p-actions order-actions' },
  1239. h(A.Button, { block: true, onClick: frontElement }, '⤒ 置顶'),
  1240. h(A.Button, { block: true, onClick: raiseElement }, '↑ 上移'),
  1241. h(A.Button, { block: true, onClick: lowerElement }, '↓ 下移'),
  1242. h(A.Button, { block: true, onClick: backElement }, '⤓ 置底'),
  1243. h(A.Button, { block: true, onClick: duplicateElement }, '复制'),
  1244. h(A.Button, { block: true, danger: true, onClick: deleteElement }, '删除')
  1245. )
  1246. )
  1247. );
  1248. }
  1249. /* ---------------- AI 交互式排版(登录后可用,后台控额度) ---------------- */
  1250. const ai = { open: false, side: 'front', brief: '', busy: false, last: null, quota: null };
  1251. function aiPanelEnsure() {
  1252. if (document.getElementById('plAiPanel')) return;
  1253. const wrap = document.createElement('div');
  1254. wrap.id = 'plAiPanel';
  1255. wrap.className = 'pl-ai-panel';
  1256. wrap.hidden = true;
  1257. wrap.innerHTML =
  1258. '<div class="pl-ai-head"><b>AI 排版</b><span class="pl-ai-quota" id="plAiQuota"></span>' +
  1259. '<button type="button" class="pl-ai-close" id="plAiClose">✕</button></div>' +
  1260. '<div class="pl-ai-sides" id="plAiSides">' +
  1261. '<button type="button" data-ai-side="front" class="on">正面</button>' +
  1262. '<button type="button" data-ai-side="back">背面</button>' +
  1263. '<button type="button" data-ai-side="both">双面同款</button></div>' +
  1264. '<textarea id="plAiBrief" placeholder="描述你想要的排版,如:&#10;极简咖啡包装,暖米底色,顶部衬线体品牌名,中部咖啡豆贴纸,底部一行英文 slogan&#10;生成后可继续说:文字再大一点 / 换深色背景"></textarea>' +
  1265. '<div class="pl-ai-actions">' +
  1266. '<button type="button" class="btn btn-primary" id="plAiGen">生成排版</button>' +
  1267. '<button type="button" class="pl-ai-clear" id="plAiClear">清空本面</button></div>' +
  1268. '<p class="pl-ai-tip">AI 结果直接应用到画布,可随时撤销(⌘Z)。每次生成消耗 1 次额度。</p>';
  1269. document.body.appendChild(wrap);
  1270. wrap.querySelector('#plAiClose').addEventListener('click', function () { aiPanelToggle(false); });
  1271. wrap.querySelector('#plAiSides').addEventListener('click', function (e) {
  1272. const b = e.target.closest('[data-ai-side]');
  1273. if (!b) return;
  1274. ai.side = b.dataset.aiSide;
  1275. wrap.querySelectorAll('#plAiSides button').forEach(function (x) { x.classList.toggle('on', x === b); });
  1276. });
  1277. wrap.querySelector('#plAiGen').addEventListener('click', aiGenerate);
  1278. wrap.querySelector('#plAiClear').addEventListener('click', function () {
  1279. sideData().elements = [];
  1280. if (state.sides[ai.side === 'back' ? 'back' : 'front']) state.sides[ai.side === 'back' ? 'back' : 'front'].bg = null;
  1281. commit(); renderCanvas(); renderSummarySafe();
  1282. });
  1283. }
  1284. function renderSummarySafe() { try { renderSummary(); } catch (e) {} }
  1285. function aiPanelToggle(open) {
  1286. aiPanelEnsure();
  1287. if (open !== undefined) ai.open = open; else ai.open = !ai.open;
  1288. document.getElementById('plAiPanel').hidden = !ai.open;
  1289. if (ai.open) {
  1290. if (window.PL.auth && !PL.auth.user()) {
  1291. PL.auth.require(function () { aiRefreshQuota(); });
  1292. toast('登录后可用 AI 排版');
  1293. } else {
  1294. aiRefreshQuota();
  1295. }
  1296. }
  1297. }
  1298. function aiRefreshQuota() {
  1299. if (!window.PL || !PL.api || !PL.api.token()) return;
  1300. PL.api.get('/ai/quota').then(function (q) {
  1301. ai.quota = q;
  1302. const el = document.getElementById('plAiQuota');
  1303. if (!el) return;
  1304. el.textContent = q.configured ? ('剩余 ' + q.left + ' 次') : 'AI 未配置';
  1305. document.getElementById('plAiGen').disabled = !q.configured;
  1306. }, function () {});
  1307. }
  1308. function aiApplyTo(sideKey, result) {
  1309. const sd = state.sides[sideKey];
  1310. if (!sd) return;
  1311. sd.elements = (result.elements || []).map(function (el) {
  1312. el.id = R.uid('el');
  1313. el.opacity = el.opacity == null ? 1 : el.opacity;
  1314. return el;
  1315. });
  1316. sd.bg = result.bg || null;
  1317. }
  1318. function aiGenerate() {
  1319. if (window.PL.auth && !PL.auth.user()) {
  1320. PL.auth.require(function () { aiGenerate(); });
  1321. return;
  1322. }
  1323. if (!window.PL || !PL.api) { toast('AI 需要联网登录后使用'); return; }
  1324. const brief = (document.getElementById('plAiBrief').value || '').trim();
  1325. if (!brief) { toast('先描述一下排版需求'); return; }
  1326. if (ai.busy) return;
  1327. ai.busy = true;
  1328. const btn = document.getElementById('plAiGen');
  1329. btn.disabled = true;
  1330. const t0 = Date.now();
  1331. btn.textContent = 'AI 生成中… 0s';
  1332. const timer = setInterval(function () {
  1333. btn.textContent = 'AI 生成中… ' + Math.round((Date.now() - t0) / 1000) + 's';
  1334. }, 1000);
  1335. const tip = document.querySelector('.pl-ai-tip');
  1336. if (tip) tip.textContent = 'AI 正在设计中,通常 10~60 秒,请勿关闭面板或刷新页面…';
  1337. const s = size();
  1338. const applySide = ai.side === 'back' ? 'back' : 'front';
  1339. const contextEl = document.getElementById('plAiQuota');
  1340. PL.api.post('/ai/layout', {
  1341. type: 'bag',
  1342. brief: brief,
  1343. meta: { w: s.w, h: s.h, product: product().name },
  1344. context: ai.last && ai.last.side === applySide ? { bg: state.sides[applySide].bg, elements: state.sides[applySide].elements } : null
  1345. }, { timeout: 150000 }).then(function (r) {
  1346. ai.busy = false; clearInterval(timer);
  1347. btn.disabled = false; btn.textContent = '生成排版';
  1348. if (tip) tip.textContent = 'AI 结果已应用到画布,可继续提修改意见(每次生成消耗 1 次额度)。';
  1349. if (!(r.result.elements || []).length) {
  1350. toast('AI 这次没能生成有效排版(未扣次数),换个说法再试');
  1351. if (contextEl) contextEl.textContent = '剩余 ' + r.left + ' 次';
  1352. return;
  1353. }
  1354. ai.last = { side: applySide, result: r.result };
  1355. aiApplyTo(applySide, r.result);
  1356. if (ai.side === 'both') aiApplyTo('back', r.result);
  1357. commit(); renderCanvas(); renderSummarySafe();
  1358. selectedId = null;
  1359. if (contextEl) contextEl.textContent = '剩余 ' + r.left + ' 次';
  1360. toast('AI 排版已应用,可继续提修改意见');
  1361. }, function (err) {
  1362. ai.busy = false; clearInterval(timer);
  1363. btn.disabled = false; btn.textContent = '生成排版';
  1364. if (tip) tip.textContent = 'AI 结果直接应用到画布,可随时撤销(⌘Z)。每次生成消耗 1 次额度。';
  1365. if (err.status === 401) {
  1366. PL.auth.require(function () { aiGenerate(); });
  1367. } else {
  1368. toast(err.message || 'AI 生成失败');
  1369. }
  1370. });
  1371. }
  1372. function addElement(el) {
  1373. const s = size();
  1374. const box = R.elementBox(el);
  1375. if (el.x == null) el.x = (s.w - box.w) / 2;
  1376. if (el.y == null) el.y = (s.h - box.h) / 2;
  1377. el.id = R.uid('el');
  1378. sideData().elements.push(el);
  1379. selectedId = el.id;
  1380. commit();
  1381. renderCanvas();
  1382. renderProps();
  1383. renderTool();
  1384. return el;
  1385. }
  1386. function addTextPreset(kind, fontOverride) {
  1387. const s = size();
  1388. const presets = {
  1389. title: { text: '你的标题', size: s.w * 0.15, weight: 800, font: 'sans', align: 'left' },
  1390. subtitle: { text: '一句打动人的副标题', size: s.w * 0.052, weight: 600, font: 'sans', align: 'left' },
  1391. body: { text: '在这里输入产品说明、配料或品牌故事。', size: s.w * 0.03, weight: 400, font: 'sans', align: 'left' },
  1392. latin: { text: 'YOUR BRAND', size: s.w * 0.11, weight: 800, font: 'latin', align: 'left', spacing: 0.02 }
  1393. };
  1394. const p = Object.assign({}, presets[kind] || presets.body);
  1395. p.font = fontOverride || p.font || lastFont;
  1396. lastFont = p.font;
  1397. p.type = 'text';
  1398. p.w = s.w * 0.8;
  1399. p.color = '#17140f';
  1400. p.spacing = p.spacing || 0;
  1401. p.lineHeight = 1.2;
  1402. p.strokeWidth = 0;
  1403. p.rotation = 0;
  1404. p.opacity = 1;
  1405. const textCount = allElements().filter(function (e) { return e.type === 'text'; }).length;
  1406. const step = Math.max(6, Math.min(14, s.h * 0.035));
  1407. p.x = clamp(s.w * 0.1 + (textCount % 5) * step * 0.7, 2, Math.max(2, s.w * 0.18));
  1408. p.y = clamp(s.h * 0.3 + (textCount % 7) * step, 2, Math.max(2, s.h - 24));
  1409. addElement(p);
  1410. toast('已添加文字 · 双击画布可直接编辑');
  1411. }
  1412. function addShape(kind) {
  1413. const s = size();
  1414. const base = { type: 'shape', rotation: 0, opacity: 1, fill: '#ff5c2b', stroke: 'none', strokeWidth: 0, radius: 0 };
  1415. let el;
  1416. if (kind === 'circle') {
  1417. el = Object.assign(base, { shape: 'circle', w: s.w * 0.36, h: s.w * 0.36, fill: '#d9f07c' });
  1418. } else if (kind === 'line') {
  1419. el = Object.assign(base, { shape: 'line', w: s.w * 0.7, h: 4, fill: 'none', stroke: '#17140f', strokeWidth: 1 });
  1420. } else if (kind === 'badge') {
  1421. el = { type: 'badge', w: s.w * 0.34, text: 'SMALL BATCH · POUCHLAB · ', color: '#17140f', size: s.w * 0.028, rotation: 0, opacity: 1 };
  1422. } else if (kind === 'barcode') {
  1423. el = { type: 'barcode', w: s.w * 0.5, h: s.h * 0.12, value: '6971234567890', color: '#17140f', showText: true, rotation: 0, opacity: 1 };
  1424. } else {
  1425. el = Object.assign(base, { shape: 'rect', w: s.w * 0.44, h: s.h * 0.22, fill: '#ff5c2b' });
  1426. }
  1427. addElement(el);
  1428. toast('已添加' + (kind === 'barcode' ? '条码' : kind === 'badge' ? '徽章' : '图形'));
  1429. }
  1430. function addSticker(name) {
  1431. const s = size();
  1432. addElement({ type: 'sticker', sticker: name, w: s.w * 0.2, h: s.w * 0.2, color: '#ff5c2b', rotation: 0, opacity: 1 });
  1433. }
  1434. function addImageFromUpload(up) {
  1435. const s = size();
  1436. let w = s.w * 0.55;
  1437. let h = w * (up.h / up.w);
  1438. if (h > s.h * 0.7) {
  1439. h = s.h * 0.7;
  1440. w = h * (up.w / up.h);
  1441. }
  1442. addElement({ type: 'image', src: up.src, name: up.name, w: w, h: h, fit: 'contain', mono: false, rotation: 0, opacity: 1 });
  1443. toast('图片已放置到画布');
  1444. }
  1445. function clearSide(side) {
  1446. const target = side || activeSide;
  1447. state.sides[target] = { bg: null, elements: [] };
  1448. selectedId = null;
  1449. commit();
  1450. renderDesign();
  1451. renderSettings();
  1452. toast('已清空' + (target === 'front' ? '正面' : '背面') + ' · 可撤销');
  1453. }
  1454. function duplicateSide() {
  1455. const from = activeSide;
  1456. const to = from === 'front' ? 'back' : 'front';
  1457. const src = sideData(from);
  1458. const copy = {
  1459. bg: src.bg,
  1460. elements: src.elements.map(function (el) {
  1461. const c = JSON.parse(JSON.stringify(el));
  1462. c.id = R.uid('el');
  1463. return c;
  1464. })
  1465. };
  1466. state.sides[to] = copy;
  1467. activeSide = to;
  1468. selectedId = null;
  1469. commit();
  1470. renderDesign();
  1471. toast('已复制到' + (to === 'front' ? '正面' : '背面'));
  1472. }
  1473. function selectedIndex() {
  1474. return allElements().findIndex(function (e) { return e.id === selectedId; });
  1475. }
  1476. function raiseElement() {
  1477. const i = selectedIndex();
  1478. if (i < 0 || i >= allElements().length - 1) return;
  1479. const arr = allElements();
  1480. const tmp = arr[i];
  1481. arr[i] = arr[i + 1];
  1482. arr[i + 1] = tmp;
  1483. commit();
  1484. renderCanvas();
  1485. renderTool();
  1486. }
  1487. function lowerElement() {
  1488. const i = selectedIndex();
  1489. if (i <= 0) return;
  1490. const arr = allElements();
  1491. const tmp = arr[i];
  1492. arr[i] = arr[i - 1];
  1493. arr[i - 1] = tmp;
  1494. commit();
  1495. renderCanvas();
  1496. renderTool();
  1497. }
  1498. function frontElement() {
  1499. const i = selectedIndex();
  1500. if (i < 0 || i >= allElements().length - 1) return;
  1501. const arr = allElements();
  1502. arr.push(arr.splice(i, 1)[0]);
  1503. commit();
  1504. renderCanvas();
  1505. renderTool();
  1506. }
  1507. function backElement() {
  1508. const i = selectedIndex();
  1509. if (i <= 0) return;
  1510. const arr = allElements();
  1511. arr.unshift(arr.splice(i, 1)[0]);
  1512. commit();
  1513. renderCanvas();
  1514. renderTool();
  1515. }
  1516. /* 拖拽排序:把 fromId 移动到 toId 的上/下(above=true 为更高层) */
  1517. function reorderElement(fromId, toId, above) {
  1518. if (!fromId || !toId || fromId === toId) return;
  1519. const arr = allElements();
  1520. const rv = arr.slice().reverse();
  1521. const si = rv.findIndex(function (x) { return x.id === fromId; });
  1522. const ti = rv.findIndex(function (x) { return x.id === toId; });
  1523. if (si < 0 || ti < 0) return;
  1524. const it = rv.splice(si, 1)[0];
  1525. let ins = ti > si ? ti - 1 : ti;
  1526. if (!above) ins += 1;
  1527. rv.splice(ins, 0, it);
  1528. arr.splice.apply(arr, [0, arr.length].concat(rv.reverse()));
  1529. selectedId = fromId;
  1530. commit();
  1531. renderCanvas();
  1532. renderTool();
  1533. renderProps();
  1534. }
  1535. function duplicateElement() {
  1536. const el = selectedEl();
  1537. if (!el) return;
  1538. const copy = JSON.parse(JSON.stringify(el));
  1539. copy.id = R.uid('el');
  1540. copy.x += 4;
  1541. copy.y += 4;
  1542. allElements().push(copy);
  1543. selectedId = copy.id;
  1544. commit();
  1545. renderCanvas();
  1546. renderProps();
  1547. renderTool();
  1548. }
  1549. function deleteElementById(id) {
  1550. const arr = allElements();
  1551. const i = arr.findIndex(function (e) { return e.id === id; });
  1552. if (i < 0) return;
  1553. arr.splice(i, 1);
  1554. if (selectedId === id) selectedId = null;
  1555. commit();
  1556. renderCanvas();
  1557. renderProps();
  1558. renderTool();
  1559. toast('已删除 · 可撤销');
  1560. }
  1561. function deleteElement() {
  1562. const i = selectedIndex();
  1563. if (i < 0) return;
  1564. allElements().splice(i, 1);
  1565. selectedId = null;
  1566. commit();
  1567. renderCanvas();
  1568. renderProps();
  1569. renderTool();
  1570. toast('已删除 · 可撤销');
  1571. }
  1572. function updateSelected(prop, value) {
  1573. const el = selectedEl();
  1574. if (!el) return;
  1575. if (prop === 'x' || prop === 'y' || prop === 'w' || prop === 'h' || prop === 'rotation' || prop === 'opacity' || prop === 'size' || prop === 'spacing' || prop === 'lineHeight' || prop === 'strokeWidth' || prop === 'radius') {
  1576. const n = Number(value);
  1577. if (isNaN(n)) return;
  1578. if (prop === 'opacity') el.opacity = clamp(n / 100, 0.1, 1);
  1579. else if (prop === 'size') el.size = Math.max(2, n);
  1580. else if (prop === 'w') el.w = Math.max(2, n);
  1581. else if (prop === 'h') el.h = Math.max(1, n);
  1582. else if (prop === 'lineHeight') el.lineHeight = Math.max(0.7, n);
  1583. else el[prop] = n;
  1584. if (el.type === 'badge' && prop === 'w') el.h = el.w;
  1585. if (el.type === 'sticker' && prop === 'w') el.h = el.w;
  1586. } else if (prop === 'italic' || prop === 'mono' || prop === 'showText') {
  1587. el[prop] = !!value;
  1588. } else {
  1589. el[prop] = value;
  1590. }
  1591. if (el.type === 'text' && prop === 'text') {
  1592. el.w = el.w || size().w * 0.6;
  1593. }
  1594. if (el.type === 'badge' && prop === 'size') el.h = el.w;
  1595. scheduleRenderCanvas();
  1596. }
  1597. function openInlineText(el) {
  1598. if (!el || el.type !== 'text') return;
  1599. inlineTarget = el;
  1600. const g = els.canvasStage.querySelector('.sel-overlay');
  1601. let rect = g ? g.getBoundingClientRect() : { left: innerWidth / 2 - 150, bottom: innerHeight / 2, top: innerHeight / 2 };
  1602. const width = 300;
  1603. const left = clamp(rect.left, 12, innerWidth - width - 12);
  1604. let top = rect.bottom + 10;
  1605. if (top + 160 > innerHeight) top = Math.max(12, rect.top - 158);
  1606. els.inlineText.style.left = left + 'px';
  1607. els.inlineText.style.top = top + 'px';
  1608. els.inlineTextArea.value = el.text || '';
  1609. els.inlineText.hidden = false;
  1610. setTimeout(function () { els.inlineTextArea.focus(); els.inlineTextArea.select(); }, 20);
  1611. }
  1612. function hideInlineText() {
  1613. if (!els.inlineText.hidden) els.inlineText.hidden = true;
  1614. inlineTarget = null;
  1615. }
  1616. function commitInlineText() {
  1617. if (!inlineTarget) return;
  1618. const el = inlineTarget;
  1619. el.text = els.inlineTextArea.value;
  1620. hideInlineText();
  1621. commit();
  1622. renderCanvas();
  1623. renderProps();
  1624. renderTool();
  1625. }
  1626. function changeSide(side) {
  1627. if (side === activeSide) return;
  1628. activeSide = side;
  1629. selectedId = null;
  1630. hideInlineText();
  1631. renderDesign();
  1632. }
  1633. function doUndo() {
  1634. if (hIndex <= 0) return;
  1635. hIndex -= 1;
  1636. applySnapshot(history[hIndex]);
  1637. selectedId = null;
  1638. saveState();
  1639. renderSettings();
  1640. if (mode === 'design') renderDesign();
  1641. if (mode === 'summary') renderSummary();
  1642. updateMeta();
  1643. toast('已撤销');
  1644. }
  1645. function doRedo() {
  1646. if (hIndex >= history.length - 1) return;
  1647. hIndex += 1;
  1648. applySnapshot(history[hIndex]);
  1649. selectedId = null;
  1650. saveState();
  1651. renderSettings();
  1652. if (mode === 'design') renderDesign();
  1653. if (mode === 'summary') renderSummary();
  1654. updateMeta();
  1655. toast('已重做');
  1656. }
  1657. function renderSummary() {
  1658. const p = renderProduct();
  1659. const s = size();
  1660. const design = sideData(summarySide);
  1661. els.summarySideSwitch.querySelectorAll('button').forEach(function (b) {
  1662. b.classList.toggle('on', b.dataset.side === summarySide);
  1663. });
  1664. els.summaryPreview.innerHTML = '<div class="bag-wrap">' + R.bagSVG(p, summarySide, design, { size: s, card: true, material: state.material, finish: state.finish }) + '</div>';
  1665. els.summaryThumbs.innerHTML = ['front', 'back'].map(function (side) {
  1666. return '<button class="summary-thumb ' + (side === summarySide ? 'on' : '') + '" data-summary-side="' + side + '">' +
  1667. R.bagSVG(p, side, sideData(side), { size: s, card: true, material: state.material, finish: state.finish }) + '</button>';
  1668. }).join('');
  1669. const price = D.price(state);
  1670. els.summaryOrder.innerHTML =
  1671. '<div class="order-lines" style="margin-top:0;padding-top:0;border-top:0">' +
  1672. priceLines().map(function (row) { return '<div class="order-line"><span>' + row[0] + '</span><b>' + row[1] + '</b></div>'; }).join('') +
  1673. '<div class="order-line"><span>设计名称</span><b>' + esc(state.name) + '</b></div></div>' +
  1674. '<div class="order-total"><span>合计</span><b>¥' + price.total.toFixed(2) + '<small> / ' + state.qty + ' 个</small></b></div>';
  1675. const submit = $('#submitOrder');
  1676. if (submit) submit.textContent = '提交订单 · ¥' + price.total.toFixed(2);
  1677. updateMeta();
  1678. }
  1679. function exportCurrent() {
  1680. const p = renderProduct();
  1681. const s = size();
  1682. const side = mode === 'summary' ? summarySide : activeSide;
  1683. const svg = R.bagSVG(p, side, sideData(side), { size: s, card: true, width: 1400, material: state.material, finish: state.finish });
  1684. const blob = new Blob([svg], { type: 'image/svg+xml;charset=utf-8' });
  1685. const url = URL.createObjectURL(blob);
  1686. const img = new Image();
  1687. img.onload = function () {
  1688. const pad = 90;
  1689. const footer = 150;
  1690. const canvas = document.createElement('canvas');
  1691. const scale = 1;
  1692. canvas.width = (img.width + pad * 2) * scale;
  1693. canvas.height = (img.height + pad + footer) * scale;
  1694. const ctx = canvas.getContext('2d');
  1695. ctx.scale(scale, scale);
  1696. ctx.fillStyle = '#f6f2e9';
  1697. ctx.fillRect(0, 0, canvas.width, canvas.height);
  1698. ctx.drawImage(img, pad, pad, img.width, img.height);
  1699. ctx.fillStyle = '#17140f';
  1700. ctx.font = '700 24px "PingFang SC", "Helvetica Neue", sans-serif';
  1701. ctx.fillText(state.name, pad, img.height + pad + 46);
  1702. ctx.fillStyle = '#7d7466';
  1703. ctx.font = '400 15px "PingFang SC", "Helvetica Neue", sans-serif';
  1704. ctx.fillText(p.name + ' · ' + s.label + ' · ' + s.w + '×' + s.h + ' mm · ' + state.qty + ' 个 · ' + (side === 'front' ? '正面' : '背面'), pad, img.height + pad + 74);
  1705. ctx.fillStyle = '#a79d8d';
  1706. ctx.font = '400 12px "SF Mono", Menlo, monospace';
  1707. ctx.fillText('POUCHLAB DESIGN STUDIO · 300 DPI · ' + new Date().toLocaleDateString('zh-CN'), pad, img.height + pad + 100);
  1708. URL.revokeObjectURL(url);
  1709. canvas.toBlob(function (b) {
  1710. const a = document.createElement('a');
  1711. a.href = URL.createObjectURL(b);
  1712. a.download = 'pouchlab-' + p.id + '-' + side + '.png';
  1713. a.click();
  1714. setTimeout(function () { URL.revokeObjectURL(a.href); }, 1500);
  1715. toast('效果图已下载');
  1716. }, 'image/png');
  1717. };
  1718. img.onerror = function () {
  1719. URL.revokeObjectURL(url);
  1720. const a = document.createElement('a');
  1721. a.href = URL.createObjectURL(blob);
  1722. a.download = 'pouchlab-' + p.id + '.svg';
  1723. a.click();
  1724. toast('已下载 SVG 文件');
  1725. };
  1726. img.src = url;
  1727. }
  1728. function open3d() {
  1729. three.side = mode === 'summary' ? summarySide : activeSide;
  1730. three.rot = three.side === 'front' ? -18 : 162;
  1731. els.rotateRange.value = three.rot;
  1732. els.modal3d.hidden = false;
  1733. if (ensurePouchGL()) {
  1734. updatePouchGL();
  1735. return;
  1736. }
  1737. render3d();
  1738. }
  1739. /* ---- FBX 真实模型 3D 预览(pouch3d) ---- */
  1740. let pouchGL = null;
  1741. function ensurePouchGL() {
  1742. if (!window.PL || !PL.pouch3d) return false;
  1743. if (!pouchGL) {
  1744. const stage = document.createElement('div');
  1745. stage.id = 'pouchGL';
  1746. stage.style.cssText = 'position:absolute;inset:0;z-index:2;';
  1747. $('#scene3d').appendChild(stage);
  1748. pouchGL = PL.pouch3d.create(stage, {
  1749. onLoadError: function () {
  1750. // GL 失败 → 回退 CSS 3D
  1751. try { stage.remove(); } catch (e) {}
  1752. pouchGL = null;
  1753. if (els.pouch3d) els.pouch3d.style.display = '';
  1754. render3d();
  1755. }
  1756. });
  1757. }
  1758. if (els.pouch3d) els.pouch3d.style.display = 'none';
  1759. return true;
  1760. }
  1761. function updatePouchGL() {
  1762. if (!pouchGL) return;
  1763. const p = renderProduct();
  1764. const s = size();
  1765. const color = (state.bagColor || p.mockColor || '#e8e2d4');
  1766. const shape = p.shape || 'standup';
  1767. // 用户显式选择 open/closed 优先;未选择时按袋型默认(邮封袋→开口,其余→封口)
  1768. const eff = three.modelMode || (shape === 'mailer' ? 'open' : 'closed');
  1769. const sw = document.getElementById('pouchModelSwitch');
  1770. if (sw) sw.querySelectorAll('button').forEach(function (x) {
  1771. x.classList.toggle('on', x.dataset.model === eff);
  1772. });
  1773. pouchGL.load(eff, function () {
  1774. pouchGL.applyDesign({
  1775. color: color,
  1776. frontDesign: previewDesignFor('front'),
  1777. backDesign: previewDesignFor('back'),
  1778. frontBg: previewDesignFor('front').bg || color,
  1779. backBg: previewDesignFor('back').bg || color,
  1780. W: s.w, H: s.h
  1781. });
  1782. pouchGL.setRotation(three.rot);
  1783. });
  1784. }
  1785. function previewDesignFor(side) {
  1786. const sd = sideData(side);
  1787. if (sd.elements.length) return sd;
  1788. const s = size();
  1789. const t = D.templateById(sampleMap[product().id] || 'citrus');
  1790. return R.designFromTemplate(t.id, s.w, s.h, side);
  1791. }
  1792. function render3d() {
  1793. if (pouchGL && pouchGL.ready()) {
  1794. updatePouchGL();
  1795. els.rotateRange.value = three.rot;
  1796. els.previewSideSwitch.querySelectorAll('button').forEach(function (b) {
  1797. b.classList.toggle('on', (b.dataset.side === 'front' && three.rot > -90 && three.rot < 90) || (b.dataset.side === 'back' && (three.rot > 90 || three.rot < -90)));
  1798. });
  1799. return;
  1800. }
  1801. const p = renderProduct();
  1802. const s = size();
  1803. const front = R.bagSVG(p, 'front', previewDesignFor('front'), { size: s, tight: true, material: state.material, finish: state.finish });
  1804. const back = R.bagSVG(p, 'back', previewDesignFor('back'), { size: s, tight: true, material: state.material, finish: state.finish });
  1805. els.faceFront.innerHTML = front || '';
  1806. els.faceBack.innerHTML = back || '';
  1807. window.__r3d.push('written');
  1808. const pad = p.pad;
  1809. const aspect = (s.w + pad.l + pad.r) / (s.h + pad.t + pad.b);
  1810. const sceneH = $('.scene').clientHeight || 440;
  1811. const h = Math.min(400, Math.max(260, sceneH - 80));
  1812. const w = clamp(h * aspect, 150, 360);
  1813. els.pouch3d.style.height = h + 'px';
  1814. els.pouch3d.style.width = w + 'px';
  1815. // 侧面体积渐变:顶部封口薄暗 → 中下鼓面高光(膨鼓最饱满处 ~74%)→ 底部承重微暗,基色跟随袋色
  1816. const sideVolume = function (lightPos) {
  1817. return [
  1818. 'radial-gradient(ellipse 120% 60% at 50% 74%, rgba(255,255,255,0.30), transparent 58%)',
  1819. 'linear-gradient(180deg, rgba(0,0,0,0.34) 0%, rgba(0,0,0,0.08) 22%, transparent 42%, rgba(0,0,0,0.10) 92%)',
  1820. 'linear-gradient(90deg,' + R.shade(p.mockColor, -0.30) + ',' + R.shade(p.mockColor, 0.14) + ' ' + lightPos + '%,' + R.shade(p.mockColor, -0.34) + ')'
  1821. ].join(',');
  1822. };
  1823. els.faceSide.style.transform = 'rotateY(90deg) translateZ(' + (w / 2) + 'px)';
  1824. els.faceSide.style.background = sideVolume(46);
  1825. if (els.faceSideLeft) {
  1826. els.faceSideLeft.style.transform = 'rotateY(-90deg) translateZ(' + (w / 2) + 'px)';
  1827. els.faceSideLeft.style.background = sideVolume(54);
  1828. }
  1829. apply3dRotation();
  1830. els.previewSideSwitch.querySelectorAll('button').forEach(function (b) {
  1831. b.classList.toggle('on', (b.dataset.side === 'front' && three.rot > -90 && three.rot < 90) || (b.dataset.side === 'back' && (three.rot > 90 || three.rot < -90)));
  1832. });
  1833. }
  1834. function apply3dRotation() {
  1835. els.pouch3d.style.transform = 'rotateX(4deg) rotateY(' + three.rot + 'deg)';
  1836. els.rotateRange.value = three.rot;
  1837. }
  1838. function close3d() {
  1839. els.modal3d.hidden = true;
  1840. }
  1841. function goSummary() {
  1842. if (!state.sides.front.elements.length && !state.sides.back.elements.length) {
  1843. toast('先添加一些内容,再确认订单');
  1844. return;
  1845. }
  1846. setMode('summary');
  1847. }
  1848. function nextStep() {
  1849. if (mode === 'settings') enterDesign();
  1850. else if (mode === 'design') goSummary();
  1851. else {
  1852. const form = $('#orderForm');
  1853. if (form) {
  1854. if (form.reportValidity()) form.requestSubmit();
  1855. }
  1856. }
  1857. }
  1858. function addUploadedFile(file) {
  1859. if (!file || file.type.indexOf('image') !== 0) {
  1860. toast('请选择图片文件');
  1861. return;
  1862. }
  1863. if (file.size > 12 * 1024 * 1024) {
  1864. toast('图片过大,请使用 12MB 以内的文件');
  1865. return;
  1866. }
  1867. const reader = new FileReader();
  1868. reader.onload = function () {
  1869. const img = new Image();
  1870. img.onload = function () {
  1871. const max = 1400;
  1872. let w = img.width;
  1873. let h = img.height;
  1874. if (Math.max(w, h) > max) {
  1875. const k = max / Math.max(w, h);
  1876. w = Math.round(w * k);
  1877. h = Math.round(h * k);
  1878. }
  1879. const canvas = document.createElement('canvas');
  1880. canvas.width = w;
  1881. canvas.height = h;
  1882. const ctx = canvas.getContext('2d');
  1883. ctx.drawImage(img, 0, 0, w, h);
  1884. const isPng = file.type === 'image/png' || file.type === 'image/svg+xml';
  1885. const src = canvas.toDataURL(isPng ? 'image/png' : 'image/jpeg', 0.9);
  1886. const up = { id: R.uid('up'), name: file.name, src: src, w: w, h: h };
  1887. state.uploads.unshift(up);
  1888. if (state.uploads.length > 12) state.uploads = state.uploads.slice(0, 12);
  1889. addImageFromUpload(up);
  1890. saveState(true);
  1891. renderTool();
  1892. };
  1893. img.src = reader.result;
  1894. };
  1895. reader.readAsDataURL(file);
  1896. }
  1897. function pickUpload(replace) {
  1898. const input = document.createElement('input');
  1899. input.type = 'file';
  1900. input.accept = 'image/png,image/jpeg,image/svg+xml,image/webp';
  1901. input.onchange = function () {
  1902. const file = input.files && input.files[0];
  1903. if (!file) return;
  1904. if (replace) {
  1905. const el = selectedEl();
  1906. if (!el) return;
  1907. const reader = new FileReader();
  1908. reader.onload = function () {
  1909. el.src = reader.result;
  1910. el.name = file.name;
  1911. const img = new Image();
  1912. img.onload = function () {
  1913. el.h = el.w * (img.height / img.width);
  1914. commit();
  1915. renderCanvas();
  1916. renderProps();
  1917. };
  1918. img.src = reader.result;
  1919. };
  1920. reader.readAsDataURL(file);
  1921. } else {
  1922. addUploadedFile(file);
  1923. }
  1924. };
  1925. input.click();
  1926. }
  1927. function bindSettings() {
  1928. els.settingsView.addEventListener('click', function (e) {
  1929. const color = e.target.closest('[data-color]');
  1930. if (color) { changeBagColor(color.dataset.color); }
  1931. });
  1932. }
  1933. function bindTopbar() {
  1934. els.continueBtn.addEventListener('click', nextStep);
  1935. els.undoBtn.addEventListener('click', doUndo);
  1936. els.redoBtn.addEventListener('click', doRedo);
  1937. els.studioSteps.addEventListener('click', function (e) {
  1938. const btn = e.target.closest('[data-step]');
  1939. if (!btn) return;
  1940. if (btn.dataset.step === 'summary' && mode !== 'summary') {
  1941. if (!state.sides.front.elements.length && !state.sides.back.elements.length) {
  1942. ensureSample();
  1943. }
  1944. setMode('summary');
  1945. return;
  1946. }
  1947. setMode(btn.dataset.step);
  1948. });
  1949. els.designName.addEventListener('input', function () {
  1950. state.name = this.value || '未命名设计';
  1951. saveState(true);
  1952. updateMeta();
  1953. if (mode === 'summary') renderSummary();
  1954. });
  1955. els.designName.addEventListener('change', function () { commit(); });
  1956. $('#preview3dBtn').addEventListener('click', open3d);
  1957. }
  1958. function bindDesign() {
  1959. els.toolRail.addEventListener('click', function (e) {
  1960. const btn = e.target.closest('[data-tool]');
  1961. if (!btn) return;
  1962. tool = btn.dataset.tool;
  1963. renderTool();
  1964. els.designView.classList.remove('panel-collapsed');
  1965. els.designView.classList.add('panel-open');
  1966. });
  1967. els.sideSwitch.addEventListener('click', function (e) {
  1968. const btn = e.target.closest('[data-side]');
  1969. if (btn) changeSide(btn.dataset.side);
  1970. });
  1971. els.guidesToggle.addEventListener('change', function () {
  1972. showGuides = this.checked;
  1973. renderCanvas();
  1974. });
  1975. $('#zoomIn').addEventListener('click', function () { updateZoom(zoom * 1.18); });
  1976. $('#zoomOut').addEventListener('click', function () { updateZoom(zoom / 1.18); });
  1977. $('#zoomFit').addEventListener('click', function () { zoom = 1; renderCanvas(); });
  1978. $('#downloadBtn').addEventListener('click', exportCurrent);
  1979. $('#toolPanelClose').addEventListener('click', function () {
  1980. els.designView.classList.remove('panel-open');
  1981. els.designView.classList.add('panel-collapsed');
  1982. });
  1983. els.canvasEmpty.addEventListener('click', function (e) {
  1984. const btn = e.target.closest('[data-empty-action]');
  1985. if (!btn) return;
  1986. tool = btn.dataset.emptyAction === 'upload' ? 'upload' : 'templates';
  1987. renderTool();
  1988. });
  1989. els.toolBody.addEventListener('click', function (e) {
  1990. const tpl = e.target.closest('[data-template]');
  1991. if (tpl) { applyTemplate(tpl.dataset.template); return; }
  1992. const preset = e.target.closest('[data-preset]');
  1993. if (preset) { addTextPreset(preset.dataset.preset); return; }
  1994. const font = e.target.closest('[data-font]');
  1995. if (font) {
  1996. const el = selectedEl();
  1997. if (el && el.type === 'text') {
  1998. el.font = font.dataset.font;
  1999. lastFont = el.font;
  2000. commit();
  2001. renderCanvas();
  2002. renderProps();
  2003. } else {
  2004. addTextPreset('body', font.dataset.font);
  2005. }
  2006. return;
  2007. }
  2008. const shape = e.target.closest('[data-shape]');
  2009. if (shape) { addShape(shape.dataset.shape); return; }
  2010. const sticker = e.target.closest('[data-sticker]');
  2011. if (sticker) { addSticker(sticker.dataset.sticker); return; }
  2012. const layer = e.target.closest('[data-layer]');
  2013. if (layer && !e.target.closest('[data-eye]')) {
  2014. selectedId = layer.dataset.layer;
  2015. renderCanvas();
  2016. renderProps();
  2017. renderTool();
  2018. return;
  2019. }
  2020. const eye = e.target.closest('[data-eye]');
  2021. if (eye) {
  2022. const el = allElements().find(function (x) { return x.id === eye.dataset.eye; });
  2023. if (el) { el.hidden = !el.hidden; commit(); renderCanvas(); renderTool(); }
  2024. return;
  2025. }
  2026. const rm = e.target.closest('[data-remove-upload]');
  2027. if (rm) {
  2028. state.uploads = state.uploads.filter(function (u) { return u.id !== rm.dataset.removeUpload; });
  2029. commit();
  2030. renderTool();
  2031. return;
  2032. }
  2033. const uploadZone = e.target.closest('[data-action="pick-upload"]');
  2034. if (uploadZone) { pickUpload(false); return; }
  2035. const ins = e.target.closest('[data-size]');
  2036. if (ins) { changeSize(ins.dataset.size); renderTool(); return; }
  2037. const qty = e.target.closest('[data-qty]');
  2038. if (qty) { changeSetting('qty', qty.dataset.qty); renderTool(); return; }
  2039. const bagColor = e.target.closest('[data-bag-color]');
  2040. if (bagColor) { changeBagColor(bagColor.dataset.bagColor); renderTool(); return; }
  2041. const action = e.target.closest('[data-action]');
  2042. if (action) {
  2043. const a = action.dataset.action;
  2044. if (a === 'settings') setMode('settings');
  2045. if (a === 'clear-side') clearSide();
  2046. if (a === 'dup-side') duplicateSide();
  2047. }
  2048. });
  2049. els.toolBody.addEventListener('change', function (e) {
  2050. if (e.target.id === 'toolMaterial') { changeSetting('material', e.target.value); renderTool(); }
  2051. if (e.target.id === 'toolFinish') { changeSetting('finish', e.target.value); renderTool(); }
  2052. });
  2053. els.toolBody.addEventListener('dragover', function (e) {
  2054. const zone = e.target.closest('.upload-zone');
  2055. if (!zone) return;
  2056. e.preventDefault();
  2057. zone.classList.add('drag');
  2058. });
  2059. els.toolBody.addEventListener('dragleave', function (e) {
  2060. const zone = e.target.closest('.upload-zone');
  2061. if (zone) zone.classList.remove('drag');
  2062. });
  2063. els.toolBody.addEventListener('drop', function (e) {
  2064. const zone = e.target.closest('.upload-zone');
  2065. if (!zone) return;
  2066. e.preventDefault();
  2067. zone.classList.remove('drag');
  2068. Array.from(e.dataTransfer.files).slice(0, 4).forEach(addUploadedFile);
  2069. });
  2070. els.propsBody.addEventListener('input', function (e) {
  2071. const t = e.target;
  2072. if (t.hasAttribute('data-toggle-guides')) {
  2073. showGuides = t.checked;
  2074. renderCanvas();
  2075. return;
  2076. }
  2077. const bgCustom = t.closest('[data-bg-custom]');
  2078. if (bgCustom) {
  2079. sideData().bg = bgCustom.value;
  2080. scheduleRenderCanvas();
  2081. return;
  2082. }
  2083. const prop = t.dataset.prop;
  2084. if (!prop) return;
  2085. let v;
  2086. if (t.type === 'checkbox') v = t.checked;
  2087. else if (t.hasAttribute('data-num')) v = num(t.value, 0);
  2088. else v = t.value;
  2089. if (t.dataset.scale) v = Number(v);
  2090. if (prop === 'opacity') v = v;
  2091. updateSelected(prop, v);
  2092. const colorSpan = t.parentElement && t.parentElement.querySelector('span');
  2093. if (t.type === 'color' && colorSpan) colorSpan.textContent = String(t.value).replace('#', '');
  2094. });
  2095. els.propsBody.addEventListener('change', function (e) {
  2096. const t = e.target;
  2097. if (t.hasAttribute('data-toggle-guides')) return;
  2098. const bgCustom = t.closest('[data-bg-custom]');
  2099. if (bgCustom) {
  2100. sideData().bg = bgCustom.value;
  2101. commit();
  2102. renderCanvas();
  2103. renderProps();
  2104. return;
  2105. }
  2106. if (t.dataset.prop || t.type === 'color') {
  2107. commit();
  2108. renderTool();
  2109. }
  2110. });
  2111. els.propsBody.addEventListener('click', function (e) {
  2112. const prop = e.target.closest('[data-prop]');
  2113. if (prop && (prop.type === 'color')) return;
  2114. const weight = e.target.closest('[data-weight]');
  2115. if (weight) { const el = selectedEl(); if (el) { el.weight = Number(weight.dataset.weight); commit(); renderCanvas(); renderProps(); } return; }
  2116. const align = e.target.closest('[data-align]');
  2117. if (align) { const el = selectedEl(); if (el) { el.align = align.dataset.align; commit(); renderCanvas(); renderProps(); } return; }
  2118. const fit = e.target.closest('[data-fit]');
  2119. if (fit) { const el = selectedEl(); if (el) { el.fit = fit.dataset.fit; commit(); renderCanvas(); renderProps(); } return; }
  2120. const bg = e.target.closest('[data-bg]');
  2121. if (bg) { sideData().bg = bg.dataset.bg || null; commit(); renderCanvas(); renderProps(); return; }
  2122. const bagColor = e.target.closest('[data-bag-color]');
  2123. if (bagColor) { changeBagColor(bagColor.dataset.bagColor); renderProps(); return; }
  2124. const sideJump = e.target.closest('[data-side-jump]');
  2125. if (sideJump) { changeSide(sideJump.dataset.sideJump); return; }
  2126. const action = e.target.closest('[data-action]');
  2127. if (action) {
  2128. const a = action.dataset.action;
  2129. if (a === 'raise') raiseElement();
  2130. if (a === 'lower') lowerElement();
  2131. if (a === 'duplicate') duplicateElement();
  2132. if (a === 'delete') deleteElement();
  2133. if (a === 'replace-image') pickUpload(true);
  2134. if (a === 'clear-side') clearSide();
  2135. if (a === 'dup-side') duplicateSide();
  2136. }
  2137. });
  2138. els.canvasStage.addEventListener('pointerdown', onCanvasPointerDown);
  2139. els.canvasStage.addEventListener('dblclick', function (e) {
  2140. const g = e.target.closest('[data-id]');
  2141. if (!g) return;
  2142. const el = allElements().find(function (x) { return x.id === g.dataset.id; });
  2143. if (el && el.type === 'text') {
  2144. selectedId = el.id;
  2145. renderCanvas();
  2146. renderProps();
  2147. openInlineText(el);
  2148. }
  2149. });
  2150. els.inlineTextDone.addEventListener('click', commitInlineText);
  2151. els.inlineTextArea.addEventListener('keydown', function (e) {
  2152. if ((e.metaKey || e.ctrlKey) && e.key === 'Enter') { e.preventDefault(); commitInlineText(); }
  2153. e.stopPropagation();
  2154. });
  2155. els.inlineTextArea.addEventListener('blur', function () {
  2156. setTimeout(function () {
  2157. if (document.activeElement !== els.inlineTextDone && document.activeElement !== els.inlineTextArea) commitInlineText();
  2158. }, 120);
  2159. });
  2160. $('#summarySideSwitch').addEventListener('click', function (e) {
  2161. const b = e.target.closest('[data-side]');
  2162. if (!b) return;
  2163. summarySide = b.dataset.side;
  2164. renderSummary();
  2165. });
  2166. els.summaryThumbs.addEventListener('click', function (e) {
  2167. const b = e.target.closest('[data-summary-side]');
  2168. if (!b) return;
  2169. summarySide = b.dataset.summarySide;
  2170. renderSummary();
  2171. });
  2172. $('#backToDesign').addEventListener('click', function () { setMode('design'); });
  2173. $('#summaryDownload').addEventListener('click', exportCurrent);
  2174. $('#summaryPreview3d').addEventListener('click', open3d);
  2175. let orderSubmitting = false;
  2176. function buildOrderPayload(data) {
  2177. const p = product();
  2178. const s = size();
  2179. const mat = D.materialById(state.material);
  2180. const fin = D.finishById(state.finish);
  2181. const price = D.price(state);
  2182. let design = null;
  2183. try { design = JSON.parse(snapshot()); } catch (err) { design = null; }
  2184. const payload = {
  2185. type: 'bag',
  2186. contact: {
  2187. name: data.get('name') || '',
  2188. phone: data.get('phone') || '',
  2189. email: data.get('email') || '',
  2190. address: data.get('address') || '',
  2191. note: data.get('note') || ''
  2192. },
  2193. spec: {
  2194. productId: p.id, productName: p.name,
  2195. sizeId: state.sizeId, sizeLabel: s.label, w: s.w, h: s.h,
  2196. material: state.material, materialName: mat ? mat.name : state.material,
  2197. finish: state.finish, finishName: fin ? fin.name : state.finish,
  2198. qty: state.qty
  2199. },
  2200. quote: { unit: price.unit, total: price.total },
  2201. summary: p.name + ' ' + s.w + '×' + s.h + 'mm · ' + (mat ? mat.name : '') + ' · ' + state.qty + ' 只',
  2202. design: design,
  2203. dieline: {
  2204. kind: 'bag', bleed: 3,
  2205. faces: [{ key: 'front', w: s.w, h: s.h }, { key: 'back', w: s.w, h: s.h }],
  2206. meta: { productName: p.name, material: mat ? mat.name : '', finish: fin ? fin.name : '', qty: state.qty }
  2207. },
  2208. previews: {}
  2209. };
  2210. return Promise.all(['front', 'back'].map(function (side) {
  2211. const svg = R.bagSVG(renderProduct(), side, sideData(side), { size: s, card: true, width: 900, material: state.material, finish: state.finish });
  2212. return PL.api.svgToPng(svg, 900);
  2213. })).then(function (pngs) {
  2214. payload.previews = { front: pngs[0], back: pngs[1] };
  2215. return payload;
  2216. }, function () {
  2217. return payload; // 预览图失败不阻塞下单
  2218. });
  2219. }
  2220. function finishSubmit(orderNo, offline) {
  2221. orderSubmitting = false;
  2222. const btn = $('#submitOrder');
  2223. btn.disabled = false;
  2224. btn.textContent = '提交订单';
  2225. els.orderNumber.textContent = orderNo;
  2226. const tip = document.getElementById('successTip');
  2227. if (tip) tip.hidden = !offline;
  2228. els.successView.hidden = false;
  2229. toast(offline ? '订单已离线保存(服务器不可达)' : '订单已提交,可前往「我的订单」支付');
  2230. }
  2231. $('#orderForm').addEventListener('submit', function (e) {
  2232. e.preventDefault();
  2233. if (window.PL.auth && !window.PL.auth.user()) {
  2234. window.PL.auth.require(function () { $('#orderForm').requestSubmit(); });
  2235. return;
  2236. }
  2237. const form = this;
  2238. const data = new FormData(form);
  2239. if (!data.get('name') || !data.get('phone') || !data.get('address')) {
  2240. form.reportValidity();
  2241. return;
  2242. }
  2243. if (orderSubmitting) return;
  2244. if (!window.PL || !PL.api) return;
  2245. orderSubmitting = true;
  2246. const btn = $('#submitOrder');
  2247. btn.disabled = true;
  2248. btn.textContent = '正在提交订单…';
  2249. buildOrderPayload(data).then(function (payload) {
  2250. return PL.api.post('/orders', payload, { timeout: 60000 });
  2251. }).then(function (r) {
  2252. finishSubmit(r.orderNo, false);
  2253. }, function (err) {
  2254. if (err && err.network) {
  2255. // 离线回退:沿用旧的本地保存行为
  2256. const n = 'PL-' + String(new Date().getFullYear()) + String(Date.now()).slice(-6);
  2257. try {
  2258. localStorage.setItem('pouchlab.order.' + n, JSON.stringify({
  2259. name: data.get('name'), phone: data.get('phone'), email: data.get('email'),
  2260. note: data.get('note'), order: n, total: D.price(state).total, design: snapshot(), at: Date.now()
  2261. }));
  2262. } catch (e2) {}
  2263. finishSubmit(n, true);
  2264. return;
  2265. }
  2266. orderSubmitting = false;
  2267. btn.disabled = false;
  2268. btn.textContent = '提交订单';
  2269. toast(err.message || '订单提交失败,请重试');
  2270. });
  2271. });
  2272. $('#successBack').addEventListener('click', function () { location.href = 'index.html'; });
  2273. els.modal3d.addEventListener('click', function (e) {
  2274. if (e.target.closest('[data-close="3d"]')) close3d();
  2275. });
  2276. $('#pouchModelSwitch').addEventListener('click', function (e) {
  2277. const b = e.target.closest('[data-model]');
  2278. if (!b) return;
  2279. three.modelMode = b.dataset.model;
  2280. this.querySelectorAll('button').forEach(function (x) {
  2281. x.classList.toggle('on', x === b);
  2282. });
  2283. if (pouchGL && pouchGL.ready()) updatePouchGL();
  2284. });
  2285. $('#previewSideSwitch').addEventListener('click', function (e) {
  2286. const b = e.target.closest('[data-side]');
  2287. if (!b) return;
  2288. three.rot = b.dataset.side === 'front' ? -18 : 162;
  2289. if (pouchGL && pouchGL.ready()) {
  2290. pouchGL.setRotation(three.rot);
  2291. els.previewSideSwitch.querySelectorAll('button').forEach(function (x) {
  2292. x.classList.toggle('on', x.dataset.side === b.dataset.side);
  2293. });
  2294. return;
  2295. }
  2296. apply3dRotation();
  2297. render3d();
  2298. });
  2299. els.rotateRange.addEventListener('input', function () {
  2300. three.rot = Number(this.value);
  2301. if (pouchGL && pouchGL.ready()) {
  2302. pouchGL.setRotation(three.rot);
  2303. els.previewSideSwitch.querySelectorAll('button').forEach(function (b) {
  2304. b.classList.toggle('on', (b.dataset.side === 'front' && three.rot > -90 && three.rot < 90) || (b.dataset.side === 'back' && (three.rot > 90 || three.rot < -90)));
  2305. });
  2306. return;
  2307. }
  2308. apply3dRotation();
  2309. els.previewSideSwitch.querySelectorAll('button').forEach(function (b) {
  2310. b.classList.toggle('on', (b.dataset.side === 'front' && three.rot > -90 && three.rot < 90) || (b.dataset.side === 'back' && (three.rot > 90 || three.rot < -90)));
  2311. });
  2312. });
  2313. const scene = $('#scene3d');
  2314. let rotDrag = null;
  2315. scene.addEventListener('pointerdown', function (e) {
  2316. if (pouchGL && pouchGL.ready()) return; // GL 模式由模型画布自行处理拖拽
  2317. rotDrag = { x: e.clientX, rot: three.rot };
  2318. scene.setPointerCapture(e.pointerId);
  2319. });
  2320. scene.addEventListener('pointermove', function (e) {
  2321. if (!rotDrag) return;
  2322. three.rot = clamp(rotDrag.rot + (e.clientX - rotDrag.x) * 0.45, -180, 180);
  2323. apply3dRotation();
  2324. });
  2325. scene.addEventListener('pointerup', function () { rotDrag = null; });
  2326. scene.addEventListener('pointercancel', function () { rotDrag = null; });
  2327. }
  2328. /* 参考潘通色网格(防侵权叫法:不称潘通色;实际以打样效果为准) */
  2329. function pmsGrid(onPick, currentHex) {
  2330. const P = window.PL.pantone;
  2331. const cur = (currentHex || '').toLowerCase();
  2332. return [
  2333. h('div', { className: 'pms-grid' }, P.list.map(function (c) {
  2334. return h('button', {
  2335. key: c.code, type: 'button',
  2336. className: 'pms-dot' + (cur === c.hex.toLowerCase() ? ' on' : ''),
  2337. title: '参考潘通色 ' + c.code + ' ' + c.name,
  2338. style: { background: c.hex },
  2339. onClick: function () { onPick(c); }
  2340. });
  2341. })),
  2342. h('div', { className: 'pms-note' }, P.note)
  2343. ];
  2344. }
  2345. function pointInElement(el, pt) {
  2346. const box = R.elementBox(el);
  2347. const rot = -(el.rotation || 0) * Math.PI / 180;
  2348. const cx = box.w / 2;
  2349. const cy = box.h / 2;
  2350. const dx = pt.x - el.x - cx;
  2351. const dy = pt.y - el.y - cy;
  2352. const rx = Math.cos(rot) * dx - Math.sin(rot) * dy + cx;
  2353. const ry = Math.sin(rot) * dx + Math.cos(rot) * dy + cy;
  2354. return rx >= 0 && rx <= box.w && ry >= 0 && ry <= box.h;
  2355. }
  2356. function onCanvasPointerDown(e) {
  2357. if (e.button !== 0) return;
  2358. const svg = els.canvasStage.querySelector('svg');
  2359. if (!svg) return;
  2360. const handle = e.target.closest('[data-handle]');
  2361. if (handle && selectedId) {
  2362. e.preventDefault();
  2363. startTransform(e, svg, handle.dataset.handle);
  2364. return;
  2365. }
  2366. const group = e.target.closest('[data-id]');
  2367. if (group) {
  2368. let id = group.dataset.id;
  2369. if (e.altKey && selectedId) {
  2370. const pt = svgPoint(e, svg);
  2371. const hits = allElements().filter(function (el) { return !el.hidden && pointInElement(el, pt); });
  2372. if (hits.length > 1) {
  2373. const idx = hits.findIndex(function (x) { return x.id === selectedId; });
  2374. id = hits[(idx + 1) % hits.length].id;
  2375. }
  2376. }
  2377. if (selectedId !== id) {
  2378. selectedId = id;
  2379. renderCanvas();
  2380. renderProps();
  2381. renderTool();
  2382. }
  2383. const el = selectedEl();
  2384. if (!el) return;
  2385. const liveSvg = els.canvasStage.querySelector('svg');
  2386. startDrag(e, liveSvg, el);
  2387. return;
  2388. }
  2389. selectedId = null;
  2390. renderCanvas();
  2391. renderProps();
  2392. renderTool();
  2393. }
  2394. function svgPoint(e, svg) {
  2395. const pt = svg.createSVGPoint();
  2396. pt.x = e.clientX;
  2397. pt.y = e.clientY;
  2398. const m = svg.getScreenCTM();
  2399. if (!m) return { x: 0, y: 0 };
  2400. return pt.matrixTransform(m.inverse());
  2401. }
  2402. function setElementTransform(el) {
  2403. const g = els.canvasStage.querySelector('[data-id="' + el.id + '"]');
  2404. if (!g) return;
  2405. const box = R.elementBox(el);
  2406. g.setAttribute('transform', 'translate(' + el.x + ' ' + el.y + ') rotate(' + (el.rotation || 0) + ' ' + (box.w / 2) + ' ' + (box.h / 2) + ')');
  2407. const sel = els.canvasStage.querySelector('.sel-overlay');
  2408. if (sel) sel.setAttribute('transform', 'translate(' + el.x + ' ' + el.y + ') rotate(' + (el.rotation || 0) + ' ' + (box.w / 2) + ' ' + (box.h / 2) + ')');
  2409. }
  2410. function setDragGuides(gx, gy) {
  2411. const svg = els.canvasStage.querySelector('svg');
  2412. if (!svg) return;
  2413. svg.querySelectorAll('.drag-guide').forEach(function (n) { n.remove(); });
  2414. const p = product().pad;
  2415. const s = size();
  2416. const NS = 'http://www.w3.org/2000/svg';
  2417. if (gx != null) {
  2418. const l = document.createElementNS(NS, 'line');
  2419. l.setAttribute('class', 'drag-guide');
  2420. l.setAttribute('x1', gx); l.setAttribute('x2', gx);
  2421. l.setAttribute('y1', -p.t - 6); l.setAttribute('y2', s.h + p.b + 6);
  2422. l.setAttribute('stroke', '#ff5c2b');
  2423. l.setAttribute('stroke-width', '0.5');
  2424. l.setAttribute('stroke-dasharray', '2 2');
  2425. l.setAttribute('data-ui', '1');
  2426. svg.appendChild(l);
  2427. }
  2428. if (gy != null) {
  2429. const l = document.createElementNS(NS, 'line');
  2430. l.setAttribute('class', 'drag-guide');
  2431. l.setAttribute('y1', gy); l.setAttribute('y2', gy);
  2432. l.setAttribute('x1', -p.l - 6); l.setAttribute('x2', s.w + p.r + 6);
  2433. l.setAttribute('stroke', '#ff5c2b');
  2434. l.setAttribute('stroke-width', '0.5');
  2435. l.setAttribute('stroke-dasharray', '2 2');
  2436. l.setAttribute('data-ui', '1');
  2437. svg.appendChild(l);
  2438. }
  2439. }
  2440. function startDrag(e, svg, el) {
  2441. isDragging = true;
  2442. const liveSvg = function () { return els.canvasStage.querySelector('svg') || svg; };
  2443. const start = svgPoint(e, liveSvg());
  2444. const orig = { x: el.x, y: el.y };
  2445. const box = R.elementBox(el);
  2446. const s = size();
  2447. let moved = false;
  2448. let lastGx = null;
  2449. let lastGy = null;
  2450. function move(ev) {
  2451. const p = svgPoint(ev, liveSvg());
  2452. let dx = p.x - start.x;
  2453. let dy = p.y - start.y;
  2454. if (ev.shiftKey) {
  2455. if (Math.abs(dx) > Math.abs(dy)) dy = 0; else dx = 0;
  2456. }
  2457. let x = orig.x + dx;
  2458. let y = orig.y + dy;
  2459. let gx = null;
  2460. let gy = null;
  2461. const tol = 2.2;
  2462. const cx = x + box.w / 2;
  2463. const cy = y + box.h / 2;
  2464. if (Math.abs(cx - s.w / 2) < tol) { x = s.w / 2 - box.w / 2; gx = s.w / 2; }
  2465. if (Math.abs(y) < tol) { y = 0; gy = 0; }
  2466. if (Math.abs(x) < tol) { x = 0; gx = 0; }
  2467. if (Math.abs(x + box.w - s.w) < tol) { x = s.w - box.w; gx = s.w; }
  2468. if (Math.abs(cy - s.h / 2) < tol) { y = s.h / 2 - box.h / 2; gy = s.h / 2; }
  2469. if (Math.abs(y + box.h - s.h) < tol) { y = s.h - box.h; gy = s.h; }
  2470. if (x !== el.x || y !== el.y) moved = true;
  2471. el.x = x; el.y = y;
  2472. setElementTransform(el);
  2473. if (gx !== lastGx || gy !== lastGy) {
  2474. lastGx = gx; lastGy = gy;
  2475. setDragGuides(gx, gy);
  2476. }
  2477. }
  2478. function up() {
  2479. document.removeEventListener('pointermove', move);
  2480. document.removeEventListener('pointerup', up);
  2481. isDragging = false;
  2482. setDragGuides(null, null);
  2483. if (moved) {
  2484. commit();
  2485. const xIn = els.propsBody.querySelector('[data-prop="x"]');
  2486. const yIn = els.propsBody.querySelector('[data-prop="y"]');
  2487. if (xIn) xIn.value = mm(el.x);
  2488. if (yIn) yIn.value = mm(el.y);
  2489. renderTool();
  2490. }
  2491. }
  2492. document.addEventListener('pointermove', move);
  2493. document.addEventListener('pointerup', up);
  2494. e.preventDefault();
  2495. }
  2496. function startTransform(e, svg, handle) {
  2497. const el = selectedEl();
  2498. if (!el) return;
  2499. isDragging = true;
  2500. const box = R.elementBox(el);
  2501. const start = svgPoint(e, svg);
  2502. const orig = {
  2503. x: el.x, y: el.y, w: el.w, h: el.h, size: el.size || 0,
  2504. rotation: el.rotation || 0, cx: el.x + box.w / 2, cy: el.y + box.h / 2
  2505. };
  2506. const s = size();
  2507. const rot = orig.rotation * Math.PI / 180;
  2508. let moved = false;
  2509. function move(ev) {
  2510. const p = svgPoint(ev, els.canvasStage.querySelector('svg'));
  2511. const dx = p.x - start.x;
  2512. const dy = p.y - start.y;
  2513. moved = true;
  2514. if (handle === 'rot') {
  2515. const ang = Math.atan2(p.y - orig.cy, p.x - orig.cx) * 180 / Math.PI;
  2516. let next = ang - Math.atan2(start.y - orig.cy, start.x - orig.cx) * 180 / Math.PI + orig.rotation;
  2517. if (ev.shiftKey) next = Math.round(next / 15) * 15;
  2518. el.rotation = next;
  2519. setElementTransform(el);
  2520. return;
  2521. }
  2522. const lx = dx * Math.cos(rot) + dy * Math.sin(rot);
  2523. const ly = -dx * Math.sin(rot) + dy * Math.cos(rot);
  2524. if (el.type === 'text' && (handle === 'w' || handle === 'e')) {
  2525. const nw = Math.max(4, orig.w + (handle === 'e' ? lx : -lx));
  2526. el.w = nw;
  2527. if (handle === 'w') el.x = orig.x + (orig.w - nw);
  2528. renderCanvas();
  2529. return;
  2530. }
  2531. if (el.type === 'text') {
  2532. const factor = clamp((orig.w + (handle === 'w' || handle === 'nw' || handle === 'sw' ? -lx : lx)) / Math.max(4, orig.w), 0.2, 6);
  2533. el.w = Math.max(4, orig.w * factor);
  2534. el.size = Math.max(2, orig.size * factor);
  2535. if (handle === 'w' || handle === 'nw' || handle === 'sw') el.x = orig.x + orig.w - el.w;
  2536. renderCanvas();
  2537. return;
  2538. }
  2539. let nw = orig.w;
  2540. let nh = orig.h;
  2541. let nx = orig.x;
  2542. let ny = orig.y;
  2543. if (handle === 'e' || handle === 'ne' || handle === 'se') nw = orig.w + lx;
  2544. if (handle === 'w' || handle === 'nw' || handle === 'sw') { nw = orig.w - lx; nx = orig.x + lx; }
  2545. if (handle === 's' || handle === 'se' || handle === 'sw') nh = orig.h + ly;
  2546. if (handle === 'n' || handle === 'ne' || handle === 'nw') { nh = orig.h - ly; ny = orig.y + ly; }
  2547. nw = Math.max(3, nw);
  2548. nh = Math.max(3, nh);
  2549. if (ev.shiftKey && (handle === 'nw' || handle === 'ne' || handle === 'sw' || handle === 'se')) {
  2550. const aspect = orig.w / Math.max(0.1, orig.h);
  2551. if (nw / nh > aspect) nw = nh * aspect; else nh = nw / aspect;
  2552. if (handle === 'nw' || handle === 'sw') nx = orig.x + orig.w - nw;
  2553. if (handle === 'nw' || handle === 'ne') ny = orig.y + orig.h - nh;
  2554. }
  2555. if (el.type === 'sticker' || el.type === 'badge') {
  2556. nh = nw;
  2557. if (handle === 'nw' || handle === 'ne') ny = orig.y + orig.h - nh;
  2558. }
  2559. if (el.type === 'shape' && el.shape === 'line') nh = Math.max(3, orig.h);
  2560. el.w = nw;
  2561. if (el.type !== 'badge') el.h = nh;
  2562. el.x = nx;
  2563. el.y = ny;
  2564. renderCanvas();
  2565. }
  2566. function up() {
  2567. document.removeEventListener('pointermove', move);
  2568. document.removeEventListener('pointerup', up);
  2569. isDragging = false;
  2570. if (moved) {
  2571. commit();
  2572. renderProps();
  2573. renderTool();
  2574. }
  2575. }
  2576. document.addEventListener('pointermove', move);
  2577. document.addEventListener('pointerup', up);
  2578. e.preventDefault();
  2579. e.stopPropagation();
  2580. }
  2581. function bindKeys() {
  2582. // 图层面板拖拽排序(按住行上下拖,松手落位;兼容 pointer / mouse / 合成拖拽)
  2583. let layerDrag = null;
  2584. function layerDragStart(row, e) {
  2585. if (!row || !row.dataset.layerId || layerDrag) return;
  2586. if (e.target && e.target.closest && e.target.closest('button')) return;
  2587. layerDrag = { id: row.dataset.layerId, row: row, startY: e.clientY, moved: false, target: null };
  2588. }
  2589. function layerDragMoveListen(e) {
  2590. if (!layerDrag && (e.buttons & 1) === 1) {
  2591. const row = e.target.closest && e.target.closest('.layer-row');
  2592. layerDragStart(row, e);
  2593. }
  2594. if (!layerDrag) return;
  2595. if (!layerDrag.moved && Math.abs(e.clientY - layerDrag.startY) <= 4) return;
  2596. if (!layerDrag.moved) layerDrag.row.classList.add('dragging');
  2597. layerDrag.moved = true;
  2598. if (e.cancelable) e.preventDefault();
  2599. const list = document.querySelector('.layer-list');
  2600. if (!list) return;
  2601. const rows = [...list.querySelectorAll('.layer-row')];
  2602. rows.forEach(function (r) { r.classList.remove('drop-above', 'drop-below'); });
  2603. let target = null;
  2604. for (let i = 0; i < rows.length; i += 1) {
  2605. const r = rows[i];
  2606. if (r === layerDrag.row || !r.dataset.layerId) continue;
  2607. const rc = r.getBoundingClientRect();
  2608. if (e.clientY >= rc.top && e.clientY <= rc.bottom) {
  2609. target = { row: r, above: e.clientY < rc.top + rc.height / 2 };
  2610. break;
  2611. }
  2612. }
  2613. if (target) target.row.classList.add(target.above ? 'drop-above' : 'drop-below');
  2614. // 即时落位:跨过插入线立即排序(无需等待松手)
  2615. const tid = target ? target.row.dataset.layerId : null;
  2616. if (target && (layerDrag.lastTargetId !== tid || layerDrag.lastAbove !== target.above)) {
  2617. layerDrag.lastTargetId = tid;
  2618. layerDrag.lastAbove = target.above;
  2619. reorderElement(layerDrag.id, tid, target.above);
  2620. layerDragCleanupS();
  2621. layerDrag.row = document.querySelector('.layer-row[data-layer-id="' + layerDrag.id + '"]');
  2622. } else if (!target) {
  2623. layerDrag.lastTargetId = null;
  2624. }
  2625. }
  2626. function layerDragEndListen() {
  2627. if (!layerDrag) return;
  2628. layerDrag = null;
  2629. document.querySelectorAll('.layer-row').forEach(function (r) {
  2630. r.classList.remove('dragging', 'drop-above', 'drop-below');
  2631. });
  2632. }
  2633. function layerDragCleanupS() {
  2634. document.querySelectorAll('.layer-row').forEach(function (r) {
  2635. r.classList.remove('dragging', 'drop-above', 'drop-below');
  2636. });
  2637. }
  2638. document.addEventListener('pointerdown', function (e) {
  2639. if (layerDrag) { layerDragCleanupS(); layerDrag = null; }
  2640. const row = e.target.closest && e.target.closest('.layer-row');
  2641. layerDragStart(row, e);
  2642. });
  2643. document.addEventListener('mousedown', function (e) {
  2644. if (layerDrag) { layerDragCleanupS(); layerDrag = null; }
  2645. const row = e.target.closest && e.target.closest('.layer-row');
  2646. layerDragStart(row, e);
  2647. });
  2648. document.addEventListener('pointermove', layerDragMoveListen, { passive: false });
  2649. document.addEventListener('mousemove', layerDragMoveListen, { passive: false });
  2650. document.addEventListener('pointerup', layerDragEndListen);
  2651. document.addEventListener('mouseup', layerDragEndListen);
  2652. // AI 排版悬浮入口
  2653. const aiFab = document.createElement('button');
  2654. aiFab.id = 'plAiFab';
  2655. aiFab.type = 'button';
  2656. aiFab.title = 'AI 排版(登录后可用)';
  2657. aiFab.innerHTML = '✨<span>AI 排版</span>';
  2658. document.body.appendChild(aiFab);
  2659. aiFab.addEventListener('click', function () { aiPanelToggle(); });
  2660. document.addEventListener('keydown', function (e) {
  2661. const tag = (document.activeElement && document.activeElement.tagName) || '';
  2662. const typing = tag === 'INPUT' || tag === 'TEXTAREA' || tag === 'SELECT' || document.activeElement.isContentEditable;
  2663. if (e.key === 'Escape') {
  2664. if (!els.modal3d.hidden) { close3d(); return; }
  2665. hideInlineText();
  2666. selectedId = null;
  2667. if (mode === 'design') { renderCanvas(); renderProps(); renderTool(); }
  2668. return;
  2669. }
  2670. if (typing && !((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === 's')) return;
  2671. if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === 'z') {
  2672. e.preventDefault();
  2673. if (e.shiftKey) doRedo(); else doUndo();
  2674. return;
  2675. }
  2676. if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === 's') {
  2677. e.preventDefault();
  2678. saveState();
  2679. toast('设计已保存到本地');
  2680. return;
  2681. }
  2682. if (mode !== 'design') return;
  2683. if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === 'd') {
  2684. e.preventDefault();
  2685. duplicateElement();
  2686. return;
  2687. }
  2688. if (e.key === 'Delete' || e.key === 'Backspace') {
  2689. if (selectedId) { e.preventDefault(); deleteElement(); }
  2690. return;
  2691. }
  2692. if (e.key.indexOf('Arrow') === 0 && selectedId) {
  2693. e.preventDefault();
  2694. const el = selectedEl();
  2695. if (!el) return;
  2696. const step = e.shiftKey ? 10 : 1;
  2697. if (e.key === 'ArrowLeft') el.x -= step;
  2698. if (e.key === 'ArrowRight') el.x += step;
  2699. if (e.key === 'ArrowUp') el.y -= step;
  2700. if (e.key === 'ArrowDown') el.y += step;
  2701. saveState();
  2702. renderCanvas();
  2703. const xIn = els.propsBody.querySelector('[data-prop="x"]');
  2704. const yIn = els.propsBody.querySelector('[data-prop="y"]');
  2705. if (xIn) xIn.value = mm(el.x);
  2706. if (yIn) yIn.value = mm(el.y);
  2707. return;
  2708. }
  2709. if (e.key === 'Enter' && selectedId) {
  2710. const el = selectedEl();
  2711. if (el && el.type === 'text') { e.preventDefault(); openInlineText(el); }
  2712. }
  2713. });
  2714. document.addEventListener('paste', function (e) {
  2715. if (mode !== 'design') return;
  2716. const items = e.clipboardData && e.clipboardData.items;
  2717. if (!items) return;
  2718. for (let i = 0; i < items.length; i += 1) {
  2719. if (items[i].type.indexOf('image') === 0) {
  2720. const file = items[i].getAsFile();
  2721. if (file) { addUploadedFile(file); e.preventDefault(); break; }
  2722. }
  2723. }
  2724. });
  2725. let resizeTimer;
  2726. window.addEventListener('resize', function () {
  2727. clearTimeout(resizeTimer);
  2728. resizeTimer = setTimeout(function () {
  2729. if (mode === 'design' && !isDragging) renderCanvas();
  2730. if (!els.modal3d.hidden) render3d();
  2731. }, 160);
  2732. });
  2733. }
  2734. function initFromURL() {
  2735. const params = new URLSearchParams(location.search);
  2736. const templateId = params.get('template');
  2737. const productId = params.get('product');
  2738. const toolParam = params.get('tool');
  2739. const modeParam = params.get('mode');
  2740. if (templateId) {
  2741. const t = D.templateById(templateId);
  2742. if (t) {
  2743. state.productId = t.product;
  2744. const p = product();
  2745. state.sizeId = p.sizes[Math.floor((p.sizes.length - 1) / 2)].id;
  2746. state.sampleApplied = true;
  2747. applyTemplate(templateId, { silent: true });
  2748. state.name = t.name + ' 设计';
  2749. els.designName.value = state.name;
  2750. mode = 'design';
  2751. skipSample = true;
  2752. return;
  2753. }
  2754. }
  2755. if (productId) {
  2756. const p = D.productById(productId);
  2757. if (p) {
  2758. const oldS = size();
  2759. const oldP = product();
  2760. const newS = D.sizeOf(p, p.sizes[Math.floor((p.sizes.length - 1) / 2)].id);
  2761. if (p.id !== oldP.id) {
  2762. if (state.sides.front.elements.length || state.sides.back.elements.length) scaleSides(oldS, newS);
  2763. state.productId = p.id;
  2764. state.sizeId = newS.id;
  2765. state.bagColor = null;
  2766. }
  2767. }
  2768. }
  2769. if (toolParam) {
  2770. tool = ['product', 'templates', 'upload', 'text', 'shapes', 'layers'].indexOf(toolParam) >= 0 ? toolParam : 'product';
  2771. mode = 'design';
  2772. skipSample = toolParam === 'upload';
  2773. return;
  2774. }
  2775. if (modeParam && ['settings', 'design', 'summary'].indexOf(modeParam) >= 0) {
  2776. mode = modeParam;
  2777. return;
  2778. }
  2779. mode = 'settings';
  2780. }
  2781. function init() {
  2782. els.designName.value = state.name;
  2783. initFromURL();
  2784. if (mode === 'design' && !state.sampleApplied && !skipSample) ensureSample();
  2785. history = [snapshot()];
  2786. hIndex = 0;
  2787. bindSettings();
  2788. bindTopbar();
  2789. bindDesign();
  2790. bindKeys();
  2791. renderSettings();
  2792. if (mode === 'design') {
  2793. setMode('design');
  2794. } else if (mode === 'summary') {
  2795. setMode('summary');
  2796. } else {
  2797. setMode('settings');
  2798. }
  2799. updateMeta();
  2800. saveState(true);
  2801. }
  2802. init();
  2803. })();