Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add ability to draw arbitrary lines #6

Merged
merged 1 commit into from
Dec 13, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 0 additions & 1 deletion app/api/v1/data.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,6 @@ def sales_data():

@bp.get('/data/deaths')
def death_data():
# https://www150.statcan.gc.ca/n1/daily-quotidien/231127/t001b-eng.htm
table = pa_csv.read_csv('app/static/data/can-deaths.csv')
data = {'data': table.to_pylist()}
if request.headers.get('Hx-Request'):
Expand Down
125 changes: 125 additions & 0 deletions app/static/js/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -27,3 +27,128 @@ function addData(chart, newData, labels) {
}
chart.update();
}

const chartStates = new WeakMap();
const arbLines = {
id: "chartjs-arb-lines",

defaults: {
color: "black",
lineThreshold: 15,
lineWidth: 2,
enableKey: "Control", // draw only when keypressed
modifierKey: "Shift", // extends line to borders
},

beforeInit(chart) {
chartStates.set(chart, {
lines: [],
});
},

afterEvent(chart, args, options) {
const { ctx, chartArea } = chart;
const state = chartStates.get(chart);

switch (args.event.type) {
case "mousedown":
if (args.replay !== true && isKeyDown(options.enableKey)) {
// registers mousedown event twice if you "click", ignore one.
state.startXY = { x: args.event.x, y: args.event.y };
}
break;
case "mousemove":
if (state.startXY) {
ctx.beginPath();
ctx.lineWidth = options.lineWidth;
const line = getCoords(chartArea, {
...state.startXY,
x2: args.event.x,
y2: args.event.y,
full: isKeyDown(options.modifierKey),
});
ctx.moveTo(line.x1, line.y1);
ctx.lineTo(line.x2, line.y2);
ctx.strokeStyle = "grey";
ctx.stroke();
ctx.restore();
}
break;
case "mouseup":
if (
isKeyDown(options.enableKey) &&
Math.abs(state.startXY.x - args.event.x) + Math.abs(state.startXY.y - args.event.y) >
options.lineThreshold
) {
// don't draw tiny lines
state.lines.push({
...state.startXY,
x2: args.event.x,
y2: args.event.y,
full: isKeyDown(options.modifierKey),
});
}
state.startXY = null;
break;
}
},

afterDatasetsDraw(chart, args, options) {
const { ctx, chartArea } = chart;
const state = chartStates.get(chart);
for (const line of state.lines) {
ctx.beginPath();
ctx.lineWidth = options.lineWidth;
const drawLine = getCoords(chartArea, line);
ctx.moveTo(drawLine.x1, drawLine.y1);
ctx.lineTo(drawLine.x2, drawLine.y2);
ctx.strokeStyle = options.color;
ctx.closePath();
ctx.stroke();
}
},
};

function getCoords(chartArea, line) {
if (line.full === false) {
return {
x1: line.x,
y1: line.y,
x2: line.x2,
y2: line.y2,
};
}
// NOTE: i graduated highschool and i had to google how to y = mx + b ...
const slope = (line.y - line.y2) / (line.x - line.x2);
const intercept = line.y - slope * line.x;
let x1 = chartArea.left;
if (slope * chartArea.left + intercept < chartArea.top) {
x1 = (chartArea.top - intercept) / slope;
} else if (slope * chartArea.left + intercept > chartArea.bottom) {
x1 = (chartArea.bottom - intercept) / slope;
}
let x2 = chartArea.right;
if (slope * chartArea.right + intercept < chartArea.top) {
x2 = (chartArea.top - intercept) / slope;
} else if (slope * chartArea.right + intercept > chartArea.bottom) {
x2 = (chartArea.bottom - intercept) / slope;
}
return {
x1: x1,
y1: Math.min(Math.max(slope * x1 + intercept, chartArea.top), chartArea.bottom),
x2: x2,
y2: Math.min(Math.max(slope * x2 + intercept, chartArea.top), chartArea.bottom),
};
}

const isKeyDown = (() => {
// https://stackoverflow.com/a/48750898
const state = {};

// biome-ignore lint: let it mod
window.addEventListener("keyup", (e) => (state[e.key] = false));
// biome-ignore lint: let it mod
window.addEventListener("keydown", (e) => (state[e.key] = true));

return (key) => (Object.hasOwn(state, key) && state[key]) || false;
})();
7 changes: 5 additions & 2 deletions app/templates/analytics.html
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ <h1 class="title">
hx-swap="beforeend"
hx-target="body"
id="lineChartId"></canvas>
<span>https://data.bts.gov/Research-and-Statistics/Auto-Sales/7n6a-n5tz</span>
<sup>source: https://data.bts.gov/Research-and-Statistics/Auto-Sales/7n6a-n5tz</sup>
<progress class="progress is-small htmx-indicator" max="100"></progress>
</div>
</section>
Expand All @@ -52,7 +52,7 @@ <h1 class="title">
<button
class="button"
hx-get="/api/v1/data/random"
hx-trigger="click, revealed"
hx-trigger="click, load"
hx-swap="beforeend"
hx-target="body">populate</button>
</div>
Expand All @@ -66,6 +66,7 @@ <h1 class="title">
<section class="section">
<div class="container">
<div class="is-striped" id="death-table" hx-get="/api/v1/data/deaths" hx-trigger="revealed"></div>
<sup>source: https://www150.statcan.gc.ca/n1/daily-quotidien/231127/t001b-eng.htm</sup>
</div>
</section>

Expand Down Expand Up @@ -104,7 +105,9 @@ <h1 class="title">
document.getElementById("lineChartId"),
{
type: "line",
plugins: [arbLines],
options: {
events: ['mousedown', 'mouseup', 'mousemove'],
responsive: true,
plugins: {
legend: {
Expand Down