From 18dc90b4c2f956dfd153952aa1ca2e18601f7956 Mon Sep 17 00:00:00 2001 From: Roland Date: Thu, 30 Jul 2026 09:31:15 -0600 Subject: [PATCH 01/31] ui: nine leaf files off Semantic, and the components they needed MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Phase 2, part 2. Baseline 72 -> 63. Migrated: Tables, SortableTable, DonatePage, Share, Headline, ErrorBoundary, and the QR code, VIN decoder, and temperature calculators. New in the library, all in the gallery and tested: SearchBox Semantic's ``, keeping its grouped `results` shape because four call sites already build it. A real combobox: arrows move, Enter takes the highlighted suggestion or submits the raw text, Escape closes without clearing. Pagination Semantic's prop names, but onPageChange gets the page number rather than an (event, data) pair. TabBar the strip and its house style only; routing stays at the call site, which is what decides what is active. IconStack two glyphs composed into one symbol, named once for assistive technology (Semantic's IconGroup). Table.HeaderCell gains `sorted` and `onSort`. That last one is a fix, not just a port. Semantic's `sorted` prop set `aria-sort`; migrating a table by hand dropped it, leaving a clickable that no keyboard could reach and no screen reader could describe. Putting it in the library means the next table gets it right without anyone remembering. Night mode holes closed along the way: the QR codes on the donate, share, and calculator pages are white by necessity — a scanner needs the contrast — and they render as SVG, which the media filter does not target. In night mode that was a lit panel. They now carry `.media`, so the filter remaps the block as a unit and the contrast survives the mapping. Also: `paypal` joins the icon map rather than being imported ad hoc in a page, and FileBrowser stops passing Semantic-only table props into a DOM element. --- app/src/components/DonatePage.js | 51 ++-- app/src/components/ErrorBoundary.js | 38 ++- app/src/components/FileBrowser.js | 2 +- app/src/components/Headline.js | 40 ++- app/src/components/Share.js | 15 +- app/src/components/SortableTable.js | 37 ++- app/src/components/Tables.js | 41 ++- app/src/components/ThemeSamplePage.js | 61 ++++- .../calculators/QRCodeCalculator.js | 72 +++--- .../calculators/TemperatureCalculator.js | 55 ++-- .../calculators/VinDecoderCalculator.js | 42 ++-- app/src/components/ui/DataTable.tsx | 41 ++- app/src/components/ui/Icon.tsx | 24 ++ app/src/components/ui/Navigation.tsx | 74 ++++++ app/src/components/ui/SearchBox.tsx | 230 +++++++++++++++++ app/src/components/ui/index.ts | 2 + app/src/components/ui/ui.css | 237 ++++++++++++++++++ app/src/components/ui/ui.test.js | 183 ++++++++++++++ app/src/semantic-baseline.json | 9 - 19 files changed, 1030 insertions(+), 224 deletions(-) create mode 100644 app/src/components/ui/Navigation.tsx create mode 100644 app/src/components/ui/SearchBox.tsx diff --git a/app/src/components/DonatePage.js b/app/src/components/DonatePage.js index 59c32517..7d024052 100644 --- a/app/src/components/DonatePage.js +++ b/app/src/components/DonatePage.js @@ -1,7 +1,6 @@ import React, {useState} from "react"; import {PageContainer, useTitle} from "./Common"; -import {Button, Header, Modal, Segment, Table} from "./Theme"; -import {Icon, TableBody, TableCell, TableRow} from "semantic-ui-react"; +import {Button, Header, IconButton, Modal, Panel, Table} from "./ui"; import QRCode from "react-qr-code"; const bitcoinAddress = '1mi1ddLSd6LmkuwJd1ttZsKuED724vYjS'; @@ -17,10 +16,8 @@ function CoinQRButton({qrCodeValue, header, buttonColor}) { const [open, setOpen] = useState(false); return <> - + setOpen(true)}/> setOpen(false)} @@ -28,7 +25,10 @@ function CoinQRButton({qrCodeValue, header, buttonColor}) { > {header} -
+ {/* `media`: the white field a scanner needs is filtered as a unit by night mode, + rather than sitting on screen as a lit panel. */} +
@@ -39,17 +39,17 @@ function CoinQRButton({qrCodeValue, header, buttonColor}) { function CoinRow({header, qrCodeValue, address, buttonColor}) { return <>
{header}
- - - - +
+ + + - - + +
{address}
- - - +
+
+
} @@ -58,31 +58,28 @@ export function DonatePage() { useTitle('Donate'); return - +
Donate
We appreciate any support you can provide to WROLPi!

-
+
; } diff --git a/app/src/components/ErrorBoundary.js b/app/src/components/ErrorBoundary.js index c417d688..9a05513d 100644 --- a/app/src/components/ErrorBoundary.js +++ b/app/src/components/ErrorBoundary.js @@ -1,5 +1,5 @@ import React from 'react'; -import {Button, Container, Icon, Message, Segment} from 'semantic-ui-react'; +import {Box, Button, ButtonGroup, Message, Panel} from './ui'; /** * Error Boundary component that catches JavaScript errors in child components @@ -52,23 +52,19 @@ class ErrorBoundary extends React.Component { const errorMessage = error?.message || 'An unexpected error occurred'; return ( - - - - - Something went wrong -

{errorMessage}

- - - - -
+ + +

{errorMessage}

+ + + +
-
+ ); } @@ -96,11 +92,11 @@ class InlineErrorBoundary extends React.Component { render() { if (this.state.hasError) { return ( - - - Failed to load this section + + + Failed to load this section - + ); } return this.props.children; diff --git a/app/src/components/FileBrowser.js b/app/src/components/FileBrowser.js index 61995c85..d69f2150 100644 --- a/app/src/components/FileBrowser.js +++ b/app/src/components/FileBrowser.js @@ -598,7 +598,7 @@ function FileBrowserContent({browseFiles, headers, onFolderClick, setPreviewFile return (
{ - const {s} = React.useContext(ThemeContext); if (headline) { headline = headline.replaceAll('', openTag); headline = headline.replaceAll('', closeTag); headline = headline.replaceAll('\n', '
'); // FTS headlines use ... tags which we will restyle. - return + return } } @@ -26,7 +22,7 @@ const FileHeadline = ({file, to}) => { const posterPath = findPosterPath(file); if (posterPath) { const posterUrl = posterPath ? `/media/${encodeMediaPath(posterPath)}` : null; - poster = ; + poster = poster; } else { poster = ; } @@ -48,32 +44,26 @@ const FileHeadline = ({file, to}) => { ; } - return + return - - {poster} - - - - {header} - - - + {poster} + + + + {header} + +
{body} -
+ } export const Headlines = ({results}) => { if (results === null || results === undefined) { - return - - - - + return } else if (results && results.length === 0) { - return No results! + return No results! } let headlines = []; @@ -93,4 +83,4 @@ export const Headlines = ({results}) => { return <> {headlines} -} \ No newline at end of file +} diff --git a/app/src/components/Share.js b/app/src/components/Share.js index 1b719612..e84c5de6 100644 --- a/app/src/components/Share.js +++ b/app/src/components/Share.js @@ -1,6 +1,5 @@ import React from "react"; -import {Button, Header, Icon, Modal} from "./Theme"; -import {IconGroup} from "semantic-ui-react"; +import {Button, Header, Icon, Modal} from "./ui"; import QRCode from "react-qr-code"; import {sendNotification} from "../api"; @@ -46,19 +45,19 @@ export const ShareButton = () => { Share this page
Another user can scan this QR code to view this page
-
+ {/* `media`: filtered as a unit by night mode; see DonatePage. */} +
- + - - - + -} \ No newline at end of file +} diff --git a/app/src/components/SortableTable.js b/app/src/components/SortableTable.js index 0c238f29..6dd82f9c 100644 --- a/app/src/components/SortableTable.js +++ b/app/src/components/SortableTable.js @@ -1,7 +1,6 @@ import React from "react"; import _ from "lodash"; -import {TableBody, TableCell, TableHeader, TableHeaderCell, TableRow} from "semantic-ui-react"; -import {Table} from "./Theme"; +import {Table} from "./ui"; import {TextPlaceholder} from "./Placeholder"; export class SortableTable extends React.Component { @@ -39,29 +38,29 @@ export class SortableTable extends React.Component { render() { let {rowFunc, tableHeaders, rowKey} = this.props; - let {direction} = this.state; + let {direction, sortColumn} = this.state; rowKey = rowKey || 'key'; const data = this.props['data'] ? this.sortData(this.props['data']) : null; const tableHeader = (spec) => { - const {key, text, sortBy, width} = spec; + const {key, text, sortBy} = spec; if (sortBy) { - return this.changeSort(key)} - width={width || undefined} + sorted={active ? direction : null} + onSort={() => this.changeSort(key)} > {text} - ; + ; } else { - return {text} + return {text} } } // Use placeholder while data is null. - let rows = ; + let rows = ; if (data !== null) { if (data.length > 0) { // Convert data to table rows. @@ -69,19 +68,19 @@ export class SortableTable extends React.Component { } else { // No results in data. rows = this.props.emptyRow - || No results; + || No results; } } - return - - + return
+ + {tableHeaders.map(tableHeader)} - - - + + + {rows} - + {this.props.footer}
} diff --git a/app/src/components/Tables.js b/app/src/components/Tables.js index 7241012e..d5bfea53 100644 --- a/app/src/components/Tables.js +++ b/app/src/components/Tables.js @@ -1,27 +1,26 @@ -import {Table} from "./Theme"; -import {Checkbox, TableBody, TableCell, TableFooter, TableHeader, TableHeaderCell, TableRow} from "semantic-ui-react"; +import {Checkbox, Table} from "./ui"; import React from "react"; export function SelectableTable({headerContents, selectOn, onSelect, selectedKeys, footer, rows}) { - footer = footer ? - + footer = footer ? + {footer} - - : null; + + : null; - return - - - {selectOn && } - {headerContents.map(i => {i})} - - - + return
+ + + {selectOn && } + {headerContents.map(i => {i})} + + + {rows.map(row => {row} )} - + {footer}
} @@ -32,19 +31,19 @@ function SelectableRow(props) { const c = selectedKeys && selectedKeys.indexOf(key) >= 0; let selectCell; if (selectOn) { - const localOnSelect = (e, {checked}) => { + const localOnSelect = (e) => { try { - onSelect(key, checked); + onSelect(key, e.currentTarget.checked); } catch (e) { console.error('No onSelect declared'); } }; - selectCell = + selectCell = - ; + ; } - return + return {selectCell} {props.children} - + } diff --git a/app/src/components/ThemeSamplePage.js b/app/src/components/ThemeSamplePage.js index 67650f84..0777ae96 100644 --- a/app/src/components/ThemeSamplePage.js +++ b/app/src/components/ThemeSamplePage.js @@ -14,12 +14,16 @@ import { Loading, Message, Modal, + Pagination, Panel, Placeholder, Progress, + SearchBox, Select, Statistic, StatisticGroup, + TabBar, + tabClassName, Status, Table, TextInput, @@ -63,6 +67,9 @@ export function ThemeSamplePage() { const [dismissed, setDismissed] = useState(false); const [modalOpen, setModalOpen] = useState(false); const [realColors, setRealColors] = useState(false); + const [search, setSearch] = useState(''); + const [activeTab, setActiveTab] = useState('Videos'); + const [page, setPage] = useState(3); return

Component gallery

@@ -211,8 +218,8 @@ export function ThemeSamplePage() { - URL - Downloader + {}}>URL + {}}>Downloader Progress Status Size @@ -293,6 +300,56 @@ export function ThemeSamplePage() { +
+ + toast({type: 'info', title: 'Searched', description: value})} + onResultSelect={result => setSearch(result.title)} + results={{ + directories: { + name: 'Directories', + results: [{title: 'videos/'}, {title: 'archive/'}], + }, + channels: { + name: 'Channels', + results: [ + {title: 'videos/Wranglerstar', description: 'Wranglerstar'}, + {title: 'videos/RoseRed Homestead', description: 'RoseRed Homestead'}, + ], + }, + }} + clearable + placeholder='Search directory names…' + /> +

+ Focus the field to see grouped suggestions. Arrow keys move, Enter takes the + highlighted one or submits what you typed, Escape closes the list without + clearing the text. +

+
+
+ +
+ + 1,432 videos}> + {['Videos', 'Channels', 'Playlists'].map(tab => )} + + +

+ Night and amber mark the current page with a heavier border rather than a + filled block, which would be a bright surface. The tab bar takes rendered + children, so routing stays with the caller. +

+
+
+
diff --git a/app/src/components/calculators/QRCodeCalculator.js b/app/src/components/calculators/QRCodeCalculator.js index 5ad22847..6446642a 100644 --- a/app/src/components/calculators/QRCodeCalculator.js +++ b/app/src/components/calculators/QRCodeCalculator.js @@ -1,50 +1,36 @@ -import Grid from "semantic-ui-react/dist/commonjs/collections/Grid"; import React from "react"; -import {Header} from "../Theme"; import QRCode from "react-qr-code"; -import {Input} from "semantic-ui-react"; +import {Header, Stack, TextInput} from "../ui"; import {Media} from "../../contexts/contexts"; export function QRCodeCalculator() { const [value, setValue] = React.useState(''); - return - - -
QR Code Calculator
-
-
- - - setValue(e.target.value)} placeholder='Enter link, etc.'/> - - - - - -
- -
-
- -
- -
-
-
-
-
-} \ No newline at end of file + return +
QR Code Calculator
+ setValue(e.target.value)} placeholder='Enter link, etc.'/> + +
+ +
+
+ +
+ +
+
+
+} diff --git a/app/src/components/calculators/TemperatureCalculator.js b/app/src/components/calculators/TemperatureCalculator.js index 979031bb..503bf1d6 100644 --- a/app/src/components/calculators/TemperatureCalculator.js +++ b/app/src/components/calculators/TemperatureCalculator.js @@ -1,7 +1,6 @@ import React from "react"; import {roundDigits} from "../Common"; -import Grid from "semantic-ui-react/dist/commonjs/collections/Grid"; -import {GridColumn, GridRow, Input} from "semantic-ui-react"; +import {Grid, NumberInput} from "../ui"; export function TemperatureCalculator() { const [state, setState] = React.useState({ @@ -10,14 +9,15 @@ export function TemperatureCalculator() { kelvin: '', }) - const handleInputChange = (e, {name, value}) => { - if (value === '') { + const handleInputChange = (name, value) => { + if (value === '' || value === undefined || value === null) { // User has cleared the input; setState({celsius: '', fahrenheit: '', kelvin: ''}); return } - const numValue = parseFloat(value.endsWith('.') ? `${value}0` : value); + const stringValue = `${value}`; + const numValue = parseFloat(stringValue.endsWith('.') ? `${stringValue}0` : stringValue); console.debug(`Calculating ${value} ${name}`); let newCelsius; let newKelvin; @@ -52,25 +52,30 @@ export function TemperatureCalculator() { e.target.select(); } - const commonInputProps = { - fluid: true, - labelPosition: 'right', - type: 'number', - onChange: handleInputChange, - onClick: handleClick - }; - - return - - - - - - - - - - - + return + + handleInputChange('celsius', value)} + onClick={handleClick} + /> + + + handleInputChange('fahrenheit', value)} + onClick={handleClick} + /> + + + handleInputChange('kelvin', value)} + onClick={handleClick} + /> + } diff --git a/app/src/components/calculators/VinDecoderCalculator.js b/app/src/components/calculators/VinDecoderCalculator.js index eeefa6aa..a1839658 100644 --- a/app/src/components/calculators/VinDecoderCalculator.js +++ b/app/src/components/calculators/VinDecoderCalculator.js @@ -1,37 +1,37 @@ -import React, {useContext} from 'react'; -import {Input, TableCell, TableRow} from "semantic-ui-react"; -import {ThemeContext} from "../../contexts/contexts"; +import React from 'react'; import {useVINDecoder} from "../../hooks/customHooks"; -import {Header, Table} from "../Theme"; +import {Header, Table, TextInput} from "../ui"; export function VinDecoderCalculator() { - const {t} = useContext(ThemeContext); - const basicKeys = ['Country', 'Manufacturer', 'Region', 'Years']; const detailsKeys = ['Body', 'Engine', 'Model', 'Plant', 'Transmission', 'Serial']; const {value, setValue, vin} = useVINDecoder(); - let body =

Enter a VIN number above

; + let body =

Enter a VIN number above

; if (value && !vin) { - body =

VIN number is invalid

; + body =

VIN number is invalid

; } if (vin && vin['country']) { - let details =

No details

; + let details =

No details

; if (vin['body']) { - details =
- {detailsKeys.map(i => - {i} - {vin[i.toLowerCase()] || '(Unknown)'} - )} + details =
+ + {detailsKeys.map(i => + {i} + {vin[i.toLowerCase()] || '(Unknown)'} + )} +
; } body = <> - - {basicKeys.map(i => - {i} - {vin[i.toLowerCase()]} - )} +
+ + {basicKeys.map(i => + {i} + {vin[i.toLowerCase()]} + )} +
Details
{details} @@ -40,8 +40,8 @@ export function VinDecoderCalculator() { return <>
VIN Number Decoder
- setValue(e.target.value)} diff --git a/app/src/components/ui/DataTable.tsx b/app/src/components/ui/DataTable.tsx index 81119a44..52532d98 100644 --- a/app/src/components/ui/DataTable.tsx +++ b/app/src/components/ui/DataTable.tsx @@ -1,5 +1,6 @@ import React from 'react'; import {Table as MTable, TableProps as MTableProps} from '@mantine/core'; +import {Icon} from './Icon'; /* * Tables. @@ -54,19 +55,55 @@ function Cell({numeric, style, ...props}: CellProps) { /> } +export type SortDirection = 'ascending' | 'descending'; + +export interface HeaderCellProps extends React.ComponentPropsWithoutRef<'th'> { + /** This column's current sort, or null/undefined when it is not the sorted one. */ + sorted?: SortDirection | null; + /** Makes the header a sort control. Receives nothing; the caller knows its column. */ + onSort?: () => void; +} + +/** + * A header cell, optionally a sort control. + * + * When `onSort` is given the label becomes a real ` + +} + export const Table = Object.assign(TableBase, { Header: MTable.Thead, Body: MTable.Tbody, Footer: MTable.Tfoot, Row, Cell, - HeaderCell: MTable.Th, + HeaderCell, // Mantine's own names, for new code. Thead: MTable.Thead, Tbody: MTable.Tbody, Tfoot: MTable.Tfoot, Tr: Row, Td: Cell, - Th: MTable.Th, + Th: HeaderCell, ScrollContainer: MTable.ScrollContainer, }); diff --git a/app/src/components/ui/Icon.tsx b/app/src/components/ui/Icon.tsx index dffd2c29..c505a43a 100644 --- a/app/src/components/ui/Icon.tsx +++ b/app/src/components/ui/Icon.tsx @@ -92,6 +92,7 @@ const semanticNames: Record = { 'map outline': 'IconMap', 'microchip': 'IconCpu', 'minus': 'IconMinus', + 'paypal': 'IconBrandPaypal', 'play': 'IconPlayerPlay', 'plug': 'IconPlug', 'plus': 'IconPlus', @@ -134,6 +135,29 @@ const semanticNames: Record = { 'x': 'IconX', }; +export interface IconStackProps { + /** The main glyph. */ + children: React.ReactNode; + /** A smaller glyph pinned to the bottom-right, qualifying the first. */ + corner: React.ReactNode; + /** Accessible name for the pair; the two glyphs mean one thing together. */ + label: string; +} + +/** + * Two icons composed into one symbol — a wifi glyph with a question mark on it, + * say. Replaces Semantic's IconGroup. + * + * The corner glyph gets a background matching the surface so it stays legible + * over the icon beneath it. + */ +export function IconStack({children, corner, label}: IconStackProps) { + return + {children} + + +} + export interface IconProps extends Omit, 'name' | 'ref'> { /** A Semantic UI icon name, for migrated call sites. */ name?: string; diff --git a/app/src/components/ui/Navigation.tsx b/app/src/components/ui/Navigation.tsx new file mode 100644 index 00000000..ef02c2f2 --- /dev/null +++ b/app/src/components/ui/Navigation.tsx @@ -0,0 +1,74 @@ +import React from 'react'; +import {Pagination as MPagination} from '@mantine/core'; + +/* + * Navigation: pagination and tab bars. + * + * Neither knows anything about routing — the app owns its links. The tab bar + * takes rendered children and supplies only the strip and its house style, so + * call sites keep using react-router's NavLink and its `isActive` render prop. + */ + +// --------------------------------------------------------------- Pagination + +export interface PaginationProps { + /** 1-based. */ + activePage: number; + totalPages?: number; + onPageChange: (page: number) => void; + /** Pages shown either side of the active one. Fewer on a phone. */ + siblingRange?: number; + /** Include jump-to-first and jump-to-last controls. */ + showFirstAndLast?: boolean; + size?: string; + disabled?: boolean; +} + +/** + * Page controls. Replaces Semantic's Pagination, keeping its prop names + * (`activePage`, `totalPages`, `onPageChange`) so call sites migrate as a + * rename — but `onPageChange` receives the page number directly rather than + * Semantic's `(event, data)` pair. + */ +export function Pagination({ + activePage, + totalPages, + onPageChange, + siblingRange = 2, + showFirstAndLast = false, + size = 'sm', + disabled, +}: PaginationProps) { + return ({'aria-label': `Page ${page}`})} + /> +} + +// ----------------------------------------------------------------- Tab bars + +/** A row of tabs. Children are the links; routing stays with the caller. */ +export function TabBar({children, right}: {children: React.ReactNode; right?: React.ReactNode}) { + return +} + +/** + * Class name for one tab. Exported rather than baked into a component so a + * caller can hand it straight to NavLink's `className` render prop, which is + * how the app decides what is active. + */ +export const tabClassName = (active: boolean): string => + `wrolpi-tab${active ? ' wrolpi-tab-active' : ''}`; diff --git a/app/src/components/ui/SearchBox.tsx b/app/src/components/ui/SearchBox.tsx new file mode 100644 index 00000000..affd60f7 --- /dev/null +++ b/app/src/components/ui/SearchBox.tsx @@ -0,0 +1,230 @@ +import React, {useEffect, useId, useRef, useState} from 'react'; +import {Icon} from './Icon'; +import {IconButton} from './Button'; +import {Loader} from './Feedback'; + +/* + * The search box, with optional grouped suggestions. + * + * Replaces Semantic's ``, and deliberately keeps its `results` + * shape — `{groupKey: {name, results: [{title, description}]}}` — because four + * call sites already build that structure from the API. + * + * Suggestions are a combobox: the input keeps focus and owns the keyboard, while + * `aria-activedescendant` points at the highlighted option. Arrow keys move, + * Enter takes the highlighted suggestion or submits what was typed, Escape + * closes the list without clearing the text. + */ + +export interface SearchResult { + /** The value put into the input when chosen. Also the visible first line. */ + title: string; + /** Second line, for context: a channel name, a domain. */ + description?: string; + + [key: string]: any; +} + +export interface SearchResultGroup { + /** Group heading. */ + name: string; + results: SearchResult[]; +} + +export type SearchResults = Record; + +export interface SearchBoxProps { + value?: string; + onChange?: (value: string) => void; + /** Enter, or the search button. Receives the current text. */ + onSubmit?: (value: string) => void; + /** Called with the chosen suggestion. */ + onResultSelect?: (result: SearchResult) => void; + onBlur?: React.FocusEventHandler; + results?: SearchResults; + /** Suggestions are being fetched; shows a spinner rather than "no results". */ + loading?: boolean; + placeholder?: string; + /** Show a button that empties the input. */ + clearable?: boolean; + /** Force the clear button's disabled state; defaults to "nothing typed". */ + clearDisabled?: boolean | null; + onClear?: () => void; + disabled?: boolean; + required?: boolean; + inputRef?: React.Ref; + /** Accessible name. Falls back to the placeholder. */ + label?: string; + className?: string; + autoFocus?: boolean; + name?: string; +} + +/** Flatten the groups into the order they are displayed, for keyboard movement. */ +const flatten = (results?: SearchResults): SearchResult[] => + Object.values(results ?? {}).flatMap(group => group?.results ?? []); + +export function SearchBox({ + value, + onChange, + onSubmit, + onResultSelect, + onBlur, + results, + loading, + placeholder = 'Search...', + clearable, + clearDisabled = null, + onClear, + disabled, + required, + inputRef, + label, + className, + autoFocus, + name, +}: SearchBoxProps) { + const [open, setOpen] = useState(false); + const [highlighted, setHighlighted] = useState(-1); + const containerRef = useRef(null); + const listId = useId(); + + const text = value ?? ''; + const flat = flatten(results); + const hasSuggestions = onResultSelect !== undefined || !!results; + + // Close when focus or a click leaves the box entirely. A blur handler alone would + // fire before a click on a suggestion registers. + useEffect(() => { + if (!open) return; + const onDocumentClick = (event: MouseEvent) => { + if (!containerRef.current?.contains(event.target as Node)) setOpen(false); + }; + document.addEventListener('mousedown', onDocumentClick); + return () => document.removeEventListener('mousedown', onDocumentClick); + }, [open]); + + const choose = (result: SearchResult) => { + setOpen(false); + setHighlighted(-1); + onResultSelect?.(result); + } + + const handleChange = (event: React.ChangeEvent) => { + setHighlighted(-1); + if (hasSuggestions) setOpen(true); + onChange?.(event.currentTarget.value); + } + + const handleKeyDown = (event: React.KeyboardEvent) => { + if (event.key === 'ArrowDown' || event.key === 'ArrowUp') { + if (!flat.length) return; + event.preventDefault(); + setOpen(true); + const step = event.key === 'ArrowDown' ? 1 : -1; + setHighlighted(current => { + // Wrap, so holding a key cannot strand the user at either end. + const next = current + step; + if (next < 0) return flat.length - 1; + if (next >= flat.length) return 0; + return next; + }); + } else if (event.key === 'Enter') { + event.preventDefault(); + if (open && highlighted >= 0 && flat[highlighted]) { + choose(flat[highlighted]); + } else { + setOpen(false); + onSubmit?.(text); + } + } else if (event.key === 'Escape') { + // Closes the list; the typed text is left alone. + setOpen(false); + setHighlighted(-1); + } + } + + const handleClear = () => { + onChange?.(''); + onSubmit?.(''); + onClear?.(); + setOpen(false); + } + + let index = -1; + + return
+
+ + hasSuggestions && (flat.length > 0 || loading) && setOpen(true)} + onBlur={onBlur} + role={hasSuggestions ? 'combobox' : undefined} + aria-expanded={hasSuggestions ? open : undefined} + aria-controls={hasSuggestions ? listId : undefined} + aria-autocomplete={hasSuggestions ? 'list' : undefined} + aria-activedescendant={open && highlighted >= 0 ? `${listId}-${highlighted}` : undefined} + /> + {loading && } + {clearable && } +
+ + {open && hasSuggestions &&
+ {loading && !flat.length &&
Searching…
} + {!loading && !flat.length &&
No results
} + {Object.entries(results ?? {}).map(([key, group]) => { + if (!group?.results?.length) return null; + return
+
{group.name}
+ {group.results.map((result, resultIndex) => { + index += 1; + const optionIndex = index; + return
{ + event.preventDefault(); + choose(result); + }} + onMouseEnter={() => setHighlighted(optionIndex)} + > +
{result.title}
+ {result.description &&
+ {result.description} +
} +
+ })} +
+ })} +
} +
+} diff --git a/app/src/components/ui/index.ts b/app/src/components/ui/index.ts index cb36342e..6e2ae8d5 100644 --- a/app/src/components/ui/index.ts +++ b/app/src/components/ui/index.ts @@ -16,6 +16,8 @@ export * from './Button'; export * from './Feedback'; export * from './Surfaces'; export * from './DataTable'; +export * from './Navigation'; +export * from './SearchBox'; export * from './Inputs'; export * from './Overlays'; export * from './ThemePicker'; diff --git a/app/src/components/ui/ui.css b/app/src/components/ui/ui.css index 64bd8911..a99d1641 100644 --- a/app/src/components/ui/ui.css +++ b/app/src/components/ui/ui.css @@ -26,6 +26,26 @@ } } +.wrolpi-icon-stack { + position: relative; + display: inline-flex; + line-height: 0; +} + +/* + * The corner glyph sits on the main one, so it carries the surface color behind + * it — without that the two sets of strokes cross and neither reads. + */ +.wrolpi-icon-stack-corner { + position: absolute; + right: -3px; + bottom: -3px; + display: flex; + background: var(--bg); + border-radius: 50%; + padding: 1px; +} + /* ---------------------------------------------------------------- Buttons */ /* * Dashed borders mean "destructive or failed", and nothing else may use them. @@ -117,6 +137,188 @@ html[data-theme="amber"] .wrolpi-theme-option-active { border-top: 1px solid var(--border); } +/* ------------------------------------------------------------ Pagination */ + +.wrolpi-pagination button { + background: var(--panel); + color: var(--text); + border: 1px solid var(--border); +} + +.wrolpi-pagination button[data-active] { + background: var(--blue); + color: var(--btn-text); + border-color: var(--blue); +} + +/* Night and amber have no second hue to spend, so the current page is marked by a + heavier border and the panel surface instead of a filled block of color. */ +html[data-theme="night"] .wrolpi-pagination button[data-active], +html[data-theme="amber"] .wrolpi-pagination button[data-active] { + background: var(--panel); + color: var(--text); + border: 2px solid var(--text); +} + +.wrolpi-pagination button:disabled { + color: var(--muted); + background: var(--bg); +} + +/* ---------------------------------------------------------------- Tab bar */ + +.wrolpi-tabs { + display: flex; + align-items: flex-end; + justify-content: space-between; + gap: 12px; + border-bottom: 1px solid var(--border); + margin-bottom: 14px; +} + +.wrolpi-tabs-links { + display: flex; + flex-wrap: wrap; +} + +.wrolpi-tabs-right { + padding-bottom: 6px; +} + +.wrolpi-tab { + display: inline-block; + padding: 8px 14px; + color: var(--muted); + text-decoration: none; + font-size: 13px; + border: 1px solid transparent; + /* Sits on the bar's own rule, so the active tab can erase it and read as + connected to the panel below. */ + margin-bottom: -1px; +} + +.wrolpi-tab:hover { + color: var(--text); +} + +.wrolpi-tab-active { + color: var(--text); + background: var(--panel); + border-color: var(--border); + border-bottom-color: var(--panel); + font-weight: 600; +} + +.wrolpi-tab:focus-visible { + outline: 2px solid var(--blue); + outline-offset: -2px; +} + +/* ------------------------------------------------------------- Search box */ + +.wrolpi-searchbox { + position: relative; + width: 100%; +} + +.wrolpi-searchbox-control { + display: flex; + align-items: center; + gap: 8px; + background: var(--panel); + border: 1px solid var(--border); + padding: 0 8px; +} + +.wrolpi-searchbox-control:focus-within { + border-color: var(--blue); +} + +html[data-theme="night"] .wrolpi-searchbox-control:focus-within, +html[data-theme="amber"] .wrolpi-searchbox-control:focus-within { + border-color: var(--text); +} + +.wrolpi-searchbox-icon { + display: flex; + color: var(--muted); +} + +.wrolpi-searchbox-input { + flex: 1; + min-width: 0; + padding: 8px 0; + background: none; + border: none; + outline: none; + color: var(--text); + font: inherit; + font-size: 13px; +} + +.wrolpi-searchbox-input::placeholder { + color: var(--muted); +} + +.wrolpi-searchbox-loading, +.wrolpi-searchbox-clear { + flex: none; +} + +/* + * The suggestion list overlays the page rather than pushing it down — a search + * that reflows the results underneath it is unusable while typing. + */ +.wrolpi-searchbox-results { + position: absolute; + z-index: 20; + top: 100%; + left: 0; + right: 0; + max-height: 320px; + overflow-y: auto; + background: var(--panel); + border: 1px solid var(--border); + border-top: none; +} + +.wrolpi-searchbox-group-name { + padding: 6px 10px; + font-size: 11px; + font-weight: 600; + letter-spacing: 0.08em; + text-transform: uppercase; + color: var(--muted); + background: var(--head); +} + +.wrolpi-searchbox-result { + padding: 7px 10px; + cursor: pointer; + border-top: 1px solid var(--border); +} + +.wrolpi-searchbox-result-active { + background: var(--head); +} + +.wrolpi-searchbox-result-title { + font-size: 13px; + color: var(--text); + overflow-wrap: anywhere; +} + +.wrolpi-searchbox-result-description { + font-size: 11px; + color: var(--muted); +} + +.wrolpi-searchbox-empty { + padding: 10px; + font-size: 12px; + color: var(--muted); +} + /* ---------------------------------------------------------------- Modals */ /* * Actions sit below the body, separated by a hairline rather than a raised bar. @@ -460,6 +662,41 @@ html[data-theme="night"] .wrolpi-status-failed { /* ----------------------------------------------------------------- Tables */ +/* A sortable header: a real button, so the column is reachable by keyboard. */ +.wrolpi-th-sort { + display: inline-flex; + align-items: center; + gap: 5px; + background: none; + border: none; + padding: 0; + margin: 0; + font: inherit; + color: inherit; + cursor: pointer; + white-space: nowrap; +} + +/* The unsorted columns show a faint arrow: the affordance is visible, but it does + not compete with the column actually doing the sorting. */ +.wrolpi-th-sort-idle { + opacity: 0.35; +} + +.wrolpi-th-sort:hover .wrolpi-th-sort-idle { + opacity: 0.7; +} + +.wrolpi-th-sort:focus-visible { + outline: 2px solid var(--blue); + outline-offset: 2px; +} + +html[data-theme="night"] .wrolpi-th-sort:focus-visible, +html[data-theme="amber"] .wrolpi-th-sort:focus-visible { + outline-color: var(--text); +} + /* A failed row carries the danger border, matching failed messages. */ .wrolpi-row-failed > td { border-top: 1.5px dashed var(--red); diff --git a/app/src/components/ui/ui.test.js b/app/src/components/ui/ui.test.js index f6f59782..3cfdc35d 100644 --- a/app/src/components/ui/ui.test.js +++ b/app/src/components/ui/ui.test.js @@ -12,6 +12,11 @@ import { Confirm, Header, Icon, + IconStack, + Pagination, + SearchBox, + TabBar, + tabClassName, IconButton, Label, Message, @@ -280,6 +285,30 @@ describe('Table', () => { expect(container.querySelector('.wrolpi-row-failed')).toBeInTheDocument(); }); + it('makes a sortable column a keyboard-reachable button that announces its state', async () => { + // A click handler on the alone is unreachable by keyboard, and the arrow + // glyph says nothing to a screen reader. + const onSort = jest.fn(); + renderUI( + + + Size + Name + Actions + + +
); + + expect(screen.getByRole('columnheader', {name: /Size/})).toHaveAttribute('aria-sort', 'descending'); + // Sortable but not currently sorted. + expect(screen.getByRole('columnheader', {name: /Name/})).toHaveAttribute('aria-sort', 'none'); + // Not sortable at all. + expect(screen.getByRole('columnheader', {name: 'Actions'})).not.toHaveAttribute('aria-sort'); + + await userEvent.click(screen.getByRole('button', {name: /Size/})); + expect(onSort).toHaveBeenCalled(); + }); + it('keeps wide tables from scrolling the page sideways', () => { const {container} = renderUI( wide @@ -409,6 +438,160 @@ describe('ThemePicker', () => { }); }); +describe('Pagination', () => { + it('reports the current page and moves when one is clicked', async () => { + const onPageChange = jest.fn(); + renderUI(); + + await userEvent.click(screen.getByRole('button', {name: 'Page 5'})); + + expect(onPageChange).toHaveBeenCalledWith(5); + }); + + it('still renders one page when the total is unknown', () => { + // Downloads render the paginator before the first response arrives; collapsing to + // nothing and back shifts the whole page. + renderUI(); + + expect(screen.getByRole('button', {name: 'Page 1'})).toBeInTheDocument(); + }); +}); + +describe('TabBar', () => { + it('marks the active tab with a class the themes key on', () => { + const {container} = renderUI( + + + ); + + expect(container.querySelectorAll('.wrolpi-tab')).toHaveLength(2); + expect(container.querySelectorAll('.wrolpi-tab-active')).toHaveLength(1); + }); +}); + +describe('SearchBox', () => { + const results = { + directories: {name: 'Directories', results: [{title: 'videos/'}]}, + channels: {name: 'Channels', results: [ + {title: 'videos/Wranglerstar', description: 'Wranglerstar'}, + {title: 'videos/RoseRed', description: 'RoseRed Homestead'}, + ]}, + }; + + it('submits what was typed', async () => { + const onSubmit = jest.fn(); + renderUI(); + + await userEvent.type(screen.getByRole('textbox'), '{Enter}'); + + expect(onSubmit).toHaveBeenCalledWith('axe'); + }); + + it('shows suggestions under their group headings', async () => { + renderUI(); + + await userEvent.click(screen.getByRole('combobox')); + + expect(screen.getByText('Directories')).toBeInTheDocument(); + expect(screen.getAllByRole('option')).toHaveLength(3); + }); + + it('selects a suggestion by click', async () => { + const onResultSelect = jest.fn(); + renderUI(); + await userEvent.click(screen.getByRole('combobox')); + + await userEvent.click(screen.getByText('videos/Wranglerstar')); + + expect(onResultSelect).toHaveBeenCalledWith( + expect.objectContaining({title: 'videos/Wranglerstar'})); + }); + + it('moves through suggestions with the arrow keys and takes one with Enter', async () => { + const onResultSelect = jest.fn(); + const onSubmit = jest.fn(); + renderUI(); + + const input = screen.getByRole('combobox'); + await userEvent.click(input); + await userEvent.keyboard('{ArrowDown}{ArrowDown}{Enter}'); + + expect(onResultSelect).toHaveBeenCalledWith( + expect.objectContaining({title: 'videos/Wranglerstar'})); + // Enter took the highlighted suggestion instead of submitting the raw text. + expect(onSubmit).not.toHaveBeenCalled(); + }); + + it('wraps around rather than stranding the user at the end of the list', async () => { + const onResultSelect = jest.fn(); + renderUI(); + + await userEvent.click(screen.getByRole('combobox')); + await userEvent.keyboard('{ArrowUp}{Enter}'); + + expect(onResultSelect).toHaveBeenCalledWith( + expect.objectContaining({title: 'videos/RoseRed'})); + }); + + it('closes on Escape without clearing what was typed', async () => { + const onChange = jest.fn(); + renderUI(); + await userEvent.click(screen.getByRole('combobox')); + + await userEvent.keyboard('{Escape}'); + + expect(screen.queryByRole('option')).not.toBeInTheDocument(); + expect(screen.getByRole('combobox')).toHaveValue('vid'); + expect(onChange).not.toHaveBeenCalled(); + }); + + it('says it is searching rather than "no results" while suggestions are pending', async () => { + renderUI(); + + await userEvent.click(screen.getByRole('combobox')); + + expect(screen.getByText(/searching/i)).toBeInTheDocument(); + }); + + it('clears the input and submits the empty search', async () => { + const onChange = jest.fn(); + const onSubmit = jest.fn(); + renderUI(); + + await userEvent.click(screen.getByRole('button', {name: 'Clear search'})); + + expect(onChange).toHaveBeenCalledWith(''); + expect(onSubmit).toHaveBeenCalledWith(''); + }); + + it('is a plain search field when no suggestions are wired up', () => { + // Without this, a box that can never show options still claims to be a combobox. + renderUI(); + + expect(screen.queryByRole('combobox')).not.toBeInTheDocument(); + expect(screen.getByRole('textbox')).toBeInTheDocument(); + }); +}); + +describe('IconStack', () => { + it('names the pair once, and hides the corner glyph from assistive tech', () => { + const {container} = renderUI( + } label='WiFi status unknown'> + + + ); + + expect(screen.getByRole('img', {name: 'WiFi status unknown'})).toBeInTheDocument(); + expect(container.querySelector('.wrolpi-icon-stack-corner')).toHaveAttribute('aria-hidden', 'true'); + }); +}); + describe('Confirm', () => { it('names the action on its confirming button', async () => { const onConfirm = jest.fn(); diff --git a/app/src/semantic-baseline.json b/app/src/semantic-baseline.json index 9f4e7af7..5c858fca 100644 --- a/app/src/semantic-baseline.json +++ b/app/src/semantic-baseline.json @@ -14,14 +14,11 @@ "src/components/Common.js", "src/components/DatesSelector.js", "src/components/Docs.js", - "src/components/DonatePage.js", "src/components/Download.js", - "src/components/ErrorBoundary.js", "src/components/FileBrowser.js", "src/components/FilePreview.js", "src/components/Files.js", "src/components/Flasher.js", - "src/components/Headline.js", "src/components/HelpModal.js", "src/components/Map.js", "src/components/MapSearchView.js", @@ -30,9 +27,6 @@ "src/components/Placeholder.js", "src/components/Playlists.js", "src/components/Search.js", - "src/components/Share.js", - "src/components/SortableTable.js", - "src/components/Tables.js", "src/components/TaggedDeleteConfirmModal.js", "src/components/Theme.tsx", "src/components/Upload.js", @@ -48,11 +42,8 @@ "src/components/calculators/FoodStorageCalculator.js", "src/components/calculators/HamCalculators.js", "src/components/calculators/OneTimePadCalculator.js", - "src/components/calculators/QRCodeCalculator.js", "src/components/calculators/RatioCalculator.js", "src/components/calculators/RationCalculator.js", - "src/components/calculators/TemperatureCalculator.js", - "src/components/calculators/VinDecoderCalculator.js", "src/components/calculators/WaterCalculator.js", "src/components/collections/BatchReorganizeModal.js", "src/components/collections/CollectionEditForm.js", From 851485ef1b4573db7aa93cc41fac7cbd52fab183 Mon Sep 17 00:00:00 2001 From: Roland Date: Thu, 30 Jul 2026 10:00:48 -0600 Subject: [PATCH 02/31] 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 `` 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. --- app/src/components/AddToPlaylist.js | 71 +- app/src/components/Apps.js | 135 ++- app/src/components/ArchivePreview.js | 27 +- app/src/components/CbzViewer.js | 36 +- app/src/components/Common.js | 887 +++++++----------- app/src/components/Common.test.js | 48 +- app/src/components/DesktopToggle.test.js | 8 +- app/src/components/FileBrowser.test.js | 4 +- app/src/components/Placeholder.js | 53 +- app/src/components/SearchFilterModal.test.js | 26 +- .../components/TaggedDeleteConfirmModal.js | 57 +- app/src/components/VncToggle.test.js | 2 +- .../calculators/RationCalculator.test.js | 2 +- .../collections/CollectionEditForm.js | 57 +- .../collections/CollectionEditForm.test.js | 23 +- .../collections/CollectionTagModal.js | 66 +- .../collections/CollectionTagModal.test.js | 37 +- .../ConflictResolutionModal.test.js | 7 +- app/src/components/inventory/CatalogEditor.js | 111 ++- .../inventory/InventoryExportPanel.js | 47 +- .../inventory/InventoryItemsMobile.js | 39 +- .../inventory/InventoryItemsMobile.test.js | 19 +- .../components/inventory/InventorySummary.js | 70 +- .../inventory/InventorySummary.test.js | 9 +- app/src/components/ui/Button.tsx | 26 + app/src/components/ui/Icon.tsx | 18 +- app/src/components/ui/Surfaces.tsx | 7 +- app/src/components/ui/ui.css | 73 ++ app/src/components/ui/ui.test.js | 36 + app/src/hooks/customHooks.test.js | 2 +- app/src/hooks/useForm.test.js | 2 +- app/src/hooks/useKeyboardShortcuts.test.js | 23 +- app/src/semantic-baseline.json | 13 - app/src/semantic-baseline.test.js | 17 + app/src/setupTests.js | 15 + 35 files changed, 978 insertions(+), 1095 deletions(-) diff --git a/app/src/components/AddToPlaylist.js b/app/src/components/AddToPlaylist.js index af717c33..3e282f79 100644 --- a/app/src/components/AddToPlaylist.js +++ b/app/src/components/AddToPlaylist.js @@ -1,8 +1,5 @@ import React, {useEffect, useState} from "react"; -import {Input, Message} from "semantic-ui-react"; -import {toast} from "react-semantic-toasts-2"; - -import {Button, Form, List, Loader, Modal} from "./Theme"; +import {Button, IconButton, Loading, Message, Modal, Radio, Stack, TextInput, toast} from "./ui"; import {addPlaylistItem, createPlaylist, fetchPlaylists} from "../api"; @@ -68,32 +65,38 @@ export function AddToPlaylistModal({open, onClose, items = [], onComplete}) { return Add to Playlist - {playlists === undefined && Could not load playlists} - {playlists === null && } + {playlists === undefined && } + {playlists === null && } {Array.isArray(playlists) && playlists.length > 0 && - - {playlists.map(p => setSelected(p.id)}> - - {p.name} - )} - } + + {playlists.map(p => setSelected(p.id)} + />)} + } {Array.isArray(playlists) && playlists.length === 0 &&

No playlists yet — create one below.

} -
- - - setNewName(value)}/> - - +
{ + e.preventDefault(); + handleCreateAndAdd(); + }} style={{marginTop: '1em'}}> + setNewName(e.currentTarget.value)} + /> +
- + {creating - ? - : } + ? + : }
; } @@ -104,9 +107,12 @@ export function AddToPlaylistModal({open, onClose, items = [], onComplete}) { * - one FileGroup (fileGroupId) or many (fileGroupIds), * - a Zim article (zim={zimId, entry, title}), or * - a URL (url={url, title}) — link to anything the WROLPi browser can open (e.g. a map location). - * Extra props are forwarded to the Button (color, size, disabled, icon, content, ...). + * Extra props are forwarded to the Button (size, disabled, ...). */ -export function AddToPlaylistButton({fileGroupId, fileGroupIds, zim, url, content = 'Add to Playlist', onComplete, ...buttonProps}) { +export function AddToPlaylistButton({ + fileGroupId, fileGroupIds, zim, url, content = 'Add to Playlist', + title, onComplete, ...buttonProps + }) { const [open, setOpen] = useState(false); let items; @@ -119,13 +125,16 @@ export function AddToPlaylistButton({fileGroupId, fileGroupIds, zim, url, conten items = ids.map(id => ({item_kind: 'file', file_group_id: id})); } - // An empty `content` makes a compact icon-only button (omit content entirely so Semantic does - // not reserve label padding); otherwise render the labeled "Add to Playlist" button. - const contentProps = content ? {content} : {}; + // An empty/null `content` makes a compact icon-only button; the accessible name comes + // from `title` (kept for callers that already pass it) or falls back to the action name. + const iconOnly = !content; return <> - } setOpen(false)} items={items} onComplete={onComplete}/> ; diff --git a/app/src/components/Apps.js b/app/src/components/Apps.js index 5085c65b..d7f1093c 100644 --- a/app/src/components/Apps.js +++ b/app/src/components/Apps.js @@ -1,5 +1,4 @@ -import React, {useContext} from 'react'; -import {Input, Label, StatisticLabel, StatisticValue} from "semantic-ui-react"; +import React from 'react'; import {Link, Route, Routes} from "react-router"; import { ErrorMessage, @@ -10,16 +9,13 @@ import { toLocaleString, useTitle } from "./Common"; -import {ThemeContext} from "../contexts/contexts"; -import {Header, Loader, Segment, Statistic} from "./Theme"; +import {Header, Label, Loading, Panel, Statistic, StatisticGroup, TextInput} from "./ui"; import {useStatistics} from "../hooks/customHooks"; import {CalculatorsPage} from "./Calculators"; function StatisticsPage() { useTitle('Statistics'); - const {s} = useContext(ThemeContext); - const {statistics} = useStatistics(); if (statistics === undefined) { @@ -49,90 +45,56 @@ function StatisticsPage() { return <>
Statistics
Files
- - - - {toLocaleString(total_count)} - All Files - - - {humanFileSize(total_size)} - Total Size - - - - - + + + + + + + + - - {toLocaleString(video_count)} - Videos - + - - {toLocaleString(pdf_count)} - PDFs - - - {toLocaleString(ebook_count)} - eBooks - - - {toLocaleString(archive_count)} - Archives - - - {toLocaleString(image_count)} - Images - - - - - - - {toLocaleString(zip_count)} - ZIP - - - {toLocaleString(audio_count)} - Audio - - - + + + + + + + + + + + +
Tags
- - - - {humanNumber(tags_count)} - Tags - - - {humanNumber(tagged_files)} - Tagged Files - - - {humanNumber(tagged_zims)} - Tagged Zims - - - + + + + + + +
Database
- - - - {humanFileSize(db_size)} - Size - - - + + + + + ; } return <>
Statistics
- + ; } @@ -146,7 +108,16 @@ export function MoreRoute(props) { } -export function ColoredInput({name, value, label, color, ...props}) { - label = label ? : null; - return +/** + * A text input with a colored tag attached to its leading (or trailing) edge. + * Replaces Semantic's `} labelPosition=.../>`. + */ +export function ColoredInput({name, value, label, color, labelPosition = 'left', fluid, style, ...props}) { + const labelNode = label ? : null; + + return
+ {labelNode && labelPosition === 'left' && labelNode} + + {labelNode && labelPosition !== 'left' && labelNode} +
} diff --git a/app/src/components/ArchivePreview.js b/app/src/components/ArchivePreview.js index cdbb7df4..3c959a96 100644 --- a/app/src/components/ArchivePreview.js +++ b/app/src/components/ArchivePreview.js @@ -1,8 +1,7 @@ import React from "react"; -import {Icon, Loader, Message, Placeholder, PlaceholderLine} from "semantic-ui-react"; import {downloadArchiveMember, getArchiveContents} from "../api"; import {fileSuffixIconName, humanFileSize} from "./Common"; -import {Modal, Segment, Table} from "./Theme"; +import {Icon, Message, Modal, Panel, Placeholder, Table} from "./ui"; function ArchiveEntry({entry, depth, archivePath}) { const [expanded, setExpanded] = React.useState(depth === 0); @@ -19,9 +18,9 @@ function ArchiveEntry({entry, depth, archivePath}) { {indent} - {entry.name}/ + {' '}{entry.name}/ - + — @@ -37,11 +36,11 @@ function ArchiveEntry({entry, depth, archivePath}) { {indent} - {entry.name} + {' '}{entry.name} {' '} - + - + {humanFileSize(entry.size)} @@ -52,7 +51,7 @@ function SkeletonRows() { {[1, 2, 3].map(i => - + )} @@ -88,24 +87,24 @@ export function ArchivePreviewContent({previewFile}) { if (error) { return - - Cannot read archive +

{error}

} return - {!loading && contents && + {!loading && contents && + {' '} {contents.total_files} files,{' '} {humanFileSize(contents.total_size)} total - } -
+ } +
Name - Size + Size diff --git a/app/src/components/CbzViewer.js b/app/src/components/CbzViewer.js index 7690ad33..9e3feaa4 100644 --- a/app/src/components/CbzViewer.js +++ b/app/src/components/CbzViewer.js @@ -1,7 +1,7 @@ import React, {useCallback, useEffect, useRef, useState} from 'react'; +import {IconArrowLeft, IconArrowRight} from '@tabler/icons-react'; import {getArchiveContents, getArchiveMemberUrl} from '../api'; -import {Icon, Label, Loader, Message} from 'semantic-ui-react'; -import {Button} from './Theme'; +import {IconButton, Label, Loading, Message} from './ui'; import {useLocalStorage} from './Common'; const IMAGE_EXTENSIONS = /\.(jpe?g|png|gif|webp|bmp|tiff?)$/i; @@ -77,15 +77,13 @@ export function CbzViewer({path}) { }, [onLeftClick, onRightClick]); if (error) { - return - Cannot load comic + return

{error}

; } - if (!pages) return ; + if (!pages) return ; if (pages.length === 0) { - return - No images found + return

This archive does not contain any image files.

; } @@ -94,12 +92,12 @@ export function CbzViewer({path}) { const hasNext = currentPage < pages.length - 1; return
-
- + setRtl(r => !r)}/> - + - +
; } diff --git a/app/src/components/Common.js b/app/src/components/Common.js index 5b8f5363..a83fb145 100644 --- a/app/src/components/Common.js +++ b/app/src/components/Common.js @@ -1,83 +1,52 @@ import React, {useContext, useEffect, useState} from "react"; -import { - AccordionContent, - AccordionTitle, - BreadcrumbSection, - Button as SButton, - ButtonGroup, - Card, - Container, - Dimmer, - DimmerDimmable, - Dropdown, - GridColumn, - GridRow, - Icon as SIcon, - IconGroup, - Input, - Label, - Pagination, - Search, - Transition -} from 'semantic-ui-react'; import {Link, NavLink, useNavigate} from "react-router"; -import Message from "semantic-ui-react/dist/commonjs/collections/Message"; -import {useBluetooth, useDesktop, useHotspot, useSearchDirectories, useSearchOrder, useThrottle, useVnc, useWROLMode} from "../hooks/customHooks"; -import {Media, SettingsContext, StatusContext, ThemeContext} from "../contexts/contexts"; import { Accordion, - Breadcrumb, + Breadcrumbs as UIBreadcrumbs, Button, - Card as ThemedCard, + ButtonGroup, + CardGroup, Confirm, - Form, Header, Icon, - Loader, + IconButton, + IconStack, + Label, + Loading, Menu, + Message, Modal, - Popup, - Segment, + Pagination, + Panel, + SearchBox, Statistic, - systemTheme, - themeChoices -} from "./Theme"; + TabBar, + tabClassName, + TextInput, + Toggle as UIToggle, + Tooltip, +} from "./ui"; +import {useBluetooth, useDesktop, useHotspot, useSearchDirectories, useSearchOrder, useThrottle, useVnc, useWROLMode} from "../hooks/customHooks"; +import {Media, SettingsContext, StatusContext, ThemeContext} from "../contexts/contexts"; +import {themeChoices} from "./Theme"; import {FilePreviewContext} from "./FilePreview"; import _ from "lodash"; import {killDownloads, startDownloads, unlockCookies} from "../api"; -import {allFrequencyOptions, HELP_VIEWER_URI, NAME, semanticUIColorMap, validUrlRegex} from "./Vars"; -import Grid from "semantic-ui-react/dist/commonjs/collections/Grid"; +import {allFrequencyOptions, HELP_VIEWER_URI, NAME, validUrlRegex} from "./Vars"; export function Paginator({activePage, onPageChange, totalPages, showFirstAndLast, size = 'mini'}) { - const handlePageChange = (e, {activePage}) => { - onPageChange(activePage); - } + // Fewer page numbers on a phone: the strip has to fit without wrapping. + const pager = (siblingRange) => ; return <> - - - - - - + {pager(1)} + {pager(3)} } @@ -142,11 +111,9 @@ export function secondsToElapsedPopup(seconds) { if (!elapsed) { return <>; } - return {elapsed}} - /> + return + {elapsed} + } export function isoDatetimeToElapsedPopup(dt) { @@ -161,12 +128,9 @@ export function isoDatetimeToAgoPopup(dt, short = true) { if (seconds === 0 || !elapsed) { return <>; } - const trigger = {isoDatetimeToString(dt)}; - return {elapsed} ago} - on='hover' - trigger={trigger} - /> + return + {isoDatetimeToString(dt)} + } export function secondsToHMS(totalSeconds) { @@ -431,86 +395,37 @@ export function scrollToTopOfElement(element, smooth = true) { }); } -const useClearableInput = (searchStr, onChange, onClear, onSubmit, size = 'small', placeholder = 'Search...', icon = 'search', clearDisabled = null, inputRef = null) => { +/** + * Shared behaviour for the search inputs: keep a local value so typing is not + * throttled by the parent, but follow `searchStr` when it changes underneath. + */ +const useSearchValue = (searchStr, onChange) => { const [value, setValue] = useState(searchStr || ''); - const [submitted, setSubmitted] = useState(false); React.useEffect(() => { - // `searchStr` is the source of truth from the parent (often an async URL query param). - // Depend ONLY on `searchStr` -- never on `value` -- otherwise a transient render where the - // local `value` has advanced (e.g. "ex") but `searchStr` still trails ("e") fires this - // effect and reverts `value`, garbling fast typing (flaky filter test). + // `searchStr` is the source of truth from the parent (often an async URL query + // param). Depend ONLY on `searchStr` -- never on `value` -- otherwise a transient + // render where the local `value` has advanced ("ex") but `searchStr` still trails + // ("e") fires this effect and reverts `value`, garbling fast typing. if ((searchStr || '') !== value) { setValue(searchStr || ''); } + // eslint-disable-next-line react-hooks/exhaustive-deps }, [searchStr]); - const handleChange = (e) => { - if (e) { - e.preventDefault(); - } - setValue(e.target.value); - setSubmitted(false); + const handleChange = (newValue) => { + setValue(newValue); if (onChange) { // Try to call the remote function, don't let its failure break this. try { - onChange(e.target.value); + onChange(newValue); } catch (e) { - console.error(`Call to ${onChange} failed`); + console.error('Call to onChange failed', e); } } } - const handleClearSearch = (e) => { - e.preventDefault(); - // Clear the input when the "clear" button is clicked, search again. - setValue(''); - setSubmitted(false); - if (onSubmit) { - onSubmit(''); - } - if (onClear) { - onClear(); - } - } - - const localOnSubmit = (e) => { - // Send the value up when submitting. - e.preventDefault(); - setSubmitted(true); - if (onSubmit) { - onSubmit(value); - } else { - console.debug('No onSubmit defined'); - } - } - - const clearButton = + ; @@ -691,16 +608,12 @@ export function CookiesLockedMessage() { } return <> - - - - Cookies Locked - You have encrypted cookies stored, but they are currently locked. - setModalOpen(true)}> - Unlock Cookies - - + + You have encrypted cookies stored, but they are currently locked. + setModalOpen(false)}/> @@ -722,53 +635,34 @@ export function textEllipsis(str, maxLength = 100, {side = "end", ellipsis = ".. } export function TabLinks({links, right}) { - return + return {links.map((link) => { - const active = link.isActive ? link.isActive() : isActive; - return active ? 'item active' : 'item'; - }} + className={({isActive}) => tabClassName(link.isActive ? link.isActive() : isActive)} > {link.text} )} - {right && - - {right} - } - + } export function PageContainer(props) { return <> - - {props.children} - +
{props.children}
- - {props.children} - +
{props.children}
; } export function CardGroupCentered(props) { + // One responsive grid; it centres what it cannot fill, so the two viewports no + // longer need separate markup. return
- - - {props.children} - - - - - {props.children} - - + {props.children}
} @@ -832,14 +726,12 @@ export function findPosterPath(file) { } export function CardPoster({to, file}) { - const {s} = useContext(ThemeContext); // Used to center posters in CardIcon. - const style = {display: 'flex', justifyContent: 'center', ...s['style']}; + const style = {display: 'flex', justifyContent: 'center'}; const navigate = useNavigate(); - const cardTagIcon =
- -
; + // Marks a tagged file, pinned to the poster's corner. + const cardTagIcon =
; let imageLabel = !_.isEmpty(file.tags) ? cardTagIcon : null; let posterPath = findPosterPath(file); @@ -872,18 +764,18 @@ export function CardPoster({to, file}) { if (!to || (to.startsWith('/media/') || to.startsWith('/download/'))) { // "to" is a downloadable file outside the app, preview the file. return - +
{imageLabel} - +
} else if (!posterPath && to) { // Link to the full page in this App. return - navigate(to)}> +
navigate(to)}> {imageLabel} - +
} } @@ -899,16 +791,10 @@ export function InfoPopup({ iconStyle = { margin: '0.5em'}, ...props }) { - const trigger = ; - return + return {header}
{content} : content} + multiline w={260} {...props}> + +
} export function InfoHeader({ @@ -946,7 +832,8 @@ export function HelpModal({ const style = {position: 'relative', height: '75vh', width: '100%', border: 'none'}; return <> - setOpen(true)}/> + setOpen(true)}/> setOpen(false)} size={modalSize} closeIcon> {title && {title}} @@ -1007,12 +894,13 @@ function SubsystemToggle({label, on, onChange, unsupportedMessage, info = null, {confirmStop && setConfirmOpen(false)} - onClose={() => setConfirmOpen(false)} onConfirm={handleConfirm} - header={confirmStop.header} - content={confirmStop.content} - confirmButton={confirmStop.button} - />} + title={confirmStop.header} + confirmLabel={confirmStop.button} + destructive + > + {confirmStop.content} + } { - }; - if (onChange) { - onMouseUp = (e) => { - if (disabled) { - return; - } - e.preventDefault(); - if (onChange) { - onChange(!checked); - } - } - } - - if (icon) { - icon = - } - - const body = -
- - -
- - {icon} - {label} - {info && } - -
+ // Keeps this call signature -- `onChange` receives the new boolean, not an event -- + // because a dozen call sites are written against it. + const body = + + {icon && } + {label} + } + checked={checked === true} + disabled={disabled === true} + onChange={(e) => onChange && onChange(e.currentTarget.checked)} + data-testid='toggle' + /> + {info && } + ; if (popupContent) { - return + return {body} } return body } @@ -1170,14 +1024,12 @@ export function DisableDownloadsToggle() { } const on = downloads && downloads['disabled'] === false && downloads['stopped'] === false; - return
- - ; + return ; } export function emptyToNull(obj) { @@ -1356,26 +1208,34 @@ export function fileSuffixIconName(filename) { return 'file'; } -export function FileIcon({file, disabled = true, size = 'huge', ...props}) { - // Default to a grey file icon. +export function FileIcon({file, disabled = true, size = 48, ...props}) { const {mimetype, path, primary_path} = file; // `file` may be a file_group or a file. const lowerPath = primary_path ? primary_path.toLocaleString() : path.toLowerCase(); - props['name'] = mimetypeIconName(mimetype, lowerPath); - props['color'] = mimetypeColor(mimetype, lowerPath); - return + const name = mimetypeIconName(mimetype, lowerPath); + // The mimetype picks a hue; the token picks what that hue is in this theme. + const color = mimetypeColor(mimetype, lowerPath); + return } export function LoadStatistic({label, value, cores, ...props}) { + // Load is a warning above half the cores, and a problem above three quarters. const quarter = cores / 4; + let color; if (cores && value >= (quarter * 3)) { - props['color'] = 'red'; + color = 'red'; } else if (cores && value >= (quarter * 2)) { - props['color'] = 'orange'; + color = 'orange'; } return ; } @@ -1383,23 +1243,29 @@ export function DarkModeToggle() { const {savedTheme, setTheme} = useContext(ThemeContext); const active = themeChoices.find(i => i.value === savedTheme) || themeChoices[0]; - return } - title={`Theme: ${active.text}`} - style={{padding: 0, marginRight: '0.8em'}} - > - - - {themeChoices.map(choice => + + + + + Theme + {themeChoices.map(choice => } onClick={() => setTheme(choice.value)} - />)} - - + // The chosen theme is marked by weight as well as color, so the mark + // survives in the monochrome themes. + style={choice.value === active.value ? {fontWeight: 700} : undefined} + > + {choice.text} + )} + + } @@ -1408,28 +1274,36 @@ export function UnsupportedModal(header, message, icon) { const onOpen = () => setOpen(true); const onClose = () => setOpen(false); - const modal = -
- - {header || 'Unsupported'} -
- - - {message} - - + const modal = + + + + {header || 'Unsupported'} + + + {message} - + ; return {modal, doClose: onClose, doOpen: onOpen}; } +/** + * The hotspot glyph in the nav bar: a wifi icon with a corner mark for the state. + * A button, not an anchor -- every one of these opens a dialog or toggles the + * hotspot, and `` was neither keyboard-honest nor navigable. + */ +function HotspotButton({label, corner, on, onClick}) { + const wifi = ; + return + corner + ? } label={label}>{wifi} + : wifi + }/> +} + export function HotspotStatusIcon() { const {on, inUse, setHotspot, dockerized, hotspotSsid} = useHotspot(); const {modal: unsupportedModal, doOpen: openUnsupportedModal} = @@ -1459,55 +1333,39 @@ export function HotspotStatusIcon() { return <> setInUseOpen(false)} - onClose={() => setInUseOpen(false)} onConfirm={handleConfirmInUse} - header='Wifi is in-use' - content={content} - confirmButton='Start Hotspot' - /> - setInUseOpen(true)}> - - - - - + title='Wifi is in-use' + confirmLabel='Start Hotspot' + > + {content} + + setInUseOpen(true)}/> } else if (dockerized === false && on === true) { return <> setStopHotspotOpen(false)} - onClose={() => setStopHotspotOpen(false)} onConfirm={handleConfirmStop} - header='Stop the hotspot' - content='You will be disconnected when using the hotspot. Are you sure?' - confirmButton='Stop' - /> - setStopHotspotOpen(true)}> - - - {on === false && } - {on === null && } - - + title='Stop the hotspot' + confirmLabel='Stop' + destructive + > + You will be disconnected when using the hotspot. Are you sure? + + setStopHotspotOpen(true)}/> } else if (dockerized === false && on === false) { - return setHotspot(true)}> - - - - - + return setHotspot(true)}/> } // Hotspot is not available, or, status has not yet been fetched. return <> - - - - - - + {unsupportedModal} } @@ -1566,8 +1424,6 @@ export function DirectorySearch({onSelect, value, disabled, required, ...props}) const newDirectory = isDir ? {} : { newDirectory: { name: 'New Directory', - // title must not be null; an unset form field passes a null value and - // Semantic UI's Search crashes reading null.length. results: [{title: directoryName || ''}], } }; @@ -1601,21 +1457,15 @@ export function DirectorySearch({onSelect, value, disabled, required, ...props}) loading, ]); - const handleSearchChange = (e, data) => { - if (e) { - e.preventDefault(); - } - setDirectoryName(data.value); + const handleSearchChange = (value) => { + setDirectoryName(value); } - const handleResultSelect = (e, data) => { - if (e) { - e.preventDefault(); - } - setDirectoryName(data.result.title); + const handleResultSelect = (result) => { + setDirectoryName(result.title); // title is the relative path. if (onSelect) { - onSelect(data.result.title); + onSelect(result.title); } } @@ -1626,22 +1476,23 @@ export function DirectorySearch({onSelect, value, disabled, required, ...props}) } } - return } export const BackButton = ({...props}) => { const navigate = useNavigate(); - return ; } export const filterToMimetypes = (filter) => { @@ -1750,7 +1601,8 @@ export function SortButton({sorts = []}) { let sortFields; if (sorts && sorts.length) { sortFields = sorts.map((i) => { - return + return }) } @@ -1764,17 +1616,21 @@ export function SortButton({sorts = []}) { {sortFields}
- - } export function TagIcon() { - return + return
- - - File - Tags - - - - {(taggedFileGroups || []).map((fg, idx) => ( - - {fg.primary_path || fg.name} - {(fg.tags || []).join(', ')} - - ))} - -
- - - - - - ; + return Tagged Files Will Be Deleted} + confirmLabel='Delete' + destructive + onConfirm={onConfirm} + onCancel={onCancel} + > +

