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,5 +1,5 @@
import React from "react";
import {Input, Select} from "semantic-ui-react";
import {Select, TextInput} from "../ui";
import {ALL_UNITS, evaluateExpression, NUMERIC_TYPES, UNIT_GROUPS} from "./units";
// Renders the correct editor for a single field/value, wiring up keyboard navigation. The `inputRef` is attached
@ -31,17 +31,14 @@ export function FieldCell({field, value, unitValue, onChange, onUnitChange, onEn
if (!autoFocus) {
return;
}
// Our inputs forward their ref straight to the underlying <input> DOM node, so focus + select work
// directly on it (unlike Semantic's Input, which wrapped the node behind `.inputRef`).
const node = localRef.current;
// Semantic's Input exposes the DOM <input> via `inputRef`; selecting its contents lets the user type over
// the value immediately. Other editors (e.g. Select) just take focus.
const dom = node && node.inputRef && node.inputRef.current;
if (dom) {
dom.focus();
if (dom.select) {
dom.select();
}
} else if (node && node.focus) {
if (node && node.focus) {
node.focus();
if (node.select) {
node.select();
}
}
}, [autoFocus]);
@ -81,71 +78,74 @@ export function FieldCell({field, value, unitValue, onChange, onUnitChange, onEn
const common = {
value: value ?? '',
onChange: (e, data) => onChange(data ? data.value : e.target.value),
onChange: (e) => onChange(e.currentTarget.value),
onKeyDown: handleKeyDown,
'aria-label': field.label,
name: field.key,
};
if (field.type === 'select') {
const options = (field.options || []).map(o => ({key: o, value: o, text: o}));
const options = (field.options || []).map(o => ({value: o, label: o}));
// Allow clearing.
return <Select
fluid search clearable selection
searchable
clearable
ref={setRef}
name={field.key}
options={options}
data={options}
placeholder={field.label}
value={value ?? ''}
onChange={(e, data) => onChange(data.value)}
onChange={value => onChange(value || '')}
onKeyDown={handleKeyDown}
aria-label={field.label}
/>;
}
if (field.type === 'date') {
return <Input {...common} type='date' fluid ref={setRef}/>;
return <TextInput {...common} type='date' ref={setRef}/>;
}
if (field.type === 'number' || field.type === 'calories') {
// `calories` is a number (kcal per unit) that the Summary's ration estimate detects by type. Text (not
// number) input so arithmetic expressions can be typed; evaluated on blur/Enter.
return <Input {...common} type='text' inputMode='decimal' fluid ref={setRef} onBlur={onBlur}/>;
return <TextInput {...common} type='text' inputMode='decimal' ref={setRef} onBlur={onBlur}/>;
}
if (field.type === 'quantity') {
const unitOptions = ALL_UNITS.map(u => ({key: u, value: u, text: u}));
return <Input
type='text'
inputMode='decimal'
fluid
ref={setRef}
name={field.key}
value={value ?? ''}
onChange={(e) => onChange(e.target.value)}
onKeyDown={handleKeyDown}
onBlur={onBlur}
aria-label={field.label}
label={<Select
compact
name={`${field.key}_unit`}
options={unitOptions}
const unitOptions = ALL_UNITS.map(u => ({value: u, label: u}));
// Value + unit share one outline (the same layout `ActionInput` builds), but we need a real ref on the
// value input to support the parent's focus/select behavior, which a plain-function `ActionInput` cannot
// forward.
return <div className='wrolpi-action-input'>
<TextInput
type='text'
inputMode='decimal'
ref={setRef}
name={field.key}
value={value ?? ''}
onChange={e => onChange(e.currentTarget.value)}
onKeyDown={handleKeyDown}
onBlur={onBlur}
aria-label={field.label}
/>
<Select
data={unitOptions}
value={unitValue ?? field.unit ?? ''}
onChange={(e, data) => onUnitChange(data.value)}
onChange={value => onUnitChange(value)}
aria-label={`${field.label} unit`}
/>}
labelPosition='right'
/>;
style={{width: '5.5em'}}
/>
</div>;
}
if (field.type === 'location') {
// Native datalist autocomplete fed by all inventories' locations (basement, attic, ...). Using a datalist
// (rather than a Dropdown) keeps it a real text input, so the Tab/Enter row-entry flow still works.
return <Input {...common} fluid ref={setRef} list={listId}/>;
return <TextInput {...common} ref={setRef} list={listId}/>;
}
// text / fallback (supports a datalist via listId, e.g. catalog name suggestions on the Name field).
return <Input {...common} fluid ref={setRef} list={listId}/>;
return <TextInput {...common} ref={setRef} list={listId}/>;
}
// The list of selectable unit groups, re-exported for the field editor.

View file

@ -1,15 +1,12 @@
import React, {useState} from "react";
import {
Checkbox, Input, Select, TableBody, TableCell, TableHeader, TableHeaderCell, TableRow
} from "semantic-ui-react";
import {Button, Icon, Modal, Table} from "../Theme";
import {Button, Icon, IconButton, Modal, Select, Table, TextInput, Toggle} from "../ui";
import {ALL_UNITS} from "./units";
import {addCountByWeightFields, isCountByWeight} from "./computeFields";
const FIELD_TYPE_OPTIONS = ['text', 'number', 'quantity', 'date', 'select', 'location', 'calories']
.map(t => ({key: t, value: t, text: t}));
.map(t => ({value: t, label: t}));
const UNIT_OPTIONS = ALL_UNITS.map(u => ({key: u, value: u, text: u}));
const UNIT_OPTIONS = ALL_UNITS.map(u => ({value: u, label: u}));
function slugifyKey(label) {
return (label || '').trim().toLowerCase().replace(/[^a-z0-9]+/g, '_').replace(/^_+|_+$/g, '') || 'field';
@ -67,74 +64,72 @@ export function FieldSchemaEditor({fields, open, onClose, onSave}) {
return <Modal open={open} onClose={onClose} closeIcon size='large'>
<Modal.Header>Customize Fields</Modal.Header>
<Modal.Content scrolling>
{/* NOTE: do NOT use `fixed` here — semantic gives fixed-table cells `overflow:hidden`, which clips the
Type/Unit dropdown menus to the cell height. The `width` props below size the columns without it. */}
<Table celled unstackable>
<TableHeader>
<TableRow>
<TableHeaderCell width={2}>Order</TableHeaderCell>
<TableHeaderCell width={3}>Label</TableHeaderCell>
<TableHeaderCell width={3}>Type</TableHeaderCell>
<TableHeaderCell width={5}>Unit / Options</TableHeaderCell>
<TableHeaderCell width={2} textAlign='center'
title='Show this field in the read-only portrait-mobile view'>
<Table>
<Table.Header>
<Table.Row>
<Table.HeaderCell>Order</Table.HeaderCell>
<Table.HeaderCell>Label</Table.HeaderCell>
<Table.HeaderCell>Type</Table.HeaderCell>
<Table.HeaderCell>Unit / Options</Table.HeaderCell>
<Table.HeaderCell style={{textAlign: 'center'}}
title='Show this field in the read-only portrait-mobile view'>
Mobile
</TableHeaderCell>
<TableHeaderCell width={1}/>
</TableRow>
</TableHeader>
<TableBody>
{draft.map((f, index) => <TableRow key={index}>
<TableCell collapsing>
<Button icon size='mini' onClick={() => move(index, -1)} disabled={index === 0}
aria-label='Move up'><Icon name='arrow up'/></Button>
<Button icon size='mini' onClick={() => move(index, 1)}
disabled={index === draft.length - 1}
aria-label='Move down'><Icon name='arrow down'/></Button>
</TableCell>
<TableCell>
<Input fluid value={f.label || ''} placeholder='Label'
onChange={e => update(index, {label: e.target.value})}/>
</TableCell>
<TableCell>
<Select fluid options={FIELD_TYPE_OPTIONS} value={f.type}
onChange={(e, data) => update(index, {type: data.value})}/>
</TableCell>
<TableCell>
</Table.HeaderCell>
<Table.HeaderCell/>
</Table.Row>
</Table.Header>
<Table.Body>
{draft.map((f, index) => <Table.Row key={index}>
<Table.Cell>
<IconButton size='xs' icon='arrow up' onClick={() => move(index, -1)}
disabled={index === 0} label='Move up'/>
<IconButton size='xs' icon='arrow down' onClick={() => move(index, 1)}
disabled={index === draft.length - 1} label='Move down'/>
</Table.Cell>
<Table.Cell>
<TextInput value={f.label || ''} placeholder='Label'
onChange={e => update(index, {label: e.currentTarget.value})}/>
</Table.Cell>
<Table.Cell>
<Select data={FIELD_TYPE_OPTIONS} value={f.type}
onChange={value => update(index, {type: value})}/>
</Table.Cell>
<Table.Cell>
{f.type === 'quantity' &&
<Select fluid search options={UNIT_OPTIONS} value={f.unit || ''}
<Select searchable data={UNIT_OPTIONS} value={f.unit || ''}
placeholder='Default unit'
onChange={(e, data) => update(index, {unit: data.value})}/>}
onChange={value => update(index, {unit: value})}/>}
{f.type === 'select' &&
/* Keep the raw split (no trim/filter) so typing a comma to start the next option
isn't swallowed mid-edit; options are trimmed/cleaned on save(). */
<Input fluid placeholder='comma,separated,options'
value={(f.options || []).join(',')}
onChange={e => update(index, {options: e.target.value.split(',')})}/>}
<TextInput placeholder='comma,separated,options'
value={(f.options || []).join(',')}
onChange={e => update(index, {options: e.currentTarget.value.split(',')})}/>}
{isCountByWeight(f) &&
<span style={{opacity: 0.7, fontSize: '0.9em'}}>
<Icon name='calculator'/> Auto-counted: Total Weight ÷ Unit Weight
</span>}
</TableCell>
<TableCell collapsing textAlign='center'>
<Checkbox toggle checked={!!f.mobile} aria-label={`Show ${f.label || f.key} on mobile`}
onChange={(e, data) => update(index, {mobile: data.checked})}/>
</TableCell>
<TableCell collapsing>
<Button color='red' icon size='mini' onClick={() => remove(index)}
aria-label='Remove field'><Icon name='trash'/></Button>
</TableCell>
</TableRow>)}
</TableBody>
</Table.Cell>
<Table.Cell style={{textAlign: 'center'}}>
<Toggle checked={!!f.mobile} aria-label={`Show ${f.label || f.key} on mobile`}
onChange={e => update(index, {mobile: e.currentTarget.checked})}/>
</Table.Cell>
<Table.Cell>
<IconButton role='danger' size='xs' icon='trash' onClick={() => remove(index)}
label='Remove field'/>
</Table.Cell>
</Table.Row>)}
</Table.Body>
</Table>
<Button onClick={add}><Icon name='plus'/>Add Field</Button>
<Button onClick={addCountByWeight} title='Add Unit Weight, Total Weight, and an auto-counted Count'>
<Icon name='balance scale'/>Count by Weight
<Button icon='plus' onClick={add}>Add Field</Button>
<Button icon='balance scale' onClick={addCountByWeight}
title='Add Unit Weight, Total Weight, and an auto-counted Count'>
Count by Weight
</Button>
</Modal.Content>
<Modal.Actions>
<Button onClick={onClose}>Cancel</Button>
<Button primary onClick={save}>Save Fields</Button>
<Button role='cancel' onClick={onClose}>Cancel</Button>
<Button role='save' onClick={save}>Save Fields</Button>
</Modal.Actions>
</Modal>;
}

View file

@ -1,5 +1,5 @@
import React from "react";
import {fireEvent, render, screen} from "@testing-library/react";
import {fireEvent, render, screen} from "../../test-utils";
import {FieldSchemaEditor} from "./FieldSchemaEditor";
const FIELDS = [

View file

@ -1,11 +1,8 @@
import React, {useContext, useEffect, useState} from "react";
import {toast} from "react-semantic-toasts-2";
import {TableBody, TableCell, TableHeader, TableHeaderCell, TableRow} from "semantic-ui-react";
import {Button, Divider, Header, Icon, Loader, Modal, Table} from "../Theme";
import React, {useEffect, useState} from "react";
import {Button, Divider, Header, Icon, Loading, Modal, Table, toast} from "../ui";
import {
getInventoryBackups, postInventoryRestore, postInventoryRestorePreview, reimportInventories,
} from "../../api";
import {ThemeContext} from "../../contexts/contexts";
const formatDate = (d) => d && d.length === 8 ? `${d.substring(0, 4)}-${d.substring(4, 6)}-${d.substring(6, 8)}` : d;
@ -13,12 +10,11 @@ const itemName = (item) => (item && (item.name || `Item ${item.id}`)) || 'Item';
// Compact list of item names from a preview's add/remove arrays.
function ItemNameList({items}) {
const {t} = useContext(ThemeContext);
if (!items || items.length === 0) {
return null;
}
return <ul style={{marginTop: '0.25em'}}>
{items.map((i, idx) => <li key={`${i.id}-${idx}`} {...t}>{itemName(i)}</li>)}
{items.map((i, idx) => <li key={`${i.id}-${idx}`}>{itemName(i)}</li>)}
</ul>;
}
@ -29,7 +25,6 @@ function ItemNameList({items}) {
* `onChanged` refreshes the page's inventory state after a successful action.
*/
export function InventoryImportModal({open, onClose, slug, name, onChanged}) {
const {t} = useContext(ThemeContext);
const [dates, setDates] = useState(null); // null while loading
const [reimporting, setReimporting] = useState(false);
const [selected, setSelected] = useState(null); // {date, mode, preview} confirmation view
@ -96,38 +91,42 @@ export function InventoryImportModal({open, onClose, slug, name, onChanged}) {
<Modal.Header>{modeLabel} backup from {formatDate(date)}</Modal.Header>
<Modal.Content>
{applying
? <Loader active inline='centered'>Restoring…</Loader>
? <Loading>Restoring…</Loading>
: <>
{mode === 'overwrite'
? <p {...t}>
? <p>
Replace <strong>{name}</strong> entirely with the {formatDate(date)} backup
({preview.backup_count} item{preview.backup_count === 1 ? '' : 's'}).
</p>
: <p {...t}>
: <p>
Add items from the {formatDate(date)} backup that aren't already present; your
current items and fields are kept.
</p>}
{preview.add.length > 0 && <>
<Header as='h5' color='green'><Icon name='plus'/> {preview.add.length} to add</Header>
<Header as='h5' icon='plus' style={{color: 'var(--green)'}}>
{preview.add.length} to add
</Header>
<ItemNameList items={preview.add}/>
</>}
{preview.remove.length > 0 && <>
<Header as='h5' color='red'><Icon name='minus'/> {preview.remove.length} to remove</Header>
<Header as='h5' icon='minus' style={{color: 'var(--red)'}}>
{preview.remove.length} to remove
</Header>
<ItemNameList items={preview.remove}/>
</>}
{preview.fields_change &&
<p {...t}><Icon name='columns'/> The field columns will also change.</p>}
<p><Icon name='columns'/> The field columns will also change.</p>}
{preview.add.length === 0 && preview.remove.length === 0 && !preview.fields_change &&
<p {...t}>No changes — this backup matches the current inventory.</p>}
<p style={{color: 'grey'}}>{preview.unchanged} unchanged
<p>No changes — this backup matches the current inventory.</p>}
<p style={{color: 'var(--muted)'}}>{preview.unchanged} unchanged
item{preview.unchanged === 1 ? '' : 's'}</p>
</>}
</Modal.Content>
<Modal.Actions>
{!applying && <>
<Button onClick={() => setSelected(null)}>Back</Button>
<Button color='green' onClick={applyRestore}><Icon name='check'/> Apply</Button>
<Button role='cancel' onClick={() => setSelected(null)}>Back</Button>
<Button role='save' icon='check' onClick={applyRestore}>Apply</Button>
</>}
</Modal.Actions>
</Modal>;
@ -137,57 +136,58 @@ export function InventoryImportModal({open, onClose, slug, name, onChanged}) {
<Modal.Header>Import / Restore: {name}</Modal.Header>
<Modal.Content>
<Header as='h4'>Re-import from disk</Header>
<p {...t}>
<p>
Reload every inventory from its config file. Use this after editing a file by hand, or after copying
an inventory file in from another WROLPi.
</p>
<Button primary onClick={doReimport} loading={reimporting} disabled={reimporting}>
<Icon name='sync'/> Re-import from disk
<Button role='primary' icon='sync' onClick={doReimport} loading={reimporting} disabled={reimporting}>
Re-import from disk
</Button>
<Divider/>
<Header as='h4'>Restore from a backup</Header>
<p {...t}>
<p>
<strong>Merge</strong> adds items from the backup that aren't already present.
{' '}<strong>Overwrite</strong> replaces this inventory entirely with the backup.
</p>
{dates === null
? <Loader active inline='centered'>Loading backups…</Loader>
? <Loading>Loading backups…</Loading>
: dates.length === 0
? <p {...t}>No backups yet. A backup is saved automatically whenever this inventory changes.</p>
? <p>No backups yet. A backup is saved automatically whenever this inventory changes.</p>
: <div style={{maxHeight: '320px', overflowY: 'auto'}}>
<Table compact unstackable>
<TableHeader>
<TableRow>
<TableHeaderCell>Date</TableHeaderCell>
<TableHeaderCell>Merge</TableHeaderCell>
<TableHeaderCell>Overwrite</TableHeaderCell>
</TableRow>
</TableHeader>
<TableBody>
{dates.map(date => <TableRow key={date}>
<TableCell>{formatDate(date)}</TableCell>
<TableCell>
<Button size='mini' color='green' loading={previewing === `${date}:merge`}
<Table>
<Table.Header>
<Table.Row>
<Table.HeaderCell>Date</Table.HeaderCell>
<Table.HeaderCell>Merge</Table.HeaderCell>
<Table.HeaderCell>Overwrite</Table.HeaderCell>
</Table.Row>
</Table.Header>
<Table.Body>
{dates.map(date => <Table.Row key={date}>
<Table.Cell>{formatDate(date)}</Table.Cell>
<Table.Cell>
<Button size='xs' role='save' icon='plus'
loading={previewing === `${date}:merge`}
onClick={() => selectAction(date, 'merge')}>
<Icon name='plus'/> Merge
Merge
</Button>
</TableCell>
<TableCell>
<Button size='mini' color='orange'
</Table.Cell>
<Table.Cell>
<Button size='xs' color='orange' icon='refresh'
loading={previewing === `${date}:overwrite`}
onClick={() => selectAction(date, 'overwrite')}>
<Icon name='refresh'/> Overwrite
Overwrite
</Button>
</TableCell>
</TableRow>)}
</TableBody>
</Table.Cell>
</Table.Row>)}
</Table.Body>
</Table>
</div>}
</Modal.Content>
<Modal.Actions>
<Button onClick={onClose}>Close</Button>
<Button role='cancel' onClick={onClose}>Close</Button>
</Modal.Actions>
</Modal>;
}

View file

@ -1,7 +1,6 @@
import React from "react";
import {fireEvent, render, screen, waitFor, within} from "@testing-library/react";
import {fireEvent, render, screen, waitFor, within} from "../../test-utils";
jest.mock("react-semantic-toasts-2", () => ({toast: jest.fn()}));
jest.mock("../../api", () => ({
getInventoryBackups: jest.fn(),
postInventoryRestorePreview: jest.fn(),

View file

@ -1,6 +1,8 @@
import React, {useMemo, useState} from "react";
import {Dropdown, Input, Select} from "semantic-ui-react";
import {Button, Confirm, Header, Icon, Loader, Menu, Modal, Segment} from "../Theme";
import {
Button, Confirm, Header, IconButton, Loading, Modal, Panel, SearchBox, Select, TabBar, tabClassName, Text,
TextInput,
} from "../ui";
import {PageContainer, useTitle} from "../Common";
import {collectLocations, useCatalog, useInventories} from "../../hooks/customHooks";
import {filterItems, InventoryTable} from "./InventoryTable";
@ -13,18 +15,17 @@ import {defaultGroupKey, defaultSumKey, findCaloriesKey, findCountKey} from "./s
import {FieldSchemaEditor} from "./FieldSchemaEditor";
import {CatalogEditor} from "./CatalogEditor";
import {InventoryImportModal} from "./InventoryImportModal";
import {Media, ThemeContext} from "../../contexts/contexts";
import {Media} from "../../contexts/contexts";
const INVENTORY_TYPES = [
{key: 'food', value: 'food', text: 'Food Storage'},
{key: 'fuel', value: 'fuel', text: 'Fuel'},
{key: 'tool', value: 'tool', text: 'Tools'},
{value: 'food', label: 'Food Storage'},
{value: 'fuel', label: 'Fuel'},
{value: 'tool', label: 'Tools'},
];
function NewInventoryModal({open, onClose, onCreate}) {
const [name, setName] = useState('');
const [type, setType] = useState('food');
const {t} = React.useContext(ThemeContext);
const create = async () => {
const inventory = await onCreate(name, type);
@ -38,19 +39,19 @@ function NewInventoryModal({open, onClose, onCreate}) {
return <Modal open={open} onClose={onClose} closeIcon>
<Modal.Header>New Inventory</Modal.Header>
<Modal.Content>
<Input fluid autoFocus label='Name' value={name} onChange={e => setName(e.target.value)}
placeholder='Food Storage' style={{marginBottom: '1em'}}/>
<TextInput autoFocus label='Name' value={name} onChange={e => setName(e.currentTarget.value)}
placeholder='Food Storage' mb='1em'/>
<div>
Type:{' '}
<Select options={INVENTORY_TYPES} value={type} onChange={(e, data) => setType(data.value)}/>
<p {...t} style={{...t.style, fontSize: '0.85em', opacity: 0.7, marginTop: '0.5em'}}>
<Select data={INVENTORY_TYPES} value={type} onChange={setType}/>
<Text size='sm' c='dimmed' mt='0.5em'>
The type seeds a starting set of fields — you can customize them afterward.
</p>
</Text>
</div>
</Modal.Content>
<Modal.Actions>
<Button onClick={onClose}>Cancel</Button>
<Button primary onClick={create} disabled={!name.trim()}>Create</Button>
<Button role='cancel' onClick={onClose}>Cancel</Button>
<Button role='primary' onClick={create} disabled={!name.trim()}>Create</Button>
</Modal.Actions>
</Modal>;
}
@ -76,8 +77,6 @@ export function InventoryRoute() {
// Free-text filter applied to the active inventory's items across every column.
const [search, setSearch] = useState('');
const {t} = React.useContext(ThemeContext);
// Default to the first inventory once loaded.
React.useEffect(() => {
if (slug == null && inventories && inventories.length > 0) {
@ -134,62 +133,61 @@ export function InventoryRoute() {
};
if (inventories === null) {
return <PageContainer><Loader active inline='centered'/></PageContainer>;
return <PageContainer><Loading/></PageContainer>;
}
const inventoryOptions = inventories.map(i => ({key: i.slug, value: i.slug, text: i.name}));
const inventoryOptions = inventories.map(i => ({value: i.slug, label: i.name}));
const tabs = [
{key: 'items', label: 'Items'},
{key: 'summary', label: 'Summary'},
...(caloriesKey ? [{key: 'ration', label: 'Ration'}] : []),
{key: 'export', label: 'Export'},
];
return <PageContainer>
<Header as='h1'>Inventory</Header>
<Segment>
<Panel>
<div style={{display: 'flex', gap: '0.5em', alignItems: 'center', flexWrap: 'wrap'}}>
<Dropdown
selection
<Select
placeholder='Select an inventory'
options={inventoryOptions}
data={inventoryOptions}
value={slug || ''}
onChange={(e, data) => setSlug(data.value)}
onChange={value => setSlug(value)}
style={{minWidth: '14em'}}
/>
<Button primary icon onClick={() => setNewOpen(true)} aria-label='New inventory'>
<Icon name='plus'/>
</Button>
<Button icon onClick={() => setCatalogOpen(true)} aria-label='Food catalog'>
<Icon name='book'/> Catalog
</Button>
<IconButton role='primary' icon='plus' onClick={() => setNewOpen(true)} label='New inventory'/>
<Button icon='book' onClick={() => setCatalogOpen(true)}>Catalog</Button>
{current && <>
<Button icon onClick={() => {
<IconButton icon='edit' onClick={() => {
setRenameValue(current.name);
setRenaming(true);
}} aria-label='Rename inventory'><Icon name='edit'/></Button>
<Button icon onClick={() => setEditFieldsOpen(true)} aria-label='Customize fields'>
<Icon name='columns'/> Fields
</Button>
<Button icon onClick={() => setImportOpen(true)} aria-label='Import or restore inventory'>
<Icon name='history'/> Restore
</Button>
<Button color='red' icon onClick={() => setConfirmDelete(true)} aria-label='Delete inventory'>
<Icon name='trash'/>
</Button>
}} label='Rename inventory'/>
<Button icon='columns' onClick={() => setEditFieldsOpen(true)}>Fields</Button>
<Button icon='history' onClick={() => setImportOpen(true)}>Restore</Button>
<IconButton role='danger' icon='trash' onClick={() => setConfirmDelete(true)}
label='Delete inventory'/>
</>}
</div>
</Segment>
</Panel>
{current ? <>
<Menu pointing secondary>
<Menu.Item name='Items' active={tab === 'items'} onClick={() => setTab('items')}/>
<Menu.Item name='Summary' active={tab === 'summary'} onClick={() => setTab('summary')}/>
{caloriesKey &&
<Menu.Item name='Ration' active={tab === 'ration'} onClick={() => setTab('ration')}/>}
<Menu.Item name='Export' active={tab === 'export'} onClick={() => setTab('export')}/>
</Menu>
<TabBar>
{tabs.map(({key, label}) => <button
key={key}
type='button'
className={tabClassName(tab === key)}
onClick={() => setTab(key)}
>{label}</button>)}
</TabBar>
{tab === 'items' && <>
{/* The search filter lives here so it clearly applies to the Items tab only, not Summary/Ration/Export. */}
<Input fluid icon='search' iconPosition='left' placeholder='Search items…' value={search}
aria-label='Search items' clearable style={{marginBottom: '0.75em'}}
onChange={(e, data) => setSearch(data.value)}/>
<div style={{marginBottom: '0.75em'}}>
<SearchBox value={search} onChange={setSearch} clearable placeholder='Search items…'
label='Search items'/>
</div>
{/* Portrait mobile: condensed, read-only. Rotate to landscape (tablet+) for the full editor. */}
<Media at='mobile'>
<InventoryItemsMobile fields={fields} items={filteredItems}/>
@ -221,7 +219,7 @@ export function InventoryRoute() {
<InventoryImportModal open={importOpen} onClose={() => setImportOpen(false)}
slug={slug} name={current.name} onChanged={fetchInventories}/>
</> : <p {...t}>Create an inventory to get started.</p>}
</> : <Text>Create an inventory to get started.</Text>}
<NewInventoryModal open={newOpen} onClose={() => setNewOpen(false)} onCreate={onCreate}/>
@ -231,21 +229,23 @@ export function InventoryRoute() {
<Modal open={renaming} onClose={() => setRenaming(false)} closeIcon size='tiny'>
<Modal.Header>Rename Inventory</Modal.Header>
<Modal.Content>
<Input fluid autoFocus value={renameValue} onChange={e => setRenameValue(e.target.value)}/>
<TextInput autoFocus value={renameValue} onChange={e => setRenameValue(e.currentTarget.value)}/>
</Modal.Content>
<Modal.Actions>
<Button onClick={() => setRenaming(false)}>Cancel</Button>
<Button primary onClick={doRename} disabled={!renameValue.trim()}>Save</Button>
<Button role='cancel' onClick={() => setRenaming(false)}>Cancel</Button>
<Button role='save' onClick={doRename} disabled={!renameValue.trim()}>Save</Button>
</Modal.Actions>
</Modal>
<Confirm
open={confirmDelete}
header='Delete Inventory'
content={`Delete "${current?.name}" and all its items? This cannot be undone.`}
confirmButton='Delete'
title='Delete Inventory'
destructive
confirmLabel='Delete'
onCancel={() => setConfirmDelete(false)}
onConfirm={doDelete}
/>
>
{`Delete "${current?.name}" and all its items? This cannot be undone.`}
</Confirm>
</PageContainer>;
}

View file

@ -1,6 +1,5 @@
import React, {useMemo, useRef, useState} from "react";
import {Checkbox, TableBody, TableCell, TableFooter, TableHeader, TableHeaderCell, TableRow} from "semantic-ui-react";
import {Button, Icon, Table} from "../Theme";
import {Button, Checkbox, Icon, Table} from "../ui";
import {FieldCell} from "./FieldCell";
import {applyComputedCounts, computedCountConfigs} from "./computeFields";
import {NUMERIC_TYPES} from "./units";
@ -129,11 +128,11 @@ export function InventoryTable({slug, fields, items, locations, catalog, search,
const visibleItems = useMemo(() => filterItems(displayItems, fields, search), [displayItems, fields, search]);
const focusFirst = () => {
// Our inputs forward their ref straight to the underlying <input> DOM node (unlike Semantic's Input,
// which wrapped it behind `.inputRef`).
const node = firstInputRef.current;
if (node && node.focus) {
node.focus();
} else if (node && node.inputRef && node.inputRef.current) {
node.inputRef.current.focus();
}
};
@ -213,33 +212,32 @@ export function InventoryTable({slug, fields, items, locations, catalog, search,
{catalog.map(e => <option key={e.id ?? e.name} value={e.name}/>)}
</datalist>}
{selected.size > 0 &&
<Button color='red' onClick={removeSelected} style={{marginBottom: '0.5em'}}>
<Button role='danger' onClick={removeSelected} style={{marginBottom: '0.5em'}}>
Delete {selected.size} selected
</Button>}
<Table celled unstackable sortable>
<TableHeader>
<TableRow>
<TableHeaderCell collapsing/>
{sortedFields.map(f => <TableHeaderCell
<Table>
<Table.Header>
<Table.Row>
<Table.HeaderCell/>
{sortedFields.map(f => <Table.HeaderCell
key={f.key}
sorted={sort && sort.key === f.key ? (sort.dir === 'asc' ? 'ascending' : 'descending') : undefined}
onClick={() => toggleSort(f.key)}
style={{cursor: 'pointer'}}>
onSort={() => toggleSort(f.key)}>
{f.label}
</TableHeaderCell>)}
</TableRow>
</TableHeader>
<TableBody>
</Table.HeaderCell>)}
</Table.Row>
</Table.Header>
<Table.Body>
{visibleItems.map(item => {
const editing = edits[item.id];
const expired = isExpired(item);
return <TableRow key={item.id} negative={expired}>
<TableCell collapsing>
return <Table.Row key={item.id} failed={expired}>
<Table.Cell>
<Checkbox checked={selected.has(item.id)} onChange={() => toggleSelected(item.id)}/>
{expired && <Icon name='warning sign' color='red' title='Expired'
style={{marginLeft: '0.4em'}}/>}
</TableCell>
{sortedFields.map(f => <TableCell key={f.key}>
{expired && <Icon name='warning sign' label='Expired'
style={{color: 'var(--red)', marginLeft: '0.4em'}}/>}
</Table.Cell>
{sortedFields.map(f => <Table.Cell key={f.key}>
{editing
? <FieldCell
field={f}
@ -254,23 +252,23 @@ export function InventoryTable({slug, fields, items, locations, catalog, search,
: <span onClick={() => startEdit(item, f.key)} style={{cursor: 'pointer'}}>
{formatValue(item, f)}
</span>}
</TableCell>)}
</TableRow>;
</Table.Cell>)}
</Table.Row>;
})}
{search && visibleItems.length === 0 && (items || []).length > 0 &&
<TableRow>
<TableCell colSpan={sortedFields.length + 1} style={{opacity: 0.7}}>
<Table.Row>
<Table.Cell colSpan={sortedFields.length + 1} style={{opacity: 0.7}}>
No items match "{search}".
</TableCell>
</TableRow>}
</TableBody>
<TableFooter>
</Table.Cell>
</Table.Row>}
</Table.Body>
<Table.Footer>
{/* The persistent new-item entry row. */}
<TableRow>
<TableCell collapsing>
<Button primary size='mini' onClick={submitDraft} aria-label='Add item'>+</Button>
</TableCell>
{sortedFields.map((f, index) => <TableCell key={f.key}>
<Table.Row>
<Table.Cell>
<Button role='primary' size='xs' onClick={submitDraft} aria-label='Add item'>+</Button>
</Table.Cell>
{sortedFields.map((f, index) => <Table.Cell key={f.key}>
<FieldCell
field={f}
value={draft[f.key]}
@ -281,9 +279,9 @@ export function InventoryTable({slug, fields, items, locations, catalog, search,
inputRef={index === 0 ? firstInputRef : undefined}
listId={listIdFor(f)}
/>
</TableCell>)}
</TableRow>
</TableFooter>
</Table.Cell>)}
</Table.Row>
</Table.Footer>
</Table>
</>;
}

View file

@ -1,5 +1,5 @@
import React from "react";
import {fireEvent, render, screen, within} from "@testing-library/react";
import {fireEvent, render, screen, within} from "../../test-utils";
import {filterItems, InventoryTable} from "./InventoryTable";
const FIELDS = [
@ -252,14 +252,14 @@ describe('InventoryTable expired highlighting', () => {
{id: 1, name: 'Old', expiration_date: '2000-01-01'},
{id: 2, name: 'Fresh', expiration_date: '2999-01-01'},
];
const {container} = render(
render(
<InventoryTable slug='s' fields={FIELDS_WITH_DATE} items={items} locations={[]} onChange={jest.fn()}/>);
const rowOf = (name) => screen.getByText(name).closest('tr');
expect(rowOf('Old').className).toContain('negative');
expect(rowOf('Fresh').className).not.toContain('negative');
expect(rowOf('Old').className).toContain('wrolpi-row-failed');
expect(rowOf('Fresh').className).not.toContain('wrolpi-row-failed');
// One expired row -> one warning icon.
expect(container.querySelectorAll('i.warning.sign.icon').length).toBe(1);
expect(screen.getAllByLabelText('Expired').length).toBe(1);
});
});