studio.js 132 KB

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