ui: Common.js and thirteen more files off Semantic

Phase 2, part 3.  Baseline 63 -> 50.

Common.js is the one that mattered: 51 files import it, so its Semantic usage
was propping up the rest of the migration.  Everything in it now comes from the
library -- Paginator, the two search inputs, DirectorySearch, TabLinks, the
toggles, the messages, APIButton, Breadcrumbs, SimpleAccordion, IframeViewer,
CardPoster, FileIcon, LoadStatistic, the theme menu, and the hotspot icons.

Also migrated: Placeholder, Apps, ArchivePreview, CbzViewer, AddToPlaylist,
TaggedDeleteConfirmModal, the collection edit/tag forms, and four inventory
components.

New in the library, all in the gallery and tested:

  SearchBox     Semantic's `<Search category>` with its grouped results shape
                kept, because four call sites already build it.  A real
                combobox rather than a div that listens for clicks.
  Pagination    Semantic's prop names; onPageChange gets the page number.
  TabBar        the strip only -- routing stays with the caller.
  IconStack     Semantic's IconGroup, named once for assistive technology.
  Table.HeaderCell sorted/onSort -- a real button carrying aria-sort.
  Button/IconButton translate Semantic's size names.

That last one is defensive: unmigrated callers still pass size='tiny', and
Mantine drops a size it does not recognise without a word, so the button
quietly renders at the wrong size.  Mapping here keeps the mixed state honest.

Three real bugs found and fixed on the way, none of them cosmetic:

  * `fileSuffixIconName` returned fourteen icon names the map did not have, so
    opening a folder with a PDF, a Word document or an archive in it logged an
    error and drew a fallback glyph.  All fourteen mapped, with a test that
    walks the mapper's own return values, and another asserting every mapped
    name resolves to a Tabler component that exists.
  * `Statistic` relied on Semantic's `Statistic.Group` for its spacing, so on
    the dashboard the load averages ran together into "1 MIN. LOAD5 MIN.
    LOAD15 MIN. LOAD".  It carries its own spacing now.
  * Semantic's inverted stylesheet colors every descendant of an inverted
    segment, so Toggle labels inherited #dddddd -- white pixels in night mode,
    on the Settings page, which is exactly where someone adjusts their WROLPi
    in the dark.  Restated from tokens.

The baseline ratchet gained a third assertion: a migrated file may still lean
on Semantic's CSS classes without importing the library, which the import check
cannot see and which would collapse silently when Phase 4 deletes the
stylesheet.  There is one such bridge today and it is now declared.
This commit is contained in:
Roland 2026-07-30 10:00:48 -06:00 • committed by lrnselfreliance
parent 18dc90b4c2
commit 851485ef1b
35 changed files with 978 additions and 1095 deletions

View file

