Skip to content

Instantly share code, notes, and snippets.

@WebInspectInc
Last active August 6, 2024 09:52
Show Gist options
  • Save WebInspectInc/4f13e9e02239df3f7074323ce5772203 to your computer and use it in GitHub Desktop.
Save WebInspectInc/4f13e9e02239df3f7074323ce5772203 to your computer and use it in GitHub Desktop.
Word Count Tracker for Obsidian
daysback chartlength location
200
200
"Notes"
const start = moment();
const daysback = parseInt(dv.current().daysback) || 2;
const location = dv.current().location || '';
const dateField = 'created';
const chartColor = '#4e9a06';
const chartlength = parseInt(dv.current().chartlength) || 50;
const docs = dv.pages(location);
const hideTable = false;

function getRecentDocs(numDays) {
	// this function finds recently created docs
	// it uses a where function to return a collection
	// based on days in the past
	return docs
		.where(f => {
			if (!f[dateField] || !f[dateField].toISO) return false;
			var startDate = moment(start);
			var pastDate = startDate.subtract(numDays, 'days');
			var docDate = moment(f[dateField].toISO());
			return docDate.isAfter(pastDate) && docDate.isBefore(start);
		});
}

// creating the table
var ztDocs = getRecentDocs(daysback);

if (!hideTable) {
	dv.table(['link', 'word count', 'date'], ztDocs
		.sort(a => a[dateField], 'desc')
		.map(b => [b.file.link, b.file.size, moment(b[dateField].toISO()).format('YYYY-MM-DD hh:mm')]));
}

// creating the charts
var ztLastWeek = getRecentDocs(chartlength).sort(f => f[dateField]);
var daysData = [];
var totalcount = 0;

// formatting the data
for (var i=0; i<=ztLastWeek.length; i++) {
	var f = ztLastWeek[i];
	if (f && f[dateField]) {
		var itemDate = moment(f[dateField].toISO());
		var newDate = itemDate.format('MM-DD');
		var index = daysData.findIndex(d => d.label === newDate);
		if (index !== -1) {
			daysData[index].num += f.file.size;
		} else {
			daysData.push({label: newDate, num: f.file.size});
		}
		totalcount += 1;
	}
};

var labels = [],
	data = [],
	aggData = [];

daysData.map(el => {
	labels.push(el.label);
	data.push(el.num);

	if (aggData.length) {
		var lastNum = aggData[aggData.length - 1];
		aggData.push(el.num + lastNum);
	} else {
		aggData.push(el.num);
	}
});

const lineChart = {
	type: 'line',
	data: {
	labels: labels,
	datasets: [{
		label: 'Characters Typed',
		data: data,
		backgroundColor: [
			chartColor
		],
		borderColor: [
			chartColor
		],
		borderWidth: 1
	}]
   }
}

const aggregateChart = {
	type: 'line',
	data: {
		labels: labels,
		datasets: [{
			label: 'Aggregate Characters Typed',
			data: aggData,
			backgroundColor: [
				chartColor
			],
			borderColor: [
				chartColor
			],
			borderWidth: 1
		}]
	}
}

window.renderChart(lineChart, this.container);
window.renderChart(aggregateChart, this.container);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment