// One deterministic renderer for preview, individual exports, and the overview.
export const KINDS = ['space', 'model', 'dataset', 'paper', 'blog'];
export const LABELS = {space:'Spaces', model:'Models', dataset:'Datasets', paper:'Papers', blog:'Blog posts'};
export const WIDTHS = {slim:240,wide:320,wider:640};
export const spineWidth = mode => WIDTHS[mode] || WIDTHS.slim;
export const ICONS = {
chip:'M7 7h10v10H7z M9 3v4 M15 3v4 M9 17v4 M15 17v4 M3 9h4 M3 15h4 M17 9h4 M17 15h4',
calendar:'M5 4h14a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2z M7 2v4 M17 2v4 M3 10h18 M8 14h2 M14 14h2 M8 18h2',
space:'M4 5h16a1 1 0 0 1 1 1v13a1 1 0 0 1-1 1H4a1 1 0 0 1-1-1V6a1 1 0 0 1 1-1z M3 10h18 M6 7.5h.1 M9 7.5h.1 M12 7.5h.1',
model:'M12 6a2.5 2.5 0 1 0 0-5 2.5 2.5 0 0 0 0 5z M5 22a2.5 2.5 0 1 0 0-5 2.5 2.5 0 0 0 0 5z M19 22a2.5 2.5 0 1 0 0-5 2.5 2.5 0 0 0 0 5z M10.7 5.7 6.2 17 M13.3 5.7 17.8 17 M7.5 19.5h9',
dataset:'M20 5c0 2-3.6 3.5-8 3.5S4 7 4 5s3.6-3.5 8-3.5S20 3 20 5z M4 5v14c0 2 3.6 3.5 8 3.5s8-1.5 8-3.5V5 M4 12c0 2 3.6 3.5 8 3.5s8-1.5 8-3.5',
paper:'M5 2h9l5 5v15H5z M14 2v6h5 M8 12h8 M8 16h8 M8 19h5',
blog:'M4 20l1-5L17 3a2 2 0 0 1 3 3L8 18z M14.5 5.5l3 3 M3 22h18',
plus:'M12 5v14 M5 12h14', close:'M6 6l12 12 M18 6 6 18',
search:'M17 10a7 7 0 1 1-14 0 7 7 0 0 1 14 0z M15.3 15.3 21 21',
down:'M6 9l6 6 6-6', up:'M6 15l6-6 6 6',
upvote:'M12 21V3 M5 10l7-7 7 7',
grip:'M9 5h.1 M15 5h.1 M9 12h.1 M15 12h.1 M9 19h.1 M15 19h.1',
heart:'M20.8 4.6a5.5 5.5 0 0 0-7.8 0L12 5.7l-1.1-1.1a5.5 5.5 0 0 0-7.8 7.8L12 21l8.8-8.6a5.5 5.5 0 0 0 0-7.8z',
download:'M12 3v12 M7 10l5 5 5-5 M4 16v5h16v-5',
link:'M10 13a5 5 0 0 0 7 .1l4-4a5 5 0 0 0-7-7l-2 2 M14 11a5 5 0 0 0-7-.1l-4 4a5 5 0 0 0 7 7l2-2',
arrow:'M7 17 17 7 M7 7h10v10', check:'m5 12 4 4L19 6',
refresh:'M20 7a9 9 0 1 0 1 8 M20 3v5h-5',
edit:'m3 21 1-6L17 2l5 5L9 20z M14 5l5 5',
share:'M12 16V2 M7 7l5-5 5 5 M5 11H3v11h18V11h-2',
trash:'M3 6h18 M9 6V3h6v3 M5 6l1 15h12l1-15 M10 10v7 M14 10v7',
};
export function icon(name, cls='') {
return ``;
}
// Hub Space-card color tokens, observed 2026-11-18. These are NOT CSS named colors.
export const COLOR_LCH = {
red:[.577,.245,27.325], yellow:[.666,.179,58.318], green:[.596,.145,163.225],
blue:[.546,.245,262.881], indigo:[.511,.262,276.966], purple:[.541,.281,293.009],
pink:[.592,.249,.584], gray:[.446,.03,256.802],
};
const lab = ([l,c,h]) => [l, c*Math.cos(h*Math.PI/180), c*Math.sin(h*Math.PI/180)];
function rgb([L,a,b]) {
const l=(L+.3963377774*a+.2158037573*b)**3, m=(L-.1055613458*a-.0638541728*b)**3, s=(L-.0894841775*a-1.291485548*b)**3;
const values=[4.0767416621*l-3.3077115913*m+.2309699292*s, -1.2684380046*l+2.6097574011*m-.3413193965*s, -.0041960863*l-.7034186147*m+1.707614701*s];
const gamma=v => Math.round(255*Math.max(0,Math.min(1,v<=.0031308?12.92*v:1.055*Math.max(v,0)**(1/2.4)-.055)));
return `rgb(${values.map(gamma).join(',')})`;
}
export const COLORS = Object.fromEntries(Object.entries(COLOR_LCH).map(([k,v])=>[k,rgb(lab(v))]));
export function gradientCSS(p) { return `linear-gradient(140deg,${COLORS[p?.from]||COLORS.blue},${COLORS[p?.to]||COLORS.indigo})`; }
export function compact(n) {
if (!Number.isFinite(n)) return '';
for (const [unit,div] of [['B',1e9],['M',1e6],['k',1e3]]) if(n>=div) {
const v=n/div; return `${Number(v.toFixed(v>=100?1:2))}${unit}`;
}
return String(n);
}
export function facts(item) {
const result=[];
if(item.kind==='space' && item.hardware) result.push({value:item.hardware,label:'Hardware',icon:'chip'});
if(['model','dataset'].includes(item.kind) && Number.isFinite(item.downloads)) result.push({value:compact(item.downloads),label:'downloads / 30d',icon:'download'});
if(['paper','blog'].includes(item.kind) && item.publishedAt) {
const date=new Date(item.publishedAt);
if(!Number.isNaN(+date)) result.push({value:item.kind==='paper'?String(date.getUTCFullYear()):date.toLocaleDateString('en-US',{month:'short',year:'numeric',timeZone:'UTC'}).toUpperCase(),label:'Published',icon:'calendar'});
}
if(Number.isFinite(item.likes)) result.push({value:`${compact(item.likes)} likes`,icon:'heart'});
if(Number.isFinite(item.upvotes)) result.push({value:`${compact(item.upvotes)} upvotes`,icon:'upvote'});
return result.slice(0,2);
}
// Two semantic slots keep mixed shelves aligned, including missing public data.
export function spineFacts(item){
const known=Number.isFinite,repo=['model','dataset'].includes(item.kind),votes=['paper','blog'].includes(item.kind);
let value='—',label=item.kind==='space'?'Hardware':repo?'Downloads / 30d':'Published';
if(item.kind==='space'&&typeof item.hardware==='string'&&item.hardware.trim())value=item.hardware.trim();
if(repo&&known(item.downloads)&&item.downloads>=0)value=compact(item.downloads);
if(votes&&item.publishedAt){
const date=new Date(item.publishedAt);
if(!Number.isNaN(+date))value=item.kind==='paper'?String(date.getUTCFullYear()):date.toLocaleDateString('en-US',{month:'short',year:'numeric',timeZone:'UTC'});
}
const count=votes?item.upvotes:item.likes;
// Three significant digits bound a single community line; source counts stay exact.
let community='—';
if(known(count)&&count>=0){
const rounded=count>=1000?Number(count.toPrecision(3)):count;
community=compact(rounded);
}
return {primary:{value,label},community:{value:community,label:votes?'upvotes':'likes',icon:votes?'upvote':'heart'}};
}
export function contextFacts(item){
const result=[];
if(item.kind==='space'&&item.sdk)result.push({label:'SDK',value:item.sdk});
if(item.kind==='model'&&item.library)result.push({label:'Library',value:item.library});
if(['model','dataset'].includes(item.kind)&&item.languages)result.push({label:'Languages',value:item.languages});
if(['space','model','dataset'].includes(item.kind)&&item.license)result.push({label:'License',value:item.license});
if(item.kind==='paper')result.push({label:'arXiv',value:item.id});
if(item.kind==='blog'&&item.articleType)result.push({label:'Article',value:item.articleType});
return result;
}
function fitText(ctx, text, maxWidth, preferred, minimum, weight='600') {
let size=preferred;
while(true){ctx.font=`${weight} ${size}px "Source Sans 3", sans-serif`;if(ctx.measureText(text).width<=maxWidth||size<=minimum)break;size--;}
return size;
}
function clippedText(ctx,text,width){
if(ctx.measureText(text).width<=width)return text;
const chars=Array.from(text);while(chars.length&&ctx.measureText(chars.join('')+'…').width>width)chars.pop();return chars.join('')+'…';
}
function wrapText(ctx,text,width,maxLines=3){
const words=text.split(/\s+/).flatMap(word=>{
const chunks=[];let chunk='';
for(const char of word){if(chunk&&ctx.measureText(chunk+char).width>width){chunks.push(chunk);chunk='';}chunk+=char;}
if(chunk)chunks.push(chunk);
// Prefer balanced breaks at hyphens over splitting a name after its first letter.
if(chunks.length>1){
const chars=Array.from(chunks.slice(-2).join(''));let best=null;
for(let i=1;iwidth||bw>width)continue;
const score=Math.abs(aw-bw)+(chars[i-1]==='-'?0:width*.2);
if(!best||scorewidth&&line){lines.push(line);line=word;}else line=candidate;
}if(line)lines.push(line);
if(lines.length<=maxLines)return lines;
const out=lines.slice(0,maxLines);out[maxLines-1]=lines.slice(maxLines-1).join(' ');return out;
}
function balancedTitleLines(ctx,text,width,original){
const words=text.split(/\s+/),count=original.length;
if(count<2||words.lengthctx.measureText(w).width>width))return original;
const space=ctx.measureText(' ').width,prefix=[0];
words.forEach(w=>prefix.push(prefix.at(-1)+ctx.measureText(w).width));
const target=(prefix.at(-1)+(words.length-count)*space)/count;
const costs=Array.from({length:count+1},()=>Array(words.length+1).fill(Infinity)),breaks=costs.map(a=>a.map(()=>0));costs[0][0]=0;
for(let k=1;k<=count;k++)for(let end=k;end<=words.length;end++)for(let start=k-1;startwidth)continue;
const cost=costs[k-1][start]+(length-target)**2;
if(cost0;k--){const start=breaks[k][end];lines.unshift(words.slice(start,end).join(' '));end=start;}
return lines.every(line=>ctx.measureText(line).width<=width)?lines:original;
}
export function titleLayout(ctx,title,width,wide=false,maxHeight=Infinity){
const wider=wide==='wider',preferred=wider?200:wide?100:84,minimum=wider?84:wide?56:52,maxLines=wider?5:wide?4:3;
const text=title.replace(/\s+/g,' ').trim();
for(let size=preferred;size>=minimum;size--){
ctx.font=`600 ${size}px "Source Sans 3", sans-serif`;
const lines=wrapText(ctx,text,width,Infinity),m=inkMetrics(ctx,'Hgj'),leading=Math.round(size*.98);
if(lines.length<=maxLines&&m.ascent+m.descent+(lines.length-1)*leading<=maxHeight){
const fitted=!wider&&lines.length===2?Math.min(size,wide?90:76):size;
ctx.font=`600 ${fitted}px "Source Sans 3", sans-serif`;
return {size:fitted,lines:balancedTitleLines(ctx,text,width,lines)};
}
}
ctx.font=`600 ${minimum}px "Source Sans 3", sans-serif`;
const m=inkMetrics(ctx,'Hgj'),count=Math.max(1,Math.min(maxLines,1+Math.floor((maxHeight-m.ascent-m.descent)/Math.round(minimum*.98))));
return {size:minimum,lines:wrapText(ctx,text,width,count).map(line=>clippedText(ctx,line,width))};
}
export function byline(item){
const task=typeof item.task==='string'?item.task.trim().replace(/-/g,' '):'';
return [item.author,task?task[0].toUpperCase()+task.slice(1):''].filter(Boolean).join(' · ');
}
function inkMetrics(ctx,text){
const metrics=ctx.measureText(text),size=Number(ctx.font.match(/([\d.]+)px/)?.[1])||40;
return {ascent:metrics.actualBoundingBoxAscent??size*.75,descent:metrics.actualBoundingBoxDescent??size*.2};
}
// Center fixed typographic line boxes, rather than moving baselines for each word.
export function textBlockLayout(width,titleMetrics,lineHeight,authorMetrics=null,gap=14,contextMetrics=[],contextLeading=40){
const top=Math.min(...titleMetrics.map((m,i)=>i*lineHeight-m.ascent));
const titleBottom=Math.max(...titleMetrics.map((m,i)=>i*lineHeight+m.descent));
const author=authorMetrics?titleBottom+gap+authorMetrics.ascent:null;
const bodyBottom=authorMetrics?author+authorMetrics.descent:titleBottom;
const context=contextMetrics.map((m,i)=>bodyBottom+22+contextMetrics[0].ascent+i*contextLeading);
const bottom=context.length?context.at(-1)+contextMetrics.at(-1).descent:bodyBottom;
const offset=(width-(bottom-top))/2-top;
return {title:titleMetrics.map((_,i)=>offset+i*lineHeight),author:author===null?null:offset+author,context:context.map(y=>y+offset)};
}
export function spineTypography(ctx,title,author,width,maxLength,context=[]){
ctx.font=`400 ${width===640?48:width===320?44:40}px "Source Sans 3", sans-serif`;
const authorFont=ctx.font,authorText=clippedText(ctx,author,maxLength),authorMetrics=author?inkMetrics(ctx,'Hgj'):null;
ctx.font='400 36px "Source Sans 3", sans-serif';
const contextFont=ctx.font,contextMetrics=inkMetrics(ctx,'Hgj');
const contextText=context.flatMap((text,i)=>wrapText(ctx,text,maxLength,1).map(line=>{
let value=clippedText(ctx,line,maxLength);
if(value.endsWith('…')&&value.includes(' '))value=value.slice(0,value.lastIndexOf(' '))+'…';
return value;
})).slice(0,2);
const reserved=(authorMetrics?authorMetrics.ascent+authorMetrics.descent+14:0)+(contextText.length?22+contextMetrics.ascent+contextMetrics.descent+(contextText.length-1)*40:0);
const margin=width===640?36:width===320?30:20;
const {size,lines}=titleLayout(ctx,title,maxLength,width===640?'wider':width===320,width-2*margin-reserved),titleFont=ctx.font,reference=inkMetrics(ctx,'Hgj');
const layout=textBlockLayout(width,lines.map(()=>reference),Math.round(size*.98),authorMetrics,14,contextText.map(()=>contextMetrics));
return {lines,titleFont,authorFont,authorText,contextFont,contextText,layout};
}
export function spineGeometry(width,options={},hasFacts=false){
const ranked=options.numbers!==false,details=options.details!==false&&hasFacts;
const base=1930-(ranked?128:0)-(details?280:0);
return {base,ruleY:base+64,rankRuleY:1840,firstValueY:base+150,rowHeight:106,
labelY:base+198,communityY:base+264,
inset:width===640?96:width===320?52:36,valueSize:width===640?72:width===320?62:52,valueMin:width===640?42:width===320?32:26,
labelSize:width===640?36:width===320?30:24,communitySize:width===640?44:width===320?34:28,communityMin:width===640?36:width===320?28:22,
iconSize:width===640?36:width===320?28:24,iconGap:width===640?14:width===320?10:8};
}
export function counterIconTop(ctx,value,baseline,iconSize){
// Align to the number, independent of descenders in labels such as "upvotes".
const {ascent,descent}=inkMetrics(ctx,value.split(' ')[0]);
return baseline+(descent-ascent)/2-iconSize/2;
}
function drawIcon(ctx,name,x,y,size){ctx.save();ctx.translate(x,y);ctx.scale(size/24,size/24);ctx.lineWidth=1.65;ctx.lineCap='round';ctx.lineJoin='round';ctx.strokeStyle='#fff';ctx.stroke(new Path2D(ICONS[name]||ICONS.paper));ctx.restore();}
export function spineContext(item){
// Description and declared card data only. No generated summaries or inferred counts.
const source=/^a blog post by .+ on hugging face\.?$/i.test(item.description||'')?'':item.description;
const raw=(source||'').replace(/\p{Extended_Pictographic}|\uFE0F/gu,'').replace(/\s+/g,' ').trim();
const description=raw?raw[0].toUpperCase()+raw.slice(1):'';
const metadata=contextFacts(item).map(f=>['SDK','arXiv'].includes(f.label)?`${f.label} · ${f.value}`:f.value).join(' · ');
return [metadata||description].filter(Boolean);
}
export function drawSpine(canvas,item,index,options={},scale=1) {
const W=spineWidth(options.width),H=2048,wider=W===640;
canvas.width=Math.round(W*scale);canvas.height=Math.round(H*scale);
const ctx=canvas.getContext('2d');ctx.scale(scale,scale);
const p=item.customPalette||item.palette||{from:'blue',to:'indigo'};
const from=lab(COLOR_LCH[p.from]||COLOR_LCH.blue),to=lab(COLOR_LCH[p.to]||COLOR_LCH.indigo);
const g=ctx.createLinearGradient(0,0,W,H);
for(let n=0;n<=24;n++) {const t=n/24;g.addColorStop(t,rgb(from.map((v,i)=>v+(to[i]-v)*t)));}
ctx.fillStyle=g;ctx.fillRect(0,0,W,H);
const shadow=ctx.createLinearGradient(0,0,W*.85,H*.5);shadow.addColorStop(0,'rgba(0,0,0,.15)');shadow.addColorStop(1,'rgba(0,0,0,0)');ctx.fillStyle=shadow;ctx.fillRect(0,0,W,H);
ctx.fillStyle='#fff';ctx.textAlign='center';
if(options.icons===true)drawIcon(ctx,item.kind,(W-88)/2,95,88);
ctx.font=`600 ${wider?40:32}px "Source Sans 3", sans-serif`;ctx.fillText(item.kind.toUpperCase(),W/2,options.icons===true?245:135);
const detailFacts=spineFacts(item),hasFacts=options.details!==false;
const geometry=spineGeometry(W,options,hasFacts),{base}=geometry;
const maxTitle=base-(options.icons===true?380:230);
const title=(item.displayTitle||item.title||item.id).trim();
ctx.fillStyle='#fff';
ctx.save();ctx.translate(0,base);ctx.rotate(-Math.PI/2);ctx.textAlign='left';
const author=byline(item);
const {lines,titleFont,authorFont,authorText,contextFont,contextText,layout}=spineTypography(ctx,title,author,W,maxTitle,wider&&options.details!==false?spineContext(item):[]);
ctx.font=titleFont;
for(let i=0;ictx.fillText(text,0,layout.context[i]));
ctx.restore();
if(hasFacts){
const {inset,ruleY,firstValueY,labelY,communityY,valueSize,valueMin,labelSize,communitySize,communityMin,iconSize,iconGap}=geometry;
ctx.strokeStyle='rgba(255,255,255,.5)';ctx.lineWidth=2;ctx.beginPath();ctx.moveTo(inset,ruleY);ctx.lineTo(W-inset,ruleY);ctx.stroke();
const {primary,community}=detailFacts,available=W-2*inset;
ctx.textAlign='left';ctx.fillStyle='#fff';
fitText(ctx,primary.value,available,valueSize,valueMin);
ctx.fillText(clippedText(ctx,primary.value,available),inset,firstValueY);
ctx.font=`400 ${labelSize}px "Source Sans 3", sans-serif`;ctx.fillStyle='rgba(255,255,255,.9)';
ctx.fillText(primary.label,inset,labelY);
const text=`${community.value} ${community.label}`,x=inset+iconSize+iconGap;
fitText(ctx,text,W-inset-x,communitySize,communityMin,'400');ctx.fillStyle='#fff';
ctx.fillText(clippedText(ctx,text,W-inset-x),x,communityY);
drawIcon(ctx,community.icon,inset,counterIconTop(ctx,community.value,communityY,iconSize),iconSize);
}
if(options.numbers!==false){
ctx.strokeStyle='rgba(255,255,255,.5)';ctx.lineWidth=2;ctx.beginPath();ctx.moveTo(geometry.inset,geometry.rankRuleY);ctx.lineTo(W-geometry.inset,geometry.rankRuleY);ctx.stroke();
ctx.textAlign='center';ctx.fillStyle='#fff';ctx.font='600 80px "Source Sans 3", sans-serif';ctx.fillText(String(index+1).padStart(2,'0'),W/2,1960);
}
return canvas;
}
export async function canvasBlob(canvas,type='image/jpeg',quality=.96){
return new Promise((resolve,reject)=>canvas.toBlob(b=>b?resolve(b):reject(new Error('The image could not be exported.')),type,quality));
}
export async function exportImages(items,options,onProgress=()=>{}){
await document.fonts.ready;
const result=[];const stamp=Date.now();
for(let i=0;i{let c=value;for(let bit=0;bit<8;bit++)c=(c&1)?(0xedb88320^(c>>>1)):(c>>>1);return c>>>0;});
function crc32(bytes){let c=0xffffffff;for(const b of bytes)c=CRC_TABLE[(c^b)&255]^(c>>>8);return (c^0xffffffff)>>>0;}
export async function makeZip(files){
const chunks=[],directory=[];let offset=0,dirSize=0;
for(const file of files){
const bytes=new Uint8Array(await file.arrayBuffer()),name=new TextEncoder().encode(file.name),crc=crc32(bytes);
const date=new Date(file.lastModified||Date.now());const dosTime=(date.getHours()<<11)|(date.getMinutes()<<5)|(date.getSeconds()>>1),dosDate=((Math.max(1980,date.getFullYear())-1980)<<9)|((date.getMonth()+1)<<5)|date.getDate();
const local=new DataView(new ArrayBuffer(30));local.setUint32(0,0x04034b50,true);local.setUint16(4,20,true);local.setUint16(6,0x800,true);local.setUint16(10,dosTime,true);local.setUint16(12,dosDate,true);local.setUint32(14,crc,true);local.setUint32(18,bytes.length,true);local.setUint32(22,bytes.length,true);local.setUint16(26,name.length,true);
chunks.push(local.buffer,name,bytes);
const central=new DataView(new ArrayBuffer(46));central.setUint32(0,0x02014b50,true);central.setUint16(4,20,true);central.setUint16(6,20,true);central.setUint16(8,0x800,true);central.setUint16(12,dosTime,true);central.setUint16(14,dosDate,true);central.setUint32(16,crc,true);central.setUint32(20,bytes.length,true);central.setUint32(24,bytes.length,true);central.setUint16(28,name.length,true);central.setUint32(42,offset,true);
directory.push(central.buffer,name);dirSize+=46+name.length;offset+=30+name.length+bytes.length;
}
const end=new DataView(new ArrayBuffer(22));end.setUint32(0,0x06054b50,true);end.setUint16(8,files.length,true);end.setUint16(10,files.length,true);end.setUint32(12,dirSize,true);end.setUint32(16,offset,true);
return new Blob([...chunks,...directory,end.buffer],{type:'application/zip'});
}