Scrapbox のトップページに今日更新したページ数を表示する

May 14, 2022 06:30 ·

Scrapbox のトップページに今日どれぐらいのページを更新したかがわかれば、ページを編集するモチベーションが上がるかなと思ったので、やってみた。自分のユーザー名のページを作成し、 code:script.js に以下のコードを記述すると、更新したページ数を画面下に表示できる。

const url = "https://scrapbox.io/api/stream/{プロジェクト名}";
const opts = {
  headers: {
    "Content-Type": "application/json"
  },
};
fetch(url, opts).then(res => res.json()).then(json => {
const pages = json.pages;
const history = {};
const endDate = new Date();
let startDate;
const getLatestLine = (lines) => {
 let latestLine;
 for(let i = 0; i < lines.length;i++) {
 	const line = lines[i];
	if (i === 0) {
	   latestLine = line;
 	} else if (latestLine.updated < line.updated) {
 	   latestLine = line;
 	}
 }
 return latestLine;
}

for(let i = 0; i < pages.length;i++){
	const page = pages[i];
	const line = getLatestLine(page.lines);
 	const updatedTimeStamp = parseInt(line.created,10) * 1000;
 	const d = new Date(updatedTimeStamp);
 	const updated =  new Date(d.getFullYear(), d.getMonth(), d.getDate());
 	if (!startDate) {
  	    startDate = updated;
  	} else if (startDate > updated) {
  		startDate = updated;
  	 }
 	if (!history[updated]){
 	    history[updated] = 1;
 	} else {
 		history[updated] += 1;
 	}
}
//https://stackoverflow.com/questions/4413590/javascript-get-array-of-dates-between-2-dates
const getDaysArray = function(s,e) {for(var a=[],d=new Date(s);d<=new Date(e);d.setDate(d.getDate()+1)){ a.push(new Date(d));}return a;};

const differences = getDaysArray(startDate,endDate);
const normalizeHistory = (history,differences) => {
	const normalized = {};
    for(let i = 0 ; i < differences.length; i++) {
    	const d = differences[i];
        if (!history[d]) {
            normalized[d] = 0;
        } else {
        	normalized[d] = history[d];
        }
    }
    return normalized;
};
const normalizedHistory = normalizeHistory(history,differences);
const normalizedHistoryArray = Object.entries(normalizedHistory).reverse();
const numberOfPagesUpdatedToday = normalizedHistoryArray[0][1];
const pageLabel = numberOfPagesUpdatedToday > 1 ? 'pages' : 'page'
const t = `<span class="item">, updated  ${numberOfPagesUpdatedToday} ${pageLabel} today</span>`;
$(".status-bar .page-list-status").append(t);
});
image