Skip to content

Commit

Permalink
📐 formatting rules (#153)
Browse files Browse the repository at this point in the history
* :rule: formatting rules

* ⛏️ infix ops

* lockfiles are dumb >_<

---------

Co-authored-by: Alex Ruddick <alex@ruddick.tech>
juli4nb4dillo and alexrudd2 authored Jan 20, 2025
1 parent 4f9b6c4 commit 5bbd0e9
Showing 13 changed files with 353 additions and 126 deletions.
7 changes: 6 additions & 1 deletion .eslintrc.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
module.exports = {
parser: '@typescript-eslint/parser',
plugins: ['@typescript-eslint'],
plugins: ['@typescript-eslint', '@stylistic/eslint-plugin'],
extends: [
'eslint:recommended',
'plugin:react/recommended',
@@ -22,6 +22,11 @@ module.exports = {
argsIgnorePattern: "^_",
varsIgnorePattern: "^_",
}],
'@stylistic/indent': ['error', 2],
"@stylistic/space-infix-ops": 1,
'@stylistic/object-curly-spacing': ['error', 'always'],
// "semi": [1, "always"],
// "consistent-return": 2,
},
settings: {
react: {
223 changes: 222 additions & 1 deletion package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -20,7 +20,7 @@
},
"scripts": {
"prebuild": "npm run lint",
"lint": "eslint --cache --ext .ts,.tsx src",
"lint": "eslint --cache --ext .ts,.tsx src && eslint --format stylish --fix src",
"build": "npm run build:server && npm run build:ui",
"build:server": "tsc",
"build:ui": "node --experimental-modules build.mjs",
@@ -36,6 +36,7 @@
"@craftamap/esbuild-plugin-html": "^0.7.0 || ^0.8.0",
"@rehooks/component-size": "^1.0.2",
"@serialport/bindings-cpp": "^12.0.0 || ^13.0.0",
"@stylistic/eslint-plugin": "^2.10.1",
"@types/cors": "^2.8.4",
"@types/express": "^4.17.9",
"@types/jest": "^29.0.0",
2 changes: 1 addition & 1 deletion src/background-planner.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { replan } from './massager';

self.addEventListener("message", (m) => {
const {paths, planOptions} = m.data;
const { paths, planOptions } = m.data;
const plan = replan(paths, planOptions);
console.time("serializing");
const serialized = plan.serialize();
14 changes: 7 additions & 7 deletions src/cli.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import yargs from "yargs";
import {connectEBB, startServer} from "./server";
import {replan} from "./massager";
import {Window} from "svgdom";
import { connectEBB, startServer } from "./server";
import { replan } from "./massager";
import { Window } from "svgdom";
import * as fs from "node:fs";
import {flattenSVG} from "flatten-svg";
import { flattenSVG } from "flatten-svg";
import type { Vec2 } from "./vec";
import { formatDuration } from "./util";
import { Device, type PlanOptions, defaultPlanOptions } from "./planning";
@@ -45,7 +45,7 @@ export function cli(argv: string[]): void {
} else {
const m = /^([0-9]*(?:\.[0-9]+)?)\s*x\s*([0-9]*(?:\.[0-9]+)?)\s*(cm|mm|in)$/i.exec(String(value).trim())
if (m) {
return new PaperSize({x: Number(m[1]), y: Number(m[2])})
return new PaperSize({ x: Number(m[1]), y: Number(m[2]) })
}
}
throw new Error(`Paper size should be a standard size (${Object.keys(PaperSize.standard).join(", ")}) or a custom size such as "100x100mm" or "16x10in"`)
@@ -219,7 +219,7 @@ export function cli(argv: string[]): void {
}
)
.command('pen [percent]', 'put the pen to [percent]', yargs => yargs
.positional('percent', { type: 'number', description: 'percent height between 0 and 100', required: true})
.positional('percent', { type: 'number', description: 'percent height between 0 and 100', required: true })
.check(args => args.percent >= 0 && args.percent <= 100),
async args => {
console.log('connecting to plotter...')
@@ -260,7 +260,7 @@ export function cli(argv: string[]): void {

function linesToVecs(lines: any[]): Vec2[][] {
return lines.map((line) => {
const a = line.points.map(([x, y]: [number, number]) => ({x, y}));
const a = line.points.map(([x, y]: [number, number]) => ({ x, y }));
(a as any).stroke = line.stroke;
(a as any).groupId = line.groupId;
return a;
6 changes: 3 additions & 3 deletions src/ebb.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import {type Block, type Motion, PenMotion, type Plan, XYMotion} from "./planning";
import { type Block, type Motion, PenMotion, type Plan, XYMotion } from "./planning";
import { RegexParser } from "./regex-transform-stream";
import {type Vec2, vsub} from "./vec";
import { type Vec2, vsub } from "./vec";

/** Split d into its fractional and integral parts */
function modf(d: number): [number, number] {
@@ -21,7 +21,7 @@ export class EBB {
private microsteppingMode = 0;

/** Accumulated XY error, used to correct for movements with sub-step resolution */
private error: Vec2 = {x: 0, y: 0};
private error: Vec2 = { x: 0, y: 0 };

private cachedFirmwareVersion: [number, number, number] | undefined = undefined;

8 changes: 4 additions & 4 deletions src/massager.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import * as Optimization from "optimize-paths";
import {Device, type Plan, type PlanOptions, plan} from "./planning";
import {dedupPoints, scaleToPaper, cropToMargins} from "./util";
import {type Vec2, vmul, vrot} from "./vec";
import { Device, type Plan, type PlanOptions, plan } from "./planning";
import { dedupPoints, scaleToPaper, cropToMargins } from "./util";
import { type Vec2, vmul, vrot } from "./vec";

// CSS, and thus SVG, defines 1px = 1/96th of 1in
// https://www.w3.org/TR/css-values-4/#absolute-lengths
@@ -19,7 +19,7 @@ export function replan(inPaths: Vec2[][], planOptions: PlanOptions): Plan {
if (planOptions.rotateDrawing !== 0) {
console.time("rotating paths");
paths = paths.map((pl) => pl.map((p) => vrot(p,
vmul({x:planOptions.paperSize.size.x/2, y: planOptions.paperSize.size.y/2}, 1/mmPerSvgUnit),
vmul({ x:planOptions.paperSize.size.x / 2, y: planOptions.paperSize.size.y / 2 }, 1 / mmPerSvgUnit),
planOptions.rotateDrawing)
));
console.timeEnd("rotating paths");
24 changes: 12 additions & 12 deletions src/paper-size.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import {type Vec2, vmul} from "./vec";
import { type Vec2, vmul } from "./vec";

function vround(v: Vec2, digits = 2): Vec2 {
return { x: Number(v.x.toFixed(digits)), y: Number(v.y.toFixed(digits)) };
@@ -24,17 +24,17 @@ export class PaperSize {
return this.size.x === Math.max(this.size.x, this.size.y);
}

public static standard: {[name: string]: PaperSize} = {
"USLetter": new PaperSize(vround(vmul({x: 8.5, y: 11}, 25.4))),
"USLegal": new PaperSize(vround(vmul({x: 8.5, y: 14}, 25.4))),
"ArchA": new PaperSize(vround(vmul({x: 9, y: 12}, 25.4))),
"A3": new PaperSize({x: 297, y: 420}),
"A4": new PaperSize({x: 210, y: 297}),
"A5": new PaperSize({x: 148, y: 210}),
"A6": new PaperSize({x: 105, y: 148}),
"6x8": new PaperSize(vround(vmul({x: 6, y: 8}, 25.4))),
"5x7": new PaperSize(vround(vmul({x: 5, y: 7}, 25.4))),
"11x14": new PaperSize(vround(vmul({x: 11, y: 14}, 25.4))),
public static standard: { [name: string]: PaperSize } = {
"USLetter": new PaperSize(vround(vmul({ x: 8.5, y: 11 }, 25.4))),
"USLegal": new PaperSize(vround(vmul({ x: 8.5, y: 14 }, 25.4))),
"ArchA": new PaperSize(vround(vmul({ x: 9, y: 12 }, 25.4))),
"A3": new PaperSize({ x: 297, y: 420 }),
"A4": new PaperSize({ x: 210, y: 297 }),
"A5": new PaperSize({ x: 148, y: 210 }),
"A6": new PaperSize({ x: 105, y: 148 }),
"6x8": new PaperSize(vround(vmul({ x: 6, y: 8 }, 25.4))),
"5x7": new PaperSize(vround(vmul({ x: 5, y: 7 }, 25.4))),
"11x14": new PaperSize(vround(vmul({ x: 11, y: 14 }, 25.4))),
};
public size: Vec2;
public constructor(size: Vec2) {
8 changes: 4 additions & 4 deletions src/planning.ts
Original file line number Diff line number Diff line change
@@ -193,13 +193,13 @@ export class Block {

public get vFinal(): number { return Math.max(0, this.vInitial + this.accel * this.duration); }

public instant(tU: number, dt= 0, ds= 0): Instant {
public instant(tU: number, dt = 0, ds = 0): Instant {
const t = Math.max(0, Math.min(this.duration, tU));
const a = this.accel;
const v = this.vInitial + this.accel * t;
const s = Math.max(0, Math.min(this.distance, this.vInitial * t + a * t * t / 2));
const p = vadd(this.p1, vmul(vnorm(vsub(this.p2, this.p1)), s));
return {t: t + dt, p, s: s + ds, v, a};
return { t: t + dt, p, s: s + ds, v, a };
}

public serialize(): any {
@@ -439,7 +439,7 @@ function computeTriangle(
const t1 = (vMax - initialVel) / accel;
const t2 = (finalVel - vMax) / -accel;
const p2 = vadd(p1, vmul(vnorm(vsub(p3, p1)), acceleratingDistance));
return {s1: acceleratingDistance, s2: deceleratingDistance, t1, t2, vMax, p1, p2, p3};
return { s1: acceleratingDistance, s2: deceleratingDistance, t1, t2, vMax, p1, p2, p3 };
}

/** Represents a trapezoidal velocity profile for moving in a straight line.
@@ -492,7 +492,7 @@ function computeTrapezoid(
const dir = vnorm(vsub(p4, p1));
const p2 = vadd(p1, vmul(dir, s1));
const p3 = vadd(p1, vmul(dir, (distance - s3)));
return {s1, s2, s3, t1, t2, t3, p1, p2, p3, p4};
return { s1, s2, s3, t1, t2, t3, p1, p2, p3, p4 };
}

function dedupPoints(points: Vec2[], epsilon: number): Vec2[] {
22 changes: 11 additions & 11 deletions src/server.ts
Original file line number Diff line number Diff line change
@@ -46,7 +46,7 @@ export async function startServer (port: number, hardware: Hardware = 'v3', com:
const msg = JSON.parse(message.toString());
switch (msg.c) {
case "ping":
ws.send(JSON.stringify({c: "pong"}));
ws.send(JSON.stringify({ c: "pong" }));
break;
case "limp":
if (ebb) { ebb.disableMotors(); }
@@ -64,14 +64,14 @@ export async function startServer (port: number, hardware: Hardware = 'v3', com:
}
});

ws.send(JSON.stringify({c: 'dev', p: getDeviceInfo(ebb, com)}))
ws.send(JSON.stringify({ c: 'dev', p: getDeviceInfo(ebb, com) }))

ws.send(JSON.stringify({c: "pause", p: {paused: !!unpaused}}));
ws.send(JSON.stringify({ c: "pause", p: { paused: !!unpaused } }));
if (motionIdx != null) {
ws.send(JSON.stringify({c: "progress", p: {motionIdx}}));
ws.send(JSON.stringify({ c: "progress", p: { motionIdx } }));
}
if (currentPlan != null) {
ws.send(JSON.stringify({c: "plan", p: {plan: currentPlan}}));
ws.send(JSON.stringify({ c: "plan", p: { plan: currentPlan } }));
}

ws.on("close", () => {
@@ -131,7 +131,7 @@ export async function startServer (port: number, hardware: Hardware = 'v3', com:
unpaused = new Promise(resolve => {
signalUnpause = resolve;
});
broadcast({c: "pause", p: {paused: true}});
broadcast({ c: "pause", p: { paused: true } });
}
res.status(200).end();
});
@@ -208,14 +208,14 @@ export async function startServer (port: number, hardware: Hardware = 'v3', com:
let penIsUp = true;

for (const motion of plan.motions) {
broadcast({c: "progress", p: {motionIdx}});
broadcast({ c: "progress", p: { motionIdx } });
await plotter.executeMotion(motion, [motionIdx, plan.motions.length]);
if (motion instanceof PenMotion) {
penIsUp = motion.initialPos < motion.finalPos;
}
if (unpaused && penIsUp) {
await unpaused;
broadcast({c: "pause", p: {paused: false}});
broadcast({ c: "pause", p: { paused: false } });
}
if (cancelRequested) { break; }
motionIdx += 1;
@@ -224,10 +224,10 @@ export async function startServer (port: number, hardware: Hardware = 'v3', com:
currentPlan = null;
if (cancelRequested) {
await plotter.postCancel();
broadcast({c: "cancelled"});
broadcast({ c: "cancelled" });
cancelRequested = false;
} else {
broadcast({c: "finished"});
broadcast({ c: "finished" });
}
await plotter.postPlot();
}
@@ -242,7 +242,7 @@ export async function startServer (port: number, hardware: Hardware = 'v3', com:
}
}
connect();
const {family, address, port} = server.address() as any;
const { family, address, port } = server.address() as any;
const addr = `${family === "IPv6" ? `[${address}]` : address}:${port}`;
console.log(`Server listening on http://${addr}`);
resolve(server);
138 changes: 69 additions & 69 deletions src/ui.tsx

Large diffs are not rendered by default.

16 changes: 8 additions & 8 deletions src/util.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import type {PaperSize} from "./paper-size";
import {vadd, type Vec2, vlen2, vmul, vsub} from "./vec";
import type { PaperSize } from "./paper-size";
import { vadd, type Vec2, vlen2, vmul, vsub } from "./vec";

/** Format a smallish duration in 2h30m15s form */
export function formatDuration(seconds: number): string {
@@ -28,7 +28,7 @@ function extent(pointLists: Vec2[][]): [Vec2, Vec2] {
if (p.y < minY) { minY = p.y; }
}
}
return [{x: minX, y: minY}, {x: maxX, y: maxY}];
return [{ x: minX, y: minY }, { x: maxX, y: maxY }];
}

/**
@@ -54,8 +54,8 @@ function scaleToFit(pointLists: Vec2[][], targetMin: Vec2, targetMax: Vec2): Vec
export function scaleToPaper(pointLists: Vec2[][], paperSize: PaperSize, marginMm: number): Vec2[][] {
return scaleToFit(
pointLists,
{x: marginMm, y: marginMm},
vsub(paperSize.size, {x: marginMm, y: marginMm})
{ x: marginMm, y: marginMm },
vsub(paperSize.size, { x: marginMm, y: marginMm })
);
}

@@ -123,7 +123,7 @@ function cropLineToAabb(pointList: Vec2[], aabb: [Vec2, Vec2]): Vec2[][] {
const truncatedPointLists: Vec2[][] = []
let currentPointList: Vec2[] | null = null
for (let i = 1; i < pointList.length; i++) {
const [a, b] = [pointList[i-1], pointList[i]]
const [a, b] = [pointList[i - 1], pointList[i]]
const truncated = truncate(aabb, [a, b])
if (truncated) {
if (!currentPointList) {
@@ -147,8 +147,8 @@ function cropLineToAabb(pointList: Vec2[], aabb: [Vec2, Vec2]): Vec2[][] {
* Crops a drawing so it is kept entirely within the given margin.
*/
export function cropToMargins(pointLists: Vec2[][], paperSize: PaperSize, marginMm: number): Vec2[][] {
const pageAabb: [Vec2, Vec2] = [{x: 0, y: 0}, paperSize.size]
const margin = {x: marginMm, y: marginMm}
const pageAabb: [Vec2, Vec2] = [{ x: 0, y: 0 }, paperSize.size]
const margin = { x: marginMm, y: marginMm }
const insetAabb: [Vec2, Vec2] = [vadd(pageAabb[0], margin), vsub(pageAabb[1], margin)]
const truncatedPointLists: Vec2[][] = []
for (const pointList of pointLists) {
8 changes: 4 additions & 4 deletions src/vec.ts
Original file line number Diff line number Diff line change
@@ -10,16 +10,16 @@ export function vlen(a: Vec2): number {
return Math.sqrt(vlen2(a));
}
export function vsub(a: Vec2, b: Vec2): Vec2 {
return {x: a.x - b.x, y: a.y - b.y};
return { x: a.x - b.x, y: a.y - b.y };
}
export function vmul(a: Vec2, s: number): Vec2 {
return {x: a.x * s, y: a.y * s};
return { x: a.x * s, y: a.y * s };
}
export function vnorm(a: Vec2): Vec2 {
return vmul(a, 1 / vlen(a));
}
export function vadd(a: Vec2, b: Vec2): Vec2 {
return {x: a.x + b.x, y: a.y + b.y};
return { x: a.x + b.x, y: a.y + b.y };
}
export function vdot(a: Vec2, b: Vec2): number {
return a.x * b.x + a.y * b.y;
@@ -34,5 +34,5 @@ export function vrot(v: Vec2, c: Vec2, a: number): Vec2 {
nx = cos * (v.x - c.x) - sin * (v.y - c.y) + c.x,
ny = cos * (v.y - c.y) + sin * (v.x - c.x) + c.y;

return {x:nx, y:ny};
return { x:nx, y:ny };
}

0 comments on commit 5bbd0e9

Please sign in to comment.