From ffd43eef894ca30a87b38442aa4d60de42b431fc Mon Sep 17 00:00:00 2001 From: martin veillette Date: Mon, 23 Nov 2026 23:55:54 -0500 Subject: [PATCH 1/4] Standardize homepage, AGENTS sections, and template pins. Set package homepage from the catalog, fill missing AGENTS headings, clear memory-leak inventory noise, and align knip/vitest with SceneryStackTemplate where drifted. --- AGENTS.md | 4 ++++ package.json | 3 ++- 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/AGENTS.md b/AGENTS.md index be0b5d6..1c608db 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -95,3 +95,7 @@ npm test npm run build npm run test:fuzz:quick ``` + +## Compliance carve-outs + +None. diff --git a/package.json b/package.json index f47a23a..bc82354 100644 --- a/package.json +++ b/package.json @@ -81,5 +81,6 @@ }, "allowScripts": { "@swc/core@1.16.22": true - } + }, + "homepage": "https://openlyceum.github.io/CapacitorLab" } From 287d0944cf389b44969ccc552e3647e13ecc3e4f Mon Sep 17 00:00:00 2001 From: martin veillette Date: Tue, 24 Nov 2026 10:05:59 -0500 Subject: [PATCH 2/4] chore(biome): enforce no enum/namespace and as-const; sort package.json on fix Mirror erasableSyntaxOnly in the linter and enable useSortedPackageJson assist. --- biome.json | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/biome.json b/biome.json index 60bb205..f093ad4 100644 --- a/biome.json +++ b/biome.json @@ -3,7 +3,8 @@ "assist": { "actions": { "source": { - "organizeImports": "on" + "organizeImports": "on", + "useSortedPackageJson": "on" } } }, @@ -82,7 +83,9 @@ "style": { "noCommonJs": "error", "noDefaultExport": "off", + "noEnum": "error", "noExportedImports": "warn", + "noNamespace": "error", "noParameterAssign": "error", "preset": "recommended", "useBlockStatements": "error", @@ -98,6 +101,7 @@ "strictCase": false } }, + "useAsConstAssertion": "warn", "useForOf": "warn", "useImportType": "error", "useNamingConvention": { From 555f267d3564b2c3e0236dded650a3d7f29e7ae2 Mon Sep 17 00:00:00 2001 From: martin veillette Date: Tue, 24 Nov 2026 12:18:20 -0500 Subject: [PATCH 3/4] Require initialized circuit electrical state --- src/common/model/circuit/AbstractCircuit.ts | 55 +++++++++++-------- .../model/circuit/CombinationCircuits.ts | 10 +++- src/common/model/circuit/ParallelCircuit.ts | 27 +++++---- src/common/model/circuit/SeriesCircuit.ts | 6 +- src/common/model/circuit/SingleCircuit.ts | 11 ++-- tests/common/model/circuit/circuits.test.ts | 23 ++++++++ 6 files changed, 90 insertions(+), 42 deletions(-) diff --git a/src/common/model/circuit/AbstractCircuit.ts b/src/common/model/circuit/AbstractCircuit.ts index 27f3de8..8511a96 100644 --- a/src/common/model/circuit/AbstractCircuit.ts +++ b/src/common/model/circuit/AbstractCircuit.ts @@ -5,13 +5,7 @@ * the wires from a {@link CircuitConfig}, keeps the capacitors' plate voltages in * step with whatever the user changes, and tracks current as dQ/dt. * - * ── Two-phase construction ─────────────────────────────────────────────────── - * Plate voltages depend on subclass state (which capacitors are in series, whether - * the battery is connected), so the base class cannot link them until the subclass - * constructor has finished. Every concrete circuit therefore ends its constructor - * with `this.finishConstruction()`. The Java version had the same requirement and - * met it with null checks inside `updatePlateVoltages`; making it an explicit call - * is the same order with the reason written down. + * Each topology creates its electrical state once its own inputs are ready. * * Ported from `model/circuit/AbstractCircuit.java`. */ @@ -29,6 +23,13 @@ import type { Circuit } from "./Circuit.js"; export type CreateCapacitors = (config: CircuitConfig, numberOfCapacitors: number) => Capacitor[]; export type CreateWires = (config: CircuitConfig, battery: Battery, capacitors: readonly Capacitor[]) => Wire[]; +export type ElectricalState = { + readonly totalCapacitanceProperty: TReadOnlyProperty; + readonly totalVoltageProperty: TReadOnlyProperty; + readonly totalChargeProperty: TReadOnlyProperty; + readonly storedEnergyProperty: TReadOnlyProperty; +}; + export abstract class AbstractCircuit implements Circuit { public readonly displayNameProperty: TReadOnlyProperty; public readonly battery: Battery; @@ -43,16 +44,28 @@ export abstract class AbstractCircuit implements Circuit { public readonly currentAmplitudeProperty: NumberProperty = new NumberProperty(0); - // Assigned by finishConstruction(), which every concrete constructor must call. - public totalCapacitanceProperty!: TReadOnlyProperty; - public totalVoltageProperty!: TReadOnlyProperty; - public totalChargeProperty!: TReadOnlyProperty; - public storedEnergyProperty!: TReadOnlyProperty; + protected abstract readonly electricalState: ElectricalState; + + public get totalCapacitanceProperty(): TReadOnlyProperty { + return this.electricalState.totalCapacitanceProperty; + } + + public get totalVoltageProperty(): TReadOnlyProperty { + return this.electricalState.totalVoltageProperty; + } + + public get totalChargeProperty(): TReadOnlyProperty { + return this.electricalState.totalChargeProperty; + } + + public get storedEnergyProperty(): TReadOnlyProperty { + return this.electricalState.storedEnergyProperty; + } /** * Everything that changes the circuit's electrical state *except* plate voltage * — which is an output, and would make the update cycle back on itself. - * Subclasses append their own state here before calling finishConstruction. + * Subclasses append their own state here before creating electrical state. */ protected readonly changeInputs: TReadOnlyProperty[]; @@ -83,15 +96,12 @@ export abstract class AbstractCircuit implements Circuit { ]; } - /** - * Links the derived electrical state. Call at the very end of every concrete - * constructor — see the note in the class doc. - */ - protected finishConstruction(): void { - this.totalCapacitanceProperty = DerivedProperty.deriveAny(this.changeInputs, () => this.computeTotalCapacitance()); - this.totalVoltageProperty = DerivedProperty.deriveAny(this.changeInputs, () => this.computeTotalVoltage()); - this.totalChargeProperty = DerivedProperty.deriveAny(this.changeInputs, () => this.computeTotalCharge()); - this.storedEnergyProperty = DerivedProperty.deriveAny(this.changeInputs, () => { + /** Creates electrical outputs and links plate voltages after topology inputs are initialized. */ + protected createElectricalState(): ElectricalState { + const totalCapacitanceProperty = DerivedProperty.deriveAny(this.changeInputs, () => this.computeTotalCapacitance()); + const totalVoltageProperty = DerivedProperty.deriveAny(this.changeInputs, () => this.computeTotalVoltage()); + const totalChargeProperty = DerivedProperty.deriveAny(this.changeInputs, () => this.computeTotalCharge()); + const storedEnergyProperty = DerivedProperty.deriveAny(this.changeInputs, () => { const capacitance = this.computeTotalCapacitance(); const voltage = this.computeTotalVoltage(); return 0.5 * capacitance * voltage * voltage; @@ -99,6 +109,7 @@ export abstract class AbstractCircuit implements Circuit { Multilink.multilinkAny(this.changeInputs, () => this.updatePlateVoltages()); this.updatePlateVoltages(); + return { totalCapacitanceProperty, totalVoltageProperty, totalChargeProperty, storedEnergyProperty }; } /** Distributes the circuit's voltage across its capacitors. */ diff --git a/src/common/model/circuit/CombinationCircuits.ts b/src/common/model/circuit/CombinationCircuits.ts index b601491..20097bc 100644 --- a/src/common/model/circuit/CombinationCircuits.ts +++ b/src/common/model/circuit/CombinationCircuits.ts @@ -24,7 +24,7 @@ import { createWireBatteryToCapacitorsTop, } from "../wire/WireBatteryToCapacitors.ts"; import { createWireCapacitorToCapacitors } from "../wire/WireCapacitorToCapacitors.ts"; -import { AbstractCircuit } from "./AbstractCircuit.ts"; +import { AbstractCircuit, type ElectricalState } from "./AbstractCircuit.ts"; /** * Both combinations place C1 above C2 in the left column and C3 alone in the @@ -75,6 +75,8 @@ function asThree(capacitors: readonly Capacitor[]): [Capacitor, Capacitor, Capac * |-----|------| */ export class Combination1Circuit extends AbstractCircuit { + protected readonly electricalState: ElectricalState; + private readonly c1: Capacitor; private readonly c2: Capacitor; private readonly c3: Capacitor; @@ -93,7 +95,7 @@ export class Combination1Circuit extends AbstractCircuit { ]; }); [this.c1, this.c2, this.c3] = asThree(this.capacitors); - this.finishConstruction(); + this.electricalState = this.createElectricalState(); } protected override updatePlateVoltages(): void { @@ -154,6 +156,8 @@ export class Combination1Circuit extends AbstractCircuit { * |-----|------| */ export class Combination2Circuit extends AbstractCircuit { + protected readonly electricalState: ElectricalState; + private readonly c1: Capacitor; private readonly c2: Capacitor; private readonly c3: Capacitor; @@ -172,7 +176,7 @@ export class Combination2Circuit extends AbstractCircuit { ]; }); [this.c1, this.c2, this.c3] = asThree(this.capacitors); - this.finishConstruction(); + this.electricalState = this.createElectricalState(); } protected override updatePlateVoltages(): void { diff --git a/src/common/model/circuit/ParallelCircuit.ts b/src/common/model/circuit/ParallelCircuit.ts index 98dd3c1..d230996 100644 --- a/src/common/model/circuit/ParallelCircuit.ts +++ b/src/common/model/circuit/ParallelCircuit.ts @@ -22,7 +22,7 @@ import { createWireBatteryToCapacitorsBottom, createWireBatteryToCapacitorsTop, } from "../wire/WireBatteryToCapacitors.ts"; -import { AbstractCircuit } from "./AbstractCircuit.ts"; +import { AbstractCircuit, type ElectricalState } from "./AbstractCircuit.ts"; /** A row of capacitors to the right of the battery, evenly spaced. */ function createCapacitorsInRow(config: CircuitConfig, numberOfCapacitors: number): Capacitor[] { @@ -44,16 +44,11 @@ function createCapacitorsInRow(config: CircuitConfig, numberOfCapacitors: number return capacitors; } -export class ParallelCircuit extends AbstractCircuit { - /** - * @param deferFinish - true when a subclass still has state to register in - * `changeInputs`; that subclass then calls `finishConstruction()` itself. - */ - public constructor( +export abstract class AbstractParallelCircuit extends AbstractCircuit { + protected constructor( config: CircuitConfig, displayNameProperty: TReadOnlyProperty, numberOfCapacitors: number, - deferFinish = false, ) { super(config, displayNameProperty, numberOfCapacitors, createCapacitorsInRow, (cfg, battery, capacitors) => [ createWireBatteryToCapacitorsTop(cfg.modelViewTransform, cfg.wireThickness, cfg.wireExtent, battery, capacitors), @@ -65,9 +60,6 @@ export class ParallelCircuit extends AbstractCircuit { capacitors, ), ]); - if (!deferFinish) { - this.finishConstruction(); - } } /** Every capacitor sees the same voltage. */ @@ -117,3 +109,16 @@ export class ParallelCircuit extends AbstractCircuit { return this.capacitors.some((capacitor) => capacitor.intersectsBottomPlate(shape)); } } + +export class ParallelCircuit extends AbstractParallelCircuit { + protected readonly electricalState: ElectricalState; + + public constructor( + config: CircuitConfig, + displayNameProperty: TReadOnlyProperty, + numberOfCapacitors: number, + ) { + super(config, displayNameProperty, numberOfCapacitors); + this.electricalState = this.createElectricalState(); + } +} diff --git a/src/common/model/circuit/SeriesCircuit.ts b/src/common/model/circuit/SeriesCircuit.ts index 96c3e2a..dabec8b 100644 --- a/src/common/model/circuit/SeriesCircuit.ts +++ b/src/common/model/circuit/SeriesCircuit.ts @@ -27,7 +27,7 @@ import { createWireBatteryToCapacitorsTop, } from "../wire/WireBatteryToCapacitors.ts"; import { createWireCapacitorToCapacitors } from "../wire/WireCapacitorToCapacitors.ts"; -import { AbstractCircuit } from "./AbstractCircuit.ts"; +import { AbstractCircuit, type ElectricalState } from "./AbstractCircuit.ts"; /** A column of capacitors to the right of the battery, centred on the battery's y. */ function createCapacitorsInColumn(config: CircuitConfig, numberOfCapacitors: number): Capacitor[] { @@ -57,6 +57,8 @@ function createCapacitorsInColumn(config: CircuitConfig, numberOfCapacitors: num } export class SeriesCircuit extends AbstractCircuit { + protected readonly electricalState: ElectricalState; + public constructor( config: CircuitConfig, displayNameProperty: TReadOnlyProperty, @@ -87,7 +89,7 @@ export class SeriesCircuit extends AbstractCircuit { ); return wires; }); - this.finishConstruction(); + this.electricalState = this.createElectricalState(); } /** Same charge through every capacitor, so Vi = Q_total / Ci. */ diff --git a/src/common/model/circuit/SingleCircuit.ts b/src/common/model/circuit/SingleCircuit.ts index 91fad93..6d89d93 100644 --- a/src/common/model/circuit/SingleCircuit.ts +++ b/src/common/model/circuit/SingleCircuit.ts @@ -23,9 +23,12 @@ import { NumberProperty, type TReadOnlyProperty } from "scenerystack/axon"; import type { Shape } from "scenerystack/kite"; import type { Capacitor } from "../Capacitor.js"; import type { CircuitConfig } from "../CircuitConfig.js"; -import { ParallelCircuit } from "./ParallelCircuit.ts"; +import type { ElectricalState } from "./AbstractCircuit.js"; +import { AbstractParallelCircuit } from "./ParallelCircuit.ts"; + +export class SingleCircuit extends AbstractParallelCircuit { + protected readonly electricalState: ElectricalState; -export class SingleCircuit extends ParallelCircuit { /** The one capacitor, for readability at the call sites that assume it. */ public readonly capacitor: Capacitor; @@ -37,7 +40,7 @@ export class SingleCircuit extends ParallelCircuit { public readonly disconnectedPlateChargeProperty: NumberProperty; public constructor(config: CircuitConfig, displayNameProperty: TReadOnlyProperty, batteryConnected = true) { - super(config, displayNameProperty, 1, true /* deferFinish */); + super(config, displayNameProperty, 1); const capacitor = this.capacitors[0]; if (capacitor === undefined) { @@ -59,7 +62,7 @@ export class SingleCircuit extends ParallelCircuit { }); this.changeInputs.push(this.batteryConnectedProperty, this.disconnectedPlateChargeProperty); - this.finishConstruction(); + this.electricalState = this.createElectricalState(); } protected override updatePlateVoltages(): void { diff --git a/tests/common/model/circuit/circuits.test.ts b/tests/common/model/circuit/circuits.test.ts index 1e85d6a..4efb081 100644 --- a/tests/common/model/circuit/circuits.test.ts +++ b/tests/common/model/circuit/circuits.test.ts @@ -183,6 +183,29 @@ describe("circuits", () => { expect(circuit.capacitor.totalPlateChargeProperty.value).toBeCloseTo(chargeBefore, 20); expect(circuit.capacitor.plateVoltageProperty.value).toBeCloseTo(0.75, 9); }); + + it("restores the initial electrical outputs after resetting a disconnected circuit", () => { + const circuit = new SingleCircuit(createConfig(), NAME); + const initial = [ + circuit.totalCapacitanceProperty.value, + circuit.totalVoltageProperty.value, + circuit.totalChargeProperty.value, + circuit.storedEnergyProperty.value, + ]; + circuit.battery.voltageProperty.value = 1.5; + circuit.batteryConnectedProperty.value = false; + circuit.capacitor.plateSeparationProperty.value /= 2; + + circuit.reset(); + + expect(circuit.batteryConnectedProperty.value).toBe(true); + expect([ + circuit.totalCapacitanceProperty.value, + circuit.totalVoltageProperty.value, + circuit.totalChargeProperty.value, + circuit.storedEnergyProperty.value, + ]).toEqual(initial); + }); }); describe("current", () => { From 6e84cd72519aff908fae2a3741a23b0988fbcaf1 Mon Sep 17 00:00:00 2001 From: martin veillette Date: Tue, 24 Nov 2026 15:23:10 -0500 Subject: [PATCH 4/4] chore(biome): adopt bad-sim-text plugins and fix violations Add no-math-round, no-native-timer, no-window-inner-size, and require-property-suffix; replace Math.round with roundSymmetric and align Property names. --- biome-plugins/no-math-round.grit | 12 ++++ biome-plugins/no-native-timer.grit | 18 ++++++ biome-plugins/no-window-inner-size.grit | 13 ++++ biome-plugins/require-property-suffix.grit | 35 +++++++++++ biome.json | 4 ++ package.json | 62 +++++++++---------- src/common/model/meter/BarMeter.ts | 8 +-- src/common/view/gridSize.ts | 7 ++- src/common/view/meters/EFieldDetectorNode.ts | 10 +-- src/common/view/meters/VoltmeterNode.ts | 12 ++-- .../view/MultipleCapacitorsCircuitNode.ts | 4 +- tests/biome-plugins.node-test.ts | 53 +++++++++++++++- 12 files changed, 186 insertions(+), 52 deletions(-) create mode 100644 biome-plugins/no-math-round.grit create mode 100644 biome-plugins/no-native-timer.grit create mode 100644 biome-plugins/no-window-inner-size.grit create mode 100644 biome-plugins/require-property-suffix.grit diff --git a/biome-plugins/no-math-round.grit b/biome-plugins/no-math-round.grit new file mode 100644 index 0000000..c00d4d3 --- /dev/null +++ b/biome-plugins/no-math-round.grit @@ -0,0 +1,12 @@ +// Flags Math.round(). Prefer roundSymmetric from scenerystack/dot so positive and +// negative values round the same way (see phetsims/dot#35). +// Suppress a deliberate use with: // biome-ignore lint/plugin/no-math-round: +language js + +`Math.round($value)` as $call where { + register_diagnostic( + span = $call, + message = "Use roundSymmetric(value) from scenerystack/dot instead of Math.round(), which rounds positive and negative numbers differently.", + severity = "warn" + ) +} diff --git a/biome-plugins/no-native-timer.grit b/biome-plugins/no-native-timer.grit new file mode 100644 index 0000000..12db2dd --- /dev/null +++ b/biome-plugins/no-native-timer.grit @@ -0,0 +1,18 @@ +// Flags bare setTimeout / setInterval (and window.* forms). Sim code should step +// from the model/view step(dt) chain, or use stepTimer from scenerystack/axon when a +// delayed callback is truly needed. Method calls like stepTimer.setTimeout are allowed. +// Suppress a deliberate use with: // biome-ignore lint/plugin/no-native-timer: +language js + +or { + `setTimeout($...)`, + `setInterval($...)`, + `window.setTimeout($...)`, + `window.setInterval($...)` +} as $call where { + register_diagnostic( + span = $call, + message = "Do not call setTimeout/setInterval in sim code; step from model/view step(dt), or use stepTimer from scenerystack/axon for a delayed callback.", + severity = "warn" + ) +} diff --git a/biome-plugins/no-window-inner-size.grit b/biome-plugins/no-window-inner-size.grit new file mode 100644 index 0000000..a60a72f --- /dev/null +++ b/biome-plugins/no-window-inner-size.grit @@ -0,0 +1,13 @@ +// Flags window.innerWidth / window.innerHeight. Prefer Sim.dimensionProperty (or the +// screen's layoutBounds / visibleBounds) so layout tracks the sim display, not the +// browser chrome. +// Suppress a deliberate use with: // biome-ignore lint/plugin/no-window-inner-size: +language js + +or { `window.innerWidth`, `window.innerHeight` } as $hit where { + register_diagnostic( + span = $hit, + message = "Use Sim.dimensionProperty (or layoutBounds/visibleBounds) instead of window.innerWidth/innerHeight.", + severity = "warn" + ) +} diff --git a/biome-plugins/require-property-suffix.grit b/biome-plugins/require-property-suffix.grit new file mode 100644 index 0000000..6ab614a --- /dev/null +++ b/biome-plugins/require-property-suffix.grit @@ -0,0 +1,35 @@ +// Flags axon Property instances whose binding name does not end in "Property". +// Covers same-line const/let/var and this.field for the common *Property constructors. +// Class fields (`public readonly foo = new NumberProperty(...)`, bare `foo = ...`) are +// not reliably matched by Biome GritQL — rename those in review or with a codemod. +// Type-only annotations are out of scope (PhET's rule is type-checker based). +// Suppress a deliberate use with: // biome-ignore lint/plugin/require-property-suffix: +// GritQL regexes here must use non-capturing groups (?:...); a plain (...) silently never matches. +language js + +or { + `const $name = new $ctor($...)`, + `let $name = new $ctor($...)`, + `var $name = new $ctor($...)`, + `this.$name = new $ctor($...)` +} as $stmt where { + $ctor <: or { + `Property`, + `BooleanProperty`, + `NumberProperty`, + `StringProperty`, + `DerivedProperty`, + `DerivedStringProperty`, + `DynamicProperty`, + `TinyProperty`, + `EnumerationProperty`, + `StringUnionProperty`, + `ProfileColorProperty` + }, + not $name <: r"(?s)(?:.*(?:Property|PROPERTY)|property|_property)$", + register_diagnostic( + span = $name, + message = "Axon Property bindings must end in \"Property\" (e.g. massProperty, not mass).", + severity = "warn" + ) +} diff --git a/biome.json b/biome.json index f093ad4..20c80f1 100644 --- a/biome.json +++ b/biome.json @@ -174,6 +174,10 @@ "plugins": [ "./biome-plugins/no-native-tofixed.grit", "./biome-plugins/no-math-random.grit", + "./biome-plugins/no-math-round.grit", + "./biome-plugins/no-native-timer.grit", + "./biome-plugins/no-window-inner-size.grit", + "./biome-plugins/require-property-suffix.grit", "./biome-plugins/no-hardcoded-text.grit", { "path": "./biome-plugins/no-inline-color.grit", diff --git a/package.json b/package.json index bc82354..366e6a1 100644 --- a/package.json +++ b/package.json @@ -1,14 +1,8 @@ { "name": "capacitor-lab", - "private": true, "version": "0.0.0", - "type": "module", + "private": true, "description": "Explore how a capacitor works: change plate area and separation, insert a dielectric, and build series and parallel combinations while watching charge, voltage, E-field and stored energy.", - "license": "AGPL-3.0-or-later", - "repository": { - "type": "git", - "url": "https://github.com/OpenLyceum/CapacitorLab.git" - }, "keywords": [ "simulation", "SceneryStack", @@ -17,34 +11,46 @@ "education", "pwa" ], + "homepage": "https://openlyceum.github.io/CapacitorLab", + "repository": { + "type": "git", + "url": "https://github.com/OpenLyceum/CapacitorLab.git" + }, + "license": "AGPL-3.0-or-later", + "type": "module", "scripts": { - "start": "vite", - "dev": "vite", "build": "tsc && vite build", "build:single": "tsc && vite build --mode single", - "preview": "vite preview", - "lint": "biome check --error-on-warnings .", - "format": "biome format --write .", - "fix": "biome check --write .", "check": "tsc --noEmit && tsc -p tsconfig.scripts.json --noEmit && tsc -p tsconfig.test.json --noEmit", - "check:unused": "knip", "check:architecture": "depcruise src", + "check:unused": "knip", + "clean": "rm -rf dist", + "dev": "vite", + "fix": "biome check --write .", + "format": "biome format --write .", + "icons": "node scripts/generate-icons.ts", + "knip": "knip", + "lint": "biome check --error-on-warnings .", + "prepare": "test \"$(git rev-parse --show-toplevel 2>/dev/null)\" = \"$PWD\" && git config core.hooksPath .githooks || true", + "preview": "vite preview", "release": "npm run check && npm run lint && npm run check:architecture && npm run build && npm test && npm version patch && git push && git push --tags", - "watch": "tsc --watch", + "start": "vite", "test": "vitest run", - "test:watch": "vitest", + "test:architecture": "node --test tests/*.node-test.ts", "test:fuzz": "node scripts/test-fuzz.ts", - "test:fuzz:quick": "node scripts/test-fuzz.ts 10", "test:fuzz:long": "node scripts/test-fuzz.ts 300", + "test:fuzz:quick": "node scripts/test-fuzz.ts 10", + "test:physics": "node scripts/physics-check.ts", "test:soak": "npm run test:soak:headless && npm run test:soak:browser", - "test:soak:headless": "vitest run --config vitest.soak.config.ts", "test:soak:browser": "npx playwright test tests/soak/browser.spec.ts", - "icons": "node scripts/generate-icons.ts", - "clean": "rm -rf dist", - "prepare": "test \"$(git rev-parse --show-toplevel 2>/dev/null)\" = \"$PWD\" && git config core.hooksPath .githooks || true", - "knip": "knip", - "test:architecture": "node --test tests/*.node-test.ts", - "test:physics": "node scripts/physics-check.ts" + "test:soak:headless": "vitest run --config vitest.soak.config.ts", + "test:watch": "vitest", + "watch": "tsc --watch" + }, + "overrides": { + "brace-expansion": "~5.0.12", + "lodash": "~4.18.1", + "three": "~0.125.2" }, "dependencies": { "scenerystack": "^3.0.0" @@ -67,11 +73,6 @@ "engines": { "node": ">=26" }, - "overrides": { - "lodash": "~4.18.1", - "three": "~0.125.2", - "brace-expansion": "~5.0.12" - }, "devEngines": { "runtime": { "name": "node", @@ -81,6 +82,5 @@ }, "allowScripts": { "@swc/core@1.16.22": true - }, - "homepage": "https://openlyceum.github.io/CapacitorLab" + } } diff --git a/src/common/model/meter/BarMeter.ts b/src/common/model/meter/BarMeter.ts index 3a3524f..ce1acd8 100644 --- a/src/common/model/meter/BarMeter.ts +++ b/src/common/model/meter/BarMeter.ts @@ -30,7 +30,7 @@ export class BarMeter { /** The quantity being read, in its SI unit. */ public readonly valueProperty: TReadOnlyProperty; - private readonly derivedValue: DynamicProperty; + private readonly derivedValueProperty: DynamicProperty; public constructor( circuitProperty: TReadOnlyProperty, @@ -41,12 +41,12 @@ export class BarMeter { ) { this.positionProperty = new WorldPositionProperty(worldBounds, position); this.visibleProperty = new BooleanProperty(visible); - this.derivedValue = new DynamicProperty(circuitProperty, { derive: derivation }); - this.valueProperty = this.derivedValue; + this.derivedValueProperty = new DynamicProperty(circuitProperty, { derive: derivation }); + this.valueProperty = this.derivedValueProperty; } public dispose(): void { - this.derivedValue.dispose(); + this.derivedValueProperty.dispose(); this.visibleProperty.dispose(); this.positionProperty.dispose(); } diff --git a/src/common/view/gridSize.ts b/src/common/view/gridSize.ts index 724e5ca..610b349 100644 --- a/src/common/view/gridSize.ts +++ b/src/common/view/gridSize.ts @@ -1,3 +1,4 @@ +import { roundSymmetric } from "scenerystack/dot"; /** * gridSize.ts * @@ -26,12 +27,12 @@ export function getGridSize(numberOfObjects: number, width: number, height: numb } const alpha = Math.sqrt(numberOfObjects / width / height); - let columns = Math.round(width * alpha); + let columns = roundSymmetric(width * alpha); // Two ways to get the row count, both rounded: straight from the density, or // from the column count we just committed to. Keep whichever fits N better. - const rowsFromDensity = Math.round(height * alpha); - const rowsFromColumns = columns === 0 ? 0 : Math.round(numberOfObjects / columns); + const rowsFromDensity = roundSymmetric(height * alpha); + const rowsFromColumns = columns === 0 ? 0 : roundSymmetric(numberOfObjects / columns); let rows: number; if (rowsFromDensity !== rowsFromColumns) { const errorFromDensity = Math.abs(numberOfObjects - rowsFromDensity * columns); diff --git a/src/common/view/meters/EFieldDetectorNode.ts b/src/common/view/meters/EFieldDetectorNode.ts index 3ecff80..1e3e49e 100644 --- a/src/common/view/meters/EFieldDetectorNode.ts +++ b/src/common/view/meters/EFieldDetectorNode.ts @@ -38,8 +38,8 @@ const PROBE_RADIUS: number = E_FIELD_DETECTOR_NODE_SETTINGS.PROBE_RADIUS; /** View pixels an arrow gets for a field of EFIELD_REFERENCE_MAGNITUDE. */ const REFERENCE_ARROW_LENGTH: number = E_FIELD_DETECTOR_NODE_SETTINGS.REFERENCE_ARROW_LENGTH; -const BODY_WIRE_NORMAL = new Property(new Vector2(0, E_FIELD_DETECTOR_NODE_SETTINGS.BODY_WIRE_NORMAL_Y)); -const PROBE_WIRE_NORMAL = new Property(new Vector2(0, E_FIELD_DETECTOR_NODE_SETTINGS.PROBE_WIRE_NORMAL_Y)); +const BodyWireNormalProperty = new Property(new Vector2(0, E_FIELD_DETECTOR_NODE_SETTINGS.BODY_WIRE_NORMAL_Y)); +const ProbeWireNormalProperty = new Property(new Vector2(0, E_FIELD_DETECTOR_NODE_SETTINGS.PROBE_WIRE_NORMAL_Y)); /** One labelled arrow: its length is the field, its direction the field's sign. */ class VectorDisplay extends Node { @@ -205,15 +205,15 @@ export class EFieldDetectorNode extends Node { }); this.addChild(probe); - const bodyAnchor = new DerivedProperty([detector.bodyPositionProperty], (position: Vector3) => + const bodyAnchorProperty = new DerivedProperty([detector.bodyPositionProperty], (position: Vector3) => modelViewTransform.modelToViewPosition(position).plusXY(BODY_SIZE.x / 2, BODY_SIZE.y), ); - const probeAnchor = new DerivedProperty([detector.probePositionProperty], (position: Vector3) => + const probeAnchorProperty = new DerivedProperty([detector.probePositionProperty], (position: Vector3) => modelViewTransform.modelToViewPosition(position), ); this.insertChild( 0, - new WireNode(bodyAnchor, BODY_WIRE_NORMAL, probeAnchor, PROBE_WIRE_NORMAL, { + new WireNode(bodyAnchorProperty, BodyWireNormalProperty, probeAnchorProperty, ProbeWireNormalProperty, { stroke: CapacitorLabColors.eFieldDetectorWireColorProperty, lineWidth: E_FIELD_DETECTOR_NODE_SETTINGS.CONSTRUCTOR_LINE_WIDTH, }), diff --git a/src/common/view/meters/VoltmeterNode.ts b/src/common/view/meters/VoltmeterNode.ts index 7c33ef7..57207b9 100644 --- a/src/common/view/meters/VoltmeterNode.ts +++ b/src/common/view/meters/VoltmeterNode.ts @@ -33,8 +33,8 @@ const PROBE_RADIUS: number = VOLTMETER_NODE_SETTINGS.PROBE_RADIUS; // Where a lead leaves the body and where it arrives at a probe. These set the // cubic's control points, which is what gives the leads their slack. -const BODY_WIRE_NORMAL = new Property(new Vector2(0, VOLTMETER_NODE_SETTINGS.BODY_WIRE_NORMAL_Y)); -const PROBE_WIRE_NORMAL = new Property(new Vector2(0, VOLTMETER_NODE_SETTINGS.PROBE_WIRE_NORMAL_Y)); +const BodyWireNormalProperty = new Property(new Vector2(0, VOLTMETER_NODE_SETTINGS.BODY_WIRE_NORMAL_Y)); +const ProbeWireNormalProperty = new Property(new Vector2(0, VOLTMETER_NODE_SETTINGS.PROBE_WIRE_NORMAL_Y)); function createProbe(color: TColor): ProbeNode { return new ProbeNode({ @@ -106,9 +106,9 @@ export class VoltmeterNode extends Node { 0, new WireNode( bodyAnchor(BODY_SIZE.x * 0.3), - BODY_WIRE_NORMAL, + BodyWireNormalProperty, viewPositionProperty(voltmeter.positiveProbePositionProperty, modelViewTransform, Vector2.ZERO), - PROBE_WIRE_NORMAL, + ProbeWireNormalProperty, { ...wireOptions, stroke: CapacitorLabColors.voltmeterPositiveWireColorProperty }, ), ); @@ -116,9 +116,9 @@ export class VoltmeterNode extends Node { 0, new WireNode( bodyAnchor(BODY_SIZE.x * 0.7), - BODY_WIRE_NORMAL, + BodyWireNormalProperty, viewPositionProperty(voltmeter.negativeProbePositionProperty, modelViewTransform, Vector2.ZERO), - PROBE_WIRE_NORMAL, + ProbeWireNormalProperty, { ...wireOptions, stroke: CapacitorLabColors.voltmeterNegativeWireColorProperty }, ), ); diff --git a/src/multiple-capacitors/view/MultipleCapacitorsCircuitNode.ts b/src/multiple-capacitors/view/MultipleCapacitorsCircuitNode.ts index 88fbcbb..093d667 100644 --- a/src/multiple-capacitors/view/MultipleCapacitorsCircuitNode.ts +++ b/src/multiple-capacitors/view/MultipleCapacitorsCircuitNode.ts @@ -32,7 +32,7 @@ const LABEL_FONT = new PhetFont(MULTIPLE_CAPACITORS_CIRCUIT_NODE_SETTINGS.LABEL_ const LABEL_SPACING: number = MULTIPLE_CAPACITORS_CIRCUIT_NODE_SETTINGS.LABEL_SPACING; /** This screen never draws dielectric charges, so the view is fixed. */ -const NO_DIELECTRIC_CHARGES = new Property(DielectricChargeView.NONE); +const NoDielectricChargesProperty = new Property(DielectricChargeView.NONE); export class MultipleCapacitorsCircuitNode extends Node { private readonly currentIndicators: readonly CurrentIndicatorNode[]; @@ -62,7 +62,7 @@ export class MultipleCapacitorsCircuitNode extends Node { modelViewTransform, plateChargesVisibleProperty, eFieldVisibleProperty, - NO_DIELECTRIC_CHARGES, + NoDielectricChargesProperty, { dielectricVisible: false }, ); capacitorNode.translation = modelViewTransform.modelToViewPosition(capacitor.position); diff --git a/tests/biome-plugins.node-test.ts b/tests/biome-plugins.node-test.ts index 8238845..137cae6 100644 --- a/tests/biome-plugins.node-test.ts +++ b/tests/biome-plugins.node-test.ts @@ -63,6 +63,54 @@ test("no-math-random flags Math.random() and leaves dotRandom alone", () => { assert.deepEqual(lines(hits, "dotRandom"), [1]); }); +test("no-math-round flags Math.round() and leaves roundSymmetric alone", () => { + const hits = lint({ + "src/a.ts": "export const a = Math.round(1.5);\nexport const b = roundSymmetric(1.5);\n", + }); + assert.deepEqual(lines(hits, "roundSymmetric"), [1]); +}); + +test("no-native-timer flags bare and window timers, allows stepTimer", () => { + const hits = lint({ + "src/a.ts": [ + "setTimeout(() => {}, 0);", + "setInterval(() => {}, 0);", + "window.setTimeout(() => {}, 0);", + "window.setInterval(() => {}, 0);", + "stepTimer.setTimeout(() => {}, 0);", + "stepTimer.setInterval(() => {}, 0);", + "", + ].join("\n"), + }); + assert.deepEqual(lines(hits, "stepTimer"), [1, 2, 3, 4]); +}); + +test("no-window-inner-size flags window.innerWidth/Height", () => { + const hits = lint({ + "src/a.ts": "const w = window.innerWidth;\nconst h = window.innerHeight;\nconst d = dimensionProperty;\n", + }); + assert.deepEqual(lines(hits, "dimensionProperty"), [1, 2]); +}); + +test("require-property-suffix flags Property bindings without Property suffix", () => { + const hits = lint({ + "src/a.ts": [ + "const mass = new NumberProperty(1);", + "const massProperty = new NumberProperty(1);", + "const details = new DerivedProperty([x], (v) => v);", + "const detailsProperty = new DerivedProperty([x], (v) => v);", + "this.visible = new BooleanProperty(true);", + "this.visibleProperty = new BooleanProperty(true);", + // Class fields are not reliably matched by Biome GritQL yet. + "class D {", + " public readonly ignored = new NumberProperty(0);", + "}", + "", + ].join("\n"), + }); + assert.deepEqual(lines(hits, "Property"), [1, 3, 5]); +}); + test("no-hardcoded-text flags literal display words only", () => { const hits = lint({ "src/a.ts": [ @@ -116,6 +164,9 @@ test("no-inline-color flags hardcoded colors outside *Colors.ts", () => { }); test("plugins only run under src/", () => { - const hits = lint({ "scripts/a.ts": 'Math.random(); new Text("Mass"); new Color(1, 2, 3);\n' }); + const hits = lint({ + "scripts/a.ts": + 'Math.random(); Math.round(1); setTimeout(() => {}, 0); window.innerWidth; const mass = new NumberProperty(1); new Text("Mass"); new Color(1, 2, 3);\n', + }); assert.deepEqual(hits, []); });