// ==UserScript==
// @name WaniKani Workload Graph
// @namespace rwesterhof
// @version 1.0.2
// @description adds a button to the heatmap that displays your average workload over time
// @match https://www.wanikani.com/
// @match https://preview.wanikani.com/
// @match https://www.wanikani.com/dashboard
// @match https://preview.wanikani.com/dashboard
// @require https://greasyfork.org/scripts/410909-wanikani-review-cache/code/Wanikani:%20Review%20Cache.js?version=852495
// @run-at document-end
// @grant none
// ==/UserScript==
(function(wkof, review_cache) {
'use strict';
/* global $, wkof */
if (!wkof) {
let response = confirm('WaniKani Workload Graph script requires WaniKani Open Framework.\n Click "OK" to be forwarded to installation instructions.');
if (response) {
window.location.href = 'https://community.wanikani.com/t/instructions-installing-wanikani-open-framework/28549';
}
return;
}
// --------------------------- //
// -------- TRIGGER ---------- //
// --------------------------- //
var graphButton =
'<li class="sitemap__section"><button id="headerGraphButton" class="sitemap__section-header" data-navigation-section-toggle="" data-expanded="false" aria-expanded="false" type="button" onclick="window.graphReviews()">'
+ '<span lang="ja">図表</span><span lang="en" class="font-sans">Graph</span>'
+ '</button></li>';
var heatmapButton =
'<button class="graph-button hover-wrapper-target" onclick="window.graphReviews()"'
// todo: put in css for class graph-button
+ 'style="height: 30px; width: 30px; background-color: transparent !important; outline: none !important; box-shadow: none !important; color: var(--color); border: none; left: 25px; top: -5px;">'
+ '<div class="hover-wrapper above">Workload graph</div>'
+ '<i class="icon-bar-chart"></i>'
+ '</button>';
// put graph button in header initially
$('#sitemap').prepend(graphButton);
// add event listener
$('.dashboard')[0].addEventListener('heatmap-loaded', moveButtonToHeatmap);
// eventlistener that moves the graph button to the heatmap once it is loaded
function moveButtonToHeatmap(event) {
$('#headerGraphButton').detach();
$('#heatmap .views .reviews.view').prepend(heatmapButton);
}
// --------------------------- //
// -- VARIABLES & CONSTANTS -- //
// --------------------------- //
const msInDay = 24 * 60 * 60 * 1000;
const maxWidth = 900;
const minWidth = maxWidth / 2;
const maxPointSize = 10;
const xAxisPadding = 50;
const yAxisPadding = 50;
const categoryColor = [ "#dd0093", "#882d9e", "#294ddb", "#0093dd" ];
const resetColors = ["#660000", "#aaaaaa", "#0000cc", "#00cc00", "#cccc00", "#cc00cc", "#00cccc", "#999999", "#0000aa", "#00aa00", "#aaaa00", "#aa00aa", "#00aaaa", "#666666", "#000099", "#009900", "#999900", "#990099", "#009999"];
const labelAll = { type: "all" };
const labelLevel = { type: "level", signal: 5 }; // x axis labels every signalLevel
// OPTIONS
var runningAverageDays = 7;
var fillInd = [ true, false ];
var wlgReverse = false; // set to true to put enlightened on bottom and apprentice on top
// ------------------------------------ //
// ----- RETRIEVAL AND STRIPPING ------ //
// ------------------------------------ //
var retrieved = false;
var cachedStrippedData = null;
// main button entry point takes care of retrieval and shows the workload graph
async function graphReviews() {
if (!retrieved) {
wkof.include('ItemData');
await wkof.ready('ItemData')
.then(displayProgressPane)
.then(stripData);
retrieved = true;
}
displayGraph();
}
window.graphReviews = graphReviews;
// produces an empty stripped data object
function getBlankStrippedData() {
return { lastReviewDate: 0, reviewDays: [], reviewsPerLevel: [], levelUps: [] };
}
// convert stage to category
const categories = [ -1, 0, 0, 0, 0, 1, 1, 2, 3, 4 ];
function toCategory(stage) {
return categories[stage];
}
// produces an empty stripped data review day
function getBlankReviewDayObj() {
return { day: 0,
date: 0,
year: 0,
reviewsPerStage: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
reviewsPerCategory: [0, 0, 0, 0],
reviewsTotal: 0
};
}
// gets an inited count per level per day
function getReviewsPerLevel(strippedData, level) {
var curList = strippedData.reviewsPerLevel.pop();
if (!curList) {
curList = new Array(61);
}
strippedData.reviewsPerLevel.push(curList);
if (!curList[level]) {
curList[level] = { level: level, total: 0, errors: 0 };
}
return curList[level];
}
// pushes all > reset level reviews to a pre-reset review overview
// keeps all < reset level reviews for the "current run" overview
function processResetToLevel(strippedData, level) {
var curList = strippedData.reviewsPerLevel.pop();
if (!curList) {
curList = new Array(61);
}
else {
var preResetReviews = new Array(61);
for (var index = level; index < curList.length; index++) {
preResetReviews[index] = curList[index];
delete curList[index];
}
strippedData.reviewsPerLevel.push(preResetReviews);
}
strippedData.reviewsPerLevel.push(curList);
}
// strips the review_cache down to what is needed for the current script
async function stripData() {
var data = await Promise.all([review_cache.get_reviews(), wkof.ItemData.get_items('assignments, include_hidden')]);
var strippedData = getBlankStrippedData();
if (data.length < 1 || data[0].length < 1 || data[0][0].length < 1) return strippedData;
// get the level ups first
strippedData.levelUps = await get_level_ups(data[1]);
// determine the resetTimestamps (if any)
var previousLevel = 0;
var resetTimestamps = strippedData.levelUps.reduce((resultObj, levelItem) => {
if (levelItem[0] <= previousLevel) resultObj.push([ levelItem[0], levelItem[1].minTs ]);
previousLevel = levelItem[0];
return resultObj;
}, []);
var reviews = data[0];
var minDate = new Date(data[0][0][0]);
minDate.setHours(0,0,0,0);
var minMs = minDate.getTime();
var curYear = 0;
var wkDays = 0;
var progressCounter = data[0].length;
var resetToProcess = 0;
const itemsById = await wkof.ItemData.get_index(await wkof.ItemData.get_items('include_hidden'), 'subject_id');
var stripFunction = function(item) {
if (--progressCounter % 100000 == 50000) {
console.log("Processing... " + progressCounter + " reviews left");
}
var nextDateMs = minMs + (wkDays * msInDay);
while (item[0] > nextDateMs) {
var nextReviewDay = getBlankReviewDayObj();
nextReviewDay.date = nextDateMs;
var reviewYear = new Date(nextReviewDay.date).getFullYear();
if (reviewYear > curYear) {
nextReviewDay.year = reviewYear;
curYear = reviewYear;
}
wkDays++;
nextDateMs += msInDay;
nextReviewDay.day = wkDays;
strippedData.reviewDays.push(nextReviewDay);
}
var reviewDay = strippedData.reviewDays[wkDays-1];
reviewDay.reviewsPerStage[item[2]]++;
reviewDay.reviewsPerCategory[toCategory(item[2])]++;
reviewDay.reviewsTotal++;
if ( (resetToProcess < resetTimestamps.length)
&& (resetTimestamps[resetToProcess][1] <= item[0])
) {
processResetToLevel(strippedData, resetTimestamps[resetToProcess][0]);
resetToProcess++;
}
var level = itemsById[item[1]].data.level;
var reviewsPerLevel = getReviewsPerLevel(strippedData, level);
reviewsPerLevel.total++;
reviewsPerLevel.errors += (item[3]+item[4]==0?0:1);
strippedData.lastReviewDate = item[0];
};
reviews.forEach(stripFunction);
cachedStrippedData = strippedData;
return strippedData;
}
// plain copy from the heatmap script - wonder if we can store this somewhere so it can be reused rather than refetched. Also
// requires retrieval of all the items from wkof.
// ...and we adapted it. I'm using this method to also determine the exact (as exact as possible) timestamps of resets
// Get level up dates from API and lesson history
async function get_level_ups(items) {
let level_progressions = await wkof.Apiv2.get_endpoint('level_progressions');
let first_recorded_date = level_progressions[Math.min(...Object.keys(level_progressions))].data.unlocked_at;
// Find indefinite level ups by looking at lesson history
let levels = {};
// Sort lessons by level then unlocked date
items.forEach(item => {
if (item.object !== "kanji" || !item.assignments || !item.assignments.unlocked_at || item.assignments.unlocked_at >= first_recorded_date) return;
let date = new Date(item.assignments.unlocked_at).toDateString();
if (!levels[item.data.level]) levels[item.data.level] = {};
// altered : store an object with count and min timestamp instead of just a count
if (!levels[item.data.level][date]) levels[item.data.level][date] = { minTs: item.assignments.unlocked_at, count: 1 };
else {
// altered: store an object with count and min timestamp instead of just a count
levels[item.data.level][date].count++;
if (item.assignments.unlocked_at < levels[item.data.level][date].minTs) levels[item.data.level][date].minTs = item.assignments.unlocked_at;
}
});
// Discard dates with less than 10 unlocked
// then discard levels with no dates
// then keep earliest date for each level
for (let [level, data] of Object.entries(levels)) {
// altered as we now have a object in stead of just a count
for (let [date, countObj] of Object.entries(data)) {
if (countObj.count < 10) delete data[date];
}
if (Object.keys(levels[level]).length == 0) {
delete levels[level];
continue;
}
// altered, instead of a resulting date we store date and min timestamp per level
var minDate = Object.keys(data).reduce((low, curr) => low < curr ? low : curr, Date.now());
var minData = levels[level][minDate];
levels[level] = { date: minDate, minTs: Date.parse(minData.minTs) };
}
// Map to array of [[level0, date0], [level1, date1], ...] Format
levels = Object.entries(levels).map(([level, date]) => [Number(level), date]);
// Add definite level ups from API
// altered to provide the same object format (date + min Timestamp)
Object.values(level_progressions).forEach(level => levels.push([level.data.level, { date: new Date(level.data.unlocked_at).toDateString(), minTs: Date.parse(level.data.unlocked_at) }]));
return levels;
}
// -------------------------------------- //
// ------------- PROCESSING ------------- //
// -------------------------------------- //
var init = [ false, false ];
var graphs = [ "workloadGraph", "levelDifficultyGraph" ];
var currentGraph = 0;
// determines if the current graph must be redrawn or simply displayed
function displayGraph() {
if (!init[currentGraph]) {
var progressPane = $('#' + graphs[currentGraph]);
progressPane.removeClass('hidden');
var dataPoints = toDataPoints(cachedStrippedData);
var graphPoints = scaleGraph(dataPoints);
drawGraph(graphPoints);
init[currentGraph] = true;
}
else {
$('#' + graphs[currentGraph]).removeClass('hidden');
}
}
// inits a blank data point object
function getBlankWLGDataPointObj() {
return { point: 0,
year: 0,
levelUp: 0,
nrOfDays: 0,
reviewsPerCategory: [0, 0, 0, 0],
reviewsTotal: 0
};
}
// retrieves the matching data point object from the array. Inits if not yet existing
function getWLGDataPoint(dataPoints, index) {
if (index >= dataPoints.length) return null;
if (!dataPoints[index]) {
dataPoints[index] = getBlankWLGDataPointObj();
dataPoints[index].point = index;
}
return dataPoints[index];
}
// adds the values of two arrays together
function addArrayTotals(arrayOne, arrayTwo) {
if (arrayOne == null) return arrayTwo;
if (arrayTwo == null) return arrayOne;
if (arrayTwo.length < arrayOne.length) return addArrayTotals(arrayTwo, arrayOne);
for (var index = 0; index < arrayOne.length; index++) {
arrayOne[index] += arrayTwo[index];
}
return arrayOne;
}
function toDataPoints(strippedData) {
switch(currentGraph) {
case 0:
return toWLGDataPoints(strippedData);
case 1:
return toLDDataPoints(strippedData);
default:
return [];
}
}
// accumulate reviewdata to data points
function toWLGDataPoints(strippedData) {
var nrOfEntries = strippedData.reviewDays.length;
console.log("Scaling for " + nrOfEntries + " review days");
var daysPerPoint = Math.floor(nrOfEntries / maxWidth);
if ((nrOfEntries % maxWidth > 0) || (daysPerPoint == 0)) {
daysPerPoint++;
}
var totalPoints = Math.floor(nrOfEntries / daysPerPoint);
if (nrOfEntries % daysPerPoint > 0) {
totalPoints++;
}
var dataPoints = new Array(totalPoints + 1);
var cookFunction = function(reviewDay) {
for (var countDay = reviewDay.day; countDay < reviewDay.day + runningAverageDays; countDay++) {
var xValue = Math.ceil(countDay / daysPerPoint);
var dataPoint = getWLGDataPoint(dataPoints, xValue);
if (!dataPoint) break;
dataPoint.nrOfDays++;
dataPoint.reviewsPerCategory = addArrayTotals(dataPoint.reviewsPerCategory, reviewDay.reviewsPerCategory);
dataPoint.reviewsTotal += reviewDay.reviewsTotal;
// add xAxis labels for this point, if any
if (countDay == reviewDay.day) {
if (reviewDay.year != 0) {
dataPoint.year = reviewDay.year;
}
const searchDate = new Date(reviewDay.date).toDateString();
let level = (strippedData.levelUps.find(a=>a[1].date==searchDate) || [undefined])[0];
// note that we overwrite any previous level label (if you level up and reset on the same day or on consecutive days that are merged)
// because we're only interested in the latest label that goes with this data point
if (level) {
dataPoint.levelUp = level;
}
}
}
};
strippedData.reviewDays.forEach(cookFunction);
// now we have datapointed the xaxis points properly, now do the same for yaxis points
var dataPointSeries = new Array(dataPoints.length);
var xAxisYears = new Array();
var xAxisLevelUps = new Array();
var yAxisMaxValue = 0;
var pointFunction = function(dataPoint) {
if (dataPoint == null) return;
dataPointSeries[dataPoint.point] = [0, 0, 0, 0];
var divider = dataPoint.nrOfDays;
for (var index = 0; index < dataPointSeries[dataPoint.point].length; index++) {
if (wlgReverse) {
dataPointSeries[dataPoint.point][index] = getArraySum(dataPoint.reviewsPerCategory, index, dataPoint.reviewsPerCategory.length) / dataPoint.nrOfDays;
}
else {
dataPointSeries[dataPoint.point][index] = getArraySum(dataPoint.reviewsPerCategory, 0, index) / dataPoint.nrOfDays;
}
}
if (wlgReverse) dataPointSeries[dataPoint.point].reverse();
if (dataPoint.year != 0) {
xAxisYears.push([ dataPoint.point, dataPoint.year ]);
}
if (dataPoint.levelUp != 0) {
xAxisLevelUps.push([ dataPoint.point, dataPoint.levelUp ]);
}
var yValue = dataPoint.reviewsTotal / dataPoint.nrOfDays;
yAxisMaxValue = Math.max(yValue, yAxisMaxValue);
};
dataPoints.forEach(pointFunction);
var xAxisLabels = new Array();
xAxisLabels.push({ labelType: labelAll, labels: xAxisYears });
xAxisLabels.push({ labelType: labelLevel, labels: xAxisLevelUps }); // by going in the array later, the labels overwrite the previous labels
// drawing color for the series
var seriesColors = [...categoryColor];
if (wlgReverse) seriesColors.reverse();
return { dataPointSeries: dataPointSeries, seriesColors: seriesColors, xAxisLabels: xAxisLabels, yAxisMaxValue: yAxisMaxValue, graphTitle: "Workload - reviews per day" };
}
// sums array values from index to index inclusive
function getArraySum(array, fromIndexIncl, toIndexIncl) {
if (!array) return 0;
const minIndex = Math.min(Math.max(0, fromIndexIncl), array.length);
const maxIndex = Math.min(array.length, toIndexIncl + 1);
var result = 0;
for (var index = minIndex; index < maxIndex; index++) {
result += array[index];
}
return result;
}
// accumulate reviewdata to data points
function toLDDataPoints(strippedData) {
var maxLevel = 0;
var maxFinder = function(levelList) {
var reviewMax = levelList.reduce((max, item) => { return ((item && (item.level > max)) ? item.level : max); }, 1);
if (reviewMax > maxLevel) {
maxLevel = reviewMax;
}
}
strippedData.reviewsPerLevel.forEach(maxFinder);
console.log("Scaling for " + maxLevel + " levels");
var dataPoints = new Array(maxLevel + 1);
var yAxisMaxValue = 0;
// convert levels by reset series to reset series by level
var cookFunction = function(levelList) {
for (var levelNr = 1; levelNr < dataPoints.length; levelNr++) {
var seriesLevelInfo = levelList[levelNr];
if (!dataPoints[levelNr]) dataPoints[levelNr] = new Array();
if (!seriesLevelInfo) {
dataPoints[levelNr].push(0);
}
else {
var yValue = 100 * seriesLevelInfo.errors / seriesLevelInfo.total; // error percentage per level
dataPoints[levelNr].push(yValue);
yAxisMaxValue = Math.max(yValue, yAxisMaxValue);
}
}
};
strippedData.reviewsPerLevel.forEach(cookFunction);
// reverse the series to draw them in proper order
dataPoints.forEach(item => item.reverse());
// x axis labels
var xAxisLevelUps = new Array();
for (var i = 1; i <= maxLevel; i++) {
xAxisLevelUps.push([ i, i ]);
}
var xAxisLabels = new Array();
xAxisLabels.push({ labelType: labelLevel, labels: xAxisLevelUps });
// drawing color for the series
var seriesColors = [...resetColors];
return { dataPointSeries: dataPoints, seriesColors: seriesColors, xAxisLabels: xAxisLabels, yAxisMaxValue: yAxisMaxValue, graphTitle: "Level difficulty - error percentage", seriesOpacity: 0.4 };
}
// ---------------------------------------------- //
// -------------- DISPLAY ----------------------- //
// ---------------------------------------------- //
const graphDiv = [
'<div id="workloadGraph" class="" style="background-color:#f4f4f4; position: fixed; top: 100px; left: 100px; z-index: 1;"></div>',
'<div id="levelDifficultyGraph" class="hidden" style="background-color:#f4f4f4; position: fixed; top: 100px; left: 100px; z-index: 1;"></div>'
];
const optionDiv = [
'<div id="workloadGraphOptionsDiv" style="position: absolute; right:20px; top:20%;">'
+ '<span title="Number of days the running average of reviews is calculated over. A higher number leads to a smoother graph">Running average days</span><br/>'
+ '<input id="runningAverageInput" maxlength="4" style="width:100px;"/><p/>'
+ '<button onclick="window.adjustWLGOptions()" style="cursor:pointer;">Redraw</button></div>',
'<div id="levelDifficultyGraphOptionsDiv" style="position: absolute; right:20px; top:20%;">'
+ '</div>'
];
const optionDivWidth = 180;
const closeGraphButton = '<button id="closeGraphButton" onclick="window.hideGraph()" title="Close window" style="cursor:pointer; position:absolute; top: 10px; right: 10px; border: 0px;"><i class="icon-minus"></i></button>';
const toggleGraphButton = '<button id="toggleGraphButton" onclick="window.toggleGraph()" title="Switch graph type" style="cursor:pointer; position:absolute; top: 10px; right: 40px; border: 0px;"><i class="icon-inbox"></i></button>';
function hideGraph() {
$('#' + graphs[currentGraph]).addClass('hidden');
}
window.hideGraph = hideGraph;
function toggleGraph() {
hideGraph();
currentGraph = (currentGraph + 1) % graphs.length;
displayGraph();
}
window.toggleGraph = toggleGraph;
// process new options and redraw
function adjustWLGOptions() {
var newDays = $('#runningAverageInput')[0].value;
if (isNaN(newDays)) {
newDays = 7;
$('#runningAverageInput')[0].value = 7;
}
newDays = parseInt(newDays);
if (newDays < 1) {
newDays = 7;
$('#runningAverageInput')[0].value = 7;
}
runningAverageDays = newDays;
init[currentGraph] = false;
displayGraph();
}
window.adjustWLGOptions = adjustWLGOptions;
// indicate the user clicked the button by showing the init... pane - and set up all the graph divs
function displayProgressPane() {
for (var index = 0; index < graphs.length; index++) {
$('.srs-progress').before(graphDiv[index]);
var graphCanvas = document.createElement("canvas");
graphCanvas.id = graphs[index] + "Canvas";
graphCanvas.width = 200;
graphCanvas.height = 200;
var progressPane = $('#' + graphs[index]);
progressPane.append(graphCanvas);
}
progressPane = $('#' + graphs[currentGraph]);
progressPane.removeClass('hidden');
clearGraph("Init..."); // turns out the graph refresh during processing doesn't want to trigger, so we log instead
}
// draws a single point on the canvas
function drawPoint(ctx, toX, toY, xAxisPointSize, fillIndicator, sameValue, firstPointInd) {
if (fillIndicator || (!firstPointInd && !sameValue)) {
ctx.lineTo(toX, toY);
}
else {
ctx.moveTo(toX, toY);
}
if (xAxisPointSize > 1) {
toX += xAxisPointSize - 1;
if (fillIndicator || !sameValue) {
ctx.lineTo(toX, toY);
}
else {
ctx.moveTo(toX, toY);
}
}
}
// clears the current graph and optionally adds progress text
function clearGraph(text) {
var graphCanvas = $('#' + graphs[currentGraph] + 'Canvas')[0];
var ctx = graphCanvas.getContext("2d");
ctx.save();
ctx.fillStyle="#f4f4f4";
ctx.fillRect(0, 0, graphCanvas.width, graphCanvas.height);
ctx.strokeStyle = "#000000";
ctx.beginPath();
ctx.rect(0, 0, graphCanvas.width, graphCanvas.height);
ctx.stroke();
if (text) {
ctx.strokeText(text, xAxisPadding, yAxisPadding);
}
ctx.restore();
}
// translate review datapoints to graph points
function scaleGraph(dataPoints) {
// scaling of axes
var xAxisMaxSize = dataPoints.dataPointSeries.length;
var xAxisPointSize = 1;
if (xAxisMaxSize < minWidth) {
xAxisPointSize = Math.ceil(minWidth / xAxisMaxSize);
xAxisMaxSize = xAxisPointSize * dataPoints.dataPointSeries.length;
if (xAxisPointSize > maxPointSize) {
xAxisPointSize = maxPointSize;
xAxisMaxSize = minWidth;
}
}
var yAxisMaxSize = Math.ceil(xAxisMaxSize * 9 / 16); // take a standard aspect ratio
var yScale = 1;
var decimalPlaces = 2;
while (yScale < dataPoints.yAxisMaxValue) {
yScale *=10;
decimalPlaces--;
}
yScale /= 100;
decimalPlaces = Math.max(0, decimalPlaces);
var yAxisMaxValue = Math.ceil(dataPoints.yAxisMaxValue * 1.2 / yScale) * yScale; // let the values climb to abou 80% of the graph
var yAxisPointValue = yAxisMaxValue / yAxisMaxSize; // not an integer
// scale the y values of the series
var graphPointSeries = new Array(dataPoints.dataPointSeries.length);
for (var index = 0; index < dataPoints.dataPointSeries.length; index++) {
var dataPoint = dataPoints.dataPointSeries[index];
if (dataPoint == null) continue;
graphPointSeries[index] = dataPoint.map((a) => (a / yAxisPointValue));
};
// yAxis labels
var nrOfDashes = 3;
var yIndicatorsPer = Math.ceil(yAxisMaxValue / ((nrOfDashes+1) * yScale)) * yScale;
var yAxisValues = new Array();
for (var dash = 1; dash <= nrOfDashes; dash++) {
yAxisValues.push([ ((yIndicatorsPer * dash) / yAxisPointValue), (yIndicatorsPer * dash).toFixed(decimalPlaces) ]);
}
var yAxisLabels = new Array();
yAxisLabels.push({ labelType: labelAll, labels: yAxisValues });
// return the accumulated graph data for drawing
return {
xAxisMaxSize: xAxisMaxSize,
xAxisPointSize: xAxisPointSize,
xAxisLabels: dataPoints.xAxisLabels,
yAxisMaxSize: yAxisMaxSize,
yAxisPointValue: yAxisPointValue,
yAxisLabels: yAxisLabels,
graphPointSeries: graphPointSeries,
seriesColors: dataPoints.seriesColors,
title: dataPoints.graphTitle,
seriesOpacity: dataPoints.seriesOpacity
};
}
// display the graph on canvas
function drawGraph(graphData) {
// resize and empty the canvas for redrawing
var graphCanvas = $('#' + graphs[currentGraph] + 'Canvas')[0];
graphCanvas.width = graphData.xAxisMaxSize + 2*xAxisPadding;
graphCanvas.height = graphData.yAxisMaxSize + 2*yAxisPadding;
clearGraph();
var ctx = graphCanvas.getContext("2d");
if (graphData.graphPointSeries.length < 2) {
ctx.strokeText("No data", xAxisPadding, yAxisPadding);
return;
}
ctx.save();
var baseY = graphCanvas.height - yAxisPadding;
for (var cat = graphData.graphPointSeries[1].length - 1; cat >= 0; cat--) {
if ((cat > 0) && (graphData.seriesOpacity)) {
// seriesOpacity is defined only if series beyond the first are 'greyed out'
ctx.globalAlpha = graphData.seriesOpacity;
}
else {
// first series is always full opacity
ctx.globalAlpha = 1;
}
var currentX = xAxisPadding;
var colorIndex = cat % graphData.seriesColors.length;
ctx.fillStyle = graphData.seriesColors[colorIndex];
ctx.strokeStyle = graphData.seriesColors[colorIndex];
ctx.beginPath();
ctx.moveTo(currentX, baseY);
currentX++;
// nb: 0th entry is not a point!
for (var pointIndex = 1; pointIndex < graphData.graphPointSeries.length; pointIndex++) {
var currentY = baseY - graphData.graphPointSeries[pointIndex][cat];
var sameValue = (graphData.graphPointSeries[pointIndex][cat] == ((cat > 0) ? graphData.graphPointSeries[pointIndex][cat - 1] : 0));
drawPoint(ctx, currentX, currentY, graphData.xAxisPointSize, fillInd[currentGraph], sameValue, (pointIndex == 1));
currentX += graphData.xAxisPointSize;
}
if (fillInd[currentGraph]) {
ctx.lineTo(currentX - 1, baseY);
ctx.lineTo(xAxisPadding, baseY);
ctx.fill();
}
else {
ctx.stroke();
}
}
// draw axes
ctx.strokeStyle = "#000000";
ctx.beginPath();
ctx.moveTo(xAxisPadding, baseY);
ctx.lineTo(xAxisPadding + graphData.xAxisMaxSize, baseY);
ctx.stroke();
var middleCorrection = Math.floor(graphData.xAxisPointSize / 2);
// x axis labels
var labelColors = [ "#007700", "#000000" ];
var xColorOffset = labelColors.length - graphData.xAxisLabels.length % labelColors.length;
for (var index = 0 ; index < graphData.xAxisLabels.length; index++) {
colorIndex = (xColorOffset + index) % labelColors.length;
ctx.strokeStyle = labelColors[colorIndex];
var labelObj = graphData.xAxisLabels[index];
for (var dashIndex = 0; dashIndex < labelObj.labels.length; dashIndex++) {
var atX = xAxisPadding + labelObj.labels[dashIndex][0] * graphData.xAxisPointSize - middleCorrection;
var signalInd = true;
var override = true;
if (labelObj.labelType.type == "level") {
var levelLabel = parseInt(labelObj.labels[dashIndex][1]);
signalInd = (levelLabel % labelObj.labelType.signal == 0);
override = (dashIndex > 0) && (levelLabel <= parseInt(labelObj.labels[dashIndex - 1][1]));
}
var dashLength = (graphData.xAxisLabels.length - index - 1) * 15;
ctx.beginPath();
ctx.moveTo(atX, baseY);
ctx.lineTo(atX, baseY + dashLength + (signalInd ? 10 : 5));
ctx.stroke();
if (signalInd || override) {
var labelOffset = (labelObj.labels[dashIndex][1] + "").length * 3;
ctx.strokeText(labelObj.labels[dashIndex][1], atX - labelOffset, baseY + dashLength + 20);
}
}
}
ctx.beginPath();
ctx.moveTo(xAxisPadding, baseY);
ctx.lineTo(xAxisPadding, baseY - graphData.yAxisMaxSize);
ctx.stroke();
// y axis labels
var yColorOffset = labelColors.length - graphData.yAxisLabels.length % labelColors.length;
for (index = 0 ; index < graphData.yAxisLabels.length; index++) {
colorIndex = (yColorOffset + index) % labelColors.length;
ctx.strokeStyle = labelColors[colorIndex];
labelObj = graphData.yAxisLabels[index];
for (dashIndex = 0; dashIndex < labelObj.labels.length; dashIndex++) {
var atY = baseY - labelObj.labels[dashIndex][0];
if (atY < yAxisPadding) break; // no labels above graph size
signalInd = true;
override = true;
if (labelObj.labelType.type == "level") {
levelLabel = parseInt(labelObj.labels[dashIndex][1]);
signalInd = (levelLabel % labelObj.labelType.signal == 0);
override = (dashIndex > 0) && (levelLabel <= parseInt(labelObj.labels[dashIndex - 1][1]));
}
dashLength = (graphData.yAxisLabels.length - index - 1) * 30;
ctx.beginPath();
ctx.moveTo(xAxisPadding, atY);
ctx.lineTo(xAxisPadding - dashLength - 5, atY); // no long dashes for signal levels
ctx.stroke();
if (signalInd || override) {
labelOffset = (labelObj.labels[dashIndex][1] + "").length * 7;
ctx.strokeText(labelObj.labels[dashIndex][1], xAxisPadding - labelOffset - 6, atY + 3);
}
}
}
// title
ctx.font = "bold 24px Arial, sans-serif";
ctx.fillStyle="#007700";
var titleOffset = graphData.title.length * 6;
ctx.fillText(graphData.title, Math.floor(graphData.xAxisMaxSize / 2) - titleOffset + xAxisPadding, yAxisPadding - 10);
ctx.restore();
// complete the graph window
var currentGraphDiv = $('#' + graphs[currentGraph]);
currentGraphDiv.css('width', graphCanvas.width + optionDivWidth);
// allow closing of the graph
if (!$('#' + graphs[currentGraph] + '#closeGraphButton')[0]) {
currentGraphDiv.append(closeGraphButton);
}
if (!$('#' + graphs[currentGraph] + 'OptionsDiv')[0]) {
currentGraphDiv.append(optionDiv[currentGraph]);
}
// allow toggling of graph type
if (!$('#' + graphs[currentGraph] + '#toggleGraphButton')[0]) {
currentGraphDiv.append(toggleGraphButton);
}
}
function consoleLog(obj) {
$.each(obj, function(key, element) {
console.log('key: ' + key + ', value: ' + element);
});
}
})(window.wkof, window.review_cache);