The following tagged files will be deleted:

+ + + + File + Tags + + + + {(taggedFileGroups || []).map((fg, idx) => ( + + {fg.primary_path || fg.name} + {(fg.tags || []).join(', ')} + + ))} + +
+
; } diff --git a/app/src/components/VncToggle.test.js b/app/src/components/VncToggle.test.js index 9c2c37ce..6c7408c1 100644 --- a/app/src/components/VncToggle.test.js +++ b/app/src/components/VncToggle.test.js @@ -1,5 +1,5 @@ import React from 'react'; -import {render, screen} from '@testing-library/react'; +import {render, screen} from '../test-utils'; import userEvent from '@testing-library/user-event'; import {VncToggle} from './Common'; diff --git a/app/src/components/calculators/RationCalculator.test.js b/app/src/components/calculators/RationCalculator.test.js index f6953fc3..80f9de99 100644 --- a/app/src/components/calculators/RationCalculator.test.js +++ b/app/src/components/calculators/RationCalculator.test.js @@ -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 { dailyCalorieDemand, daysOfFood, findCaloriesKey, findCountKey, RationEstimatePanel, totalCalories, } from "./RationCalculator"; diff --git a/app/src/components/collections/CollectionEditForm.js b/app/src/components/collections/CollectionEditForm.js index 0e152baa..f0354cee 100644 --- a/app/src/components/collections/CollectionEditForm.js +++ b/app/src/components/collections/CollectionEditForm.js @@ -1,6 +1,5 @@ import React from 'react'; -import {Button, Form, Grid, Message} from 'semantic-ui-react'; -import {Header, Segment} from '../Theme'; +import {Button, Header, Message, Panel} from '../ui'; import {TagsContext} from '../../Tags'; import {WROLModeMessage} from '../Common'; @@ -37,51 +36,63 @@ export function CollectionEditForm({ } }; - return + return {title &&
{title}
} {wrolModeContent && } {/* Display form-level errors */} - {form.error && - Error + {form.error &&

{form.error}

} -
- + + {/* + * `ui stackable grid` replicates Semantic's own Grid CSS classes (still loaded + * globally via semantic-ui-offline while other call sites remain unmigrated). + * Callers of this component (Channels.js, Archive.js, Playlists.js) still pass + * Semantic / children -- they have not migrated to the + * component library yet. This div keeps their layout without importing + * semantic-ui-react here. Replace with the real `Grid`/`Grid.Col` once every + * caller has migrated. + */} +
{children} - {appliedTagName && - + {appliedTagName &&
+
- - } +
+
} - - +
+
{actionButtons} {onCancel && } - - +
+
- - - - - ; +
+
+
+ +
; } diff --git a/app/src/components/collections/CollectionEditForm.test.js b/app/src/components/collections/CollectionEditForm.test.js index 34fb8070..7cf2f7e2 100644 --- a/app/src/components/collections/CollectionEditForm.test.js +++ b/app/src/components/collections/CollectionEditForm.test.js @@ -2,7 +2,6 @@ import React from 'react'; import { createMockDomain, createTestForm, - hasInvertedStyling, render, renderInDarkMode, renderInLightMode, @@ -210,7 +209,11 @@ describe('CollectionEditForm', () => { }); describe('Theme Integration', () => { - it('applies inverted styling to Segment in dark mode', () => { + // Panel/Header are token-driven (see ui/Surfaces.tsx): their colors come from CSS + // variables scoped on `[data-theme]`, not from JS branching on the theme. There is + // no more "inverted" prop/class to assert on -- just that the same markup renders + // in both modes. + it('renders a token-driven Panel in dark mode', () => { const form = createTestForm(mockCollection); const {container} = renderInDarkMode( @@ -219,12 +222,10 @@ describe('CollectionEditForm', () => { ); - const segment = container.querySelector('.ui.segment'); - expect(segment).toBeInTheDocument(); - expect(hasInvertedStyling(segment)).toBe(true); + expect(container.querySelector('.wrolpi-panel')).toBeInTheDocument(); }); - it('does not apply inverted styling in light mode', () => { + it('renders a token-driven Panel in light mode', () => { const form = createTestForm(mockCollection); const {container} = renderInLightMode( @@ -233,12 +234,10 @@ describe('CollectionEditForm', () => { ); - const segment = container.querySelector('.ui.segment'); - expect(segment).toBeInTheDocument(); - expect(hasInvertedStyling(segment)).toBe(false); + expect(container.querySelector('.wrolpi-panel')).toBeInTheDocument(); }); - it('applies dark theme styling to Header in dark mode', () => { + it('renders a token-driven Header for the title', () => { const form = createTestForm(mockCollection); const {container} = renderInDarkMode( @@ -247,9 +246,9 @@ describe('CollectionEditForm', () => { ); - const header = container.querySelector('.ui.header'); + const header = container.querySelector('.wrolpi-header'); expect(header).toBeInTheDocument(); - expect(header.style.color).toBe('rgb(238, 238, 238)'); // #eeeeee + expect(header).toHaveTextContent('Test Collection'); }); }); diff --git a/app/src/components/collections/CollectionTagModal.js b/app/src/components/collections/CollectionTagModal.js index fdbc6b96..5ba70b41 100644 --- a/app/src/components/collections/CollectionTagModal.js +++ b/app/src/components/collections/CollectionTagModal.js @@ -1,7 +1,5 @@ import React, {useCallback, useEffect, useState} from 'react'; -import {Grid, Input} from 'semantic-ui-react'; -import Message from 'semantic-ui-react/dist/commonjs/collections/Message'; -import {Button, Modal} from '../Theme'; +import {Button, Message, Modal, Stack, TextInput} from '../ui'; import {TagsSelector} from '../../Tags'; import {APIButton, Toggle} from '../Common'; @@ -107,54 +105,36 @@ export function CollectionTagModal({ > {modalTitle} - - - - handleTagChange(null)} - /> - - + + handleTagChange(null)} + /> {hasDirectory && ( - - - - - + )} {hasDirectory && ( - - - setNewTagDirectory(value)} - disabled={!moveToTagDirectory} - /> - - + setNewTagDirectory(e.currentTarget.value)} + disabled={!moveToTagDirectory} + /> )} {hasDirectory && conflictMessage && ( - - - - Directory Conflict -

{conflictMessage}

-
-
-
+ +

{conflictMessage}

+
)} -
+
- + { - const MockModal = ({open, onClose, children, closeIcon}) => { - if (!open) return null; - return ( -
- {closeIcon && } - {children} -
- ); - }; - MockModal.Header = ({children}) =>
{children}
; - MockModal.Content = ({children}) =>
{children}
; - MockModal.Actions = ({children}) =>
{children}
; - MockModal.Description = ({children}) =>
{children}
; - - return { - ...jest.requireActual('../Theme'), - Modal: MockModal, - Button: ({children, onClick, ...props}) => ( - - ), - }; -}); - // Mock Common components jest.mock('../Common', () => ({ ...jest.requireActual('../Common'), @@ -76,22 +51,22 @@ describe('CollectionTagModal', () => { describe('Modal Rendering', () => { it('renders modal when open is true', () => { render(); - expect(screen.getByTestId('modal')).toBeInTheDocument(); + expect(screen.getByRole('dialog')).toBeInTheDocument(); }); it('does not render modal when open is false', () => { render(); - expect(screen.queryByTestId('modal')).not.toBeInTheDocument(); + expect(screen.queryByRole('dialog')).not.toBeInTheDocument(); }); it('shows "Add Tag" header when no current tag', () => { render(); - expect(screen.getByTestId('modal-header')).toHaveTextContent('Add Tag'); + expect(screen.getByRole('heading')).toHaveTextContent('Add Tag'); }); it('shows "Modify Tag" header when there is a current tag', () => { render(); - expect(screen.getByTestId('modal-header')).toHaveTextContent('Modify Tag'); + expect(screen.getByRole('heading')).toHaveTextContent('Modify Tag'); }); }); @@ -308,7 +283,7 @@ describe('CollectionTagModal', () => { const mockOnClose = jest.fn(); render(); - const cancelButton = screen.getByTestId('button-Cancel'); + const cancelButton = screen.getByRole('button', {name: 'Cancel'}); await userEvent.click(cancelButton); expect(mockOnClose).toHaveBeenCalled(); @@ -341,7 +316,7 @@ describe('CollectionTagModal', () => { }); // Close the modal - const cancelButton = screen.getByTestId('button-Cancel'); + const cancelButton = screen.getByRole('button', {name: 'Cancel'}); await userEvent.click(cancelButton); // Reopen modal diff --git a/app/src/components/collections/ConflictResolutionModal.test.js b/app/src/components/collections/ConflictResolutionModal.test.js index f24dfaa0..27a90054 100644 --- a/app/src/components/collections/ConflictResolutionModal.test.js +++ b/app/src/components/collections/ConflictResolutionModal.test.js @@ -340,10 +340,9 @@ describe('ConflictResolutionModal', () => { // Confirming should re-call deleteFileGroups with force=true. api.deleteFileGroups.mockResolvedValueOnce({}); - // The TaggedDeleteConfirmModal's Delete button has the trash icon. - const confirmButton = screen.getAllByRole('button') - .find(b => b.classList.contains('red') && b.textContent.includes('Delete') - && b.querySelector('.trash.icon')); + // The TaggedDeleteConfirmModal (a Confirm) names its destructive action "Delete", + // distinct from the "Delete this file" icon buttons queried above. + const confirmButton = screen.getByRole('button', {name: 'Delete'}); fireEvent.click(confirmButton); await waitFor(() => { diff --git a/app/src/components/inventory/CatalogEditor.js b/app/src/components/inventory/CatalogEditor.js index 3927a89d..2c087a5d 100644 --- a/app/src/components/inventory/CatalogEditor.js +++ b/app/src/components/inventory/CatalogEditor.js @@ -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 + return Food Catalog - -

+ + Known items used to autocomplete and pre-fill the entry form. kcal is the total calories for one package of the given size. -

- - - - - {COLUMNS.map(c => {c.label})} - - - - + + +
+ + + {COLUMNS.map(c => {c.label})} + + + + {draft.map((entry, index) => { const aria = (col) => `${entry.name || 'new item'} ${col}`; - return - - update(index, 'name', e.target.value)}/> - - - + + update(index, 'name', e.currentTarget.value)}/> + + + update(index, 'category', e.target.value)}/> - - - update(index, 'category', e.currentTarget.value)}/> + + + update(index, 'subcategory', e.target.value)}/> - - - update(index, 'subcategory', e.currentTarget.value)}/> + + + update(index, 'item_size', e.target.value)}/> - - - update(index, 'item_size_unit', data.value)}/> - - - update(index, 'item_size_unit', value)}/> + + + update(index, 'calories', e.target.value)}/> - - - - - ; + onChange={e => update(index, 'calories', e.currentTarget.value)}/> + + + remove(index)}/> + + ; })} - +
- - + +
; } diff --git a/app/src/components/inventory/InventoryExportPanel.js b/app/src/components/inventory/InventoryExportPanel.js index 7d7ec0f1..b91f00c7 100644 --- a/app/src/components/inventory/InventoryExportPanel.js +++ b/app/src/components/inventory/InventoryExportPanel.js @@ -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 <> - -
CSV
-

