Download app.js from Franmer/shop: direct link, hf CLI and curl.
- Browser
- Download file 19.8 kB
-
https://huggingface.co/spaces/Franmer/shop/resolve/main/app.js
- Command line
-
hf download hf://spaces/Franmer/shop/app.js
-
curl -L -o app.js https://huggingface.co/spaces/Franmer/shop/resolve/main/app.js
19.8 kB
| { | |
| const $0=id=>document.getElementById(id);document.querySelector('.mast .wrap').insertAdjacentHTML('beforeend','<button class="cartb" id="cartb" aria-label="Корзина"><svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M3 4h2l2.4 11h11L21 7H6.2"/><circle cx="9" cy="19.5" r="1.5"/><circle cx="17" cy="19.5" r="1.5"/></svg><b id="cartn" hidden></b></button>');$0('catalog').insertAdjacentHTML('beforebegin','<div class="bar" id="bar"><div class="wrap"><label class="search"><svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2"><circle cx="11" cy="11" r="7"/><path d="m20 20-4-4"/></svg><input id="q" type="search" placeholder="Модель, бренд или название" autocomplete="off" aria-label="Поиск"><button class="x" id="qx" hidden aria-label="Очистить">×</button></label><div class="flags" id="flags"></div></div></div>');$0('ttl').insertAdjacentHTML('afterend','<select id="sort" aria-label="Сортировка"><option value="ph">Рекомендуемые</option><option value="lo">Сначала дешевле</option><option value="hi">Сначала дороже</option><option value="az">По названию</option></select>');document.body.insertAdjacentHTML('beforeend','<div class="cartbar" id="cartbar" hidden><button id="cartgo"><span id="cartbt">Корзина</span><span>Оформить →</span></button></div><dialog id="cdlg" aria-labelledby="ch"><div class="dtop"><span id="ch">Корзина</span><button class="ib" id="cclose" aria-label="Закрыть">×</button></div><div class="dbody"><div id="cbody"></div><form class="of" id="of" novalidate hidden><label>Имя<input id="oname" autocomplete="name" required></label><label>Телефон<input id="ophone" type="tel" autocomplete="tel" inputmode="tel" required placeholder="+7"></label><label>Эл. почта, если удобно<input id="omail" type="email" autocomplete="email"></label><label>Адрес доставки или комментарий<textarea id="ocom" rows="2"></textarea></label><p class="err" id="oerr" hidden></p><div class="obtn"><button class="go" type="submit">Отправить заказ</button><button type="button" id="ocopy">Скопировать заказ</button></div><p class="ohow">Заказ придёт менеджеру на почту, он перезвонит и подтвердит наличие и цену. Если не получится отправить, позвоните +7 (495) 545-49-60.</p><div class="done" id="odone" hidden></div></form></div></dialog><dialog id="dlg"><div class="dtop"><span id="dpos"></span><button class="ib" id="prev" aria-label="Предыдущий">‹</button><button class="ib" id="next" aria-label="Следующий">›</button><button class="ib" id="close" aria-label="Закрыть">×</button></div><div class="dph" id="dph"></div><div class="dbody" id="dbody"></div></dialog>'); | |
| const $=id=>document.getElementById(id); | |
| const SL={"pump": "nasosy-dlya-basseyna.html", "filter": "filtry-dlya-basseyna.html", "treat": "dezinfekciya-vody-basseyna.html", "chem": "himiya-dlya-basseyna.html", "water": "skimmery-forsunki-dlya-basseyna.html", "light": "prozhektory-dlya-basseyna.html", "electrical": "avtomatika-dlya-basseyna.html", "heat": "teploobmenniki-i-nagrevateli-dlya-basseyna.html", "jets": "protivotoki-i-gidromassazh-dlya-basseyna.html", "cover": "pokryvala-dlya-basseyna.html", "access": "lestnicy-dlya-basseyna.html", "plumbing": "armatura-dlya-basseyna.html", "p": "zapchasti-dlya-basseyna.html", "u": "bu-oborudovanie-dlya-basseyna.html", "s": "rasprodazha-oborudovaniya-dlya-basseyna.html", "spare": "zapchasti-dlya-basseyna.html"},B=document.body.dataset; | |
| const esc=s=>String(s??'').replace(/[&<>"']/g,c=>({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c])); | |
| const rub=n=>Math.round(n).toLocaleString('ru-RU').replace(/\s/g,' ')+' ₽'; | |
| const ICON='<svg viewBox="0 0 48 48" fill="none" stroke="currentColor" stroke-width="2"><rect x="6" y="10" width="36" height="28"/><path d="M6 30c5-4 9-4 12 0s8 4 12 0 8-4 12 0"/><circle cx="17" cy="20" r="3"/></svg>'; | |
| const PAGE=24; | |
| let D,G={},list=[],shown=PAGE,cur=-1; | |
| const st={q:'',flags:new Set(B.f?[B.f]:[]),g:B.g||'all',sort:'ph'}; | |
| const FL=[['u','Б/у','sale'],['p','Запчасти','']]; | |
| const spec=x=>!!x.sa&&x.rp!=null; | |
| const hasPh=x=>!!x.img; | |
| const FT={u:x=>!!x.u&&!spec(x),s:x=>spec(x),pr:x=>price(x)!=null,p:x=>!!x.p}; | |
| const old=x=>!spec(x)&&x.pr==null&&x.np!=null?x.np:null; | |
| let RT={}; | |
| // везде розница, без скидок; не ниже закупки (цена сайта pr) | |
| const price=x=>{const r=RT[x.id];let v=r&&r.r?r.r:spec(x)?x.rp:x.pr!=null?x.pr:old(x);if(v==null)return null;if(x.pr!=null&&v<x.pr)v=x.pr;return Math.round(v)}; | |
| function pic(x,big){ | |
| if(!hasPh(x))return '<div class="nop">'+ICON+'<span>Фото скоро будет</span></div>'; | |
| return '<img '+(big?'':'loading="lazy" ')+'src="'+esc(x.img)+'" alt="'+esc(x.n)+'" onerror="this.outerHTML=\'<div class=nop><span>Фото скоро будет</span></div>\'">'; | |
| } | |
| function prHtml(x,cls,big){ | |
| if(price(x)!=null)return '<p class="'+cls+'">'+rub(price(x))+'</p>'; | |
| return '<p class="'+cls+' none">Цена по запросу</p>'; | |
| } | |
| function match(x){ | |
| if(st.g!=='all'&&x.g!==st.g)return false; | |
| for(const f of st.flags){if(f==='s'&&!spec(x))return false;if(f==='pr'&&price(x)==null)return false;if(f==='u'&&(!x.u||spec(x)))return false;if(f==='p'&&!x.p)return false} | |
| if(st.q){const w=st.q.toLowerCase().split(/\s+/).filter(Boolean),h=(x.n+' '+(x.c||'')+' '+(x.u&&!spec(x)?'б/у бу':'')+' '+G[x.g]).toLowerCase();if(!w.every(t=>h.includes(t)))return false} | |
| return true; | |
| } | |
| function card(x,i){ | |
| return '<div class="card"><button class="open" data-i="'+i+'"><div class="ph">'+pic(x)+(x.u?'<span class="used">Б/у</span>':'')+'</div><div class="body"><div class="meta"><span>'+esc(G[x.g])+'</span>'+(x.c?'<span>· '+esc(x.c)+'</span>':'')+'</div><div class="nm">'+esc(x.n)+'</div>'+prHtml(x,'pr')+stk(x,'stk')+'</div></button><div class="buy" data-id="'+esc(x.id)+'">'+buyHtml(x)+'</div></div>'; | |
| } | |
| function render(){ | |
| list=D.items.filter(match); | |
| const s=st.sort,by=(a,b)=>a.n.localeCompare(b.n,'ru'); | |
| list.sort(s==='ph'?(a,b)=>(!!b.u&&!spec(b))-(!!a.u&&!spec(a))||spec(b)-spec(a)||hasPh(b)-hasPh(a)||(price(b)!=null)-(price(a)!=null)||by(a,b):s==='az'?by:(a,b)=>{const pa=price(a),pb=price(b);if(pa==null)return pb==null?by(a,b):1;if(pb==null)return -1;return s==='lo'?pa-pb:pb-pa}); | |
| const v=list.slice(0,shown); | |
| $('grid').innerHTML=v.length?v.map(card).join(''):'<div class="empty">Ничего не нашлось. Попробуйте другое слово или снимите фильтры.</div>'; | |
| $('ttl').textContent=st.flags.has('u')&&st.g==='all'?'Б/у оборудование':st.flags.has('p')&&st.g==='all'?'Запчасти для бассейна':st.g==='all'?'Весь каталог':G[st.g]; | |
| const left=list.length-v.length;$('more').hidden=left<=0;$('more').textContent='Показать ещё'; | |
| ctrls(); | |
| } | |
| function ctrls(){ | |
| $('flags').innerHTML=(st.g!=='all'?'<button class="pill grp" data-g="all">'+esc(G[st.g])+'<b aria-label="Снять раздел">×</b></button>':'')+FL.filter(([k])=>k!=='s'||D.items.some(spec)).map(([k,t,c])=>'<button class="pill '+c+'" data-f="'+k+'" aria-pressed="'+st.flags.has(k)+'">'+t+'<span class="cnt">('+D.items.filter(x=>(st.g==='all'||x.g===st.g)&&FT[k](x)).length+')</span></button>').join(''); | |
| } | |
| function tiles(){ | |
| const rep={};D.items.forEach(x=>{if(x.img&&(!rep[x.g]||(x.pr!=null&&rep[x.g].pr==null)))rep[x.g]=x}); | |
| const has={};D.items.forEach(x=>has[x.g]=(has[x.g]||0)+1);const cn=n=>'<span class="cnt">('+n+')</span>',here=location.pathname.split('/').pop()||'./',cur=h=>h===here||(h==='./'&&here==='index.html')?' aria-current="page"':''; | |
| $('tiles').innerHTML='<a class="tile all" href="./"'+cur('./')+'><span class="ti"><svg width="22" height="22" viewBox="0 0 24 24" fill="currentColor"><rect x="3" y="3" width="8" height="8"/><rect x="13" y="3" width="8" height="8"/><rect x="3" y="13" width="8" height="8"/><rect x="13" y="13" width="8" height="8"/></svg></span>Весь каталог'+cn(D.items.length)+'</a>' | |
| +'<a class="tile sale" href="'+SL.u+'"'+cur(SL.u)+'><span class="ti">Б/у</span>Б/у оборудование'+cn(D.items.filter(FT.u).length)+'</a>' | |
| +D.groups.filter(g=>has[g.id]).map(g=>'<a class="tile" href="'+(SL[g.id]||'./')+'"'+cur(SL[g.id])+'><span class="ti">'+(rep[g.id]?'<img loading="lazy" src="'+esc(rep[g.id].img)+'" alt="">':'')+'</span>'+(g.id==='spare'?'Запчасти'+cn(D.items.filter(FT.p).length):esc(g.name)+cn(has[g.id]))+'</a>').join(''); | |
| } | |
| function open(i){ | |
| cur=i;const x=list[i]; | |
| $('dpos').textContent=(i+1)+' из '+list.length; | |
| const ph=$('dph');ph.classList.remove('z');ph.innerHTML=pic(x,1); | |
| let cap=x.cap||'';if(x.u&&hasPh(x))cap+=(cap?'. ':'')+'На фото модель, а не сам б/у товар'; | |
| $('dbody').innerHTML='<h2>'+esc(x.n)+'</h2><div class="chips"><span>'+esc(G[x.g])+'</span>'+(x.c?'<span>'+esc(x.c)+'</span>':'')+(x.u?'<span class="u">Б/у</span>':'')+(x.p?'<span>Запчасть</span>':'')+'</div>'+prHtml(x,'dpr',1)+stk(x,'stk dstk')+(cap&&hasPh(x)?'<p class="cap">'+esc(cap)+'</p>':'')+'<div class="buy" data-id="'+esc(x.id)+'" style="padding:12px 0 0">'+buyHtml(x)+'</div><p class="call">Вопросы по товару: <a href="tel:+74955454960">+7 (495) 545-49-60</a></p>'; | |
| $('prev').disabled=i<=0;$('next').disabled=i>=list.length-1; | |
| const d=$('dlg');if(!d.open)d.showModal(); | |
| } | |
| $('grid').onclick=e=>{if(cartClick(e))return;const c=e.target.closest('.open');if(c)open(+c.dataset.i)}; | |
| $('flags').onclick=e=>{const g=e.target.closest('[data-g]');if(g){location.href='./#catalog';return}const b=e.target.closest('[data-f]');if(!b)return;const f=b.dataset.f;if(st.flags.has(f))st.flags.delete(f);else{st.flags.add(f);if(f==='u')st.flags.delete('s');if(f==='s')st.flags.delete('u')}shown=PAGE;render()}; | |
| let t;$('q').oninput=e=>{clearTimeout(t);$('qx').hidden=!e.target.value;t=setTimeout(()=>{st.q=e.target.value.trim();shown=PAGE;render()},150)}; | |
| $('qx').onclick=e=>{e.preventDefault();$('q').value='';$('qx').hidden=true;st.q='';render();$('q').focus()}; | |
| $('sort').onchange=e=>{st.sort=e.target.value;shown=PAGE;render()}; | |
| $('more').onclick=()=>{shown+=PAGE;render()}; | |
| $('close').onclick=()=>$('dlg').close(); | |
| $('dbody').onclick=e=>{cartClick(e)}; | |
| $('prev').onclick=()=>cur>0&&open(cur-1); | |
| $('next').onclick=()=>{if(cur<list.length-1){if(cur+1>=shown){shown+=PAGE;render()}open(cur+1)}}; | |
| $('dlg').onclick=e=>{if(e.target===$('dlg'))$('dlg').close()}; | |
| $('dph').onclick=()=>{if($('dph').querySelector('img'))$('dph').classList.toggle('z')}; | |
| document.addEventListener('keydown',e=>{if(!$('dlg').open)return;if(e.key==='ArrowLeft')$('prev').click();if(e.key==='ArrowRight')$('next').click()}); | |
| new IntersectionObserver(([e])=>$('bar').classList.toggle('on',!e.isIntersecting),{rootMargin:'-1px 0px 0px 0px'}).observe($('cats')); | |
| // ---- cart | |
| const MAILS=['artem010@yandex.ru','Kozhevnikova.kseniya@franmerpools.ru'],MAIL=MAILS.join(' и '),KEY='franmer-cart'; | |
| let C={};try{C=JSON.parse(localStorage.getItem(KEY)||'{}')||{}}catch(e){C={}} | |
| const byId={}; | |
| function save(){try{localStorage.setItem(KEY,JSON.stringify(C))}catch(e){}} | |
| const stk=(x,cls)=>x.q?'<p class="'+cls+'">В наличии: '+x.q+' шт</p>':''; | |
| function buyHtml(x){const n=C[x.id]||0;return n?'<div class="qty"><button data-dec="'+esc(x.id)+'" aria-label="Меньше">−</button><span>В корзине: '+n+'</span><button data-inc="'+esc(x.id)+'" aria-label="Больше">+</button></div>':'<button class="add" data-add="'+esc(x.id)+'">В корзину</button>'} | |
| function setQ(id,n){if(!byId[id])return;if(n>0)C[id]=Math.min(n,byId[id].q||99);else delete C[id];save();syncCart()} | |
| function cartClick(e){const b=e.target.closest('[data-add],[data-inc],[data-dec],[data-rm]');if(!b)return false; | |
| const id=b.dataset.add||b.dataset.inc||b.dataset.dec||b.dataset.rm; | |
| if(b.dataset.add||b.dataset.inc)setQ(id,(C[id]||0)+1);else if(b.dataset.dec)setQ(id,(C[id]||0)-1);else setQ(id,0);return true} | |
| function lines(){return Object.keys(C).filter(id=>byId[id]).map(id=>({x:byId[id],n:C[id]}))} | |
| function totals(){let s=0,ask=0,q=0;lines().forEach(({x,n})=>{q+=n;const p=price(x);if(p==null)ask++;else s+=p*n});return{s,ask,q}} | |
| function syncCart(){ | |
| document.querySelectorAll('.buy[data-id]').forEach(el=>{const x=byId[el.dataset.id];if(x)el.innerHTML=buyHtml(x)}); | |
| const t=totals();$('cartn').hidden=!t.q;$('cartn').textContent=t.q; | |
| $('cartbar').hidden=!t.q;document.body.classList.toggle('hc',!!t.q); | |
| $('cartbt').textContent='Корзина · '+t.q+' шт'+(t.s?' · '+rub(t.s):''); | |
| if($('cdlg').open)drawCart(); | |
| } | |
| function drawCart(){ | |
| const L=lines(),t=totals(); | |
| $('of').hidden=!L.length; | |
| if(!L.length){$('cbody').innerHTML='<p class="cempty">Корзина пуста. Добавьте товары кнопкой «В корзину».</p>';return} | |
| $('cbody').innerHTML='<ul class="cl">'+L.map(({x,n})=>{const p=price(x);return '<li><div class="cim">'+(x.img?'<img src="'+esc(x.img)+'" alt="">':'')+'</div><div class="cn">'+esc(x.n)+(x.u?' <b style="color:var(--red)">(б/у)</b>':'')+'</div><div class="cr"><div class="qty"><button data-dec="'+esc(x.id)+'" aria-label="Меньше">−</button><span>'+n+' шт</span><button data-inc="'+esc(x.id)+'" aria-label="Больше">+</button></div><span class="sum">'+(p==null?'Цена по запросу':rub(p*n))+'</span><button class="rm" data-rm="'+esc(x.id)+'">Убрать</button></div></li>'}).join('')+'</ul>' | |
| +'<div class="ctot"><span>Итого</span><span>'+rub(t.s)+'</span></div>'+(t.ask?'<p class="cask">Плюс '+t.ask+' поз. с ценой по запросу: её назовёт менеджер.</p>':''); | |
| } | |
| function orderText(){ | |
| const t=totals(); | |
| return 'Заказ с сайта FRANMER\n\n'+lines().map(({x,n},i)=>{const p=price(x);return (i+1)+'. '+x.n+(x.u?' (б/у)':'')+' — '+n+' шт × '+(p==null?'цена по запросу':rub(p)+' = '+rub(p*n))}).join('\n') | |
| +'\n\nИтого: '+rub(t.s)+(t.ask?' + '+t.ask+' поз. с ценой по запросу':'') | |
| +'\n\nИмя: '+$('oname').value.trim()+'\nТелефон: '+$('ophone').value.trim()+($('omail').value.trim()?'\nПочта: '+$('omail').value.trim():'')+($('ocom').value.trim()?'\nКомментарий: '+$('ocom').value.trim():''); | |
| } | |
| function check(){const err=!$('oname').value.trim()?'Укажите имя.':($('ophone').value.replace(/\D/g,'').length<10?'Укажите телефон, чтобы мы могли перезвонить.':'');$('oerr').hidden=!err;$('oerr').textContent=err;return !err} | |
| function showText(head,txt){const d=$('odone');d.hidden=false;d.className='done';d.removeAttribute('role');d.innerHTML='';const p=document.createElement('div');p.textContent=head;const ta=document.createElement('textarea');ta.readOnly=true;ta.value=txt;d.append(p,ta);return ta} | |
| let sending=false; | |
| $('of').addEventListener('submit',e=>{e.preventDefault();if(sending||!check())return; | |
| const txt=orderText(),go=$('of').querySelector('.go'),t=totals(); | |
| sending=true;go.disabled=true;go.innerHTML='<span class="spin"></span>Отправляю…';$('odone').hidden=true; | |
| const ctl=new AbortController(),tm=setTimeout(()=>ctl.abort(),25000); | |
| const fail=why=>{const d=$('odone');d.hidden=false;d.className='rbox no';d.setAttribute('role','alert');d.innerHTML='<svg class="ic" viewBox="0 0 96 96" aria-hidden="true"><circle cx="48" cy="48" r="48" fill="#e3262f"/><path d="M33 33l30 30M63 33L33 63" fill="none" stroke="#fff" stroke-width="9" stroke-linecap="round"/></svg><h3>Заказ не отправлен</h3><p></p><p>Позвоните нам, и мы оформим заказ по телефону:</p><a class="tel" href="tel:+74955454960">+7 (495) 545-49-60</a><p>Или скопируйте заказ ниже и отправьте на '+MAIL+'.</p><textarea readonly></textarea>';d.querySelector('p').textContent=why;d.querySelector('textarea').value=txt;try{d.scrollIntoView({block:'start',behavior:'smooth'})}catch(err){}}; | |
| let req; | |
| try{req=fetch('https://formsubmit.co/ajax/'+MAILS[0],{method:'POST',signal:ctl.signal,headers:{'Content-Type':'application/json',Accept:'application/json'}, | |
| body:JSON.stringify({_subject:'Заказ с сайта FRANMER: '+$('oname').value.trim(),_cc:MAILS.slice(1).join(','),_template:'table', | |
| 'Имя':$('oname').value.trim(),'Телефон':$('ophone').value.trim(),'Почта':$('omail').value.trim()||'—','Комментарий':$('ocom').value.trim()||'—', | |
| 'Итого':rub(t.s)+(t.ask?' + '+t.ask+' поз. с ценой по запросу':''),'Заказ':txt})})}catch(err){req=Promise.reject(err)} | |
| req.then(r=>r.json().catch(()=>({}))).then(j=>{ | |
| if(j&&(j.success===true||j.success==='true')){const ph=$('ophone').value.trim();C={};save();syncCart(); | |
| const d=document.createElement('div');d.className='rbox ok';d.setAttribute('role','status');d.innerHTML='<svg class="ic" viewBox="0 0 96 96" aria-hidden="true"><circle cx="48" cy="48" r="48" fill="#2f8a3e"/><path d="M27 50l14 14 28-31" fill="none" stroke="#fff" stroke-width="9" stroke-linecap="round" stroke-linejoin="round"/></svg><h3>Заказ отправлен</h3><p>Менеджер перезвонит по номеру <b></b> и подтвердит наличие и цену.</p><button type="button" class="rb">Готово</button>';d.querySelector('b').textContent=ph;d.querySelector('.rb').onclick=()=>$('cdlg').close();$('cbody').replaceChildren(d);$('cdlg').querySelector('.dbody').scrollTop=0;$('cdlg').scrollTop=0} | |
| else fail(j&&j.message?'Сервис отправки ответил: '+j.message:'Сервис отправки ответил ошибкой.'); | |
| }).catch(e=>fail(e&&e.name==='AbortError'?'Сервис отправки не ответил.':'Нет связи с сервисом отправки.')).finally(()=>{clearTimeout(tm);sending=false;go.disabled=false;go.textContent='Отправить заказ'}); | |
| }); | |
| $('ocopy').onclick=()=>{if(!check())return;const txt=orderText();const ta=showText('Текст заказа ниже. Отправьте его на '+MAIL+' или в мессенджер.',txt); | |
| try{navigator.clipboard.writeText(txt).then(()=>{$('odone').firstChild.textContent='Заказ скопирован. Отправьте его на '+MAIL+'.'}).catch(()=>{ta.select()})}catch(err){ta.select()}}; | |
| $('cbody').onclick=e=>{cartClick(e)}; | |
| const openCart=()=>{drawCart();$('odone').hidden=true;$('odone').className='done';$('oerr').hidden=true;$('cdlg').showModal()}; | |
| $('cartb').onclick=openCart;$('cartgo').onclick=openCart; | |
| $('cclose').onclick=()=>$('cdlg').close(); | |
| $('cdlg').onclick=e=>{if(e.target===$('cdlg'))$('cdlg').close()}; | |
| Promise.all([fetch('catalog.json').then(r=>r.json()),fetch('patch.json',{cache:'no-store'}).then(r=>r.ok?r.json():null).catch(()=>null),fetch('https://franmer-montazh.static.hf.space/retail.json',{cache:'no-store'}).then(r=>r.ok?r.json():{}).catch(()=>({}))]).then(([d,pt,rt])=>{RT=rt||{}; | |
| if(pt){const m={};d.items.forEach(x=>m[x.id]=x);Object.entries(pt.set||{}).forEach(([id,f])=>{if(m[id])Object.assign(m[id],f)});(pt.add||[]).forEach(x=>{if(!m[x.id])d.items.push(x)})} | |
| d.items=d.items.filter(x=>price(x)!=null); | |
| D=d;D.groups.forEach(g=>G[g.id]=g.name);D.items.forEach(x=>byId[x.id]=x); | |
| tiles();render();syncCart(); | |
| }).catch(()=>{$('grid').innerHTML='<div class="empty">Каталог не загрузился. Обновите страницу.</div>'}); | |
| } | |