@ -1,18 +1,16 @@
import React, {useState} from "react";
import {Input, Select, TableBody, TableCell, TableHeader, TableHeaderCell, TableRow} from "semantic-ui-react";
import {Button, Header, Icon, Modal, Table} from "../Theme";
import {Button, IconButton, Modal, Select, Table, Text, TextInput} from "../ui";
import {ALL_UNITS} from "./units";
import {ThemeContext} from "../../contexts/contexts";
const UNIT_OPTIONS = [{key: '', value: '', text: '—'}, ...ALL_UNITS.map(u => ({key: u, value: u, text: u}))];
const UNIT_OPTIONS = [{value: '', label: '—'}, ...ALL_UNITS.map(u => ({value: u, label: u}))];
const COLUMNS = [
{key: 'name', label: 'Name', width: 4},
{key: 'category', label: 'Category', width: 3},
{key: 'subcategory', label: 'Subcategory', width: 3},
{key: 'item_size', label: 'Size', width: 2},
{key: 'item_size_unit', label: 'Unit', width: 2},
{key: 'calories', label: 'kcal', width: 2},
{key: 'name', label: 'Name'},
{key: 'category', label: 'Category'},
{key: 'subcategory', label: 'Subcategory'},
{key: 'item_size', label: 'Size'},
{key: 'item_size_unit', label: 'Unit'},
{key: 'calories', label: 'kcal'},
];
function blankEntry() {
@ -25,7 +23,6 @@ function blankEntry() {
*/
export function CatalogEditor({catalog, open, onClose, onSave}) {
const [draft, setDraft] = useState([]);
const {t} = React.useContext(ThemeContext);
React.useEffect(() => {
if (open) {
@ -45,66 +42,66 @@ export function CatalogEditor({catalog, open, onClose, onSave}) {
onClose();
};
return <Modal open={open} onClose={onClose} closeIcon size='fullscreen'>
return <Modal open={open} onClose={onClose} size='fullscreen'>
<Modal.Header>Food Catalog</Modal.Header>
<Modal.Content scrolling>
<p {...t} style={{...t.style, opacity: 0.8}}>
<Modal.Content>
<Text size='sm' c='dimmed' mb='sm'>
Known items used to autocomplete and pre-fill the entry form. <strong>kcal</strong> is the total
calories for one package of the given size.
</p>
<Button onClick={add} style={{marginBottom: '0.5em'}}><Icon name='plus'/>Add Item</Button>
<Table celled unstackable compact>
<TableHeader>
<TableRow>
{COLUMNS.map(c => <TableHeaderCell key={c.key} width={c.width}>{c.label}</TableHeaderCell>)}
<TableHeaderCell collapsing/>
</TableRow>
</TableHeader>
<TableBody>
</Text>
<Button onClick={add} icon='plus' style={{marginBottom: '0.5em'}}>Add Item</Button>
<Table>
<Table.Header>
<Table.Row>
{COLUMNS.map(c => <Table.HeaderCell key={c.key}>{c.label}</Table.HeaderCell>)}
<Table.HeaderCell/>
</Table.Row>
</Table.Header>
<Table.Body>
{draft.map((entry, index) => {
const aria = (col) => `${entry.name || 'new item'} ${col}`;
return <TableRow key={entry.id ?? `new-${index}`}>
<TableCell>
<Input fluid name='catalog-name' aria-label={aria('name')} value={entry.name || ''}
placeholder='Name' onChange={e => update(index, 'name', e.target.value)}/>
</TableCell>
<TableCell>
<Input fluid name='catalog-category' aria-label={aria('category')}
return <Table.Row key={entry.id ?? `new-${index}`}>
<Table.Cell>
<TextInput name='catalog-name' aria-label={aria('name')} value={entry.name || ''}
placeholder='Name' onChange={e => update(index, 'name', e.currentTarget.value)}/>
</Table.Cell>
<Table.Cell>
<TextInput name='catalog-category' aria-label={aria('category')}
value={entry.category || ''}
onChange={e => update(index, 'category', e.target.value)}/>
</TableCell>
<TableCell>
<Input fluid name='catalog-subcategory' aria-label={aria('subcategory')}
onChange={e => update(index, 'category', e.currentTarget.value)}/>
</Table.Cell>
<Table.Cell>
<TextInput name='catalog-subcategory' aria-label={aria('subcategory')}
value={entry.subcategory || ''}
onChange={e => update(index, 'subcategory', e.target.value)}/>
</TableCell>
<TableCell>
<Input fluid type='number' name='catalog-size' aria-label={aria('size')}
onChange={e => update(index, 'subcategory', e.currentTarget.value)}/>
</Table.Cell>
<Table.Cell>
<TextInput type='number' name='catalog-size' aria-label={aria('size')}
value={entry.item_size || ''}
onChange={e => update(index, 'item_size', e.target.value)}/>
</TableCell>
<TableCell>
<Select compact search name='catalog-unit' aria-label={aria('unit')} options={UNIT_OPTIONS}
onChange={e => update(index, 'item_size', e.currentTarget.value)}/>
</Table.Cell>
<Table.Cell>
<Select searchable name='catalog-unit' aria-label={aria('unit')} data={UNIT_OPTIONS}
value={entry.item_size_unit || ''}
onChange={(e, data) => update(index, 'item_size_unit', data.value)}/>
</TableCell>
<TableCell>
<Input fluid type='number' name='catalog-calories' aria-label={aria('calories')}
onChange={value => update(index, 'item_size_unit', value)}/>
</Table.Cell>
<Table.Cell>
<TextInput type='number' name='catalog-calories' aria-label={aria('calories')}
value={entry.calories || ''}
onChange={e => update(index, 'calories', e.target.value)}/>
</TableCell>
<TableCell collapsing>
<Button color='red' icon size='mini' aria-label='Remove'
onClick={() => remove(index)}><Icon name='trash'/></Button>
</TableCell>
</TableRow>;
onChange={e => update(index, 'calories', e.currentTarget.value)}/>
</Table.Cell>
<Table.Cell>
<IconButton role='danger' icon='trash' label='Remove'
onClick={() => remove(index)}/>
</Table.Cell>
</Table.Row>;
})}
</TableBody>
</Table.Body>
</Table>
</Modal.Content>
<Modal.Actions>
<Button onClick={onClose}>Cancel</Button>
<Button primary onClick={save}>Save Catalog</Button>
<Button role='cancel' onClick={onClose}>Cancel</Button>
<Button role='save' onClick={save}>Save Catalog</Button>
</Modal.Actions>
</Modal>;
}

View file

@ -1,11 +1,9 @@
import React from "react";
import {Select} from "semantic-ui-react";
import {Button, Header, Icon, Segment} from "../Theme";
import {Button, Group, Header, Panel, Select, Text} from "../ui";
import {downloadCSV, inventoryExportFilename, toCSV} from "./inventoryExport";
import {groupFieldsOf, summableFieldsOf} from "./summarize";
import {ThemeContext} from "../../contexts/contexts";
const fieldOptions = (fs) => fs.map(f => ({key: f.key, value: f.key, text: f.label}));
const fieldOptions = (fs) => fs.map(f => ({value: f.key, label: f.label}));
/**
* The "Export" tab: explains each export format and provides the action to produce it. CSV is the raw items table,
@ -16,47 +14,46 @@ export function InventoryExportPanel({name, fields, items, groupKey, sumKey, onG
const count = (items || []).length;
const groupFields = groupFieldsOf(fields);
const summableFields = summableFieldsOf(fields);
const {t} = React.useContext(ThemeContext);
const exportCSV = () =>
downloadCSV(inventoryExportFilename(name, 'csv'), toCSV(fields, items));
return <>
<Segment>
<Header as='h3'><Icon name='file alternate outline'/> CSV</Header>
<p {...t}>
<Panel>
<Header as='h3' icon='file alternate outline'>CSV</Header>
<Text>
A comma-separated spreadsheet of all {count} item{count === 1 ? '' : 's'} and every field, openable
in Excel, Numbers, or Google Sheets. Generated entirely on this device.
</p>
<Button primary onClick={exportCSV} disabled={count === 0}>
<Icon name='download'/> Download CSV
</Text>
<Button role='primary' onClick={exportCSV} disabled={count === 0} icon='download'>
Download CSV
</Button>
</Segment>
</Panel>
<Segment>
<Header as='h3'><Icon name='file pdf outline'/> PDF</Header>
<p {...t}>
<Panel>
<Header as='h3' icon='file pdf outline'>PDF</Header>
<Text>
A printable table of the whole inventory, followed by a summary grouped by the field you choose.
This opens your browser's print dialog — choose "Save as PDF" as the destination to get a PDF file,
or print it on paper.
</p>
</Text>
{groupFields.length > 0 &&
<div style={{marginBottom: '1em', display: 'flex', gap: '1em', flexWrap: 'wrap'}}>
<Group mb='1em' gap='1em' wrap='wrap'>
<span>
Summary group:{' '}
<Select options={fieldOptions(groupFields)} value={groupKey || ''}
onChange={(e, data) => onGroupKey(data.value)}/>
<Select data={fieldOptions(groupFields)} value={groupKey || ''}
onChange={value => onGroupKey(value)}/>
</span>
{summableFields.length > 0 &&
<span>
Sum:{' '}
<Select clearable options={fieldOptions(summableFields)} value={sumKey || ''}
onChange={(e, data) => onSumKey(data.value || undefined)}/>
<Select clearable data={fieldOptions(summableFields)} value={sumKey || ''}
onChange={value => onSumKey(value || undefined)}/>
</span>}
</div>}
<Button onClick={() => window.print()} disabled={count === 0}>
<Icon name='print'/> Print / Save as PDF
</Group>}
<Button onClick={() => window.print()} disabled={count === 0} icon='print'>
Print / Save as PDF
</Button>
</Segment>
</Panel>
</>;
}

View file

@ -1,8 +1,6 @@
import React from "react";
import {TableBody, TableCell, TableHeader, TableHeaderCell, TableRow} from "semantic-ui-react";
import {Icon, Table} from "../Theme";
import {Icon, Table, Text} from "../ui";
import {formatValue, isItemExpired} from "./InventoryTable";
import {ThemeContext} from "../../contexts/contexts";
// Fallback columns for inventories whose schema predates the per-field `mobile` flag: these preferred keys in
// order, else the first few fields.
@ -31,33 +29,32 @@ export function mobileColumns(fields) {
*/
export function InventoryItemsMobile({fields, items}) {
const columns = mobileColumns(fields);
const {t} = React.useContext(ThemeContext);
return <>
<p {...t} style={{...t.style, opacity: 0.7, fontSize: '0.85em', marginBottom: '0.5em'}}>
<Text size='sm' c='dimmed' mb='0.5em'>
Read-only — rotate to landscape to edit.
</p>
</Text>
{(items || []).length === 0
? <p {...t}>No items yet.</p>
: <Table celled unstackable>
<TableHeader>
<TableRow>
{columns.map(f => <TableHeaderCell key={f.key}>{f.label}</TableHeaderCell>)}
</TableRow>
</TableHeader>
<TableBody>
? <Text>No items yet.</Text>
: <Table>
<Table.Header>
<Table.Row>
{columns.map(f => <Table.HeaderCell key={f.key}>{f.label}</Table.HeaderCell>)}
</Table.Row>
</Table.Header>
<Table.Body>
{items.map(item => {
const expired = isItemExpired(item, fields);
return <TableRow key={item.id} negative={expired}>
{columns.map((f, idx) => <TableCell key={f.key}>
return <Table.Row key={item.id} failed={expired}>
{columns.map((f, idx) => <Table.Cell key={f.key}>
{idx === 0 && expired &&
<Icon name='warning sign' color='red' title='Expired'
style={{marginRight: '0.4em'}}/>}
<Icon name='warning sign' label='Expired'
style={{color: 'var(--red)', marginRight: '0.4em'}}/>}
{formatValue(item, f)}
</TableCell>)}
</TableRow>;
</Table.Cell>)}
</Table.Row>;
})}
</TableBody>
</Table.Body>
</Table>}
</>;
}

View file

@ -1,5 +1,6 @@
import React from "react";
import {render, screen} from "@testing-library/react";
import {screen} from "@testing-library/react";
import {renderWithProviders} from "../../test-utils";
import {InventoryItemsMobile} from "./InventoryItemsMobile";
const FIELDS = [
@ -19,7 +20,7 @@ describe('InventoryItemsMobile', () => {
{key: 'count', label: 'Count', type: 'number', order: 2, mobile: true},
{key: 'expiration_date', label: 'Expires', type: 'date', order: 3, mobile: true},
];
render(<InventoryItemsMobile fields={flagged} items={[{id: 1, name: 'Rice'}]}/>);
renderWithProviders(<InventoryItemsMobile fields={flagged} items={[{id: 1, name: 'Rice'}]}/>);
const headers = [...document.querySelectorAll('thead th')].map(th => th.textContent);
expect(headers).toEqual(['Name', 'Count', 'Expires']);
@ -28,7 +29,7 @@ describe('InventoryItemsMobile', () => {
});
test('falls back to default columns when no field is flagged mobile', () => {
render(<InventoryItemsMobile fields={FIELDS} items={[{id: 1, name: 'Rice'}]}/>);
renderWithProviders(<InventoryItemsMobile fields={FIELDS} items={[{id: 1, name: 'Rice'}]}/>);
const headers = [...document.querySelectorAll('thead th')].map(th => th.textContent);
expect(headers).toEqual(['Name', 'Sub-category', 'Size', 'Count']);
@ -44,7 +45,7 @@ describe('InventoryItemsMobile', () => {
{key: 'purchase_date', label: 'Purchased', type: 'date', order: 3},
{key: 'location', label: 'Location', type: 'location', order: 4},
];
render(<InventoryItemsMobile fields={fields} items={[{id: 1, fuel_type: 'Diesel'}]}/>);
renderWithProviders(<InventoryItemsMobile fields={fields} items={[{id: 1, fuel_type: 'Diesel'}]}/>);
const headers = [...document.querySelectorAll('thead th')].map(th => th.textContent);
expect(headers).toEqual(['Fuel', 'Container', 'Volume', 'Purchased']);
});
@ -56,17 +57,17 @@ describe('InventoryItemsMobile', () => {
{id: 2, name: 'Fresh', subcategory: 'beans', item_size: '10', item_size_unit: 'lb', count: '4',
expiration_date: '2999-01-01'},
];
const {container} = render(<InventoryItemsMobile fields={FIELDS} items={items}/>);
renderWithProviders(<InventoryItemsMobile fields={FIELDS} items={items}/>);
expect(screen.getByText('5 lb')).toBeTruthy();
const rowOf = (name) => screen.getByText(name).closest('tr');
expect(rowOf('Old').className).toContain('negative');
expect(rowOf('Fresh').className).not.toContain('negative');
expect(container.querySelectorAll('i.warning.sign.icon').length).toBe(1);
expect(rowOf('Old').className).toContain('wrolpi-row-failed');
expect(rowOf('Fresh').className).not.toContain('wrolpi-row-failed');
expect(screen.getAllByLabelText('Expired').length).toBe(1);
});
test('shows an empty state when there are no items', () => {
render(<InventoryItemsMobile fields={FIELDS} items={[]}/>);
renderWithProviders(<InventoryItemsMobile fields={FIELDS} items={[]}/>);
expect(screen.getByText('No items yet.')).toBeTruthy();
});
});

View file

@ -1,11 +1,9 @@
import React, {useMemo, useState} from "react";
import {Select, TableBody, TableCell, TableHeader, TableHeaderCell, TableRow} from "semantic-ui-react";
import {Header, Table} from "../Theme";
import {Group, Header, Select, Table, Text} from "../ui";
import {
defaultGroupKey, defaultSumKey, findCaloriesKey, findCountKey, groupFieldsOf, sortSummaryRows,
summableFieldsOf, summarizeInventory,
} from "./summarize";
import {ThemeContext} from "../../contexts/contexts";
// Aggregate the inventory client-side: group items by a chosen text/select field and sum a chosen quantity, number,
// or calories field. The grouping math lives in summarize.js (shared with the PDF export). The ration estimate
@ -15,7 +13,6 @@ export function InventorySummary({fields, items}) {
const summableFields = summableFieldsOf(fields);
const caloriesKey = findCaloriesKey(fields);
const countKey = findCountKey(fields);
const {t} = React.useContext(ThemeContext);
// Default to grouping by Category (easier to see grains/dairy/etc.), falling back to the first group field.
const [groupKey, setGroupKey] = useState(defaultGroupKey(fields));
@ -35,50 +32,53 @@ export function InventorySummary({fields, items}) {
const sortDir = (key) => sort.key === key ? (sort.dir === 'asc' ? 'ascending' : 'descending') : undefined;
if (!items || items.length === 0) {
return <p {...t}>No items to summarize yet.</p>;
return <Text>No items to summarize yet.</Text>;
}
const fieldOptions = (fs) => fs.map(f => ({key: f.key, value: f.key, text: f.label}));
const fieldOptions = (fs) => fs.map(f => ({value: f.key, label: f.label}));
return <>
<Header as='h3'>Summary</Header>
<div style={{marginBottom: '1em', display: 'flex', gap: '1em', flexWrap: 'wrap'}}>
<span {...t}>
<Group mb='1em' gap='1em' wrap='wrap'>
<span>
Group by:{' '}
<Select options={fieldOptions(groupFields)} value={groupKey}
onChange={(e, data) => setGroupKey(data.value)}/>
<Select data={fieldOptions(groupFields)} value={groupKey}
onChange={value => setGroupKey(value)}/>
</span>
{summableFields.length > 0 &&
<span>
Sum:{' '}
<Select clearable options={fieldOptions(summableFields)} value={sumKey || ''}
onChange={(e, data) => setSumKey(data.value || undefined)}/>
<Select clearable data={fieldOptions(summableFields)} value={sumKey || ''}
onChange={value => setSumKey(value || undefined)}/>
</span>}
</div>
<Table celled unstackable sortable>
<TableHeader>
<TableRow>
<TableHeaderCell sorted={sortDir('name')} onClick={() => toggleSort('name')}
style={{cursor: 'pointer'}}>
</Group>
<Table>
<Table.Header>
<Table.Row>
<Table.HeaderCell sorted={sortDir('name')} onSort={() => toggleSort('name')}>
{groupFields.find(f => f.key === groupKey)?.label || 'Group'}
</TableHeaderCell>
<TableHeaderCell sorted={sortDir('count')} onClick={() => toggleSort('count')}
style={{cursor: 'pointer'}}>Items</TableHeaderCell>
{sumKey && <TableHeaderCell sorted={sortDir('total')} onClick={() => toggleSort('total')}
style={{cursor: 'pointer'}}>Total</TableHeaderCell>}
{caloriesKey && <TableHeaderCell sorted={sortDir('calories')} onClick={() => toggleSort('calories')}
style={{cursor: 'pointer'}}>Calories</TableHeaderCell>}
</TableRow>
</TableHeader>
<TableBody>
{rows.map(row => <TableRow key={row.name}>
<TableCell>{row.name}</TableCell>
<TableCell>{row.count}</TableCell>
{sumKey && <TableCell>{row.total}</TableCell>}
</Table.HeaderCell>
<Table.HeaderCell sorted={sortDir('count')} onSort={() => toggleSort('count')}>
Items
</Table.HeaderCell>
{sumKey && <Table.HeaderCell sorted={sortDir('total')} onSort={() => toggleSort('total')}>
Total
</Table.HeaderCell>}
{caloriesKey && <Table.HeaderCell sorted={sortDir('calories')}
onSort={() => toggleSort('calories')}>
Calories
</Table.HeaderCell>}
</Table.Row>
</Table.Header>
<Table.Body>
{rows.map(row => <Table.Row key={row.name}>
<Table.Cell>{row.name}</Table.Cell>
<Table.Cell>{row.count}</Table.Cell>
{sumKey && <Table.Cell>{row.total}</Table.Cell>}
{caloriesKey &&
<TableCell>{row.calories > 0 ? `${row.calories.toLocaleString()} kcal` : '—'}</TableCell>}
</TableRow>)}
</TableBody>
<Table.Cell>{row.calories > 0 ? `${row.calories.toLocaleString()} kcal` : '—'}</Table.Cell>}
</Table.Row>)}
</Table.Body>
</Table>
</>;
}

View file

@ -1,5 +1,6 @@
import React from "react";
import {fireEvent, render, screen} from "@testing-library/react";
import {fireEvent, screen} from "@testing-library/react";
import {renderWithProviders} from "../../test-utils";
import {InventorySummary} from "./InventorySummary";
// Group by the first text field (category); two groups with different item counts and size totals.
@ -19,12 +20,12 @@ const groupOrder = () =>
describe('InventorySummary sortable columns', () => {
test('defaults to group name ascending', () => {
render(<InventorySummary fields={FIELDS} items={ITEMS}/>);
renderWithProviders(<InventorySummary fields={FIELDS} items={ITEMS}/>);
expect(groupOrder()).toEqual(['beans', 'grains']);
});
test('sorting by Items uses the numeric count', () => {
render(<InventorySummary fields={FIELDS} items={ITEMS}/>);
renderWithProviders(<InventorySummary fields={FIELDS} items={ITEMS}/>);
fireEvent.click(screen.getByText('Items')); // first click -> descending
expect(groupOrder()).toEqual(['grains', 'beans']); // grains has 2 items, beans 1
fireEvent.click(screen.getByText('Items')); // toggle -> ascending
@ -32,7 +33,7 @@ describe('InventorySummary sortable columns', () => {
});
test('sorting by Total uses the summed magnitude, not the formatted string', () => {
render(<InventorySummary fields={FIELDS} items={ITEMS}/>);
renderWithProviders(<InventorySummary fields={FIELDS} items={ITEMS}/>);
fireEvent.click(screen.getByText('Total')); // descending
expect(groupOrder()).toEqual(['beans', 'grains']); // beans 100 lb > grains 30 lb
});