ui: thirty-five files off Semantic, leaving fifteen

Phase 2, part 4.  Baseline 50 -> 15.

Migrated: all eight calculators, the rest of inventory and collections, the
Map/Zim/Docs cluster, Videos, Files, Search, Archive, DashboardPage,
DatesSelector, HelpModal, Events, Tags, Flasher's neighbours, admin Settings
and Status, Download, and App.

Also the three shared modules everything imports: api.js and customHooks.js
swap the Semantic toast library for the library's shim (same call shape), and
useForm.js renders the library's Message.  useForm accepts both the old
`{content, header, positive|negative}` shape and the new `{kind, title}`,
because the pages building those objects migrate separately.

Two library gaps closed, both found by call sites needing them:

  ActionInput is a forwardRef now.  Its ref reaches the input rather than the
  wrapper, because callers use it to focus or select the field -- a ref to the
  surrounding div would do neither, which is why one call site had resorted to
  hand-copying the component's markup.

  Header takes a `color` token name.  Three separate call sites had reached for
  an inline style to colour a heading that carries meaning ("3 items to add"
  against "2 to remove"), which is how a hex ends up in markup.

Two files needed repair after being interrupted mid-edit: MapViewer had a
Segment left in its error branch, and VideoPlayer had lost the useContext
import its own code still used.  Neither jest nor tsc noticed; only
`npm run build` did, which is the whole reason that check exists.

Fifteen files remain: Archive, BulkTagModal, Channels, Docs, FileBrowser,
FilePreview, Flasher, Nav, Playlists, Theme.tsx, Upload, VideoPlayer, Zim,
ControllerPage, admin/Downloads.  Theme.tsx is deliberately last -- the
unmigrated files still import its Semantic-backed wrappers, so it can only go
once they have.
This commit is contained in:
Roland 2026-07-30 12:21:30 -06:00 • committed by lrnselfreliance
parent 16bdffbac7
commit 906705e5b4
48 changed files with 3273 additions and 3877 deletions

View file

