forked from langchain-ai/docs
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathintegration-downloads-table.js
More file actions
272 lines (235 loc) · 8.7 KB
/
Copy pathintegration-downloads-table.js
File metadata and controls
272 lines (235 loc) · 8.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
/**
* Sortable integration download tables
*
* Generated snippets wrap markdown tables in
* `<div class="integration-downloads-table">`. Cells that need numeric or
* categorical sort expose `<span data-sort-value="...">`. This script makes
* every header clickable and reorders tbody rows.
*
* Download badges (pepy / shields.io) are live images. On enhance, this script
* fetches each badge SVG, parses the displayed count into data-sort-value, and
* re-sorts so order matches the badges even when baked-in values have drifted.
*
* Mintlify auto-injects every .js file under src/, so this runs site-wide.
* A MutationObserver re-enhances tables after client-side navigations.
*/
(function () {
"use strict";
const WRAPPER = ".integration-downloads-table";
const ENHANCED = "data-sort-enhanced";
const BADGE_IMG =
'img[src*="pepy.tech/badge/"], img[src*="img.shields.io/"]';
/** @type {Map<string, Promise<number|null>>} */
const badgeCountCache = new Map();
function parseAbbreviatedCount(raw) {
const text = String(raw || "")
.replace(/\/month/i, "")
.replace(/,/g, "")
.trim();
const match = text.match(/^([\d.]+)\s*([kKmMbB])?$/);
if (!match) return null;
const n = Number(match[1]);
if (Number.isNaN(n)) return null;
const suffix = (match[2] || "").toLowerCase();
if (suffix === "k") return Math.round(n * 1e3);
if (suffix === "m") return Math.round(n * 1e6);
if (suffix === "b") return Math.round(n * 1e9);
return Math.round(n);
}
function extractCountFromPepySvg(svgText) {
const texts = Array.from(
String(svgText).matchAll(/<text[^>]*>([^<]+)<\/text>/g),
).map((match) => match[1].trim());
for (let i = texts.length - 1; i >= 0; i -= 1) {
if (/downloads/i.test(texts[i])) continue;
const count = parseAbbreviatedCount(texts[i]);
if (count !== null) return count;
}
return null;
}
function extractCountFromShields(svgOrLabel) {
const text = String(svgOrLabel);
const labeled =
text.match(/aria-label="([^"]+)"/i) ||
text.match(/<title>([^<]+)<\/title>/i);
const source = labeled ? labeled[1] : text;
const downloads = source.match(/downloads:\s*(.+)/i);
if (downloads) return parseAbbreviatedCount(downloads[1]);
return parseAbbreviatedCount(source);
}
function extractBadgeCount(url, body) {
if (/pepy\.tech/i.test(url)) return extractCountFromPepySvg(body);
if (/shields\.io/i.test(url)) return extractCountFromShields(body);
return extractCountFromPepySvg(body) ?? extractCountFromShields(body);
}
function fetchBadgeCount(url) {
if (badgeCountCache.has(url)) return badgeCountCache.get(url);
const pending = fetch(url, { mode: "cors", credentials: "omit" })
.then(function (response) {
if (!response.ok) return null;
return response.text();
})
.then(function (body) {
if (!body) return null;
return extractBadgeCount(url, body);
})
.catch(function () {
return null;
});
badgeCountCache.set(url, pending);
return pending;
}
function syncDownloadSortValues(table) {
const images = table.querySelectorAll(BADGE_IMG);
if (images.length === 0) return Promise.resolve(false);
const jobs = Array.from(images).map(function (img) {
const span = img.closest("[data-sort-value]");
if (!span) return Promise.resolve(false);
const url = img.currentSrc || img.getAttribute("src") || "";
if (!url) return Promise.resolve(false);
return fetchBadgeCount(url).then(function (count) {
if (count === null) return false;
const next = String(count);
if (span.getAttribute("data-sort-value") === next) return false;
span.setAttribute("data-sort-value", next);
return true;
});
});
return Promise.all(jobs).then(function (results) {
return results.some(Boolean);
});
}
function cellSortValue(cell) {
if (!cell) return { kind: "empty", value: "" };
const marked = cell.querySelector("[data-sort-value]");
if (marked) {
const raw = marked.getAttribute("data-sort-value");
const asNumber = Number(raw);
if (raw !== null && raw !== "" && !Number.isNaN(asNumber)) {
return { kind: "number", value: asNumber };
}
return { kind: "string", value: (raw || "").toLowerCase() };
}
// Name / link column: prefer link text, fall back to cell text.
const link = cell.querySelector("a");
const text = (link ? link.textContent : cell.textContent) || "";
return { kind: "string", value: text.trim().toLowerCase() };
}
function compareValues(a, b, direction) {
const aMissing = a.kind === "number" && a.value < 0;
const bMissing = b.kind === "number" && b.value < 0;
// Keep N/A (-1) at the bottom for either downloads sort direction.
if (aMissing !== bMissing) return aMissing ? 1 : -1;
let result = 0;
if (a.kind === "number" && b.kind === "number") {
result = a.value - b.value;
} else {
result = String(a.value).localeCompare(String(b.value));
}
return direction === "asc" ? result : -result;
}
function sortTable(table, columnIndex, direction) {
const tbody = table.tBodies[0];
if (!tbody) return;
const rows = Array.from(tbody.rows);
rows.sort((rowA, rowB) =>
compareValues(
cellSortValue(rowA.cells[columnIndex]),
cellSortValue(rowB.cells[columnIndex]),
direction,
),
);
rows.forEach((row) => tbody.appendChild(row));
}
function setAriaSort(headers, activeIndex, direction) {
headers.forEach((th, index) => {
if (index === activeIndex) {
th.setAttribute(
"aria-sort",
direction === "asc" ? "ascending" : "descending",
);
} else {
th.removeAttribute("aria-sort");
}
});
}
function enhanceTable(wrapper) {
const table = wrapper.querySelector("table");
if (!table || table.getAttribute(ENHANCED) === "true") return;
const headRow = table.tHead && table.tHead.rows[0];
if (!headRow || !table.tBodies[0]) return;
const headers = Array.from(headRow.cells);
if (headers.length === 0) return;
table.setAttribute(ENHANCED, "true");
// Default: Downloads column descending when present, else first column.
let activeColumn = Math.max(
0,
headers.findIndex((th) => /downloads/i.test(th.textContent || "")),
);
let direction = "desc";
setAriaSort(headers, activeColumn, direction);
sortTable(table, activeColumn, direction);
// Prefer live badge counts over baked-in data-sort-value.
syncDownloadSortValues(table).then(function (changed) {
if (!changed) return;
if (!/downloads/i.test(headers[activeColumn].textContent || "")) return;
sortTable(table, activeColumn, direction);
});
headers.forEach((th, columnIndex) => {
th.setAttribute("data-sortable", "true");
th.setAttribute("tabindex", "0");
th.setAttribute("role", "columnheader");
th.title = "Sort by this column";
const toggle = function (event) {
// Keep markdown header links navigable.
if (event.target && event.target.closest && event.target.closest("a")) {
return;
}
event.preventDefault();
if (activeColumn === columnIndex) {
direction = direction === "asc" ? "desc" : "asc";
} else {
activeColumn = columnIndex;
// Downloads default to high-first; other columns start ascending.
direction = /downloads/i.test(th.textContent || "") ? "desc" : "asc";
}
setAriaSort(headers, activeColumn, direction);
sortTable(table, activeColumn, direction);
};
th.addEventListener("click", toggle);
th.addEventListener("keydown", function (event) {
if (event.key === "Enter" || event.key === " ") {
toggle(event);
}
});
});
}
function enhanceAll(root) {
const scope = root && root.querySelectorAll ? root : document;
scope.querySelectorAll(WRAPPER).forEach(enhanceTable);
}
function start() {
enhanceAll(document);
const observer = new MutationObserver(function (mutations) {
for (const mutation of mutations) {
for (const node of mutation.addedNodes) {
if (!node || node.nodeType !== 1) continue;
if (node.matches && node.matches(WRAPPER)) {
enhanceTable(node);
} else if (node.querySelectorAll) {
enhanceAll(node);
}
}
}
});
observer.observe(document.documentElement, {
childList: true,
subtree: true,
});
}
if (document.readyState === "loading") {
document.addEventListener("DOMContentLoaded", start);
} else {
start();
}
})();