Skip to content
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
4 changes: 4 additions & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -95,3 +95,7 @@ npm test
npm run build
npm run test:fuzz:quick
```

## Compliance carve-outs

None.
12 changes: 12 additions & 0 deletions biome-plugins/no-math-round.grit
Original file line number Diff line number Diff line change
@@ -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: <reason>
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"
)
}
18 changes: 18 additions & 0 deletions biome-plugins/no-native-timer.grit
Original file line number Diff line number Diff line change
@@ -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: <reason>
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"
)
}
13 changes: 13 additions & 0 deletions biome-plugins/no-window-inner-size.grit
Original file line number Diff line number Diff line change
@@ -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: <reason>
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"
)
}
35 changes: 35 additions & 0 deletions biome-plugins/require-property-suffix.grit
Original file line number Diff line number Diff line change
@@ -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: <reason>
// 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"
)
}
10 changes: 9 additions & 1 deletion biome.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,8 @@
"assist": {
"actions": {
"source": {
"organizeImports": "on"
"organizeImports": "on",
"useSortedPackageJson": "on"
}
}
},
Expand Down Expand Up @@ -82,7 +83,9 @@
"style": {
"noCommonJs": "error",
"noDefaultExport": "off",
"noEnum": "error",
"noExportedImports": "warn",
"noNamespace": "error",
"noParameterAssign": "error",
"preset": "recommended",
"useBlockStatements": "error",
Expand All @@ -98,6 +101,7 @@
"strictCase": false
}
},
"useAsConstAssertion": "warn",
"useForOf": "warn",
"useImportType": "error",
"useNamingConvention": {
Expand Down Expand Up @@ -170,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",
Expand Down
59 changes: 30 additions & 29 deletions package.json
Original file line number Diff line number Diff line change
@@ -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",
Expand All @@ -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"
Expand All @@ -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",
Expand Down
55 changes: 33 additions & 22 deletions src/common/model/circuit/AbstractCircuit.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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`.
*/
Expand All @@ -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<number>;
readonly totalVoltageProperty: TReadOnlyProperty<number>;
readonly totalChargeProperty: TReadOnlyProperty<number>;
readonly storedEnergyProperty: TReadOnlyProperty<number>;
};

export abstract class AbstractCircuit implements Circuit {
public readonly displayNameProperty: TReadOnlyProperty<string>;
public readonly battery: Battery;
Expand All @@ -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<number>;
public totalVoltageProperty!: TReadOnlyProperty<number>;
public totalChargeProperty!: TReadOnlyProperty<number>;
public storedEnergyProperty!: TReadOnlyProperty<number>;
protected abstract readonly electricalState: ElectricalState;

public get totalCapacitanceProperty(): TReadOnlyProperty<number> {
return this.electricalState.totalCapacitanceProperty;
}

public get totalVoltageProperty(): TReadOnlyProperty<number> {
return this.electricalState.totalVoltageProperty;
}

public get totalChargeProperty(): TReadOnlyProperty<number> {
return this.electricalState.totalChargeProperty;
}

public get storedEnergyProperty(): TReadOnlyProperty<number> {
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<unknown>[];

Expand Down Expand Up @@ -83,22 +96,20 @@ 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;
});

Multilink.multilinkAny(this.changeInputs, () => this.updatePlateVoltages());
this.updatePlateVoltages();
return { totalCapacitanceProperty, totalVoltageProperty, totalChargeProperty, storedEnergyProperty };
}

/** Distributes the circuit's voltage across its capacitors. */
Expand Down
10 changes: 7 additions & 3 deletions src/common/model/circuit/CombinationCircuits.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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;
Expand All @@ -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 {
Expand Down Expand Up @@ -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;
Expand All @@ -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 {
Expand Down
Loading
Loading