+ +

CSV
+ 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. -

- -
+ - -
PDF
-

+ +

PDF
+ 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. -

+
{groupFields.length > 0 && -
+ Summary group:{' '} - onGroupKey(value)}/> {summableFields.length > 0 && Sum:{' '} - onSumKey(value || undefined)}/> } -
} - -
+ ; } diff --git a/app/src/components/inventory/InventoryItemsMobile.js b/app/src/components/inventory/InventoryItemsMobile.js index fa3c478a..f85f6574 100644 --- a/app/src/components/inventory/InventoryItemsMobile.js +++ b/app/src/components/inventory/InventoryItemsMobile.js @@ -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 <> -

+ Read-only — rotate to landscape to edit. -

+ {(items || []).length === 0 - ?

No items yet.

- : - - - {columns.map(f => {f.label})} - - - + ? No items yet. + :
+ + + {columns.map(f => {f.label})} + + + {items.map(item => { const expired = isItemExpired(item, fields); - return - {columns.map((f, idx) => + return + {columns.map((f, idx) => {idx === 0 && expired && - } + } {formatValue(item, f)} - )} - ; + )} + ; })} - +
} ; } diff --git a/app/src/components/inventory/InventoryItemsMobile.test.js b/app/src/components/inventory/InventoryItemsMobile.test.js index 9d644674..84a4007b 100644 --- a/app/src/components/inventory/InventoryItemsMobile.test.js +++ b/app/src/components/inventory/InventoryItemsMobile.test.js @@ -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(); + renderWithProviders(); 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(); + renderWithProviders(); 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(); + renderWithProviders(); 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(); + renderWithProviders(); 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(); + renderWithProviders(); expect(screen.getByText('No items yet.')).toBeTruthy(); }); }); diff --git a/app/src/components/inventory/InventorySummary.js b/app/src/components/inventory/InventorySummary.js index e3cdbd25..2ce0a8da 100644 --- a/app/src/components/inventory/InventorySummary.js +++ b/app/src/components/inventory/InventorySummary.js @@ -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

