From a5417d200e60d002965e14355a3f08f57b805300 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Cau=C3=AA=20Faleiros?= Date: Thu, 29 Oct 2026 18:18:56 -0300 Subject: [PATCH] feat: a real progress bar per file while it uploads (Dropstar's third round, item 6) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A file starts uploading as soon as it is on the product page, not once the item is in the cart. Under the uploader, each file has its row: "Enviando NOME · 62% · 1,2 MB de 2,0 MB", then the security check, then "enviado"; a failure says why, with "Tentar de novo". Each part goes through XMLHttpRequest, so the bytes move while a part is on its way instead of once per 8 MB part. A file taken off the page, and in no cart item, stops uploading. Co-Authored-By: Claude Opus 5.5 --- tests/artwork_browser_test.mjs | 6 ++++++ tests/browser_test.mjs | 4 ++++ web/checkout.js | 28 ++++++++++++++++++++------ web/index.html | 1 + web/site-pdf.js | 6 +++--- web/site-upload.js | 36 ++++++++++++++++++++++++++++++++++ web/site-v2.css | 11 +++++++++++ web/upload.js | 27 +++++++++++++++++++------ 8 files changed, 104 insertions(+), 15 deletions(-) diff --git a/tests/artwork_browser_test.mjs b/tests/artwork_browser_test.mjs index fbfad0e..354d269 100644 --- a/tests/artwork_browser_test.mjs +++ b/tests/artwork_browser_test.mjs @@ -288,6 +288,12 @@ try{ await click('#bVoltar');await click('[data-modo="file"]'); await evaluate('sendSheet()'); await waitFor(()=>evaluate('folhas.length===1 && !!folhas[0].previewSrc && metros===0.342'),'ready-sheet image'); + // On its way at once, with its own row under the uploader (Dropstar, + // 2026-10-29). There is no storage here, so it fails, and says so with a + // way to try again; tests/browser_test.mjs sends it for real. + await waitFor(()=>evaluate(`!!dtfEnvio.estado(folhas[0].f)`),'the sheet starts uploading at once'); + await waitFor(()=>evaluate(`$('envios').textContent.includes('Não foi possível enviar folha-montada.png') && + !!$('envios').querySelector('[data-envio]')`),'a failed upload says so under the uploader'); assert.deepEqual(await evaluate(`({mode:modo,art:artes.length,title:$('montcabTit').textContent,rate:precoMetro()})`),{mode:'file',art:0,title:'Sua folha',rate:19.9}); // One price per product (Dropstar, 2026-10-23): the sheet is graded, and the // grade is shown, but the metre costs the same as for any other grade. diff --git a/tests/browser_test.mjs b/tests/browser_test.mjs index 1ad3325..e60f192 100644 --- a/tests/browser_test.mjs +++ b/tests/browser_test.mjs @@ -73,6 +73,10 @@ try{ const input=await site.call('DOM.querySelector',{nodeId:root.root.nodeId,selector:'#inp'}); await site.call('DOM.setFileInputFiles',{nodeId:input.nodeId,files:[resolve('tests/fixtures/local-test.cdr')]}); await waitFor(()=>site.eval('!!document.querySelector("[data-comp]")'),'manual length field'); + // On its way from the product page already, with its own row under the + // uploader (Dropstar, 2026-10-29). + await waitFor(()=>site.eval(`$('envios').textContent.includes('local-test.cdr') && !$('envios').textContent.includes('Não foi possível')`), + 'the file uploads from the product page',45000); await site.fill('[data-comp]','1.01','change'); await waitFor(()=>site.eval('!!itemAtual'),'cart calculation'); // A CDR is opened by hand: the full price, plus the per-metre charge when diff --git a/web/checkout.js b/web/checkout.js index 328771b..40dc8ed 100644 --- a/web/checkout.js +++ b/web/checkout.js @@ -126,27 +126,42 @@ message('Nenhum pedido aguardando pagamento.'); button('Ir para o carrinho', () => vaiPara(CARRINHO)); } - // Files start uploading as soon as they are in the cart, so a sheet of - // several GB is on its way while the customer fills in the order. The - // checkout waits for whatever is still going. + // Files start uploading as soon as they are on the product page (Dropstar, + // 2026-10-29; before, once in the cart), so a sheet of several GB is on its + // way while the customer builds the order. The checkout waits for whatever + // is still going. const envios=new Map(); const chaveArquivo=f=>[f.name,f.size,f.lastModified].join('|'); function enviar(file) { const k=chaveArquivo(file); let e=envios.get(k); if (!e) { - e={file, sent:0, done:false, failed:null}; + e={file, sent:0, done:false, failed:null, stop:new AbortController()}; e.promise=(async()=>{ const session=await ready; - return window.dtfUpload(file,{api,scope:session.cart_scope,progress:()=>{}, + return window.dtfUpload(file,{api,scope:session.cart_scope,progress:()=>{},signal:e.stop.signal, onBytes:n=>{e.sent=n;pintaEnvio();}}); })(); e.promise.then(()=>{e.done=true;falhas.delete(k);pintaEnvio();}, - error=>{envios.delete(k);falhas.set(k,{file,error});pintaEnvio();}); + error=>{envios.delete(k);if(error?.name!=='AbortError')falhas.set(k,{file,error});pintaEnvio();}); envios.set(k,e); } return e.promise; } + // Each file's upload as the product page shows it, under the uploader. + window.dtfEnvio={ + enviar:file=>{if(!falhas.has(chaveArquivo(file)))enviar(file).catch(()=>{});}, + estado:file=>{const k=chaveArquivo(file),e=envios.get(k),f=falhas.get(k); + return f?{fase:'falhou',erro:f.error?.message||'erro no envio'} + :!e?null:e.done?{fase:'pronto'}:e.sent>=file.size?{fase:'verificando'}:{fase:'enviando',enviado:e.sent};}, + deNovo:file=>{falhas.delete(chaveArquivo(file));enviar(file).catch(()=>{});pintaEnvio();}, + // A file taken off the page, and in no cart item, stops going. + manter:files=>{ + const quero=new Set([...files,...pedido.flatMap(it=>it.localFiles||[]),...(itemAtual?.localFiles||[])].map(chaveArquivo)); + for(const [k,e] of envios) if(!e.done && !quero.has(k)) e.stop.abort(); + for(const k of falhas.keys()) if(!quero.has(k)) falhas.delete(k); + }, + }; // The Kanban shows each order's artwork from the small picture this page // already made of it (site-upload.js). Never blocks the order: a picture that // fails to go leaves the Kanban with the layout drawing it shows today. @@ -203,6 +218,7 @@ return 'Enviando seus arquivos · '+restante(e); } function pintaEnvio() { + window.dispatchEvent(new Event('dtf-envio')); const e=estadoEnvio(), texto=textoEnvio(e); const el=document.getElementById('envioArq'); const falhou=arquivosDoCarrinho().map(f=>falhas.get(chaveArquivo(f))).filter(Boolean); diff --git a/web/index.html b/web/index.html index b90069e..7e2e91a 100644 --- a/web/index.html +++ b/web/index.html @@ -844,6 +844,7 @@ h2 em{font-style:normal;color:var(--laranja)} Tem CDR, AI, PSD ou TIFF? Pode mandar também. Alguém abre na mão, e o metro custa R$ 2,00 a mais. +
diff --git a/web/site-pdf.js b/web/site-pdf.js index 12d7027..af7a3b4 100644 --- a/web/site-pdf.js +++ b/web/site-pdf.js @@ -492,7 +492,7 @@ function pintaFolha(){ const L=larguraFilme(); pintaTipoEnvio(); // trava o seletor enquanto houver folha $('zona').classList.toggle('compacta', folhas.length>0); - if(!folhas.length){ $('lista').innerHTML=''; agendaAvaliacao(); previaAoVivo(); return; } + if(!folhas.length){ $('lista').innerHTML=''; agendaAvaliacao(); previaAoVivo(); agendaEnvios(); return; } const tot=folhaTotalM(); $('lista').innerHTML = '

Seus arquivos

'+ @@ -595,7 +595,7 @@ function pintaFolha(){ })); $('lista').querySelectorAll('[data-repf], [data-comp]').forEach(el=> el.addEventListener('input',invalidaItemAtual)); - agendaAvaliacao(); previaAoVivo(); + agendaAvaliacao(); previaAoVivo(); agendaEnvios(); } // sugestão de largura @@ -722,7 +722,7 @@ function pintaArtes(){ const a=artes[+b.dataset.esp]; a.esp=!a.esp; pintaArtes(); })); resumoArtes(); - previaAoVivo(); + previaAoVivo(); agendaEnvios(); } function resumoArtes(){ const r=$('rA'), prontas=artes.filter(a=>a.cm>0 && a.cm<=larguraFilme() && (a.src||a.semPrevia)); diff --git a/web/site-upload.js b/web/site-upload.js index 5d193d0..4ff6221 100644 --- a/web/site-upload.js +++ b/web/site-upload.js @@ -58,6 +58,40 @@ Z.addEventListener('keydown',e=>{if(e.key==='Enter'||e.key===' '){I.click();e.pr if(ev==='drop') sel([...e.dataTransfer.files]); })); I.addEventListener('change',()=>sel([...I.files])); +// Each file's upload, under the uploader (Dropstar, 2026-10-29): the bytes +// sent of its size, then the security check; a failure says why. It starts +// as soon as the file is on the page (checkout.js sends it). +const ENVIADO_MS=4000; +const enviadoEm=new WeakMap(); +// A few repaints a second, page in view or not: progress comes in far more often. +let envioQuadro=0; +function agendaEnvios(){ if(!envioQuadro) envioQuadro=setTimeout(()=>{ envioQuadro=0; pintaEnvios(); },120); } +function pintaEnvios(){ + const el=$('envios'); if(!el || !window.dtfEnvio) return; + dtfEnvio.manter([...artes,...folhas].map(x=>x.f)); + // Off the product page there is no uploader to paint under. + if(!MODOS[modo]){ el.innerHTML=''; return; } + const agora=Date.now(); + el.innerHTML=(ehFolha()?folhas:artes).map((x,i)=>{ + const f=x.f, e=dtfEnvio.estado(f), nome=''+escapeHTML(f.name)+''; + if(!e) return ''; + if(e.fase==='pronto'){ + if(!enviadoEm.has(f)){ enviadoEm.set(f,agora); setTimeout(agendaEnvios,ENVIADO_MS+50); } + return agora-enviadoEm.get(f)>ENVIADO_MS ? '' : '
'+icone('okCirculo')+''+nome+' enviado
'; + } + if(e.fase==='falhou') return '
Não foi possível enviar '+nome+': '+ + escapeHTML(e.erro.replace(/\.$/,''))+'.
'; + const pct=e.fase==='verificando' ? 100 : Math.floor(e.enviado/f.size*100); + return '
'+(e.fase==='verificando' ? 'Verificando a segurança de '+nome+'…' + : 'Enviando '+nome+' · '+pct+'% · '+fmt(e.enviado)+' de '+fmt(f.size))+''+ + '
'; + }).join(''); +} +addEventListener('dtf-envio',agendaEnvios); +$('envios').addEventListener('click',e=>{ + const b=e.target.closest('[data-envio]'); if(!b || !MODOS[modo]) return; + const x=(ehFolha()?folhas:artes)[+b.dataset.envio]; if(x) dtfEnvio.deNovo(x.f); +}); // A sheet with residue gets its preview circled where the dots are. async function marcaResiduos(x){ if(!(x.an && x.an.residuos && !x.an.fundoChapado && x.previewSrc && x.an.pontos?.length)) return; @@ -84,6 +118,8 @@ async function sel(fs){ fs=fs.filter(f=>f.size<=max); } if(!fs.length) return; + // On their way at once; a JPG is refused at the order anyway. + fs.filter(f=>!/\.jpe?g$/i.test(f.name)).forEach(f=>window.dtfEnvio?.enviar(f)); if(ehFolha()){ const novas=fs.map(f=>({f, med:null, rep:1, m:0, semAnalise:null})); folhas=folhas.concat(novas); // soma, não substitui diff --git a/web/site-v2.css b/web/site-v2.css index 6840a58..15469e0 100644 --- a/web/site-v2.css +++ b/web/site-v2.css @@ -381,6 +381,17 @@ html:is([data-rota="pagamento"],[data-rota="pix"]) .pagGrid{display:grid;grid-te .envioBarra{height:6px;border-radius:999px;background:#EDEDED;overflow:hidden;margin-bottom:6px} .envioBarra i{display:block;height:100%;background:var(--laranja);border-radius:999px;transition:width .4s} .cartEnvio{font-size:15px;font-weight:700;color:var(--laranja-escuro);margin-left:6px} +/* Each file's upload under the uploader (Dropstar, 2026-10-29). */ +.envios{display:flex;flex-direction:column;gap:8px;margin:0 0 14px} +.envios:empty{display:none} +.envio{padding:12px 14px;border:1px solid #CFE9D8;border-radius:12px;background:#F2FBF5;font-size:15px;line-height:1.4;color:var(--preto);overflow-wrap:anywhere} +.envio span{display:block;margin-bottom:8px} +.envio .envioBarra{height:12px;margin:0;background:#DDEFE3} +.envio .envioBarra i{background:var(--verde-ml)} +.envio.ok{display:flex;align-items:center;gap:8px;color:#00753A} +.envio.erro{display:flex;flex-wrap:wrap;align-items:center;gap:6px 10px;border-color:#F4C7C1;background:#FDE8E6;color:#B3261E} +.envio.ok span,.envio.erro span{margin:0} +.envio.erro button{padding:0;border:0;background:none;color:inherit;font:inherit;font-weight:700;text-decoration:underline;cursor:pointer} .cartEnvio:empty{display:none} .envioArq:empty{display:none} .pagCab{display:flex;align-items:baseline;justify-content:space-between;gap:16px;margin-bottom:20px} diff --git a/web/upload.js b/web/upload.js index fd434b8..d89f5bc 100644 --- a/web/upload.js +++ b/web/upload.js @@ -1,5 +1,6 @@ /* Shared direct multipart transport for customer originals/corrections and operator finals. */ -window.dtfUpload = async (file, {api, prefix='/uploads', startPath=prefix, progress=()=>{}, onBytes=()=>{}, scope='guest', resume=true}) => { +window.dtfUpload = async (file, {api, prefix='/uploads', startPath=prefix, progress=()=>{}, onBytes=()=>{}, scope='guest', resume=true, signal=null}) => { + const cancelled=()=>new DOMException('Envio cancelado.','AbortError'); const samples=new Blob([file.slice(0,65536),file.slice(Math.max(0,file.size-65536))]); const hash=Array.from(new Uint8Array(await crypto.subtle.digest('SHA-256',await samples.arrayBuffer())),b=>b.toString(16).padStart(2,'0')).join(''); const key='dtf-upload:'+JSON.stringify([scope,file.name,file.size,file.lastModified,hash]); @@ -22,15 +23,29 @@ window.dtfUpload = async (file, {api, prefix='/uploads', startPath=prefix, progr } if(state.complete)return waitForScan(); const done=new Set(state.parts||[]),size=state.part_bytes; - onBytes(Math.min(file.size,done.size*size)); + const length=part=>Math.min(size,file.size-(part-1)*size); + let sent=[...done].reduce((t,part)=>t+length(part),0); + onBytes(sent); + // Each part through XMLHttpRequest, which reports the bytes as they go: the + // bar moves while a part is on its way, not once per part (Dropstar, 2026-10-29). + const put=(url,body)=>new Promise((resolve,reject)=>{ + if(signal?.aborted)return reject(cancelled()); + const xhr=new XMLHttpRequest();xhr.open('PUT',url); + xhr.upload.onprogress=e=>onBytes(Math.min(file.size,sent+e.loaded)); + const lost=()=>reject(new Error('Upload interrompido. Tente novamente para retomar.')); + xhr.onload=()=>xhr.status>=200&&xhr.status<300?resolve():lost(); + xhr.onerror=lost;xhr.ontimeout=lost;xhr.onabort=()=>reject(cancelled()); + signal?.addEventListener('abort',()=>xhr.abort(),{once:true}); + xhr.send(body); + }); for(let offset=0,part=1;offset