Spaces:
Running
Running
Download admin/generator.js from runi-data-science/Certificates: direct link, hf CLI and curl.
- Browser
- Download file 6.06 kB
-
https://huggingface.co/spaces/runi-data-science/Certificates/resolve/main/admin/generator.js
- Command line
-
hf download hf://spaces/runi-data-science/Certificates/admin/generator.js
-
curl -L -o generator.js https://huggingface.co/spaces/runi-data-science/Certificates/resolve/main/admin/generator.js
6.06 kB
| import '../certificate-renderer.js'; | |
| import {COURSE,LABELS,parseCSV,validateSettings,generateBatch,zipCertificates} from './certificate-core.js'; | |
| const $=id=>document.getElementById(id); | |
| const base=new URL('../',import.meta.url); | |
| let students=[],settings=null,template='',controller=null,urls=[],ready=false,zipClicked=false,privateClicked=false,downloadNavigation=false; | |
| function message(text,error=false){$('message').textContent=text;$('message').classList.toggle('error',error);} | |
| function revoke(){for(const url of urls)URL.revokeObjectURL(url);urls=[];} | |
| function invalidate(){students=[];settings=null;$('review').hidden=true;message('');} | |
| $('generator-form').addEventListener('submit',event=>event.preventDefault()); | |
| $('inputs').addEventListener('input',invalidate); | |
| $('example').addEventListener('click',()=>{invalidate();$('students').value='email,name,grade\nfictional.one@example.com,Example Student One,89.5\nfictional.two@example.com,Example Student Two,90\nfictional.three@example.com,"Example Student, Three",95\n';}); | |
| $('csv-file').addEventListener('change',async()=>{ | |
| invalidate();const file=$('csv-file').files[0];if(!file)return; | |
| if(file.size>5000000){message('CSV file is too large.',true);return;} | |
| try{$('students').value=await file.text();}catch{message('Could not read that file.',true);} | |
| }); | |
| async function preview(){ | |
| const student=students[Number($('preview-student').value)];if(!student)return; | |
| const holder=document.createElement('template');holder.innerHTML=template; | |
| const record={version:1,...COURSE,studentName:student.name,distinction:student.distinction,lecturer:settings.lecturer,completionDate:settings.date,reference:`${settings.term}-2686-${String(Number($('preview-student').value)+1).padStart(3,'0')}`}; | |
| CertificateRenderer.fill(holder.content,record); | |
| const width=$('preview').clientWidth||800,scale=Math.min(1,width/CertificateRenderer.width); | |
| $('preview').style.height=`${Math.ceil(CertificateRenderer.height*scale)+12}px`; | |
| $('preview').srcdoc=`<!doctype html><html><head><meta charset="utf-8"><link rel="stylesheet" href="${new URL('certificate.css',base).href}"><style>body{margin:0;display:block!important;min-height:0!important}.certificate{transform:scale(${scale});transform-origin:top left}html{overflow:hidden}</style></head><body>${holder.innerHTML}</body></html>`; | |
| } | |
| $('preview-student').addEventListener('change',preview); | |
| window.addEventListener('resize',()=>{if(!$('review').hidden)preview();}); | |
| $('validate').addEventListener('click',async()=>{ | |
| invalidate();$('validate').disabled=true; | |
| try{ | |
| if(!window.isSecureContext||!crypto.subtle)throw new Error('Use the HTTPS Space app or localhost in a browser with Web Crypto support.'); | |
| settings={term:$('term').value.trim(),lecturer:$('lecturer').value.trim(),date:$('date').value};validateSettings(settings); | |
| students=parseCSV($('students').value); | |
| if(!template){const response=await fetch(new URL('certificate-template.html',base),{credentials:'omit',referrerPolicy:'no-referrer'});if(!response.ok)throw new Error('Certificate template is unavailable.');template=await response.text();} | |
| const counts=LABELS.map(label=>`${students.filter(s=>s.distinction===label).length} ${label.toLowerCase()}`); | |
| $('summary').textContent=`${students.length} certificates · ${settings.term}/\n${counts.join(' · ')}`; | |
| $('preview-student').replaceChildren(...students.map((student,i)=>{const option=document.createElement('option');option.value=i;option.textContent=student.name;return option;})); | |
| $('review').hidden=false;await preview();message('Review the names, date and distinction before generating.'); | |
| }catch(error){invalidate();message(error.message,true);}finally{$('validate').disabled=false;} | |
| }); | |
| function download(id,blob,name,isPrivate){const url=URL.createObjectURL(blob);urls.push(url);const a=$(id);a.href=url;a.download=name;a.onclick=()=>{downloadNavigation=true;setTimeout(()=>{downloadNavigation=false;},2000);if(isPrivate)privateClicked=true;else zipClicked=true;};} | |
| $('generate').addEventListener('click',async()=>{ | |
| if(!students.length||!settings)return; | |
| $('generate').disabled=true;$('inputs').disabled=true;$('preview-student').disabled=true;controller=new AbortController(); | |
| try{ | |
| const batch=await generateBatch(settings,students,(done,total)=>message(`Encrypting ${done} of ${total}…`),controller.signal); | |
| revoke(); | |
| download('zip-download',zipCertificates(batch.files),`${settings.term}-certificates.zip`,false); | |
| // Both formats are CSV-structured text; the extension is a convenience only. | |
| download('txt-download',new Blob([batch.recipients],{type:'application/octet-stream'}),`${settings.term}-recipients.txt`,true); | |
| download('csv-download',new Blob([batch.recipients],{type:'application/octet-stream'}),`${settings.term}-recipients.csv`,true); | |
| ready=true;zipClicked=false;privateClicked=false;$('results').hidden=false; | |
| $('result-summary').textContent=`${students.length} certificates generated for ${settings.term}. Nothing has been uploaded.`; | |
| message('Download the encrypted ZIP and your private recipient file.');$('results').scrollIntoView({behavior:'auto',block:'start'}); | |
| }catch(error){if(error.name!=='AbortError')message('Generation failed. No files were uploaded. Clear the batch and try again.',true);} | |
| finally{controller=null;if(!ready){$('inputs').disabled=false;$('generate').disabled=false;$('preview-student').disabled=false;}} | |
| }); | |
| $('reset').addEventListener('click',()=>{ | |
| if((ready||controller)&&!confirm('Clear this batch and its download links? Save your files first; this page cannot recover keys after clearing.'))return; | |
| controller?.abort();revoke();ready=false;zipClicked=false;privateClicked=false; | |
| $('generator-form').reset();$('inputs').disabled=false;$('generate').disabled=false;$('preview-student').disabled=false;$('results').hidden=true;$('preview').srcdoc='';invalidate(); | |
| }); | |
| window.addEventListener('beforeunload',event=>{if(!downloadNavigation&&(controller||(ready&&(!zipClicked||!privateClicked)))){event.preventDefault();event.returnValue='';}}); | |