A popularity rank doesn't tell you how many catalog fonts outrank it.
You're adding a percentile to your font dashboard. The sorting looks right, the percentage formatter behaves, and the result feels suspiciously authoritative.
popularity and trending are sparse upstream snapshot ranks where lower is better. They support ordering, but their gaps can't establish catalog percentiles or percentage growth in usage.
The denominator is missing
The source publishes these ranks from an opaque upstream universe. The Actor preserves them rather than renumbering the returned families, so dividing a rank by your downloaded row count combines measurements from different populations.
That's the trap.
These deliberately hypothetical Example ranks expose the shortcut without requiring malformed data.
const exampleRanks = [1, 200, 5000]; const inventedPercentiles = exampleRanks.map( rank => 100 * (1 - rank / exampleRanks.length), ); const hasImpossiblePercentile = inventedPercentiles.some( value => value < 0 || value > 100, ); The calculation can produce a negative percentile. The arithmetic works.
Even when the answer falls inside the expected range, it still lacks a valid interpretation, because a plausible result doesn't establish that your denominator belongs to the upstream ranking universe.
Keep the available signals separate:
| Field | Defensible dashboard label | Unsupported interpretation |
|---|---|---|
popularity | Upstream popularity rank | Global catalog percentile |
trending | Upstream trending rank | Percentage increase in usage |
defaultSort | Dense catalog position | Popularity position |
The dense ordering gives you catalog positions. It doesn't supply the missing popularity denominator, and substituting it would quietly change the question your dashboard claims to answer.
Your consumer needs separate paths:
upstream rank ───────────────> preserve as source evidence │ └─ explicit cohort ──> calculate a local comparison snapshot pair ──────────────> report rank movement Fetch the snapshot you mean
The font metadata Actor fetches the current public catalog on each run. Optional license and file enrichment adds per-family requests; neither supplies a missing popularity denominator.
Leave those packs disabled for this dashboard. You need comparison data.
This Example request selects the library without additional filters and makes both enrichment choices explicit.
import { ApifyClient } from 'apify-client'; import { z } from 'zod'; const client = new ApifyClient({ token: process.env.APIFY_TOKEN }); const run_input = { mode: 'listAll', sortBy: 'popularity', maxItems: 5000, includeLicense: false, includeFiles: false, }; const run = await client .actor('nimbryxo-studio/google-fonts-library-metadata-extractor') .call(run_input); if (run.status !== 'SUCCEEDED') { throw new Error(`Snapshot run ended with ${run.status}`); } const { items } = await client .dataset(run.defaultDatasetId) .listItems(); const rankSchema = z.number().finite(); const fontSchema = z.object({ recordType: z.literal('font'), family: z.string().min(1), popularity: rankSchema.optional(), trending: rankSchema.optional(), defaultSort: rankSchema.optional(), scrapedAt: z.string().datetime({ offset: true }), }); type FontRow = z.infer<typeof fontSchema>; const fontRows: FontRow[] = []; const rejected: unknown[] = []; for (const item of items) { const parsed = fontSchema.safeParse(item); if (parsed.success) fontRows.push(parsed.data); else rejected.push(item); } Empty fields are omitted, so missing ranks remain missing. Converting them to zero would place unranked families ahead of ranked ones, turning an absence of evidence into the strongest popularity claim on the screen.
Typed error records also belong outside the font cohort. Keep rejected available for inspection.
A successful run doesn't establish a library-wide denominator: your calculation can describe only the validated rows you retrieved unless you separately establish retrieval completeness and ranked coverage.
Until then, label the comparison accordingly.
Canonical names survive a rerun
Family lookups accept case-insensitive names and display aliases, and handle duplicate requests. A requested label therefore isn't a reliable identity for comparing snapshots.
Use the returned canonical family. Array position remembers where something arrived.
That distinction matters when a later request uses an alias for a family you've already stored, because treating the requested spelling as identity can manufacture a new competitor.
The consumer below collapses matching analytical records and sets aside conflicting duplicates. That's a defensive ingestion policy, not a claim that duplicates are expected.
This block retains a family only when its validated records agree.
const currentByFamily = new Map<string, FontRow>(); const conflicts = new Set<string>(); for (const row of fontRows) { if (conflicts.has(row.family)) continue; const existing = currentByFamily.get(row.family); if (existing && JSON.stringify(existing) !== JSON.stringify(row)) { currentByFamily.delete(row.family); conflicts.add(row.family); continue; } currentByFamily.set(row.family, row); } Don't choose whichever conflicting row arrived last. Arrival order doesn't establish authority.
Input fallbacks deserve attention too: an empty byFamily selection falls back to a default family, so passing an empty selection doesn't express an empty comparison group.
Choose the mode deliberately.
What does your percentile actually compare?
You can calculate a useful local percentile. Name what it measures.
Here, the cohort consists of unique, validated, nonconflicting returned families with a popularity rank, and the percentile means the percentage of those families with a strictly worse rank.
Ties don't count as worse. Tied families share a competition position, defined as one plus the number of strictly better families.
This block calculates both measures without treating gaps as distances.
const ranked = [...currentByFamily.values()].filter( (row): row is FontRow & { popularity: number } => row.popularity !== undefined, ); const sortedRanks = ranked .map(row => row.popularity) .sort((left, right) => left - right); const localByRank = new Map< number, { position: number; percentile: number | null } >(); for (let start = 0; start < sortedRanks.length;) { let end = start + 1; while ( end < sortedRanks.length && sortedRanks[end] === sortedRanks[start] ) { end++; } localByRank.set(sortedRanks[start], { position: start + 1, percentile: sortedRanks.length > 1 ? 100 * (sortedRanks.length - end) / sortedRanks.length : null, }); start = end; } const localComparisons = ranked.map(row => ({ ...row, localComparison: localByRank.get(row.popularity)!, })); const cohortFamilies = ranked.map(row => row.family).sort(); const missingPopularity = currentByFamily.size - ranked.length; A singleton cohort gets no percentile. There's nobody else to compare.
Label the result “Returned cohort popularity percentile,” with its definition nearby, and retain run_input, cohortFamilies, and the dataset identifier so you can reconstruct what the comparison included.
Keep missingPopularity, rejected records, and conflicting families alongside it. Exclusions affect the denominator.
This calculation has a useful property: widening the upstream rank gaps without changing order or ties won't change your local result, because it counts families rather than rank units.
Changing a filter does change the question. A family can improve its local percentile simply because stronger competitors leave the cohort.
That's a population change. Your dashboard should make it visible.
Rank movement isn't usage growth
Subtracting snapshot ranks describes movement in the published scale. It can't describe how much usage changed.
Other families can move around your tracked family, while changes to the upstream universe and gaps in its ranks prevent the subtraction from counting competitors overtaken.
Keep both snapshots.
Compare canonical names, preserve both collection timestamps, and decline movement when a rank is missing or the snapshots aren't chronological.
This function leaves the baseline empty until you load a previously saved, validated snapshot.
function compareSnapshots( before: ReadonlyMap<string, FontRow>, after: ReadonlyMap<string, FontRow>, ) { return [...after.values()].map(row => { const earlier = before.get(row.family); const chronological = earlier !== undefined && Date.parse(earlier.scrapedAt) < Date.parse(row.scrapedAt); const prior = chronological ? earlier : undefined; const movement = ( previous: number | undefined, current: number | undefined, ) => previous !== undefined && current !== undefined ? previous - current : null; return { family: row.family, scrapedAt: row.scrapedAt, previousScrapedAt: earlier?.scrapedAt ?? null, popularityMovement: movement(prior?.popularity, row.popularity), trendingMovement: movement(prior?.trending, row.trending), }; }); } const previousByFamily = new Map<string, FontRow>(); const movements = compareSnapshots(previousByFamily, currentByFamily); Positive movement means improvement under this sign convention. It doesn't mean more installations, downloads, page views, or market share.
scrapedAt records collection time. Without the upstream signal's measurement interval, collecting snapshots regularly still doesn't turn their difference into a usage growth rate.
An unmatched family gets no movement calculation. Its absence from your retrieved cohort doesn't prove it disappeared from the catalog.
Make the label carry its evidence
The worked example uses Google Fonts Library Metadata Extractor. The reusable pattern keeps source evidence, local calculations, and presentation claims distinguishable.
The broken assumption is that a sortable number must also measure magnitude. A sorting check can pass while every growth label remains unjustified, because correct ordering says nothing about the distance between neighboring values.
Put a guard where labels are assembled.
This formatter rejects percentage-growth requests backed only by rank fields.
type RankPresentation = { metric: 'popularity' | 'trending'; kind: 'rank' | 'rankMovement' | 'percentageGrowth'; value: number; }; function formatRankClaim(claim: RankPresentation): string { if (claim.kind === 'percentageGrowth') { throw new Error('Rank fields cannot substantiate percentage growth'); } if (!Number.isFinite(claim.value)) { throw new Error('A rank claim requires a finite value'); } if (claim.kind === 'rank') { return `${claim.metric} rank: ${claim.value}`; } const sign = claim.value > 0 ? '+' : ''; return `${claim.metric} rank movement: ${sign}${claim.value}`; } const popularityLabels = ranked.map(row => formatRankClaim({ metric: 'popularity', kind: 'rank', value: row.popularity, }), ); The guard covers claims routed through it. Give dashboard labels and exports the same boundary, or a spreadsheet formula can quietly restore the unsupported percentage after your application carefully refused to calculate it.
Typography won't rescue that column.
We'd rather leave a growth field absent than make a precise claim from evidence that supports only direction.
Before the dashboard ships
- Keep raw ranks and their scrape timestamps.
- Separate font records from errors and unrecognized rows.
- Key snapshots by canonical family.
- Name the local cohort, exclusions, and tie policy.
- Require a real baseline before showing movement.
- Reserve usage-growth claims for actual usage measurements.
A rank can tell you who's ahead. It can't tell you how much more they're used.
Drafted with AI assistance and reviewed for accuracy.
