Reworking CollectionTable and CollectionEditForm.

This commit is contained in:
Roland 2025-12-02 15:33:46 -07:00
parent 5fc16f3f79
commit 2680263c41
No known key found for this signature in database
GPG key ID: 1BA620CE6C9A4680
8 changed files with 864 additions and 225 deletions

View file

@ -258,3 +258,73 @@ table.ratio-table td.equal-width {
table.ratio-table td.min-width {
width: auto;
}
/* CollectionEditForm styles */
.required-indicator {
color: red;
}
.action-button-spacing {
margin-top: 1em;
}
/* Form loading skeleton */
.form-skeleton-field {
margin-bottom: 1.5em;
}
.form-skeleton-label {
height: 14px;
width: 80px;
margin-bottom: 8px;
background: linear-gradient(90deg, #e0e0e0 25%, #f0f0f0 50%, #e0e0e0 75%);
background-size: 200% 100%;
animation: skeleton-shimmer 1.5s infinite;
border-radius: 3px;
}
.form-skeleton-input {
height: 38px;
width: 100%;
background: linear-gradient(90deg, #e0e0e0 25%, #f0f0f0 50%, #e0e0e0 75%);
background-size: 200% 100%;
animation: skeleton-shimmer 1.5s infinite;
border-radius: 4px;
}
.form-skeleton-textarea {
height: 80px;
width: 100%;
background: linear-gradient(90deg, #e0e0e0 25%, #f0f0f0 50%, #e0e0e0 75%);
background-size: 200% 100%;
animation: skeleton-shimmer 1.5s infinite;
border-radius: 4px;
}
.form-skeleton-button {
height: 42px;
width: 100px;
background: linear-gradient(90deg, #e0e0e0 25%, #f0f0f0 50%, #e0e0e0 75%);
background-size: 200% 100%;
animation: skeleton-shimmer 1.5s infinite;
border-radius: 4px;
}
@keyframes skeleton-shimmer {
0% {
background-position: -200% 0;
}
100% {
background-position: 200% 0;
}
}
/* Dark mode skeleton */
.inverted .form-skeleton-label,
.inverted .form-skeleton-input,
.inverted .form-skeleton-textarea,
.inverted .form-skeleton-button {
background: linear-gradient(90deg, #333 25%, #444 50%, #333 75%);
background-size: 200% 100%;
animation: skeleton-shimmer 1.5s infinite;
}

View file

@ -255,9 +255,17 @@ export function RequiredAsterisk() {
return <span style={{color: '#db2828'}}> *</span>
}
export function secondsToFrequency(seconds) {
const option = allFrequencyOptions[seconds];
return option ? option.text : null;
/**
* Format a frequency value (in seconds) to a human-readable string using allFrequencyOptions.
* @param {number|null} frequency - Frequency in seconds
* @returns {string} Human-readable frequency text or '-' if null/undefined
*/
export function formatFrequency(frequency) {
if (frequency === null || frequency === undefined) {
return '-';
}
const option = allFrequencyOptions[frequency];
return option ? option.text : `${frequency}s`;
}
const secondsToYears = 31536000;

View file

@ -12,13 +12,14 @@ import {
APIButton,
DisableDownloadsToggle,
ErrorMessage,
formatFrequency,
isoDatetimeToElapsedPopup,
secondsToFrequency,
useTitle,
WROLModeMessage
} from "../Common";
import {
Button as SButton, ButtonGroup,
Button as SButton,
ButtonGroup,
Label,
Loader,
PlaceholderLine,
@ -32,12 +33,12 @@ import {
import {Button, Header, Modal, ModalActions, ModalContent, ModalHeader, Placeholder, Segment, Table} from "../Theme";
import {useDownloads} from "../../hooks/customHooks";
import {
EditArchiveDownloadForm,
EditChannelDownloadForm,
EditRSSDownloadForm,
EditScrapeFilesDownloadForm,
EditZimDownloadForm,
EditVideosDownloadForm,
EditArchiveDownloadForm
EditZimDownloadForm
} from "../Download";
import {Downloaders} from "../Vars";
@ -230,7 +231,7 @@ function RecurringDownloadRow({download, fetchDownloads, onDelete}) {
<TableCell className='column-ellipsis'>
{link(url)}
</TableCell>
<TableCell>{secondsToFrequency(frequency)}</TableCell>
<TableCell>{formatFrequency(frequency)}</TableCell>
<TableCell>
{last_successful_download && isoDatetimeToElapsedPopup(last_successful_download)}
{status === 'pending' && <Loader active inline size='tiny'/>}
@ -278,11 +279,11 @@ class OnceDownloadRow extends React.Component {
};
handleEditOpen = () => {
this.setState({ editModalOpen: true });
this.setState({editModalOpen: true});
};
handleEditClose = () => {
this.setState({ editModalOpen: false });
this.setState({editModalOpen: false});
};
handleEditSuccess = async () => {
@ -317,29 +318,29 @@ class OnceDownloadRow extends React.Component {
<TableCell>
<ButtonGroup>
<APIButton
color='red'
icon='trash'
onClick={this.handleDelete}
confirmContent='Are you sure you want to delete this download?'
confirmButton='Delete'
obeyWROLMode={true}
/>
{(downloader === Downloaders.Video || downloader === Downloaders.Archive) && status !== 'pending' && (
<Button
icon='edit'
color='blue'
onClick={this.handleEditOpen}
<APIButton
color='red'
icon='trash'
onClick={this.handleDelete}
confirmContent='Are you sure you want to delete this download?'
confirmButton='Delete'
obeyWROLMode={true}
/>
{(downloader === Downloaders.Video || downloader === Downloaders.Archive) && status !== 'pending' && (
<Button
icon='edit'
color='blue'
onClick={this.handleEditOpen}
/>
)}
<APIButton
color='green'
icon='redo'
confirmContent='Are you sure you want to restart this download?'
confirmButton='Start'
onClick={this.handleRestart}
obeyWROLMode={true}
/>
)}
<APIButton
color='green'
icon='redo'
confirmContent='Are you sure you want to restart this download?'
confirmButton='Start'
onClick={this.handleRestart}
obeyWROLMode={true}
/>
</ButtonGroup>
</TableCell>
);

View file

@ -6,6 +6,96 @@ import {WROLModeMessage} from '../Common';
import {DestinationForm} from '../Download';
import {InputForm} from '../../hooks/useForm';
/**
* Renders a single form field based on field configuration.
* Extracted outside the component to avoid recreation on every render.
*
* @param {Object} field - Field configuration from metadata
* @param {Object} form - Form object from useForm hook
* @param {Object} metadata - Backend-provided metadata containing messages
*/
function renderField(field, form, metadata) {
const disabled = field.depends_on && !form.formData[field.depends_on];
switch (field.type) {
case 'directory':
return <DestinationForm
form={form}
label={field.label}
name={field.key}
path={field.key}
required={field.required}
/>;
case 'text':
return <InputForm
form={form}
label={field.label}
name={field.key}
placeholder={field.placeholder}
required={field.required}
/>;
case 'textarea':
const [textareaProps] = form.getCustomProps({name: field.key, path: field.key, required: field.required});
return <Form.Field>
<label>
{field.label}
{field.required && <span className="required-indicator"> *</span>}
</label>
<TextArea
placeholder={field.placeholder}
{...textareaProps}
onChange={(e, {value}) => textareaProps.onChange(value)}
rows={3}
/>
</Form.Field>;
case 'tag':
const [tagProps] = form.getCustomProps({name: field.key, path: field.key, required: field.required});
return <Form.Field disabled={disabled}>
<label>
{field.label}
{field.required && <span className="required-indicator"> *</span>}
</label>
{disabled && <Message info size='small'>
{metadata.messages?.no_directory || 'Set a directory to enable tagging'}
</Message>}
<TagsSelector
selectedTagNames={tagProps.value ? [tagProps.value] : []}
onChange={(tagNames) => tagProps.onChange(tagNames[0] || null)}
single={true}
disabled={disabled || tagProps.disabled}
/>
{!disabled && tagProps.value && metadata.messages?.tag_will_move && <Message warning size='small'>
{metadata.messages.tag_will_move}
</Message>}
</Form.Field>;
default:
return null;
}
}
/**
* Loading skeleton component for the form.
*/
function FormSkeleton({fieldCount = 3}) {
return (
<div>
{Array.from({length: fieldCount}).map((_, i) => (
<div key={i} className="form-skeleton-field">
<div className="form-skeleton-label"/>
<div className={i === fieldCount - 1 ? "form-skeleton-textarea" : "form-skeleton-input"}/>
</div>
))}
<div style={{display: 'flex', justifyContent: 'flex-end', marginTop: '1em'}}>
<div className="form-skeleton-button"/>
</div>
</div>
);
}
/**
* Reusable form component for editing collections (Domains, Channels, etc).
*
@ -27,6 +117,7 @@ export function CollectionEditForm({
appliedTagName
}) {
const {SingleTag} = React.useContext(TagsContext);
if (!metadata) {
return <Message warning>
<Message.Header>No metadata available</Message.Header>
@ -38,115 +129,64 @@ export function CollectionEditForm({
form.onSubmit();
};
const renderField = (field) => {
const value = form.formData[field.key] || '';
const disabled = field.depends_on && !form.formData[field.depends_on];
switch (field.type) {
case 'text':
if (field.key === 'directory') {
// Use DestinationForm for directory picker
return <DestinationForm
key={field.key}
form={form}
label={field.label}
name={field.key}
path={field.key}
required={field.required}
/>;
}
// Use InputForm for regular text fields
return <InputForm
key={field.key}
form={form}
label={field.label}
name={field.key}
placeholder={field.placeholder}
required={field.required}
/>;
case 'textarea':
// Textarea doesn't have a form component, use manual Field
const [textareaProps] = form.getCustomProps({name: field.key, path: field.key, required: field.required});
return <Form.Field key={field.key}>
<label>{field.label}{field.required && <span style={{color: 'red'}}> *</span>}</label>
<TextArea
placeholder={field.placeholder}
{...textareaProps}
onChange={(e, {value}) => textareaProps.onChange(value)}
rows={3}
/>
</Form.Field>;
case 'tag':
// TagsSelector is custom, use manual Field with form props
const [tagProps] = form.getCustomProps({name: field.key, path: field.key, required: field.required});
return <Form.Field key={field.key} disabled={disabled}>
<label>{field.label}{field.required && <span style={{color: 'red'}}> *</span>}</label>
{disabled && <Message info size='small'>
{metadata.messages?.no_directory || 'Set a directory to enable tagging'}
</Message>}
<TagsSelector
selectedTagNames={tagProps.value ? [tagProps.value] : []}
onChange={(tagNames) => tagProps.onChange(tagNames[0] || null)}
single={true}
disabled={disabled || tagProps.disabled}
/>
{!disabled && tagProps.value && metadata.messages?.tag_will_move && <Message warning size='small'>
{metadata.messages.tag_will_move}
</Message>}
</Form.Field>;
default:
return null;
}
};
// Show skeleton when loading and no form data yet
const showSkeleton = form.loading && Object.keys(form.formData).length === 0;
return <Segment>
{title && <Header as="h1">{title}</Header>}
{wrolModeContent && <WROLModeMessage content={wrolModeContent}/>}
<Form onSubmit={handleSubmit} loading={form.loading} autoComplete="off">
<Grid stackable columns={2}>
{metadata.fields.map(field => (
<Grid.Row key={field.key}>
<Grid.Column width={16}>
{renderField(field)}
{/* Display form-level errors */}
{form.error && <Message error>
<Message.Header>Error</Message.Header>
<p>{form.error}</p>
</Message>}
{showSkeleton ? (
<FormSkeleton fieldCount={metadata.fields.length}/>
) : (
<Form onSubmit={handleSubmit} loading={form.loading} autoComplete="off">
<Grid stackable>
{metadata.fields.map(field => (
<Grid.Row key={field.key}>
<Grid.Column>
{renderField(field, form, metadata)}
</Grid.Column>
</Grid.Row>
))}
{appliedTagName && <Grid.Row>
<Grid.Column>
<SingleTag name={appliedTagName}/>
</Grid.Column>
</Grid.Row>}
<Grid.Row columns={2}>
<Grid.Column>
{actionButtons}
{onCancel && <Button
type='button'
onClick={onCancel}
disabled={form.disabled}
className="action-button-spacing"
>
Cancel
</Button>}
</Grid.Column>
<Grid.Column>
<Button
type='submit'
color='violet'
size='big'
floated='right'
disabled={form.disabled}
>
Save
</Button>
</Grid.Column>
</Grid.Row>
))}
{appliedTagName && <Grid.Row>
<Grid.Column>
<SingleTag name={appliedTagName}/>
</Grid.Column>
</Grid.Row>}
<Grid.Row>
<Grid.Column width={8}>
{actionButtons}
{onCancel && <Button
type='button'
onClick={onCancel}
disabled={form.disabled}
style={{marginTop: '1em'}}
>
Cancel
</Button>}
</Grid.Column>
<Grid.Column width={8}>
<Button
type='submit'
color='violet'
size='big'
floated='right'
disabled={form.disabled}
>
Save
</Button>
</Grid.Column>
</Grid.Row>
</Grid>
</Form>
</Grid>
</Form>
)}
</Segment>;
}

View file

@ -133,7 +133,7 @@ describe('CollectionEditForm', () => {
expect(descriptionField.tagName).toBe('TEXTAREA');
});
it('renders directory field using DestinationForm', () => {
it('renders directory field using DestinationForm for type=directory', () => {
const form = createTestForm(mockCollection);
render(
@ -276,6 +276,76 @@ describe('CollectionEditForm', () => {
// Should show warning about missing metadata
expect(screen.getByText(/no metadata available/i)).toBeInTheDocument();
});
it('displays form-level errors', () => {
const form = createTestForm(mockCollection, {
overrides: {error: 'Something went wrong'}
});
render(
<CollectionEditForm
form={form}
metadata={mockMetadata}
/>
);
// Should display the error message
expect(screen.getByText(/something went wrong/i)).toBeInTheDocument();
});
});
describe('Loading Skeleton', () => {
it('shows skeleton when loading with empty form data', () => {
const form = createTestForm({}, {
overrides: {loading: true}
});
const {container} = render(
<CollectionEditForm
form={form}
metadata={mockMetadata}
/>
);
// Should show skeleton elements
expect(container.querySelector('.form-skeleton-label')).toBeInTheDocument();
expect(container.querySelector('.form-skeleton-input')).toBeInTheDocument();
});
it('shows form (not skeleton) when loading with existing form data', () => {
const form = createTestForm(mockCollection, {
overrides: {loading: true}
});
const {container} = render(
<CollectionEditForm
form={form}
metadata={mockMetadata}
/>
);
// Should NOT show skeleton when there's form data
expect(container.querySelector('.form-skeleton-label')).not.toBeInTheDocument();
// Should show actual form fields
expect(screen.getByTestId('directory-search')).toBeInTheDocument();
});
it('renders correct number of skeleton fields based on metadata', () => {
const form = createTestForm({}, {
overrides: {loading: true}
});
const {container} = render(
<CollectionEditForm
form={form}
metadata={mockMetadata}
/>
);
// Should have skeleton fields equal to metadata.fields.length (3)
const skeletonFields = container.querySelectorAll('.form-skeleton-field');
expect(skeletonFields).toHaveLength(mockMetadata.fields.length);
});
});
describe('Theme Integration', () => {
@ -344,4 +414,44 @@ describe('CollectionEditForm', () => {
expect(hasInvertedStyling(segment)).toBe(false);
});
});
describe('CSS Classes', () => {
it('uses required-indicator class for required fields', () => {
const metadataWithRequired = createMockMetadata('domain', {
fields: [
{key: 'name', label: 'Name', type: 'text', required: true},
{key: 'description', label: 'Description', type: 'textarea', required: true},
]
});
const form = createTestForm(mockCollection);
const {container} = render(
<CollectionEditForm
form={form}
metadata={metadataWithRequired}
/>
);
// Should use CSS class instead of inline style for required indicator
const requiredIndicators = container.querySelectorAll('.required-indicator');
expect(requiredIndicators.length).toBeGreaterThan(0);
});
it('uses action-button-spacing class for cancel button', () => {
const form = createTestForm(mockCollection);
const mockOnCancel = jest.fn();
const {container} = render(
<CollectionEditForm
form={form}
metadata={mockMetadata}
onCancel={mockOnCancel}
/>
);
const cancelButton = screen.getByRole('button', {name: /cancel/i});
expect(cancelButton).toHaveClass('action-button-spacing');
});
});
});

View file

@ -3,22 +3,43 @@ import {Link} from 'react-router-dom';
import {Message, Placeholder, PlaceholderHeader, PlaceholderLine, Table, TableCell, TableRow} from 'semantic-ui-react';
import _ from 'lodash';
import {SortableTable} from '../SortableTable';
import {humanFileSize} from '../Common';
import {humanFileSize, formatFrequency} from '../Common';
import {ThemeContext, Media} from '../../contexts/contexts';
import {TagsContext} from '../../Tags';
import {allFrequencyOptions} from '../Vars';
/**
* Format a frequency value (in seconds) to a human-readable string using allFrequencyOptions.
* @param {number|null} frequency - Frequency in seconds
* @returns {string} Human-readable frequency text or '-' if null/undefined
* Get the ID field from metadata routes configuration.
* @param {Object} metadata - Collection metadata
* @returns {string} The ID field name
*/
function formatFrequency(frequency) {
if (frequency === null || frequency === undefined) {
return '-';
}
const option = allFrequencyOptions[frequency];
return option ? option.text : `${frequency}s`;
function getIdField(metadata) {
return metadata?.routes?.id_field || 'id';
}
/**
* Calculate column widths based on column metadata.
* Uses Semantic UI's 16-column grid system.
*
* @param {Array} columns - Array of column configurations
* @returns {Array} Array of width values (1-16)
*/
function calculateColumnWidths(columns) {
const TOTAL = 16;
const widths = columns.map(col => {
if (col.type === 'actions') return 1;
if (col.format === 'bytes' || col.format === 'frequency') return 2;
if (col.align === 'right') return 2; // numeric columns
if (col.key === 'tag_name') return 2;
return null; // grow column - calculate later
});
// Distribute remaining space to null (grow) columns
const fixedWidth = widths.filter(w => w !== null).reduce((a, b) => a + b, 0);
const growColumns = widths.filter(w => w === null).length;
const growWidth = Math.floor((TOTAL - fixedWidth) / (growColumns || 1));
return widths.map(w => w === null ? growWidth : w);
}
/**
@ -42,8 +63,7 @@ function getCollectionSearchLink(collection, metadata, primaryKey) {
return `${searchRoute}?${metadata.routes.searchParam}=${collection[primaryKey]}`;
} else if (searchRoute.includes(':id')) {
// Route parameter-based linking (e.g., /videos/channel/123/video)
// Use id_field if specified (e.g., channel_id for channels), otherwise use id
const idField = metadata.routes.id_field || 'id';
const idField = getIdField(metadata);
return searchRoute.replace(':id', collection[idField]);
}
@ -51,14 +71,71 @@ function getCollectionSearchLink(collection, metadata, primaryKey) {
return null;
}
/**
* Render a single table row for desktop view.
*
* @param {Object} collection - The collection data
* @param {Object} metadata - Collection metadata
* @param {string} inverted - Inverted theme class
* @param {Function} SingleTag - Tag component from context
* @param {Function} onRowClick - Optional click handler
* @param {Array} columnWidths - Calculated column widths
*/
function renderRow(collection, metadata, inverted, SingleTag, onRowClick, columnWidths) {
const cells = metadata.columns.map((col, index) => {
let value = collection[col.key];
// Handle actions column - render action buttons
if (col.type === 'actions') {
const idField = getIdField(metadata);
const editRoute = metadata.routes?.edit?.replace(':id', collection[idField]);
const buttonClass = `ui button secondary ${inverted}`;
return <Table.Cell key={col.key} textAlign={col.align || 'right'} width={columnWidths[index]}>
{editRoute && <Link className={buttonClass} to={editRoute}>Edit</Link>}
</Table.Cell>;
}
// Format the value based on column configuration
if (col.format === 'bytes') {
value = humanFileSize(value);
} else if (col.format === 'frequency') {
value = formatFrequency(value);
}
// Special handling for tag_name column - render SingleTag component
if (col.key === 'tag_name' && value) {
value = <SingleTag name={value} />;
}
// Special handling for the primary column (usually domain/name)
if (col.key === metadata.columns[0].key) {
const searchLink = getCollectionSearchLink(collection, metadata, col.key);
if (searchLink) {
value = <Link to={searchLink}>{value}</Link>;
}
}
return <Table.Cell key={col.key} textAlign={col.align || 'left'} width={columnWidths[index]}>
{value || '-'}
</Table.Cell>;
});
return <Table.Row
key={collection.id}
onClick={() => onRowClick && onRowClick(collection)}
className={onRowClick ? 'clickable' : ''}
>
{cells}
</Table.Row>;
}
/**
* Mobile row component for collections
*/
function MobileCollectionRow({collection, metadata}) {
const {SingleTag} = useContext(TagsContext);
const primaryColumn = metadata.columns[0];
// Use id_field if specified (e.g., channel_id for channels), otherwise use id
const idField = metadata.routes?.id_field || 'id';
const idField = getIdField(metadata);
const editRoute = metadata.routes?.edit?.replace(':id', collection[idField]);
const searchLink = getCollectionSearchLink(collection, metadata, primaryColumn.key);
@ -161,80 +238,16 @@ export function CollectionTable({collections, metadata, searchStr = '', onRowCli
});
}
// Build row renderer based on metadata
const renderRow = (collection) => {
const cells = metadata.columns.map(col => {
let value = collection[col.key];
// Handle actions column - render action buttons
if (col.type === 'actions') {
// Use id_field if specified (e.g., channel_id for channels), otherwise use id
const idField = metadata.routes?.id_field || 'id';
const editRoute = metadata.routes?.edit?.replace(':id', collection[idField]);
const buttonClass = `ui button secondary ${inverted}`;
return <Table.Cell key={col.key} textAlign={col.align || 'right'}>
{editRoute && <Link className={buttonClass} to={editRoute}>Edit</Link>}
</Table.Cell>;
}
// Format the value based on column configuration
if (col.format === 'bytes') {
value = humanFileSize(value);
} else if (col.format === 'frequency') {
value = formatFrequency(value);
}
// Special handling for tag_name column - render SingleTag component
if (col.key === 'tag_name' && value) {
value = <SingleTag name={value} />;
}
// Special handling for the primary column (usually domain/name)
if (col.key === metadata.columns[0].key) {
const searchLink = getCollectionSearchLink(collection, metadata, col.key);
if (searchLink) {
value = <Link to={searchLink}>{value}</Link>;
}
}
return <Table.Cell key={col.key} textAlign={col.align || 'left'}>
{value || '-'}
</Table.Cell>;
});
return <Table.Row
key={collection.id}
onClick={() => onRowClick && onRowClick(collection)}
style={onRowClick ? {cursor: 'pointer'} : {}}
>
{cells}
</Table.Row>;
};
// Calculate column widths dynamically
const columnWidths = calculateColumnWidths(metadata.columns);
// Build table headers from metadata (desktop)
const headers = metadata.columns.map((col, index) => {
// Determine width based on column position and type
// Widths use Semantic UI's 16-column grid system and should sum to 16
let width = null;
if (index === 0) {
// First column (name/domain) - gets most space to expand
// For 6 columns: 16 - (2+2+2+2+1) = 7
width = 7;
} else if (col.type === 'actions') {
// Actions column - minimum width to shrink to fit button
width = 1;
} else {
// Other columns (tags, counts, frequency, sizes)
width = 2;
}
return {
key: col.key,
text: col.label,
sortBy: col.sortable ? col.key : null,
width: width,
};
});
const headers = metadata.columns.map((col, index) => ({
key: col.key,
text: col.label,
sortBy: col.sortable ? col.key : null,
width: columnWidths[index],
}));
// Build mobile headers - simplified columns
const primaryColumn = metadata.columns[0];
@ -269,7 +282,7 @@ export function CollectionTable({collections, metadata, searchStr = '', onRowCli
<SortableTable
tableProps={{striped: true, size: 'large', unstackable: true, compact: true}}
data={filteredCollections}
rowFunc={(collection) => renderRow(collection)}
rowFunc={(collection) => renderRow(collection, metadata, inverted, SingleTag, onRowClick, columnWidths)}
rowKey='id'
tableHeaders={headers}
defaultSortColumn={defaultSortColumn}

View file

@ -0,0 +1,397 @@
import React from 'react';
import {render, screen, renderInDarkMode, renderInLightMode, hasInvertedStyling} from '../../test-utils';
import {CollectionTable} from './CollectionTable';
import {createMockMetadata, createMockDomains} from '../../test-utils';
// Mock the TagsContext
jest.mock('../../Tags', () => ({
TagsContext: {
_currentValue: {
SingleTag: ({name}) => <span data-testid="single-tag">{name}</span>
}
},
}));
// Mock the Media component to test both mobile and desktop views
jest.mock('../../contexts/contexts', () => ({
...jest.requireActual('../../contexts/contexts'),
Media: ({children, at, greaterThanOrEqual}) => {
// Default to desktop view for most tests
if (greaterThanOrEqual === 'tablet') {
return <div data-testid="desktop-view">{children}</div>;
}
if (at === 'mobile') {
return <div data-testid="mobile-view">{children}</div>;
}
return children;
},
}));
// Mock SortableTable to simplify testing
jest.mock('../SortableTable', () => ({
SortableTable: ({data, rowFunc, tableHeaders}) => (
<table data-testid="sortable-table">
<thead>
<tr>
{tableHeaders.map(h => (
<th key={h.key} data-width={h.width}>{h.text}</th>
))}
</tr>
</thead>
<tbody>
{data.map(item => rowFunc(item))}
</tbody>
</table>
),
}));
describe('CollectionTable', () => {
const mockMetadata = createMockMetadata();
const mockCollections = createMockDomains(3);
describe('Loading and Error States', () => {
it('renders loading placeholder when collections is null', () => {
const {container} = render(
<CollectionTable
collections={null}
metadata={mockMetadata}
/>
);
expect(container.querySelector('.ui.placeholder')).toBeInTheDocument();
});
it('renders error message when collections is undefined', () => {
render(
<CollectionTable
collections={undefined}
metadata={mockMetadata}
/>
);
expect(screen.getByText(/could not fetch collections/i)).toBeInTheDocument();
});
it('renders empty message when collections is empty array', () => {
render(
<CollectionTable
collections={[]}
metadata={mockMetadata}
/>
);
expect(screen.getByText(/no items yet/i)).toBeInTheDocument();
});
it('renders custom empty message', () => {
render(
<CollectionTable
collections={[]}
metadata={mockMetadata}
emptyMessage="No domains found"
/>
);
expect(screen.getByText(/no domains found/i)).toBeInTheDocument();
});
it('renders warning when metadata is null', () => {
render(
<CollectionTable
collections={mockCollections}
metadata={null}
/>
);
expect(screen.getByText(/no metadata available/i)).toBeInTheDocument();
});
});
describe('Table Rendering', () => {
it('renders table with collection data', () => {
render(
<CollectionTable
collections={mockCollections}
metadata={mockMetadata}
/>
);
// Should render the sortable table
expect(screen.getAllByTestId('sortable-table')).toHaveLength(2); // mobile + desktop
});
it('renders correct number of rows', () => {
render(
<CollectionTable
collections={mockCollections}
metadata={mockMetadata}
/>
);
// Each collection should have a row in desktop view
const desktopView = screen.getByTestId('desktop-view');
const rows = desktopView.querySelectorAll('tbody tr');
expect(rows).toHaveLength(mockCollections.length);
});
it('renders Edit links for each collection', () => {
render(
<CollectionTable
collections={mockCollections}
metadata={mockMetadata}
/>
);
const editLinks = screen.getAllByText('Edit');
// Should have edit links for both mobile and desktop views
expect(editLinks.length).toBeGreaterThan(0);
});
});
describe('Search Filtering', () => {
it('filters collections by search string', () => {
render(
<CollectionTable
collections={mockCollections}
metadata={mockMetadata}
searchStr="example1"
/>
);
const desktopView = screen.getByTestId('desktop-view');
const rows = desktopView.querySelectorAll('tbody tr');
// Should only show matching collection
expect(rows).toHaveLength(1);
});
it('shows all collections when search string is empty', () => {
render(
<CollectionTable
collections={mockCollections}
metadata={mockMetadata}
searchStr=""
/>
);
const desktopView = screen.getByTestId('desktop-view');
const rows = desktopView.querySelectorAll('tbody tr');
expect(rows).toHaveLength(mockCollections.length);
});
it('handles case-insensitive search', () => {
render(
<CollectionTable
collections={mockCollections}
metadata={mockMetadata}
searchStr="EXAMPLE1"
/>
);
const desktopView = screen.getByTestId('desktop-view');
const rows = desktopView.querySelectorAll('tbody tr');
expect(rows).toHaveLength(1);
});
});
describe('Column Width Calculation', () => {
it('calculates widths for 5-column metadata', () => {
render(
<CollectionTable
collections={mockCollections}
metadata={mockMetadata}
/>
);
const desktopView = screen.getByTestId('desktop-view');
const headers = desktopView.querySelectorAll('th');
// Mock metadata has 5 columns: domain, archive_count, size, tag_name, actions
// archive_count (right-aligned)=2, size (bytes)=2, tag_name=2, actions=1
// Total fixed = 7, remaining = 16 - 7 = 9 for domain
expect(headers[0]).toHaveAttribute('data-width', '9');
// Actions column should be 1
const actionsHeader = Array.from(headers).find(h => h.textContent === 'Manage');
expect(actionsHeader).toHaveAttribute('data-width', '1');
});
it('calculates widths for 4-column metadata', () => {
const fourColumnMetadata = {
...mockMetadata,
columns: [
{key: 'name', label: 'Name', sortable: true},
{key: 'count', label: 'Count', sortable: true, align: 'right'},
{key: 'size', label: 'Size', sortable: true, format: 'bytes'},
{key: 'actions', label: 'Manage', type: 'actions'},
]
};
render(
<CollectionTable
collections={mockCollections}
metadata={fourColumnMetadata}
/>
);
const desktopView = screen.getByTestId('desktop-view');
const headers = desktopView.querySelectorAll('th');
// count (right-aligned)=2, size (bytes)=2, actions=1
// Total fixed = 5, remaining = 16 - 5 = 11 for name
expect(headers[0]).toHaveAttribute('data-width', '11');
});
it('distributes space among multiple grow columns', () => {
const twoGrowMetadata = {
...mockMetadata,
columns: [
{key: 'name', label: 'Name', sortable: true},
{key: 'description', label: 'Description', sortable: false},
{key: 'actions', label: 'Manage', type: 'actions'},
]
};
render(
<CollectionTable
collections={mockCollections}
metadata={twoGrowMetadata}
/>
);
const desktopView = screen.getByTestId('desktop-view');
const headers = desktopView.querySelectorAll('th');
// actions=1, remaining = 15 / 2 grow columns = 7 each
expect(headers[0]).toHaveAttribute('data-width', '7');
expect(headers[1]).toHaveAttribute('data-width', '7');
});
});
describe('Row Click Handler', () => {
it('calls onRowClick when row is clicked', () => {
const mockOnRowClick = jest.fn();
render(
<CollectionTable
collections={mockCollections}
metadata={mockMetadata}
onRowClick={mockOnRowClick}
/>
);
const desktopView = screen.getByTestId('desktop-view');
const firstRow = desktopView.querySelector('tbody tr');
firstRow.click();
expect(mockOnRowClick).toHaveBeenCalledWith(mockCollections[0]);
});
it('adds clickable class when onRowClick is provided', () => {
const mockOnRowClick = jest.fn();
render(
<CollectionTable
collections={mockCollections}
metadata={mockMetadata}
onRowClick={mockOnRowClick}
/>
);
const desktopView = screen.getByTestId('desktop-view');
const firstRow = desktopView.querySelector('tbody tr');
expect(firstRow).toHaveClass('clickable');
});
it('does not add clickable class when onRowClick is not provided', () => {
render(
<CollectionTable
collections={mockCollections}
metadata={mockMetadata}
/>
);
const desktopView = screen.getByTestId('desktop-view');
const firstRow = desktopView.querySelector('tbody tr');
expect(firstRow).not.toHaveClass('clickable');
});
});
describe('Value Formatting', () => {
it('formats bytes values using humanFileSize', () => {
const collectionsWithSize = [{
id: 1,
domain: 'test.com',
size: 1048576, // 1 MB
archive_count: 5,
}];
render(
<CollectionTable
collections={collectionsWithSize}
metadata={mockMetadata}
/>
);
// humanFileSize(1048576) should return "1.0 MB"
// Multiple elements found (mobile + desktop), use getAllByText
const sizeElements = screen.getAllByText(/1\.0 MB/i);
expect(sizeElements.length).toBeGreaterThan(0);
});
it('renders SingleTag for tag_name column', () => {
const collectionsWithTag = [{
id: 1,
domain: 'test.com',
tag_name: 'News',
size: 1000,
archive_count: 5,
}];
render(
<CollectionTable
collections={collectionsWithTag}
metadata={mockMetadata}
/>
);
expect(screen.getAllByTestId('single-tag')[0]).toHaveTextContent('News');
});
});
describe('Links', () => {
it('renders search link on primary column when searchParam is configured', () => {
const metadataWithSearchParam = {
...mockMetadata,
routes: {
...mockMetadata.routes,
searchParam: 'domain'
}
};
render(
<CollectionTable
collections={mockCollections}
metadata={metadataWithSearchParam}
/>
);
// Domain column should link to search with domain parameter
const desktopView = screen.getByTestId('desktop-view');
const domainLink = desktopView.querySelector('a[href*="domain="]');
expect(domainLink).toBeInTheDocument();
});
it('renders edit link in actions column', () => {
render(
<CollectionTable
collections={mockCollections}
metadata={mockMetadata}
/>
);
const editLinks = screen.getAllByRole('link', {name: /edit/i});
expect(editLinks.length).toBeGreaterThan(0);
expect(editLinks[0]).toHaveAttribute('href', expect.stringContaining('/edit'));
});
});
});

View file

@ -72,7 +72,7 @@ export function createMockMetadata(kind = 'domain', overrides = {}) {
{key: 'actions', label: 'Manage', sortable: false, type: 'actions'},
],
fields: [
{key: 'directory', label: 'Directory', type: 'text', placeholder: 'Optional directory path'},
{key: 'directory', label: 'Directory', type: 'directory', placeholder: 'Optional directory path'},
{key: 'tag_name', label: 'Tag', type: 'tag', placeholder: 'Select or create tag', depends_on: 'directory'},
{key: 'description', label: 'Description', type: 'textarea', placeholder: 'Optional description'},
],