No items to summarize yet.

; + return No items to summarize yet.; } - 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 <>
Summary
-
- + + Group by:{' '} - setGroupKey(value)}/> {summableFields.length > 0 && Sum:{' '} - setSumKey(value || undefined)}/> } -
- - - - toggleSort('name')} - style={{cursor: 'pointer'}}> + +
+ + + toggleSort('name')}> {groupFields.find(f => f.key === groupKey)?.label || 'Group'} - - toggleSort('count')} - style={{cursor: 'pointer'}}>Items - {sumKey && toggleSort('total')} - style={{cursor: 'pointer'}}>Total} - {caloriesKey && toggleSort('calories')} - style={{cursor: 'pointer'}}>Calories} - - - - {rows.map(row => - {row.name} - {row.count} - {sumKey && {row.total}} + + toggleSort('count')}> + Items + + {sumKey && toggleSort('total')}> + Total + } + {caloriesKey && toggleSort('calories')}> + Calories + } + + + + {rows.map(row => + {row.name} + {row.count} + {sumKey && {row.total}} {caloriesKey && - {row.calories > 0 ? `${row.calories.toLocaleString()} kcal` : '—'}} - )} - + {row.calories > 0 ? `${row.calories.toLocaleString()} kcal` : '—'}} + )} +
; } diff --git a/app/src/components/inventory/InventorySummary.test.js b/app/src/components/inventory/InventorySummary.test.js index 162aeeaf..08921c5c 100644 --- a/app/src/components/inventory/InventorySummary.test.js +++ b/app/src/components/inventory/InventorySummary.test.js @@ -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(); + renderWithProviders(); expect(groupOrder()).toEqual(['beans', 'grains']); }); test('sorting by Items uses the numeric count', () => { - render(); + renderWithProviders(); 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(); + renderWithProviders(); fireEvent.click(screen.getByText('Total')); // descending expect(groupOrder()).toEqual(['beans', 'grains']); // beans 100 lb > grains 30 lb }); diff --git a/app/src/components/ui/Button.tsx b/app/src/components/ui/Button.tsx index b62b9629..fa46588b 100644 --- a/app/src/components/ui/Button.tsx +++ b/app/src/components/ui/Button.tsx @@ -39,6 +39,30 @@ const renderIcon = (icon?: string | React.ComponentType) => { return typeof icon === 'string' ? : ; } +/* + * Semantic's size names, mapped onto Mantine's scale. + * + * Unmigrated call sites still pass `size='tiny'`, and Mantine silently ignores a + * size it does not know — the button renders at the default size and nobody sees + * a warning. Translating here keeps those call sites looking right until they + * migrate, and costs nothing once they have. + */ +const semanticSizes: Record = { + mini: 'xs', + tiny: 'xs', + small: 'sm', + medium: 'md', + large: 'lg', + big: 'lg', + huge: 'xl', + massive: 'xl', +}; + +// Generic so it passes each component's own size type straight through; only a +// string that Semantic knew about is rewritten. +export const resolveSize = (size: T): T => + typeof size === 'string' ? ((semanticSizes[size] ?? size) as T) : size; + export const Button = forwardRef(( {role, icon, iconAfter, className, ...props}, ref ) => { @@ -52,6 +76,7 @@ export const Button = forwardRef(( leftSection={renderIcon(icon)} rightSection={renderIcon(iconAfter)} {...props} + size={resolveSize(props.size)} /> }); Button.displayName = 'Button'; @@ -78,6 +103,7 @@ export const IconButton = forwardRef(( variant={props.variant ?? fromRole?.variant ?? 'default'} className={[fromRole?.className, className].filter(Boolean).join(' ') || undefined} {...props} + size={resolveSize(props.size)} > {renderIcon(icon)} diff --git a/app/src/components/ui/Icon.tsx b/app/src/components/ui/Icon.tsx index c505a43a..44fce012 100644 --- a/app/src/components/ui/Icon.tsx +++ b/app/src/components/ui/Icon.tsx @@ -25,6 +25,7 @@ const sizes: Record = {small: 16, medium: 20, large: 24}; */ const semanticNames: Record = { 'add': 'IconPlus', + 'apple': 'IconBrandApple', 'archive': 'IconArchive', 'arrow alternate circle up': 'IconCircleArrowUp', 'arrow down': 'IconArrowDown', @@ -35,6 +36,7 @@ const semanticNames: Record = { 'bug': 'IconBug', 'calculator': 'IconCalculator', 'calendar': 'IconCalendar', + 'certificate': 'IconCertificate', 'charset': 'IconLanguage', 'check': 'IconCheck', 'check circle': 'IconCircleCheck', @@ -46,11 +48,13 @@ const semanticNames: Record = { 'circle notch': 'IconLoader2', 'circle notched': 'IconLoader2', 'close': 'IconX', + 'closed captioning': 'IconBadgeCc', 'columns': 'IconColumns', 'copy': 'IconCopy', 'cube': 'IconCube', 'directory': 'IconFolder', 'disk': 'IconDatabase', + 'dot circle': 'IconCircleDot', 'download': 'IconDownload', 'dropdown': 'IconChevronDown', 'edit': 'IconEdit', @@ -63,10 +67,16 @@ const semanticNames: Record = { 'file': 'IconFile', 'file alternate': 'IconFileDescription', 'file alternate outline': 'IconFileDescription', + 'file archive': 'IconFileZip', + 'file audio': 'IconFileMusic', 'file code': 'IconFileCode', + 'file excel': 'IconFileSpreadsheet', + 'file pdf': 'IconFileTypePdf', 'file pdf outline': 'IconFileTypePdf', + 'file powerpoint': 'IconPresentation', 'file text': 'IconFileText', 'file video': 'IconFileSmile', + 'file word': 'IconFileText', 'film': 'IconMovie', 'filter': 'IconFilter', 'firefox': 'IconBrandFirefox', @@ -74,6 +84,7 @@ const semanticNames: Record = { 'folder open': 'IconFolderOpen', 'folder open outline': 'IconFolderOpen', 'folder outline': 'IconFolder', + 'font': 'IconTypography', 'globe': 'IconWorld', 'hand point right': 'IconHandFinger', 'hdd': 'IconDeviceSdCard', @@ -84,14 +95,16 @@ const semanticNames: Record = { 'lightbulb': 'IconBulb', 'lightbulb outline': 'IconBulb', 'lightning': 'IconBolt', - 'moon': 'IconMoon', - 'moon outline': 'IconMoon', 'linkify': 'IconLink', + 'linux': 'IconBrandUbuntu', 'list': 'IconList', 'lock': 'IconLock', + 'mail': 'IconMail', 'map outline': 'IconMap', 'microchip': 'IconCpu', 'minus': 'IconMinus', + 'moon': 'IconMoon', + 'moon outline': 'IconMoon', 'paypal': 'IconBrandPaypal', 'play': 'IconPlayerPlay', 'plug': 'IconPlug', @@ -131,6 +144,7 @@ const semanticNames: Record = { 'warning circle': 'IconAlertCircle', 'warning sign': 'IconAlertTriangle', 'wifi': 'IconWifi', + 'windows': 'IconBrandWindows', 'wrench': 'IconTool', 'x': 'IconX', }; diff --git a/app/src/components/ui/Surfaces.tsx b/app/src/components/ui/Surfaces.tsx index d56b518c..a5fd2d28 100644 --- a/app/src/components/ui/Surfaces.tsx +++ b/app/src/components/ui/Surfaces.tsx @@ -68,10 +68,12 @@ export interface StatisticProps { value: React.ReactNode; label: React.ReactNode; color?: string; + className?: string; + style?: React.CSSProperties; } -export function Statistic({value, label, color}: StatisticProps) { - return
+export function Statistic({value, label, color, className, style}: StatisticProps) { + return
{value}
@@ -89,6 +91,7 @@ export function StatisticGroup({children}: {children: React.ReactNode}) { }}> {items.map((child, index) =>
{ expect(unmapped.map(c => `${c.text}: ${c.icon}`)).toEqual([]); }); + it('maps every name the mimetype and file-suffix helpers can return', () => { + // These two build icon names from arbitrary files in the user's library, so an + // unmapped one is not hypothetical — it is a console error and a fallback glyph + // the moment somebody opens a folder containing that file type. + const common = fs.readFileSync(path.join(__dirname, '..', 'Common.js'), 'utf8'); + const section = common.slice( + common.indexOf('export function mimetypeIconName'), + common.indexOf('export function FileIcon')); + const returned = [...new Set([...section.matchAll(/return '([^']+)'/g)].map(m => m[1]))]; + + expect(returned.length).toBeGreaterThan(10); + expect(returned.filter(name => !resolveIconName(name))).toEqual([]); + }); + + it('points every mapped name at a Tabler component that exists', () => { + // A typo in the map resolves to undefined and renders the fallback glyph, which + // looks like a design choice rather than a bug. + const source = fs.readFileSync(path.join(__dirname, 'Icon.tsx'), 'utf8'); + const names = [...source.matchAll(/^ {4}'([^']+)': '([^']+)',$/gm)].map(m => m[1]); + + expect(names.length).toBeGreaterThan(100); + expect(names.filter(name => !resolveIconName(name))).toEqual([]); + }); + it('reports an unknown name instead of failing silently', () => { const error = jest.spyOn(console, 'error').mockImplementation(() => {}); @@ -116,6 +142,16 @@ describe('Button', () => { expect(screen.getByRole('button', {name: 'Save'})).toBeInTheDocument(); }); + it('translates Semantic size names, which Mantine would otherwise ignore', () => { + // Unmigrated call sites still pass size='tiny'. Mantine drops a size it does not + // recognise without warning, so the button quietly renders at the default size. + renderUI(<>); + + expect(screen.getByRole('button', {name: 'Old'})).toHaveAttribute('data-size', 'xs'); + // A Mantine size still passes through untouched. + expect(screen.getByRole('button', {name: 'New'})).toHaveAttribute('data-size', 'sm'); + }); + it('gives icon-only buttons an accessible name', () => { renderUI(); diff --git a/app/src/hooks/customHooks.test.js b/app/src/hooks/customHooks.test.js index c762081b..5d925cc3 100644 --- a/app/src/hooks/customHooks.test.js +++ b/app/src/hooks/customHooks.test.js @@ -1,6 +1,6 @@ import React from 'react'; import {act, renderHook} from '@testing-library/react'; -import {render, screen} from '@testing-library/react'; +import {render, screen} from '../test-utils'; import {usePages, useDriveTemperature, useDriveHealth} from './customHooks'; import {QueryContext, StatusContext} from '../contexts/contexts'; import {Paginator} from '../components/Common'; diff --git a/app/src/hooks/useForm.test.js b/app/src/hooks/useForm.test.js index 8433ed1a..601f4bee 100644 --- a/app/src/hooks/useForm.test.js +++ b/app/src/hooks/useForm.test.js @@ -1044,7 +1044,7 @@ describe('Form Components', () => { /> ); - expect(screen.getByRole('checkbox')).toBeInTheDocument(); + expect(screen.getByRole('switch')).toBeInTheDocument(); }); }); diff --git a/app/src/hooks/useKeyboardShortcuts.test.js b/app/src/hooks/useKeyboardShortcuts.test.js index 51c1c263..d358e0ec 100644 --- a/app/src/hooks/useKeyboardShortcuts.test.js +++ b/app/src/hooks/useKeyboardShortcuts.test.js @@ -1,6 +1,5 @@ import React from 'react'; -import {render, screen, fireEvent, act} from '@testing-library/react'; -import {MemoryRouter} from 'react-router'; +import {render, screen, fireEvent, act} from '../test-utils'; import {KeyboardShortcutsContext} from '../contexts/KeyboardShortcutsContext'; import {KeyboardShortcutsProvider, SHORTCUTS} from '../components/KeyboardShortcutsProvider'; import {ThemeContext} from '../contexts/contexts'; @@ -43,17 +42,15 @@ function TestWrapper({children}) { }; return ( - - - - - - {children} - - - - - + + + + + {children} + + + + ); } diff --git a/app/src/semantic-baseline.json b/app/src/semantic-baseline.json index 5c858fca..fb5ae591 100644 --- a/app/src/semantic-baseline.json +++ b/app/src/semantic-baseline.json @@ -4,14 +4,9 @@ "src/Events.js", "src/Tags.js", "src/api.js", - "src/components/AddToPlaylist.js", - "src/components/Apps.js", "src/components/Archive.js", - "src/components/ArchivePreview.js", "src/components/BulkTagModal.js", - "src/components/CbzViewer.js", "src/components/Channels.js", - "src/components/Common.js", "src/components/DatesSelector.js", "src/components/Docs.js", "src/components/Download.js", @@ -24,10 +19,8 @@ "src/components/MapSearchView.js", "src/components/MapViewer.js", "src/components/Nav.js", - "src/components/Placeholder.js", "src/components/Playlists.js", "src/components/Search.js", - "src/components/TaggedDeleteConfirmModal.js", "src/components/Theme.tsx", "src/components/Upload.js", "src/components/VideoPlayer.js", @@ -46,19 +39,13 @@ "src/components/calculators/RationCalculator.js", "src/components/calculators/WaterCalculator.js", "src/components/collections/BatchReorganizeModal.js", - "src/components/collections/CollectionEditForm.js", "src/components/collections/CollectionReorganizeModal.js", "src/components/collections/CollectionTable.js", - "src/components/collections/CollectionTagModal.js", "src/components/collections/ConflictResolutionModal.js", - "src/components/inventory/CatalogEditor.js", "src/components/inventory/FieldCell.js", "src/components/inventory/FieldSchemaEditor.js", - "src/components/inventory/InventoryExportPanel.js", "src/components/inventory/InventoryImportModal.js", - "src/components/inventory/InventoryItemsMobile.js", "src/components/inventory/InventoryRoute.js", - "src/components/inventory/InventorySummary.js", "src/components/inventory/InventoryTable.js", "src/hooks/customHooks.js", "src/hooks/useForm.js" diff --git a/app/src/semantic-baseline.test.js b/app/src/semantic-baseline.test.js index 5d9fd5cc..7d21c93a 100644 --- a/app/src/semantic-baseline.test.js +++ b/app/src/semantic-baseline.test.js @@ -48,6 +48,23 @@ describe('Semantic UI removal', () => { expect(stale).toEqual([]); }); + it('declares every migrated file that still leans on Semantic CSS classes', () => { + /* + * A file can stop importing semantic-ui-react and still depend on its stylesheet + * by writing `className="ui stackable grid"`. The import ratchet above cannot see + * that, so when Phase 4 deletes semantic.min.css the layout would silently + * collapse. Anything on this list is a deliberate bridge that must be revisited + * then; anything NOT on it is an accident. + */ + const allowed = ['src/components/collections/CollectionEditForm.js']; + + const bridges = sourceFiles() + .filter(file => !baseline.includes(file)) + .filter(file => /className=["']ui /.test(fs.readFileSync(path.join(SRC, '..', file), 'utf8'))); + + expect(bridges.sort()).toEqual(allowed.sort()); + }); + it('reports how much of the migration is left', () => { // Not an assertion so much as a progress readout in the test output. const remaining = importers().length; diff --git a/app/src/setupTests.js b/app/src/setupTests.js index 24a37e2a..5f2ae4c6 100644 --- a/app/src/setupTests.js +++ b/app/src/setupTests.js @@ -52,6 +52,21 @@ global.IntersectionObserver = class IntersectionObserver { } }; +// Mock ResizeObserver (used by Mantine's ScrollArea, e.g. inside Select/Combobox dropdowns). +global.ResizeObserver = class ResizeObserver { + constructor() { + } + + disconnect() { + } + + observe() { + } + + unobserve() { + } +}; + // Suppress console errors during tests (optional - uncomment if needed) // const originalError = console.error; // beforeAll(() => { From 16bdffbac7ee6df86d8a66baf942769885787e6c Mon Sep 17 00:00:00 2001 From: Roland Date: Thu, 30 Jul 2026 11:28:17 -0600 Subject: [PATCH 03/31] ui: fix search suggestion selection, rendering, and clipping Three findings from review and CI on the Common.js migration, all real. Selecting a suggestion navigated nowhere. Semantic handed its callers `{result}` and every caller destructures that shape, so passing the bare result left `result.location` undefined -- the search suggestions and the Ctrl+K modal both stopped navigating. The shape stays until the call sites can change together. (Greptile P1.) Suggestions lost their custom markup. Callers pass `resultRenderer` to draw a tag as a chip rather than a line of text, and the migrated wrapper forwarded it into a div's props instead of to SearchBox, so every suggestion fell back to the generic title and description. SearchBox takes it now. (Greptile P2.) The suggestion list clipped its last group. A cypress spec caught it: with directories, channels and domains all present, the content runs past the 320px cap and the final row was cut off. Eight grouped suggestions is an ordinary result set, so the cap was simply too low; it is viewport-relative now and still bounded. Both regressions are pinned by tests -- one asserting the callback shape a caller actually destructures, one asserting the custom renderer replaces the default markup rather than wrapping it. --- app/src/components/Common.js | 7 +++++- app/src/components/Common.test.js | 39 ++++++++++++++++++++++++++++- app/src/components/ui/SearchBox.tsx | 17 ++++++++++--- app/src/components/ui/ui.css | 7 +++++- app/src/components/ui/ui.test.js | 14 +++++++++++ 5 files changed, 77 insertions(+), 7 deletions(-) diff --git a/app/src/components/Common.js b/app/src/components/Common.js index a83fb145..bd0c7be7 100644 --- a/app/src/components/Common.js +++ b/app/src/components/Common.js @@ -469,6 +469,7 @@ export function SearchResultsInput({ clearDisabled = null, results = undefined, handleResultSelect = null, + resultRenderer = undefined, loading = false, inputRef = null, ...props @@ -484,7 +485,10 @@ export function SearchResultsInput({ const localHandleResultSelect = (result) => { if (handleResultSelect) { - handleResultSelect(result); + // Semantic handed its callers `{result}`, and they destructure it -- passing the + // bare result silently broke navigation from the search suggestions. The shape + // stays until the call sites are ready to change together. + handleResultSelect({result}); } else { console.error('No handleResultSelect defined!'); } @@ -498,6 +502,7 @@ export function SearchResultsInput({ onResultSelect={localHandleResultSelect} onClear={handleClear} results={results} + resultRenderer={resultRenderer} loading={loading} placeholder={placeholder} clearable={clearable} diff --git a/app/src/components/Common.test.js b/app/src/components/Common.test.js index 316eebdf..a3c01a04 100644 --- a/app/src/components/Common.test.js +++ b/app/src/components/Common.test.js @@ -1,7 +1,7 @@ import React from 'react'; import {act, render, screen, waitFor} from '../test-utils'; import userEvent from '@testing-library/user-event'; -import {DirectorySearch} from './Common'; +import {DirectorySearch, SearchResultsInput} from './Common'; // Mock debounce to make tests run faster jest.mock('lodash/debounce', () => jest.fn(fn => { @@ -442,3 +442,40 @@ describe('DirectorySearch', () => { }); }); }); + +describe('SearchResultsInput', () => { + const results = { + tags: {name: 'Tags', results: [{type: 'tag', title: 'Cooking'}]}, + videos: {name: 'Videos', results: [ + {title: 'How To Sharpen An Axe', description: 'Wranglerstar', location: '/videos/1'}, + ]}, + }; + + it('hands the selected suggestion to its caller as {result}', async () => { + /* + * Regression: the migration passed the bare result, but every caller destructures + * `{result}` (see Search.js), so `result.location` was undefined and clicking a + * search suggestion navigated nowhere. + */ + const handleResultSelect = jest.fn(); + render(); + + await userEvent.click(screen.getByRole('combobox')); + await userEvent.click(screen.getByText('How To Sharpen An Axe')); + + expect(handleResultSelect).toHaveBeenCalledWith( + {result: expect.objectContaining({location: '/videos/1'})}); + }); + + it('forwards resultRenderer so a caller keeps its own suggestion markup', async () => { + // Search.js renders a tag suggestion as a tag chip, not a line of text. + const resultRenderer = (result) => rendered:{result.title}; + render(); + + await userEvent.click(screen.getByRole('combobox')); + + expect(screen.getByText('rendered:Cooking')).toBeInTheDocument(); + }); +}); diff --git a/app/src/components/ui/SearchBox.tsx b/app/src/components/ui/SearchBox.tsx index affd60f7..10bae23c 100644 --- a/app/src/components/ui/SearchBox.tsx +++ b/app/src/components/ui/SearchBox.tsx @@ -42,6 +42,12 @@ export interface SearchBoxProps { onResultSelect?: (result: SearchResult) => void; onBlur?: React.FocusEventHandler; results?: SearchResults; + /** + * Render one suggestion's contents. Callers use this to give a kind of result its + * own presentation — a tag chip rather than a line of text, say. Falls back to + * the title and description. + */ + resultRenderer?: (result: SearchResult) => React.ReactNode; /** Suggestions are being fetched; shows a spinner rather than "no results". */ loading?: boolean; placeholder?: string; @@ -71,6 +77,7 @@ export function SearchBox({ onResultSelect, onBlur, results, + resultRenderer, loading, placeholder = 'Search...', clearable, @@ -217,10 +224,12 @@ export function SearchBox({ }} onMouseEnter={() => setHighlighted(optionIndex)} > -
{result.title}
- {result.description &&
- {result.description} -
} + {resultRenderer ? resultRenderer(result) : <> +
{result.title}
+ {result.description &&
+ {result.description} +
} + }
})}
diff --git a/app/src/components/ui/ui.css b/app/src/components/ui/ui.css index a06a4644..2eb5cca7 100644 --- a/app/src/components/ui/ui.css +++ b/app/src/components/ui/ui.css @@ -275,7 +275,12 @@ html[data-theme="amber"] .wrolpi-searchbox-control:focus-within { top: 100%; left: 0; right: 0; - max-height: 320px; + /* + * Tall enough for a full set of grouped suggestions -- directories, channels and + * domains together run past 320px, and the last group was being clipped -- but + * still capped so a long list cannot cover the page. + */ + max-height: min(60vh, 480px); overflow-y: auto; background: var(--panel); border: 1px solid var(--border); diff --git a/app/src/components/ui/ui.test.js b/app/src/components/ui/ui.test.js index cda287c2..7b9fb6c0 100644 --- a/app/src/components/ui/ui.test.js +++ b/app/src/components/ui/ui.test.js @@ -573,6 +573,20 @@ describe('SearchBox', () => { expect.objectContaining({title: 'videos/RoseRed'})); }); + it('lets a caller render a suggestion its own way', async () => { + // The search suggestions render a tag as a chip rather than a line of text; a + // dropped resultRenderer loses that presentation silently. + renderUI( {`custom: ${result.title}`}}/>); + + await userEvent.click(screen.getByRole('combobox')); + + expect(screen.getByText('custom: videos/Wranglerstar').tagName).toBe('EM'); + // The default title/description markup is replaced, not wrapped. + expect(document.querySelector('.wrolpi-searchbox-result-title')).not.toBeInTheDocument(); + }); + it('closes on Escape without clearing what was typed', async () => { const onChange = jest.fn(); renderUI( Date: Thu, 30 Jul 2026 12:21:30 -0600 Subject: [PATCH 04/31] 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. --- app/src/App.js | 24 +- app/src/DashboardPage.js | 153 +- app/src/DashboardPage.test.js | 33 +- app/src/Events.js | 2 +- app/src/Tags.js | 235 ++-- app/src/api.js | 2 +- app/src/components/Archive.js | 141 +- app/src/components/DatesSelector.js | 153 +- app/src/components/Download.js | 1230 +++++++---------- app/src/components/Files.js | 468 +++---- app/src/components/HelpModal.js | 41 +- app/src/components/Map.js | 188 ++- app/src/components/MapSearchView.js | 64 +- app/src/components/MapViewer.js | 68 +- app/src/components/Search.js | 73 +- app/src/components/SearchFilterModal.test.js | 34 +- app/src/components/Videos.js | 572 ++++---- app/src/components/admin/Settings.js | 625 ++++----- app/src/components/admin/Status.js | 235 ++-- .../components/calculators/DriveCalculator.js | 228 +-- .../calculators/ElectricalCalculators.js | 295 ++-- .../calculators/FoodStorageCalculator.js | 111 +- .../components/calculators/HamCalculators.js | 121 +- .../calculators/OneTimePadCalculator.js | 124 +- .../components/calculators/RatioCalculator.js | 186 +-- .../calculators/RationCalculator.js | 136 +- .../calculators/RationCalculator.test.js | 6 +- .../components/calculators/WaterCalculator.js | 170 ++- .../collections/BatchReorganizeModal.js | 241 ++-- .../collections/BatchReorganizeModal.test.js | 2 +- .../collections/CollectionReorganizeModal.js | 239 ++-- .../CollectionReorganizeModal.test.js | 2 +- .../components/collections/CollectionTable.js | 64 +- .../collections/CollectionTable.test.js | 41 +- .../collections/ConflictResolutionModal.js | 260 ++-- app/src/components/inventory/FieldCell.js | 78 +- .../components/inventory/FieldSchemaEditor.js | 115 +- .../inventory/FieldSchemaEditor.test.js | 2 +- .../inventory/InventoryImportModal.js | 92 +- .../inventory/InventoryImportModal.test.js | 3 +- .../components/inventory/InventoryRoute.js | 118 +- .../components/inventory/InventoryTable.js | 74 +- .../inventory/InventoryTable.test.js | 10 +- app/src/components/ui/Inputs.tsx | 15 +- app/src/components/ui/Surfaces.tsx | 16 +- app/src/hooks/customHooks.js | 2 +- app/src/hooks/useForm.js | 21 +- app/src/semantic-baseline.json | 37 +- 48 files changed, 3273 insertions(+), 3877 deletions(-) diff --git a/app/src/App.js b/app/src/App.js index 425a3a45..68d69f8a 100644 --- a/app/src/App.js +++ b/app/src/App.js @@ -4,7 +4,7 @@ import {NavBar} from "./components/Nav"; import {createBrowserRouter, createRoutesFromElements, Link, Outlet, Route, RouterProvider} from "react-router"; import {VideosTabLayout, VideosPage, VideosSettingsPage, VideosStatistics, VideoWrapper} from "./components/Videos"; import AdminRoute from "./components/admin/AdminRoute"; -import {Container} from "semantic-ui-react"; +import {Box, Header} from "./components/ui"; import 'semantic-ui-offline/semantic.min.css'; import '@mantine/core/styles.css'; import '@mantine/notifications/styles.css'; @@ -20,13 +20,12 @@ import {QueryProvider, StatusProvider} from "./hooks/customHooks"; import {FileWorkerStatusProvider} from "./contexts/FileWorkerStatusContext"; import {ChannelEditPage, ChannelNewPage, ChannelsPage} from "./components/Channels"; import {MapRoute} from "./components/Map"; -import {MediaContextProvider, mediaStyles, StatusContext, ThemeContext} from "./contexts/contexts"; -import {Header, ThemeProvider} from "./components/Theme"; +import {MediaContextProvider, mediaStyles, StatusContext} from "./contexts/contexts"; +import {ThemeProvider} from "./components/Theme"; import {DashboardPage} from "./DashboardPage"; import {DonatePage} from "./components/DonatePage"; import {ThemeSamplePage} from "./components/ThemeSamplePage"; import {useEventsInterval} from "./Events"; -import {SemanticToastContainer} from "react-semantic-toasts-2"; import {FilePreviewProvider} from "./components/FilePreview"; import {TagsProvider} from "./Tags"; import {ZimRoute} from "./components/Zim"; @@ -37,11 +36,10 @@ import ErrorBoundary from "./components/ErrorBoundary"; import {KeyboardShortcutsProvider} from "./components/KeyboardShortcutsProvider"; function PageNotFound() { - const {t} = useContext(ThemeContext); - return + return
Page Not Found!
-

The page you requested cannot be found

-
+

The page you requested cannot be found

+ } function Dot() { @@ -49,7 +47,6 @@ function Dot() { } function Footer() { - const {t} = useContext(ThemeContext); const {status} = useContext(StatusContext); let version; try { @@ -57,13 +54,13 @@ function Footer() { } catch (e) { // Not logging because this is not that important. } - return - + return + WROLPi {version} WROLPi.org Donate - + } function Root() { @@ -129,8 +126,7 @@ export default function App() { {/* Context and style to handle switching between mobile/computer. */} - {/* Toasts can be on any page. */} - + {/* Toasts (from components/ui) are mounted by ThemeProvider, which wraps every page. */} diff --git a/app/src/DashboardPage.js b/app/src/DashboardPage.js index 440b4d31..82902bc6 100644 --- a/app/src/DashboardPage.js +++ b/app/src/DashboardPage.js @@ -12,19 +12,22 @@ import {useHotkeys} from "react-hotkeys-hook"; import {Media, SettingsContext, StatusContext} from "./contexts/contexts"; import {DownloadMenu} from "./components/Download"; import { + ActionInput, Button, Divider, - Form, + Group, Header, + Icon, + Message, Modal, - Segment, - Statistic -} from "./components/Theme"; + Panel, + Stack, + Statistic, + StatisticGroup, +} from "./components/ui"; import {Link, useNavigate, useSearchParams} from "react-router"; import {BandwidthProgressCombined, CPUUsageProgress} from "./components/admin/Status"; import {ProgressPlaceholder} from "./components/Placeholder"; -import {GridColumn, GridRow, Icon, Input, Message} from "semantic-ui-react"; -import Grid from "semantic-ui-react/dist/commonjs/collections/Grid"; import {refreshFiles} from "./api"; import _ from "lodash"; import {TagsDashboard} from "./Tags"; @@ -37,6 +40,9 @@ import {fileMimetypeFilterOptions, FileCards, SearchFilterButton} from "./compon import {useCalculators} from "./components/Calculators"; import {classifyAndEvaluate} from "./components/calculators/mathConfig"; +// A spinning refresh glyph, used as the `icon` for the "files are being refreshed" Message. +const RefreshingIcon = (props) => ; + export function FlagsMessages() { const {settings, fetchSettings} = React.useContext(SettingsContext); const {status} = useContext(StatusContext); @@ -53,47 +59,44 @@ export function FlagsMessages() { // Do not tell the maintainer to refresh the files if the FileWorker is busy. if (flags.file_worker_busy) { // FileWorker is busy. - refreshingMessage = - - - Your files are being refreshed. -

Click here to view the progress

-
+ refreshingMessage = +

Click here to view the progress

; } else if (!flags.refresh_complete) { // `refresh_complete` flag is not set. Tell the maintainer to refresh the files. - refreshRequiredMessage = - - - Refresh required - Click here to refresh all your files. - + refreshRequiredMessage = + { + e.preventDefault(); + refreshFiles(); + }}>Click here to refresh all your files. ; } let dbDownMessage; if (!flags.db_up) { dbDownMessage = - Database is down - API is unable to connect to the database. Check the server logs. + Database is down +

API is unable to connect to the database. Check the server logs.

} let internetDownMessage; if (!flags.have_internet && !settings.wrol_mode) { internetDownMessage = - No Internet - WROLPi has no Internet. Downloads will not start. + No Internet +

WROLPi has no Internet. Downloads will not start.

; } let mediaUnmountedMessage; if (flags.media_mounted === false) { - mediaUnmountedMessage = - No drive mounted - WROLPi has no media drive mounted for one or more storage locations. - Downloads would write to the root filesystem and can fill it. - {' '}Open the Controller to mount a drive. + mediaUnmountedMessage = + No drive mounted +

+ WROLPi has no media drive mounted for one or more storage locations. + Downloads would write to the root filesystem and can fill it. + {' '}Open the Controller to mount a drive. +

; } @@ -140,7 +143,6 @@ function EvaluateForm() {
2 Tb to Gb
- const inputRef = React.useRef(); const [showMessage, setShowMessage] = React.useState(false); const [inputValue, setInputValue] = React.useState(''); const [evaluatedValue, setEvaluatedValue] = React.useState(helpContents); @@ -166,45 +168,36 @@ function EvaluateForm() { } } - return
- setShowMessage(true)} - onChange={(e, {value}) => setInputValue(value)} - action={} + return { + e.preventDefault(); + doEvaluate(); + }}> + setShowMessage(true)} + onChange={(e) => setInputValue(e.currentTarget.value)} + action={} /> {showMessage && - - Result - - {evaluatedValue} - + + {evaluatedValue} } - + } function DashboardCalculators() { const {calculatorLinks} = useCalculators(); - return + return
Calculators
- - - - - - - - - {calculatorLinks} - - - -
+ + +
{calculatorLinks}
+
+ } export function Getters() { @@ -244,25 +237,17 @@ export function Getters() { } } - const getter = - - Or - - - - - - - - - - ; + const getter = + + + + + + ; let getterModal; if (selectedGetter === 'downloads') { @@ -330,16 +315,16 @@ function DashboardStatus() { bandwidths = null; } - return + return
Status
- + - +
Bandwidth
{bandwidths} @@ -348,25 +333,25 @@ function DashboardStatus() { - + - + -
; + ; } function DashboardRecentFiles() { const {searchFiles, loading, fetchFiles} = useSearchRecentFiles(); - return + return - + } export function DashboardPage() { diff --git a/app/src/DashboardPage.test.js b/app/src/DashboardPage.test.js index c86d2021..20f71055 100644 --- a/app/src/DashboardPage.test.js +++ b/app/src/DashboardPage.test.js @@ -1,8 +1,7 @@ import React from 'react'; -import {render, screen} from '@testing-library/react'; -import {MemoryRouter} from 'react-router'; +import {render, screen} from './test-utils'; import {Getters, FlagsMessages} from './DashboardPage'; -import {SettingsContext, StatusContext, ThemeContext} from './contexts/contexts'; +import {SettingsContext, StatusContext} from './contexts/contexts'; // Replace DownloadMenu with a stub that records its props. The deep-link // behavior under test is just "Getters reads URL params and forwards them @@ -23,18 +22,14 @@ jest.mock('./hooks/customHooks', () => ({ })); function renderAtUrl(url) { + // test-utils' render() wraps content in a BrowserRouter (not MemoryRouter), + // so point the jsdom location at the desired URL before rendering. + window.history.pushState({}, '', url); const status = {flags: {refresh_complete: true}}; - const theme = { - i: {}, s: {}, t: {}, theme: 'light', inverted: false, setInverted: () => {}, - }; return render( - - - - - - - + + + ); } @@ -80,13 +75,11 @@ describe('DashboardPage Getters deep-link', () => { function renderFlagsMessages({flags = {}, settings = {}} = {}) { const status = {flags: {refresh_complete: true, db_up: true, have_internet: true, ...flags}}; return render( - - {}}}> - - - - - + {}}}> + + + + ); } diff --git a/app/src/Events.js b/app/src/Events.js index be4b6795..3d21622b 100644 --- a/app/src/Events.js +++ b/app/src/Events.js @@ -1,7 +1,7 @@ import React, {useEffect} from 'react'; import {useRecurringTimeout} from "./hooks/customHooks"; import {ApiDownError, getEvents} from "./api"; -import {toast} from "react-semantic-toasts-2"; +import {toast} from "./components/ui"; const apiEventName = 'apiEvent'; diff --git a/app/src/Tags.js b/app/src/Tags.js index ce2f42f2..585feac9 100644 --- a/app/src/Tags.js +++ b/app/src/Tags.js @@ -1,6 +1,5 @@ import React, {useEffect} from "react"; import {ApiDownError, deleteTag, getRecentTags, getTags, saveTag} from "./api"; -import {Dimmer, Divider, Grid, GridColumn, GridRow, Input, Label, TableCell, TableRow,} from "semantic-ui-react"; import { APIButton, contrastingColor, @@ -10,17 +9,24 @@ import { scrollToTopOfElement } from "./components/Common"; import { + Box, Button, - Form, + Divider, + Group, Header, - Loader, + Icon, + IconButton, + Label, + Loading, Modal, - Segment -} from "./components/Theme"; + Panel, + Table, + TextInput, +} from "./components/ui"; import _ from "lodash"; import {HexColorPicker} from "react-colorful"; import {useRecurringTimeout} from "./hooks/customHooks"; -import {Media, QueryContext, ThemeContext} from "./contexts/contexts"; +import {Media, QueryContext} from "./contexts/contexts"; import {Link, useNavigate} from "react-router"; import {TagPlaceholder} from "./components/Placeholder"; import {SortableTable} from "./components/SortableTable"; @@ -96,33 +102,36 @@ export function useTags() { || fuzzyMatch(lowerName, i.name.toLowerCase(), 2)) } + // A single tag chip. Tag colors are chosen by the user (stored per-tag), not by the + // theme, so they are rendered with the raw hex value rather than a token -- but the + // `wrolpi-label` className still gives them the theme's shape (and its night-mode + // outline treatment, which keys off the same `--label-color` variable). const NameToTagLabel = ({name, to, ...props}) => { const tag = findTagByName(name); if (tag !== null && tag !== undefined) { const tagColor = tag['color'] || DEFAULT_TAG_COLOR; const textColor = contrastingColor(tagColor); - const style = {...props['style'], backgroundColor: tagColor, color: textColor}; - return ; + ; } // No tags have been fetched. - return ; + return ; } const TagsGroup = ({tagNames, onClick}) => { if (!tagNames || tagNames.length === 0) { return ; } - return + return {tagNames.map(i => onClick(i)}/>)} - + } const TagLabelLink = ({name, props}) => { @@ -147,13 +156,13 @@ export function useTags() { return ; } - return + return {tagNames.map(i => )} - + } const SingleTag = ({name, ...props}) => { - return + return } useEffect(() => { @@ -187,16 +196,15 @@ function EditTagRow({tag, onDelete, onEdit}) { const {SingleTag} = React.useContext(TagsContext); const {name, color, id, file_group_count, zim_entry_count, channel_count, domain_count} = tag; - const deleteConfirm = <> - onDelete(id, name)} - /> - ; - const editButton = - - - Save - - - + + + Save + } @@ -378,7 +368,6 @@ function EditTagsModal() { } @@ -388,7 +377,7 @@ function EditTagsModal() {
- @@ -406,7 +395,6 @@ export function AddTagsButton({ limit = null, disabled = false, filterByOverlap = false, - color = 'violet', }) { // A button which displays a modal in which the user can add or remove tags. @@ -556,19 +544,17 @@ export function AddTagsButton({ const hideFrequentTags = filterByOverlap && localTags && localTags.length > 0; return <> - - {showAny && } - - - - + + + {!hideEdit && } + + + + {showAny && } + + +
@@ -663,43 +646,37 @@ export const TagsSelector = ({ return button; } - return - - - {button} - - - - - - + return + {button} + + + + } export const TagsDashboard = () => { const {tagNames, TagsLinkGroup} = React.useContext(TagsContext); - const tagPlaceholder = ; - let availableTagsGroup = - - {tagPlaceholder} - {tagPlaceholder} - {tagPlaceholder} - - ; + const tagPlaceholder = ; + let availableTagsGroup = + {tagPlaceholder} + {tagPlaceholder} + {tagPlaceholder} + ; if (tagNames && tagNames.length >= 1) { availableTagsGroup = ; } else if (tagNames === undefined) { availableTagsGroup = Could not fetch tags } - return + return
Tags
{availableTagsGroup} -
+ } export const TagsProvider = (props) => { diff --git a/app/src/api.js b/app/src/api.js index 3d8a3e4b..a55d44a8 100644 --- a/app/src/api.js +++ b/app/src/api.js @@ -1,5 +1,5 @@ import {emptyToNull} from "./components/Common"; -import {toast} from "react-semantic-toasts-2"; +import {toast} from "./components/ui"; import _ from "lodash"; import { API_URI, diff --git a/app/src/components/Archive.js b/app/src/components/Archive.js index 6824fff4..8893b919 100644 --- a/app/src/components/Archive.js +++ b/app/src/components/Archive.js @@ -237,28 +237,12 @@ function ArchivePage() { ? isoDatetimeToAgoPopup(archiveFile.published_modified_datetime, true) : 'unknown'; - const aboutPane = { - menuItem: 'About', render: () => -
Domain
- {domainHeader} - -
Size
- {humanFileSize(size)} - -
URL
-

{archiveFile.url ? {archiveFile.url} : 'N/A'}

- -
Modified Date
-

{modifiedDatetimeString}

-
- }; - // Helper to find file size from the files array by resolved path const findFileSize = (resolvedPath) => { if (!resolvedPath || !archiveFile.files) return null; const file = archiveFile.files.find(i => String(i.path) === String(resolvedPath)); return file && file.size - ? ({humanFileSize(file.size)}) + ? ({humanFileSize(file.size)}) : null; }; @@ -275,51 +259,11 @@ function ArchivePage() { const tableStyle = {width: '100%', borderCollapse: 'separate', borderSpacing: '0 0.7em'}; const labelStyle = {whiteSpace: 'nowrap', paddingRight: '1.5em', verticalAlign: 'top'}; - const filesPane = { - menuItem: 'Files', render: () => - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Singlefile File{localPreviewPath(data.singlefile_path, 'text/html')}
Readability File{localPreviewPath(data.readability_path, 'text/html')}
Readability Text File{localPreviewPath(data.readability_txt_path, 'text/plain')}
Readability JSON File{localPreviewPath(data.readability_json_path, 'application/json')}
Screenshot File - {screenshotPath - ? <>{screenshotPath}{findFileSize(screenshotPath)} - : 'Unknown'} -
Directory
-
- }; - - const tabPanes = [aboutPane, filesPane]; - const tabMenu = theme === darkTheme ? {inverted: true, attached: true} : {attached: true}; return <> - + {screenshot}
{textEllipsis(archiveFile.title || data.url)}
@@ -327,15 +271,13 @@ function ArchivePage() {
Author: {archiveFile.author ? archiveFile.author : 'unknown'}
- - - -
Published: {publishedDatetimeString}
-
- -
Downloaded: {downloadDatetimeString}
-
-
+ + +
Published: {publishedDatetimeString}
+
+ +
Downloaded: {downloadDatetimeString}
+
{singlefileButton} @@ -344,25 +286,78 @@ function ArchivePage() { {deleteButton} {generateScreenshotButton} -
+ - + - + - + + + About + Files + + +
Domain
+ {domainHeader} - +
Size
+ {humanFileSize(size)} + +
URL
+

{archiveFile.url ? {archiveFile.url} : 'N/A'}

+ +
Modified Date
+

{modifiedDatetimeString}

+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Singlefile File{localPreviewPath(data.singlefile_path, 'text/html')}
Readability File{localPreviewPath(data.readability_path, 'text/html')}
Readability Text File{localPreviewPath(data.readability_txt_path, 'text/plain')}
Readability JSON File{localPreviewPath(data.readability_json_path, 'application/json')}
Screenshot File + {screenshotPath + ? <>{screenshotPath}{findFileSize(screenshotPath)} + : 'Unknown'} +
Directory
+
+
+ + {historyList} -
+ { return dateRange[0] === null && dateRange[1] === null; @@ -39,9 +36,10 @@ export function MonthsForm({monthsSelected, setMonthsSelected}) { return { + size='lg' + onChange={(e) => { // Add or remove month index if the respective checkbox is checked. + const checked = e.currentTarget.checked; if (checked) { setMonthsSelected([...monthsSelected, idx]); } else { @@ -51,36 +49,37 @@ export function MonthsForm({monthsSelected, setMonthsSelected}) { /> } - return
- - - {monthCheckbox('January')} - {monthCheckbox('February')} - {monthCheckbox('March')} - - - {monthCheckbox('April')} - {monthCheckbox('May')} - {monthCheckbox('June')} - - - {monthCheckbox('July')} - {monthCheckbox('August')} - {monthCheckbox('September')} - - - {monthCheckbox('October')} - {monthCheckbox('November')} - {monthCheckbox('December')} - - - - - - - - -
+ const monthRowStyle = {display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: '0.7em', marginBottom: '0.7em'}; + const seasonRowStyle = {display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: '0.7em'}; + + return
+
+
{monthCheckbox('January')}
+
{monthCheckbox('February')}
+
{monthCheckbox('March')}
+
+
+
{monthCheckbox('April')}
+
{monthCheckbox('May')}
+
{monthCheckbox('June')}
+
+
+
{monthCheckbox('July')}
+
{monthCheckbox('August')}
+
{monthCheckbox('September')}
+
+
+
{monthCheckbox('October')}
+
{monthCheckbox('November')}
+
{monthCheckbox('December')}
+
+
+ + + + +
+
} export function DateRangeForm({dateRange, setDateRange}) { @@ -89,20 +88,16 @@ export function DateRangeForm({dateRange, setDateRange}) { let yearRange = []; for (let i = 1970; i <= currentYear; i++) { - yearRange = [...yearRange, { - key: i, - text: i, - value: i, - }]; + yearRange = [...yearRange, {value: i.toString(), label: i.toString()}]; } - const handleFromYear = (e, {value}) => { + const handleFromYear = (value) => { const toYear = dateRange[1] || currentYear; - setDateRange([value, toYear]); + setDateRange([value ? parseInt(value) : null, toYear]); } - const handleToYear = (e, {value}) => { - setDateRange([dateRange[0], value]); + const handleToYear = (value) => { + setDateRange([dateRange[0], value ? parseInt(value) : null]); } React.useEffect(() => { @@ -113,37 +108,33 @@ export function DateRangeForm({dateRange, setDateRange}) { } }, [dateRange]) - const errorMessage = error && ; + const errorMessage = error && {error}; return -
- - - - - - - - - - - - - - - - -
+ + + + + + {errorMessage}
} @@ -221,7 +212,7 @@ export function DateSelectorButton({ return - + + diff --git a/app/src/components/Download.js b/app/src/components/Download.js index a7af9306..d854348b 100644 --- a/app/src/components/Download.js +++ b/app/src/components/Download.js @@ -7,23 +7,18 @@ import { InfoPopup, mergeDeep, RequiredAsterisk, - useLocalStorage + SimpleAccordion, + Toggle, + useLocalStorage, + validURL, + validURLs, } from "./Common"; -import Icon from "semantic-ui-react/dist/commonjs/elements/Icon"; -import Message from "semantic-ui-react/dist/commonjs/collections/Message"; -import {Accordion, Button, Form, Header} from "./Theme"; -import {Form as SForm, FormDropdown} from "semantic-ui-react"; +import {Button, Group, Header, Icon, Message, MultiSelect, NumberInput, Select, Stack, TextInput, Textarea} from "./ui"; import {Link} from "react-router"; import {TagsSelector} from "../Tags"; -import Grid from "semantic-ui-react/dist/commonjs/collections/Grid"; import { commaSeparatedValidator, - InputForm, - NumberInputForm, - ToggleForm, - UrlInput, - UrlsTextarea, - useForm + useForm, } from "../hooks/useForm"; import { channelFrequencyOptions, @@ -41,8 +36,134 @@ import { weeklyOption } from "./Vars"; +/* + * Download.js was built around Semantic UI's
family (Form.Input, + * FormDropdown, TextArea) via `hooks/useForm.js`'s JSX helpers (InputForm, + * NumberInputForm, ToggleForm, UrlInput, UrlsTextarea). `hooks/useForm.js` is + * off-limits for this migration and its JSX helpers still render through + * `./Theme` (Semantic UI). Rather than use those helpers, the field + * components below call `useForm`'s plain data getters (getInputProps, + * getSelectionProps, getCustomProps) directly and render our own markup with + * the token-driven `./ui` library. See the migration report for what this + * leaves out of scope (hooks/useForm.js itself is unmigrated). + */ + +function FieldLabel({htmlFor, label, required, helpContent, helpPosition = 'top'}) { + if (!label) return null; + return +} + +/** Text field backed by `form.getInputProps`. TextInput passes a DOM event, which is exactly + * what `handleInputEvent` (inside useForm) expects, so the props can be spread through. */ +function TextField({ + form, name, path, type = 'text', validator, required = false, + placeholder = '', label, helpContent, helpPosition, disabled = false, + }) { + const [inputProps] = form.getInputProps({name, path, validator, type, required}); + return
+ + +
+} + +/** Number field. Mantine's NumberInput hands back the value itself, not an event, so it is + * wrapped into the event shape `handleInputEvent` expects. */ +function NumberField({ + form, name, path, validator, required = false, placeholder = '', + label, helpContent, helpPosition, min = 1, max = 9999999999, + }) { + validator = validator || ((value) => { + value = typeof value === 'number' ? value : parseFloat(value); + if (value < 0) { + return 'Number must be positive'; + } + }); + const [inputProps] = form.getInputProps({name, path, validator, type: 'number', required}); + const dataPath = inputProps['data-path']; + return
+ + inputProps.onChange({target: {value, type: 'number', dataset: {path: dataPath}}})} + disabled={inputProps.disabled} + error={inputProps.error} + /> +
+} + +/** A single-select field. `options` are Semantic-shaped ({key, text, value}); Mantine's Select + * requires string data values, so values are stringified for display and mapped back on change. */ +function SelectField({form, name, path, label, options, required = false, placeholder, disabled = false, afterChange}) { + const [inputProps] = form.getSelectionProps({name, path, required, afterChange}); + const data = options.map(o => ({value: String(o.value), label: o.text})); + const stringValue = (inputProps.value === null || inputProps.value === undefined) ? null : String(inputProps.value); + + const handleChange = (val) => { + if (val === null || val === undefined) { + inputProps.onChange(null, {value: null}); + return; + } + const match = options.find(o => String(o.value) === val); + inputProps.onChange(null, {value: match ? match.value : val}); + }; + + return
+ + - - + return } export function TitleExclusionInput({form, path = 'settings.title_exclude'}) { - const [inputProps, inputAttrs] = form.getInputProps({ - name: 'title_exclude', - path, - validator: commaSeparatedValidator, - }); - - return <> - - - - - + return } export function DownloadFormButtons({onCancel, form}) { - return - - - + Download + } export function EditDownloadFormButtons({onDelete, onCancel, form}) { - return - - - Delete - - - + Save + + } function VideoDownloadOrder({form, path = 'settings.download_order'}) { - const [inputProps, inputAttrs] = form.getSelectionProps({ - name: 'download_order', - path, - }); - - return } function VideoDownloadCountLimit({form, name = 'video_count_limit', path = 'settings.video_count_limit'}) { - return + return
- - +
} export function VideoFormatSelectorForm({form, name = 'video_format', path = 'settings.video_format'}) { - const [inputProps, inputAttrs] = form.getSelectionProps({ - name, - path, - defaultValue: defaultVideoFormatOption, - }); - - return <> + return
- - + +
} export function AudioOnlyToggle({form, onChange}) { - return { + inputProps.onChange(value); + if (onChange) onChange(value); + }} + info='Download only the audio track from videos.' /> } export function AudioFormatSelectorForm({form, name = 'audio_format', path = 'settings.audio_format'}) { - const [inputProps, inputAttrs] = form.getSelectionProps({ - name, - path, - defaultValue: defaultAudioFormatOption, - }); - - return <> + return
- - + +
} function VideoDurationLimit({form, name, path, label, helpContent, placeholder, helpPosition}) { - return + return
- +
} export function ChannelTagNameForm({form}) { - return <> + return
- +
} function AdvancedVideoSettings({form, isVideoLevel = false, isConfigLoaded = true}) { - const [active, setActive] = React.useState(false); - if (!isConfigLoaded) return null; - return - setActive(!active)}> - - Advanced Settings - - - - - - - - - - - - - - - - - - - - {isVideoLevel && - - - - - - - } - - - - - - - - - - - - - - - - + return + + + + + + + + + + {isVideoLevel && + + + + } + + + + + + + +} + +/** A labeled Toggle backed by `form.getCustomProps`. */ +function AudioOnlyToggleLikeVideoSetting({form, name, path, label, icon}) { + const [inputProps] = form.getCustomProps({name, path}); + return } export function CompressSinglefileToggle({form}) { - return <> + const [inputProps] = form.getCustomProps({name: 'compress_singlefile', path: 'settings.compress_singlefile'}); + return
- - + +
} function AdvancedDownloadSettings({form}) { - const [active, setActive] = React.useState(false); + const [inputProps] = form.getCustomProps({ + name: 'skip_already_downloaded', + path: 'settings.skip_already_downloaded' + }); - return - setActive(!active)}> - - Advanced Settings - - - - - - - - - - - + return + + } export function VideosDownloadForm({ @@ -667,77 +675,42 @@ export function VideosDownloadForm({ // This form can handle a single Video download, or multiple video downloads. const urlInput = singleDownload ? - - : ; + + : ; - return -
- - Videos -
+ return e.preventDefault()}> +
Videos

Download each video at the URLs provided below.

- - - {urlInput} - - - - - - - - - - - - - - - - - - + + {urlInput} + + + {form.formData?.settings?.audio_only - ? - - - - - : - + ? + : +
setUserChangedResolutions(true)} /> - - +
+
- - +
+
} - - - - - - - - - - + + {showMessage && } - - - {actions ? actions({onCancel: localOnCancel, form}) : - } - - -
- + {actions ? actions({onCancel: localOnCancel, form}) : + } + + } @@ -925,108 +898,67 @@ export function ChannelDownloadForm({ } }, [form.formData]); - const onceMessage = - Download Once - You have selected a frequency of Once, this is useful when you want to download - all videos in a Playlist, and when you do not want to download any videos added to the playlist - in the future. + const onceMessage = + You have selected a frequency of Once, this is useful when you want to download + all videos in a Playlist, and when you do not want to download any videos added to the playlist + in the future. ; // Default to "new" download buttons. actions = actions || DownloadFormButtons; const actionsElm = actions({onDelete, onCancel, form}); - return
-
Channel / Playlist
+ return e.preventDefault()}> +
Channel / Playlist
- - - - - - - - - - - - - + + + + +
- - +
+
- - - {form.formData.frequency === 0 && {onceMessage}} - - - - - - - - - - - - - - - - - - - - - +
+
+ {form.formData.frequency === 0 && onceMessage} + + + + + + + + + {form.formData?.settings?.audio_only - ? - - - - - : - + ? + : +
setUserChangedResolutions(true)} /> - - +
+
- - +
+
} - - - - - - - - - - - - - - - - - - + + + + + + {showMessage && } - - - {actionsElm} - - -
-
+ {actionsElm} + + } export function EditChannelDownloadForm({ @@ -1064,15 +996,9 @@ export function EditChannelDownloadForm({ } function SuccessfulDownloadSubmitMessage() { - return - - Download Submitted - - View downloads - - - - + return + View downloads + } export function EditArchiveDownloadForm({ @@ -1166,43 +1092,23 @@ export function ArchiveDownloadForm({ } const urlInput = singleDownload ? - - : ; + + : ; - return
-
Archives
+ return e.preventDefault()}> +
Archives

Create a Singlefile Archive for each of the URLs provided below.

- - - - {urlInput} - - - - - - - - - - - - - - - - - + + {urlInput} + + + {showMessage && } - - - {actions ? actions({onCancel: localOnCancel, form}) : - } - - - -
+ {actions ? actions({onCancel: localOnCancel, form}) : + } + + } export function RSSDownloadForm({download, submitter, onDelete, onCancel, actions, clearOnSuccess = true}) { @@ -1323,106 +1229,58 @@ export function RSSDownloadForm({download, submitter, onDelete, onCancel, action let downloaderRows; if (form.formData.sub_downloader === Downloaders.Video) { downloaderRows = <> - - - - - - - - - - - - - - - - - - + + + + + + {form.formData?.settings?.audio_only - ? - - - - - : - + ? + : +
setUserChangedResolutions(true)} /> - - +
+
- - +
+
} - - - - - - - - - - - - - + + + + + ; } else if (form.formData.sub_downloader === Downloaders.Archive) { downloaderRows = <> - - - - - - - - - - + + ; } - return
-
RSS Feed
+ return e.preventDefault()}> +
RSS Feed

Download each link provided by this RSS feed using the selected downloader.

- - - - - - - - - - - - - - - - - - - + + + + + + + {downloaderRows} {showMessage && } - - - {actionsElm} - - - -
+ {actionsElm} + + } export function EditRSSDownloadForm({download, onDelete, onCancel, actions = EditDownloadFormButtons}) { @@ -1486,28 +1344,16 @@ export function EditZimDownloadForm({download, onDelete, onCancel, actions = Edi actions = actions || DownloadFormButtons; const actionsElm = actions({onDelete, onCancel, form}); - return
+ return e.preventDefault()}>
Zim File
- - - - - - - - - - - + + + {showMessage && } - - - {actionsElm} - - - -
+ {actionsElm} + + } export function FilesDownloadForm({ @@ -1549,39 +1395,19 @@ export function FilesDownloadForm({ const actionsElm = actions({onCancel, form}); - return
-
Files
+ return e.preventDefault()}> +
Files

Download each file at the URLs provided below.

- - - - - - - - - - - - - - - - - - - - - + + + + + {showMessage && } - - - {actionsElm} - - - -
+ {actionsElm} + + } const suffixValidator = (value) => { @@ -1602,7 +1428,7 @@ const suffixValidator = (value) => { } export function SuffixFormInput({form, name = 'suffix', path = 'settings.suffix'}) { - return - : ; + + : ; // Default to "new" download buttons. actions = actions || DownloadFormButtons; const actionsElm = actions({onDelete, onCancel, form}); - return
-
Scrape Files
+ return e.preventDefault()}> +
Scrape Files

Search each of the URLs for files matching the suffix (.pdf, etc.).

- - - - {urlInput} - - - - + + {urlInput} + +
- - +
+
- - - - - - - - - - +
+
+ + + + {showMessage && } - - - {actionsElm} - - -
-
+ {actionsElm} + + } export function EditScrapeFilesDownloadForm({download, onDelete, onCancel, onSuccess}) { @@ -1733,6 +1547,67 @@ export function EditScrapeFilesDownloadForm({download, onDelete, onCancel, onSuc /> } +/** URL field for a single URL (Semantic's `UrlInput`). */ +function UrlField({form, required = true, name = 'url', path = 'url', disabled = false}) { + const validator = (i) => validURL(i) ? null : 'Invalid URL'; + return +} + +/** Multiline URLs field (Semantic's `UrlsTextarea`). */ +function UrlsField({name = 'urls', required, form}) { + required = required !== undefined; + + const validator = (value) => { + if (!validURLs(value)) { + return 'Invalid URLs'; + } + }; + + const [inputProps, inputAttrs] = form.getInputProps({name, validator, required}); + + const handleDrop = (e) => { + if (e) e.preventDefault(); + const droppedUrl = e.dataTransfer.getData('text'); + let urls = (inputProps.value || '').split('\n'); + urls = [...urls, droppedUrl]; + urls = urls.filter(i => !!i).join('\n'); + inputAttrs.localSetValue(`${urls}\n`); + }; + + const handleKeyDown = (event) => { + if ((event.ctrlKey || event.metaKey) && event.key === 'Enter') { + event.preventDefault(); + form.onSubmit(); + } + }; + + return
+ +