@ -1,10 +1,9 @@
import React from "react";
import {Form, Header, Segment, Table} from "../Theme";
import {Button, GridColumn, GridRow, Input, Label, TableBody, TableCell, TableRow} from "semantic-ui-react";
import Grid from "semantic-ui-react/dist/commonjs/collections/Grid";
import {Button, ButtonGroup, Grid, Group, Header, IconButton, NumberInput, Panel, Table} from "../ui";
import {ColoredInput} from "../Apps";
import {InfoPopup, roundDigits, Toggle, useLocalStorage} from "../Common";
import {Media} from "../../contexts/contexts";
import {IconSettings, IconSettings2} from "@tabler/icons-react";
// Pure calculation functions for the Drive Ratio calculator (pulleys, gears, sprockets).
//
@ -206,13 +205,15 @@ export function gearPoints(cx, cy, rOuter, rInner, teeth, tipFrac = 0.5) {
// Per-mode wording. All three drive types share the same math; only the size
// label (and the diagram) differ.
const MODES = {
pulley: {button: 'Pulley', icon: 'circle outline', sizeLabel: 'Diameter', toothed: false},
gear: {button: 'Gear', icon: 'cogs', sizeLabel: 'Teeth', toothed: true},
sprocket: {button: 'Sprocket', icon: 'cog', sizeLabel: 'Teeth', toothed: true},
pulley: {button: 'Pulley', icon: 'circle', sizeLabel: 'Diameter', toothed: false},
gear: {button: 'Gear', icon: IconSettings, sizeLabel: 'Teeth', toothed: true},
sprocket: {button: 'Sprocket', icon: IconSettings2, sizeLabel: 'Teeth', toothed: true},
};
// Distinct, colorblind-friendly wheel colors (Paul Tol's bright palette):
// blue, red, green, yellow, cyan, purple. Grey is reserved as a neutral.
// These are diagram/data-visualization colors, matched 1:1 to the drawn wheels
// below; they are not themed UI chrome, so they stay literal hex.
const ELEMENT_COLORS = ['#4477aa', '#ee6677', '#228833', '#ccbb44', '#66ccee', '#aa3377'];
const MIN_ELEMENTS = 2;
@ -393,6 +394,20 @@ function fmtSpeed(speed) {
return speed ? `${roundDigits(speed.value, 3)} ${speed.unit}` : '—';
}
// One wheel's size/RPM input, its label tinted to match its diagram color. The
// color is a literal hex (matched to the diagram, not a theme token), so this is
// a small local composition rather than the token-driven `Label`.
function WheelInput({hex, label, value, onChange, name, min, step}) {
return <Group gap={0} wrap='nowrap' align='stretch' style={{marginBottom: '0.25em'}}>
<span style={{
display: 'flex', alignItems: 'center', padding: '0 10px', fontSize: 13, fontWeight: 500,
whiteSpace: 'nowrap', background: hex, color: textColorFor(hex), border: `1px solid ${hex}`,
}}>{label}</span>
<NumberInput name={name} value={value} onChange={onChange} min={min} step={step}
onFocus={e => e.target.select()} hideControls style={{flex: 1}}/>
</Group>;
}
export function DriveCalculator() {
const [mode, setMode] = React.useState('pulley');
const [metric, setMetric] = useLocalStorage('drive_calculator_metric', false);
@ -433,20 +448,10 @@ export function DriveCalculator() {
const ratio = driveRatio(firstSize, lastSize);
const outTorque = torqueIn !== '' ? torqueOut(Number(torqueIn), firstSize, lastSize) : null;
const inputProps = {
fluid: true,
type: 'number',
onSelect: e => e.target.select(),
autoComplete: 'off',
};
// Each wheel's inputs use its diagram color so the form and the picture line up.
const coloredField = (hex, labelText, value, onChange, extraProps = {}, name) =>
<Input {...inputProps} {...extraProps} name={name} labelPosition='left' value={value} onChange={onChange}
label={<Label style={{backgroundColor: hex, color: textColorFor(hex), borderColor: hex}}>
{labelText}</Label>}/>;
// Auxiliary (non-solver) numeric input.
const auxInput = (label, value, setter, name) =>
<ColoredInput {...inputProps} name={name} label={label} value={value}
<ColoredInput fluid type='number' onSelect={e => e.target.select()} autoComplete='off'
name={name} label={label} value={value}
onChange={e => setter(e.target.value)}/>;
// Pitch diameter of a wheel given the mode's extra parameter. Pulley size IS the
@ -468,43 +473,47 @@ export function DriveCalculator() {
? surfaceSpeedDisplay(pitchDiameter(Number(speedEl.size)), Number(speedEl.rpm), metric)
: null;
const modeButtons = <Button.Group style={{marginBottom: '1em', flexWrap: 'wrap'}}>
const modeButtons = <ButtonGroup style={{marginBottom: '1em', flexWrap: 'wrap'}}>
{Object.entries(MODES).map(([key, m]) =>
<Button key={key} type='button' icon={m.icon} content={m.button}
primary={mode === key} onClick={() => setMode(key)}/>)}
</Button.Group>;
<Button key={key} type='button' icon={m.icon} role={mode === key ? 'primary' : 'cancel'}
onClick={() => setMode(key)}>{m.button}</Button>)}
</ButtonGroup>;
// One row of inputs per wheel: size, RPM, and a remove button (above the minimum).
const elementRows = elements.map((el, i) => {
const hex = ELEMENT_COLORS[i % ELEMENT_COLORS.length];
const onField = (field) => (e) => {
dispatch({type: 'field', index: i, field, value: e.target.value});
const onField = (field) => (value) => {
dispatch({type: 'field', index: i, field, value});
scheduleSolve();
};
// Teeth are whole numbers; pulley diameters stay continuous.
const onSize = toothed
? (e) => {
dispatch({type: 'field', index: i, field: 'size',
value: e.target.value === '' ? '' : String(Math.round(Math.abs(Number(e.target.value))))});
? (value) => {
dispatch({
type: 'field', index: i, field: 'size',
value: value === '' ? '' : String(Math.round(Math.abs(Number(value)))),
});
scheduleSolve();
}
: onField('size');
return {
hex,
sizeField: coloredField(hex, `#${i + 1} ${sizeLabel}${sizeUnit}`, el.size, onSize,
toothed ? {step: 1, min: 1} : {}, `size-${i}`),
rpmField: coloredField(hex, `#${i + 1} RPM`, el.rpm, onField('rpm'), {}, `rpm-${i}`),
sizeField: <WheelInput hex={hex} label={`#${i + 1} ${sizeLabel}${sizeUnit}`} value={el.size}
onChange={onSize} name={`size-${i}`} min={toothed ? 1 : undefined}
step={toothed ? 1 : undefined}/>,
rpmField: <WheelInput hex={hex} label={`#${i + 1} RPM`} value={el.rpm}
onChange={onField('rpm')} name={`rpm-${i}`}/>,
removeBtn: elements.length > MIN_ELEMENTS
? <Button type='button' basic color='red' icon='close' size='small'
aria-label={`Remove #${i + 1}`} onClick={() => dispatch({type: 'remove', index: i})}/>
? <IconButton type='button' role='danger' icon='close' size='sm'
label={`Remove #${i + 1}`} onClick={() => dispatch({type: 'remove', index: i})}/>
: null,
};
});
const addButton = <Button type='button' icon='plus' primary content={`Add ${button}`}
const addButton = <Button type='button' icon='plus' role='primary'
disabled={elements.length >= MAX_ELEMENTS}
onClick={() => dispatch({type: 'add'})}
style={{marginTop: '0.5em'}}/>;
style={{marginTop: '0.5em'}}>Add {button}</Button>;
// Small colored swatch matching a wheel, used to label its detail rows.
const swatch = (hex) => <span style={{
@ -514,10 +523,10 @@ export function DriveCalculator() {
// Per-wheel pitch-diameter rows (gear/sprocket only).
const pitchDiameterRows = toothed ? elements.map((el, i) =>
<TableRow key={i}>
<TableCell>{swatch(ELEMENT_COLORS[i % ELEMENT_COLORS.length])}#{i + 1} Pitch Diameter</TableCell>
<TableCell>{fmt(pitchDiameter(Number(el.size)), lengthUnit)}</TableCell>
</TableRow>) : null;
<Table.Row key={i}>
<Table.Cell>{swatch(ELEMENT_COLORS[i % ELEMENT_COLORS.length])}#{i + 1} Pitch Diameter</Table.Cell>
<Table.Cell>{fmt(pitchDiameter(Number(el.size)), lengthUnit)}</Table.Cell>
</Table.Row>) : null;
// Pairwise belt/chain length and center distance only make sense for a two-wheel
// drive; with 3+ wheels they depend on the physical layout, so they are omitted.
@ -526,38 +535,38 @@ export function DriveCalculator() {
const belt = twoElements ? beltLength(firstSize, lastSize, Number(centerDistance)) : null;
detailRows = <>
{twoElements && <>
<TableRow>
<TableCell width={6}>Center Distance <InfoPopup content={CENTER_DISTANCE_INFO}/></TableCell>
<TableCell>{auxInput(`Center Distance (${lengthUnit})`, centerDistance, setCenterDistance, "centerDistance")}</TableCell>
</TableRow>
<TableRow>
<TableCell>Belt Length</TableCell>
<TableCell>{fmt(belt, lengthUnit)}</TableCell>
</TableRow>
<Table.Row>
<Table.Cell style={{fontWeight: 600}}>Center Distance <InfoPopup content={CENTER_DISTANCE_INFO}/></Table.Cell>
<Table.Cell>{auxInput(`Center Distance (${lengthUnit})`, centerDistance, setCenterDistance, "centerDistance")}</Table.Cell>
</Table.Row>
<Table.Row>
<Table.Cell style={{fontWeight: 600}}>Belt Length</Table.Cell>
<Table.Cell>{fmt(belt, lengthUnit)}</Table.Cell>
</Table.Row>
</>}
<TableRow>
<TableCell width={6}>Belt Speed</TableCell>
<TableCell>{fmtSpeed(trainSpeed)}</TableCell>
</TableRow>
<Table.Row>
<Table.Cell style={{fontWeight: 600}}>Belt Speed</Table.Cell>
<Table.Cell>{fmtSpeed(trainSpeed)}</Table.Cell>
</Table.Row>
</>;
} else if (mode === 'gear') {
const paramLabel = metric ? 'Module (mm)' : 'Diametral Pitch (1/in)';
const pd1 = pitchDiameter(firstSize), pd2 = pitchDiameter(lastSize);
const cd = twoElements && pd1 > 0 && pd2 > 0 ? centerDistanceFromPitchDiameters(pd1, pd2) : null;
detailRows = <>
<TableRow>
<TableCell width={6}>{paramLabel}</TableCell>
<TableCell>{auxInput(paramLabel, gearTooth, setGearTooth, "gearParam")}</TableCell>
</TableRow>
<Table.Row>
<Table.Cell style={{fontWeight: 600}}>{paramLabel}</Table.Cell>
<Table.Cell>{auxInput(paramLabel, gearTooth, setGearTooth, "gearParam")}</Table.Cell>
</Table.Row>
{pitchDiameterRows}
{twoElements && <TableRow>
<TableCell>Center Distance</TableCell>
<TableCell>{fmt(cd, lengthUnit)}</TableCell>
</TableRow>}
<TableRow>
<TableCell>Pitch-Line Velocity</TableCell>
<TableCell>{fmtSpeed(trainSpeed)}</TableCell>
</TableRow>
{twoElements && <Table.Row>
<Table.Cell style={{fontWeight: 600}}>Center Distance</Table.Cell>
<Table.Cell>{fmt(cd, lengthUnit)}</Table.Cell>
</Table.Row>}
<Table.Row>
<Table.Cell style={{fontWeight: 600}}>Pitch-Line Velocity</Table.Cell>
<Table.Cell>{fmtSpeed(trainSpeed)}</Table.Cell>
</Table.Row>
</>;
} else { // sprocket
const pitch = Number(chainPitch);
@ -565,27 +574,27 @@ export function DriveCalculator() {
? chainLengthPitchesEven(firstSize, lastSize, Number(centerDistance), pitch)
: null;
detailRows = <>
<TableRow>
<TableCell width={6}>Chain Pitch</TableCell>
<TableCell>{auxInput(`Chain Pitch (${lengthUnit})`, chainPitch, setChainPitch, "chainPitch")}</TableCell>
</TableRow>
{twoElements && <TableRow>
<TableCell>Center Distance <InfoPopup content={CENTER_DISTANCE_INFO}/></TableCell>
<TableCell>{auxInput(`Center Distance (${lengthUnit})`, centerDistance, setCenterDistance, "centerDistance")}</TableCell>
</TableRow>}
<Table.Row>
<Table.Cell style={{fontWeight: 600}}>Chain Pitch</Table.Cell>
<Table.Cell>{auxInput(`Chain Pitch (${lengthUnit})`, chainPitch, setChainPitch, "chainPitch")}</Table.Cell>
</Table.Row>
{twoElements && <Table.Row>
<Table.Cell style={{fontWeight: 600}}>Center Distance <InfoPopup content={CENTER_DISTANCE_INFO}/></Table.Cell>
<Table.Cell>{auxInput(`Center Distance (${lengthUnit})`, centerDistance, setCenterDistance, "centerDistance")}</Table.Cell>
</Table.Row>}
{pitchDiameterRows}
{twoElements && <TableRow>
<TableCell>Chain Length</TableCell>
<TableCell>{links === null ? '—' : `${links} pitches`}</TableCell>
</TableRow>}
<TableRow>
<TableCell>Chain Speed</TableCell>
<TableCell>{fmtSpeed(trainSpeed)}</TableCell>
</TableRow>
{twoElements && <Table.Row>
<Table.Cell style={{fontWeight: 600}}>Chain Length</Table.Cell>
<Table.Cell>{links === null ? '—' : `${links} pitches`}</Table.Cell>
</Table.Row>}
<Table.Row>
<Table.Cell style={{fontWeight: 600}}>Chain Speed</Table.Cell>
<Table.Cell>{fmtSpeed(trainSpeed)}</Table.Cell>
</Table.Row>
</>;
}
return <Form>
return <div>
<Header as='h1'>Drive Ratio</Header>
<div style={{marginBottom: '1em'}}>{modeButtons}</div>
@ -605,53 +614,52 @@ export function DriveCalculator() {
</Media>
<Media greaterThanOrEqual='tablet'>
<Grid verticalAlign='middle'>
{elementRows.map(({sizeField, rpmField, removeBtn}, i) =>
<GridRow key={i}>
<GridColumn width={7}>{sizeField}</GridColumn>
<GridColumn width={7}>{rpmField}</GridColumn>
<GridColumn width={2}>{removeBtn}</GridColumn>
</GridRow>)}
</Grid>
{elementRows.map(({sizeField, rpmField, removeBtn}, i) =>
<Grid key={i} align='center'>
<Grid.Col span={5}>{sizeField}</Grid.Col>
<Grid.Col span={5}>{rpmField}</Grid.Col>
<Grid.Col span={2}>{removeBtn}</Grid.Col>
</Grid>)}
</Media>
<div>{addButton}</div>
<Segment style={{textAlign: 'center', overflowX: 'auto'}}>
<Panel style={{textAlign: 'center', overflowX: 'auto'}}>
<DriveDiagram mode={mode} sizes={elements.map(el => el.size)}/>
</Segment>
</Panel>
<Table definition unstackable>
<TableBody>
<TableRow>
<TableCell width={6}>Drive Ratio{' '}
<Table>
<Table.Body>
<Table.Row>
<Table.Cell style={{fontWeight: 600}}>Drive Ratio{' '}
<span style={{fontWeight: 'normal', opacity: 0.7}}>(#1 → #{elements.length})</span>
</TableCell>
<TableCell>{formatRatio(ratio)}</TableCell>
</TableRow>
<TableRow>
<TableCell>Torque Multiplier</TableCell>
<TableCell>{ratio === null ? '—' : `${roundDigits(ratio, 3)}×`}</TableCell>
</TableRow>
<TableRow>
<TableCell>Output Torque <InfoPopup content={TORQUE_INFO}/></TableCell>
<TableCell>
<ColoredInput {...inputProps} name="torqueIn" label={`Input Torque (${torqueUnit})`}
</Table.Cell>
<Table.Cell>{formatRatio(ratio)}</Table.Cell>
</Table.Row>
<Table.Row>
<Table.Cell style={{fontWeight: 600}}>Torque Multiplier</Table.Cell>
<Table.Cell>{ratio === null ? '—' : `${roundDigits(ratio, 3)}×`}</Table.Cell>
</Table.Row>
<Table.Row>
<Table.Cell style={{fontWeight: 600}}>Output Torque <InfoPopup content={TORQUE_INFO}/></Table.Cell>
<Table.Cell>
<ColoredInput fluid type='number' onSelect={e => e.target.select()} autoComplete='off'
name="torqueIn" label={`Input Torque (${torqueUnit})`}
value={torqueIn}
onChange={e => setTorqueIn(e.target.value)}/>
{outTorque !== null && <span style={{marginLeft: '1em'}}>
= <b>{roundDigits(outTorque, 3)} {torqueUnit}</b>
</span>}
</TableCell>
</TableRow>
</TableBody>
</Table.Cell>
</Table.Row>
</Table.Body>
</Table>
<Header as='h3' style={{marginTop: '1em'}}>{button} Details</Header>
<Table definition unstackable>
<TableBody>{detailRows}</TableBody>
<Table>
<Table.Body>{detailRows}</Table.Body>
</Table>
</Form>;
</div>;
}
// Exported for testing

View file

@ -1,23 +1,8 @@
import {InfoPopup, roundDigits, Toggle, useLocalStorage, useLocalStorageInt} from "../Common";
import React, {useState} from "react";
import {Form, Header, Segment, Table} from "../Theme";
import Grid from "semantic-ui-react/dist/commonjs/collections/Grid";
import {
Container,
Dropdown,
GridColumn,
GridRow,
Icon,
Input,
TableBody,
TableCell,
TableHeader,
TableHeaderCell,
TableRow,
} from "semantic-ui-react";
import {Grid, Header, Message, Panel, Select, Stack, Table} from "../ui";
import {ColoredInput} from "../Apps";
import Message from "semantic-ui-react/dist/commonjs/collections/Message";
import {Media, ThemeContext} from "../../contexts/contexts";
import {Media} from "../../contexts/contexts";
const initialState = {
volts: '',
@ -119,7 +104,6 @@ export function OhmsLawCalculator({setVolts}) {
const inputProps = {
fluid: true,
type: 'number',
labelPosition: 'right',
onSelect: e => e.target.select(), // Select the contents of the Input when a user selects it.
autoComplete: 'off',
};
@ -133,43 +117,39 @@ export function OhmsLawCalculator({setVolts}) {
return <div>
<Header as='h1'>Ohm's Law</Header>
<Grid columns={2}>
<GridRow>
<GridColumn>
<ColoredInput {...inputProps}
value={state.volts}
onChange={e => dispatch({type: 'volts', value: e.target.value})}
label='Volts'
color={calculateColor('volts')}
/>
</GridColumn>
<GridColumn>
<ColoredInput {...inputProps}
value={state.amps}
onChange={e => dispatch({type: 'amps', value: e.target.value})}
label='Amps'
color={calculateColor('amps')}
/>
</GridColumn>
</GridRow>
<GridRow>
<GridColumn>
<ColoredInput {...inputProps}
value={state.ohms}
onChange={e => dispatch({type: 'ohms', value: e.target.value})}
label='Ohms'
color={calculateColor('ohms')}
/>
</GridColumn>
<GridColumn>
<ColoredInput {...inputProps}
value={state.watts}
onChange={e => dispatch({type: 'watts', value: e.target.value})}
label='Watts'
color={calculateColor('watts')}
/>
</GridColumn>
</GridRow>
<Grid>
<Grid.Col span={{base: 12, xs: 6}}>
<ColoredInput {...inputProps}
value={state.volts}
onChange={e => dispatch({type: 'volts', value: e.target.value})}
label='Volts'
color={calculateColor('volts')}
/>
</Grid.Col>
<Grid.Col span={{base: 12, xs: 6}}>
<ColoredInput {...inputProps}
value={state.amps}
onChange={e => dispatch({type: 'amps', value: e.target.value})}
label='Amps'
color={calculateColor('amps')}
/>
</Grid.Col>
<Grid.Col span={{base: 12, xs: 6}}>
<ColoredInput {...inputProps}
value={state.ohms}
onChange={e => dispatch({type: 'ohms', value: e.target.value})}
label='Ohms'
color={calculateColor('ohms')}
/>
</Grid.Col>
<Grid.Col span={{base: 12, xs: 6}}>
<ColoredInput {...inputProps}
value={state.watts}
onChange={e => dispatch({type: 'watts', value: e.target.value})}
label='Watts'
color={calculateColor('watts')}
/>
</Grid.Col>
</Grid>
</div>
}
@ -301,10 +281,10 @@ export const resistancesPerKm = {
// Dropdown options for wire types
const wireTypeOptions = [
{key: 'solid', text: 'Solid Copper', value: 'solid'},
{key: 'stranded', text: 'Stranded Copper', value: 'stranded'},
{key: 'solid_aluminum', text: 'Solid Aluminum', value: 'solid_aluminum'},
{key: 'stranded_aluminum', text: 'Stranded Aluminum', value: 'stranded_aluminum'},
{value: 'solid', label: 'Solid Copper'},
{value: 'stranded', label: 'Stranded Copper'},
{value: 'solid_aluminum', label: 'Solid Aluminum'},
{value: 'stranded_aluminum', label: 'Stranded Aluminum'},
];
// Helper function to calculate power loss
@ -325,18 +305,15 @@ export const calcPowerLossPercent = (isSAE, volts, amps, resistancePerKiloLength
const PowerLossCalculator = ({volts, setVolts, wireType, setWireType, isSAE, setIsSAE, length, setLength}) => {
const [ampsRange] = useState([1, 5, 10, 20, 40, 100]);
const {inverted} = React.useContext(ThemeContext);
const warningBackgroundColor = inverted === 'inverted' ? '#332020' : '#ffbebe';
const resistances = isSAE ? resistancesPerKFeet[wireType]
: resistancesPerKm[wireType];
const voltsInput = <Input fluid
const voltsInput = <ColoredInput fluid
label='Volts'
labelPosition='right'
type='number'
value={volts}
onChange={(e, {value}) => setVolts(parseInt(value))}
onChange={e => setVolts(parseInt(e.target.value))}
autoComplete="off"
/>;
@ -346,91 +323,79 @@ const PowerLossCalculator = ({volts, setVolts, wireType, setWireType, isSAE, set
onChange={() => setIsSAE(!isSAE)}
/>;
const lengthInput = <Grid columns={2}>
<Grid.Row>
<Grid.Column mobile={12} tablet={12}>
<Input fluid
label={isSAE ? 'feet' : 'meters'}
labelPosition='right'
type='number'
value={length}
onChange={(e, {value}) => setLength(parseInt(value))}
autoComplete="off"
/>
</Grid.Column>
<Grid.Column mobile={4} tablet={2}>
<InfoPopup
content='Length is one way. This length will be doubled to account for return wire.'/>
</Grid.Column>
</Grid.Row>
const lengthInput = <Grid>
<Grid.Col span={10}>
<ColoredInput fluid
label={isSAE ? 'feet' : 'meters'}
labelPosition='right'
type='number'
value={length}
onChange={e => setLength(parseInt(e.target.value))}
autoComplete="off"
/>
</Grid.Col>
<Grid.Col span={2}>
<InfoPopup
content='Length is one way. This length will be doubled to account for return wire.'/>
</Grid.Col>
</Grid>;
const wireTypeDropdown = <Dropdown
const wireTypeDropdown = <Select
placeholder='Select Wire Type'
fluid
selection
options={wireTypeOptions}
data={wireTypeOptions}
value={wireType}
onChange={(e, {value}) => setWireType(value)}
onChange={value => setWireType(value)}
/>;
return <Form>
return <div>
<Header as='h1'>Power Loss</Header>
<Media at='mobile'>
<Grid columns={2} divided stackable>
<Grid.Row>
<Grid.Column>{voltsInput}</Grid.Column>
<Grid.Column>{lengthInput}</Grid.Column>
</Grid.Row>
<Grid.Row>
<Grid.Column>{wireTypeDropdown}</Grid.Column>
<Grid.Column>{saeToggle}</Grid.Column>
</Grid.Row>
<Grid>
<Grid.Col span={6}>{voltsInput}</Grid.Col>
<Grid.Col span={6}>{lengthInput}</Grid.Col>
<Grid.Col span={6}>{wireTypeDropdown}</Grid.Col>
<Grid.Col span={6}>{saeToggle}</Grid.Col>
</Grid>
</Media>
<Media greaterThan='mobile'>
<Grid columns={2} divided>
<Grid.Row>
<Grid.Column>{voltsInput}</Grid.Column>
<Grid.Column>{saeToggle}</Grid.Column>
</Grid.Row>
<Grid.Row>
<Grid.Column>{lengthInput}</Grid.Column>
<Grid.Column>{wireTypeDropdown}</Grid.Column>
</Grid.Row>
<Grid>
<Grid.Col span={6}>{voltsInput}</Grid.Col>
<Grid.Col span={6}>{saeToggle}</Grid.Col>
<Grid.Col span={6}>{lengthInput}</Grid.Col>
<Grid.Col span={6}>{wireTypeDropdown}</Grid.Col>
</Grid>
</Media>
<Table unstackable compact celled definition>
<TableHeader>
<TableRow>
<TableHeaderCell/>
{ampsRange.map(amp => <TableHeaderCell key={amp}>{amp}A</TableHeaderCell>)}
</TableRow>
</TableHeader>
<TableBody>
<Table>
<Table.Header>
<Table.Row>
<Table.HeaderCell/>
{ampsRange.map(amp => <Table.HeaderCell key={amp}>{amp}A</Table.HeaderCell>)}
</Table.Row>
</Table.Header>
<Table.Body>
{Object.entries(resistances).map(([size, resistence]) => (
<TableRow key={size}>
<TableCell>{size}</TableCell>
<Table.Row key={size}>
<Table.Cell style={{fontWeight: 600}}>{size}</Table.Cell>
{ampsRange.map(amp => {
const lossPercentage = calcPowerLossPercent(isSAE, volts, amp, resistence, length);
const style = lossPercentage > 2 ? {backgroundColor: warningBackgroundColor} : null;
return <TableCell key={`${size}-${amp}`} style={style}>
// The warning tint blends the amber token into the panel background, so
// it stays a token-driven color in every theme rather than a fixed hex.
const style = lossPercentage > 2
? {backgroundColor: 'color-mix(in srgb, var(--amber) 30%, var(--panel))'}
: null;
return <Table.Cell key={`${size}-${amp}`} style={style}>
{lossPercentage >= 100 ? '-' : roundDigits(lossPercentage, 1) + '%'}
</TableCell>
</Table.Cell>
})}
</TableRow>
</Table.Row>
))}
</TableBody>
</Table.Body>
</Table>
<Message icon color='yellow'>
<Icon name='exclamation'/>
<Message.Content>
<Message.Header>Warning</Message.Header>
These numbers are only an estimate and are only applicable for bare wires.
</Message.Content>
<Message kind='warning' icon='warning' title='Warning'>
These numbers are only an estimate and are only applicable for bare wires.
</Message>
</Form>
</div>
};
// Resistance changes with temperature; the resistance tables are referenced at 20°C.
@ -479,7 +444,7 @@ const FourWireKelvinCalculator = ({wireType, isSAE, length}) => {
setTemperatureC(isSAE ? (temperature - 32) * 5 / 9 : temperature);
};
return <Form>
return <div>
<Header as='h1'>4-Wire Kelvin</Header>
<p>
Expected millivolt drop across {length} {isSAE ? 'feet' : 'meters'} of wire when driving a known
@ -488,48 +453,46 @@ const FourWireKelvinCalculator = ({wireType, isSAE, length}) => {
content='Uses the length and wire type from the Power Loss calculator above. The length is NOT doubled because the sense leads measure across a single conductor.'/>
</p>
<Grid columns={2}>
<Grid.Row>
<Grid.Column mobile={12} tablet={12}>
<Input fluid
label={isSAE ? '°F' : '°C'}
labelPosition='right'
type='number'
value={displayTemperature}
onChange={(e, {value}) => handleTemperatureChange(value)}
autoComplete="off"
/>
</Grid.Column>
<Grid.Column mobile={4} tablet={2}>
<InfoPopup
content='Wire temperature. Resistances are referenced at 20°C (68°F) and corrected using the temperature coefficient of the wire material (copper 0.393% per °C, aluminum 0.403% per °C).'/>
</Grid.Column>
</Grid.Row>
<Grid>
<Grid.Col span={10}>
<ColoredInput fluid
label={isSAE ? '°F' : '°C'}
labelPosition='right'
type='number'
value={displayTemperature}
onChange={e => handleTemperatureChange(e.target.value)}
autoComplete="off"
/>
</Grid.Col>
<Grid.Col span={2}>
<InfoPopup
content='Wire temperature. Resistances are referenced at 20°C (68°F) and corrected using the temperature coefficient of the wire material (copper 0.393% per °C, aluminum 0.403% per °C).'/>
</Grid.Col>
</Grid>
<Table unstackable compact celled definition>
<TableHeader>
<TableRow>
<TableHeaderCell/>
{ampsRange.map(amp => <TableHeaderCell key={amp}>{amp}A</TableHeaderCell>)}
</TableRow>
</TableHeader>
<TableBody>
<Table>
<Table.Header>
<Table.Row>
<Table.HeaderCell/>
{ampsRange.map(amp => <Table.HeaderCell key={amp}>{amp}A</Table.HeaderCell>)}
</Table.Row>
</Table.Header>
<Table.Body>
{Object.entries(resistances).map(([size, resistance]) => (
<TableRow key={size}>
<TableCell>{size}</TableCell>
<Table.Row key={size}>
<Table.Cell style={{fontWeight: 600}}>{size}</Table.Cell>
{ampsRange.map(amp => {
const milliVolts = calcKelvinMilliVoltDrop(
amp, resistance, length, temperatureC, tempCoefficientForWireType(wireType));
return <TableCell key={`${size}-${amp}`}>
return <Table.Cell key={`${size}-${amp}`}>
{roundDigits(milliVolts, 1)} mV
</TableCell>
</Table.Cell>
})}
</TableRow>
</Table.Row>
))}
</TableBody>
</Table.Body>
</Table>
</Form>
</div>
};
export const ElectricalCalculators = () => {
@ -537,12 +500,12 @@ export const ElectricalCalculators = () => {
const [wireType, setWireType] = useLocalStorage('calculators.power_loss.wire_type', 'solid');
const [isSAE, setIsSAE] = useLocalStorage('calculators.power_loss.is_sae', true);
const [length, setLength] = useLocalStorageInt('calculators.power_loss.length', 100);
return <Container>
<Segment><OhmsLawCalculator setVolts={setVolts}/></Segment>
<Segment><PowerLossCalculator volts={volts} setVolts={setVolts}
return <Stack>
<Panel><OhmsLawCalculator setVolts={setVolts}/></Panel>
<Panel><PowerLossCalculator volts={volts} setVolts={setVolts}
wireType={wireType} setWireType={setWireType}
isSAE={isSAE} setIsSAE={setIsSAE}
length={length} setLength={setLength}/></Segment>
<Segment><FourWireKelvinCalculator wireType={wireType} isSAE={isSAE} length={length}/></Segment>
</Container>
length={length} setLength={setLength}/></Panel>
<Panel><FourWireKelvinCalculator wireType={wireType} isSAE={isSAE} length={length}/></Panel>
</Stack>
}

View file

@ -1,9 +1,7 @@
import React from "react";
import {GridColumn, Input, Label, TableBody, TableCell, TableFooter, TableHeader, TableHeaderCell, TableRow} from "semantic-ui-react";
import Grid from "semantic-ui-react/dist/commonjs/collections/Grid";
import {Form, Header, Segment, Table} from "../Theme";
import {InfoPopup, roundDigits, Toggle, useLocalStorage} from "../Common";
import {ThemeContext} from "../../contexts/contexts";
import {Grid, Header, Panel, Table, TextInput, Toggle} from "../ui";
import {ColoredInput} from "../Apps";
import {InfoPopup, roundDigits, useLocalStorage} from "../Common";
// Generic food-storage planner: given a household, estimate how much of each food category to store for a chosen
// duration. Independent of any inventory (like the Water calculator). Defaults are a common one-year-per-adult
@ -97,19 +95,14 @@ const SHARES_INFO = 'Each person\'s share of one adult man\'s ration. Defaults f
+ 'Americans 2020-2025 moderate-activity calorie needs (man ~2,600, woman ~2,000, child ~1,800 kcal/day) — '
+ 'food storage scales with calories. Children vary widely by age, so adjust as needed.';
// Category colors are theme tokens (not hex) so the tags stay legible — and become outlines instead of fills — in
// night mode.
const PEOPLE_META = [
{key: 'men', label: 'Men', color: '#4477aa'},
{key: 'women', label: 'Women', color: '#aa3377'},
{key: 'children', label: 'Children', color: '#228833'},
{key: 'men', label: 'Men', color: 'blue'},
{key: 'women', label: 'Women', color: 'pink'},
{key: 'children', label: 'Children', color: 'green'},
];
function textColorFor(hex) {
const r = parseInt(hex.slice(1, 3), 16);
const g = parseInt(hex.slice(3, 5), 16);
const b = parseInt(hex.slice(5, 7), 16);
return (0.299 * r + 0.587 * g + 0.114 * b) / 255 > 0.6 ? '#000000' : '#ffffff';
}
function fmt(value, unit) {
return Number.isFinite(value) && value > 0 ? `${roundDigits(value, 1)} ${unit}` : '—';
}
@ -120,7 +113,6 @@ export function FoodStorageCalculator() {
const [monthsIndex, setMonthsIndex] = useLocalStorage('food_storage_months_index', MONTH_STOPS.indexOf(12));
const [amounts, setAmounts] = useLocalStorage('food_storage_amounts', DEFAULT_AMOUNTS);
const [metric, setMetric] = useLocalStorage('food_storage_metric', false);
const {t} = React.useContext(ThemeContext);
const unit = metric ? 'kg' : 'lb';
// Convert the editable amounts when switching units so the user keeps their numbers.
@ -135,18 +127,13 @@ export function FoodStorageCalculator() {
const inputProps = {fluid: true, type: 'number', min: 0, onSelect: e => e.target.select(), autoComplete: 'off'};
const labelStyle = (color) =>
({backgroundColor: color, color: textColorFor(color), borderColor: color});
const countInput = ({key, label, color}) =>
<Input {...inputProps} step={1} name={`count-${key}`} labelPosition='left' value={counts[key]}
onChange={e => setCounts({...counts, [key]: e.target.value})}
label={<Label style={labelStyle(color)}>{label}</Label>}/>;
<ColoredInput {...inputProps} step={1} name={`count-${key}`} label={label} color={color}
value={counts[key]} onChange={e => setCounts({...counts, [key]: e.target.value})}/>;
const shareInput = ({key, label, color}) =>
<Input {...inputProps} step={1} name={`share-${key}`} labelPosition='left' value={shares[key]}
onChange={e => setShares({...shares, [key]: e.target.value})}
label={<Label style={labelStyle(color)}>{label}</Label>}/>;
<ColoredInput {...inputProps} step={1} name={`share-${key}`} label={label} color={color}
value={shares[key]} onChange={e => setShares({...shares, [key]: e.target.value})}/>;
const rows = FOOD_CATEGORIES.map(c => {
const perYear = amounts[c.key] ?? '';
@ -155,26 +142,26 @@ export function FoodStorageCalculator() {
});
const grandTotal = rows.reduce((s, r) => s + r.total, 0);
return <Form>
return <div>
<Header as='h1'>Food Storage</Header>
<p {...t}>Estimate how much food to store for your household over time.</p>
<p>Estimate how much food to store for your household over time.</p>
<div style={{marginBottom: '1em'}}>
<Toggle label={metric ? 'Metric (kg)' : 'Imperial (lb)'} checked={metric} onChange={toggleMetric}/>
</div>
<Header as='h3'>People</Header>
<Grid stackable columns={3}>
{PEOPLE_META.map(meta => <GridColumn key={meta.key}>{countInput(meta)}</GridColumn>)}
<Grid>
{PEOPLE_META.map(meta => <Grid.Col key={meta.key} span={{base: 12, sm: 4}}>{countInput(meta)}</Grid.Col>)}
</Grid>
<Header as='h4' style={{marginTop: '1em', marginBottom: '0.5em'}}>
Ration share (% of an adult man) <InfoPopup content={SHARES_INFO}/>
</Header>
<Grid stackable columns={3}>
{PEOPLE_META.map(meta => <GridColumn key={meta.key}>{shareInput(meta)}</GridColumn>)}
<Grid>
{PEOPLE_META.map(meta => <Grid.Col key={meta.key} span={{base: 12, sm: 4}}>{shareInput(meta)}</Grid.Col>)}
</Grid>
<p {...t} style={{...t.style, marginTop: '0.5em', opacity: 0.8}}>
<p style={{marginTop: '0.5em', opacity: 0.8}}>
≈ {roundDigits(equivalents, 2)} adult-equivalent{equivalents === 1 ? '' : 's'}
</p>
@ -183,40 +170,40 @@ export function FoodStorageCalculator() {
<input type='range' min={0} max={MONTH_STOPS.length - 1} step={1} value={monthStop}
aria-label='Duration' onChange={e => setMonthsIndex(Number(e.target.value))}
style={{width: '100%'}}/>
<Header as='h2' textAlign='center' style={{marginTop: '0.25em'}}>{formatMonths(months)}</Header>
<Header as='h2' style={{marginTop: '0.25em', textAlign: 'center'}}>{formatMonths(months)}</Header>
</div>
<Header as='h3' style={{marginTop: '1em'}}>
Amounts ({unit} per person per year) <InfoPopup content={CATEGORY_INFO}/>
</Header>
<Segment>
<Table unstackable>
<TableHeader>
<TableRow>
<TableHeaderCell width={7}>Category</TableHeaderCell>
<TableHeaderCell width={5}>{unit === 'kg' ? 'Kg' : 'Lbs'} / person / year</TableHeaderCell>
<TableHeaderCell width={4}>Total needed</TableHeaderCell>
</TableRow>
</TableHeader>
<TableBody>
{rows.map(r => <TableRow key={r.key}>
<TableCell>{r.label}</TableCell>
<TableCell>
<Input fluid type='number' min={0} value={r.perYear}
aria-label={`${r.label} per person per year`}
onChange={e => setAmounts({...amounts, [r.key]: e.target.value})}/>
</TableCell>
<TableCell>{fmt(r.total, unit)}</TableCell>
</TableRow>)}
</TableBody>
<TableFooter>
<TableRow>
<TableHeaderCell>Total</TableHeaderCell>
<TableHeaderCell/>
<TableHeaderCell>{fmt(grandTotal, unit)}</TableHeaderCell>
</TableRow>
</TableFooter>
<Panel>
<Table>
<Table.Header>
<Table.Row>
<Table.HeaderCell>Category</Table.HeaderCell>
<Table.HeaderCell>{unit === 'kg' ? 'Kg' : 'Lbs'} / person / year</Table.HeaderCell>
<Table.HeaderCell>Total needed</Table.HeaderCell>
</Table.Row>
</Table.Header>
<Table.Body>
{rows.map(r => <Table.Row key={r.key}>
<Table.Cell>{r.label}</Table.Cell>
<Table.Cell>
<TextInput type='number' min={0} value={r.perYear} style={{width: '100%'}}
aria-label={`${r.label} per person per year`}
onChange={e => setAmounts({...amounts, [r.key]: e.target.value})}/>
</Table.Cell>
<Table.Cell>{fmt(r.total, unit)}</Table.Cell>
</Table.Row>)}
</Table.Body>
<Table.Footer>
<Table.Row>
<Table.HeaderCell>Total</Table.HeaderCell>
<Table.HeaderCell/>
<Table.HeaderCell>{fmt(grandTotal, unit)}</Table.HeaderCell>
</Table.Row>
</Table.Footer>
</Table>
</Segment>
</Form>;
</Panel>
</div>;
}

View file

@ -1,9 +1,7 @@
import React from "react";
import {TableBody, TableCell, TableHeader, TableHeaderCell, TableRow} from "semantic-ui-react";
import {Header, Table} from "../Theme";
import Grid from "semantic-ui-react/dist/commonjs/collections/Grid";
import {roundDigits} from "../Common";
import {Grid, Header, Table} from "../ui";
import {ColoredInput} from "../Apps";
import {roundDigits} from "../Common";
// ---------------------------------------------------------------------------
// Pure antenna math
@ -212,9 +210,10 @@ export function DipoleAntennaCalculator() {
setMhzInputValue(storageMhzValue);
}
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
const handleMhzChange = (e, {value}) => {
const handleMhzChange = (value) => {
setMhzInputValue(value);
const parsed = parseFloat(value);
// Require a finite positive frequency so overflow (e.g. 1e999 → Infinity) does not stick.
@ -222,7 +221,7 @@ export function DipoleAntennaCalculator() {
localStorage.setItem(mhzStorageKey, value);
}
const handleWaveChange = (e, {value}) => {
const handleWaveChange = (value) => {
setWaveInputValue(value);
const parsed = parseFloat(value);
if (value && Number.isFinite(parsed) && parsed > 0) {
@ -257,76 +256,74 @@ export function DipoleAntennaCalculator() {
return <>
<Header as='h2'>Dipole Antenna</Header>
<Grid columns={2}>
<Grid.Row>
<Grid.Column>
<ColoredInput fluid
label='MHz'
labelPosition='right'
value={mhzInputValue}
onChange={handleMhzChange}
onSelect={e => handleClick(e, 'mhz')}
color={mhzSelected ? null : 'grey'}
/>
</Grid.Column>
<Grid.Column>
<ColoredInput fluid
label='Wavelength'
labelPosition='right'
value={waveInputValue}
onChange={handleWaveChange}
onSelect={e => handleClick(e, 'wave')}
color={mhzSelected ? 'grey' : null}
/>
</Grid.Column>
</Grid.Row>
<Grid>
<Grid.Col span={{base: 12, sm: 6}}>
<ColoredInput fluid
label='MHz'
labelPosition='right'
value={mhzInputValue}
onChange={e => handleMhzChange(e.target.value)}
onSelect={e => handleClick(e, 'mhz')}
color={mhzSelected ? null : 'grey'}
/>
</Grid.Col>
<Grid.Col span={{base: 12, sm: 6}}>
<ColoredInput fluid
label='Wavelength'
labelPosition='right'
value={waveInputValue}
onChange={e => handleWaveChange(e.target.value)}
onSelect={e => handleClick(e, 'wave')}
color={mhzSelected ? 'grey' : null}
/>
</Grid.Col>
</Grid>
{ANTENNA_FRACTIONS.map(i => {
const [feet_, inches_] = convertFeetToFeetAndInches(feet * i.multiplier);
const [half_feet, half_inches] = convertFeetToFeetAndInches(feet * i.multiplier / 2);
return <Table key={i.name} size='large' striped unstackable>
<TableHeader>
<TableRow>
<TableHeaderCell>{i.name}</TableHeaderCell>
<TableHeaderCell>Leg Length</TableHeaderCell>
</TableRow>
</TableHeader>
return <Table key={i.name} style={{marginTop: '1em'}}>
<Table.Header>
<Table.Row>
<Table.HeaderCell>{i.name}</Table.HeaderCell>
<Table.HeaderCell>Leg Length</Table.HeaderCell>
</Table.Row>
</Table.Header>
<TableBody>
<TableRow>
<TableCell>
<Table.Body>
<Table.Row>
<Table.Cell>
{feet_} ft. {inches_} in.
</TableCell>
<TableCell>
</Table.Cell>
<Table.Cell>
{half_feet} ft. {half_inches} in.
</TableCell>
</TableRow>
<TableRow>
<TableCell>
</Table.Cell>
</Table.Row>
<Table.Row>
<Table.Cell>
{roundDigits(inches * i.multiplier)} inches
</TableCell>
<TableCell>
</Table.Cell>
<Table.Cell>
{roundDigits(inches * i.multiplier / 2)} inches
</TableCell>
</TableRow>
<TableRow>
<TableCell>
</Table.Cell>
</Table.Row>
<Table.Row>
<Table.Cell>
{roundDigits(meters * i.multiplier)} meters
</TableCell>
<TableCell>
</Table.Cell>
<Table.Cell>
{roundDigits(meters * i.multiplier / 2)} meters
</TableCell>
</TableRow>
<TableRow>
<TableCell>
</Table.Cell>
</Table.Row>
<Table.Row>
<Table.Cell>
{roundDigits(cm * i.multiplier)} cm.
</TableCell>
<TableCell>
</Table.Cell>
<Table.Cell>
{roundDigits(cm * i.multiplier / 2)} cm.
</TableCell>
</TableRow>
</TableBody>
</Table.Cell>
</Table.Row>
</Table.Body>
</Table>
})}
</>

View file

@ -1,5 +1,4 @@
import React, {useContext, useState} from 'react';
import {Checkbox, Divider, Icon, Input, Radio, SegmentGroup} from "semantic-ui-react";
import React, {useState} from 'react';
import {
appendChecksum,
decryptOTP,
@ -12,22 +11,13 @@ import {
validateCharset
} from "../otp";
import {ErrorMessage, SimpleAccordion} from "../Common";
import {ThemeContext} from "../../contexts/contexts";
import {Button, Form, Header, Segment, TextArea} from "../Theme";
import {Button, Checkbox, Divider, Header, Panel, Radio, Stack, Status, Textarea, TextInput} from "../ui";
function Encrypt({chars, checksum}) {
// Encrypt happens live as the user types or pastes. Nothing leaves the browser.
const [otp, setOtp] = useState('');
const [plaintext, setPlaintext] = useState('');
const handleInputChange = (event, {name, value}) => {
if (name === 'otp') {
setOtp(value);
} else {
setPlaintext(value);
}
};
let ciphertext = '';
let error = '';
if (otp && plaintext && chars) {
@ -42,34 +32,34 @@ function Encrypt({chars, checksum}) {
return <>
<Header as='h2'>Encrypt</Header>
<SegmentGroup>
<Segment>
<Stack gap='sm'>
<Panel>
<h3>Key</h3>
<TextArea
<Textarea
name='otp'
className='otp'
style={{width: '100%'}}
value={otp}
onChange={handleInputChange}
onChange={e => setOtp(e.currentTarget.value)}
placeholder='The random letters from your One-Time Pad'
/>
</Segment>
<Segment>
</Panel>
<Panel>
<h3>Plaintext</h3>
<TextArea
<Textarea
name='plaintext'
className='otp'
style={{width: '100%'}}
value={plaintext}
onChange={handleInputChange}
onChange={e => setPlaintext(e.currentTarget.value)}
placeholder='The message you want to send'
/>
</Segment>
<Segment>
</Panel>
<Panel>
<h3>Ciphertext</h3>
{error
? <ErrorMessage>{error}</ErrorMessage>
: <pre>{ciphertext || (chars ? 'Enter your message above' : 'Set valid characters in Advanced options')}</pre>}
</Segment>
</SegmentGroup>
</Panel>
</Stack>
</>
}
@ -78,14 +68,6 @@ function Decrypt({chars, checksum}) {
const [otp, setOtp] = useState('');
const [ciphertext, setCiphertext] = useState('');
const handleInputChange = (event, {name, value}) => {
if (name === 'otp') {
setOtp(value);
} else {
setCiphertext(value);
}
};
let plaintext = '';
let error = '';
let checksumValid = null; // null = not applicable (checksum off or nothing to check)
@ -107,44 +89,42 @@ function Decrypt({chars, checksum}) {
return <>
<Header as='h2'>Decrypt</Header>
<SegmentGroup>
<Segment>
<Stack gap='sm'>
<Panel>
<h3>Key</h3>
<TextArea
<Textarea
name='otp'
className='otp'
style={{width: '100%'}}
value={otp}
onChange={handleInputChange}
onChange={e => setOtp(e.currentTarget.value)}
placeholder='The random letters from your One-Time Pad'
/>
</Segment>
<Segment>
</Panel>
<Panel>
<h3>Ciphertext</h3>
<TextArea
<Textarea
name='ciphertext'
className='otp'
style={{width: '100%'}}
value={ciphertext}
onChange={handleInputChange}
onChange={e => setCiphertext(e.currentTarget.value)}
placeholder='The message you received'
/>
</Segment>
<Segment>
</Panel>
<Panel>
<h3>Plaintext</h3>
{checksumValid !== null && <p>
<Icon name={checksumValid ? 'check' : 'times'} color={checksumValid ? 'green' : 'red'}/>
{checksumValid ? 'Checksum is valid' : 'Checksum is invalid'}
</p>}
{checksumValid !== null &&
<Status kind={checksumValid ? 'complete' : 'failed'}>
{checksumValid ? 'Checksum is valid' : 'Checksum is invalid'}
</Status>}
{error
? <ErrorMessage>{error}</ErrorMessage>
: <pre>{plaintext || (chars ? 'Enter the encrypted message above' : 'Set valid characters in Advanced options')}</pre>}
</Segment>
</SegmentGroup>
</Panel>
</Stack>
</>
}
export function OneTimePadCalculator() {
const {t} = useContext(ThemeContext);
// The character set is a property of the pad: encrypt, decrypt, and generation all use the same alphabet.
const [charsetKind, setCharsetKind] = useState('alphanumeric'); // 'alpha' | 'alphanumeric' | 'custom'
const [customChars, setCustomChars] = useState('');
@ -174,32 +154,28 @@ export function OneTimePadCalculator() {
<Header as='h1'>One-Time Pad</Header>
<Header as='h4'>One-Time Pads can be used to encrypt your communications. This can be done by hand
(yes, really) or in this app.</Header>
<p {...t}>These messages are never stored and cannot be retrieved.</p>
<Button color='violet' disabled={!activeChars} onClick={handleGenerateNewPad}>Generate New Pad</Button>
<Button secondary href={cheatSheetURL}>Cheat Sheet PDF</Button>
<p>These messages are never stored and cannot be retrieved.</p>
<Button color='violet' disabled={!activeChars} onClick={handleGenerateNewPad}>
Generate New Pad
</Button>
<Button role='cancel' component='a' href={cheatSheetURL}>Cheat Sheet PDF</Button>
<SimpleAccordion title='Advanced'>
<Header as='h4'>Pad characters</Header>
<Form>
<Form.Field>
<Radio label='A–Z' name='charset' value='alpha'
checked={charsetKind === 'alpha'} onChange={() => setCharsetKind('alpha')}/>
</Form.Field>
<Form.Field>
<Radio label='A–Z and 0–9' name='charset' value='alphanumeric'
checked={charsetKind === 'alphanumeric'} onChange={() => setCharsetKind('alphanumeric')}/>
</Form.Field>
<Form.Field>
<Radio label='Custom' name='charset' value='custom'
checked={charsetKind === 'custom'} onChange={() => setCharsetKind('custom')}/>
</Form.Field>
</Form>
<Stack gap={4}>
<Radio label='A–Z' name='charset' value='alpha'
checked={charsetKind === 'alpha'} onChange={() => setCharsetKind('alpha')}/>
<Radio label='A–Z and 0–9' name='charset' value='alphanumeric'
checked={charsetKind === 'alphanumeric'} onChange={() => setCharsetKind('alphanumeric')}/>
<Radio label='Custom' name='charset' value='custom'
checked={charsetKind === 'custom'} onChange={() => setCharsetKind('custom')}/>
</Stack>
{charsetKind === 'custom' && <>
<Input
fluid
<TextInput
style={{width: '100%'}}
value={customChars}
placeholder='e.g. ABCDEF0123'
onChange={(e, {value}) => setCustomChars(value)}
onChange={e => setCustomChars(e.currentTarget.value)}
/>
{charsetError && <ErrorMessage>{charsetError}</ErrorMessage>}
</>}

View file

@ -1,5 +1,4 @@
import {Dropdown, MessageHeader, TableBody, TableCell, TableRow} from "semantic-ui-react";
import {Form, Header, Table} from "../Theme";
import {Group, Header, Label, NumberInput, Select, Table} from "../ui";
import React from "react";
import {HandPointMessage, roundDigits, useLocalStorage} from "../Common";
import {createUnit, multiply, unit} from "mathjs";
@ -91,65 +90,65 @@ function ratioReducer(prevState, e) {
const baseToUnitsMap = {
'length': [
{key: 'centimeter', value: 'centimeter', text: 'centimeter'},
{key: 'feet', value: 'feet', text: 'feet'},
{key: 'inch', value: 'inch', text: 'inch'},
{key: 'kilometer', value: 'kilometer', text: 'kilometer'},
{key: 'meter', value: 'meter', text: 'meter'},
{key: 'mile', value: 'mile', text: 'mile'},
{value: 'centimeter', text: 'centimeter'},
{value: 'feet', text: 'feet'},
{value: 'inch', text: 'inch'},
{value: 'kilometer', text: 'kilometer'},
{value: 'meter', text: 'meter'},
{value: 'mile', text: 'mile'},
],
'area': [
{key: 'm2', value: 'm2', text: 'm²'},
{key: 'sqin', value: 'sqin', text: 'square inch'},
{key: 'sqyd', value: 'sqyd', text: 'square yard'},
{key: 'sqmi', value: 'sqmi', text: 'square mile'},
{key: 'acre', value: 'acre', text: 'acre'},
{key: 'hectare', value: 'hectare', text: 'hectare'},
{value: 'm2', text: 'm²'},
{value: 'sqin', text: 'square inch'},
{value: 'sqyd', text: 'square yard'},
{value: 'sqmi', text: 'square mile'},
{value: 'acre', text: 'acre'},
{value: 'hectare', text: 'hectare'},
],
'volume': [
{key: 'cc', value: 'cc', text: 'cc'},
{key: 'liter', value: 'liter', text: 'liter'},
{key: 'm3', value: 'm3', text: 'meters³'},
{key: 'cup', value: 'cup', text: 'cup'},
{key: 'fluidounce', value: 'fluidounce', text: 'fl.oz'},
{key: 'gallon', value: 'gallon', text: 'gallon'},
{key: 'quart', value: 'quart', text: 'quart'},
{key: 'milliliter', value: 'milliliter', text: 'ml'},
{key: 'tablespoon', value: 'tablespoon', text: 'tablespoon'},
{key: 'teaspoon', value: 'teaspoon', text: 'teaspoon'},
{key: 'cuin', value: 'cuin', text: 'cuin'},
{value: 'cc', text: 'cc'},
{value: 'liter', text: 'liter'},
{value: 'm3', text: 'meters³'},
{value: 'cup', text: 'cup'},
{value: 'fluidounce', text: 'fl.oz'},
{value: 'gallon', text: 'gallon'},
{value: 'quart', text: 'quart'},
{value: 'milliliter', text: 'ml'},
{value: 'tablespoon', text: 'tablespoon'},
{value: 'teaspoon', text: 'teaspoon'},
{value: 'cuin', text: 'cuin'},
],
'mass': [
{key: 'grain', value: 'grain', text: 'grain'},
{key: 'gram', value: 'gram', text: 'gram'},
{key: 'lbs', value: 'lbs', text: 'pound'},
{key: 'stone', value: 'stone', text: 'stone'},
{key: 'ton', value: 'ton', text: 'ton'},
{value: 'grain', text: 'grain'},
{value: 'gram', text: 'gram'},
{value: 'lbs', text: 'pound'},
{value: 'stone', text: 'stone'},
{value: 'ton', text: 'ton'},
],
'energy': [
{key: 'joule', value: 'joule', text: 'joule'},
{key: 'Wh', value: 'Wh', text: 'Wh'},
{key: 'BTU', value: 'BTU', text: 'BTU'},
{key: 'watt', value: 'watt', text: 'watt'},
{key: 'hp', value: 'hp', text: 'hp'},
{value: 'joule', text: 'joule'},
{value: 'Wh', text: 'Wh'},
{value: 'BTU', text: 'BTU'},
{value: 'watt', text: 'watt'},
{value: 'hp', text: 'hp'},
],
};
// Used to get from unit like `BTU` back to the base `energy`.
let unitsToBaseMap = {};
for (const [base, units] of Object.entries(baseToUnitsMap)) {
for (const {key} of units) {
unitsToBaseMap[key] = base;
for (const {value} of units) {
unitsToBaseMap[value] = base;
}
}
const defaultUnits = {
// These will be replaced using local storage.
length: baseToUnitsMap.length[0]['key'], // centimeter
area: baseToUnitsMap.area[0]['key'], // m2
volume: baseToUnitsMap.volume[0]['key'], // cc
mass: baseToUnitsMap.mass[0]['key'], // grain
energy: baseToUnitsMap.energy[0]['key'], // joule
length: baseToUnitsMap.length[0]['value'], // centimeter
area: baseToUnitsMap.area[0]['value'], // m2
volume: baseToUnitsMap.volume[0]['value'], // cc
mass: baseToUnitsMap.mass[0]['value'], // grain
energy: baseToUnitsMap.energy[0]['value'], // joule
[null]: null, // nullUnit
};
@ -175,37 +174,40 @@ const unitToInputValue = (u) => {
return roundDigits(num, 3)
}
// "None" is represented by an empty string in the Select (which needs a string value);
// the reducer still receives/produces `null` for the base, same as before migration.
const baseOptions = [
{key: null, value: null, text: 'None'},
{key: 'length', value: 'length', label: 'meter, feet, inch, etc.', text: 'Length'},
{key: 'area', value: 'area', label: 'inch², m², etc.', text: 'Area'},
{key: 'volume', value: 'volume', label: 'liter, m³, cup, etc.', text: 'Volume'},
{key: 'mass', value: 'mass', label: 'gram, pound, etc.', text: 'Mass'},
{key: 'energy', value: 'energy', label: 'joule, watt, etc.', text: 'Energy'},
{value: '', label: 'None'},
{value: 'length', label: 'Length — meter, feet, inch, etc.'},
{value: 'area', label: 'Area — inch², m², etc.'},
{value: 'volume', label: 'Volume — liter, m³, cup, etc.'},
{value: 'mass', label: 'Mass — gram, pound, etc.'},
{value: 'energy', label: 'Energy — joule, watt, etc.'},
];
const RatioInput = React.forwardRef(({name, label, value, unitValue, unitName, unitOptions, color, dispatch, onKeyDown}, ref) => (
<div className="ui fluid labeled input" style={{marginBottom: '0.25em'}}>
<div className={`ui label ${color}`}>{label}</div>
<input
<Group gap={0} wrap='nowrap' align='stretch' style={{marginBottom: '0.25em'}}>
<Label color={color || 'grey'}>{label}</Label>
<NumberInput
id={name}
name={name}
type="number"
ref={ref}
value={unitToInputValue(value)}
onChange={e => dispatch(e)}
onChange={val => dispatch({name, value: val})}
onKeyDown={onKeyDown}
onFocus={e => e.target.select()}
hideControls
style={{flex: 1}}
/>
{unitOptions &&
<Dropdown
options={unitOptions}
className='label'
onChange={(_, data) => dispatch(data)}
<Select
data={unitOptions.map(o => ({value: o.value, label: o.text}))}
onChange={val => dispatch({name: unitName, value: val})}
name={unitName}
value={unitValue}
style={{minWidth: 150}}
/>}
</div>
</Group>
));
const RatioCalculator = () => {
@ -239,16 +241,17 @@ const RatioCalculator = () => {
const unitOptions = baseToUnitsMap[state.base];
const getColor = (name) => state.lastUpdated.includes(name) ? '' : 'grey';
// Recently-updated inputs (the ones the user is actively typing) are highlighted;
// the others read as inactive/grey.
const getColor = (name) => state.lastUpdated.includes(name) ? 'blue' : 'grey';
const baseDropdown = <Dropdown selection
fluid
placeholder='Base Units'
options={baseOptions}
value={state.base}
name='base'
onChange={(_, data) => dispatch(data)}
style={{marginBottom: '1em'}}
const baseDropdown = <Select
placeholder='Base Units'
data={baseOptions}
value={state.base ?? ''}
name='base'
onChange={val => dispatch({name: 'base', value: val || null})}
style={{marginBottom: '1em'}}
/>;
const handleInputChange = (e) => {
@ -318,7 +321,7 @@ const RatioCalculator = () => {
}
}, []);
return <Form>
return <div>
<Header as='h1'>Ratio</Header>
<Header as='h2'>A : B = C : D</Header>
@ -335,37 +338,36 @@ const RatioCalculator = () => {
</Media>
<Media greaterThanOrEqual='tablet'>
<Table unstackable className='ratio-table'>
<TableBody>
<TableRow>
<TableCell className='equal-width'>{inputA}</TableCell>
<TableCell className='min-width'/>
<TableCell className='equal-width'>{inputC}</TableCell>
</TableRow>
<TableRow>
<TableCell className='equal-width'>
<Table className='ratio-table'>
<Table.Body>
<Table.Row>
<Table.Cell className='equal-width'>{inputA}</Table.Cell>
<Table.Cell className='min-width'/>
<Table.Cell className='equal-width'>{inputC}</Table.Cell>
</Table.Row>
<Table.Row>
<Table.Cell className='equal-width'>
<hr/>
</TableCell>
<TableCell textAlign='center' className='min-width'>
</Table.Cell>
<Table.Cell style={{textAlign: 'center'}} className='min-width'>
<Header as='h1'>=</Header>
</TableCell>
<TableCell className='equal-width'>
</Table.Cell>
<Table.Cell className='equal-width'>
<hr/>
</TableCell>
</TableRow>
<TableRow>
<TableCell className='equal-width'>{inputB}</TableCell>
<TableCell className='min-width'/>
<TableCell className='equal-width'>{inputD}</TableCell>
</TableRow>
</TableBody>
</Table.Cell>
</Table.Row>
<Table.Row>
<Table.Cell className='equal-width'>{inputB}</Table.Cell>
<Table.Cell className='min-width'/>
<Table.Cell className='equal-width'>{inputD}</Table.Cell>
</Table.Row>
</Table.Body>
</Table>
</Media>
<HandPointMessage storageName='hint_ratio_calculator'>
<MessageHeader>Tip</MessageHeader>
You can change inputs using the <b>a</b>, <b>b</b>, <b>c</b>, and <b>d</b> keys.
<strong>Tip</strong> You can change inputs using the <b>a</b>, <b>b</b>, <b>c</b>, and <b>d</b> keys.
</HandPointMessage>
</Form>
</div>
}
export const RatioCalculators = () => {

View file

@ -1,12 +1,10 @@
import React from "react";
import {GridColumn, Input, Label, TableBody, TableCell, TableHeader, TableHeaderCell, TableRow} from "semantic-ui-react";
import Grid from "semantic-ui-react/dist/commonjs/collections/Grid";
import {Button, Form, Header, Icon, Table} from "../Theme";
import {Button, Grid, Header, Table} from "../ui";
import {ColoredInput} from "../Apps";
import {InfoPopup, roundDigits, useLocalStorage} from "../Common";
import {formatDuration} from "./WaterCalculator";
import {findNameKey, planSupplyPurchase} from "../inventory/summarize";
import {downloadCSV, inventoryExportFilename, shoppingListCSV} from "../inventory/inventoryExport";
import {ThemeContext} from "../../contexts/contexts";
// Field-role detection lives in inventory/summarize.js (single source of truth); re-exported here for back-compat.
export {findCaloriesKey, findCountKey} from "../inventory/summarize";
@ -81,10 +79,12 @@ export const RATION_PRESETS = {
const DEFAULT_PRESET = 'moderate';
// Category colors are theme tokens (not hex) so the tags stay legible — and become outlines instead of fills — in
// night mode.
const CATEGORY_META = [
{key: 'men', label: 'Men', color: '#4477aa'},
{key: 'women', label: 'Women', color: '#aa3377'},
{key: 'children', label: 'Children', color: '#228833'},
{key: 'men', label: 'Men', color: 'blue'},
{key: 'women', label: 'Women', color: 'pink'},
{key: 'children', label: 'Children', color: 'green'},
];
const DEMAND_INFO = 'Per-person daily calorie needs come from the Dietary Guidelines for Americans 2020-2025 '
@ -93,13 +93,6 @@ const DEMAND_INFO = 'Per-person daily calorie needs come from the Dietary Guidel
+ 'The Survival preset is a short-term emergency ration floor, below maintenance. All values are editable — '
+ 'adjust the household and activity level to see how long the stored food lasts.';
function textColorFor(hex) {
const r = parseInt(hex.slice(1, 3), 16);
const g = parseInt(hex.slice(3, 5), 16);
const b = parseInt(hex.slice(5, 7), 16);
return (0.299 * r + 0.587 * g + 0.114 * b) / 255 > 0.6 ? '#000000' : '#ffffff';
}
function fmt(value, unit) {
if (!Number.isFinite(value) || value <= 0) {
return '—';
@ -130,61 +123,55 @@ export function RationEstimatePanel({name, items, fields, caloriesKey, countKey}
const inputProps = {fluid: true, type: 'number', onSelect: e => e.target.select(), autoComplete: 'off'};
const countInput = ({key, label, color}) =>
<Input {...inputProps} min={0} step={1} name={`count-${key}`} labelPosition='left' value={counts[key]}
onChange={e => setCounts({...counts, [key]: e.target.value})}
label={<Label style={{backgroundColor: color, color: textColorFor(color), borderColor: color}}>
{label}</Label>}/>;
<ColoredInput {...inputProps} min={0} step={1} name={`count-${key}`} label={label} color={color}
value={counts[key]} onChange={e => setCounts({...counts, [key]: e.target.value})}/>;
const rateInput = ({key, label, color}) =>
<Input {...inputProps} min={0} step={50} name={`rate-${key}`} labelPosition='left' value={rates[key]}
onChange={e => setRates({...rates, [key]: e.target.value})}
label={<Label style={{backgroundColor: color, color: textColorFor(color), borderColor: color}}>
{label}</Label>}/>;
<ColoredInput {...inputProps} min={0} step={50} name={`rate-${key}`} label={label} color={color}
value={rates[key]} onChange={e => setRates({...rates, [key]: e.target.value})}/>;
return <Form>
return <div>
<Header as='h3'>People</Header>
<Grid stackable columns={3}>
{CATEGORY_META.map(meta => <GridColumn key={meta.key}>{countInput(meta)}</GridColumn>)}
<Grid>
{CATEGORY_META.map(meta =>
<Grid.Col key={meta.key} span={{base: 12, sm: 4}}>{countInput(meta)}</Grid.Col>)}
</Grid>
<Header as='h3' style={{marginTop: '1em'}}>
Daily Calories (per person) <InfoPopup content={DEMAND_INFO}/>
</Header>
<div style={{marginBottom: '1em'}}>
<div style={{marginBottom: '1em', display: 'flex', flexWrap: 'wrap', gap: '0.5em'}}>
{Object.entries(RATION_PRESETS).map(([key, p]) => (
<button key={key} type='button' onClick={() => setPreset(key)} style={{
marginRight: '0.5em', padding: '0.4em 0.8em',
border: preset === key ? '2px solid #2185d0' : '1px solid #ccc',
background: preset === key ? '#e8f4fc' : 'white', borderRadius: '4px', cursor: 'pointer',
}}>
<Button key={key} role={preset === key ? 'primary' : 'cancel'} onClick={() => setPreset(key)}>
<strong>{p.label}</strong> — {p.description}
</button>
</Button>
))}
</div>
<Grid stackable columns={3}>
{CATEGORY_META.map(meta => <GridColumn key={meta.key}>{rateInput(meta)}</GridColumn>)}
<Grid>
{CATEGORY_META.map(meta =>
<Grid.Col key={meta.key} span={{base: 12, sm: 4}}>{rateInput(meta)}</Grid.Col>)}
</Grid>
<Table definition unstackable style={{marginTop: '1em'}}>
<TableBody>
<TableRow>
<TableCell width={6}>Total Stored Calories</TableCell>
<TableCell>{fmt(total, 'kcal')}</TableCell>
</TableRow>
<TableRow>
<TableCell>Daily Demand</TableCell>
<TableCell>{fmt(daily, 'kcal/day')}</TableCell>
</TableRow>
<TableRow>
<TableCell>Food Lasts</TableCell>
<TableCell>{days ? formatDuration(days) : '—'}</TableCell>
</TableRow>
</TableBody>
<Table style={{marginTop: '1em'}}>
<Table.Body>
<Table.Row>
<Table.Cell>Total Stored Calories</Table.Cell>
<Table.Cell>{fmt(total, 'kcal')}</Table.Cell>
</Table.Row>
<Table.Row>
<Table.Cell>Daily Demand</Table.Cell>
<Table.Cell>{fmt(daily, 'kcal/day')}</Table.Cell>
</Table.Row>
<Table.Row>
<Table.Cell>Food Lasts</Table.Cell>
<Table.Cell>{days ? formatDuration(days) : '—'}</Table.Cell>
</Table.Row>
</Table.Body>
</Table>
<SupplyPlan name={name} items={items} fields={fields} caloriesKey={caloriesKey} countKey={countKey}
currentDays={days} total={total} daily={daily}/>
</Form>;
</div>;
}
// Print only the supply-plan shopping list (not the whole-inventory print block): toggle a body class that the
@ -218,7 +205,6 @@ const PLAN_INFO = 'Drag the slider to a target duration longer than your current
* the additional packages to buy to reach it (the inventory scaled up proportionally — see planSupplyPurchase).
*/
function SupplyPlan({name, items, fields, caloriesKey, countKey, currentDays, total, daily}) {
const {t} = React.useContext(ThemeContext);
const nameKey = findNameKey(fields);
const currentMonths = (currentDays || 0) / PLAN_MONTH_DAYS;
@ -252,62 +238,60 @@ function SupplyPlan({name, items, fields, caloriesKey, countKey, currentDays, to
});
const sortDir = (key) => sort.key === key ? (sort.dir === 'asc' ? 'ascending' : 'descending') : undefined;
const headerCell = (key, label) =>
<TableHeaderCell sorted={sortDir(key)} onClick={() => toggleSort(key)} style={{cursor: 'pointer'}}>
{label}
</TableHeaderCell>;
<Table.HeaderCell sorted={sortDir(key)} onSort={() => toggleSort(key)}>{label}</Table.HeaderCell>;
return <div style={{marginTop: '2em'}}>
<Header as='h3'>Plan More Supply <InfoPopup content={PLAN_INFO}/></Header>
{!countKey
? <p {...t}>Add a <strong>Count</strong> field to this inventory to plan purchases.</p>
? <p>Add a <strong>Count</strong> field to this inventory to plan purchases.</p>
: <>
<div style={{padding: '0 0.5em'}}>
<input type='range' min={minMonths} max={maxMonths} step={1} value={targetMonths}
aria-label='Target duration (months)' style={{width: '100%'}}
onChange={e => setTargetMonths(Number(e.target.value))}/>
<Header as='h2' textAlign='center' style={{marginTop: '0.25em'}}>
<Header as='h2' style={{marginTop: '0.25em', textAlign: 'center'}}>
Target: {formatDuration(targetDays)}
</Header>
<p {...t} style={{...t.style, textAlign: 'center', opacity: 0.8}}>
<p style={{textAlign: 'center', opacity: 0.8}}>
Currently {formatDuration(currentDays)}
</p>
</div>
{rows.length === 0
? <p {...t}>Drag the slider above your current estimate to see a shopping list.</p>
? <p>Drag the slider above your current estimate to see a shopping list.</p>
: <>
<Table celled unstackable sortable>
<TableHeader>
<TableRow>
<Table className='shopping-list-table'>
<Table.Header>
<Table.Row>
{headerCell('name', 'Item')}
{headerCell('current', 'Have')}
{headerCell('additional', 'Buy')}
{headerCell('target', 'New Total')}
</TableRow>
</TableHeader>
<TableBody>
{sortedRows.map((r, i) => <TableRow key={`${r.name}-${i}`}>
<TableCell>{r.name}</TableCell>
<TableCell>{r.current}</TableCell>
<TableCell><strong>+{r.additional}</strong></TableCell>
<TableCell>{r.target}</TableCell>
</TableRow>)}
</TableBody>
</Table.Row>
</Table.Header>
<Table.Body>
{sortedRows.map((r, i) => <Table.Row key={`${r.name}-${i}`}>
<Table.Cell>{r.name}</Table.Cell>
<Table.Cell>{r.current}</Table.Cell>
<Table.Cell><strong>+{r.additional}</strong></Table.Cell>
<Table.Cell>{r.target}</Table.Cell>
</Table.Row>)}
</Table.Body>
</Table>
<p {...t}>
<p>
Buy <strong>{totalToBuy.toLocaleString()}</strong> additional package{totalToBuy === 1 ? '' : 's'}
{' '}across <strong>{rows.length}</strong> item{rows.length === 1 ? '' : 's'}
{projectedDays ? <> to reach about <strong>{formatDuration(projectedDays)}</strong> of food.</> : '.'}
</p>
<Button primary
<Button role='primary' icon='download'
onClick={() => downloadCSV(
inventoryExportFilename(`${name || 'inventory'} shopping list`, 'csv'),
shoppingListCSV(sortedRows))}>
<Icon name='download'/> Download CSV
Download CSV
</Button>
<Button onClick={printShoppingList}>
<Icon name='print'/> Print / Save as PDF
<Button icon='print' onClick={printShoppingList}>
Print / Save as PDF
</Button>
{/* Hidden printable block — `printShoppingList` makes this the only thing printed. */}

View file

@ -102,7 +102,7 @@ describe('RationEstimatePanel supply plan', () => {
fireEvent.change(screen.getByLabelText(/target duration/i), {target: {value: '2'}});
// Scope to the on-screen table (the hidden print block duplicates these texts in the DOM).
const plan = within(document.querySelector('table.sortable'));
const plan = within(document.querySelector('table.shopping-list-table'));
expect(plan.getByText('Beans')).toBeTruthy();
expect(plan.getByText('+100')).toBeTruthy();
// Summary line reports the total to buy.
@ -118,13 +118,13 @@ describe('RationEstimatePanel supply plan', () => {
fireEvent.change(screen.getByLabelText(/target duration/i), {target: {value: '2'}});
const itemNames = () =>
[...document.querySelectorAll('table.sortable tbody tr td:first-child')].map(td => td.textContent);
[...document.querySelectorAll('table.shopping-list-table tbody tr td:first-child')].map(td => td.textContent);
// Default sort is largest purchase first (Beans buys far more than Apples).
expect(itemNames()).toEqual(['Beans', 'Apples']);
// Sorting by Item ascending flips to alphabetical (scope to the sortable table; the print block also has an
// "Item" header).
fireEvent.click(within(document.querySelector('table.sortable')).getByText('Item'));
fireEvent.click(within(document.querySelector('table.shopping-list-table')).getByText('Item'));
expect(itemNames()).toEqual(['Apples', 'Beans']);
});

View file

@ -1,7 +1,5 @@
import React from "react";
import {GridColumn, Input, Label, TableBody, TableCell, TableHeader, TableHeaderCell, TableRow} from "semantic-ui-react";
import Grid from "semantic-ui-react/dist/commonjs/collections/Grid";
import {Form, Header, Segment, Table} from "../Theme";
import {Button, Grid, Group, Header, NumberInput, Panel, Table} from "../ui";
import {InfoPopup, roundDigits, Toggle, useLocalStorage} from "../Common";
// Pure calculation functions for the Water Storage calculator.
@ -171,11 +169,13 @@ const DEMAND_INFO = 'Per-person daily water includes drinking plus basic hygiene
+ 'livestock, or other needs not covered by the per-person categories.';
// Per-category colors (Paul Tol bright palette) so the count inputs read at a glance.
// These are diagram/legend colors matched to a fixed visual identity per category —
// not themed UI chrome — so they stay literal hex.
const CATEGORY_META = [
{key: 'men', label: 'Men', icon: 'man', color: '#4477aa'},
{key: 'women', label: 'Women', icon: 'woman', color: '#aa3377'},
{key: 'children', label: 'Children', icon: 'child', color: '#228833'},
{key: 'pregnant', label: 'Pregnant/Nursing', icon: 'heart', color: '#ee6677'},
{key: 'men', label: 'Men', color: '#4477aa'},
{key: 'women', label: 'Women', color: '#aa3377'},
{key: 'children', label: 'Children', color: '#228833'},
{key: 'pregnant', label: 'Pregnant/Nursing', color: '#ee6677'},
];
// Pick black or white label text for legibility on a given background color.
@ -202,7 +202,21 @@ export function clampNonNegative(value) {
if (value === '') {
return '';
}
return value.startsWith('-') ? value.slice(1) : value;
return `${value}`.startsWith('-') ? `${value}`.slice(1) : value;
}
// A labeled numeric input whose label is tinted to match a category's diagram color.
// The color is a literal hex from CATEGORY_META, not a theme token, so this is a small
// local composition rather than the token-driven `Label`.
function SwatchInput({hex, label, value, onChange, name, min, step}) {
return <Group gap={0} wrap='nowrap' align='stretch' style={{marginBottom: '0.25em'}}>
<span style={{
display: 'flex', alignItems: 'center', padding: '0 10px', fontSize: 13, fontWeight: 500,
whiteSpace: 'nowrap', background: hex, color: textColorFor(hex), border: `1px solid ${hex}`,
}}>{label}</span>
<NumberInput name={name} value={value} onChange={onChange} min={min} step={step}
onFocus={e => e.target.select()} hideControls style={{flex: 1}}/>
</Group>;
}
export function WaterCalculator() {
@ -236,69 +250,51 @@ export function WaterCalculator() {
const total = totalWater(daily, days);
const weight = waterWeight(total, metric);
const inputProps = {fluid: true, type: 'number', onSelect: e => e.target.select(), autoComplete: 'off'};
// One count input per category, label colored to match.
const countInput = ({key, label, icon, color}) =>
<Input {...inputProps} min={0} step={1} name={`count-${key}`}
labelPosition='left' value={counts[key]}
onChange={e => setCounts({...counts, [key]: e.target.value === '' ? '' : String(Math.max(0, Math.round(Number(e.target.value))))})}
label={<Label style={{backgroundColor: color, color: textColorFor(color), borderColor: color}}>
<i className={`${icon} icon`} style={{marginRight: '0.4em'}}/>{label}</Label>}/>;
const countInput = ({key, label, color}) =>
<SwatchInput hex={color} label={label} value={counts[key]} min={0} step={1} name={`count-${key}`}
onChange={value => setCounts({
...counts,
[key]: value === '' ? '' : String(Math.max(0, Math.round(Number(value)))),
})}/>;
// One editable rate input per category, sharing the category color.
const rateInput = ({key, label, color}) =>
<Input {...inputProps} min={0} step={0.1} name={`rate-${key}`}
labelPosition='left' value={rates[key]}
onChange={e => setRates({...rates, [key]: clampNonNegative(e.target.value)})}
label={<Label style={{backgroundColor: color, color: textColorFor(color), borderColor: color}}>
{label}</Label>}/>;
<SwatchInput hex={color} label={label} value={rates[key]} min={0} step={0.1} name={`rate-${key}`}
onChange={value => setRates({...rates, [key]: clampNonNegative(value)})}/>;
const presetButtons = (
<div>
{Object.entries(WATER_PRESETS).map(([key, p]) => (
<button
key={key}
type="button"
onClick={() => setPreset(key)}
style={{
marginRight: '0.5em',
padding: '0.4em 0.8em',
border: preset === key ? '2px solid #2185d0' : '1px solid #ccc',
background: preset === key ? '#e8f4fc' : 'white',
borderRadius: '4px',
cursor: 'pointer'
}}
>
<strong>{p.label}</strong> — {p.description}
</button>
))}
<span style={{fontSize: '0.85em', opacity: 0.7, marginLeft: '0.5em'}}>
(switching resets rates to preset defaults)
</span>
</div>
);
const presetButtons = <Group gap='xs' style={{flexWrap: 'wrap'}}>
{Object.entries(WATER_PRESETS).map(([key, p]) => (
<Button key={key} type='button' role={preset === key ? 'primary' : 'cancel'}
onClick={() => setPreset(key)}>
{p.label} — {p.description}
</Button>
))}
<span style={{fontSize: '0.85em', opacity: 0.7}}>
(switching resets rates to preset defaults)
</span>
</Group>;
// One row per container: how many of it the total water would fill, and the spare
// capacity in the last one. Shown for every container so the user can compare.
const containerRows = CONTAINERS.map(c => {
const capacity = metric ? c.liters : c.gallons;
const need = total !== null ? containersNeeded(total, capacity) : null;
return <TableRow key={c.key}>
<TableCell>{c.label}</TableCell>
<TableCell>{capacity} {volumeUnit}</TableCell>
<TableCell>
return <Table.Row key={c.key}>
<Table.Cell>{c.label}</Table.Cell>
<Table.Cell>{capacity} {volumeUnit}</Table.Cell>
<Table.Cell>
{need === null
? '—'
: <span><b>{need.count}</b>
{need.leftover > 0 &&
<span style={{opacity: 0.7}}> ({fmt(need.leftover, volumeUnit)} spare)</span>}
</span>}
</TableCell>
</TableRow>;
</Table.Cell>
</Table.Row>;
});
return <Form>
return <div>
<Header as='h1'>Water Storage</Header>
<div style={{marginBottom: '1em'}}>
@ -308,25 +304,23 @@ export function WaterCalculator() {
<div style={{marginBottom: '1em'}}>{presetButtons}</div>
<Header as='h3'>People</Header>
<Grid stackable columns={2}>
<Grid>
{CATEGORY_META.map(meta =>
<GridColumn key={meta.key}>{countInput(meta)}</GridColumn>)}
<Grid.Col key={meta.key} span={{base: 12, xs: 6}}>{countInput(meta)}</Grid.Col>)}
</Grid>
<Header as='h3' style={{marginTop: '1em'}}>
Daily Use ({rateUnit} per person) <InfoPopup content={DEMAND_INFO}/>
</Header>
<Grid stackable columns={2}>
<Grid>
{CATEGORY_META.map(meta =>
<GridColumn key={meta.key}>{rateInput(meta)}</GridColumn>)}
<Grid.Col key={meta.key} span={{base: 12, xs: 6}}>{rateInput(meta)}</Grid.Col>)}
</Grid>
<Header as='h3' style={{marginTop: '1em'}}>Additional daily demand</Header>
<div style={{maxWidth: '320px'}}>
<Input {...inputProps} min={0} step={0.1} name="extra"
labelPosition='left' value={extra}
onChange={e => setExtra(clampNonNegative(e.target.value))}
label={<Label>Extra {rateUnit}</Label>}/>
<SwatchInput hex='#5f686a' label={`Extra ${rateUnit}`} value={extra} min={0} step={0.1} name="extra"
onChange={value => setExtra(clampNonNegative(value))}/>
<p style={{fontSize: '0.85em', opacity: 0.7, marginTop: '0.25em'}}>
Pets, livestock, guests, sick household members, or anything else not covered above.
</p>
@ -338,40 +332,40 @@ export function WaterCalculator() {
value={durationStop} aria-label='Duration'
onChange={e => setDurationIndex(Number(e.target.value))}
style={{width: '100%'}}/>
<Header as='h2' textAlign='center' style={{marginTop: '0.25em'}}>
<Header as='h2' style={{marginTop: '0.25em', textAlign: 'center'}}>
{formatDuration(days)}
</Header>
</div>
<Segment style={{marginTop: '1em'}}>
<Table definition unstackable>
<TableBody>
<TableRow>
<TableCell width={6}>Daily Use</TableCell>
<TableCell>{fmt(daily, `${volumeUnit}/day`)}</TableCell>
</TableRow>
<TableRow>
<TableCell>Total Water for {formatDuration(days)}</TableCell>
<TableCell>{fmt(total, volumeUnit)}</TableCell>
</TableRow>
<TableRow>
<TableCell>Water Weight</TableCell>
<TableCell>{fmt(weight, weightUnit)}</TableCell>
</TableRow>
</TableBody>
<Panel style={{marginTop: '1em'}}>
<Table>
<Table.Body>
<Table.Row>
<Table.Cell style={{fontWeight: 600}}>Daily Use</Table.Cell>
<Table.Cell>{fmt(daily, `${volumeUnit}/day`)}</Table.Cell>
</Table.Row>
<Table.Row>
<Table.Cell style={{fontWeight: 600}}>Total Water for {formatDuration(days)}</Table.Cell>
<Table.Cell>{fmt(total, volumeUnit)}</Table.Cell>
</Table.Row>
<Table.Row>
<Table.Cell style={{fontWeight: 600}}>Water Weight</Table.Cell>
<Table.Cell>{fmt(weight, weightUnit)}</Table.Cell>
</Table.Row>
</Table.Body>
</Table>
<Header as='h3'>Containers Needed</Header>
<Table unstackable>
<TableHeader>
<TableRow>
<TableHeaderCell>Container</TableHeaderCell>
<TableHeaderCell>Capacity</TableHeaderCell>
<TableHeaderCell>Needed</TableHeaderCell>
</TableRow>
</TableHeader>
<TableBody>{containerRows}</TableBody>
<Table>
<Table.Header>
<Table.Row>
<Table.HeaderCell>Container</Table.HeaderCell>
<Table.HeaderCell>Capacity</Table.HeaderCell>
<Table.HeaderCell>Needed</Table.HeaderCell>
</Table.Row>
</Table.Header>
<Table.Body>{containerRows}</Table.Body>
</Table>
</Segment>
</Form>;
</Panel>
</div>;
}