Sort menu posts by publication date with YYYY-MM-DD shortened-title prefix
This commit is contained in:
@@ -0,0 +1,54 @@
|
||||
<script>
|
||||
(function () {
|
||||
var data = window.blogData;
|
||||
if (!data || !data.articles || !data.articles.length) return;
|
||||
var menu = document.getElementById("menu");
|
||||
if (!menu) return;
|
||||
|
||||
var byAlias = {};
|
||||
data.articles.forEach(function (a) {
|
||||
var alias = String(a.url || "").split("/").pop();
|
||||
if (alias) byAlias[alias] = a;
|
||||
});
|
||||
|
||||
function shorten(t) {
|
||||
t = String(t || "").replace(/\s+/g, " ").trim();
|
||||
if (t.length <= 26) return t;
|
||||
var cut = t.slice(0, 26).replace(/\s+\S*$/, "");
|
||||
return (cut.length ? cut : t.slice(0, 26)) + "…";
|
||||
}
|
||||
|
||||
menu.querySelectorAll("li").forEach(function (li) {
|
||||
var a = li.querySelector(":scope > a");
|
||||
if (!a) return;
|
||||
var m = String(a.getAttribute("href") || "").match(/\.\/([^/?#]+)$/);
|
||||
if (!m) return;
|
||||
var art = byAlias[m[1]];
|
||||
if (!art) return;
|
||||
var date = String(art.date || "").slice(0, 10);
|
||||
li.setAttribute("data-pubdate", date);
|
||||
var span = a.querySelector("span");
|
||||
if (span) {
|
||||
var label = (date ? date + " " : "") + shorten(a.textContent.replace(/\s+/g, " ").trim());
|
||||
var icon = span.querySelector("i");
|
||||
span.textContent = "";
|
||||
if (icon) span.appendChild(icon);
|
||||
span.appendChild(document.createTextNode(" " + label));
|
||||
}
|
||||
});
|
||||
|
||||
menu.querySelectorAll("ul").forEach(function (ul) {
|
||||
var items = Array.from(ul.children);
|
||||
var dated = items.filter(function (li) { return li.hasAttribute("data-pubdate"); });
|
||||
if (dated.length < 2) return;
|
||||
dated.sort(function (x, y) {
|
||||
var dx = x.getAttribute("data-pubdate");
|
||||
var dy = y.getAttribute("data-pubdate");
|
||||
if (dx === dy) return 0;
|
||||
return dx > dy ? -1 : 1;
|
||||
});
|
||||
items.forEach(function (li) { if (!li.hasAttribute("data-pubdate")) ul.appendChild(li); });
|
||||
dated.forEach(function (li) { ul.appendChild(li); });
|
||||
});
|
||||
})();
|
||||
</script>
|
||||
Reference in New Issue
Block a user