JS:
import { apiInitializer } from “discourse/lib/api”;
import { iconHTML } from “discourse/lib/icon-library”;
// 1234 → 1.2k, 15000 → 15k
const formatCount = (n) => {
if (n < 1000) return ${n};
const k = n / 1000;
return ${k >= 10 ? Math.round(k) : k.toFixed(1).replace(/\.0$/, "")}k;
};
export default apiInitializer(“1.8.0”, (api) => {
api.decorateCookedElement(
(el, helper) => {
const post = helper?.getModel?.();
if (!post || post.post_number !== 1) return; // first post only
const links = post.link_counts || [];
el.querySelectorAll("a.attachment").forEach((a) => {
if (a.dataset.dlDecorated) return;
a.dataset.dlDecorated = "1";
// Look up the download count for this file
const path = new URL(a.href, location.origin).pathname;
const match = links.find((l) => l.url && l.url.includes(path));
const downloads = match?.clicks || 0;
// Rebuild the button: [icon] filename | count
const fileName = a.textContent.trim();
a.textContent = "";
a.classList.add("gm-download-btn");
a.insertAdjacentHTML("afterbegin", iconHTML("download"));
const name = document.createElement("span");
name.className = "gm-download-name";
name.textContent = fileName;
a.appendChild(name);
const count = document.createElement("span");
count.className = "gm-download-count";
count.textContent = formatCount(downloads);
count.title = `${downloads} download${downloads === 1 ? "" : "s"}`;
a.appendChild(count);
});
},
{ id: "gm-download-button", onlyStream: true }
);
});
CSS:.gm-download-btn {
display: inline-flex;
align-items: center;
gap: 0.6em;
padding: 0.55em 0.55em 0.55em 1.2em;
border-radius: 999px;
background: var(–tertiary);
color: var(–secondary) !important;
font-weight: 600;
text-decoration: none;
&:hover {
background: var(–tertiary-hover);
color: var(–secondary) !important;
}
.d-icon {
color: var(–secondary);
}
.gm-download-count {
margin-left: 0.4em;
padding: 0.15em 0.8em;
border-radius: 999px;
background: rgba(255, 255, 255, 0.22);
font-size: var(–font-down-1);
font-variant-numeric: tabular-nums;
}
}