| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299 |
- (function () {
- const D = window.PL.data;
- const R = window.PL.render;
- const UI = window.PL.ui;
- const h = UI.h;
- const A = UI.antd;
- const KEY = 'pouchlab.design.v1';
- const PLANS_KEY = 'pouchlab.bag.plans.v1';
- const $ = function (s, root) { return (root || document).querySelector(s); };
- const $$ = function (s, root) { return Array.prototype.slice.call((root || document).querySelectorAll(s)); };
- const sampleMap = { standup: 'citrus', flatbottom: 'glow', coffee: 'morning', kraft: 'sunday', mailer: 'noir', garment: 'bloom' };
- const bagPalette = ['#efe7d6', '#171513', '#f4eee3', '#c49a68', '#8a9f76', '#ff7a45', '#bfe3f2', '#d9f07c'];
- function defaults() {
- return {
- version: 1,
- name: '未命名设计',
- productId: 'standup',
- sizeId: 'm',
- customSize: { w: 140, h: 210 },
- material: 'matte',
- finish: 'none',
- qty: 100,
- bagColor: null,
- sides: { front: { bg: null, elements: [] }, back: { bg: null, elements: [] } },
- uploads: [],
- sampleApplied: false
- };
- }
- let state = defaults();
- try {
- const saved = JSON.parse(localStorage.getItem(KEY) || 'null');
- if (saved && saved.sides) state = Object.assign(defaults(), saved);
- } catch (e) {}
- if (!state.sides.front) state.sides.front = { bg: null, elements: [] };
- if (!state.sides.back) state.sides.back = { bg: null, elements: [] };
- if (!Array.isArray(state.uploads)) state.uploads = [];
- if (!state.customSize || !state.customSize.w || !state.customSize.h) {
- const savedSize = D.sizeOf(D.productById(state.productId), state.sizeId);
- state.customSize = { w: savedSize.w, h: savedSize.h };
- }
- let plans = [];
- try {
- const savedPlans = JSON.parse(localStorage.getItem(PLANS_KEY) || '[]');
- if (Array.isArray(savedPlans)) plans = savedPlans.filter(function (p) { return p && p.id && p.snap; });
- } catch (e) { plans = []; }
- let planName = state.name;
- /* AI 设计师(首页 Agent)交接:应用其生成的袋子方案 */
- (function applyAgentHandoff() {
- try {
- const raw = localStorage.getItem('pouchlab.agent.handoff');
- if (!raw) return;
- const h = JSON.parse(raw);
- localStorage.removeItem('pouchlab.agent.handoff');
- const s = h && h.state;
- if (!s || s.kind !== 'bag' || !s.bag) return;
- const b = s.bag;
- if (b.productId && D.productById(b.productId)) {
- state.productId = b.productId;
- state.sizeId = 'custom';
- }
- if (b.customSize && b.customSize.w) {
- state.customSize = { w: b.customSize.w, h: b.customSize.h };
- state.sizeId = 'custom';
- }
- if (b.material) state.material = b.material;
- if (b.finish) state.finish = b.finish;
- if (b.qty) state.qty = b.qty;
- ['front', 'back'].forEach(function (k) {
- const d = (b.design || {})[k];
- if (d && (d.elements || []).length) {
- state.sides[k] = {
- bg: d.bg || null,
- elements: d.elements.map(function (el) {
- el.id = R.uid('el');
- el.opacity = el.opacity == null ? 1 : el.opacity;
- return el;
- })
- };
- }
- });
- setTimeout(function () { toast('已载入 AI 设计师方案,可继续微调'); }, 600);
- } catch (e) {}
- })();
- let mode = 'settings';
- let tool = 'product';
- let activeSide = 'front';
- let selectedId = null;
- let zoom = 1;
- let summarySide = 'front';
- let showGuides = true;
- let lastFont = 'sans';
- let history = [];
- let hIndex = -1;
- let dragGuides = null;
- let inlineTarget = null;
- let saveTimer = null;
- let renderFrame = null;
- let three = { rot: -18, side: 'front', modelMode: null };
- let isDragging = false;
- const els = {
- settingsView: $('#settingsView'),
- designView: $('#designView'),
- summaryView: $('#summaryView'),
- settingsColors: $('#settingsColors'),
- settingsPreview: $('#settingsPreview'),
- settingsPreviewNote: $('#settingsPreviewNote'),
- studioSteps: $('#studioSteps'),
- saveState: $('#saveState'),
- undoBtn: $('#undoBtn'),
- redoBtn: $('#redoBtn'),
- continueBtn: $('#continueBtn'),
- designName: $('#designName'),
- designMeta: $('#designMeta'),
- toolRail: $('#toolRail'),
- toolKicker: $('#toolKicker'),
- toolTitle: $('#toolTitle'),
- toolDesc: $('#toolDesc'),
- toolBody: $('#toolBody'),
- sideSwitch: $('#sideSwitch'),
- guidesToggle: $('#guidesToggle'),
- zoomLabel: $('#zoomLabel'),
- canvasShell: $('#canvasShell'),
- canvasStage: $('#canvasStage'),
- canvasEmpty: $('#canvasEmpty'),
- printInfo: $('#printInfo'),
- elementCount: $('#elementCount'),
- propsChip: $('#propsChip'),
- propsBody: $('#propsBody'),
- propsClose: $('#propsClose'),
- summaryPreview: $('#summaryPreview'),
- summaryThumbs: $('#summaryThumbs'),
- summaryOrder: $('#summaryOrder'),
- summarySideSwitch: $('#summarySideSwitch'),
- modal3d: $('#modal3d'),
- pouch3d: $('#pouch3d'),
- faceFront: $('#faceFront'),
- faceBack: $('#faceBack'),
- faceSide: $('#faceSide'),
- faceSideLeft: $('#faceSideLeft'),
- rotateRange: $('#rotateRange'),
- previewSideSwitch: $('#previewSideSwitch'),
- inlineText: $('#inlineText'),
- inlineTextArea: $('#inlineTextArea'),
- inlineTextDone: $('#inlineTextDone'),
- successView: $('#successView'),
- orderNumber: $('#orderNumber'),
- toast: $('#toast'),
- toastText: $('#toastText')
- };
- function product() { return D.productById(state.productId); }
- function size() {
- if (D.resolveSize) return D.resolveSize(product(), state);
- return D.sizeOf(product(), state.sizeId);
- }
- function renderProduct() {
- const p = product();
- return state.bagColor ? Object.assign({}, p, { mockColor: state.bagColor }) : p;
- }
- function sideData(side) { return state.sides[side || activeSide]; }
- function selectedEl() {
- return sideData().elements.find(function (e) { return e.id === selectedId; }) || null;
- }
- function allElements() {
- return sideData().elements;
- }
- function esc(s) { return R.esc(s); }
- function num(v, fallback) {
- const n = parseFloat(v);
- return isNaN(n) ? fallback : n;
- }
- function clamp(v, min, max) { return Math.min(max, Math.max(min, v)); }
- function mm(v) { return (Math.round(v * 10) / 10).toString(); }
- function inputVal(v) { return v && v.target && 'value' in v.target ? v.target.value : v; }
- function InlineNumber(props) {
- const [val, setVal] = React.useState(String(props.value));
- React.useEffect(function () { setVal(String(props.value)); }, [props.value]);
- return h('input', {
- type: 'number',
- min: props.min,
- max: props.max,
- step: props.step || 1,
- className: 's-inline-input',
- value: val,
- onChange: function (e) {
- setVal(e.target.value);
- if (props.onInput) props.onInput(e.target.value);
- },
- onBlur: function (e) { if (props.onCommit) props.onCommit(e.target.value); },
- onKeyDown: function (e) { if (e.key === 'Enter') e.currentTarget.blur(); }
- });
- }
- function TextField(props) {
- const [val, setVal] = React.useState(props.value == null ? '' : String(props.value));
- React.useEffect(function () { setVal(props.value == null ? '' : String(props.value)); }, [props.value]);
- const Comp = props.multiline ? A.Input.TextArea : A.Input;
- return h(Comp, Object.assign({}, props.extra || {}, {
- value: val,
- placeholder: props.placeholder,
- onChange: function (e) {
- const v = inputVal(e);
- setVal(v);
- if (props.onInput) props.onInput(v);
- },
- onBlur: function () { if (props.onCommit) props.onCommit(); }
- }));
- }
- function toast(msg, kind) {
- if (window.PL && PL.ui && PL.ui.message) {
- if (kind === 'warn') PL.ui.message.warning(msg);
- else PL.ui.message.success(msg);
- return;
- }
- els.toastText.textContent = msg;
- els.toast.classList.add('show');
- clearTimeout(toast.timer);
- toast.timer = setTimeout(function () { els.toast.classList.remove('show'); }, 2600);
- }
- function snapshot() {
- return JSON.stringify({
- name: state.name, productId: state.productId, sizeId: state.sizeId, customSize: state.customSize,
- material: state.material, finish: state.finish, qty: state.qty,
- bagColor: state.bagColor, sides: state.sides, sampleApplied: state.sampleApplied
- });
- }
- function applySnapshot(str) {
- const s = JSON.parse(str);
- state.name = s.name;
- state.productId = s.productId;
- state.sizeId = s.sizeId;
- state.customSize = s.customSize || state.customSize;
- state.material = s.material;
- state.finish = s.finish;
- state.qty = s.qty;
- state.bagColor = s.bagColor;
- state.sides = s.sides;
- state.sampleApplied = s.sampleApplied;
- selectedId = null;
- }
- function persistPlans() {
- try {
- localStorage.setItem(PLANS_KEY, JSON.stringify(plans));
- return true;
- } catch (e) {
- toast('本地空间不足,请先删除旧方案');
- return false;
- }
- }
- function planThumb(plan) {
- try {
- const s = JSON.parse(plan.snap);
- const prod = D.productById(s.productId);
- const size = s.sizeId === 'custom' && s.customSize
- ? { id: 'custom', label: '自定义', w: s.customSize.w, h: s.customSize.h }
- : D.sizeOf(prod, s.sizeId);
- const design = (s.sides && s.sides.front) || { bg: null, elements: [] };
- return R.bagSVG(prod, 'front', design, { size: size, card: true, material: s.material, finish: s.finish });
- } catch (e) {
- return '';
- }
- }
- function savePlan() {
- const name = (planName || state.name || '未命名方案').trim().slice(0, 30) || '未命名方案';
- const plan = { id: R.uid('plan'), name: name, savedAt: Date.now(), snap: snapshot() };
- const same = plans.findIndex(function (p) { return p.name === name; });
- if (same >= 0) plan.id = plans[same].id;
- plans = plans.filter(function (p) { return p.name !== name; });
- plans.unshift(plan);
- if (plans.length > 12) plans = plans.slice(0, 12);
- if (!persistPlans()) return;
- state.name = name;
- planName = name;
- if (els.designName) els.designName.value = name;
- updateMeta();
- renderTool();
- toast('方案已保存 · ' + name);
- }
- function loadPlan(id) {
- const plan = plans.find(function (p) { return p.id === id; });
- if (!plan) return;
- try {
- applySnapshot(plan.snap);
- } catch (e) {
- toast('方案数据已损坏');
- return;
- }
- state.name = plan.name;
- planName = plan.name;
- if (els.designName) els.designName.value = plan.name;
- selectedId = null;
- commit();
- if (mode === 'design') renderDesign();
- else renderSettings();
- toast('已载入方案 · ' + plan.name);
- }
- function removePlan(id) {
- plans = plans.filter(function (p) { return p.id !== id; });
- if (!persistPlans()) return;
- renderTool();
- toast('方案已删除');
- }
- function pushHistory() {
- const snap = snapshot();
- if (history[hIndex] === snap) return;
- history = history.slice(0, hIndex + 1);
- history.push(snap);
- if (history.length > 70) history.shift();
- hIndex = history.length - 1;
- updateUndoButtons();
- }
- function updateUndoButtons() {
- els.undoBtn.disabled = hIndex <= 0;
- els.redoBtn.disabled = hIndex >= history.length - 1;
- }
- let stateDirty = false;
- let stateSaveTimer = null;
- function writeStateNow(silent) {
- try {
- const payload = {
- version: 1, name: state.name, productId: state.productId, sizeId: state.sizeId, customSize: state.customSize,
- material: state.material, finish: state.finish, qty: state.qty, bagColor: state.bagColor,
- sides: state.sides, uploads: state.uploads.slice(0, 12), sampleApplied: state.sampleApplied,
- savedAt: Date.now()
- };
- localStorage.setItem(KEY, JSON.stringify(payload));
- if (!silent) {
- els.saveState.classList.add('saving');
- els.saveState.querySelector('span').textContent = '保存中…';
- clearTimeout(saveTimer);
- saveTimer = setTimeout(function () {
- els.saveState.classList.remove('saving');
- const d = new Date();
- els.saveState.querySelector('span').textContent = '已保存 ' + String(d.getHours()).padStart(2, '0') + ':' + String(d.getMinutes()).padStart(2, '0');
- }, 420);
- }
- } catch (e) {
- toast('本地存储空间不足,建议下载效果图备份');
- }
- }
- // 合并短时间内的多次保存,避免大图 dataURL 同步写 localStorage 卡住删除/拖动
- function saveState(silent) {
- stateDirty = true;
- clearTimeout(stateSaveTimer);
- stateSaveTimer = setTimeout(function () {
- if (!stateDirty) return;
- stateDirty = false;
- writeStateNow(silent);
- }, 160);
- }
- function flushStateSave() {
- if (!stateDirty) return;
- clearTimeout(stateSaveTimer);
- stateDirty = false;
- writeStateNow(true);
- }
- window.addEventListener('beforeunload', flushStateSave);
- window.addEventListener('pagehide', flushStateSave);
- function commit(message) {
- pushHistory();
- saveState();
- updateMeta();
- if (message) toast(message);
- }
- function updateMeta() {
- const p = product();
- const s = size();
- const price = D.price(state);
- const sizeLabel = state.sizeId === 'custom' ? s.w + '×' + s.h + ' mm' : s.label;
- els.designMeta.textContent = p.name + ' · ' + sizeLabel + ' · ' + state.qty + ' 个';
- if (mode === 'settings') els.continueBtn.innerHTML = '开始设计 →';
- else if (mode === 'design') els.continueBtn.innerHTML = '下一步 · ¥' + price.total.toFixed(2);
- else els.continueBtn.innerHTML = '提交订单 · ¥' + price.total.toFixed(2);
- els.studioSteps.querySelectorAll('.step').forEach(function (btn) {
- const step = btn.dataset.step;
- btn.classList.toggle('active', step === mode);
- const order = ['settings', 'design', 'summary'];
- btn.classList.toggle('done', order.indexOf(step) < order.indexOf(mode));
- });
- els.undoBtn.disabled = hIndex <= 0;
- els.redoBtn.disabled = hIndex >= history.length - 1;
- document.title = state.name + ' — Steady Packaging';
- }
- function priceLines() {
- const price = D.price(state);
- return [
- ['袋型', price.product.name],
- ['尺寸', price.size.label + ' · ' + price.size.w + '×' + price.size.h + ' mm'],
- ['材质', price.material.name],
- ['工艺', price.finish.name],
- ['数量', price.quantity.value + ' 个'],
- ['单价', '¥' + price.unit.toFixed(2) + ' / 个']
- ];
- }
- function sampleDesignFor(p, w, h) {
- const t = D.templateById(sampleMap[p.id] || 'citrus');
- return { template: t, design: R.designFromTemplate(t.id, w, h, 'front') };
- }
- function currentPreviewDesign() {
- const s = size();
- if (sideData('front').elements.length) return sideData('front');
- return sampleDesignFor(product(), s.w, s.h).design;
- }
- function renderSettings() {
- const p = product();
- const s = size();
- const price = D.price(state);
- const productCards = D.products.map(function (item) {
- const smp = sampleDesignFor(item, item.sizes[0].w, item.sizes[0].h);
- const svg = R.bagSVG(item, 'front', smp.design, { size: item.sizes[0], card: true });
- return h(A.Card, {
- key: item.id,
- hoverable: true,
- bordered: false,
- className: 's-choice' + (item.id === state.productId ? ' on' : ''),
- onClick: function () { changeProduct(item.id); }
- },
- h('div', { className: 's-choice-thumb', dangerouslySetInnerHTML: { __html: svg } }),
- h('div', { className: 's-choice-name' }, h('b', null, item.name), h('em', null, item.en))
- );
- });
- const sizeRadios = p.sizes.map(function (item) {
- const unit = D.price(Object.assign({}, state, { sizeId: item.id })).unit;
- return h(A.Radio, { key: item.id, value: item.id }, h('span', { className: 's-size-opt' },
- h('b', null, item.label),
- h('em', null, item.w + '×' + item.h + ' mm'),
- h('i', null, '¥' + unit.toFixed(2))
- ));
- });
- sizeRadios.push(h(A.Radio, { key: 'custom', value: 'custom' }, h('span', { className: 's-size-opt' },
- h('b', null, '自定义'),
- h('em', null, s.w + '×' + s.h + ' mm'),
- h('i', null, '可调尺寸')
- )));
- const sizeInput = function (key, labelText) {
- return h('div', { className: 's-inline-field' },
- h('label', null, labelText),
- h(InlineNumber, {
- value: size()[key],
- min: 30,
- max: key === 'w' ? 1200 : 1600,
- step: 5,
- onInput: function (v) { applyCustomSize(key, v, false); },
- onCommit: function (v) { applyCustomSize(key, v, true); }
- })
- );
- };
- const panel = h('div', { className: 's-panel' },
- h('span', { className: 'step-kicker' }, 'STEP 01 / PRODUCT'),
- h('h1', null, '选择你的袋子'),
- h('p', null, '袋型、尺寸、材质与数量都会影响最终报价。'),
- h('div', { className: 's-field' },
- h('div', { className: 's-label' }, '袋型', h('span', null, '6 种可选')),
- h('div', { className: 's-choices' }, productCards)
- ),
- h('div', { className: 's-field' },
- h('div', { className: 's-label' }, '尺寸', h('span', null, s.w + ' × ' + s.h + ' mm')),
- h(A.Radio.Group, { className: 's-size-group', value: state.sizeId, onChange: function (e) { changeSize(e.target.value); } }, sizeRadios),
- h('div', { className: 's-custom-size' + (state.sizeId === 'custom' ? ' on' : '') },
- h('div', { className: 's-custom-title' }, '自定义尺寸', h('span', null, 'mm')),
- h('div', { className: 's-custom-inputs' }, sizeInput('w', '宽'), h('span', { className: 's-times' }, '×'), sizeInput('h', '高')),
- h('div', { className: 'p-hint' }, '宽 30–1200 mm,高 30–1600 mm,按面积计价。')
- )
- ),
- h('div', { className: 's-field' },
- h('div', { className: 's-label' }, '材质与工艺'),
- h('div', { className: 's-two' },
- h('div', null, h('label', null, '材质'), h(A.Select, {
- value: state.material,
- onChange: function (v) { changeSetting('material', v); },
- options: D.materials.map(function (m) { return { value: m.id, label: m.name }; })
- })),
- h('div', null, h('label', null, '工艺'), h(A.Select, {
- value: state.finish,
- onChange: function (v) { changeSetting('finish', v); },
- options: D.finishes.map(function (f) { return { value: f.id, label: f.name }; })
- }))
- )
- ),
- h('div', { className: 's-field' },
- h('div', { className: 's-label' }, '数量', h('span', null, '100 个起订')),
- h(A.Radio.Group, {
- className: 's-qty-group',
- optionType: 'button',
- buttonStyle: 'solid',
- value: String(state.qty),
- onChange: function (e) { changeSetting('qty', e.target.value); },
- options: D.quantities.map(function (q) { return { label: String(q.value), value: String(q.value) }; })
- }),
- h('div', { className: 's-qty-custom' },
- h('label', null, '自定义数量'),
- h(InlineNumber, {
- value: state.qty,
- min: 100,
- max: 100000,
- step: 50,
- onInput: function (v) { setQty(v, false); },
- onCommit: function (v) { setQty(v, true); }
- }),
- h('span', null, '个 · 100 起订')
- )
- ),
- h('div', { className: 's-link' },
- '需要纸盒?',
- h('a', { href: 'box.html' }, '打开纸盒设计器 →')
- )
- );
- const order = h('div', { className: 'order-card' },
- h('span', { className: 'eyebrow' }, 'YOUR QUOTE'),
- h('h2', null, '实时报价'),
- h('div', { className: 'order-lines' }, priceLines().map(function (row, i) {
- return h('div', { className: 'order-line', key: i }, h('span', null, row[0]), h('b', null, row[1]));
- })),
- h('div', { className: 'order-total' },
- h('span', null, '预计总价', h('br'), h('small', null, '含税,不含运费')),
- h('b', null, '¥' + price.total.toFixed(2), h('small', null, ' / ' + state.qty + ' 个'))
- ),
- h(A.Button, { type: 'primary', size: 'large', block: true, onClick: enterDesign }, '开始设计 →'),
- h('p', { className: 'micro' }, '免费设计 · 免费刀版 · 不满意随时修改')
- );
- UI.render(document.getElementById('settingsPanel'), panel);
- UI.render(document.getElementById('settingsOrderCard'), order);
- UI.hydrate(document.getElementById('settingsView'));
- els.settingsPreviewNote.textContent = s.w + ' × ' + s.h + ' mm · 正面预览';
- els.settingsPreview.innerHTML = R.bagSVG(renderProduct(), 'front', currentPreviewDesign(), { size: s, card: true, material: state.material, finish: state.finish });
- const colors = [p.mockColor].concat(bagPalette).filter(function (c, i, a) { return a.indexOf(c) === i; });
- els.settingsColors.innerHTML = colors.map(function (c) {
- const on = (state.bagColor || p.mockColor).toLowerCase() === c.toLowerCase();
- return '<button class="color-dot ' + (on ? 'on' : '') + '" data-color="' + c + '" style="background:' + c + '" aria-label="' + c + '"></button>';
- }).join('');
- }
- function scaleSides(oldSize, newSize) {
- const sx = newSize.w / oldSize.w;
- const sy = newSize.h / oldSize.h;
- const sm = Math.min(sx, sy);
- ['front', 'back'].forEach(function (side) {
- sideData(side).elements.forEach(function (el) {
- el.x *= sx;
- el.y *= sy;
- el.w *= sx;
- if (el.h != null) el.h *= sy;
- if (el.type === 'text') {
- el.size *= sm;
- if (el.strokeWidth) el.strokeWidth *= sm;
- }
- if (el.type === 'badge') {
- el.size *= sm;
- el.h = el.w;
- }
- if (el.type === 'sticker') el.h = el.w;
- if (el.strokeWidth) el.strokeWidth *= sm;
- if (el.radius) el.radius *= sm;
- });
- });
- }
- function changeProduct(id) {
- const oldP = product();
- const oldS = size();
- const newP = D.productById(id);
- if (newP.id === oldP.id) return;
- const newS = D.sizeOf(newP, newP.sizes[Math.floor(newP.sizes.length / 2)].id);
- const hasElements = state.sides.front.elements.length || state.sides.back.elements.length;
- if (hasElements) scaleSides(oldS, newS);
- state.productId = newP.id;
- state.sizeId = newS.id;
- state.bagColor = null;
- selectedId = null;
- commit();
- renderSettings();
- renderDesign();
- if (mode === 'summary') renderSummary();
- toast(hasElements ? '已切换袋型,设计已等比适配' : '已选择「' + newP.name + '」');
- }
- function changeSize(id) {
- const oldS = size();
- if (id === 'custom') {
- if (state.sizeId !== 'custom') state.customSize = { w: oldS.w, h: oldS.h };
- state.sizeId = 'custom';
- } else {
- if (state.sizeId === id) return;
- state.sizeId = id;
- }
- const newS = size();
- if (newS.w !== oldS.w || newS.h !== oldS.h) scaleSides(oldS, newS);
- selectedId = null;
- commit();
- renderSettings();
- renderDesign();
- if (mode === 'summary') renderSummary();
- }
- function refreshSettingsPreview() {
- if (mode !== 'settings') return;
- const s = size();
- els.settingsPreviewNote.textContent = s.w + ' × ' + s.h + ' mm · 正面预览';
- els.settingsPreview.innerHTML = R.bagSVG(renderProduct(), 'front', currentPreviewDesign(), {
- size: s, card: true, material: state.material, finish: state.finish
- });
- }
- function applyCustomSize(key, raw, commitNow) {
- const p = product();
- const base = D.sizeOf(p, p.sizes[Math.floor(p.sizes.length / 2)].id);
- const oldS = size();
- const dims = {
- w: state.sizeId === 'custom' ? state.customSize.w : oldS.w,
- h: state.sizeId === 'custom' ? state.customSize.h : oldS.h
- };
- const fallback = key === 'w' ? base.w : base.h;
- dims[key] = clamp(Math.round(num(raw, fallback)), 30, key === 'w' ? 1200 : 1600);
- state.customSize = dims;
- state.sizeId = 'custom';
- const newS = size();
- if (newS.w !== oldS.w || newS.h !== oldS.h) scaleSides(oldS, newS);
- updateMeta();
- refreshSettingsPreview();
- if (mode === 'design') scheduleRenderCanvas();
- if (mode === 'summary') renderSummary();
- if (commitNow) {
- commit();
- renderSettings();
- if (mode === 'design') renderTool();
- }
- }
- function setQty(raw, commitNow) {
- const v = clamp(Math.round(num(raw, 100)), 100, 100000);
- if (v === state.qty) {
- if (commitNow) {
- commit();
- renderSettings();
- if (mode === 'design') renderTool();
- }
- return;
- }
- state.qty = v;
- updateMeta();
- if (mode === 'settings') refreshSettingsPreview();
- if (mode === 'summary') renderSummary();
- if (commitNow) {
- commit();
- renderSettings();
- if (mode === 'design') renderTool();
- }
- }
- function changeSetting(key, value) {
- if (key === 'material') state.material = value;
- if (key === 'finish') state.finish = value;
- if (key === 'qty') { setQty(value, true); return; }
- commit();
- renderSettings();
- if (mode === 'design') { renderCanvas(); renderTool(); }
- if (mode === 'summary') renderSummary();
- }
- function changeBagColor(color) {
- state.bagColor = color;
- commit();
- renderSettings();
- renderDesign();
- if (mode === 'summary') renderSummary();
- }
- function applyTemplate(id, opts) {
- const t = D.templateById(id);
- if (!t) return;
- const s = size();
- state.sides.front = R.designFromTemplate(id, s.w, s.h, 'front');
- const back = R.designFromTemplate(id, s.w, s.h, 'back');
- state.sides.back = back;
- state.sampleApplied = true;
- activeSide = 'front';
- selectedId = null;
- commit();
- renderSettings();
- renderDesign();
- if (!opts || !opts.silent) toast('已套用模板「' + t.name + '」· 可撤销');
- }
- function ensureSample() {
- if (state.sampleApplied) return;
- if (state.sides.front.elements.length || state.sides.back.elements.length) return;
- const s = size();
- const t = D.templateById(sampleMap[product().id] || 'citrus');
- state.sides.front = R.designFromTemplate(t.id, s.w, s.h, 'front');
- state.sides.back = R.designFromTemplate(t.id, s.w, s.h, 'back');
- state.sampleApplied = true;
- saveState(true);
- pushHistory();
- }
- function setMode(next) {
- mode = next;
- els.settingsView.hidden = next !== 'settings';
- els.designView.hidden = next !== 'design';
- els.summaryView.hidden = next !== 'summary';
- hideInlineText();
- if (next === 'settings') {
- renderSettings();
- } else if (next === 'design') {
- if (!skipSample) ensureSample();
- skipSample = false;
- renderDesign();
- requestAnimationFrame(function () { renderCanvas(); });
- } else if (next === 'summary') {
- renderSummary();
- }
- updateMeta();
- }
- let skipSample = false;
- function enterDesign() {
- setMode('design');
- }
- function renderDesign() {
- if (mode !== 'design') return;
- els.sideSwitch.querySelectorAll('button').forEach(function (b) {
- b.classList.toggle('on', b.dataset.side === activeSide);
- });
- els.guidesToggle.checked = showGuides;
- const s = size();
- els.printInfo.textContent = '印刷区 ' + s.w + ' × ' + s.h + ' mm';
- renderCanvas();
- renderProps();
- renderTool();
- updateMeta();
- }
- function editorViewBox() {
- const p = product().pad;
- const s = size();
- 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 };
- }
- function computeScale() {
- const vb = editorViewBox();
- const availW = Math.max(220, els.canvasShell.clientWidth - 68);
- const availH = Math.max(220, els.canvasShell.clientHeight - 52);
- const fit = Math.min(availW / vb.w, availH / vb.h);
- return { vb: vb, fit: fit, scale: fit * zoom };
- }
- function renderCanvas() {
- if (mode !== 'design') return;
- if (selectedId && !selectedEl()) selectedId = null;
- const p = renderProduct();
- const s = size();
- const total = state.sides.front.elements.length + state.sides.back.elements.length;
- els.elementCount.textContent = total + ' 个图层';
- els.canvasEmpty.hidden = sideData().elements.length > 0;
- els.printInfo.textContent = '印刷区 ' + s.w + ' × ' + s.h + ' mm';
- const cs = computeScale();
- els.canvasStage.style.width = (cs.vb.w * cs.scale) + 'px';
- els.canvasStage.style.height = (cs.vb.h * cs.scale) + 'px';
- els.zoomLabel.textContent = zoom === 1 ? '适应' : Math.round(zoom * 100) + '%';
- const scrollLeft = els.canvasShell.scrollLeft;
- const scrollTop = els.canvasShell.scrollTop;
- els.canvasStage.innerHTML = R.bagSVG(p, activeSide, sideData(), {
- size: s, ui: true, selectedId: selectedId, showGuides: showGuides,
- showDims: true, pxPerMm: cs.scale, guides: dragGuides,
- material: state.material, finish: state.finish
- });
- els.canvasShell.scrollLeft = scrollLeft;
- els.canvasShell.scrollTop = scrollTop;
- }
- function scheduleRenderCanvas() {
- if (renderFrame) return;
- renderFrame = requestAnimationFrame(function () {
- renderFrame = null;
- renderCanvas();
- });
- }
- function updateZoom(next) {
- zoom = clamp(next, 0.45, 2.6);
- renderCanvas();
- }
- function elementLabel(el) {
- if (el.type === 'text') return (el.text || '文字').slice(0, 16);
- if (el.type === 'image') return el.name || '图片';
- if (el.type === 'shape') return { rect: '矩形', circle: '圆形', triangle: '三角形', line: '线条' }[el.shape] || '图形';
- if (el.type === 'sticker') return '贴纸 · ' + el.sticker;
- if (el.type === 'badge') return '圆形徽章';
- if (el.type === 'barcode') return '条码 · ' + (el.value || '');
- if (el.type === 'qr') return '二维码 · ' + (el.value || '');
- if (el.type === 'asset') return '素材 · ' + (el.name || el.asset || '');
- return '图层';
- }
- function elementIcon(el) {
- const icons = {
- text: '<path d="M5 5h14M12 5v14M8 19h8"/>',
- 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"/>',
- shape: '<rect x="4" y="4" width="16" height="16" rx="3"/>',
- sticker: '<path d="M20 4C11 4 4 9 4 17c0 2 1 3 3 3 8 0 13-7 13-16Z"/>',
- badge: '<circle cx="12" cy="12" r="8" stroke-dasharray="2 2"/><circle cx="12" cy="12" r="3"/>',
- barcode: '<path d="M4 5v14M8 5v14M12 5v10M16 5v14M20 5v14"/>',
- 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"/>',
- 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"/>'
- };
- return '<svg class="icon" viewBox="0 0 24 24">' + (icons[el.type] || icons.shape) + '</svg>';
- }
- function renderTool() {
- const meta = {
- product: ['PRODUCT', '产品设置', '当前袋型、尺寸与印刷信息'],
- templates: ['TEMPLATES', '模板库', '套用后可继续自由修改'],
- upload: ['UPLOAD', '上传素材', '建议使用透明背景 PNG 或 SVG'],
- text: ['TYPOGRAPHY', '文字工具', '标题、正文与字体选择'],
- shapes: ['GRAPHICS', '图形与贴纸', '用图形建立视觉层次'],
- layers: ['LAYERS', '图层管理', '从上到下即前后顺序']
- }[tool] || ['TOOL', '工具', ''];
- els.toolKicker.textContent = meta[0];
- els.toolTitle.textContent = meta[1];
- els.toolDesc.textContent = meta[2];
- els.toolRail.querySelectorAll('button[data-tool]').forEach(function (b) {
- b.classList.toggle('active', b.dataset.tool === tool);
- });
- UI.render(els.toolBody, toolPanelReact());
- }
- 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>' } });
- 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>' } });
- 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>' } });
- function eyeIcon(hidden) {
- return h('span', {
- dangerouslySetInnerHTML: {
- __html: hidden
- ? '<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>'
- : '<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>'
- }
- });
- }
- function applyFont(key) {
- const el = selectedEl();
- if (el && el.type === 'text') {
- el.font = key;
- lastFont = key;
- commit();
- renderCanvas();
- renderProps();
- return;
- }
- addTextPreset('body', key);
- }
- function toolPanelReact() {
- if (tool === 'templates') {
- return h('div', null,
- h('div', { className: 'p-hint', style: { marginBottom: '12px' } }, '点击套用 · 会覆盖当前画布,可用撤销恢复。'),
- h('div', { className: 'tpl-grid' }, D.templates.map(function (t) {
- return h(A.Card, {
- key: t.id,
- hoverable: true,
- bordered: false,
- className: 'tpl-card',
- bodyStyle: { padding: 0 },
- onClick: function () { applyTemplate(t.id); }
- },
- h('div', { className: 'tpl-thumb', style: { background: t.tint }, dangerouslySetInnerHTML: { __html: R.templatePreview(t) } }),
- h('div', { className: 'tpl-name' }, t.name, h(A.Tag, { bordered: false, className: 'tpl-tag' }, t.category))
- );
- }))
- );
- }
- if (tool === 'upload') {
- return h('div', null,
- h('div', { className: 'tool-section' },
- h('div', { className: 'tool-section-title' }, '上传素材'),
- h(A.Upload.Dragger, {
- accept: 'image/*',
- showUploadList: false,
- customRequest: function (options) { addUploadedFile(options.file); },
- children: h('div', { className: 'upload-zone' },
- h('div', { className: 'icon-box' }, h('span', { className: 'icon', style: { width: '18px', height: '18px' } })),
- h('b', null, '点击上传,或拖入图片'),
- h('span', null, 'PNG · JPG · SVG · 建议 ≥ 1000px')
- )
- })
- ),
- state.uploads.length ? h('div', { className: 'tool-section' },
- h('div', { className: 'tool-section-title' }, '最近上传', h('span', null, state.uploads.length + '')),
- h('div', { className: 'uploaded-grid' }, state.uploads.map(function (up) {
- return h('div', {
- className: 'uploaded-item', key: up.id, title: '点击放置到画布',
- onClick: function (e) {
- if (e.target.closest('button')) return;
- addImageFromUpload(up);
- }
- },
- h('img', { src: up.src, alt: up.name }),
- h('button', {
- onClick: function (e) {
- e.stopPropagation();
- state.uploads = state.uploads.filter(function (x) { return x.id !== up.id; });
- commit();
- renderTool();
- }
- }, '✕')
- );
- }))
- ) : null,
- h('div', { className: 'tool-section' },
- h('div', { className: 'tool-section-title' }, '使用建议'),
- h('div', { className: 'p-hint' }, 'Logo 请使用 1 色或透明背景 PNG;图片会自动等比缩放。上传后可在右侧属性面板调整「填满 / 完整显示」与单色印刷。')
- )
- );
- }
- if (tool === 'text') {
- const presets = [
- { id: 'title', name: '大标题', desc: '适合品牌名 / 产品名', cls: 'big' },
- { id: 'subtitle', name: '副标题', desc: '补充口味或卖点', cls: 'mid' },
- { id: 'body', name: '正文', desc: '配料、说明与信息', cls: 'sm' },
- { id: 'latin', name: '英文标题', desc: '无衬线大写字母', cls: 'en' }
- ];
- return h('div', null,
- h('div', { className: 'tool-section' },
- h('div', { className: 'tool-section-title' }, '添加文字'),
- presets.map(function (p) {
- return h('button', { key: p.id, className: 'text-preset', onClick: function () { addTextPreset(p.id); } },
- h('span', null, h('b', null, p.name), h('span', null, p.desc)),
- h('span', { className: 't-label ' + p.cls }, p.cls === 'en' ? 'EN' : 'Aa')
- );
- })
- ),
- h('div', { className: 'tool-section' },
- h('div', { className: 'tool-section-title' }, '字体', h('span', null, '点击应用或新建')),
- h('div', { className: 'font-grid' }, Object.keys(D.fonts).map(function (k) {
- return h('button', { key: k, className: 'font-item', onClick: function () { applyFont(k); } },
- h('span', { style: { fontFamily: D.fonts[k].stack } }, '字体 Aa'),
- h('span', null, D.fonts[k].label)
- );
- }))
- )
- );
- }
- if (tool === 'shapes') {
- const shapes = [
- { id: 'rect', name: '矩形' },
- { id: 'circle', name: '圆形' },
- { id: 'triangle', name: '三角形' },
- { id: 'line', name: '线条' }
- ];
- const lib = window.PL && window.PL.boxlib;
- const icons = lib && lib.ICONS ? lib.ICONS : {};
- return h('div', null,
- h('div', { className: 'tool-section' },
- h('div', { className: 'tool-section-title' }, '基础图形'),
- h('div', { className: 'shape-grid' }, shapes.map(function (s) {
- return h('button', { key: s.id, className: 'shape-btn', title: s.name, onClick: function () { addShape(s.id); } },
- h('span', { className: 'shape-ico ' + s.id })
- );
- })),
- h('div', { className: 'p-actions', style: { marginTop: '8px' } },
- h(A.Button, { block: true, icon: barcodeIcon, onClick: function () { addShape('barcode'); } }, '添加条码'),
- h(A.Button, { block: true, icon: qrIcon, onClick: function () { addShape('qr'); } }, '添加二维码')
- )
- ),
- Object.keys(icons).length ? h('div', { className: 'tool-section' },
- h('div', { className: 'tool-section-title' }, '平台素材', h('span', null, Object.keys(icons).length + '')),
- h('div', { className: 'asset-grid' }, Object.keys(icons).map(function (id) {
- return h('button', {
- key: id, className: 'asset-btn', title: icons[id].name,
- onClick: function () { addAsset(id); },
- dangerouslySetInnerHTML: { __html: lib.assetSvg(id, '#17140f') }
- });
- }))
- ) : null,
- h('div', { className: 'tool-section' },
- h('div', { className: 'tool-section-title' }, '贴纸库', h('span', null, Object.keys(D.stickers).length + '')),
- h('div', { className: 'sticker-grid' }, Object.keys(D.stickers).map(function (k) {
- return h('button', { key: k, className: 'sticker-btn', title: k, onClick: function () { addSticker(k); } },
- h('span', {
- dangerouslySetInnerHTML: {
- __html: '<svg viewBox="0 0 24 24" fill="none">' + D.stickers[k].paths.map(function (p) {
- return p.stroke
- ? '<path d="' + p.d + '" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round"/>'
- : '<path d="' + p.d + '" fill="currentColor"/>';
- }).join('') + '</svg>'
- }
- })
- );
- }))
- )
- );
- }
- if (tool === 'layers') {
- const list = allElements();
- return h('div', null,
- h('div', { className: 'tool-section' },
- h('div', { className: 'tool-section-title' }, '图层 · ' + (activeSide === 'front' ? '正面' : '背面'), h('span', null, list.length + ' 个')),
- list.length ? h(A.List, {
- className: 'layer-list ant-list',
- dataSource: list.slice().reverse(),
- renderItem: function (item) {
- return h(A.List.Item, {
- key: item.id,
- className: 'layer-row' + (item.id === selectedId ? ' on' : ''),
- 'data-layer-id': item.id,
- onClick: function () { selectedId = item.id; renderCanvas(); renderProps(); renderTool(); }
- },
- h('span', { className: 'layer-icon', dangerouslySetInnerHTML: { __html: elementIcon(item) } }),
- h('span', { className: 'layer-name' }, elementLabel(item), h('small', null, item.type)),
- h('button', {
- className: 'layer-eye',
- title: item.hidden ? '显示图层' : '隐藏图层',
- onClick: function (e) { e.stopPropagation(); item.hidden = !item.hidden; commit(); renderCanvas(); renderTool(); }
- }, eyeIcon(item.hidden)),
- h('button', {
- className: 'layer-order',
- title: '移到最顶层',
- onClick: function (e) { e.stopPropagation(); selectedId = item.id; frontElement(); }
- }, '⤒'),
- h('button', {
- className: 'layer-order',
- title: '移到最底层',
- onClick: function (e) { e.stopPropagation(); selectedId = item.id; backElement(); }
- }, '⤓'),
- h('button', {
- className: 'layer-del',
- title: '删除图层',
- onClick: function (e) { e.stopPropagation(); deleteElementById(item.id); }
- }, '✕')
- );
- }
- }) : h(A.Empty, { description: '这一面还没有图层', image: A.Empty.PRESENTED_IMAGE_SIMPLE })
- ),
- h('div', { className: 'p-actions' },
- h(A.Button, { block: true, icon: copyIcon, onClick: duplicateSide }, '复制到另一面'),
- h(A.Button, { block: true, danger: true, onClick: function () { clearSide(); } }, '清空本面'),
- h(A.Button, { block: true, danger: true, onClick: clearAllSides }, '一键清空全部')
- )
- );
- }
- const s = size();
- const p = product();
- const price = D.price(state);
- return h('div', null,
- h('div', { className: 'tool-section' },
- h('div', { className: 'tool-section-title' }, '当前袋型'),
- h('div', { className: 's-current' },
- h('div', { className: 's-current-thumb', dangerouslySetInnerHTML: { __html: R.bagSVG(renderProduct(), 'front', currentPreviewDesign(), { size: s, card: true, material: state.material, finish: state.finish }) } }),
- h('div', null, h('b', null, p.name), h('em', null, p.en), h('span', null, s.w + ' × ' + s.h + ' mm'))
- )
- ),
- h('div', { className: 'tool-section' },
- h('div', { className: 'tool-section-title' }, '尺寸'),
- h(A.Radio.Group, {
- className: 's-size-group',
- value: state.sizeId,
- onChange: function (e) { changeSize(e.target.value); },
- options: p.sizes.map(function (item) { return { label: item.label, value: item.id }; }).concat([{ label: '自定义', value: 'custom' }])
- }),
- h('div', { className: 's-custom-inputs', style: { marginTop: '10px' } },
- h('div', { className: 's-inline-field' }, h('label', null, '宽'),
- h(InlineNumber, {
- value: size().w, min: 30, max: 1200, step: 5,
- onInput: function (v) { applyCustomSize('w', v, false); },
- onCommit: function (v) { applyCustomSize('w', v, true); }
- })
- ),
- h('span', { className: 's-times' }, '×'),
- h('div', { className: 's-inline-field' }, h('label', null, '高'),
- h(InlineNumber, {
- value: size().h, min: 30, max: 1600, step: 5,
- onInput: function (v) { applyCustomSize('h', v, false); },
- onCommit: function (v) { applyCustomSize('h', v, true); }
- })
- )
- )
- ),
- h('div', { className: 'tool-section' },
- h('div', { className: 'tool-section-title' }, '材质与工艺'),
- h('div', { className: 's-two' },
- h('div', null, h('label', null, '材质'), h(A.Select, {
- value: state.material,
- onChange: function (v) { changeSetting('material', v); },
- options: D.materials.map(function (m) { return { value: m.id, label: m.name }; })
- })),
- h('div', null, h('label', null, '工艺'), h(A.Select, {
- value: state.finish,
- onChange: function (v) { changeSetting('finish', v); },
- options: D.finishes.map(function (f) { return { value: f.id, label: f.name }; })
- }))
- )
- ),
- h('div', { className: 'tool-section' },
- h('div', { className: 'tool-section-title' }, '数量'),
- h(A.Radio.Group, {
- className: 's-qty-group',
- optionType: 'button',
- buttonStyle: 'solid',
- value: String(state.qty),
- onChange: function (e) { changeSetting('qty', e.target.value); },
- options: D.quantities.map(function (q) { return { label: String(q.value), value: String(q.value) }; })
- }),
- h('div', { className: 's-qty-custom' },
- h('label', null, '自定义数量'),
- h(InlineNumber, {
- value: state.qty, min: 100, max: 100000, step: 50,
- onInput: function (v) { setQty(v, false); },
- onCommit: function (v) { setQty(v, true); }
- }),
- h('span', null, '个 · 100 起订')
- )
- ),
- h('div', { className: 'tool-section' },
- h('div', { className: 'tool-section-title' }, '袋身颜色'),
- h('div', { className: 'p-swatches' }, [p.mockColor].concat(bagPalette).filter(function (c, i, a) { return a.indexOf(c) === i; }).map(function (c) {
- const on = (state.bagColor || p.mockColor).toLowerCase() === c.toLowerCase();
- return h('button', { key: c, className: 'p-swatch' + (on ? ' on' : ''), style: { background: c }, onClick: function () { changeBagColor(c); } });
- })),
- h('div', { className: 'pms-title' }, '参考潘通色'),
- pmsGrid(function (c) { changeBagColor(c.hex); }, state.bagColor || p.mockColor)
- ),
- h('div', { className: 'p-price-card' },
- h('div', { className: 'p-price-line' }, h('span', null, '单价'), h('b', null, '¥' + price.unit.toFixed(2) + ' / 个')),
- h('div', { className: 'p-price-line' }, h('span', null, '合计 · ' + state.qty + ' 个'), h('b', null, '¥' + price.total.toFixed(2)))
- ),
- h('div', { className: 'tool-section' },
- h('div', { className: 'tool-section-title' }, '我的方案', h('span', null, plans.length + ' 个')),
- h('div', { className: 'plan-save' },
- h(A.Input, {
- defaultValue: planName,
- placeholder: '给当前设计起个名字',
- maxLength: 30,
- onChange: function (e) { planName = e.target.value; },
- onPressEnter: savePlan
- }),
- h(A.Button, { type: 'primary', onClick: savePlan }, '保存')
- ),
- plans.length ? h('div', { className: 'plan-list' }, plans.map(function (plan) {
- return h('div', { className: 'plan-item', key: plan.id },
- h('div', { className: 'plan-thumb', dangerouslySetInnerHTML: { __html: planThumb(plan) } }),
- h('div', { className: 'plan-meta' },
- h('b', null, plan.name),
- h('span', null, new Date(plan.savedAt).toLocaleString('zh-CN', { month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit' }))
- ),
- h('div', { className: 'plan-actions' },
- h('button', { onClick: function () { loadPlan(plan.id); }, title: '载入方案' }, '载入'),
- h('button', { className: 'del', onClick: function () { removePlan(plan.id); }, title: '删除方案' }, '✕')
- )
- );
- })) : h('div', { className: 'p-hint' }, '保存后可随时切换不同设计方案,最多 12 个。')
- ),
- h('div', { className: 'p-actions', style: { marginTop: '12px' } },
- h(A.Button, { block: true, onClick: function () { setMode('settings'); } }, '返回设置'),
- h(A.Button, { block: true, danger: true, onClick: function () { clearSide(); } }, '清空本面')
- )
- );
- }
- function renderProps() {
- UI.render(els.propsBody, propsTree());
- document.body.classList.toggle('props-open', !!selectedEl());
- }
- function propsTree() {
- const el = selectedEl();
- if (!el) {
- const s = size();
- const p = product();
- const side = sideData();
- const price = D.price(state);
- els.propsChip.textContent = 'CANVAS';
- const bgColors = ['#f7f2e7', '#ffffff', '#17140f', '#ff5c2b', '#d9f07c', '#1e3a2c', '#bfe3f2', '#e8d5b8', '#f3d9d3'];
- return h('div', null,
- h('div', { className: 'p-section' },
- h('div', { className: 'p-section-title' }, '印刷画布'),
- h('div', { className: 'p-row' },
- h('div', { className: 'p-field' }, h('label', null, '宽度'), h(A.Input, { value: s.w + ' mm', readOnly: true })),
- h('div', { className: 'p-field' }, h('label', null, '高度'), h(A.Input, { value: s.h + ' mm', readOnly: true }))
- ),
- h('div', { className: 'p-row' },
- h('div', { className: 'p-field' }, h('label', null, '当前面'),
- h(A.Segmented, {
- value: activeSide,
- block: true,
- onChange: function (v) { changeSide(v); },
- options: [{ label: '正面', value: 'front' }, { label: '背面', value: 'back' }]
- })
- )
- ),
- h('div', { className: 'p-hint' }, '刀版线外 3mm 为出血位,重要文字请放在安全区内。')
- ),
- h('div', { className: 'p-section' },
- h('div', { className: 'p-section-title' }, '印刷底色'),
- h('div', { className: 'p-swatches' },
- 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(); } }),
- bgColors.map(function (c) {
- return h('button', { key: c, className: 'p-swatch' + (side.bg === c ? ' on' : ''), style: { background: c }, onClick: function () { side.bg = c; commit(); renderCanvas(); renderProps(); } });
- })
- ),
- h('div', { className: 'p-row', style: { marginTop: '10px' } },
- h('div', { className: 'p-field' }, h('label', null, '自定义底色'),
- h(A.ColorPicker, {
- key: 'bg-' + activeSide + '-' + (side.bg || 'none'),
- defaultValue: side.bg || '#f7f2e7',
- showText: true,
- onChange: function (c) { side.bg = c.toHexString(); renderCanvas(); },
- onChangeComplete: function (c) { side.bg = c.toHexString(); commit(); renderCanvas(); }
- })
- )
- ),
- h('div', { className: 'pms-title' }, '参考潘通色'),
- pmsGrid(function (c) { side.bg = c.hex; commit(); renderCanvas(); renderProps(); }, side.bg)
- ),
- h('div', { className: 'p-section' },
- h('div', { className: 'p-section-title' }, '袋身颜色'),
- h('div', { className: 'p-swatches' }, [p.mockColor].concat(bagPalette).filter(function (c, i, a) { return a.indexOf(c) === i; }).map(function (c) {
- const on = (state.bagColor || p.mockColor).toLowerCase() === c.toLowerCase();
- return h('button', { key: c, className: 'p-swatch' + (on ? ' on' : ''), style: { background: c }, onClick: function () { changeBagColor(c); renderProps(); } });
- }))
- ),
- h('div', { className: 'p-section' },
- h('div', { className: 'p-section-title' }, '画布工具'),
- h('label', { className: 'p-check' }, '显示刀版线',
- h(A.Switch, { size: 'small', checked: showGuides, onChange: function (v) { showGuides = v; renderCanvas(); } })
- ),
- h('div', { className: 'p-actions', style: { marginTop: '10px' } },
- h(A.Button, { block: true, onClick: duplicateSide }, '复制到' + (activeSide === 'front' ? '背面' : '正面')),
- h(A.Button, { block: true, danger: true, onClick: function () { clearSide(); } }, '清空本面')
- )
- ),
- h('div', { className: 'p-section' },
- h('div', { className: 'p-section-title' }, '报价'),
- h('div', { className: 'p-price-card' },
- h('div', { className: 'p-price-line' }, h('span', null, p.name + ' · ' + s.label + ' · ' + state.qty + ' 个'), h('b', null, '¥' + price.total.toFixed(2)))
- ),
- h('div', { className: 'p-hint' }, '切换尺寸或数量后价格会实时更新。')
- )
- );
- }
- els.propsChip.textContent = el.type.toUpperCase();
- const box = R.elementBox(el);
- const numField = function (label, prop, value, min, max, step) {
- const rounded = typeof value === 'number' ? Math.round(value * 100) / 100 : value;
- return h('div', { className: 'p-field' }, h('label', null, label),
- h(A.InputNumber, {
- value: rounded,
- min: min,
- max: max,
- step: step || 0.5,
- style: { width: '100%' },
- onChange: function (v) { if (v != null) { updateSelected(prop, v); commit(); renderCanvas(); } }
- })
- );
- };
- const colorField = function (label, prop, value) {
- const hex = value && value !== 'none' ? value : '#17140f';
- return h('div', { className: 'p-field' }, h('label', null, label),
- h(A.ColorPicker, {
- // 非受控:拖动色相时由组件自身维护 HSV,避免每次 onChange 重建导致色相回弹
- key: 'cp-' + prop + '-' + (selectedId || '') + '-' + hex,
- defaultValue: hex,
- showText: true,
- onChange: function (c) { updateSelected(prop, c.toHexString()); renderCanvas(); },
- // 提交时不再 renderProps,避免重建 ColorPicker 导致取色面板关闭
- onChangeComplete: function (c) { updateSelected(prop, c.toHexString()); commit(); renderCanvas(); }
- })
- );
- };
- let specific = null;
- if (el.type === 'text') {
- specific = h('div', { className: 'p-section' },
- h('div', { className: 'p-section-title' }, '文字内容'),
- h(TextField, {
- multiline: true,
- value: el.text,
- extra: { autoSize: { minRows: 2, maxRows: 5 } },
- onInput: function (v) { updateSelected('text', v); renderCanvas(); },
- onCommit: function () { commit(); renderTool(); }
- }),
- h('div', { className: 'p-section-title', style: { marginTop: '16px' } }, '字体'),
- h(A.Select, {
- value: el.font || 'sans',
- style: { width: '100%' },
- onChange: function (v) { updateSelected('font', v); commit(); renderCanvas(); renderProps(); },
- options: Object.keys(D.fonts).map(function (k) { return { value: k, label: D.fonts[k].label }; })
- }),
- h('div', { className: 'p-row', style: { marginTop: '9px' } },
- numField('字号 mm', 'size', el.size, 2, 120, 0.5),
- numField('字距', 'spacing', el.spacing || 0, -0.2, 0.4, 0.01)
- ),
- h('div', { className: 'p-row' },
- numField('行高', 'lineHeight', el.lineHeight || 1.25, 0.7, 3, 0.05),
- colorField('颜色', 'color', el.color)
- ),
- h('div', { className: 'p-row' },
- h('div', { className: 'p-field' }, h('label', null, '字重'),
- h(A.Segmented, {
- value: String(el.weight || 400),
- block: true,
- onChange: function (v) { updateSelected('weight', Number(v)); commit(); renderCanvas(); renderProps(); },
- options: [{ label: '400', value: '400' }, { label: '600', value: '600' }, { label: '800', value: '800' }]
- })
- )
- ),
- h('div', { className: 'p-row' },
- h('div', { className: 'p-field' }, h('label', null, '对齐'),
- h(A.Segmented, {
- value: el.align || 'left',
- block: true,
- onChange: function (v) { updateSelected('align', v); commit(); renderCanvas(); renderProps(); },
- options: [{ label: '左', value: 'left' }, { label: '中', value: 'center' }, { label: '右', value: 'right' }]
- })
- ),
- h('div', { className: 'p-field' }, h('label', null, '斜体'),
- h('div', { className: 'p-check p-check-box' }, h('span', { style: { fontFamily: 'Georgia' } }, 'I'),
- h(A.Switch, { size: 'small', checked: !!el.italic, onChange: function (v) { updateSelected('italic', v); commit(); renderCanvas(); renderProps(); } })
- )
- )
- )
- );
- } else if (el.type === 'image') {
- specific = h('div', { className: 'p-section' },
- h('div', { className: 'p-section-title' }, '图片'),
- h('div', { className: 'p-row' },
- h('div', { className: 'p-field' }, h('label', null, '填充方式'),
- h(A.Segmented, {
- value: el.fit || 'contain',
- block: true,
- onChange: function (v) { updateSelected('fit', v); commit(); renderCanvas(); renderProps(); },
- options: [{ label: '完整显示', value: 'contain' }, { label: '填满裁切', value: 'cover' }]
- })
- )
- ),
- h('label', { className: 'p-check' }, '单色印刷',
- h(A.Switch, { size: 'small', checked: !!el.mono, onChange: function (v) { updateSelected('mono', v); commit(); renderCanvas(); renderProps(); } })
- ),
- h('div', { className: 'p-actions', style: { marginTop: '10px' } },
- h(A.Button, { block: true, onClick: function () { pickUpload(true); } }, '替换图片')
- )
- );
- } else if (el.type === 'shape') {
- specific = h('div', { className: 'p-section' },
- h('div', { className: 'p-section-title' }, el.shape === 'line' ? '线条' : '外观'),
- el.shape !== 'line' ? h('div', { className: 'p-row' },
- colorField('填充', 'fill', el.fill),
- el.shape === 'rect' ? numField('圆角', 'radius', el.radius || 0, 0, 80, 0.5) : null
- ) : null,
- h('div', { className: 'p-row' },
- colorField('描边', 'stroke', el.stroke),
- numField('描边宽', 'strokeWidth', el.strokeWidth || 0, 0, 20, 0.1)
- )
- );
- } else if (el.type === 'sticker') {
- specific = h('div', { className: 'p-section' },
- h('div', { className: 'p-section-title' }, '贴纸'),
- h('div', { className: 'p-row' }, colorField('颜色', 'color', el.color)),
- h('div', { className: 'p-hint' }, '拖动四角可等比缩放。')
- );
- } else if (el.type === 'badge') {
- specific = h('div', { className: 'p-section' },
- h('div', { className: 'p-section-title' }, '圆形徽章'),
- h(TextField, {
- multiline: true,
- value: el.text || '',
- extra: { autoSize: { minRows: 2, maxRows: 3 } },
- onInput: function (v) { updateSelected('text', v); renderCanvas(); },
- onCommit: function () { commit(); renderTool(); }
- }),
- h('div', { className: 'p-row', style: { marginTop: '9px' } },
- numField('环文字号', 'size', el.size || 3, 1, 40, 0.2),
- colorField('颜色', 'color', el.color)
- )
- );
- } else if (el.type === 'barcode') {
- specific = h('div', { className: 'p-section' },
- h('div', { className: 'p-section-title' }, '条码 / SKU'),
- h(TextField, {
- value: el.value || '',
- onInput: function (v) { updateSelected('value', v); renderCanvas(); },
- onCommit: function () { commit(); renderTool(); }
- }),
- h('label', { className: 'p-check', style: { marginTop: '9px' } }, '显示数字',
- h(A.Switch, { size: 'small', checked: el.showText !== false, onChange: function (v) { updateSelected('showText', v); commit(); renderCanvas(); renderProps(); } })
- ),
- h('div', { className: 'p-row' }, colorField('颜色', 'color', el.color)),
- h('div', { className: 'p-hint' }, '输入 12–13 位数字会生成真实 EAN-13 校验位;输入链接或文字会生成稳定条码。')
- );
- } else if (el.type === 'qr') {
- specific = h('div', { className: 'p-section' },
- h('div', { className: 'p-section-title' }, '二维码'),
- h(TextField, {
- multiline: true,
- value: el.value || '',
- extra: { autoSize: { minRows: 2, maxRows: 4 } },
- onInput: function (v) { updateSelected('value', v); renderCanvas(); },
- onCommit: function () { commit(); renderTool(); }
- }),
- h('div', { className: 'p-row', style: { marginTop: '9px' } },
- colorField('码点颜色', 'color', el.color),
- h('div', { className: 'p-field' }, h('label', null, '浅色底'),
- h(A.Switch, { size: 'small', checked: el.light !== 'none', onChange: function (v) { updateSelected('light', v ? '#ffffff' : 'none'); commit(); renderCanvas(); renderProps(); } })
- )
- ),
- h('div', { className: 'p-hint' }, '填写网址、微信号或任意文字即可生成二维码;保留浅色底可提高扫码成功率。')
- );
- } else if (el.type === 'asset') {
- specific = h('div', { className: 'p-section' },
- h('div', { className: 'p-section-title' }, '平台素材'),
- h('div', { className: 'p-row' }, colorField('颜色', 'color', el.color)),
- h('div', { className: 'p-hint' }, '素材为矢量图标,可任意缩放;拖动四角等比调整大小。')
- );
- }
- return h('div', null,
- specific,
- h('div', { className: 'p-section' },
- h('div', { className: 'p-section-title' }, '位置与尺寸'),
- h('div', { className: 'p-row' },
- numField('X (mm)', 'x', el.x, -9999, 9999),
- numField('Y (mm)', 'y', el.y, -9999, 9999)
- ),
- h('div', { className: 'p-row' },
- numField('宽度', 'w', el.w, 2, 9999),
- (el.type === 'text' || el.type === 'qr' || el.type === 'badge' || el.type === 'asset')
- ? h('div', { className: 'p-field' }, h('label', null, '高度(自动)'), h(A.Input, { value: box.h.toFixed(1) + ' mm', readOnly: true }))
- : numField('高度', 'h', el.h, 1, 9999)
- ),
- h('div', { className: 'p-row' },
- numField('旋转 °', 'rotation', el.rotation || 0, -180, 180, 1),
- h('div', { className: 'p-field' }, h('label', null, '不透明度 ' + Math.round((el.opacity == null ? 1 : el.opacity) * 100) + '%'),
- h(A.Slider, {
- value: (el.opacity == null ? 1 : el.opacity) * 100,
- min: 0,
- max: 100,
- onChange: function (v) { updateSelected('opacity', v); renderCanvas(); },
- onAfterChange: function () { commit(); renderProps(); }
- })
- )
- )
- ),
- h('div', { className: 'p-section' },
- h('div', { className: 'p-section-title' }, '图层顺序'),
- h('div', { className: 'p-actions order-actions' },
- h(A.Button, { block: true, onClick: frontElement }, '⤒ 置顶'),
- h(A.Button, { block: true, onClick: raiseElement }, '↑ 上移'),
- h(A.Button, { block: true, onClick: lowerElement }, '↓ 下移'),
- h(A.Button, { block: true, onClick: backElement }, '⤓ 置底'),
- h(A.Button, { block: true, onClick: duplicateElement }, '复制'),
- h(A.Button, { block: true, danger: true, onClick: deleteElement }, '删除')
- )
- )
- );
- }
- /* ---------------- AI 交互式排版(登录后可用,后台控额度) ---------------- */
- const ai = { open: false, side: 'front', brief: '', busy: false, last: null, quota: null };
- function aiPanelEnsure() {
- if (document.getElementById('plAiPanel')) return;
- const wrap = document.createElement('div');
- wrap.id = 'plAiPanel';
- wrap.className = 'pl-ai-panel';
- wrap.hidden = true;
- wrap.innerHTML =
- '<div class="pl-ai-head"><b>AI 排版</b><span class="pl-ai-quota" id="plAiQuota"></span>' +
- '<button type="button" class="pl-ai-close" id="plAiClose">✕</button></div>' +
- '<div class="pl-ai-sides" id="plAiSides">' +
- '<button type="button" data-ai-side="front" class="on">正面</button>' +
- '<button type="button" data-ai-side="back">背面</button>' +
- '<button type="button" data-ai-side="both">双面同款</button></div>' +
- '<textarea id="plAiBrief" placeholder="描述你想要的排版,如: 极简咖啡包装,暖米底色,顶部衬线体品牌名,中部咖啡豆贴纸,底部一行英文 slogan 生成后可继续说:文字再大一点 / 换深色背景"></textarea>' +
- '<div class="pl-ai-actions">' +
- '<button type="button" class="btn btn-primary" id="plAiGen">生成排版</button>' +
- '<button type="button" class="pl-ai-clear" id="plAiClear">清空本面</button></div>' +
- '<p class="pl-ai-tip">AI 结果直接应用到画布,可随时撤销(⌘Z)。每次生成消耗 1 次额度。</p>';
- document.body.appendChild(wrap);
- (function makePanelDraggable() {
- const head = wrap.querySelector('.pl-ai-head');
- let drag = null;
- head.style.touchAction = 'none';
- head.addEventListener('pointerdown', function (e) {
- if (e.target.closest('button')) return;
- const r = wrap.getBoundingClientRect();
- drag = { dx: e.clientX - r.left, dy: e.clientY - r.top };
- wrap.style.left = r.left + 'px';
- wrap.style.top = r.top + 'px';
- wrap.style.right = 'auto';
- wrap.style.bottom = 'auto';
- if (head.setPointerCapture) head.setPointerCapture(e.pointerId);
- e.preventDefault();
- });
- head.addEventListener('pointermove', function (e) {
- if (!drag) return;
- const maxX = Math.max(6, window.innerWidth - 100);
- const maxY = Math.max(6, window.innerHeight - 60);
- wrap.style.left = clamp(e.clientX - drag.dx, 6, maxX) + 'px';
- wrap.style.top = clamp(e.clientY - drag.dy, 6, maxY) + 'px';
- });
- head.addEventListener('pointerup', function () { drag = null; });
- head.addEventListener('pointercancel', function () { drag = null; });
- })();
- wrap.querySelector('#plAiClose').addEventListener('click', function () { aiPanelToggle(false); });
- wrap.querySelector('#plAiSides').addEventListener('click', function (e) {
- const b = e.target.closest('[data-ai-side]');
- if (!b) return;
- ai.side = b.dataset.aiSide;
- wrap.querySelectorAll('#plAiSides button').forEach(function (x) { x.classList.toggle('on', x === b); });
- });
- wrap.querySelector('#plAiGen').addEventListener('click', aiGenerate);
- wrap.querySelector('#plAiClear').addEventListener('click', function () {
- const targets = ai.side === 'both' ? ['front', 'back'] : [ai.side === 'back' ? 'back' : 'front'];
- targets.forEach(function (k) { state.sides[k] = { bg: null, elements: [] }; });
- selectedId = null;
- commit(); renderCanvas(); renderSummarySafe(); renderProps();
- });
- }
- function renderSummarySafe() { try { renderSummary(); } catch (e) {} }
- function aiPanelToggle(open) {
- aiPanelEnsure();
- if (open !== undefined) ai.open = open; else ai.open = !ai.open;
- document.getElementById('plAiPanel').hidden = !ai.open;
- if (ai.open) {
- if (window.PL.auth && !PL.auth.user()) {
- PL.auth.require(function () { aiRefreshQuota(); });
- toast('登录后可用 AI 排版');
- } else {
- aiRefreshQuota();
- }
- }
- }
- function aiRefreshQuota() {
- if (!window.PL || !PL.api || !PL.api.token()) return;
- PL.api.get('/ai/quota').then(function (q) {
- ai.quota = q;
- const el = document.getElementById('plAiQuota');
- if (!el) return;
- el.textContent = q.configured ? ('剩余 ' + q.left + ' 次') : 'AI 未配置';
- document.getElementById('plAiGen').disabled = !q.configured;
- }, function () {});
- }
- function clampElementToCanvas(el, s) {
- const square = el.type === 'qr' || el.type === 'asset' || el.type === 'badge';
- let box = R.elementBox(el);
- let w = box.w;
- let h = box.h;
- const maxW = Math.max(6, s.w);
- const maxH = Math.max(6, s.h);
- if (w > maxW) {
- const k = maxW / w;
- w = maxW;
- if (!square && el.type !== 'text') h = Math.max(4, h * k);
- }
- if (h > maxH) {
- const k = maxH / h;
- h = maxH;
- if (!square) w = Math.max(4, w * k);
- }
- if (square) h = w;
- if (el.type === 'text') {
- el.w = Math.round(w * 10) / 10;
- h = R.elementBox(el).h;
- } else if (square) {
- el.w = Math.round(w * 10) / 10;
- } else {
- el.w = Math.round(w * 10) / 10;
- el.h = Math.round(h * 10) / 10;
- }
- const rot = ((num(el.rotation, 0) % 360) + 360) % 360;
- const rad = rot * Math.PI / 180;
- const bw = Math.abs(w * Math.cos(rad)) + Math.abs(h * Math.sin(rad));
- const bh = Math.abs(w * Math.sin(rad)) + Math.abs(h * Math.cos(rad));
- const halfW = Math.min(bw, s.w) / 2;
- const halfH = Math.min(bh, s.h) / 2;
- const cx = num(el.x, 0) + w / 2;
- const cy = num(el.y, 0) + h / 2;
- const ncx = Math.min(Math.max(cx, halfW), Math.max(halfW, s.w - halfW));
- const ncy = Math.min(Math.max(cy, halfH), Math.max(halfH, s.h - halfH));
- el.x = Math.round((ncx - w / 2) * 10) / 10;
- el.y = Math.round((ncy - h / 2) * 10) / 10;
- return el;
- }
- function aiApplyTo(sideKey, result) {
- const sd = state.sides[sideKey];
- if (!sd) return;
- const s = size();
- sd.elements = (result.elements || []).map(function (el) {
- el.id = R.uid('el');
- el.opacity = el.opacity == null ? 1 : el.opacity;
- return clampElementToCanvas(el, s);
- });
- sd.bg = result.bg || null;
- }
- function aiGenerate() {
- if (window.PL.auth && !PL.auth.user()) {
- PL.auth.require(function () { aiGenerate(); });
- return;
- }
- if (!window.PL || !PL.api) { toast('AI 需要联网登录后使用'); return; }
- const brief = (document.getElementById('plAiBrief').value || '').trim();
- if (!brief) { toast('先描述一下排版需求'); return; }
- if (ai.busy) return;
- ai.busy = true;
- const btn = document.getElementById('plAiGen');
- btn.disabled = true;
- const t0 = Date.now();
- btn.textContent = 'AI 生成中… 0s';
- const timer = setInterval(function () {
- btn.textContent = 'AI 生成中… ' + Math.round((Date.now() - t0) / 1000) + 's';
- }, 1000);
- const tip = document.querySelector('.pl-ai-tip');
- if (tip) tip.textContent = 'AI 正在设计中,通常 10~60 秒,请勿关闭面板或刷新页面…';
- const s = size();
- const applySide = ai.side === 'back' ? 'back' : 'front';
- const contextEl = document.getElementById('plAiQuota');
- PL.api.post('/ai/layout', {
- type: 'bag',
- brief: brief,
- meta: { w: s.w, h: s.h, product: product().name },
- context: ai.last && ai.last.side === applySide ? { bg: state.sides[applySide].bg, elements: state.sides[applySide].elements } : null
- }, { timeout: 150000 }).then(function (r) {
- ai.busy = false; clearInterval(timer);
- btn.disabled = false; btn.textContent = '生成排版';
- if (tip) tip.textContent = 'AI 结果已应用到画布,可继续提修改意见(每次生成消耗 1 次额度)。';
- if (!(r.result.elements || []).length) {
- toast('AI 这次没能生成有效排版(未扣次数),换个说法再试');
- if (contextEl) contextEl.textContent = '剩余 ' + r.left + ' 次';
- return;
- }
- ai.last = { side: applySide, result: r.result };
- aiApplyTo(applySide, r.result);
- if (ai.side === 'both') aiApplyTo('back', r.result);
- commit(); renderCanvas(); renderSummarySafe();
- selectedId = null;
- if (contextEl) contextEl.textContent = '剩余 ' + r.left + ' 次';
- toast('AI 排版已应用,可继续提修改意见');
- }, function (err) {
- ai.busy = false; clearInterval(timer);
- btn.disabled = false; btn.textContent = '生成排版';
- if (tip) tip.textContent = 'AI 结果直接应用到画布,可随时撤销(⌘Z)。每次生成消耗 1 次额度。';
- if (err.status === 401) {
- PL.auth.require(function () { aiGenerate(); });
- } else {
- toast(err.message || 'AI 生成失败');
- }
- });
- }
- function addElement(el) {
- const s = size();
- const box = R.elementBox(el);
- if (el.x == null) el.x = (s.w - box.w) / 2;
- if (el.y == null) el.y = (s.h - box.h) / 2;
- el.id = R.uid('el');
- sideData().elements.push(el);
- selectedId = el.id;
- commit();
- renderCanvas();
- renderProps();
- renderTool();
- return el;
- }
- function addTextPreset(kind, fontOverride) {
- const s = size();
- const presets = {
- title: { text: '你的标题', size: s.w * 0.15, weight: 800, font: 'sans', align: 'left' },
- subtitle: { text: '一句打动人的副标题', size: s.w * 0.052, weight: 600, font: 'sans', align: 'left' },
- body: { text: '在这里输入产品说明、配料或品牌故事。', size: s.w * 0.03, weight: 400, font: 'sans', align: 'left' },
- latin: { text: 'YOUR BRAND', size: s.w * 0.11, weight: 800, font: 'latin', align: 'left', spacing: 0.02 }
- };
- const p = Object.assign({}, presets[kind] || presets.body);
- p.font = fontOverride || p.font || lastFont;
- lastFont = p.font;
- p.type = 'text';
- p.w = s.w * 0.8;
- p.color = '#17140f';
- p.spacing = p.spacing || 0;
- p.lineHeight = 1.2;
- p.strokeWidth = 0;
- p.rotation = 0;
- p.opacity = 1;
- const textCount = allElements().filter(function (e) { return e.type === 'text'; }).length;
- const step = Math.max(6, Math.min(14, s.h * 0.035));
- p.x = clamp(s.w * 0.1 + (textCount % 5) * step * 0.7, 2, Math.max(2, s.w * 0.18));
- p.y = clamp(s.h * 0.3 + (textCount % 7) * step, 2, Math.max(2, s.h - 24));
- addElement(p);
- toast('已添加文字 · 双击画布可直接编辑');
- }
- function addShape(kind) {
- const s = size();
- const base = { type: 'shape', rotation: 0, opacity: 1, fill: '#ff5c2b', stroke: 'none', strokeWidth: 0, radius: 0 };
- let el;
- if (kind === 'circle') {
- el = Object.assign(base, { shape: 'circle', w: s.w * 0.36, h: s.w * 0.36, fill: '#d9f07c' });
- } else if (kind === 'line') {
- el = Object.assign(base, { shape: 'line', w: s.w * 0.7, h: 4, fill: 'none', stroke: '#17140f', strokeWidth: 1 });
- } else if (kind === 'triangle') {
- el = Object.assign(base, { shape: 'triangle', w: s.w * 0.36, h: s.w * 0.32, fill: '#ff5c2b' });
- } else if (kind === 'badge') {
- el = { type: 'badge', w: s.w * 0.34, text: 'SMALL BATCH · POUCHLAB · ', color: '#17140f', size: s.w * 0.028, rotation: 0, opacity: 1 };
- } else if (kind === 'barcode') {
- el = { type: 'barcode', w: s.w * 0.5, h: s.h * 0.12, value: '6971234567890', color: '#17140f', showText: true, rotation: 0, opacity: 1 };
- } else if (kind === 'qr') {
- el = { type: 'qr', w: s.w * 0.34, value: 'https://pouchlab.cn', color: '#17140f', light: '#ffffff', rotation: 0, opacity: 1 };
- } else {
- el = Object.assign(base, { shape: 'rect', w: s.w * 0.44, h: s.h * 0.22, fill: '#ff5c2b' });
- }
- addElement(el);
- toast('已添加' + (kind === 'barcode' ? '条码' : kind === 'qr' ? '二维码' : kind === 'badge' ? '徽章' : '图形'));
- }
- function addAsset(id) {
- const s = size();
- const lib = window.PL && window.PL.boxlib;
- const def = lib && lib.ICONS ? lib.ICONS[id] : null;
- addElement({
- type: 'asset', asset: id, name: def ? def.name : id,
- w: s.w * 0.2, h: s.w * 0.2, color: '#17140f', rotation: 0, opacity: 1
- });
- toast('已添加素材 · ' + (def ? def.name : id));
- }
- function addSticker(name) {
- const s = size();
- addElement({ type: 'sticker', sticker: name, w: s.w * 0.2, h: s.w * 0.2, color: '#ff5c2b', rotation: 0, opacity: 1 });
- }
- function addImageFromUpload(up) {
- const s = size();
- const ratio = up.w && up.h ? up.h / up.w : 1;
- let w = s.w * 0.55;
- let h = w * ratio;
- if (h > s.h * 0.7) {
- h = s.h * 0.7;
- w = h / ratio;
- }
- addElement({ type: 'image', src: up.src, name: up.name, w: w, h: h, fit: 'contain', mono: false, rotation: 0, opacity: 1 });
- toast('图片已放置到画布');
- }
- function clearSide(side) {
- const target = side || activeSide;
- state.sides[target] = { bg: null, elements: [] };
- selectedId = null;
- commit();
- renderDesign();
- renderSettings();
- toast('已清空' + (target === 'front' ? '正面' : '背面') + ' · 可撤销');
- }
- function clearAllSides() {
- state.sides = { front: { bg: null, elements: [] }, back: { bg: null, elements: [] } };
- selectedId = null;
- commit();
- renderDesign();
- renderSettings();
- toast('已清空全部设计 · 可撤销');
- }
- function duplicateSide() {
- const from = activeSide;
- const to = from === 'front' ? 'back' : 'front';
- const src = sideData(from);
- const copy = {
- bg: src.bg,
- elements: src.elements.map(function (el) {
- const c = JSON.parse(JSON.stringify(el));
- c.id = R.uid('el');
- return c;
- })
- };
- state.sides[to] = copy;
- activeSide = to;
- selectedId = null;
- commit();
- renderDesign();
- toast('已复制到' + (to === 'front' ? '正面' : '背面'));
- }
- function selectedIndex() {
- return allElements().findIndex(function (e) { return e.id === selectedId; });
- }
- function raiseElement() {
- const i = selectedIndex();
- if (i < 0 || i >= allElements().length - 1) return;
- const arr = allElements();
- const tmp = arr[i];
- arr[i] = arr[i + 1];
- arr[i + 1] = tmp;
- commit();
- renderCanvas();
- renderTool();
- }
- function lowerElement() {
- const i = selectedIndex();
- if (i <= 0) return;
- const arr = allElements();
- const tmp = arr[i];
- arr[i] = arr[i - 1];
- arr[i - 1] = tmp;
- commit();
- renderCanvas();
- renderTool();
- }
- function frontElement() {
- const i = selectedIndex();
- if (i < 0 || i >= allElements().length - 1) return;
- const arr = allElements();
- arr.push(arr.splice(i, 1)[0]);
- commit();
- renderCanvas();
- renderTool();
- }
- function backElement() {
- const i = selectedIndex();
- if (i <= 0) return;
- const arr = allElements();
- arr.unshift(arr.splice(i, 1)[0]);
- commit();
- renderCanvas();
- renderTool();
- }
- /* 拖拽排序:把 fromId 移动到 toId 的上/下(above=true 为更高层) */
- function reorderElement(fromId, toId, above) {
- if (!fromId || !toId || fromId === toId) return;
- const arr = allElements();
- const rv = arr.slice().reverse();
- const si = rv.findIndex(function (x) { return x.id === fromId; });
- const ti = rv.findIndex(function (x) { return x.id === toId; });
- if (si < 0 || ti < 0) return;
- const it = rv.splice(si, 1)[0];
- let ins = ti > si ? ti - 1 : ti;
- if (!above) ins += 1;
- rv.splice(ins, 0, it);
- arr.splice.apply(arr, [0, arr.length].concat(rv.reverse()));
- selectedId = fromId;
- commit();
- renderCanvas();
- renderTool();
- renderProps();
- }
- function duplicateElement() {
- const el = selectedEl();
- if (!el) return;
- const copy = JSON.parse(JSON.stringify(el));
- copy.id = R.uid('el');
- copy.x += 4;
- copy.y += 4;
- allElements().push(copy);
- selectedId = copy.id;
- commit();
- renderCanvas();
- renderProps();
- renderTool();
- }
- function deleteElementById(id) {
- const arr = allElements();
- const i = arr.findIndex(function (e) { return e.id === id; });
- if (i < 0) return;
- arr.splice(i, 1);
- if (selectedId === id) selectedId = null;
- commit();
- renderCanvas();
- renderProps();
- renderTool();
- toast('已删除 · 可撤销');
- }
- function deleteElement() {
- const i = selectedIndex();
- if (i < 0) return;
- allElements().splice(i, 1);
- selectedId = null;
- commit();
- renderCanvas();
- renderProps();
- renderTool();
- toast('已删除 · 可撤销');
- }
- function updateSelected(prop, value) {
- const el = selectedEl();
- if (!el) return;
- if (prop === 'x' || prop === 'y' || prop === 'w' || prop === 'h' || prop === 'rotation' || prop === 'opacity' || prop === 'size' || prop === 'spacing' || prop === 'lineHeight' || prop === 'strokeWidth' || prop === 'radius') {
- const n = Number(value);
- if (isNaN(n)) return;
- if (prop === 'opacity') el.opacity = clamp(n / 100, 0, 1);
- else if (prop === 'size') el.size = Math.max(2, n);
- else if (prop === 'w') el.w = Math.max(2, n);
- else if (prop === 'h') el.h = Math.max(1, n);
- else if (prop === 'lineHeight') el.lineHeight = Math.max(0.7, n);
- else el[prop] = n;
- if (el.type === 'badge' && prop === 'w') el.h = el.w;
- if (el.type === 'sticker' && prop === 'w') el.h = el.w;
- } else if (prop === 'italic' || prop === 'mono' || prop === 'showText') {
- el[prop] = !!value;
- } else {
- el[prop] = value;
- }
- if (el.type === 'text' && prop === 'text') {
- el.w = el.w || size().w * 0.6;
- }
- if (el.type === 'badge' && prop === 'size') el.h = el.w;
- scheduleRenderCanvas();
- }
- function openInlineText(el) {
- if (!el || el.type !== 'text') return;
- inlineTarget = el;
- const g = els.canvasStage.querySelector('.sel-overlay');
- let rect = g ? g.getBoundingClientRect() : { left: innerWidth / 2 - 150, bottom: innerHeight / 2, top: innerHeight / 2 };
- const width = 300;
- const left = clamp(rect.left, 12, innerWidth - width - 12);
- let top = rect.bottom + 10;
- if (top + 160 > innerHeight) top = Math.max(12, rect.top - 158);
- els.inlineText.style.left = left + 'px';
- els.inlineText.style.top = top + 'px';
- els.inlineTextArea.value = el.text || '';
- els.inlineText.hidden = false;
- setTimeout(function () { els.inlineTextArea.focus(); els.inlineTextArea.select(); }, 20);
- }
- function hideInlineText() {
- if (!els.inlineText.hidden) els.inlineText.hidden = true;
- inlineTarget = null;
- }
- function commitInlineText() {
- if (!inlineTarget) return;
- const el = inlineTarget;
- el.text = els.inlineTextArea.value;
- hideInlineText();
- commit();
- renderCanvas();
- renderProps();
- renderTool();
- }
- function changeSide(side) {
- if (side === activeSide) return;
- activeSide = side;
- selectedId = null;
- hideInlineText();
- renderDesign();
- }
- function doUndo() {
- if (hIndex <= 0) return;
- hIndex -= 1;
- applySnapshot(history[hIndex]);
- selectedId = null;
- saveState();
- renderSettings();
- if (mode === 'design') renderDesign();
- if (mode === 'summary') renderSummary();
- updateMeta();
- toast('已撤销');
- }
- function doRedo() {
- if (hIndex >= history.length - 1) return;
- hIndex += 1;
- applySnapshot(history[hIndex]);
- selectedId = null;
- saveState();
- renderSettings();
- if (mode === 'design') renderDesign();
- if (mode === 'summary') renderSummary();
- updateMeta();
- toast('已重做');
- }
- function renderSummary() {
- const p = renderProduct();
- const s = size();
- const design = sideData(summarySide);
- els.summarySideSwitch.querySelectorAll('button').forEach(function (b) {
- b.classList.toggle('on', b.dataset.side === summarySide);
- });
- els.summaryPreview.innerHTML = '<div class="bag-wrap">' + R.bagSVG(p, summarySide, design, { size: s, card: true, material: state.material, finish: state.finish }) + '</div>';
- els.summaryThumbs.innerHTML = ['front', 'back'].map(function (side) {
- return '<button class="summary-thumb ' + (side === summarySide ? 'on' : '') + '" data-summary-side="' + side + '">' +
- R.bagSVG(p, side, sideData(side), { size: s, card: true, material: state.material, finish: state.finish }) + '</button>';
- }).join('');
- const price = D.price(state);
- els.summaryOrder.innerHTML =
- '<div class="order-lines" style="margin-top:0;padding-top:0;border-top:0">' +
- priceLines().map(function (row) { return '<div class="order-line"><span>' + row[0] + '</span><b>' + row[1] + '</b></div>'; }).join('') +
- '<div class="order-line"><span>设计名称</span><b>' + esc(state.name) + '</b></div></div>' +
- '<div class="order-total"><span>合计</span><b>¥' + price.total.toFixed(2) + '<small> / ' + state.qty + ' 个</small></b></div>';
- const submit = $('#submitOrder');
- if (submit) submit.textContent = '提交订单 · ¥' + price.total.toFixed(2);
- updateMeta();
- }
- function downloadBlob(blob, filename) {
- const a = document.createElement('a');
- a.href = URL.createObjectURL(blob);
- a.download = filename;
- a.click();
- setTimeout(function () { URL.revokeObjectURL(a.href); }, 1500);
- }
- function roundedRectSegments(x, y, w, h, r, seg) {
- r = Math.max(0, Math.min(r, w / 2, h / 2));
- seg = seg || 8;
- const pts = [];
- function arc(cx, cy, a0, a1) {
- for (let i = 0; i <= seg; i += 1) {
- const a = a0 + (a1 - a0) * i / seg;
- pts.push([cx + Math.cos(a) * r, cy + Math.sin(a) * r]);
- }
- }
- pts.push([x + r, y]);
- pts.push([x + w - r, y]);
- arc(x + w - r, y + r, -Math.PI / 2, 0);
- pts.push([x + w, y + h - r]);
- arc(x + w - r, y + h - r, 0, Math.PI / 2);
- pts.push([x + r, y + h]);
- arc(x + r, y + h - r, Math.PI / 2, Math.PI);
- pts.push([x, y + r]);
- arc(x + r, y + r, Math.PI, Math.PI * 1.5);
- const segs = [];
- for (let i = 0; i < pts.length; i += 1) {
- const a = pts[i];
- const b = pts[(i + 1) % pts.length];
- if (Math.abs(a[0] - b[0]) < 1e-6 && Math.abs(a[1] - b[1]) < 1e-6) continue;
- segs.push([a[0], a[1], b[0], b[1]]);
- }
- return segs;
- }
- function exportBagDxf() {
- const p = product();
- const s = size();
- const pad = p.pad || { l: 12, r: 12, t: 34, b: 18 };
- const bleed = 3;
- const ox = pad.l + bleed;
- const oy = pad.t + bleed;
- let out = '0\nSECTION\n2\nENTITIES\n';
- function line(layer, x1, y1, x2, y2) {
- 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';
- }
- function add(layer, segs) { segs.forEach(function (g) { line(layer, g[0], g[1], g[2], g[3]); }); }
- const w = s.w + pad.l + pad.r;
- const h = s.h + pad.t + pad.b;
- add('CUT', roundedRectSegments(-pad.l, -pad.t, w, h, 6));
- add('BLEED', roundedRectSegments(-pad.l - bleed, -pad.t - bleed, w + bleed * 2, h + bleed * 2, 6 + bleed));
- line('PRINT', 0, 0, s.w, 0);
- line('PRINT', s.w, 0, s.w, s.h);
- line('PRINT', s.w, s.h, 0, s.h);
- line('PRINT', 0, s.h, 0, 0);
- line('FOLD', 0, -pad.t, 0, s.h + pad.b);
- line('FOLD', s.w, -pad.t, s.w, s.h + pad.b);
- line('FOLD', -pad.l, 0, s.w + pad.r, 0);
- line('FOLD', -pad.l, s.h, s.w + pad.r, s.h);
- out += '0\nENDSEC\n0\nEOF\n';
- downloadBlob(new Blob([out], { type: 'application/dxf' }), 'pouchlab-' + p.id + '-dieline.dxf');
- toast('刀版 DXF 已导出 · CUT/FOLD/BLEED');
- }
- function exportCurrent(opts) {
- opts = opts || {};
- const svgWidth = opts.width || 1400;
- const outWidth = opts.outWidth || 0;
- const p = renderProduct();
- const s = size();
- const side = mode === 'summary' ? summarySide : activeSide;
- const svg = R.bagSVG(p, side, sideData(side), { size: s, card: true, width: svgWidth, material: state.material, finish: state.finish });
- const blob = new Blob([svg], { type: 'image/svg+xml;charset=utf-8' });
- const url = URL.createObjectURL(blob);
- const img = new Image();
- img.onload = function () {
- const ratio = svgWidth / 1400;
- const pad = Math.round(90 * ratio);
- const footer = Math.round(150 * ratio);
- const baseW = img.width + pad * 2;
- const scale = outWidth ? outWidth / baseW : 1;
- const canvas = document.createElement('canvas');
- canvas.width = Math.round(baseW * scale);
- canvas.height = Math.round((img.height + pad + footer) * scale);
- const ctx = canvas.getContext('2d');
- ctx.scale(scale, scale);
- ctx.fillStyle = '#f6f2e9';
- ctx.fillRect(0, 0, canvas.width / scale, canvas.height / scale);
- ctx.drawImage(img, pad, pad, img.width, img.height);
- ctx.fillStyle = '#17140f';
- ctx.font = '700 24px "PingFang SC", "Helvetica Neue", sans-serif';
- ctx.fillText(state.name, pad, img.height + pad + 46);
- ctx.fillStyle = '#7d7466';
- ctx.font = '400 15px "PingFang SC", "Helvetica Neue", sans-serif';
- ctx.fillText(p.name + ' · ' + s.label + ' · ' + s.w + '×' + s.h + ' mm · ' + state.qty + ' 个 · ' + (side === 'front' ? '正面' : '背面'), pad, img.height + pad + 74);
- ctx.fillStyle = '#a79d8d';
- ctx.font = '400 12px "SF Mono", Menlo, monospace';
- ctx.fillText('STEADY PACKAGING · 300 DPI · ' + new Date().toLocaleDateString('zh-CN'), pad, img.height + pad + 100);
- URL.revokeObjectURL(url);
- canvas.toBlob(function (b) {
- downloadBlob(b, 'pouchlab-' + p.id + '-' + side + (opts.suffix || '') + '.png');
- toast(opts.label ? opts.label + '已下载' : '效果图已下载');
- }, 'image/png');
- };
- img.onerror = function () {
- URL.revokeObjectURL(url);
- downloadBlob(blob, 'pouchlab-' + p.id + '-' + side + '.svg');
- toast('已下载 SVG 文件');
- };
- img.src = url;
- }
- function open3d() {
- three.side = mode === 'summary' ? summarySide : activeSide;
- three.rot = three.side === 'front' ? -18 : 162;
- els.rotateRange.value = three.rot;
- els.modal3d.hidden = false;
- if (ensurePouchGL()) {
- updatePouchGL();
- return;
- }
- render3d();
- }
- /* ---- FBX 真实模型 3D 预览(pouch3d) ---- */
- let pouchGL = null;
- function ensurePouchGL() {
- if (!window.PL || !PL.pouch3d) return false;
- if (!pouchGL) {
- const stage = document.createElement('div');
- stage.id = 'pouchGL';
- stage.style.cssText = 'position:absolute;inset:0;z-index:2;';
- $('#scene3d').appendChild(stage);
- pouchGL = PL.pouch3d.create(stage, {
- onLoadError: function () {
- // GL 失败 → 回退 CSS 3D
- try { stage.remove(); } catch (e) {}
- pouchGL = null;
- if (els.pouch3d) els.pouch3d.style.display = '';
- render3d();
- }
- });
- }
- if (els.pouch3d) els.pouch3d.style.display = 'none';
- return true;
- }
- function updatePouchGL() {
- if (!pouchGL) return;
- const p = renderProduct();
- const s = size();
- const color = (state.bagColor || p.mockColor || '#e8e2d4');
- const shape = p.shape || 'standup';
- // 用户显式选择 open/closed 优先;未选择时按袋型默认(邮封袋→开口,其余→封口)
- const eff = three.modelMode || (shape === 'mailer' ? 'open' : 'closed');
- const sw = document.getElementById('pouchModelSwitch');
- if (sw) sw.querySelectorAll('button').forEach(function (x) {
- x.classList.toggle('on', x.dataset.model === eff);
- });
- pouchGL.load(eff, function () {
- pouchGL.applyDesign({
- color: color,
- frontDesign: previewDesignFor('front'),
- backDesign: previewDesignFor('back'),
- frontBg: previewDesignFor('front').bg || color,
- backBg: previewDesignFor('back').bg || color,
- W: s.w, H: s.h
- });
- pouchGL.setRotation(three.rot);
- });
- }
- function previewDesignFor(side) {
- const sd = sideData(side);
- if (sd.elements.length) return sd;
- const s = size();
- const t = D.templateById(sampleMap[product().id] || 'citrus');
- return R.designFromTemplate(t.id, s.w, s.h, side);
- }
- function render3d() {
- if (pouchGL && pouchGL.ready()) {
- updatePouchGL();
- els.rotateRange.value = three.rot;
- els.previewSideSwitch.querySelectorAll('button').forEach(function (b) {
- b.classList.toggle('on', (b.dataset.side === 'front' && three.rot > -90 && three.rot < 90) || (b.dataset.side === 'back' && (three.rot > 90 || three.rot < -90)));
- });
- return;
- }
- const p = renderProduct();
- const s = size();
- const front = R.bagSVG(p, 'front', previewDesignFor('front'), { size: s, tight: true, material: state.material, finish: state.finish });
- const back = R.bagSVG(p, 'back', previewDesignFor('back'), { size: s, tight: true, material: state.material, finish: state.finish });
- els.faceFront.innerHTML = front || '';
- els.faceBack.innerHTML = back || '';
- window.__r3d.push('written');
- const pad = p.pad;
- const aspect = (s.w + pad.l + pad.r) / (s.h + pad.t + pad.b);
- const sceneH = $('.scene').clientHeight || 440;
- const h = Math.min(400, Math.max(260, sceneH - 80));
- const w = clamp(h * aspect, 150, 360);
- els.pouch3d.style.height = h + 'px';
- els.pouch3d.style.width = w + 'px';
- // 侧面体积渐变:顶部封口薄暗 → 中下鼓面高光(膨鼓最饱满处 ~74%)→ 底部承重微暗,基色跟随袋色
- const sideVolume = function (lightPos) {
- return [
- 'radial-gradient(ellipse 120% 60% at 50% 74%, rgba(255,255,255,0.30), transparent 58%)',
- '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%)',
- 'linear-gradient(90deg,' + R.shade(p.mockColor, -0.30) + ',' + R.shade(p.mockColor, 0.14) + ' ' + lightPos + '%,' + R.shade(p.mockColor, -0.34) + ')'
- ].join(',');
- };
- els.faceSide.style.transform = 'rotateY(90deg) translateZ(' + (w / 2) + 'px)';
- els.faceSide.style.background = sideVolume(46);
- if (els.faceSideLeft) {
- els.faceSideLeft.style.transform = 'rotateY(-90deg) translateZ(' + (w / 2) + 'px)';
- els.faceSideLeft.style.background = sideVolume(54);
- }
- apply3dRotation();
- els.previewSideSwitch.querySelectorAll('button').forEach(function (b) {
- b.classList.toggle('on', (b.dataset.side === 'front' && three.rot > -90 && three.rot < 90) || (b.dataset.side === 'back' && (three.rot > 90 || three.rot < -90)));
- });
- }
- function apply3dRotation() {
- els.pouch3d.style.transform = 'rotateX(4deg) rotateY(' + three.rot + 'deg)';
- els.rotateRange.value = three.rot;
- }
- function close3d() {
- els.modal3d.hidden = true;
- }
- function goSummary() {
- if (!state.sides.front.elements.length && !state.sides.back.elements.length) {
- toast('先添加一些内容,再确认订单');
- return;
- }
- setMode('summary');
- }
- function nextStep() {
- if (mode === 'settings') enterDesign();
- else if (mode === 'design') goSummary();
- else {
- const form = $('#orderForm');
- if (form) {
- if (form.reportValidity()) form.requestSubmit();
- }
- }
- }
- function addUploadedFile(file) {
- if (!file || file.type.indexOf('image') !== 0) {
- toast('请选择图片文件');
- return;
- }
- if (file.size > 12 * 1024 * 1024) {
- toast('图片过大,请使用 12MB 以内的文件');
- return;
- }
- const reader = new FileReader();
- reader.onload = function () {
- const img = new Image();
- img.onload = function () {
- const max = 1400;
- let w = img.naturalWidth || img.width || 1000;
- let h = img.naturalHeight || img.height || 1000;
- if (!w || !h) { w = 1000; h = 1000; }
- if (Math.max(w, h) > max) {
- const k = max / Math.max(w, h);
- w = Math.round(w * k);
- h = Math.round(h * k);
- }
- const canvas = document.createElement('canvas');
- canvas.width = w;
- canvas.height = h;
- const ctx = canvas.getContext('2d');
- ctx.drawImage(img, 0, 0, w, h);
- const isPng = file.type === 'image/png' || file.type === 'image/svg+xml';
- const src = canvas.toDataURL(isPng ? 'image/png' : 'image/jpeg', 0.9);
- const up = { id: R.uid('up'), name: file.name, src: src, w: w, h: h };
- state.uploads.unshift(up);
- if (state.uploads.length > 12) state.uploads = state.uploads.slice(0, 12);
- addImageFromUpload(up);
- saveState(true);
- renderTool();
- };
- img.src = reader.result;
- };
- reader.readAsDataURL(file);
- }
- function pickUpload(replace) {
- const input = document.createElement('input');
- input.type = 'file';
- input.accept = 'image/png,image/jpeg,image/svg+xml,image/webp';
- input.onchange = function () {
- const file = input.files && input.files[0];
- if (!file) return;
- if (replace) {
- const el = selectedEl();
- if (!el) return;
- const reader = new FileReader();
- reader.onload = function () {
- el.src = reader.result;
- el.name = file.name;
- const img = new Image();
- img.onload = function () {
- el.h = el.w * (img.height / img.width);
- commit();
- renderCanvas();
- renderProps();
- };
- img.src = reader.result;
- };
- reader.readAsDataURL(file);
- } else {
- addUploadedFile(file);
- }
- };
- input.click();
- }
- function bindSettings() {
- els.settingsView.addEventListener('click', function (e) {
- const color = e.target.closest('[data-color]');
- if (color) { changeBagColor(color.dataset.color); }
- });
- }
- function bindTopbar() {
- els.continueBtn.addEventListener('click', nextStep);
- els.undoBtn.addEventListener('click', doUndo);
- els.redoBtn.addEventListener('click', doRedo);
- els.studioSteps.addEventListener('click', function (e) {
- const btn = e.target.closest('[data-step]');
- if (!btn) return;
- if (btn.dataset.step === 'summary' && mode !== 'summary') {
- if (!state.sides.front.elements.length && !state.sides.back.elements.length) {
- ensureSample();
- }
- setMode('summary');
- return;
- }
- setMode(btn.dataset.step);
- });
- els.designName.addEventListener('input', function () {
- state.name = this.value || '未命名设计';
- saveState(true);
- updateMeta();
- if (mode === 'summary') renderSummary();
- });
- els.designName.addEventListener('change', function () { commit(); });
- $('#preview3dBtn').addEventListener('click', open3d);
- }
- function bindDesign() {
- els.toolRail.addEventListener('click', function (e) {
- const btn = e.target.closest('[data-tool]');
- if (!btn) return;
- tool = btn.dataset.tool;
- renderTool();
- els.designView.classList.remove('panel-collapsed');
- els.designView.classList.add('panel-open');
- });
- els.sideSwitch.addEventListener('click', function (e) {
- const btn = e.target.closest('[data-side]');
- if (btn) changeSide(btn.dataset.side);
- });
- els.guidesToggle.addEventListener('change', function () {
- showGuides = this.checked;
- renderCanvas();
- });
- $('#zoomIn').addEventListener('click', function () { updateZoom(zoom * 1.18); });
- $('#zoomOut').addEventListener('click', function () { updateZoom(zoom / 1.18); });
- $('#zoomFit').addEventListener('click', function () { zoom = 1; renderCanvas(); });
- $('#downloadBtn').addEventListener('click', exportCurrent);
- const d4 = $('#download4kBtn');
- if (d4) d4.addEventListener('click', function () { exportCurrent({ width: 3600, outWidth: 3840, suffix: '-4k', label: '4K 效果图' }); });
- const ddxf = $('#downloadDxfBtn');
- if (ddxf) ddxf.addEventListener('click', exportBagDxf);
- $('#toolPanelClose').addEventListener('click', function () {
- els.designView.classList.remove('panel-open');
- els.designView.classList.add('panel-collapsed');
- });
- els.canvasEmpty.addEventListener('click', function (e) {
- const btn = e.target.closest('[data-empty-action]');
- if (!btn) return;
- tool = btn.dataset.emptyAction === 'upload' ? 'upload' : 'templates';
- renderTool();
- });
- els.toolBody.addEventListener('click', function (e) {
- const tpl = e.target.closest('[data-template]');
- if (tpl) { applyTemplate(tpl.dataset.template); return; }
- const preset = e.target.closest('[data-preset]');
- if (preset) { addTextPreset(preset.dataset.preset); return; }
- const font = e.target.closest('[data-font]');
- if (font) {
- const el = selectedEl();
- if (el && el.type === 'text') {
- el.font = font.dataset.font;
- lastFont = el.font;
- commit();
- renderCanvas();
- renderProps();
- } else {
- addTextPreset('body', font.dataset.font);
- }
- return;
- }
- const shape = e.target.closest('[data-shape]');
- if (shape) { addShape(shape.dataset.shape); return; }
- const sticker = e.target.closest('[data-sticker]');
- if (sticker) { addSticker(sticker.dataset.sticker); return; }
- const layer = e.target.closest('[data-layer]');
- if (layer && !e.target.closest('[data-eye]')) {
- selectedId = layer.dataset.layer;
- renderCanvas();
- renderProps();
- renderTool();
- return;
- }
- const eye = e.target.closest('[data-eye]');
- if (eye) {
- const el = allElements().find(function (x) { return x.id === eye.dataset.eye; });
- if (el) { el.hidden = !el.hidden; commit(); renderCanvas(); renderTool(); }
- return;
- }
- const rm = e.target.closest('[data-remove-upload]');
- if (rm) {
- state.uploads = state.uploads.filter(function (u) { return u.id !== rm.dataset.removeUpload; });
- commit();
- renderTool();
- return;
- }
- const uploadZone = e.target.closest('[data-action="pick-upload"]');
- if (uploadZone) { pickUpload(false); return; }
- const ins = e.target.closest('[data-size]');
- if (ins) { changeSize(ins.dataset.size); renderTool(); return; }
- const qty = e.target.closest('[data-qty]');
- if (qty) { changeSetting('qty', qty.dataset.qty); renderTool(); return; }
- const bagColor = e.target.closest('[data-bag-color]');
- if (bagColor) { changeBagColor(bagColor.dataset.bagColor); renderTool(); return; }
- const action = e.target.closest('[data-action]');
- if (action) {
- const a = action.dataset.action;
- if (a === 'settings') setMode('settings');
- if (a === 'clear-side') clearSide();
- if (a === 'dup-side') duplicateSide();
- }
- });
- els.toolBody.addEventListener('change', function (e) {
- if (e.target.id === 'toolMaterial') { changeSetting('material', e.target.value); renderTool(); }
- if (e.target.id === 'toolFinish') { changeSetting('finish', e.target.value); renderTool(); }
- });
- els.toolBody.addEventListener('dragover', function (e) {
- const zone = e.target.closest('.upload-zone');
- if (!zone) return;
- e.preventDefault();
- zone.classList.add('drag');
- });
- els.toolBody.addEventListener('dragleave', function (e) {
- const zone = e.target.closest('.upload-zone');
- if (zone) zone.classList.remove('drag');
- });
- els.toolBody.addEventListener('drop', function (e) {
- const zone = e.target.closest('.upload-zone');
- if (!zone) return;
- e.preventDefault();
- zone.classList.remove('drag');
- Array.from(e.dataTransfer.files).slice(0, 4).forEach(addUploadedFile);
- });
- els.propsClose.addEventListener('click', function () {
- selectedId = null;
- renderCanvas();
- renderProps();
- });
- els.propsBody.addEventListener('input', function (e) {
- const t = e.target;
- if (t.hasAttribute('data-toggle-guides')) {
- showGuides = t.checked;
- renderCanvas();
- return;
- }
- const bgCustom = t.closest('[data-bg-custom]');
- if (bgCustom) {
- sideData().bg = bgCustom.value;
- scheduleRenderCanvas();
- return;
- }
- const prop = t.dataset.prop;
- if (!prop) return;
- let v;
- if (t.type === 'checkbox') v = t.checked;
- else if (t.hasAttribute('data-num')) v = num(t.value, 0);
- else v = t.value;
- if (t.dataset.scale) v = Number(v);
- updateSelected(prop, v);
- const colorSpan = t.parentElement && t.parentElement.querySelector('span');
- if (t.type === 'color' && colorSpan) colorSpan.textContent = String(t.value).replace('#', '');
- });
- els.propsBody.addEventListener('change', function (e) {
- const t = e.target;
- if (t.hasAttribute('data-toggle-guides')) return;
- const bgCustom = t.closest('[data-bg-custom]');
- if (bgCustom) {
- sideData().bg = bgCustom.value;
- commit();
- renderCanvas();
- renderProps();
- return;
- }
- if (t.dataset.prop || t.type === 'color') {
- commit();
- renderTool();
- }
- });
- els.propsBody.addEventListener('click', function (e) {
- const prop = e.target.closest('[data-prop]');
- if (prop && (prop.type === 'color')) return;
- const weight = e.target.closest('[data-weight]');
- if (weight) { const el = selectedEl(); if (el) { el.weight = Number(weight.dataset.weight); commit(); renderCanvas(); renderProps(); } return; }
- const align = e.target.closest('[data-align]');
- if (align) { const el = selectedEl(); if (el) { el.align = align.dataset.align; commit(); renderCanvas(); renderProps(); } return; }
- const fit = e.target.closest('[data-fit]');
- if (fit) { const el = selectedEl(); if (el) { el.fit = fit.dataset.fit; commit(); renderCanvas(); renderProps(); } return; }
- const bg = e.target.closest('[data-bg]');
- if (bg) { sideData().bg = bg.dataset.bg || null; commit(); renderCanvas(); renderProps(); return; }
- const bagColor = e.target.closest('[data-bag-color]');
- if (bagColor) { changeBagColor(bagColor.dataset.bagColor); renderProps(); return; }
- const sideJump = e.target.closest('[data-side-jump]');
- if (sideJump) { changeSide(sideJump.dataset.sideJump); return; }
- const action = e.target.closest('[data-action]');
- if (action) {
- const a = action.dataset.action;
- if (a === 'raise') raiseElement();
- if (a === 'lower') lowerElement();
- if (a === 'duplicate') duplicateElement();
- if (a === 'delete') deleteElement();
- if (a === 'replace-image') pickUpload(true);
- if (a === 'clear-side') clearSide();
- if (a === 'dup-side') duplicateSide();
- }
- });
- els.canvasStage.addEventListener('pointerdown', onCanvasPointerDown);
- els.canvasStage.addEventListener('dblclick', function (e) {
- const g = e.target.closest('[data-id]');
- if (!g) return;
- const el = allElements().find(function (x) { return x.id === g.dataset.id; });
- if (el && el.type === 'text') {
- selectedId = el.id;
- renderCanvas();
- renderProps();
- openInlineText(el);
- }
- });
- els.inlineTextDone.addEventListener('click', commitInlineText);
- els.inlineTextArea.addEventListener('keydown', function (e) {
- if ((e.metaKey || e.ctrlKey) && e.key === 'Enter') { e.preventDefault(); commitInlineText(); }
- e.stopPropagation();
- });
- els.inlineTextArea.addEventListener('blur', function () {
- setTimeout(function () {
- if (document.activeElement !== els.inlineTextDone && document.activeElement !== els.inlineTextArea) commitInlineText();
- }, 120);
- });
- $('#summarySideSwitch').addEventListener('click', function (e) {
- const b = e.target.closest('[data-side]');
- if (!b) return;
- summarySide = b.dataset.side;
- renderSummary();
- });
- els.summaryThumbs.addEventListener('click', function (e) {
- const b = e.target.closest('[data-summary-side]');
- if (!b) return;
- summarySide = b.dataset.summarySide;
- renderSummary();
- });
- $('#backToDesign').addEventListener('click', function () { setMode('design'); });
- $('#summaryDownload').addEventListener('click', exportCurrent);
- const s4 = $('#summaryDownload4k');
- if (s4) s4.addEventListener('click', function () { exportCurrent({ width: 3600, outWidth: 3840, suffix: '-4k', label: '4K 效果图' }); });
- const sdxf = $('#summaryDownloadDxf');
- if (sdxf) sdxf.addEventListener('click', exportBagDxf);
- $('#summaryPreview3d').addEventListener('click', open3d);
- let orderSubmitting = false;
- function buildOrderPayload(data) {
- const p = product();
- const s = size();
- const mat = D.materialById(state.material);
- const fin = D.finishById(state.finish);
- const price = D.price(state);
- let design = null;
- try { design = JSON.parse(snapshot()); } catch (err) { design = null; }
- const payload = {
- type: 'bag',
- contact: {
- name: data.get('name') || '',
- phone: data.get('phone') || '',
- email: data.get('email') || '',
- address: data.get('address') || '',
- note: data.get('note') || ''
- },
- spec: {
- productId: p.id, productName: p.name,
- sizeId: state.sizeId, sizeLabel: s.label, w: s.w, h: s.h,
- material: state.material, materialName: mat ? mat.name : state.material,
- finish: state.finish, finishName: fin ? fin.name : state.finish,
- qty: state.qty
- },
- quote: { unit: price.unit, total: price.total },
- summary: p.name + ' ' + s.w + '×' + s.h + 'mm · ' + (mat ? mat.name : '') + ' · ' + state.qty + ' 只',
- design: design,
- dieline: {
- kind: 'bag', bleed: 3,
- faces: [{ key: 'front', w: s.w, h: s.h }, { key: 'back', w: s.w, h: s.h }],
- meta: { productName: p.name, material: mat ? mat.name : '', finish: fin ? fin.name : '', qty: state.qty }
- },
- previews: {}
- };
- return Promise.all(['front', 'back'].map(function (side) {
- const svg = R.bagSVG(renderProduct(), side, sideData(side), { size: s, card: true, width: 900, material: state.material, finish: state.finish });
- return PL.api.svgToPng(svg, 900);
- })).then(function (pngs) {
- payload.previews = { front: pngs[0], back: pngs[1] };
- return payload;
- }, function () {
- return payload; // 预览图失败不阻塞下单
- });
- }
- function finishSubmit(orderNo, offline) {
- orderSubmitting = false;
- const btn = $('#submitOrder');
- btn.disabled = false;
- btn.textContent = '提交订单';
- els.orderNumber.textContent = orderNo;
- const tip = document.getElementById('successTip');
- if (tip) tip.hidden = !offline;
- els.successView.hidden = false;
- toast(offline ? '订单已离线保存(服务器不可达)' : '订单已提交,可前往「我的订单」支付');
- }
- $('#orderForm').addEventListener('submit', function (e) {
- e.preventDefault();
- if (window.PL.auth && !window.PL.auth.user()) {
- window.PL.auth.require(function () { $('#orderForm').requestSubmit(); });
- return;
- }
- const form = this;
- const data = new FormData(form);
- if (!data.get('name') || !data.get('phone') || !data.get('address')) {
- form.reportValidity();
- return;
- }
- if (orderSubmitting) return;
- if (!window.PL || !PL.api) return;
- orderSubmitting = true;
- const btn = $('#submitOrder');
- btn.disabled = true;
- btn.textContent = '正在提交订单…';
- let orderPayload = null;
- buildOrderPayload(data).then(function (payload) {
- orderPayload = payload;
- return PL.api.post('/orders', payload, { timeout: 60000 });
- }).then(function (r) {
- finishSubmit(r.orderNo, false);
- }, function (err) {
- if (err && err.network) {
- // 离线回退:本地保存完整订单信息,联网后可在「我的订单」查看
- const n = 'PL-' + String(new Date().getFullYear()) + String(Date.now()).slice(-6);
- try {
- localStorage.setItem('pouchlab.order.' + n, JSON.stringify({
- name: data.get('name'), phone: data.get('phone'), email: data.get('email'),
- address: data.get('address') || '', note: data.get('note'),
- order: n, total: D.price(state).total, qty: state.qty,
- summary: orderPayload ? orderPayload.summary : '',
- spec: orderPayload ? orderPayload.spec : null,
- previews: orderPayload ? orderPayload.previews : {},
- design: snapshot(), at: Date.now()
- }));
- } catch (e2) {}
- finishSubmit(n, true);
- return;
- }
- orderSubmitting = false;
- btn.disabled = false;
- btn.textContent = '提交订单';
- toast(err.message || '订单提交失败,请重试');
- });
- });
- $('#successBack').addEventListener('click', function () { location.href = 'index.html'; });
- els.modal3d.addEventListener('click', function (e) {
- if (e.target.closest('[data-close="3d"]')) close3d();
- });
- $('#pouchModelSwitch').addEventListener('click', function (e) {
- const b = e.target.closest('[data-model]');
- if (!b) return;
- three.modelMode = b.dataset.model;
- this.querySelectorAll('button').forEach(function (x) {
- x.classList.toggle('on', x === b);
- });
- if (pouchGL && pouchGL.ready()) updatePouchGL();
- });
- $('#previewSideSwitch').addEventListener('click', function (e) {
- const b = e.target.closest('[data-side]');
- if (!b) return;
- three.rot = b.dataset.side === 'front' ? -18 : 162;
- if (pouchGL && pouchGL.ready()) {
- pouchGL.setRotation(three.rot);
- els.previewSideSwitch.querySelectorAll('button').forEach(function (x) {
- x.classList.toggle('on', x.dataset.side === b.dataset.side);
- });
- return;
- }
- apply3dRotation();
- render3d();
- });
- els.rotateRange.addEventListener('input', function () {
- three.rot = Number(this.value);
- if (pouchGL && pouchGL.ready()) {
- pouchGL.setRotation(three.rot);
- els.previewSideSwitch.querySelectorAll('button').forEach(function (b) {
- b.classList.toggle('on', (b.dataset.side === 'front' && three.rot > -90 && three.rot < 90) || (b.dataset.side === 'back' && (three.rot > 90 || three.rot < -90)));
- });
- return;
- }
- apply3dRotation();
- els.previewSideSwitch.querySelectorAll('button').forEach(function (b) {
- b.classList.toggle('on', (b.dataset.side === 'front' && three.rot > -90 && three.rot < 90) || (b.dataset.side === 'back' && (three.rot > 90 || three.rot < -90)));
- });
- });
- const scene = $('#scene3d');
- let rotDrag = null;
- scene.addEventListener('pointerdown', function (e) {
- if (pouchGL && pouchGL.ready()) return; // GL 模式由模型画布自行处理拖拽
- rotDrag = { x: e.clientX, rot: three.rot };
- scene.setPointerCapture(e.pointerId);
- });
- scene.addEventListener('pointermove', function (e) {
- if (!rotDrag) return;
- three.rot = clamp(rotDrag.rot + (e.clientX - rotDrag.x) * 0.45, -180, 180);
- apply3dRotation();
- });
- scene.addEventListener('pointerup', function () { rotDrag = null; });
- scene.addEventListener('pointercancel', function () { rotDrag = null; });
- }
- /* 参考潘通色网格(防侵权叫法:不称潘通色;实际以打样效果为准) */
- function pmsGrid(onPick, currentHex) {
- const P = window.PL.pantone;
- const cur = (currentHex || '').toLowerCase();
- return [
- h('div', { className: 'pms-grid' }, P.list.map(function (c) {
- return h('button', {
- key: c.code, type: 'button',
- className: 'pms-dot' + (cur === c.hex.toLowerCase() ? ' on' : ''),
- title: '参考潘通色 ' + c.code + ' ' + c.name,
- style: { background: c.hex },
- onClick: function () { onPick(c); }
- });
- })),
- h('div', { className: 'pms-note' }, P.note)
- ];
- }
- function pointInElement(el, pt) {
- const box = R.elementBox(el);
- const rot = -(el.rotation || 0) * Math.PI / 180;
- const cx = box.w / 2;
- const cy = box.h / 2;
- const dx = pt.x - el.x - cx;
- const dy = pt.y - el.y - cy;
- const rx = Math.cos(rot) * dx - Math.sin(rot) * dy + cx;
- const ry = Math.sin(rot) * dx + Math.cos(rot) * dy + cy;
- return rx >= 0 && rx <= box.w && ry >= 0 && ry <= box.h;
- }
- function onCanvasPointerDown(e) {
- if (e.button !== 0) return;
- const svg = els.canvasStage.querySelector('svg');
- if (!svg) return;
- const handle = e.target.closest('[data-handle]');
- if (handle && selectedId) {
- e.preventDefault();
- startTransform(e, svg, handle.dataset.handle);
- return;
- }
- const group = e.target.closest('[data-id]');
- if (group) {
- let id = group.dataset.id;
- if (e.altKey && selectedId) {
- const pt = svgPoint(e, svg);
- const hits = allElements().filter(function (el) { return !el.hidden && pointInElement(el, pt); });
- if (hits.length > 1) {
- const idx = hits.findIndex(function (x) { return x.id === selectedId; });
- id = hits[(idx + 1) % hits.length].id;
- }
- }
- if (selectedId !== id) {
- selectedId = id;
- renderCanvas();
- renderProps();
- renderTool();
- }
- const el = selectedEl();
- if (!el) return;
- const liveSvg = els.canvasStage.querySelector('svg');
- startDrag(e, liveSvg, el);
- return;
- }
- selectedId = null;
- renderCanvas();
- renderProps();
- renderTool();
- }
- function svgPoint(e, svg) {
- const pt = svg.createSVGPoint();
- pt.x = e.clientX;
- pt.y = e.clientY;
- const m = svg.getScreenCTM();
- if (!m) return { x: 0, y: 0 };
- return pt.matrixTransform(m.inverse());
- }
- function setElementTransform(el) {
- const g = els.canvasStage.querySelector('[data-id="' + el.id + '"]');
- if (!g) return;
- const box = R.elementBox(el);
- g.setAttribute('transform', 'translate(' + el.x + ' ' + el.y + ') rotate(' + (el.rotation || 0) + ' ' + (box.w / 2) + ' ' + (box.h / 2) + ')');
- const sel = els.canvasStage.querySelector('.sel-overlay');
- if (sel) sel.setAttribute('transform', 'translate(' + el.x + ' ' + el.y + ') rotate(' + (el.rotation || 0) + ' ' + (box.w / 2) + ' ' + (box.h / 2) + ')');
- }
- function setDragGuides(gx, gy) {
- const svg = els.canvasStage.querySelector('svg');
- if (!svg) return;
- svg.querySelectorAll('.drag-guide').forEach(function (n) { n.remove(); });
- const p = product().pad;
- const s = size();
- const NS = 'http://www.w3.org/2000/svg';
- if (gx != null) {
- const l = document.createElementNS(NS, 'line');
- l.setAttribute('class', 'drag-guide');
- l.setAttribute('x1', gx); l.setAttribute('x2', gx);
- l.setAttribute('y1', -p.t - 6); l.setAttribute('y2', s.h + p.b + 6);
- l.setAttribute('data-uistroke', '1');
- l.setAttribute('stroke-width', '0.5');
- l.setAttribute('stroke-dasharray', '2 2');
- l.setAttribute('data-ui', '1');
- svg.appendChild(l);
- }
- if (gy != null) {
- const l = document.createElementNS(NS, 'line');
- l.setAttribute('class', 'drag-guide');
- l.setAttribute('y1', gy); l.setAttribute('y2', gy);
- l.setAttribute('x1', -p.l - 6); l.setAttribute('x2', s.w + p.r + 6);
- l.setAttribute('data-uistroke', '1');
- l.setAttribute('stroke-width', '0.5');
- l.setAttribute('stroke-dasharray', '2 2');
- l.setAttribute('data-ui', '1');
- svg.appendChild(l);
- }
- }
- function startDrag(e, svg, el) {
- isDragging = true;
- const liveSvg = function () { return els.canvasStage.querySelector('svg') || svg; };
- const start = svgPoint(e, liveSvg());
- const orig = { x: el.x, y: el.y };
- const box = R.elementBox(el);
- const s = size();
- let moved = false;
- let lastGx = null;
- let lastGy = null;
- function move(ev) {
- const p = svgPoint(ev, liveSvg());
- let dx = p.x - start.x;
- let dy = p.y - start.y;
- if (ev.shiftKey) {
- if (Math.abs(dx) > Math.abs(dy)) dy = 0; else dx = 0;
- }
- let x = orig.x + dx;
- let y = orig.y + dy;
- let gx = null;
- let gy = null;
- const tol = 2.2;
- const cx = x + box.w / 2;
- const cy = y + box.h / 2;
- if (Math.abs(cx - s.w / 2) < tol) { x = s.w / 2 - box.w / 2; gx = s.w / 2; }
- if (Math.abs(y) < tol) { y = 0; gy = 0; }
- if (Math.abs(x) < tol) { x = 0; gx = 0; }
- if (Math.abs(x + box.w - s.w) < tol) { x = s.w - box.w; gx = s.w; }
- if (Math.abs(cy - s.h / 2) < tol) { y = s.h / 2 - box.h / 2; gy = s.h / 2; }
- if (Math.abs(y + box.h - s.h) < tol) { y = s.h - box.h; gy = s.h; }
- if (x !== el.x || y !== el.y) moved = true;
- el.x = x; el.y = y;
- setElementTransform(el);
- if (gx !== lastGx || gy !== lastGy) {
- lastGx = gx; lastGy = gy;
- setDragGuides(gx, gy);
- }
- }
- function up() {
- document.removeEventListener('pointermove', move);
- document.removeEventListener('pointerup', up);
- isDragging = false;
- setDragGuides(null, null);
- if (moved) {
- commit();
- const xIn = els.propsBody.querySelector('[data-prop="x"]');
- const yIn = els.propsBody.querySelector('[data-prop="y"]');
- if (xIn) xIn.value = mm(el.x);
- if (yIn) yIn.value = mm(el.y);
- renderTool();
- }
- }
- document.addEventListener('pointermove', move);
- document.addEventListener('pointerup', up);
- e.preventDefault();
- }
- function startTransform(e, svg, handle) {
- const el = selectedEl();
- if (!el) return;
- isDragging = true;
- const box = R.elementBox(el);
- const start = svgPoint(e, svg);
- const orig = {
- x: el.x, y: el.y, w: el.w, h: el.h, size: el.size || 0,
- rotation: el.rotation || 0, cx: el.x + box.w / 2, cy: el.y + box.h / 2
- };
- const s = size();
- const rot = orig.rotation * Math.PI / 180;
- let moved = false;
- function move(ev) {
- const p = svgPoint(ev, els.canvasStage.querySelector('svg'));
- const dx = p.x - start.x;
- const dy = p.y - start.y;
- moved = true;
- if (handle === 'rot') {
- const ang = Math.atan2(p.y - orig.cy, p.x - orig.cx) * 180 / Math.PI;
- let next = ang - Math.atan2(start.y - orig.cy, start.x - orig.cx) * 180 / Math.PI + orig.rotation;
- if (ev.shiftKey) next = Math.round(next / 15) * 15;
- el.rotation = next;
- setElementTransform(el);
- return;
- }
- const lx = dx * Math.cos(rot) + dy * Math.sin(rot);
- const ly = -dx * Math.sin(rot) + dy * Math.cos(rot);
- if (el.type === 'text' && (handle === 'w' || handle === 'e')) {
- const nw = Math.max(4, orig.w + (handle === 'e' ? lx : -lx));
- el.w = nw;
- if (handle === 'w') el.x = orig.x + (orig.w - nw);
- renderCanvas();
- return;
- }
- if (el.type === 'text') {
- const factor = clamp((orig.w + (handle === 'w' || handle === 'nw' || handle === 'sw' ? -lx : lx)) / Math.max(4, orig.w), 0.2, 6);
- el.w = Math.max(4, orig.w * factor);
- el.size = Math.max(2, orig.size * factor);
- if (handle === 'w' || handle === 'nw' || handle === 'sw') el.x = orig.x + orig.w - el.w;
- renderCanvas();
- return;
- }
- let nw = orig.w;
- let nh = orig.h;
- let nx = orig.x;
- let ny = orig.y;
- if (handle === 'e' || handle === 'ne' || handle === 'se') nw = orig.w + lx;
- if (handle === 'w' || handle === 'nw' || handle === 'sw') { nw = orig.w - lx; nx = orig.x + lx; }
- if (handle === 's' || handle === 'se' || handle === 'sw') nh = orig.h + ly;
- if (handle === 'n' || handle === 'ne' || handle === 'nw') { nh = orig.h - ly; ny = orig.y + ly; }
- nw = Math.max(3, nw);
- nh = Math.max(3, nh);
- if (ev.shiftKey && (handle === 'nw' || handle === 'ne' || handle === 'sw' || handle === 'se')) {
- const aspect = orig.w / Math.max(0.1, orig.h);
- if (nw / nh > aspect) nw = nh * aspect; else nh = nw / aspect;
- if (handle === 'nw' || handle === 'sw') nx = orig.x + orig.w - nw;
- if (handle === 'nw' || handle === 'ne') ny = orig.y + orig.h - nh;
- }
- if (el.type === 'sticker' || el.type === 'badge' || el.type === 'qr' || el.type === 'asset') {
- nh = nw;
- if (handle === 'nw' || handle === 'ne') ny = orig.y + orig.h - nh;
- }
- if (el.type === 'shape' && el.shape === 'line') nh = Math.max(3, orig.h);
- el.w = nw;
- if (el.type !== 'badge' && el.type !== 'qr') el.h = nh;
- el.x = nx;
- el.y = ny;
- renderCanvas();
- }
- function up() {
- document.removeEventListener('pointermove', move);
- document.removeEventListener('pointerup', up);
- isDragging = false;
- if (moved) {
- commit();
- renderProps();
- renderTool();
- }
- }
- document.addEventListener('pointermove', move);
- document.addEventListener('pointerup', up);
- e.preventDefault();
- e.stopPropagation();
- }
- function bindKeys() {
- // 图层面板拖拽排序(按住行上下拖,松手落位;兼容 pointer / mouse / 合成拖拽)
- let layerDrag = null;
- function layerDragStart(row, e) {
- if (!row || !row.dataset.layerId || layerDrag) return;
- if (e.target && e.target.closest && e.target.closest('button')) return;
- layerDrag = { id: row.dataset.layerId, row: row, startY: e.clientY, moved: false, target: null };
- }
- function layerDragMoveListen(e) {
- if (!layerDrag && (e.buttons & 1) === 1) {
- const row = e.target.closest && e.target.closest('.layer-row');
- layerDragStart(row, e);
- }
- if (!layerDrag) return;
- if (!layerDrag.moved && Math.abs(e.clientY - layerDrag.startY) <= 4) return;
- if (!layerDrag.moved) layerDrag.row.classList.add('dragging');
- layerDrag.moved = true;
- if (e.cancelable) e.preventDefault();
- const list = document.querySelector('.layer-list');
- if (!list) return;
- const rows = [...list.querySelectorAll('.layer-row')];
- rows.forEach(function (r) { r.classList.remove('drop-above', 'drop-below'); });
- let target = null;
- for (let i = 0; i < rows.length; i += 1) {
- const r = rows[i];
- if (r === layerDrag.row || !r.dataset.layerId) continue;
- const rc = r.getBoundingClientRect();
- if (e.clientY >= rc.top && e.clientY <= rc.bottom) {
- target = { row: r, above: e.clientY < rc.top + rc.height / 2 };
- break;
- }
- }
- if (target) target.row.classList.add(target.above ? 'drop-above' : 'drop-below');
- // 即时落位:跨过插入线立即排序(无需等待松手)
- const tid = target ? target.row.dataset.layerId : null;
- if (target && (layerDrag.lastTargetId !== tid || layerDrag.lastAbove !== target.above)) {
- layerDrag.lastTargetId = tid;
- layerDrag.lastAbove = target.above;
- reorderElement(layerDrag.id, tid, target.above);
- layerDragCleanupS();
- layerDrag.row = document.querySelector('.layer-row[data-layer-id="' + layerDrag.id + '"]');
- } else if (!target) {
- layerDrag.lastTargetId = null;
- }
- }
- function layerDragEndListen() {
- if (!layerDrag) return;
- layerDrag = null;
- document.querySelectorAll('.layer-row').forEach(function (r) {
- r.classList.remove('dragging', 'drop-above', 'drop-below');
- });
- }
- function layerDragCleanupS() {
- document.querySelectorAll('.layer-row').forEach(function (r) {
- r.classList.remove('dragging', 'drop-above', 'drop-below');
- });
- }
- document.addEventListener('pointerdown', function (e) {
- if (layerDrag) { layerDragCleanupS(); layerDrag = null; }
- const row = e.target.closest && e.target.closest('.layer-row');
- layerDragStart(row, e);
- });
- document.addEventListener('mousedown', function (e) {
- if (layerDrag) { layerDragCleanupS(); layerDrag = null; }
- const row = e.target.closest && e.target.closest('.layer-row');
- layerDragStart(row, e);
- });
- document.addEventListener('pointermove', layerDragMoveListen, { passive: false });
- document.addEventListener('mousemove', layerDragMoveListen, { passive: false });
- document.addEventListener('pointerup', layerDragEndListen);
- document.addEventListener('mouseup', layerDragEndListen);
- // AI 排版悬浮入口
- const aiFab = document.createElement('button');
- aiFab.id = 'plAiFab';
- aiFab.type = 'button';
- aiFab.title = 'AI 排版(登录后可用)';
- aiFab.innerHTML = '✨<span>AI 排版</span>';
- document.body.appendChild(aiFab);
- aiFab.addEventListener('click', function () { aiPanelToggle(); });
- document.addEventListener('keydown', function (e) {
- const tag = (document.activeElement && document.activeElement.tagName) || '';
- const typing = tag === 'INPUT' || tag === 'TEXTAREA' || tag === 'SELECT' || document.activeElement.isContentEditable;
- if (e.key === 'Escape') {
- if (!els.modal3d.hidden) { close3d(); return; }
- hideInlineText();
- selectedId = null;
- if (mode === 'design') { renderCanvas(); renderProps(); renderTool(); }
- return;
- }
- if (typing && !((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === 's')) return;
- if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === 'z') {
- e.preventDefault();
- if (e.shiftKey) doRedo(); else doUndo();
- return;
- }
- if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === 's') {
- e.preventDefault();
- saveState();
- toast('设计已保存到本地');
- return;
- }
- if (mode !== 'design') return;
- if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === 'd') {
- e.preventDefault();
- duplicateElement();
- return;
- }
- if (e.key === 'Delete' || e.key === 'Backspace') {
- if (selectedId) { e.preventDefault(); deleteElement(); }
- return;
- }
- if (e.key.indexOf('Arrow') === 0 && selectedId) {
- e.preventDefault();
- const el = selectedEl();
- if (!el) return;
- const step = e.shiftKey ? 10 : 1;
- if (e.key === 'ArrowLeft') el.x -= step;
- if (e.key === 'ArrowRight') el.x += step;
- if (e.key === 'ArrowUp') el.y -= step;
- if (e.key === 'ArrowDown') el.y += step;
- saveState();
- renderCanvas();
- const xIn = els.propsBody.querySelector('[data-prop="x"]');
- const yIn = els.propsBody.querySelector('[data-prop="y"]');
- if (xIn) xIn.value = mm(el.x);
- if (yIn) yIn.value = mm(el.y);
- return;
- }
- if (e.key === 'Enter' && selectedId) {
- const el = selectedEl();
- if (el && el.type === 'text') { e.preventDefault(); openInlineText(el); }
- }
- });
- document.addEventListener('paste', function (e) {
- if (mode !== 'design') return;
- const items = e.clipboardData && e.clipboardData.items;
- if (!items) return;
- for (let i = 0; i < items.length; i += 1) {
- if (items[i].type.indexOf('image') === 0) {
- const file = items[i].getAsFile();
- if (file) { addUploadedFile(file); e.preventDefault(); break; }
- }
- }
- });
- let resizeTimer;
- window.addEventListener('resize', function () {
- clearTimeout(resizeTimer);
- resizeTimer = setTimeout(function () {
- if (mode === 'design' && !isDragging) renderCanvas();
- if (!els.modal3d.hidden) render3d();
- }, 160);
- });
- }
- function initFromURL() {
- const params = new URLSearchParams(location.search);
- const templateId = params.get('template');
- const productId = params.get('product');
- const toolParam = params.get('tool');
- const modeParam = params.get('mode');
- if (templateId) {
- const t = D.templateById(templateId);
- if (t) {
- state.productId = t.product;
- const p = product();
- state.sizeId = p.sizes[Math.floor((p.sizes.length - 1) / 2)].id;
- state.sampleApplied = true;
- applyTemplate(templateId, { silent: true });
- state.name = t.name + ' 设计';
- els.designName.value = state.name;
- mode = 'design';
- skipSample = true;
- return;
- }
- }
- if (productId) {
- const p = D.productById(productId);
- if (p) {
- const oldS = size();
- const oldP = product();
- const newS = D.sizeOf(p, p.sizes[Math.floor((p.sizes.length - 1) / 2)].id);
- if (p.id !== oldP.id) {
- if (state.sides.front.elements.length || state.sides.back.elements.length) scaleSides(oldS, newS);
- state.productId = p.id;
- state.sizeId = newS.id;
- state.bagColor = null;
- }
- }
- }
- if (toolParam) {
- tool = ['product', 'templates', 'upload', 'text', 'shapes', 'layers'].indexOf(toolParam) >= 0 ? toolParam : 'product';
- mode = 'design';
- skipSample = toolParam === 'upload';
- return;
- }
- if (modeParam && ['settings', 'design', 'summary'].indexOf(modeParam) >= 0) {
- mode = modeParam;
- return;
- }
- mode = 'settings';
- }
- function init() {
- els.designName.value = state.name;
- initFromURL();
- if (mode === 'design' && !state.sampleApplied && !skipSample) ensureSample();
- history = [snapshot()];
- hIndex = 0;
- bindSettings();
- bindTopbar();
- bindDesign();
- bindKeys();
- renderSettings();
- if (mode === 'design') {
- setMode('design');
- } else if (mode === 'summary') {
- setMode('summary');
- } else {
- setMode('settings');
- }
- updateMeta();
- saveState(true);
- }
- init();
- })();
|