wrolpi/app/src/components/Calculators.js

99 lines
5.1 KiB
JavaScript
Raw Normal View History

import React from "react";
2024-06-25 17:05:41 -06:00
import {Breadcrumbs, useTitle} from "./Common";
ui: fix the cypress failures, and two real defects behind them All 43 cypress specs pass now (was 36 of 43). Five of the seven failures were stale selectors, two were real. Real, and both mine: The search modal stopped focusing its input. Mantine mounts modal content on a later tick, so the effect that focused it ran while the ref was still null; Semantic's modal mounted synchronously, which is why focusing there had been enough. Fixed declaratively -- the field asks for focus itself, and SearchBox also sets `data-autofocus`, which is what Mantine's focus trap honours when it takes focus away from a plain autoFocus. Escape closed the suggestion list and the enclosing modal at once, so a user correcting a mistyped query lost the whole modal. Escape now dismisses the suggestions and stops there; a second Escape, with the list closed, still closes the modal. Stale selectors, all in the specs: Semantic's icon font (`i.search.icon`) is SVG now, its `.ui.modal`/`.ui.dimmer` are the library's modal and overlay, and one test asserted a button carried the classes `ui button secondary`. That last one is rewritten to check what a user can actually perceive -- that Edit is a real link pointing at the edit route -- because framework class names say nothing and break on every library change. Two accessibility gaps the tests walked into: The nav's search control was an anchor with an onClick, no name and no keyboard path. It now has a name, a role and Enter/Space activation, which is also what let the spec stop matching on icon-font classes. The search dialog had no accessible name at all; it has one now. One `{force: true}` remains, with its reason recorded: Cypress judges that field covered because it sits in a fixed modal under a sticky header, and I verified by hand at Cypress's own viewport that it is the topmost element at its centre, unobscured, and focused on open. Also closed a hole in the ratchet that this uncovered. A file could drop its `semantic-ui-react` imports, leave the baseline, and still render Semantic through Theme.tsx's wrappers -- which is exactly how a Semantic modal survived in the search shortcut long after that file looked migrated. A test now forbids it, and the three files doing it (Calculators, KeyboardShortcutsProvider, and Common.js reaching for theme names) import from the library or from themes/names instead.
2026-07-30 12:53:19 -06:00
import {Button, Header, Icon} from "./ui";
import {useCalcQuery} from "../hooks/customHooks";
2024-06-20 09:51:29 -06:00
import {TemperatureCalculator} from "./calculators/TemperatureCalculator";
2024-06-25 17:05:41 -06:00
import {ElectricalCalculators} from "./calculators/ElectricalCalculators";
2024-06-20 09:51:29 -06:00
import {DipoleAntennaCalculator} from "./calculators/HamCalculators";
import {Link} from "react-router";
import {RatioCalculators} from "./calculators/RatioCalculator";
import {QRCodeCalculator} from "./calculators/QRCodeCalculator";
import {DriveCalculator} from "./calculators/DriveCalculator";
import {WaterCalculator} from "./calculators/WaterCalculator";
Rebuild Inventory as a config-only system with food catalog and calculators Replace the DB-backed inventory module with a config-only design and build out food-storage tooling around it. Inventory (config-only, no database) - Each inventory is a YAML file at config/inventory/<slug>.yaml, loaded once into memory and the single source of truth. New reusable MultiFileConfig (wrolpi/common.py) manages a directory of per-entity files. - Inventory types (food/fuel/tool) seed a customizable field schema (text/number/quantity/date/select/location/calories). Unit math/aggregation moved to the frontend (mathjs); Pint dropped from the backend. - Minimal API: GET / (all inventories full), POST /, PUT /<slug> (whole- inventory save with version-based optimistic concurrency; 404 for missing), DELETE. Legacy inventories.yaml / old tables migrate to per-inventory files (pound->lb), and an alembic migration drops the tables. Frontend - New app/src/components/inventory/ package: spreadsheet-style table with Tab/Enter keyboard entry, sortable columns, expired-row highlighting, customizable field editor, and pooled cross-inventory location autocomplete. - A single useInventories store loads everything once and persists whole inventories optimistically; list/items/summary/locations derive client-side. - Summary groups items (default by Category), totals size x count, shows a calories column, and embeds a ration estimate (how long the stock lasts). Food catalog - Shared, editable catalog (config/inventory/catalog.yaml) seeded from catalog_defaults.yaml (~60 generic items, total calories per package) with merge-keep-edits + tombstones. GET/PUT /api/inventory/catalog, a management modal, and entry-row pre-fill of category/size/calories from a name match. Calculators - Generic Food Storage planner (like the Water calculator): household + editable per-person/year amounts -> total to store over a chosen duration, with women/children weighted by DGA calorie shares and an imperial/metric toggle. Also fixes ConfigFile.save() to accept nested file_names. Backend pytest and frontend jest suites updated/added throughout; alembic check clean. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-14 14:20:10 -06:00
import {FoodStorageCalculator} from "./calculators/FoodStorageCalculator";
import {OneTimePadCalculator} from "./calculators/OneTimePadCalculator";
import {VinDecoderCalculator} from "./calculators/VinDecoderCalculator";
Speed Test calculator: ping, download, and upload against the API (#708) * Speed Test calculator: ping, download, and upload against the API Users asking whether the hotspot is fast enough, or how many people can stream video at once, had no objective tool that works offline. This adds one under Calculators > Tools & Reference. Backend (wrolpi/speedtest.py, /api/speedtest): * ping: tiny no-store JSON the browser times for round trip latency. * download: streams slices of a pre-built random buffer for a clamped number of seconds (0.1-15). Random so no proxy or compression can flatter the result; slices so no bytes are generated per request. * upload: streaming-body handler that reads and discards the body and reports bytes and elapsed time. Requests over 8 MiB are refused. * info: the client address Caddy forwarded plus how many tests are in flight. Sanic now trusts one proxy hop (PROXIES_COUNT = 1) so request.remote_addr is the browser, not Caddy. Nothing else read that field before. There is deliberately no one-test-at-a-time lock. Several people testing at once is how a user learns how the link shares between streamers, so the server only counts in-flight tests (a shared_ctx Value created pre-fork so every worker sees the same number) and the UI reports how many others ran alongside. Both Caddyfiles route /api/speedtest/* unbuffered, as the SSE chat route already is, so throughput is measured live rather than in bursts. Frontend: * speedtest.js holds the logic with no React in it (bucketed throughput, steady-state average that drops the first second, ping stats, stream-capacity tiers, hotspot address check) so Jest drives it with fake fetch and streams. * SpeedTestCalculator runs 20 pings, a 10 s download, and a 10 s upload with a live figure and rolling trace, then shows Mbps and MB/s, ping verdict, the client address with a hotspot badge, and a table of how many 480p..4K streams the download speed supports. Upload is sequential POSTs of one 4 MiB Blob because Safari cannot stream a request body. Nothing is saved. * Sparkline is a new inline-SVG ui component (no chart dependency), added to /theme-sample and checked in all four themes. A missing sample is a gap, not a plunge to zero. The page states that it measures the network path, not the drive that actually serves video files. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * speedtest: bound uploads in time, close the Start race, address review Review on #708 found three bugs and some polish: * Start could be clicked again while the first fetchInfo() was still pending, because the phase only left `idle` after that await. A second click made a second AbortController and a second concurrent run, and Cancel only reached the later one. start() now refuses when a controller already exists and enters a `starting` phase synchronously, so the button is Cancel before the first await. * The upload phase could overrun the advertised 10 s by however long the in-flight 4 MiB POST took: on a slow hotspot, the very link this tool exists for, that is tens of seconds. runUpload() now aborts the in-flight request at the phase deadline (counting only completed requests) and uses 1 MiB bodies so a few-Mbps link still completes several inside the phase. * The server upload sink was capped by size only, so a slow or paused body could hold a worker until 8 MiB eventually arrived. It now also enforces MAX_UPLOAD_SECONDS (15 s, matching download) and answers 408 when exceeded. Both caps together are what "cannot hold a worker" actually requires. Also: a NaN `seconds` now gets a NaN message instead of "must not be negative"; the module, Sparkline, and gallery docstrings are trimmed to purpose; and the upload counter is covered for the mid-stream 413, the 408, and a broken body. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> --------- Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-13 18:47:04 -06:00
import {SpeedTestCalculator} from "./calculators/SpeedTestCalculator";
// Calculators are shown in these titled groups, in this order. Each calculator carries a
// `group` matching one of these names; any calculator whose group is missing/unknown falls
// into a trailing "Other" section so a new calculator can never silently disappear.
//
ui: the last of Semantic UI, in name and in dead CSS The library has been uninstalled for some time, but the codebase still read as though it were there: identifiers named after it, rules written against its class names, and about 180 comments explaining a rule in terms of a thing that is no longer installed. Renamed, keeping the vocabulary the app actually uses: semanticUIColorMap -> navColorHexMap, semanticColorNames -> paletteColorNames, semanticNames -> iconNameAliases, semanticSizes -> sizeAliases, and SemanticUIColors -> NavColors in wrolpi/schema.py, which is what validates nav_color on the way in. ColorToSemanticHexColor had no callers at all and is gone. The baseline ratchet has done its job -- the list reached zero, so the JSON is deleted and the guard keeps only the checks with teeth: no package, no import, no `className="ui "`, no toast library. Its Theme.tsx check went with the wrappers it was watching for. It also asserts its own walk found files, so a clean result cannot mean it scanned nothing. Deleted from App.css: every rule requiring `.ui`, `.inverted`, `.segment` or `.modal`, none of which any component has set since the stylesheet stopped loading, plus the form skeletons, ui-alerts and progress-text rules that nothing renders. Two of them were doing harm rather than nothing: the drag tints had a dark-theme variant under `.inverted` that stopped applying, leaving 15% of a fixed blue over a dark row, and now mix a token instead. Two selectors naming markup that no longer exists were live bugs. The file browser's filter had `.ui.input.file-browser-filter`, so it rendered at the browser default width on a bar laid out to give it 34em -- now qualified by its container, because `.wrolpi-action-input` sets `width: 100%` at the same specificity and is loaded later. And SearchBox takes named props rather than a rest spread, so the `id` DestinationForm hands it was dropped in silence and the label it renders pointed at nothing; the download forms' Destination field has had no associated label since the migration. "Semantic roles" survives in four places, where it means what it says. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-05 19:15:57 -06:00
// `color` is one of the named palette colors (see `paletteColorNames`) used to tint the group's
// buttons. Violet is intentionally avoided — it is the default navbar color and would blend in.
export const CALCULATOR_GROUPS = [
{name: 'Preparedness & Storage', color: 'red'},
{name: 'Radio & Communications', color: 'blue'},
{name: 'Engineering', color: 'yellow'},
{name: 'Tools & Reference', color: 'grey'},
];
export const useCalculators = () => {
const [calc, setCalc] = useCalcQuery();
const calculators = [
{key: 'ratio', icon: 'th large', button: 'Ratio', group: 'Engineering', contents: <RatioCalculators/>},
{key: 'electrical', icon: 'lightning', button: 'Electrical', group: 'Engineering', contents: <ElectricalCalculators/>},
{key: 'drive', icon: 'cogs', button: 'Drive Ratio', group: 'Engineering', contents: <DriveCalculator/>},
{key: 'water', icon: 'tint', button: 'Water Storage', group: 'Preparedness & Storage', contents: <WaterCalculator/>},
{key: 'ration', icon: 'food', button: 'Food Storage', group: 'Preparedness & Storage', contents: <FoodStorageCalculator/>},
{key: 'antenna', icon: 'signal', button: 'Antenna', group: 'Radio & Communications', contents: <DipoleAntennaCalculator/>},
{key: 'temperature', icon: 'thermometer', button: 'Temperature', group: 'Tools & Reference', contents: <TemperatureCalculator/>},
{key: 'qrCode', icon: 'qrcode', button: 'QR Code', group: 'Tools & Reference', contents: <QRCodeCalculator/>},
{key: 'otp', icon: 'lock', button: 'One Time Pad', title: 'One Time Pad', group: 'Radio & Communications', contents: <OneTimePadCalculator/>},
{key: 'vin', icon: 'car', button: 'VIN Decoder', title: 'VIN Decoder', group: 'Tools & Reference', contents: <VinDecoderCalculator/>},
Speed Test calculator: ping, download, and upload against the API (#708) * Speed Test calculator: ping, download, and upload against the API Users asking whether the hotspot is fast enough, or how many people can stream video at once, had no objective tool that works offline. This adds one under Calculators > Tools & Reference. Backend (wrolpi/speedtest.py, /api/speedtest): * ping: tiny no-store JSON the browser times for round trip latency. * download: streams slices of a pre-built random buffer for a clamped number of seconds (0.1-15). Random so no proxy or compression can flatter the result; slices so no bytes are generated per request. * upload: streaming-body handler that reads and discards the body and reports bytes and elapsed time. Requests over 8 MiB are refused. * info: the client address Caddy forwarded plus how many tests are in flight. Sanic now trusts one proxy hop (PROXIES_COUNT = 1) so request.remote_addr is the browser, not Caddy. Nothing else read that field before. There is deliberately no one-test-at-a-time lock. Several people testing at once is how a user learns how the link shares between streamers, so the server only counts in-flight tests (a shared_ctx Value created pre-fork so every worker sees the same number) and the UI reports how many others ran alongside. Both Caddyfiles route /api/speedtest/* unbuffered, as the SSE chat route already is, so throughput is measured live rather than in bursts. Frontend: * speedtest.js holds the logic with no React in it (bucketed throughput, steady-state average that drops the first second, ping stats, stream-capacity tiers, hotspot address check) so Jest drives it with fake fetch and streams. * SpeedTestCalculator runs 20 pings, a 10 s download, and a 10 s upload with a live figure and rolling trace, then shows Mbps and MB/s, ping verdict, the client address with a hotspot badge, and a table of how many 480p..4K streams the download speed supports. Upload is sequential POSTs of one 4 MiB Blob because Safari cannot stream a request body. Nothing is saved. * Sparkline is a new inline-SVG ui component (no chart dependency), added to /theme-sample and checked in all four themes. A missing sample is a gap, not a plunge to zero. The page states that it measures the network path, not the drive that actually serves video files. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * speedtest: bound uploads in time, close the Start race, address review Review on #708 found three bugs and some polish: * Start could be clicked again while the first fetchInfo() was still pending, because the phase only left `idle` after that await. A second click made a second AbortController and a second concurrent run, and Cancel only reached the later one. start() now refuses when a controller already exists and enters a `starting` phase synchronously, so the button is Cancel before the first await. * The upload phase could overrun the advertised 10 s by however long the in-flight 4 MiB POST took: on a slow hotspot, the very link this tool exists for, that is tens of seconds. runUpload() now aborts the in-flight request at the phase deadline (counting only completed requests) and uses 1 MiB bodies so a few-Mbps link still completes several inside the phase. * The server upload sink was capped by size only, so a slow or paused body could hold a worker until 8 MiB eventually arrived. It now also enforces MAX_UPLOAD_SECONDS (15 s, matching download) and answers 408 when exceeded. Both caps together are what "cannot hold a worker" actually requires. Also: a NaN `seconds` now gets a NaN message instead of "must not be negative"; the module, Sparkline, and gallery docstrings are trimmed to purpose; and the upload counter is covered for the mid-stream 413, the 408, and a broken body. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> --------- Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-13 18:47:04 -06:00
{key: 'speedtest', icon: 'tachometer alternate', button: 'Speed Test', title: 'Speed Test', group: 'Tools & Reference', contents: <SpeedTestCalculator/>},
];
const activeCalculator = calc ? calculators.find(i => i.key === calc) : null;
const calculatorButton = ({button, icon, key}, color) =>
<Link key={key} to={`/more/calculators?calc=${key}`}>
<Button color={color} style={{margin: '0.5em'}}>
2024-06-25 17:05:41 -06:00
{icon && <Icon name={icon}/>}
{button}
</Button>
</Link>;
// Render each defined group as a titled section, then any leftovers under "Other".
const groupNames = CALCULATOR_GROUPS.map(g => g.name);
const grouped = CALCULATOR_GROUPS.map(g => [g.name, g.color, calculators.filter(c => c.group === g.name)]);
const leftovers = calculators.filter(c => !groupNames.includes(c.group));
if (leftovers.length > 0) {
grouped.push(['Other', undefined, leftovers]);
}
const calculatorLinks = grouped
.filter(([, , items]) => items.length > 0)
.map(([name, color, items]) =>
<div key={name} style={{marginBottom: '1.5em'}}>
<Header as='h3'>{name}</Header>
{items.map(c => calculatorButton(c, color))}
</div>);
return {calc, calculators, activeCalculator, calculatorLinks}
}
export function CalculatorsPage() {
const {activeCalculator, calculatorLinks} = useCalculators();
const {icon, button, title, contents} = activeCalculator || {};
const name = activeCalculator ? title || button + ' Calculator' : 'Calculators';
useTitle(name);
const body = activeCalculator ? <span>{contents}</span> : calculatorLinks;
2024-06-25 17:05:41 -06:00
// Make first breadcrumb a link back to Calculators only when a calculator is active.
const crumbs = activeCalculator
? [{text: 'Calculators', link: '/more/calculators'}, {text: name, icon: icon}]
: [{text: 'Calculators'}];
return <>
2024-06-25 17:05:41 -06:00
<Breadcrumbs crumbs={crumbs} size='huge'/>
<div style={{marginTop: '1em'}}>
{body}
</div>
</>
}