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 60bb205..20c80f1 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": { @@ -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", diff --git a/package.json b/package.json index 5c99035..805f6d7 100644 --- a/package.json +++ b/package.json @@ -1,14 +1,8 @@ { "name": "equilibrium-lab", - "private": true, "version": "0.0.0", - "type": "module", + "private": true, "description": "Chemical equilibrium for General Chemistry: watch a mixture react until Q reaches K with the forward and reverse rates equal, work ICE tables against a live simulation, apply Le Chatelier stresses and see whether Q or K moved, and find ΔH° and ΔS° from a van 't Hoff plot.", - "license": "AGPL-3.0-or-later", - "repository": { - "type": "git", - "url": "https://github.com/OpenLyceum/EquilibriumLab.git" - }, "keywords": [ "simulation", "SceneryStack", @@ -26,33 +20,45 @@ "education", "pwa" ], + "homepage": "https://openlyceum.github.io/EquilibriumLab", + "repository": { + "type": "git", + "url": "https://github.com/OpenLyceum/EquilibriumLab.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: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: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" @@ -75,11 +81,6 @@ "engines": { "node": ">=26" }, - "overrides": { - "lodash": "~4.18.1", - "three": "~0.125.2", - "brace-expansion": "~5.0.12" - }, "devEngines": { "runtime": { "name": "node", diff --git a/src/common/model/ParticleSystem.ts b/src/common/model/ParticleSystem.ts index aade26d..3ee67ce 100644 --- a/src/common/model/ParticleSystem.ts +++ b/src/common/model/ParticleSystem.ts @@ -17,7 +17,7 @@ import { PARTICLE_SYSTEM_SETTINGS } from "../../EquilibriumLabConstants.js"; * height is proportional to the volume, so compressing the gas squeezes the particles together. */ -import { Random } from "scenerystack/dot"; +import { Random, roundSymmetric } from "scenerystack/dot"; import { BOX_MAX_HEIGHT, BOX_WIDTH, @@ -123,7 +123,7 @@ export class ParticleSystem { const ppm = this.reaction.definition.particlesPerMole; this.reaction.species.forEach((s, i) => { if (!s.bulk) { - const count = Math.round(this.mixture.getAmount(i) * ppm); + const count = roundSymmetric(this.mixture.getAmount(i) * ppm); for (let k = 0; k < count && this.particles.length < MAX_PARTICLES; k++) { this.particles.push( this.createParticle(i, this.random.nextDouble() * BOX_WIDTH, this.random.nextDouble() * this.height, 1), @@ -134,7 +134,7 @@ export class ParticleSystem { const flows = this.mixture.getFlows(); this.forwardDone = Math.floor(flows.forward * ppm); this.reverseDone = Math.floor(flows.reverse * ppm); - this.netDone = Math.round(this.mixture.getTotalExtent() * ppm); + this.netDone = roundSymmetric(this.mixture.getTotalExtent() * ppm); } /** Replays the mixture's reaction since the last step, then moves the particles. */ @@ -195,7 +195,7 @@ export class ParticleSystem { // Keep the composition matched to the net extent (equilibrate() and dropped backlogs move it // without gross flows). - const netTarget = Math.round(this.mixture.getTotalExtent() * ppm); + const netTarget = roundSymmetric(this.mixture.getTotalExtent() * ppm); for (let i = 0; i < MAX_EVENTS_PER_STEP && this.netDone !== netTarget; i++) { const forward = netTarget > this.netDone; if (!this.react(forward)) { @@ -251,7 +251,7 @@ export class ParticleSystem { if (this.reaction.species[index]?.bulk) { return; } - const count = Math.round(Math.abs(moles) * this.reaction.definition.particlesPerMole); + const count = roundSymmetric(Math.abs(moles) * this.reaction.definition.particlesPerMole); if (moles > 0) { for (let k = 0; k < count && this.particles.length < MAX_PARTICLES; k++) { // Added material enters at the top of the box. diff --git a/src/common/model/Reaction.ts b/src/common/model/Reaction.ts index c2290f4..ee594d4 100644 --- a/src/common/model/Reaction.ts +++ b/src/common/model/Reaction.ts @@ -20,6 +20,8 @@ import type { Range } from "scenerystack/dot"; import { GAS_CONSTANT, GAS_CONSTANT_L_BAR, STANDARD_TEMPERATURE } from "../../EquilibriumLabConstants.js"; +import type stringsEn from "../../i18n/strings_en.json"; + export type Phase = "gas" | "aqueous"; /** The family a reaction belongs to, which groups it in the reaction menus. */ @@ -36,9 +38,11 @@ export type ReactionId = | "genericCombination" | "genericDimer"; +export type SpeciesId = keyof (typeof stringsEn)["common"]["speciesNames"]; + export type Species = { /** Identifier used for colours, particle sprites and string lookups (e.g. "NO2"). */ - readonly id: string; + readonly id: SpeciesId; /** Formula as RichText markup, without phase or coefficient (e.g. "NO2"). */ readonly formula: string; /** Signed stoichiometric coefficient: negative for reactants, positive for products. */ diff --git a/src/common/view/ParticleBoxNode.ts b/src/common/view/ParticleBoxNode.ts index 3be962d..75556f3 100644 --- a/src/common/view/ParticleBoxNode.ts +++ b/src/common/view/ParticleBoxNode.ts @@ -11,7 +11,7 @@ import { PARTICLE_BOX_NODE_SETTINGS } from "../../EquilibriumLabConstants.js"; */ import { Multilink, type TReadOnlyProperty } from "scenerystack/axon"; -import { Bounds2, Random } from "scenerystack/dot"; +import { Bounds2, Random, roundSymmetric } from "scenerystack/dot"; import { Shape } from "scenerystack/kite"; import { optionize } from "scenerystack/phet-core"; import { @@ -297,7 +297,10 @@ class ParticleCanvasNode extends CanvasNode { }; reaction.species.forEach((s, i) => { if (s.bulk) { - const count = Math.min(MAX_BULK_DOTS, Math.round((concentrations[i] ?? 0) * 30 * (height / this.boxMaxHeight))); + const count = Math.min( + MAX_BULK_DOTS, + roundSymmetric((concentrations[i] ?? 0) * 30 * (height / this.boxMaxHeight)), + ); context.fillStyle = speciesStyleIn(reaction, i).color.value.withAlpha(0.55).toCSS(); for (let k = 0; k < count; k++) { const fraction = this.scatter[k]; @@ -307,7 +310,10 @@ class ParticleCanvasNode extends CanvasNode { } } }); - const inert = Math.min(INERT_DOTS_CAP, Math.round(mixture.getInertAmount() * reaction.definition.particlesPerMole)); + const inert = Math.min( + INERT_DOTS_CAP, + roundSymmetric(mixture.getInertAmount() * reaction.definition.particlesPerMole), + ); context.fillStyle = EquilibriumLabColors.inertGasColorProperty.value.toCSS(); for (let k = 0; k < inert; k++) { const fraction = this.scatter[this.scatter.length - 1 - k]; diff --git a/src/common/view/QKGaugeNode.ts b/src/common/view/QKGaugeNode.ts index 8586830..7ea2552 100644 --- a/src/common/view/QKGaugeNode.ts +++ b/src/common/view/QKGaugeNode.ts @@ -1,3 +1,4 @@ +import { roundSymmetric } from "scenerystack/dot"; import { QK_GAUGE_NODE_SETTINGS } from "../../EquilibriumLabConstants.js"; /** * QKGaugeNode.ts @@ -134,7 +135,7 @@ export class QKGaugeNode extends Node { const lnQ = kp ? mixture.lnQp : mixture.lnQc; const symbols = kp ? strings.kpSymbols : strings.kcSymbols; const log10K = lnK / Math.LN10; - const centerDecade = Math.round(log10K); + const centerDecade = roundSymmetric(log10K); drawTicks(centerDecade); const toX = (log10: number) => ((log10 - centerDecade + HALF_SPAN_DECADES) / (2 * HALF_SPAN_DECADES)) * width; diff --git a/src/common/view/reactionChoices.ts b/src/common/view/reactionChoices.ts index b6cd4a2..9db187d 100644 --- a/src/common/view/reactionChoices.ts +++ b/src/common/view/reactionChoices.ts @@ -6,7 +6,7 @@ import type { TReadOnlyProperty } from "scenerystack/axon"; import { StringManager } from "../../i18n/StringManager.js"; -import type { ReactionId } from "../model/Reaction.js"; +import type { ReactionId, SpeciesId } from "../model/Reaction.js"; import type { ComboChoice } from "./ControlFactory.js"; export function reactionChoices(ids: readonly ReactionId[]): ComboChoice[] { @@ -14,15 +14,8 @@ export function reactionChoices(ids: readonly ReactionId[]): ComboChoice ({ value: id, label: names[`${id}StringProperty`] })); } -type SpeciesNames = ReturnType["speciesNames"]; - /** The spoken name of a species, e.g. "nitrogen dioxide" for NO2. */ -export function speciesName(id: string): TReadOnlyProperty { +export function speciesName(id: SpeciesId): TReadOnlyProperty { const names = StringManager.getInstance().getCommonStrings().speciesNames; - const key = `${id}StringProperty` as keyof SpeciesNames; - const name = names[key]; - if (!name) { - throw new Error(`No name for species ${id}`); - } - return name; + return names[`${id}StringProperty`]; } diff --git a/src/ice-table/model/ICEProblem.ts b/src/ice-table/model/ICEProblem.ts index 952a004..90a1470 100644 --- a/src/ice-table/model/ICEProblem.ts +++ b/src/ice-table/model/ICEProblem.ts @@ -1,3 +1,4 @@ +import { roundSymmetric } from "scenerystack/dot"; import { ICE_PROBLEM_SETTINGS } from "../../EquilibriumLabConstants.js"; /** * ICEProblem.ts @@ -17,7 +18,7 @@ import { ICE_PROBLEM_SETTINGS } from "../../EquilibriumLabConstants.js"; import type { Random } from "scenerystack/dot"; import { amountsAtExtent, extentBounds, solveEquilibriumExtent } from "../../common/model/equilibriumSolver.js"; -import type { Reaction } from "../../common/model/Reaction.js"; +import type { Reaction, Species } from "../../common/model/Reaction.js"; import { GAS_CONSTANT } from "../../EquilibriumLabConstants.js"; export type ICEMode = "findEquilibrium" | "findK"; @@ -44,12 +45,26 @@ function roundSignificant(value: number, digits: number = ICE_PROBLEM_SETTINGS.D return value; } const scale = 10 ** (digits - 1 - Math.floor(Math.log10(Math.abs(value)))); - return Math.round(value * scale) / scale; + return roundSymmetric(value * scale) / scale; +} + +function concentrationAt(concentrations: readonly number[], index: number, species: Species): number { + const concentration = concentrations[index]; + if (concentration === undefined) { + throw new Error(`Missing concentration for ${species.id}.`); + } + return concentration; } /** Kc of a set of equilibrium concentrations. */ export function kFromConcentrations(reaction: Reaction, concentrations: readonly number[]): number { - return reaction.species.reduce((product, s, i) => product * (concentrations[i] ?? 0) ** s.nu, 1); + if (concentrations.length !== reaction.species.length) { + throw new Error("A concentration must be supplied for each reaction species."); + } + return reaction.species.reduce( + (product, species, i) => product * concentrationAt(concentrations, i, species) ** species.nu, + 1, + ); } /** Generic reactions: K values that make tidy problems. */ @@ -71,10 +86,10 @@ export function createProblem(base: Reaction, mode: ICEMode, random: Random): IC // products usually absent (sometimes present, so the reaction may run either way). const largest = Math.max(...d.defaultAmounts) / volume; const anyProducts = random.nextDouble() < ICE_PROBLEM_SETTINGS.PRODUCT_PRESENT_PROBABILITY; - const initial = base.species.map((s) => { - if (s.nu < 0 || anyProducts) { + const initialRows = base.species.map((species) => { + if (species.nu < 0 || anyProducts) { const fraction = - s.nu < 0 + species.nu < 0 ? random.nextDoubleBetween( ICE_PROBLEM_SETTINGS.REACTANT_FRACTION_MIN, ICE_PROBLEM_SETTINGS.REACTANT_FRACTION_MAX, @@ -83,29 +98,34 @@ export function createProblem(base: Reaction, mode: ICEMode, random: Random): IC ICE_PROBLEM_SETTINGS.PRODUCT_FRACTION_MIN, ICE_PROBLEM_SETTINGS.PRODUCT_FRACTION_MAX, ); - return roundSignificant(fraction * largest, 2); + return { species, concentration: roundSignificant(fraction * largest, 2) }; } - return 0; + return { species, concentration: 0 }; }); + const initial = initialRows.map(({ concentration }) => concentration); const amounts = initial.map((c) => c * volume); if (mode === "findEquilibrium") { const kShown = roundSignificant(Math.exp(lnTarget), ICE_PROBLEM_SETTINGS.GIVEN_SIGNIFICANT_FIGURES); const reaction = withKc(base, temperature, kShown); const x = solveEquilibriumExtent(reaction, amounts, volume, Math.log(kShown)) / volume; - const equilibrium = initial.map((c, i) => c + (base.species[i]?.nu ?? 0) * x); + const equilibrium = initialRows.map(({ species, concentration }) => concentration + species.nu * x); return { mode, reaction, temperature, initial, givenIndex: null, givenValue: null, x, equilibrium, k: kShown }; } // findK: give the equilibrium concentration of the first product (rounded), and derive K. const trueX = solveEquilibriumExtent(base, amounts, volume, lnTarget) / volume; - const givenIndex = base.productIndices[0] ?? 0; - const nu = base.species[givenIndex]?.nu ?? 1; + const givenIndex = initialRows.findIndex(({ species }) => species.nu > 0); + const givenRow = initialRows[givenIndex]; + if (givenRow === undefined) { + throw new Error("A find K problem requires a product concentration to give."); + } + const givenCoefficient = givenRow.species.nu; const givenValue = roundSignificant( - (initial[givenIndex] ?? 0) + nu * trueX, + givenRow.concentration + givenCoefficient * trueX, ICE_PROBLEM_SETTINGS.GIVEN_SIGNIFICANT_FIGURES, ); - let x = (givenValue - (initial[givenIndex] ?? 0)) / nu; + let x = (givenValue - givenRow.concentration) / givenCoefficient; const { min, max } = extentBounds(base, amounts); x = Math.min(max / volume, Math.max(min / volume, x)); const equilibrium = amountsAtExtent(base, amounts, x * volume).map((n) => n / volume); @@ -127,9 +147,11 @@ const ANSWER_TOLERANCE: number = ICE_PROBLEM_SETTINGS.ANSWER_TOLERANCE; * Whether `coefficients` (the change row, in multiples of x) is right: each is the stoichiometric * coefficient times one common sign. Returns that sign (+1 or −1), or 0 if the row is wrong. */ -export function changeRowSign(reaction: Reaction, coefficients: readonly number[]): 1 | -1 | 0 { +export function changeRowSign( + rows: readonly { readonly species: Pick; readonly coefficient: number }[], +): 1 | -1 | 0 { for (const sign of [1, -1] as const) { - if (reaction.species.every((s, i) => coefficients[i] === sign * s.nu)) { + if (rows.every(({ species, coefficient }) => coefficient === sign * species.nu)) { return sign; } } @@ -150,9 +172,9 @@ export function matches(entered: number, expected: number): boolean { */ export function smallXPercent(problem: ICEProblem): { percent: number; index: number } | null { let best: { percent: number; index: number } | null = null; - problem.reaction.species.forEach((s, i) => { - const c0 = problem.initial[i] ?? 0; - const consumed = -s.nu * problem.x; + problem.reaction.species.forEach((species, i) => { + const c0 = concentrationAt(problem.initial, i, species); + const consumed = -species.nu * problem.x; if (c0 > 0 && consumed > 0) { const percent = (100 * consumed) / c0; if (!best || percent > best.percent) { diff --git a/src/ice-table/model/ICETableModel.ts b/src/ice-table/model/ICETableModel.ts index 1dfa250..6234320 100644 --- a/src/ice-table/model/ICETableModel.ts +++ b/src/ice-table/model/ICETableModel.ts @@ -8,10 +8,10 @@ import { ICE_TABLE_MODEL_SETTINGS } from "../../EquilibriumLabConstants.js"; * equilibrium row they wrote. */ -import { Emitter, NumberProperty, Property } from "scenerystack/axon"; +import { Emitter, NumberProperty, Property, type TReadOnlyProperty } from "scenerystack/axon"; import { Random, Range } from "scenerystack/dot"; import type { TModel } from "scenerystack/joist"; -import type { ReactionId } from "../../common/model/Reaction.js"; +import type { ReactionId, Species } from "../../common/model/Reaction.js"; import { ReactionSceneModel } from "../../common/model/ReactionSceneModel.js"; import { getReaction } from "../../common/model/Reactions.js"; import { @@ -35,7 +35,7 @@ export const ICE_REACTION_IDS: readonly ReactionId[] = [ ]; /** Range of each change-row coefficient (multiples of x). */ -export const CHANGE_COEFFICIENT_RANGE = new Range( +const CHANGE_COEFFICIENT_RANGE = new Range( ICE_TABLE_MODEL_SETTINGS.CHANGE_COEFFICIENT_RANGE_MIN, ICE_TABLE_MODEL_SETTINGS.CHANGE_COEFFICIENT_RANGE_MAX, ); @@ -54,6 +54,12 @@ export type ICECheck = { readonly kCorrect: boolean; }; +type ICESpeciesRow = { + readonly species: Species; + readonly initial: number; + readonly coefficientProperty: NumberProperty; +}; + export class ICETableModel implements TModel { public readonly modeProperty = new Property("findEquilibrium", { validValues: ["findEquilibrium", "findK"], @@ -61,12 +67,9 @@ export class ICETableModel implements TModel { public readonly reactionIdProperty = new Property("dinitrogenTetroxide", { validValues: ICE_REACTION_IDS, }); - public readonly problemProperty: Property; + public readonly problemProperty: TReadOnlyProperty; - /** The change row, one coefficient of x per species; rebuilt with each problem. */ - public changeCoefficientProperties: NumberProperty[] = []; - - /** Fires after changeCoefficientProperties is rebuilt. */ + /** Fires after the new problem and its rows are available. */ public readonly changeRowRebuiltEmitter = new Emitter(); /** The x and K the student entered (null until entered). */ @@ -82,6 +85,8 @@ export class ICETableModel implements TModel { /** The mixture "Run it" plays from the initial row. */ public readonly scene: ReactionSceneModel; + private readonly currentProblemProperty: Property; + private rows: readonly ICESpeciesRow[] = []; private readonly random = new Random({ seed: PROBLEM_SEED }); /** @@ -91,10 +96,11 @@ export class ICETableModel implements TModel { private suppressProblemRefresh = false; public constructor() { - this.problemProperty = new Property(this.generate()); - this.scene = new ReactionSceneModel(this.problemProperty.value.reaction); - this.scene.timer.isPlayingProperty.value = false; - this.applyProblem(); + const problem = this.generate(); + this.currentProblemProperty = new Property(problem); + this.problemProperty = this.currentProblemProperty; + this.scene = new ReactionSceneModel(problem.reaction); + this.applyProblem(problem); // Synchronous on purpose: the mode, reaction and problem must never disagree (showSolution or // a check in between would grade the wrong problem). applyProblem() orders the teardown so @@ -117,9 +123,9 @@ export class ICETableModel implements TModel { return this.problemProperty.value; } - /** The change row as entered. */ - public getChangeCoefficients(): number[] { - return this.changeCoefficientProperties.map((p) => p.value); + /** One editable coefficient of x per species, paired with its initial concentration. */ + public get speciesRows(): readonly ICESpeciesRow[] { + return this.rows; } /** The equilibrium row the student's entries give (M), or null until x is entered. */ @@ -128,17 +134,18 @@ export class ICETableModel implements TModel { if (x === null) { return null; } - return this.problem.initial.map((c, i) => c + (this.changeCoefficientProperties[i]?.value ?? 0) * x); + return this.rows.map(({ initial, coefficientProperty }) => initial + coefficientProperty.value * x); } public newProblem(): void { - this.problemProperty.value = this.generate(); - this.applyProblem(); + this.applyProblem(this.generate()); } public check(): void { const problem = this.problem; - const sign = changeRowSign(problem.reaction, this.getChangeCoefficients()); + const sign = changeRowSign( + this.rows.map(({ species, coefficientProperty }) => ({ species, coefficient: coefficientProperty.value })), + ); const x = this.xEntryProperty.value; const k = this.kEntryProperty.value; const expectedX = problem.x * (sign === 0 ? 1 : sign); @@ -150,9 +157,9 @@ export class ICETableModel implements TModel { /** Fills in the change row and x (and K) with the solution. */ public showSolution(): void { const problem = this.problem; - this.changeCoefficientProperties.forEach((property, i) => { - property.value = problem.reaction.species[i]?.nu ?? 0; - }); + for (const { species, coefficientProperty } of this.rows) { + coefficientProperty.value = species.nu; + } this.xEntryProperty.value = problem.x; if (problem.mode === "findK") { this.kEntryProperty.value = problem.k; @@ -165,7 +172,7 @@ export class ICETableModel implements TModel { public runIt(): void { const problem = this.problem; const volume = problem.reaction.definition.defaultVolume; - this.scene.restart(problem.initial.map((c) => c * volume)); + this.scene.restart(this.rows.map(({ initial }) => initial * volume)); this.scene.timer.isPlayingProperty.value = true; } @@ -199,23 +206,32 @@ export class ICETableModel implements TModel { * only after Multilinks/NumberPickers have released them. Setting x/k to null before that * disposal used to notify Multilinks still wired to disposed dependencies (?ea asserts). */ - private applyProblem(): void { - const problem = this.problem; - const oldCoefficients = this.changeCoefficientProperties; - this.changeCoefficientProperties = problem.reaction.species.map( - () => new NumberProperty(0, { range: CHANGE_COEFFICIENT_RANGE, numberType: "Integer" }), - ); - for (const property of this.changeCoefficientProperties) { - property.lazyLink(() => { + private applyProblem(problem: ICEProblem): void { + if (problem.initial.length !== problem.reaction.species.length) { + throw new Error("An ICE problem must provide one initial concentration per species."); + } + const initialRows = problem.reaction.species.map((species, index) => { + const initial = problem.initial[index]; + if (initial === undefined) { + throw new Error(`An ICE problem is missing the initial concentration for ${species.id}.`); + } + return { species, initial }; + }); + const oldRows = this.rows; + this.rows = initialRows.map(({ species, initial }) => { + const coefficientProperty = new NumberProperty(0, { range: CHANGE_COEFFICIENT_RANGE, numberType: "Integer" }); + coefficientProperty.lazyLink(() => { this.checkProperty.value = null; }); - } + return { species, initial, coefficientProperty }; + }); + this.currentProblemProperty.value = problem; // View drops Multilinks/pickers on the old row and binds to the new Properties. this.changeRowRebuiltEmitter.emit(); - for (const property of oldCoefficients) { - property.dispose(); + for (const { coefficientProperty } of oldRows) { + coefficientProperty.dispose(); } this.xEntryProperty.value = null; @@ -225,7 +241,7 @@ export class ICETableModel implements TModel { const volume = problem.reaction.definition.defaultVolume; this.scene.setReaction( problem.reaction, - problem.initial.map((c) => c * volume), + this.rows.map(({ initial }) => initial * volume), ); this.scene.mixture.temperatureProperty.value = problem.temperature; this.scene.timer.isPlayingProperty.value = false; diff --git a/src/ice-table/view/ICETableNode.ts b/src/ice-table/view/ICETableNode.ts index 75aeb04..416685b 100644 --- a/src/ice-table/view/ICETableNode.ts +++ b/src/ice-table/view/ICETableNode.ts @@ -8,7 +8,7 @@ import { ICE_TABLE_NODE_SETTINGS } from "../../EquilibriumLabConstants.js"; * cell. Rebuilt with each new problem. */ -import { DerivedProperty, Multilink, Property, type TReadOnlyProperty } from "scenerystack/axon"; +import { DerivedProperty, Multilink, type TReadOnlyProperty } from "scenerystack/axon"; import { StringUtils } from "scenerystack/phetcommon"; import { HBox, Line, Node, RichText, type TColor, Text, VBox } from "scenerystack/scenery"; import { PhetFont } from "scenerystack/scenery-phet"; @@ -19,7 +19,7 @@ import { speciesName } from "../../common/view/reactionChoices.js"; import EquilibriumLabColors from "../../EquilibriumLabColors.js"; import { FONT_SIZE } from "../../EquilibriumLabConstants.js"; import { StringManager } from "../../i18n/StringManager.js"; -import { CHANGE_COEFFICIENT_RANGE, type ICETableModel } from "../model/ICETableModel.js"; +import type { ICETableModel } from "../model/ICETableModel.js"; /** Width of the row-label column and of each species column (px). */ const LABEL_WIDTH: number = ICE_TABLE_NODE_SETTINGS.LABEL_WIDTH; @@ -93,8 +93,8 @@ export class ICETableNode extends Node { this.owned = []; disposeChildren(this); const problem = model.problem; - const reaction = problem.reaction; - const count = reaction.species.length; + const rows = model.speciesRows; + const count = rows.length; const columnWidth = (width - LABEL_WIDTH) / count; const columnX = (i: number) => LABEL_WIDTH + (i + 0.5) * columnWidth; const rowY = (row: number) => (row + 0.5) * ROW_HEIGHT; @@ -137,33 +137,32 @@ export class ICETableNode extends Node { }), ); - reaction.species.forEach((s, i) => { + rows.forEach(({ species, initial: initialConcentration, coefficientProperty }, i) => { // Header and initial row. - const header = text(`[${s.formula}]`, columnWidth - 8, true); + const header = text(`[${species.formula}]`, columnWidth - 8, true); header.centerX = columnX(i); header.centerY = rowY(0); const initial = text( - significant(problem.initial[i] ?? 0, ICE_TABLE_NODE_SETTINGS.INITIAL_DIGITS), + significant(initialConcentration, ICE_TABLE_NODE_SETTINGS.INITIAL_DIGITS), columnWidth - 8, ); initial.centerX = columnX(i); initial.centerY = rowY(1); // Change row: picker × x. - const coefficient = model.changeCoefficientProperties[i] ?? new Property(0); - const pickerName = new DerivedProperty( - [a11y.changePickerPatternStringProperty, speciesName(s.id)], + const pickerNameProperty = new DerivedProperty( + [a11y.changePickerPatternStringProperty, speciesName(species.id)], (pattern, name) => StringUtils.fillIn(pattern, { name }), ); - this.owned.push(pickerName); - const picker = new NumberPicker(coefficient, new Property(CHANGE_COEFFICIENT_RANGE), { + this.owned.push(pickerNameProperty); + const picker = new NumberPicker(coefficientProperty, coefficientProperty.rangeProperty, { font: new PhetFont(FONT_SIZE.readout), color: EquilibriumLabColors.accentColorProperty, backgroundStroke: EquilibriumLabColors.panelBorderColorProperty, xMargin: ICE_TABLE_NODE_SETTINGS.PICKER_X_MARGIN, yMargin: 1, formatValue: (n: number) => (n > 0 ? `+${n}` : fixed(n, 0)), - accessibleName: pickerName, + accessibleName: pickerNameProperty, }); const change = new HBox({ spacing: ICE_TABLE_NODE_SETTINGS.CHANGE_SPACING, @@ -180,10 +179,10 @@ export class ICETableNode extends Node { maxWidth: columnWidth - ICE_TABLE_NODE_SETTINGS.VALUE_MAX_WIDTH_OFFSET, }); const cell = new VBox({ spacing: 1, children: [expression, value] }); - const multilink = Multilink.multilink([coefficient, model.xEntryProperty], (c, x) => { - expression.string = changeExpression(problem.initial[i] ?? 0, c); + const multilink = Multilink.multilink([coefficientProperty, model.xEntryProperty], (c, x) => { + expression.string = changeExpression(initialConcentration, c); const evaluated = evaluateCell( - problem.initial[i] ?? 0, + initialConcentration, c, x, problem.givenIndex === i ? problem.givenValue : null, diff --git a/src/ice-table/view/ICETableScreenView.ts b/src/ice-table/view/ICETableScreenView.ts index bab9ada..b9a65dc 100644 --- a/src/ice-table/view/ICETableScreenView.ts +++ b/src/ice-table/view/ICETableScreenView.ts @@ -273,15 +273,13 @@ export class ICETableScreenView extends ScreenView { let unlinkCoefficients: (() => void) | null = null; const linkCoefficients = () => { unlinkCoefficients?.(); - const properties = model.changeCoefficientProperties; - for (const property of properties) { - property.link(updateReferences); + const rows = model.speciesRows; + for (const { coefficientProperty } of rows) { + coefficientProperty.lazyLink(updateReferences); } unlinkCoefficients = () => { - for (const property of properties) { - if (!property.isDisposed) { - property.unlink(updateReferences); - } + for (const { coefficientProperty } of rows) { + coefficientProperty.unlink(updateReferences); } unlinkCoefficients = null; }; diff --git a/src/le-chatelier/view/StressControlsNode.ts b/src/le-chatelier/view/StressControlsNode.ts index 3352ed5..978dbcd 100644 --- a/src/le-chatelier/view/StressControlsNode.ts +++ b/src/le-chatelier/view/StressControlsNode.ts @@ -50,20 +50,20 @@ export class StressControlsNode extends VBox { const rows = reaction.species.map((s, i) => { const name = speciesName(s.id); - const addName = new DerivedProperty([a11y.addPatternStringProperty, name], (pattern, n) => + const addNameProperty = new DerivedProperty([a11y.addPatternStringProperty, name], (pattern, n) => StringUtils.fillIn(pattern, { name: n }), ); - const removeName = new DerivedProperty([a11y.removePatternStringProperty, name], (pattern, n) => + const removeNameProperty = new DerivedProperty([a11y.removePatternStringProperty, name], (pattern, n) => StringUtils.fillIn(pattern, { name: n }), ); - this.owned.push(addName, removeName); + this.owned.push(addNameProperty, removeNameProperty); const addButton = pushButton( strings.addButtonStringProperty, () => { model.addSpecies(i, StringUtils.fillIn(markers.addPatternStringProperty.value, { formula: s.formula })); respond(); }, - addName, + addNameProperty, ); const removeButton = pushButton( strings.removeButtonStringProperty, @@ -74,7 +74,7 @@ export class StressControlsNode extends VBox { ); respond(); }, - removeName, + removeNameProperty, ); addButton.enabledProperty = enabledProperty; removeButton.enabledProperty = enabledProperty; @@ -124,13 +124,13 @@ export class StressControlsNode extends VBox { model.addArgon(true, markers.argonStringProperty.value); respond(); }); - const argonPressureEnabled = new DerivedProperty( + const argonPressureEnabledProperty = new DerivedProperty( [enabledProperty, mixture.volumeProperty], (enabled) => enabled && model.canAddArgonAtConstantPressure, ); - this.owned.push(argonPressureEnabled); + this.owned.push(argonPressureEnabledProperty); argonVolume.enabledProperty = enabledProperty; - argonPressure.enabledProperty = argonPressureEnabled; + argonPressure.enabledProperty = argonPressureEnabledProperty; extras.push( new HBox({ spacing: STRESS_CONTROLS_NODE_SETTINGS.REBUILD_SPACING, children: [argonVolume, argonPressure] }), ); @@ -139,12 +139,12 @@ export class StressControlsNode extends VBox { model.dilute(markers.waterStringProperty.value); respond(); }); - const waterEnabled = new DerivedProperty( + const waterEnabledProperty = new DerivedProperty( [enabledProperty, mixture.volumeProperty], (enabled, volume) => enabled && volume < reaction.definition.volumeRange.max, ); - this.owned.push(waterEnabled); - water.enabledProperty = waterEnabled; + this.owned.push(waterEnabledProperty); + water.enabledProperty = waterEnabledProperty; extras.push(water); } 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, []); }); diff --git a/tests/browser/review-regressions.spec.ts b/tests/browser/review-regressions.spec.ts index e1ca617..a21602a 100644 --- a/tests/browser/review-regressions.spec.ts +++ b/tests/browser/review-regressions.spec.ts @@ -20,6 +20,27 @@ async function ready(page: Page, screen: number, locale = "en") { await page.locator("h1").first().waitFor(); } +test("ICE-table pickers edit the species rows for the current reaction", async ({ page }) => { + await ready(page, 2); + const nitrogenDioxide = page.getByRole("slider", { name: "Change in nitrogen dioxide, in multiples of x" }); + const showSolution = page.getByRole("button", { name: "Show solution" }); + await nitrogenDioxide.press("ArrowDown"); + await expect(nitrogenDioxide).toHaveValue("-1"); + await showSolution.press("Enter"); + await expect(nitrogenDioxide).toHaveValue("2"); + + await page.getByRole("button", { name: /Reaction/ }).press("Enter"); + await page.getByRole("option", { name: "Water-gas shift" }).press("Enter"); + await expect(nitrogenDioxide).toHaveCount(0); + + const carbonDioxide = page.getByRole("slider", { name: "Change in carbon dioxide, in multiples of x" }); + await expect(carbonDioxide).toHaveValue("0"); + await carbonDioxide.press("ArrowDown"); + await expect(carbonDioxide).toHaveValue("-1"); + await showSolution.press("Enter"); + await expect(carbonDioxide).toHaveValue("1"); +}); + for (const control of ["temperature", "piston"] as const) { test(`held ${control} keyboard gesture keeps a correct prediction and resumes on release`, async ({ page }) => { await ready(page, 3); diff --git a/tests/ice-table/ICETable.test.ts b/tests/ice-table/ICETable.test.ts index 45090db..b876697 100644 --- a/tests/ice-table/ICETable.test.ts +++ b/tests/ice-table/ICETable.test.ts @@ -11,6 +11,7 @@ import { getReaction } from "../../src/common/model/Reactions.js"; import { changeRowSign, createProblem, + type ICEProblem, kFromConcentrations, smallXPercent, } from "../../src/ice-table/model/ICEProblem.js"; @@ -39,12 +40,19 @@ describe("ICE problems", () => { } }); - it("accepts the change row in either sign convention", () => { - const reaction = getReaction("hydrogenIodide"); - expect(changeRowSign(reaction, [-1, -1, 2])).toBe(1); - expect(changeRowSign(reaction, [1, 1, -2])).toBe(-1); - expect(changeRowSign(reaction, [-1, -1, 1])).toBe(0); - expect(changeRowSign(reaction, [-1, 1, 2])).toBe(0); + it.each([ + [-1, -1, 2, 1], + [1, 1, -2, -1], + [-1, -1, 1, 0], + [-1, 1, 2, 0], + ])("checks change coefficients (%i, %i, %i) with sign %i", (hydrogen, iodine, product, sign) => { + expect( + changeRowSign([ + { species: { nu: -1 }, coefficient: hydrogen }, + { species: { nu: -1 }, coefficient: iodine }, + { species: { nu: 2 }, coefficient: product }, + ]), + ).toBe(sign); }); it("reports x as a percentage of the initial concentration it depletes", () => { @@ -53,15 +61,21 @@ describe("ICE problems", () => { expect(result?.index).toBe(0); expect(result?.percent).toBeCloseTo((100 * problem.x) / (problem.initial[0] ?? 1), 9); }); + + it("rejects a missing concentration when calculating K", () => { + expect(() => kFromConcentrations(getReaction("hydrogenIodide"), [1, 1])).toThrow( + "A concentration must be supplied for each reaction species.", + ); + }); }); describe("ICETableModel", () => { it("checks a correct answer, with either sign convention", () => { const model = new ICETableModel(); const problem = model.problem; - problem.reaction.species.forEach((s, i) => { - model.changeCoefficientProperties[i]!.value = -s.nu; - }); + for (const { species, coefficientProperty } of model.speciesRows) { + coefficientProperty.value = -species.nu; + } model.xEntryProperty.value = -problem.x; model.check(); expect(model.checkProperty.value).toMatchObject({ sign: -1, xCorrect: true }); @@ -97,12 +111,37 @@ describe("ICETableModel", () => { }); }); - it("a new reaction or mode deals a new problem with a blank change row", () => { + it("publishes matching rows and releases old coefficients after the views can rebind", () => { const model = new ICETableModel(); - model.changeCoefficientProperties[0]!.value = -1; + model.showSolution(); + const oldRows = model.speciesRows; + const observeProblem = (problem: ICEProblem) => { + expect(model.speciesRows.map(({ species }) => species)).toEqual(problem.reaction.species); + expect(model.speciesRows.map(({ initial }) => initial)).toEqual(problem.initial); + }; + model.problemProperty.lazyLink(observeProblem); + const checkRebuild = () => { + expect(model.speciesRows).not.toBe(oldRows); + expect(oldRows.every(({ coefficientProperty }) => !coefficientProperty.isDisposed)).toBe(true); + }; + model.changeRowRebuiltEmitter.addListener(checkRebuild); model.reactionIdProperty.value = "waterGasShift"; + model.problemProperty.unlink(observeProblem); + model.changeRowRebuiltEmitter.removeListener(checkRebuild); + expect(model.problem.reaction.id).toBe("waterGasShift"); - expect(model.getChangeCoefficients()).toEqual([0, 0, 0, 0]); + expect(oldRows.every(({ coefficientProperty }) => coefficientProperty.isDisposed)).toBe(true); + expect(model.speciesRows.map(({ coefficientProperty }) => coefficientProperty.value)).toEqual([0, 0, 0, 0]); expect(model.xEntryProperty.value).toBeNull(); + + model.showSolution(); + expect(model.checkProperty.value).toMatchObject({ sign: 1, xCorrect: true }); + model.problem.equilibrium.forEach((expected, index) => { + expect(model.getEnteredEquilibrium()?.[index]).toBeCloseTo(expected, 10); + }); + model.reset(); + expect(model.problem.reaction.id).toBe("dinitrogenTetroxide"); + expect(model.speciesRows.map(({ coefficientProperty }) => coefficientProperty.value)).toEqual([0, 0]); + expect(model.checkProperty.value).toBeNull(); }); });