mirror of
https://github.com/lrnselfreliance/wrolpi.git
synced 2026-11-25 01:16:18 -05:00
Creating a new Collection model for use in organizing FileGroups.
Replacing Channels and Domains with Collection. Moving downloading relationships from Channel to Collection. Created domains.yaml config to manage tagged domain collections. Adding turn-key upgrade solution in the UI.
This commit is contained in:
parent
1f7b1c8744
commit
4fae4ae1b4
115 changed files with 13309 additions and 986 deletions
|
|
@ -1,6 +1,14 @@
|
|||
const { defineConfig } = require("cypress");
|
||||
|
||||
module.exports = defineConfig({
|
||||
e2e: {
|
||||
// Use HTTP for CI, HTTPS for local development
|
||||
baseUrl: process.env.CI ? 'http://localhost:3000' : 'https://localhost:8443',
|
||||
specPattern: 'cypress/e2e/**/*.cy.js',
|
||||
supportFile: 'cypress/support/e2e.js',
|
||||
video: process.env.CI ? true : false,
|
||||
screenshotOnRunFailure: true,
|
||||
},
|
||||
component: {
|
||||
devServer: {
|
||||
framework: "create-react-app",
|
||||
|
|
|
|||
270
app/cypress/e2e/domains/domain-edit.cy.js
Normal file
270
app/cypress/e2e/domains/domain-edit.cy.js
Normal file
|
|
@ -0,0 +1,270 @@
|
|||
describe('Domain Editing Workflow', () => {
|
||||
beforeEach(() => {
|
||||
// Suppress uncaught exceptions from the application (API errors are thrown as unhandled rejections)
|
||||
cy.on('uncaught:exception', (err) => {
|
||||
// Return false to prevent Cypress from failing the test
|
||||
// These are expected API errors in error handling tests
|
||||
return false;
|
||||
});
|
||||
|
||||
// Mock directory search endpoint - DirectorySearch component makes this call automatically
|
||||
cy.intercept('POST', '/api/files/search_directories', {
|
||||
statusCode: 200,
|
||||
body: {is_dir: true, directories: [], channel_directories: [], domain_directories: []}
|
||||
}).as('searchDirectories');
|
||||
|
||||
// Mock tags endpoint - needed for TagsSelector component
|
||||
cy.intercept('GET', '/api/tags', {
|
||||
statusCode: 200,
|
||||
body: {
|
||||
tags: [
|
||||
{id: 1, name: 'News', color: '#ff0000'},
|
||||
{id: 2, name: 'Tech', color: '#00ff00'}
|
||||
]
|
||||
}
|
||||
}).as('getTags');
|
||||
|
||||
// Mock the collections list for domains
|
||||
cy.intercept('GET', '/api/collections?kind=domain', {
|
||||
statusCode: 200,
|
||||
body: {
|
||||
collections: [
|
||||
{
|
||||
id: 1,
|
||||
domain: 'example.com',
|
||||
archive_count: 42,
|
||||
size: 1024000,
|
||||
tag_name: null,
|
||||
directory: null,
|
||||
can_be_tagged: false,
|
||||
description: 'Example domain'
|
||||
}
|
||||
],
|
||||
totals: {collections: 1},
|
||||
metadata: {
|
||||
kind: 'domain',
|
||||
columns: [
|
||||
{key: 'domain', label: 'Domain', sortable: true},
|
||||
{key: 'archive_count', label: 'Archives', sortable: true, align: 'right'},
|
||||
{key: 'size', label: 'Size', sortable: true, align: 'right', format: 'bytes'},
|
||||
{key: 'tag_name', label: 'Tag', sortable: true},
|
||||
{key: 'actions', label: 'Manage', sortable: false, type: 'actions'},
|
||||
],
|
||||
fields: [
|
||||
{key: 'directory', label: 'Directory', type: 'text', 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'},
|
||||
],
|
||||
routes: {
|
||||
list: '/archive/domains',
|
||||
edit: '/archive/domain/:id/edit',
|
||||
search: '/archive',
|
||||
},
|
||||
}
|
||||
}
|
||||
}).as('getDomains');
|
||||
});
|
||||
|
||||
it('completes full edit workflow: add directory and tag', () => {
|
||||
// Mock collection details endpoint BEFORE navigation
|
||||
cy.intercept('GET', '/api/collections/1', {
|
||||
statusCode: 200,
|
||||
body: {
|
||||
collection: {
|
||||
id: 1,
|
||||
domain: 'example.com',
|
||||
directory: '',
|
||||
tag_name: null,
|
||||
description: '',
|
||||
can_be_tagged: false,
|
||||
archive_count: 42,
|
||||
size: 1024000
|
||||
}
|
||||
}
|
||||
}).as('getDomain');
|
||||
|
||||
// Start at domains list
|
||||
cy.visit('/archive/domains');
|
||||
cy.wait('@getDomains');
|
||||
|
||||
// Click edit on first domain
|
||||
cy.get('table tbody tr').first().within(() => {
|
||||
cy.contains('Edit').click();
|
||||
});
|
||||
|
||||
// Should navigate to edit page
|
||||
cy.url().should('include', '/archive/domain/1/edit');
|
||||
cy.wait('@getDomain');
|
||||
|
||||
// Page should load with domain name
|
||||
cy.contains('h1', 'example.com').should('exist');
|
||||
|
||||
// Set directory - DirectorySearch component uses input inside field
|
||||
cy.contains('label', 'Directory').parent().find('input').clear().type('archive/example.com');
|
||||
|
||||
// Set description - Semantic UI TextArea
|
||||
cy.contains('label', 'Description').parent().find('textarea').clear().type('Updated example domain');
|
||||
|
||||
// Mock tags endpoint
|
||||
cy.intercept('GET', '/api/tags', {
|
||||
statusCode: 200,
|
||||
body: {
|
||||
tags: [
|
||||
{id: 1, name: 'News', color: '#ff0000'},
|
||||
{id: 2, name: 'Tech', color: '#00ff00'}
|
||||
]
|
||||
}
|
||||
}).as('getTags');
|
||||
|
||||
// Tag selector should now be enabled (because directory is set)
|
||||
// This depends on the actual implementation of CollectionEditForm
|
||||
|
||||
// Mock update endpoint
|
||||
cy.intercept('PUT', '/api/collections/1', {
|
||||
statusCode: 200,
|
||||
body: {
|
||||
success: true,
|
||||
collection: {
|
||||
id: 1,
|
||||
name: 'example.com',
|
||||
directory: 'archive/example.com',
|
||||
tag_name: null,
|
||||
description: 'Updated example domain',
|
||||
can_be_tagged: true,
|
||||
}
|
||||
}
|
||||
}).as('updateDomain');
|
||||
|
||||
// Save changes
|
||||
cy.contains('button', 'Save').click();
|
||||
|
||||
cy.wait('@updateDomain');
|
||||
|
||||
// Should show success toast and stay on edit page (page refreshes data after save)
|
||||
cy.contains('Domain Updated').should('be.visible');
|
||||
cy.url().should('include', '/archive/domain/1/edit');
|
||||
});
|
||||
|
||||
it('shows validation errors for invalid data', () => {
|
||||
// Mock domain details
|
||||
cy.intercept('GET', '/api/collections/1', {
|
||||
statusCode: 200,
|
||||
body: {
|
||||
collection: {
|
||||
id: 1,
|
||||
domain: 'example.com',
|
||||
directory: 'archive/example.com',
|
||||
tag_name: null,
|
||||
description: 'Example domain',
|
||||
can_be_tagged: true,
|
||||
archive_count: 42,
|
||||
size: 1024000
|
||||
}
|
||||
}
|
||||
}).as('getDomain');
|
||||
|
||||
cy.visit('/archive/domain/1/edit');
|
||||
cy.wait('@getDomain');
|
||||
|
||||
// Try to save with invalid directory
|
||||
cy.intercept('PUT', '/api/collections/1', {
|
||||
statusCode: 400,
|
||||
body: {
|
||||
error: 'Invalid directory path',
|
||||
cause: {
|
||||
code: 'INVALID_DIRECTORY'
|
||||
}
|
||||
}
|
||||
}).as('invalidUpdate');
|
||||
|
||||
cy.contains('label', 'Directory').parent().find('input').clear().type('/invalid/absolute/path');
|
||||
cy.contains('button', 'Save').click();
|
||||
|
||||
cy.wait('@invalidUpdate');
|
||||
|
||||
// Should show error message
|
||||
cy.contains('Invalid directory path').should('be.visible');
|
||||
|
||||
// Should stay on edit page
|
||||
cy.url().should('include', '/edit');
|
||||
});
|
||||
|
||||
it('allows navigating back without saving using Back button', () => {
|
||||
cy.intercept('GET', '/api/collections/1', {
|
||||
statusCode: 200,
|
||||
body: {
|
||||
collection: {
|
||||
id: 1,
|
||||
domain: 'example.com',
|
||||
directory: '',
|
||||
tag_name: null,
|
||||
description: 'Example domain',
|
||||
can_be_tagged: false,
|
||||
archive_count: 42,
|
||||
size: 1024000
|
||||
}
|
||||
}
|
||||
}).as('getDomain');
|
||||
|
||||
// Mock PUT endpoint but don't expect it to be called
|
||||
cy.intercept('PUT', '/api/collections/1', {
|
||||
statusCode: 200,
|
||||
body: {success: true, domain: {}}
|
||||
}).as('updateDomain');
|
||||
|
||||
cy.visit('/archive/domain/1/edit');
|
||||
cy.wait('@getDomain');
|
||||
|
||||
// Make some changes
|
||||
cy.contains('label', 'Description').parent().find('textarea').clear().type('Changed description');
|
||||
|
||||
// Click Back button (the page uses BackButton, not Cancel)
|
||||
cy.contains('button', 'Back').click();
|
||||
|
||||
// Should navigate back without saving
|
||||
// Note: Since we don't have browser history in test, we just verify no save was made
|
||||
cy.get('@updateDomain.all').should('have.length', 0);
|
||||
});
|
||||
|
||||
it('shows form after domain data loads', () => {
|
||||
cy.intercept('GET', '/api/collections/1', {
|
||||
statusCode: 200,
|
||||
body: {
|
||||
collection: {
|
||||
id: 1,
|
||||
domain: 'example.com',
|
||||
directory: null,
|
||||
tag_name: null,
|
||||
description: 'Example domain',
|
||||
can_be_tagged: false
|
||||
}
|
||||
}
|
||||
}).as('getDomain');
|
||||
|
||||
cy.visit('/archive/domain/1/edit');
|
||||
|
||||
cy.wait('@getDomain');
|
||||
|
||||
// Form should be visible with domain name in title
|
||||
cy.contains('h1', 'example.com').should('exist');
|
||||
|
||||
// Form fields should be present
|
||||
cy.contains('label', 'Directory').should('exist');
|
||||
cy.contains('label', 'Description').should('exist');
|
||||
});
|
||||
|
||||
it('handles 404 when domain not found', () => {
|
||||
cy.intercept('GET', '/api/collections/999', {
|
||||
statusCode: 404,
|
||||
body: {
|
||||
error: 'Domain collection with ID 999 not found'
|
||||
}
|
||||
}).as('domainNotFound');
|
||||
|
||||
cy.visit('/archive/domain/999/edit');
|
||||
cy.wait('@domainNotFound');
|
||||
|
||||
// Should show error message
|
||||
cy.contains('not found').should('be.visible');
|
||||
});
|
||||
});
|
||||
154
app/cypress/e2e/domains/domains-list.cy.js
Normal file
154
app/cypress/e2e/domains/domains-list.cy.js
Normal file
|
|
@ -0,0 +1,154 @@
|
|||
describe('Domains List Page', () => {
|
||||
beforeEach(() => {
|
||||
// Mock the collections API response for domains
|
||||
cy.intercept('GET', '/api/collections?kind=domain', {
|
||||
statusCode: 200,
|
||||
body: {
|
||||
collections: [
|
||||
{
|
||||
id: 1,
|
||||
domain: 'example.com',
|
||||
archive_count: 42,
|
||||
size: 1024000,
|
||||
tag_name: 'News',
|
||||
directory: '/media/archives/example.com',
|
||||
can_be_tagged: true,
|
||||
description: 'Example domain'
|
||||
},
|
||||
{
|
||||
id: 2,
|
||||
domain: 'test.org',
|
||||
archive_count: 15,
|
||||
size: 512000,
|
||||
tag_name: null,
|
||||
directory: null,
|
||||
can_be_tagged: false,
|
||||
description: null
|
||||
}
|
||||
],
|
||||
totals: {collections: 2},
|
||||
metadata: {
|
||||
kind: 'domain',
|
||||
columns: [
|
||||
{key: 'domain', label: 'Domain', sortable: true},
|
||||
{key: 'archive_count', label: 'Archives', sortable: true, align: 'right'},
|
||||
{key: 'size', label: 'Size', sortable: true, align: 'right', format: 'bytes'},
|
||||
{key: 'tag_name', label: 'Tag', sortable: true},
|
||||
{key: 'actions', label: 'Manage', sortable: false, type: 'actions'}
|
||||
],
|
||||
fields: [
|
||||
{key: 'directory', label: 'Directory', type: 'text', 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'}
|
||||
],
|
||||
routes: {
|
||||
list: '/archive/domains',
|
||||
edit: '/archive/domain/:id/edit',
|
||||
search: '/archive'
|
||||
},
|
||||
messages: {
|
||||
no_directory: 'Set a directory to enable tagging',
|
||||
tag_will_move: 'Tagging will move files to a new directory'
|
||||
}
|
||||
}
|
||||
}
|
||||
}).as('getDomains');
|
||||
|
||||
// Visit the domains page
|
||||
cy.visit('/archive/domains');
|
||||
cy.wait('@getDomains');
|
||||
});
|
||||
|
||||
it('displays domains page without errors', () => {
|
||||
// DomainsPage doesn't have h1, check for the search input instead
|
||||
cy.get('input[placeholder="Domain filter..."]').should('exist');
|
||||
});
|
||||
|
||||
it('renders CollectionTable component', () => {
|
||||
// Check that the table exists
|
||||
cy.get('table').should('exist');
|
||||
});
|
||||
|
||||
it('shows search input', () => {
|
||||
cy.get('input[placeholder="Domain filter..."]').should('exist');
|
||||
});
|
||||
|
||||
it('shows all domains from API', () => {
|
||||
cy.get('table tbody tr').should('have.length', 2);
|
||||
});
|
||||
|
||||
it('displays domain names', () => {
|
||||
cy.get('table tbody tr').first().should('contain', 'example.com');
|
||||
cy.get('table tbody tr').last().should('contain', 'test.org');
|
||||
});
|
||||
|
||||
it('displays Edit buttons in Manage column', () => {
|
||||
cy.get('table tbody tr').first().within(() => {
|
||||
cy.get('a').contains('Edit').should('exist');
|
||||
});
|
||||
});
|
||||
|
||||
it('Edit button has correct styling', () => {
|
||||
cy.get('table tbody tr').first().within(() => {
|
||||
cy.get('a').contains('Edit').should('have.class', 'ui');
|
||||
cy.get('a').contains('Edit').should('have.class', 'button');
|
||||
cy.get('a').contains('Edit').should('have.class', 'secondary');
|
||||
});
|
||||
});
|
||||
|
||||
it('navigates to domain edit page when edit clicked', () => {
|
||||
// Mock the edit page's API calls to prevent "Failed to fetch" errors
|
||||
cy.intercept('GET', '/api/collections/1', {
|
||||
statusCode: 200,
|
||||
body: {
|
||||
collection: {
|
||||
id: 1,
|
||||
domain: 'example.com',
|
||||
directory: '/media/archives/example.com',
|
||||
tag_name: 'News',
|
||||
description: 'Example domain'
|
||||
}
|
||||
}
|
||||
}).as('getDomain');
|
||||
|
||||
// Mock directory search to prevent errors
|
||||
cy.intercept('POST', '/api/files/search_directories', {
|
||||
statusCode: 200,
|
||||
body: {is_dir: true, directories: [], channel_directories: [], domain_directories: []}
|
||||
}).as('searchDirs');
|
||||
|
||||
cy.get('table tbody tr').first().within(() => {
|
||||
cy.get('a').contains('Edit').click();
|
||||
});
|
||||
cy.url().should('include', '/archive/domain/1/edit');
|
||||
});
|
||||
|
||||
it('filters domains with search', () => {
|
||||
cy.get('input[placeholder="Domain filter..."]').type('example');
|
||||
cy.get('table tbody tr').should('have.length', 1);
|
||||
cy.get('table tbody tr').should('contain', 'example.com');
|
||||
});
|
||||
|
||||
it('shows empty message when no domains', () => {
|
||||
cy.intercept('GET', '/api/collections?kind=domain', {
|
||||
statusCode: 200,
|
||||
body: {
|
||||
collections: [],
|
||||
totals: {collections: 0},
|
||||
metadata: {
|
||||
kind: 'domain',
|
||||
columns: []
|
||||
}
|
||||
}
|
||||
}).as('getEmptyDomains');
|
||||
|
||||
cy.visit('/archive/domains');
|
||||
cy.wait('@getEmptyDomains');
|
||||
|
||||
cy.contains('No domains yet').should('exist');
|
||||
});
|
||||
|
||||
it('does not show "New Domain" button (domains are auto-created)', () => {
|
||||
cy.contains('button', 'New Domain').should('not.exist');
|
||||
});
|
||||
});
|
||||
299
app/cypress/e2e/forms/directory-search.cy.js
Normal file
299
app/cypress/e2e/forms/directory-search.cy.js
Normal file
|
|
@ -0,0 +1,299 @@
|
|||
describe('DirectorySearch Integration Tests', () => {
|
||||
const mockSearchResponse = {
|
||||
is_dir: false,
|
||||
directories: [
|
||||
{path: 'videos/nature'},
|
||||
{path: 'videos/tech'},
|
||||
{path: 'videos/cooking'}
|
||||
],
|
||||
channel_directories: [
|
||||
{path: 'videos/channels/news', name: 'News Channel'},
|
||||
{path: 'videos/channels/tech', name: 'Tech Reviews'}
|
||||
],
|
||||
domain_directories: [
|
||||
{path: 'archive/example.com', domain: 'example.com'},
|
||||
{path: 'archive/test.org', domain: 'test.org'}
|
||||
]
|
||||
};
|
||||
|
||||
const mockEmptyResponse = {
|
||||
is_dir: false,
|
||||
directories: [],
|
||||
channel_directories: [],
|
||||
domain_directories: []
|
||||
};
|
||||
|
||||
const mockExistingDirResponse = {
|
||||
is_dir: true,
|
||||
directories: [
|
||||
{path: 'videos/nature/wildlife'},
|
||||
{path: 'videos/nature/ocean'}
|
||||
],
|
||||
channel_directories: [],
|
||||
domain_directories: []
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
// Mock the directory search API
|
||||
cy.intercept('POST', '/api/files/search_directories', (req) => {
|
||||
const {path} = req.body;
|
||||
|
||||
if (path === 'videos') {
|
||||
req.reply({statusCode: 200, body: mockSearchResponse});
|
||||
} else if (path === 'empty') {
|
||||
req.reply({statusCode: 200, body: mockEmptyResponse});
|
||||
} else if (path === 'videos/nature') {
|
||||
req.reply({statusCode: 200, body: mockExistingDirResponse});
|
||||
} else {
|
||||
req.reply({statusCode: 200, body: mockSearchResponse});
|
||||
}
|
||||
}).as('searchDirectories');
|
||||
});
|
||||
|
||||
context('Standalone DirectorySearch Behavior', () => {
|
||||
beforeEach(() => {
|
||||
// Visit a page with DirectorySearch (using domain edit as example)
|
||||
cy.intercept('GET', '/api/collections/1', {
|
||||
statusCode: 200,
|
||||
body: {
|
||||
collection: {
|
||||
id: 1,
|
||||
name: 'example.com',
|
||||
kind: 'domain',
|
||||
directory: '',
|
||||
description: '',
|
||||
tag_name: null
|
||||
}
|
||||
}
|
||||
}).as('getDomain');
|
||||
|
||||
cy.intercept('GET', '/api/collections?kind=domain', {
|
||||
statusCode: 200,
|
||||
body: {
|
||||
collections: [],
|
||||
totals: {collections: 0},
|
||||
metadata: {
|
||||
kind: 'domain',
|
||||
columns: [],
|
||||
fields: [
|
||||
{key: 'directory', label: 'Directory', type: 'text', required: false}
|
||||
],
|
||||
routes: {},
|
||||
messages: {}
|
||||
}
|
||||
}
|
||||
}).as('getMetadata');
|
||||
|
||||
cy.visit('/archive/domain/1/edit');
|
||||
cy.wait('@getDomain');
|
||||
cy.wait('@getMetadata');
|
||||
});
|
||||
|
||||
it('types in search box and sees results', () => {
|
||||
// Find the directory input
|
||||
cy.contains('label', 'Directory')
|
||||
.parent()
|
||||
.find('input')
|
||||
.type('videos');
|
||||
|
||||
cy.wait('@searchDirectories');
|
||||
|
||||
// Should see results in dropdown
|
||||
cy.contains('videos/nature').should('be.visible');
|
||||
cy.contains('videos/tech').should('be.visible');
|
||||
});
|
||||
|
||||
it('clicks result and value updates', () => {
|
||||
cy.contains('label', 'Directory')
|
||||
.parent()
|
||||
.find('input')
|
||||
.type('videos');
|
||||
|
||||
cy.wait('@searchDirectories');
|
||||
|
||||
// Click a result
|
||||
cy.contains('videos/nature').click();
|
||||
|
||||
// Input should show selected value
|
||||
cy.contains('label', 'Directory')
|
||||
.parent()
|
||||
.find('input')
|
||||
.should('have.value', 'videos/nature');
|
||||
});
|
||||
|
||||
|
||||
it('categories are visually distinct', () => {
|
||||
cy.contains('label', 'Directory')
|
||||
.parent()
|
||||
.find('input')
|
||||
.type('videos');
|
||||
|
||||
cy.wait('@searchDirectories');
|
||||
|
||||
// Check that categories exist
|
||||
cy.contains('Directories').should('be.visible');
|
||||
cy.contains('Channels').should('be.visible');
|
||||
cy.contains('Domains').should('be.visible');
|
||||
});
|
||||
|
||||
it('result descriptions appear correctly', () => {
|
||||
cy.contains('label', 'Directory')
|
||||
.parent()
|
||||
.find('input')
|
||||
.type('videos');
|
||||
|
||||
cy.wait('@searchDirectories');
|
||||
|
||||
// Channel should show name as description
|
||||
cy.contains('News Channel').should('be.visible');
|
||||
|
||||
// Domain should show domain as description
|
||||
cy.contains('example.com').should('be.visible');
|
||||
});
|
||||
|
||||
it('shows "New Directory" for new paths', () => {
|
||||
cy.contains('label', 'Directory')
|
||||
.parent()
|
||||
.find('input')
|
||||
.type('empty');
|
||||
|
||||
cy.wait('@searchDirectories');
|
||||
|
||||
// Should show "New Directory" option
|
||||
cy.contains('New Directory').should('be.visible');
|
||||
});
|
||||
|
||||
});
|
||||
|
||||
context('DestinationForm Workflow', () => {
|
||||
beforeEach(() => {
|
||||
// Set up domain edit page as a form with DestinationForm
|
||||
cy.intercept('GET', '/api/collections/2', {
|
||||
statusCode: 200,
|
||||
body: {
|
||||
collection: {
|
||||
id: 2,
|
||||
name: 'test.com',
|
||||
kind: 'domain',
|
||||
directory: 'archive/test.com',
|
||||
description: '',
|
||||
tag_name: null
|
||||
}
|
||||
}
|
||||
}).as('getDomain');
|
||||
|
||||
cy.intercept('GET', '/api/collections?kind=domain', {
|
||||
statusCode: 200,
|
||||
body: {
|
||||
collections: [],
|
||||
totals: {collections: 0},
|
||||
metadata: {
|
||||
kind: 'domain',
|
||||
columns: [],
|
||||
fields: [
|
||||
{key: 'directory', label: 'Directory', type: 'text', required: true}
|
||||
],
|
||||
routes: {},
|
||||
messages: {}
|
||||
}
|
||||
}
|
||||
}).as('getMetadata');
|
||||
|
||||
cy.visit('/archive/domain/2/edit');
|
||||
cy.wait('@getDomain');
|
||||
cy.wait('@getMetadata');
|
||||
});
|
||||
|
||||
it('starts with existing directory value', () => {
|
||||
cy.contains('label', 'Directory')
|
||||
.parent()
|
||||
.find('input')
|
||||
.should('have.value', 'archive/test.com');
|
||||
});
|
||||
|
||||
it('types partial path and sees suggestions', () => {
|
||||
cy.contains('label', 'Directory')
|
||||
.parent()
|
||||
.find('input')
|
||||
.clear()
|
||||
.type('videos');
|
||||
|
||||
cy.wait('@searchDirectories');
|
||||
|
||||
// Should see suggestions
|
||||
cy.contains('videos/nature').should('be.visible');
|
||||
});
|
||||
|
||||
it('selects channel directory and form updates', () => {
|
||||
cy.contains('label', 'Directory')
|
||||
.parent()
|
||||
.find('input')
|
||||
.clear()
|
||||
.type('videos');
|
||||
|
||||
cy.wait('@searchDirectories');
|
||||
|
||||
// Select a channel directory
|
||||
cy.contains('News Channel').click();
|
||||
|
||||
// Form should update
|
||||
cy.contains('label', 'Directory')
|
||||
.parent()
|
||||
.find('input')
|
||||
.should('have.value', 'videos/channels/news');
|
||||
});
|
||||
|
||||
|
||||
});
|
||||
|
||||
context('Real-World Scenarios', () => {
|
||||
it('handles API returning empty results', () => {
|
||||
cy.intercept('GET', '/api/collections/3', {
|
||||
statusCode: 200,
|
||||
body: {
|
||||
collection: {
|
||||
id: 3,
|
||||
name: 'empty.com',
|
||||
kind: 'domain',
|
||||
directory: '',
|
||||
description: '',
|
||||
tag_name: null
|
||||
}
|
||||
}
|
||||
}).as('getDomain');
|
||||
|
||||
cy.intercept('GET', '/api/collections?kind=domain', {
|
||||
statusCode: 200,
|
||||
body: {
|
||||
collections: [],
|
||||
totals: {collections: 0},
|
||||
metadata: {
|
||||
kind: 'domain',
|
||||
columns: [],
|
||||
fields: [
|
||||
{key: 'directory', label: 'Directory', type: 'text', required: false}
|
||||
],
|
||||
routes: {},
|
||||
messages: {}
|
||||
}
|
||||
}
|
||||
}).as('getMetadata');
|
||||
|
||||
cy.visit('/archive/domain/3/edit');
|
||||
cy.wait('@getDomain');
|
||||
cy.wait('@getMetadata');
|
||||
|
||||
// Type path that returns empty results
|
||||
cy.contains('label', 'Directory')
|
||||
.parent()
|
||||
.find('input')
|
||||
.type('empty');
|
||||
|
||||
cy.wait('@searchDirectories');
|
||||
|
||||
// Should show "New Directory" option
|
||||
cy.contains('New Directory').should('be.visible');
|
||||
});
|
||||
|
||||
});
|
||||
});
|
||||
63
app/cypress/fixtures/channel-collections.json
Normal file
63
app/cypress/fixtures/channel-collections.json
Normal file
|
|
@ -0,0 +1,63 @@
|
|||
{
|
||||
"collections": [
|
||||
{
|
||||
"id": 1,
|
||||
"name": "My Tech Channel",
|
||||
"video_count": 100,
|
||||
"size": 5000000000,
|
||||
"tag_name": "Tech",
|
||||
"directory": "videos/channels/tech",
|
||||
"download_frequency": "daily",
|
||||
"url": "https://youtube.com/c/tech",
|
||||
"rss_url": "https://youtube.com/feeds/tech"
|
||||
},
|
||||
{
|
||||
"id": 2,
|
||||
"name": "News Channel",
|
||||
"video_count": 50,
|
||||
"size": 2500000000,
|
||||
"tag_name": "News",
|
||||
"directory": "videos/channels/news",
|
||||
"download_frequency": "weekly",
|
||||
"url": "https://youtube.com/c/news",
|
||||
"rss_url": null
|
||||
},
|
||||
{
|
||||
"id": 3,
|
||||
"name": "Science Channel",
|
||||
"video_count": 75,
|
||||
"size": 3750000000,
|
||||
"tag_name": null,
|
||||
"directory": "videos/channels/science",
|
||||
"download_frequency": null,
|
||||
"url": null,
|
||||
"rss_url": null
|
||||
}
|
||||
],
|
||||
"totals": {
|
||||
"channels": 3
|
||||
},
|
||||
"metadata": {
|
||||
"kind": "channel",
|
||||
"columns": [
|
||||
{"key": "name", "label": "Name", "sortable": true},
|
||||
{"key": "tag_name", "label": "Tag", "sortable": true},
|
||||
{"key": "video_count", "label": "Videos", "sortable": true},
|
||||
{"key": "download_frequency", "label": "Download Frequency", "sortable": true},
|
||||
{"key": "size", "label": "Size", "sortable": true, "format": "bytes"},
|
||||
{"key": "actions", "label": "Manage", "sortable": false, "type": "actions"}
|
||||
],
|
||||
"fields": [
|
||||
{"key": "name", "label": "Channel Name", "type": "text", "required": true},
|
||||
{"key": "directory", "label": "Directory", "type": "path", "required": true},
|
||||
{"key": "url", "label": "URL", "type": "url", "optional": true},
|
||||
{"key": "tag_name", "label": "Tag", "type": "tag", "optional": true},
|
||||
{"key": "download_missing_data", "label": "Download Missing Data", "type": "boolean", "optional": true}
|
||||
],
|
||||
"routes": {
|
||||
"list": "/videos/channels",
|
||||
"edit": "/videos/channel/:id/edit",
|
||||
"search": "/videos/channel/:id/video"
|
||||
}
|
||||
}
|
||||
}
|
||||
62
app/cypress/fixtures/domain-collections.json
Normal file
62
app/cypress/fixtures/domain-collections.json
Normal file
|
|
@ -0,0 +1,62 @@
|
|||
{
|
||||
"collections": [
|
||||
{
|
||||
"id": 1,
|
||||
"domain": "example.com",
|
||||
"archive_count": 42,
|
||||
"size": 1024000,
|
||||
"tag_name": "News",
|
||||
"directory": "archive/example.com",
|
||||
"can_be_tagged": true,
|
||||
"description": "News from Example.com"
|
||||
},
|
||||
{
|
||||
"id": 2,
|
||||
"domain": "test.org",
|
||||
"archive_count": 15,
|
||||
"size": 512000,
|
||||
"tag_name": null,
|
||||
"directory": null,
|
||||
"can_be_tagged": false,
|
||||
"description": "Test archives"
|
||||
},
|
||||
{
|
||||
"id": 3,
|
||||
"domain": "demo.net",
|
||||
"archive_count": 8,
|
||||
"size": 256000,
|
||||
"tag_name": "Tech",
|
||||
"directory": "archive/demo.net",
|
||||
"can_be_tagged": true,
|
||||
"description": "Tech demos"
|
||||
}
|
||||
],
|
||||
"totals": {
|
||||
"domains": 3
|
||||
},
|
||||
"metadata": {
|
||||
"kind": "domain",
|
||||
"columns": [
|
||||
{"key": "domain", "label": "Domain", "sortable": true},
|
||||
{"key": "archive_count", "label": "URLs", "sortable": true, "align": "right"},
|
||||
{"key": "size", "label": "Size", "sortable": true, "align": "right", "format": "bytes"},
|
||||
{"key": "tag_name", "label": "Tag", "sortable": true},
|
||||
{"key": "actions", "label": "Manage", "sortable": false, "type": "actions"}
|
||||
],
|
||||
"fields": [
|
||||
{"key": "directory", "label": "Directory", "type": "text", "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"}
|
||||
],
|
||||
"routes": {
|
||||
"list": "/archive/domains",
|
||||
"edit": "/archive/domain/:id/edit",
|
||||
"search": "/archive",
|
||||
"searchParam": "domain"
|
||||
},
|
||||
"messages": {
|
||||
"no_directory": "Set a directory to enable tagging",
|
||||
"tag_will_move": "Tagging will move files to a new directory"
|
||||
}
|
||||
}
|
||||
}
|
||||
9
app/cypress/support/e2e.js
Normal file
9
app/cypress/support/e2e.js
Normal file
|
|
@ -0,0 +1,9 @@
|
|||
// ***********************************************************
|
||||
// This file is used to load the support and commands for e2e tests
|
||||
// ***********************************************************
|
||||
|
||||
// Import commands.js using ES2015 syntax:
|
||||
import './commands'
|
||||
|
||||
// Alternatively you can use CommonJS syntax:
|
||||
// require('./commands')
|
||||
153
app/package-lock.json
generated
153
app/package-lock.json
generated
|
|
@ -29,8 +29,18 @@
|
|||
"semantic-ui-react": "^2.1.4",
|
||||
"three": "^0.154",
|
||||
"web-vitals": "^2.1.4"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@testing-library/jest-dom": "^6.9.1"
|
||||
}
|
||||
},
|
||||
"node_modules/@adobe/css-tools": {
|
||||
"version": "4.4.4",
|
||||
"resolved": "https://registry.npmjs.org/@adobe/css-tools/-/css-tools-4.4.4.tgz",
|
||||
"integrity": "sha512-Elp+iwUx5rN5+Y8xLt5/GRoG20WGoDCQ/1Fb+1LiGtvwbDavuSk0jhD/eZdckHAuzcDzccnkv+rEjyWfRx18gg==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@ampproject/remapping": {
|
||||
"version": "2.2.0",
|
||||
"resolved": "https://registry.npmjs.org/@ampproject/remapping/-/remapping-2.2.0.tgz",
|
||||
|
|
@ -3728,6 +3738,33 @@
|
|||
"node": ">=8"
|
||||
}
|
||||
},
|
||||
"node_modules/@testing-library/jest-dom": {
|
||||
"version": "6.9.1",
|
||||
"resolved": "https://registry.npmjs.org/@testing-library/jest-dom/-/jest-dom-6.9.1.tgz",
|
||||
"integrity": "sha512-zIcONa+hVtVSSep9UT3jZ5rizo2BsxgyDYU7WFD5eICBE7no3881HGeb/QkGfsJs6JTkY1aQhT7rIPC7e+0nnA==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@adobe/css-tools": "^4.4.0",
|
||||
"aria-query": "^5.0.0",
|
||||
"css.escape": "^1.5.1",
|
||||
"dom-accessibility-api": "^0.6.3",
|
||||
"picocolors": "^1.1.1",
|
||||
"redent": "^3.0.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=14",
|
||||
"npm": ">=6",
|
||||
"yarn": ">=1"
|
||||
}
|
||||
},
|
||||
"node_modules/@testing-library/jest-dom/node_modules/dom-accessibility-api": {
|
||||
"version": "0.6.3",
|
||||
"resolved": "https://registry.npmjs.org/dom-accessibility-api/-/dom-accessibility-api-0.6.3.tgz",
|
||||
"integrity": "sha512-7ZgogeTnjuHbo+ct10G9Ffp0mif17idi0IyWNVA/wcwcm7NPOD/WEHVP3n7n3MhXqxoIYm8d6MuZohYWIZ4T3w==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@testing-library/react": {
|
||||
"version": "13.4.0",
|
||||
"resolved": "https://registry.npmjs.org/@testing-library/react/-/react-13.4.0.tgz",
|
||||
|
|
@ -6365,6 +6402,13 @@
|
|||
"url": "https://github.com/sponsors/fb55"
|
||||
}
|
||||
},
|
||||
"node_modules/css.escape": {
|
||||
"version": "1.5.1",
|
||||
"resolved": "https://registry.npmjs.org/css.escape/-/css.escape-1.5.1.tgz",
|
||||
"integrity": "sha512-YUifsXXuknHlUsmlgyY0PKzgPOr7/FjCePfHNt0jxm83wHZi44VDMQ7/fGNkjY3/jV1MC+1CmZbaHzugyeRtpg==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/cssdb": {
|
||||
"version": "7.4.1",
|
||||
"resolved": "https://registry.npmjs.org/cssdb/-/cssdb-7.4.1.tgz",
|
||||
|
|
@ -13041,6 +13085,16 @@
|
|||
"node": ">=6"
|
||||
}
|
||||
},
|
||||
"node_modules/min-indent": {
|
||||
"version": "1.0.1",
|
||||
"resolved": "https://registry.npmjs.org/min-indent/-/min-indent-1.0.1.tgz",
|
||||
"integrity": "sha512-I9jwMn07Sy/IwOj3zVkVik2JTvgpaykDZEigL6Rx6N9LbMywwUSMtxET+7lVoDLLd3O3IXwJwvuuns8UB/HeAg==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=4"
|
||||
}
|
||||
},
|
||||
"node_modules/mini-css-extract-plugin": {
|
||||
"version": "2.7.2",
|
||||
"resolved": "https://registry.npmjs.org/mini-css-extract-plugin/-/mini-css-extract-plugin-2.7.2.tgz",
|
||||
|
|
@ -13699,9 +13753,10 @@
|
|||
"integrity": "sha512-7EAHlyLHI56VEIdK57uwHdHKIaAGbnXPiw0yWbarQZOKaKpvUIgW0jWRVLiatnM+XXlSwsanIBH/hzGMJulMow=="
|
||||
},
|
||||
"node_modules/picocolors": {
|
||||
"version": "1.0.1",
|
||||
"resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.0.1.tgz",
|
||||
"integrity": "sha512-anP1Z8qwhkbmu7MFP5iTt+wQKXgwzf7zTyGlcdzabySa9vd0Xt392U0rVmz9poOaBj0uHJKyyo9/upk0HrEQew=="
|
||||
"version": "1.1.1",
|
||||
"resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz",
|
||||
"integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==",
|
||||
"license": "ISC"
|
||||
},
|
||||
"node_modules/picomatch": {
|
||||
"version": "2.3.1",
|
||||
|
|
@ -15751,6 +15806,20 @@
|
|||
"node": ">=6.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/redent": {
|
||||
"version": "3.0.0",
|
||||
"resolved": "https://registry.npmjs.org/redent/-/redent-3.0.0.tgz",
|
||||
"integrity": "sha512-6tDA8g98We0zd0GvVeMT9arEOnTw9qM03L9cJXaCjrip1OO764RDBLBfrB4cwzNGDj5OA5ioymC9GkizgWJDUg==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"indent-string": "^4.0.0",
|
||||
"strip-indent": "^3.0.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=8"
|
||||
}
|
||||
},
|
||||
"node_modules/regenerate": {
|
||||
"version": "1.4.2",
|
||||
"resolved": "https://registry.npmjs.org/regenerate/-/regenerate-1.4.2.tgz",
|
||||
|
|
@ -16985,6 +17054,19 @@
|
|||
"node": ">=6"
|
||||
}
|
||||
},
|
||||
"node_modules/strip-indent": {
|
||||
"version": "3.0.0",
|
||||
"resolved": "https://registry.npmjs.org/strip-indent/-/strip-indent-3.0.0.tgz",
|
||||
"integrity": "sha512-laJTa3Jb+VQpaC6DseHhF7dXVqHTfJPCRDaEbid/drOhgitgYku/letMUqOXFoWV0zIIUbjpdH2t+tYj4bQMRQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"min-indent": "^1.0.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=8"
|
||||
}
|
||||
},
|
||||
"node_modules/strip-json-comments": {
|
||||
"version": "3.1.1",
|
||||
"resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-3.1.1.tgz",
|
||||
|
|
@ -18880,6 +18962,12 @@
|
|||
}
|
||||
},
|
||||
"dependencies": {
|
||||
"@adobe/css-tools": {
|
||||
"version": "4.4.4",
|
||||
"resolved": "https://registry.npmjs.org/@adobe/css-tools/-/css-tools-4.4.4.tgz",
|
||||
"integrity": "sha512-Elp+iwUx5rN5+Y8xLt5/GRoG20WGoDCQ/1Fb+1LiGtvwbDavuSk0jhD/eZdckHAuzcDzccnkv+rEjyWfRx18gg==",
|
||||
"dev": true
|
||||
},
|
||||
"@ampproject/remapping": {
|
||||
"version": "2.2.0",
|
||||
"resolved": "https://registry.npmjs.org/@ampproject/remapping/-/remapping-2.2.0.tgz",
|
||||
|
|
@ -21357,6 +21445,28 @@
|
|||
}
|
||||
}
|
||||
},
|
||||
"@testing-library/jest-dom": {
|
||||
"version": "6.9.1",
|
||||
"resolved": "https://registry.npmjs.org/@testing-library/jest-dom/-/jest-dom-6.9.1.tgz",
|
||||
"integrity": "sha512-zIcONa+hVtVSSep9UT3jZ5rizo2BsxgyDYU7WFD5eICBE7no3881HGeb/QkGfsJs6JTkY1aQhT7rIPC7e+0nnA==",
|
||||
"dev": true,
|
||||
"requires": {
|
||||
"@adobe/css-tools": "^4.4.0",
|
||||
"aria-query": "^5.0.0",
|
||||
"css.escape": "^1.5.1",
|
||||
"dom-accessibility-api": "^0.6.3",
|
||||
"picocolors": "^1.1.1",
|
||||
"redent": "^3.0.0"
|
||||
},
|
||||
"dependencies": {
|
||||
"dom-accessibility-api": {
|
||||
"version": "0.6.3",
|
||||
"resolved": "https://registry.npmjs.org/dom-accessibility-api/-/dom-accessibility-api-0.6.3.tgz",
|
||||
"integrity": "sha512-7ZgogeTnjuHbo+ct10G9Ffp0mif17idi0IyWNVA/wcwcm7NPOD/WEHVP3n7n3MhXqxoIYm8d6MuZohYWIZ4T3w==",
|
||||
"dev": true
|
||||
}
|
||||
}
|
||||
},
|
||||
"@testing-library/react": {
|
||||
"version": "13.4.0",
|
||||
"resolved": "https://registry.npmjs.org/@testing-library/react/-/react-13.4.0.tgz",
|
||||
|
|
@ -23310,6 +23420,12 @@
|
|||
"resolved": "https://registry.npmjs.org/css-what/-/css-what-6.1.0.tgz",
|
||||
"integrity": "sha512-HTUrgRJ7r4dsZKU6GjmpfRK1O76h97Z8MfS1G0FozR+oF2kG6Vfe8JE6zwrkbxigziPHinCJ+gCPjA9EaBDtRw=="
|
||||
},
|
||||
"css.escape": {
|
||||
"version": "1.5.1",
|
||||
"resolved": "https://registry.npmjs.org/css.escape/-/css.escape-1.5.1.tgz",
|
||||
"integrity": "sha512-YUifsXXuknHlUsmlgyY0PKzgPOr7/FjCePfHNt0jxm83wHZi44VDMQ7/fGNkjY3/jV1MC+1CmZbaHzugyeRtpg==",
|
||||
"dev": true
|
||||
},
|
||||
"cssdb": {
|
||||
"version": "7.4.1",
|
||||
"resolved": "https://registry.npmjs.org/cssdb/-/cssdb-7.4.1.tgz",
|
||||
|
|
@ -28143,6 +28259,12 @@
|
|||
"resolved": "https://registry.npmjs.org/mimic-fn/-/mimic-fn-2.1.0.tgz",
|
||||
"integrity": "sha512-OqbOk5oEQeAZ8WXWydlu9HJjz9WVdEIvamMCcXmuqUYjTknH/sqsWvhQ3vgwKFRR1HpjvNBKQ37nbJgYzGqGcg=="
|
||||
},
|
||||
"min-indent": {
|
||||
"version": "1.0.1",
|
||||
"resolved": "https://registry.npmjs.org/min-indent/-/min-indent-1.0.1.tgz",
|
||||
"integrity": "sha512-I9jwMn07Sy/IwOj3zVkVik2JTvgpaykDZEigL6Rx6N9LbMywwUSMtxET+7lVoDLLd3O3IXwJwvuuns8UB/HeAg==",
|
||||
"dev": true
|
||||
},
|
||||
"mini-css-extract-plugin": {
|
||||
"version": "2.7.2",
|
||||
"resolved": "https://registry.npmjs.org/mini-css-extract-plugin/-/mini-css-extract-plugin-2.7.2.tgz",
|
||||
|
|
@ -28605,9 +28727,9 @@
|
|||
"integrity": "sha512-7EAHlyLHI56VEIdK57uwHdHKIaAGbnXPiw0yWbarQZOKaKpvUIgW0jWRVLiatnM+XXlSwsanIBH/hzGMJulMow=="
|
||||
},
|
||||
"picocolors": {
|
||||
"version": "1.0.1",
|
||||
"resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.0.1.tgz",
|
||||
"integrity": "sha512-anP1Z8qwhkbmu7MFP5iTt+wQKXgwzf7zTyGlcdzabySa9vd0Xt392U0rVmz9poOaBj0uHJKyyo9/upk0HrEQew=="
|
||||
"version": "1.1.1",
|
||||
"resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz",
|
||||
"integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA=="
|
||||
},
|
||||
"picomatch": {
|
||||
"version": "2.3.1",
|
||||
|
|
@ -29902,6 +30024,16 @@
|
|||
"minimatch": "^3.0.5"
|
||||
}
|
||||
},
|
||||
"redent": {
|
||||
"version": "3.0.0",
|
||||
"resolved": "https://registry.npmjs.org/redent/-/redent-3.0.0.tgz",
|
||||
"integrity": "sha512-6tDA8g98We0zd0GvVeMT9arEOnTw9qM03L9cJXaCjrip1OO764RDBLBfrB4cwzNGDj5OA5ioymC9GkizgWJDUg==",
|
||||
"dev": true,
|
||||
"requires": {
|
||||
"indent-string": "^4.0.0",
|
||||
"strip-indent": "^3.0.0"
|
||||
}
|
||||
},
|
||||
"regenerate": {
|
||||
"version": "1.4.2",
|
||||
"resolved": "https://registry.npmjs.org/regenerate/-/regenerate-1.4.2.tgz",
|
||||
|
|
@ -30830,6 +30962,15 @@
|
|||
"resolved": "https://registry.npmjs.org/strip-final-newline/-/strip-final-newline-2.0.0.tgz",
|
||||
"integrity": "sha512-BrpvfNAE3dcvq7ll3xVumzjKjZQ5tI1sEUIKr3Uoks0XUl45St3FlatVqef9prk4jRDzhW6WZg+3bk93y6pLjA=="
|
||||
},
|
||||
"strip-indent": {
|
||||
"version": "3.0.0",
|
||||
"resolved": "https://registry.npmjs.org/strip-indent/-/strip-indent-3.0.0.tgz",
|
||||
"integrity": "sha512-laJTa3Jb+VQpaC6DseHhF7dXVqHTfJPCRDaEbid/drOhgitgYku/letMUqOXFoWV0zIIUbjpdH2t+tYj4bQMRQ==",
|
||||
"dev": true,
|
||||
"requires": {
|
||||
"min-indent": "^1.0.0"
|
||||
}
|
||||
},
|
||||
"strip-json-comments": {
|
||||
"version": "3.1.1",
|
||||
"resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-3.1.1.tgz",
|
||||
|
|
|
|||
|
|
@ -27,9 +27,11 @@
|
|||
},
|
||||
"scripts": {
|
||||
"start": "react-scripts start",
|
||||
"build": "react-scripts build",
|
||||
"build": "BROWSERSLIST_IGNORE_OLD_DATA=true react-scripts build",
|
||||
"test": "react-scripts test",
|
||||
"eject": "react-scripts eject"
|
||||
"eject": "react-scripts eject",
|
||||
"cy:run": "cypress run",
|
||||
"cy:open": "cypress open"
|
||||
},
|
||||
"eslintConfig": {
|
||||
"extends": [
|
||||
|
|
@ -47,5 +49,8 @@
|
|||
"last 1 firefox version",
|
||||
"last 1 safari version"
|
||||
]
|
||||
},
|
||||
"devDependencies": {
|
||||
"@testing-library/jest-dom": "^6.9.1"
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -118,6 +118,14 @@ function handleEvents(events) {
|
|||
eventToast('Screenshot Generation Failed!', message, 'error', 5000);
|
||||
}
|
||||
|
||||
if (event === 'upgrade_started') {
|
||||
eventToast('Upgrade Started', message, 'info', 10000);
|
||||
// Redirect to maintenance page after a short delay
|
||||
setTimeout(() => {
|
||||
window.location.href = '/maintenance.html';
|
||||
}, 1000);
|
||||
}
|
||||
|
||||
if (subject) {
|
||||
newestEvents[subject] = dt;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -385,6 +385,11 @@ export function AddTagsButton({
|
|||
const [loading, setLoading] = React.useState(false);
|
||||
const [localTags, setLocalTags] = React.useState(selectedTagNames);
|
||||
|
||||
// Sync localTags with selectedTagNames when it changes from parent
|
||||
React.useEffect(() => {
|
||||
setLocalTags(selectedTagNames);
|
||||
}, [selectedTagNames]);
|
||||
|
||||
const active = anyTag || (selectedTagNames && selectedTagNames.length > 0);
|
||||
|
||||
const handleOpen = (e) => {
|
||||
|
|
|
|||
160
app/src/api.js
160
app/src/api.js
|
|
@ -1,7 +1,7 @@
|
|||
import {emptyToNull} from "./components/Common";
|
||||
import {toast} from "react-semantic-toasts-2";
|
||||
import _ from "lodash";
|
||||
import {API_URI, ARCHIVES_API, DEFAULT_LIMIT, Downloaders, OTP_API, VIDEOS_API, ZIM_API} from "./components/Vars";
|
||||
import {API_URI, ARCHIVES_API, COLLECTIONS_API, DEFAULT_LIMIT, Downloaders, OTP_API, VIDEOS_API, ZIM_API} from "./components/Vars";
|
||||
|
||||
function timeoutPromise(ms, promise) {
|
||||
// Create a timeout wrapper around a promise. If the timeout is reached, throw an error. Otherwise, return
|
||||
|
|
@ -719,10 +719,10 @@ export async function searchArchives(offset, limit, domain, searchStr, order, ta
|
|||
}
|
||||
|
||||
export async function fetchDomains() {
|
||||
const response = await apiGet(`${ARCHIVES_API}/domains`);
|
||||
const response = await apiGet(`${COLLECTIONS_API}?kind=domain`);
|
||||
if (response.ok) {
|
||||
let data = await response.json();
|
||||
return [data['domains'], data['totals']['domains']];
|
||||
return [data['collections'], data['totals']['collections'], data['metadata']];
|
||||
} else {
|
||||
const message = await getErrorMessage(response, 'Unable to fetch Domains. See server logs.');
|
||||
toast({
|
||||
|
|
@ -734,6 +734,137 @@ export async function fetchDomains() {
|
|||
}
|
||||
}
|
||||
|
||||
export async function fetchChannels() {
|
||||
const response = await apiGet(`${COLLECTIONS_API}?kind=channel`);
|
||||
if (response.ok) {
|
||||
let data = await response.json();
|
||||
return [data['collections'], data['totals']['collections'], data['metadata']];
|
||||
} else {
|
||||
const message = await getErrorMessage(response, 'Unable to fetch Channels. See server logs.');
|
||||
toast({
|
||||
type: 'error',
|
||||
title: 'Channels Error',
|
||||
description: message,
|
||||
time: 5000,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
export async function getDomain(domainId) {
|
||||
const response = await apiGet(`${COLLECTIONS_API}/${domainId}`);
|
||||
if (response.ok) {
|
||||
const data = await response.json();
|
||||
return data['collection'];
|
||||
} else {
|
||||
const message = await getErrorMessage(response, 'Unable to fetch Domain. See server logs.');
|
||||
toast({
|
||||
type: 'error',
|
||||
title: 'Domain Error',
|
||||
description: message,
|
||||
time: 5000,
|
||||
});
|
||||
throw new Error(message);
|
||||
}
|
||||
}
|
||||
|
||||
export async function updateDomain(domainId, updates) {
|
||||
updates = emptyToNull(updates);
|
||||
const response = await apiPut(`${COLLECTIONS_API}/${domainId}`, updates);
|
||||
if (response.ok) {
|
||||
const data = await response.json();
|
||||
return data['collection'];
|
||||
} else {
|
||||
const message = await getErrorMessage(response, 'Unable to update Domain. See server logs.');
|
||||
toast({
|
||||
type: 'error',
|
||||
title: 'Domain Update Error',
|
||||
description: message,
|
||||
time: 5000,
|
||||
});
|
||||
throw new Error(message);
|
||||
}
|
||||
}
|
||||
|
||||
export async function getCollectionTagInfo(collectionId, tagName) {
|
||||
const body = {
|
||||
tag_name: tagName,
|
||||
}
|
||||
const response = await apiPost(`${COLLECTIONS_API}/${collectionId}/tag_info`, body);
|
||||
if (response.ok) {
|
||||
const data = await response.json();
|
||||
return data;
|
||||
} else {
|
||||
const message = await getErrorMessage(response, 'Unable to get tag info. See server logs.');
|
||||
toast({
|
||||
type: 'error',
|
||||
title: 'Tag Info Error',
|
||||
description: message,
|
||||
time: 5000,
|
||||
});
|
||||
throw new Error(message);
|
||||
}
|
||||
}
|
||||
|
||||
export async function tagDomain(domainId, tagName, directory) {
|
||||
const body = {
|
||||
tag_name: tagName,
|
||||
}
|
||||
if (directory) {
|
||||
body['directory'] = directory;
|
||||
}
|
||||
const response = await apiPost(`${COLLECTIONS_API}/${domainId}/tag`, body);
|
||||
if (response.ok) {
|
||||
const data = await response.json();
|
||||
return data;
|
||||
} else {
|
||||
const message = await getErrorMessage(response, 'Unable to tag Domain. See server logs.');
|
||||
toast({
|
||||
type: 'error',
|
||||
title: 'Domain Tag Error',
|
||||
description: message,
|
||||
time: 5000,
|
||||
});
|
||||
throw new Error(message);
|
||||
}
|
||||
}
|
||||
|
||||
export async function deleteDomain(domainId) {
|
||||
const response = await apiDelete(`${COLLECTIONS_API}/${domainId}`);
|
||||
if (response.status !== 204) {
|
||||
const message = await getErrorMessage(response, 'Failed to delete domain.');
|
||||
toast({
|
||||
type: 'error',
|
||||
title: 'Delete Failed',
|
||||
description: message,
|
||||
time: 5000,
|
||||
});
|
||||
throw new Error(message);
|
||||
}
|
||||
return response;
|
||||
}
|
||||
|
||||
export async function refreshDomain(domainId) {
|
||||
let url = `${COLLECTIONS_API}/${domainId}/refresh`;
|
||||
const response = await apiPost(url);
|
||||
if (!response.ok) {
|
||||
const message = await getErrorMessage(response, "Failed to refresh this domain's directory");
|
||||
toast({
|
||||
type: 'error',
|
||||
title: 'Failed to refresh',
|
||||
description: message,
|
||||
time: 5000,
|
||||
});
|
||||
} else {
|
||||
toast({
|
||||
type: 'success',
|
||||
title: 'Domain refresh started',
|
||||
description: 'The domain directory is being refreshed',
|
||||
time: 3000,
|
||||
});
|
||||
}
|
||||
return response;
|
||||
}
|
||||
|
||||
export async function getArchive(archiveId) {
|
||||
const response = await apiGet(`${ARCHIVES_API}/${archiveId}`);
|
||||
if (response.ok) {
|
||||
|
|
@ -1519,4 +1650,27 @@ export async function postRestart() {
|
|||
export async function postVideoFileFormat(video_file_format) {
|
||||
const body = {video_file_format};
|
||||
return await apiPost(`${API_URI}/videos/file_format`, body);
|
||||
}
|
||||
|
||||
export async function checkUpgrade(force = false) {
|
||||
const url = force ? `${API_URI}/upgrade/check?force=true` : `${API_URI}/upgrade/check`;
|
||||
const response = await apiGet(url);
|
||||
if (response.ok) {
|
||||
return await response.json();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
export async function triggerUpgrade() {
|
||||
const response = await apiPost(`${API_URI}/upgrade/start`);
|
||||
if (!response.ok) {
|
||||
const message = await getErrorMessage(response, 'Failed to start upgrade. See server logs.');
|
||||
toast({
|
||||
type: 'error',
|
||||
title: 'Upgrade Error',
|
||||
description: message,
|
||||
time: 5000,
|
||||
});
|
||||
}
|
||||
return response;
|
||||
}
|
||||
|
|
@ -9,10 +9,7 @@ import {
|
|||
GridRow,
|
||||
Image,
|
||||
Input,
|
||||
PlaceholderHeader,
|
||||
PlaceholderLine,
|
||||
TableCell,
|
||||
TableRow
|
||||
} from "semantic-ui-react";
|
||||
import {
|
||||
APIButton,
|
||||
|
|
@ -35,19 +32,31 @@ import {
|
|||
textEllipsis,
|
||||
useTitle
|
||||
} from "./Common";
|
||||
import {deleteArchives, generateArchiveScreenshot, postDownload, tagFileGroup, untagFileGroup} from "../api";
|
||||
import {Link, Route, Routes, useNavigate, useParams} from "react-router-dom";
|
||||
import {deleteArchives, deleteDomain, generateArchiveScreenshot, getCollectionTagInfo, postDownload, refreshDomain, tagDomain, tagFileGroup, untagFileGroup} from "../api";
|
||||
import {CollectionTagModal} from "./collections/CollectionTagModal";
|
||||
import {Link, Route, Routes, useLocation, useNavigate, useParams} from "react-router-dom";
|
||||
import Message from "semantic-ui-react/dist/commonjs/collections/Message";
|
||||
import {useArchive, useDomains, useSearchArchives, useSearchOrder} from "../hooks/customHooks";
|
||||
import {
|
||||
useArchive,
|
||||
useCollectionMetadata,
|
||||
useDomain,
|
||||
useDomains,
|
||||
useOneQuery,
|
||||
useSearchArchives,
|
||||
useSearchOrder
|
||||
} from "../hooks/customHooks";
|
||||
import {FileCards, FileRowTagIcon, FilesView} from "./Files";
|
||||
import Grid from "semantic-ui-react/dist/commonjs/collections/Grid";
|
||||
import _ from "lodash";
|
||||
import {Media, ThemeContext} from "../contexts/contexts";
|
||||
import {Button, Card, CardIcon, darkTheme, Header, Loader, Placeholder, Popup, Segment, Tab, TabPane} from "./Theme";
|
||||
import {SortableTable} from "./SortableTable";
|
||||
import {taggedImageLabel, TagsSelector} from "../Tags";
|
||||
import {taggedImageLabel, TagsSelector, TagsContext} from "../Tags";
|
||||
import {toast} from "react-semantic-toasts-2";
|
||||
import {API_ARCHIVE_UPLOAD_URI, Downloaders} from "./Vars";
|
||||
import {CollectionTable} from "./collections/CollectionTable";
|
||||
import {CollectionEditForm} from "./collections/CollectionEditForm";
|
||||
import {RecurringDownloadsTable} from "./admin/Downloads";
|
||||
|
||||
function archiveFileLink(path, directory = false) {
|
||||
if (path) {
|
||||
|
|
@ -350,66 +359,219 @@ export function ArchiveCard({file}) {
|
|||
export function DomainsPage() {
|
||||
useTitle('Archive Domains');
|
||||
|
||||
const [domains] = useDomains();
|
||||
const [searchStr, setSearchStr] = useState('');
|
||||
const [domains, total, metadata] = useDomains();
|
||||
const [searchStr, setSearchStr] = useOneQuery('domain');
|
||||
|
||||
if (domains === null) {
|
||||
// Request is pending.
|
||||
// Header section matching ChannelsPage pattern
|
||||
const header = <div style={{marginBottom: '1em'}}>
|
||||
<Grid stackable columns={2}>
|
||||
<Grid.Row>
|
||||
<Grid.Column>
|
||||
<SearchInput
|
||||
placeholder='Domain filter...'
|
||||
size='large'
|
||||
searchStr={searchStr}
|
||||
disabled={!Array.isArray(domains) || domains.length === 0}
|
||||
onClear={() => setSearchStr('')}
|
||||
onChange={setSearchStr}
|
||||
onSubmit={null}
|
||||
/>
|
||||
</Grid.Column>
|
||||
<Grid.Column textAlign='right'>
|
||||
{/* No "New Domain" button - domains are auto-created */}
|
||||
</Grid.Column>
|
||||
</Grid.Row>
|
||||
</Grid>
|
||||
</div>;
|
||||
|
||||
// Empty state
|
||||
if (domains && domains.length === 0) {
|
||||
return <>
|
||||
<Placeholder>
|
||||
<PlaceholderHeader>
|
||||
<PlaceholderLine/>
|
||||
<PlaceholderLine/>
|
||||
</PlaceholderHeader>
|
||||
</Placeholder>
|
||||
{header}
|
||||
<Message>
|
||||
<Message.Header>No domains yet. Archive some webpages!</Message.Header>
|
||||
</Message>
|
||||
</>;
|
||||
} else if (domains === undefined) {
|
||||
return <ErrorMessage>Could not fetch domains</ErrorMessage>
|
||||
} else if (domains && domains.length === 0) {
|
||||
return <Message>
|
||||
<Message.Header>No domains yet.</Message.Header>
|
||||
<Message.Content>Archive some webpages!</Message.Content>
|
||||
</Message>;
|
||||
}
|
||||
|
||||
let filteredDomains = domains;
|
||||
if (searchStr) {
|
||||
const re = new RegExp(_.escapeRegExp(searchStr), 'i');
|
||||
filteredDomains = domains.filter(i => re.test(i['domain']));
|
||||
// Error state
|
||||
if (domains === undefined) {
|
||||
return <>
|
||||
{header}
|
||||
<ErrorMessage>Could not fetch Domains</ErrorMessage>
|
||||
</>;
|
||||
}
|
||||
|
||||
const domainRow = ({domain, url_count, size}) => {
|
||||
return <TableRow key={domain}>
|
||||
<TableCell>
|
||||
<Link to={`/archive?domain=${domain}`}>
|
||||
{domain}
|
||||
</Link>
|
||||
</TableCell>
|
||||
<TableCell>{url_count}</TableCell>
|
||||
<TableCell>{humanFileSize(size)}</TableCell>
|
||||
</TableRow>
|
||||
}
|
||||
|
||||
const headers = [
|
||||
{key: 'domain', text: 'Domain', sortBy: 'domain', width: 12},
|
||||
{key: 'archives', text: 'Archives', sortBy: 'url_count', width: 2},
|
||||
{key: 'Size', text: 'Size', sortBy: 'size', width: 2},
|
||||
];
|
||||
|
||||
return <>
|
||||
<Input
|
||||
icon='search'
|
||||
value={searchStr}
|
||||
placeholder='Search...'
|
||||
onChange={(e, {value}) => setSearchStr(value)}
|
||||
{header}
|
||||
<CollectionTable
|
||||
collections={domains}
|
||||
metadata={metadata}
|
||||
searchStr={searchStr}
|
||||
/>
|
||||
<SortableTable
|
||||
tableProps={{unstackable: true}}
|
||||
data={filteredDomains}
|
||||
rowFunc={(i, sortData) => domainRow(i)}
|
||||
rowKey='domain'
|
||||
tableHeaders={headers}
|
||||
</>;
|
||||
}
|
||||
|
||||
export function DomainEditPage() {
|
||||
const {domainId} = useParams();
|
||||
const navigate = useNavigate();
|
||||
const {domain, form, fetchDomain} = useDomain(parseInt(domainId));
|
||||
const {metadata} = useCollectionMetadata('domain');
|
||||
|
||||
// Modal state for tagging
|
||||
const [tagEditModalOpen, setTagEditModalOpen] = useState(false);
|
||||
|
||||
// Filter out tag_name field - we use the modal button instead of inline selector
|
||||
const filteredMetadata = React.useMemo(() => {
|
||||
if (!metadata) return metadata;
|
||||
return {
|
||||
...metadata,
|
||||
fields: metadata.fields.filter(field => field.key !== 'tag_name')
|
||||
};
|
||||
}, [metadata]);
|
||||
|
||||
useTitle(`Edit Domain: ${domain?.domain || '...'}`);
|
||||
|
||||
// Wrap form.onSubmit to add toast and refresh domain data
|
||||
React.useEffect(() => {
|
||||
if (form && form.onSubmit) {
|
||||
const originalOnSubmit = form.onSubmit;
|
||||
form.onSubmit = async () => {
|
||||
try {
|
||||
await originalOnSubmit();
|
||||
toast({
|
||||
type: 'success',
|
||||
title: 'Domain Updated',
|
||||
description: 'Domain was successfully updated',
|
||||
time: 3000,
|
||||
});
|
||||
// Refresh domain data to show updated values
|
||||
await fetchDomain();
|
||||
} catch (e) {
|
||||
console.error('Failed to update domain:', e);
|
||||
throw e;
|
||||
}
|
||||
};
|
||||
}
|
||||
}, [form, fetchDomain]);
|
||||
|
||||
// Handler for tag modal save
|
||||
const handleTagSave = async (tagName, directory) => {
|
||||
try {
|
||||
await tagDomain(parseInt(domainId), tagName, directory);
|
||||
toast({
|
||||
type: 'success',
|
||||
title: 'Domain Tagged',
|
||||
description: `Domain "${domain?.domain}" has been tagged with "${tagName}"`,
|
||||
time: 3000,
|
||||
});
|
||||
} catch (e) {
|
||||
console.error('Failed to tag domain', e);
|
||||
} finally {
|
||||
setTimeout(async () => {
|
||||
await fetchDomain();
|
||||
}, 500);
|
||||
}
|
||||
};
|
||||
|
||||
// Handler for fetching tag info
|
||||
const handleGetTagInfo = async (tagName) => {
|
||||
if (domain?.id) {
|
||||
return await getCollectionTagInfo(domain.id, tagName);
|
||||
}
|
||||
return null;
|
||||
};
|
||||
|
||||
const handleRefreshDomain = async (e) => {
|
||||
if (e) {
|
||||
e.preventDefault();
|
||||
}
|
||||
await refreshDomain(parseInt(domainId));
|
||||
// Refresh domain data after completion
|
||||
await fetchDomain();
|
||||
};
|
||||
|
||||
if (!form.ready) {
|
||||
return <Loader active>Loading domain...</Loader>;
|
||||
}
|
||||
|
||||
// Handler for domain deletion
|
||||
const handleDelete = async () => {
|
||||
try {
|
||||
let response = await deleteDomain(parseInt(domainId));
|
||||
if (response.status === 204) {
|
||||
navigate('/archive/domains');
|
||||
}
|
||||
} catch (e) {
|
||||
console.error('Failed to delete domain', e);
|
||||
}
|
||||
};
|
||||
|
||||
const deleteButton = <APIButton
|
||||
color='red'
|
||||
size='small'
|
||||
confirmContent='Are you sure you want to delete this domain? No archive files will be deleted, but archives will be orphaned.'
|
||||
confirmButton='Delete'
|
||||
confirmHeader='Delete Domain?'
|
||||
onClick={handleDelete}
|
||||
obeyWROLMode={true}
|
||||
style={{marginTop: '1em'}}
|
||||
>Delete</APIButton>;
|
||||
|
||||
const refreshButton = domain?.directory ? (
|
||||
<APIButton
|
||||
color='blue'
|
||||
size='small'
|
||||
onClick={handleRefreshDomain}
|
||||
obeyWROLMode={true}
|
||||
style={{marginTop: '1em'}}
|
||||
>Refresh</APIButton>
|
||||
) : null;
|
||||
|
||||
const tagButton = <Button
|
||||
type="button"
|
||||
size='small'
|
||||
onClick={() => setTagEditModalOpen(true)}
|
||||
color='green'
|
||||
style={{marginTop: '1em'}}
|
||||
>Tag</Button>;
|
||||
|
||||
const actionButtons = <>
|
||||
{deleteButton}
|
||||
{refreshButton}
|
||||
{tagButton}
|
||||
</>;
|
||||
|
||||
return <>
|
||||
<BackButton/>
|
||||
<CollectionEditForm
|
||||
form={form}
|
||||
metadata={filteredMetadata}
|
||||
title={`Edit Domain: ${domain?.domain || '...'}`}
|
||||
wrolModeContent='Domain editing is disabled while in WROL Mode.'
|
||||
actionButtons={actionButtons}
|
||||
appliedTagName={domain?.tag_name}
|
||||
/>
|
||||
|
||||
{/* Tag Modal */}
|
||||
<CollectionTagModal
|
||||
open={tagEditModalOpen}
|
||||
onClose={() => setTagEditModalOpen(false)}
|
||||
currentTagName={domain?.tag_name}
|
||||
originalDirectory={domain?.directory}
|
||||
getTagInfo={handleGetTagInfo}
|
||||
onSave={handleTagSave}
|
||||
collectionName="Domain"
|
||||
/>
|
||||
|
||||
{/* Downloads Segment */}
|
||||
<Segment>
|
||||
<Header as='h1'>Downloads</Header>
|
||||
<RecurringDownloadsTable
|
||||
downloads={domain?.downloads}
|
||||
fetchDownloads={fetchDomain}
|
||||
/>
|
||||
</Segment>
|
||||
</>;
|
||||
}
|
||||
|
||||
|
|
@ -633,9 +795,21 @@ export function ArchiveRowCells({file}) {
|
|||
}
|
||||
|
||||
export function ArchiveRoute() {
|
||||
const location = useLocation();
|
||||
const path = location.pathname;
|
||||
|
||||
const links = [
|
||||
{text: 'Archives', to: '/archive', end: true},
|
||||
{text: 'Domains', to: '/archive/domains'},
|
||||
{
|
||||
text: 'Archives',
|
||||
to: '/archive',
|
||||
end: true,
|
||||
isActive: () => path === '/archive' || /^\/archive\/\d+$/.test(path)
|
||||
},
|
||||
{
|
||||
text: 'Domains',
|
||||
to: '/archive/domains',
|
||||
isActive: () => path.startsWith('/archive/domain')
|
||||
},
|
||||
{text: 'Settings', to: '/archive/settings'},
|
||||
];
|
||||
return <PageContainer>
|
||||
|
|
@ -643,6 +817,7 @@ export function ArchiveRoute() {
|
|||
<Routes>
|
||||
<Route path='/' element={<ArchivesPage/>}/>
|
||||
<Route path='domains' element={<DomainsPage/>}/>
|
||||
<Route path='domain/:domainId/edit' element={<DomainEditPage/>}/>
|
||||
<Route path='settings' element={<ArchiveSettingsPage/>}/>
|
||||
<Route path=':archiveId' element={<ArchivePage/>}/>
|
||||
</Routes>
|
||||
|
|
|
|||
|
|
@ -1,6 +1,7 @@
|
|||
import React, {useState} from "react";
|
||||
import {Grid, Input, StatisticLabel, StatisticValue, TableCell, TableRow,} from "semantic-ui-react";
|
||||
import {Grid, StatisticLabel, StatisticValue, TableCell, TableRow,} from "semantic-ui-react";
|
||||
import {createChannel, deleteChannel, refreshChannel, tagChannel, tagChannelInfo, updateChannel} from "../api";
|
||||
import {CollectionTagModal} from "./collections/CollectionTagModal";
|
||||
import {
|
||||
APIButton,
|
||||
BackButton,
|
||||
|
|
@ -12,7 +13,6 @@ import {
|
|||
secondsToFrequency,
|
||||
secondsToFullDuration,
|
||||
SimpleAccordion,
|
||||
Toggle,
|
||||
useTitle,
|
||||
WROLModeMessage
|
||||
} from "./Common";
|
||||
|
|
@ -26,9 +26,7 @@ import {
|
|||
Header,
|
||||
Loader,
|
||||
Modal,
|
||||
ModalActions,
|
||||
ModalContent,
|
||||
ModalHeader,
|
||||
Segment,
|
||||
Statistic
|
||||
} from "./Theme";
|
||||
|
|
@ -36,9 +34,10 @@ import {Media, ThemeContext} from "../contexts/contexts";
|
|||
import {SortableTable} from "./SortableTable";
|
||||
import {toast} from "react-semantic-toasts-2";
|
||||
import {RecurringDownloadsTable} from "./admin/Downloads";
|
||||
import {TagsContext, TagsSelector} from "../Tags";
|
||||
import {TagsContext} from "../Tags";
|
||||
import {InputForm, ToggleForm} from "../hooks/useForm";
|
||||
import {ChannelDownloadForm, DestinationForm, DownloadTagsSelector} from "./Download";
|
||||
import {CollectionTable} from "./collections/CollectionTable";
|
||||
|
||||
|
||||
function ChannelStatistics({statistics}) {
|
||||
|
|
@ -86,20 +85,11 @@ export function ChannelPage({create, header}) {
|
|||
const {SingleTag} = React.useContext(TagsContext);
|
||||
|
||||
const [tagEditModalOpen, setTagEditModalOpen] = useState(false);
|
||||
const [newTagName, setNewTagName] = useState(null);
|
||||
const [moveToTagDirectory, setMoveToTagDirectory] = useState(true);
|
||||
const [newTagDirectory, setNewTagDirectory] = useState('');
|
||||
|
||||
const {channel, form, fetchChannel} = useChannel(channelId);
|
||||
|
||||
useTitle(_.isEmpty(channel) ? null : `${channel.name} Channel`);
|
||||
|
||||
React.useEffect(() => {
|
||||
if (channel && channel.tag_name !== newTagName) {
|
||||
setNewTagName(channel.tag_name);
|
||||
}
|
||||
}, [channel]);
|
||||
|
||||
if (!create && !form.ready) {
|
||||
// Waiting for editing Channel to be fetched.
|
||||
return <Loader active/>;
|
||||
|
|
@ -223,10 +213,10 @@ export function ChannelPage({create, header}) {
|
|||
setDownloadModalOpen(false);
|
||||
}
|
||||
|
||||
const handleTagEditChannel = async () => {
|
||||
// Handler for tag modal save
|
||||
const handleTagSave = async (tagName, directory) => {
|
||||
try {
|
||||
await tagChannel(channelId, newTagName, moveToTagDirectory ? newTagDirectory : null);
|
||||
setTagEditModalOpen(false);
|
||||
await tagChannel(channelId, tagName, directory);
|
||||
} catch (e) {
|
||||
console.error('Failed to tag channel', e);
|
||||
} finally {
|
||||
|
|
@ -235,69 +225,25 @@ export function ChannelPage({create, header}) {
|
|||
await fetchChannel();
|
||||
}, 500);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const handleTagSelectMoveSuggestion = async (newTagName_) => {
|
||||
setNewTagName(newTagName_);
|
||||
try {
|
||||
// Get suggested Tag directory for this Tag and Channel.
|
||||
const videosDestination = await tagChannelInfo(channelId, newTagName_);
|
||||
setNewTagDirectory(videosDestination);
|
||||
} catch (e) {
|
||||
console.error('Failed to tag channel', e);
|
||||
}
|
||||
}
|
||||
// Handler for fetching tag info
|
||||
const handleGetTagInfo = async (tagName) => {
|
||||
return await tagChannelInfo(channelId, tagName);
|
||||
};
|
||||
|
||||
let tagEditModal;
|
||||
if (!create) {
|
||||
// User is editing the Tag of the Channel.
|
||||
tagEditModal = <Modal
|
||||
tagEditModal = <CollectionTagModal
|
||||
open={tagEditModalOpen}
|
||||
onClose={() => setTagEditModalOpen(false)}
|
||||
closeIcon
|
||||
>
|
||||
<ModalHeader>{channel.tag_name ? 'Modify Tag' : 'Add Tag'}</ModalHeader>
|
||||
<ModalContent>
|
||||
<Grid columns={1}>
|
||||
<Grid.Row>
|
||||
<Grid.Column>
|
||||
<TagsSelector
|
||||
limit={1}
|
||||
selectedTagNames={newTagName ? [newTagName] : []}
|
||||
onAdd={handleTagSelectMoveSuggestion}
|
||||
onRemove={() => handleTagSelectMoveSuggestion(null)}
|
||||
/>
|
||||
</Grid.Column>
|
||||
</Grid.Row>
|
||||
<Grid.Row>
|
||||
<Grid.Column>
|
||||
<Toggle
|
||||
label='Move to directory: '
|
||||
checked={moveToTagDirectory}
|
||||
onChange={setMoveToTagDirectory}
|
||||
/>
|
||||
</Grid.Column>
|
||||
</Grid.Row>
|
||||
<Grid.Row>
|
||||
<Grid.Column>
|
||||
<Input fluid
|
||||
value={newTagDirectory}
|
||||
onChange={(e, {value}) => setNewTagDirectory(value)}
|
||||
disabled={!moveToTagDirectory}
|
||||
/>
|
||||
</Grid.Column>
|
||||
</Grid.Row>
|
||||
</Grid>
|
||||
</ModalContent>
|
||||
<ModalActions>
|
||||
<Button onClick={() => setTagEditModalOpen(false)}>Cancel</Button>
|
||||
<APIButton
|
||||
color='violet'
|
||||
onClick={handleTagEditChannel}
|
||||
obeyWROLMode={true}
|
||||
>{moveToTagDirectory ? 'Move' : 'Save'}</APIButton>
|
||||
</ModalActions>
|
||||
</Modal>;
|
||||
currentTagName={channel.tag_name}
|
||||
originalDirectory={channel.directory}
|
||||
getTagInfo={handleGetTagInfo}
|
||||
onSave={handleTagSave}
|
||||
collectionName="Channel"
|
||||
/>;
|
||||
}
|
||||
|
||||
let channelUrlRow;
|
||||
|
|
@ -502,72 +448,13 @@ export function ChannelNewPage(props) {
|
|||
return <ChannelPage header='New Channel' {...props} create/>
|
||||
}
|
||||
|
||||
function ChannelRow({channel}) {
|
||||
const {SingleTag} = React.useContext(TagsContext);
|
||||
|
||||
const videosTo = `/videos/channel/${channel.id}/video`;
|
||||
|
||||
const {inverted} = React.useContext(ThemeContext);
|
||||
const editTo = `/videos/channel/${channel.id}/edit`;
|
||||
const buttonClass = `ui button secondary ${inverted}`;
|
||||
|
||||
return <TableRow>
|
||||
<TableCell>
|
||||
<Link to={videosTo}>{channel.name}</Link>
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
{channel.tag_name ? <SingleTag name={channel.tag_name}/> : null}
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
{channel.video_count}
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
{channel.url && channel.minimum_frequency ? secondsToFrequency(channel.minimum_frequency) : null}
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
{channel.size ? humanFileSize(channel.size) : null}
|
||||
</TableCell>
|
||||
<TableCell textAlign='right'>
|
||||
<Link className={buttonClass} to={editTo}>Edit</Link>
|
||||
</TableCell>
|
||||
</TableRow>;
|
||||
}
|
||||
|
||||
function MobileChannelRow({channel}) {
|
||||
const {SingleTag} = React.useContext(TagsContext);
|
||||
|
||||
const editTo = `/videos/channel/${channel.id}/edit`;
|
||||
const videosTo = `/videos/channel/${channel.id}/video`;
|
||||
return <TableRow verticalAlign='top'>
|
||||
<TableCell width={10} colSpan={2}>
|
||||
<Link as='h3' to={videosTo}>
|
||||
<h3>
|
||||
{channel.name}
|
||||
</h3>
|
||||
{channel.tag_name ? <SingleTag name={channel.tag_name}/> : null}
|
||||
</Link>
|
||||
<p>
|
||||
Videos: {channel.video_count}
|
||||
</p>
|
||||
</TableCell>
|
||||
<TableCell width={6} colSpan={2} textAlign='right'>
|
||||
<p>
|
||||
<Link className="ui button secondary" to={editTo}>Edit</Link>
|
||||
</p>
|
||||
</TableCell>
|
||||
</TableRow>;
|
||||
}
|
||||
|
||||
|
||||
export function ChannelsPage() {
|
||||
useTitle('Channels');
|
||||
|
||||
const {channels} = useChannels();
|
||||
const [channels, total, metadata] = useChannels();
|
||||
const [searchStr, setSearchStr] = useOneQuery('name');
|
||||
// Hides Channels with few videos.
|
||||
const [hideSmall, setHideSmall] = React.useState(true);
|
||||
const enoughChannelsToHideSmall = channels && channels.length > 20;
|
||||
|
||||
// Header section matching DomainsPage pattern
|
||||
const header = <div style={{marginBottom: '1em'}}>
|
||||
<Grid stackable columns={2}>
|
||||
<Grid.Row>
|
||||
|
|
@ -591,25 +478,7 @@ export function ChannelsPage() {
|
|||
</Grid>
|
||||
</div>;
|
||||
|
||||
const headers = [
|
||||
{key: 'name', text: 'Name', sortBy: [i => i['name'].toLowerCase()], width: 8},
|
||||
{key: 'tag', text: 'Tag', sortBy: [i => i['tag_name'], i => i['name'].toLowerCase()], width: 2},
|
||||
{key: 'video_count', text: 'Videos', sortBy: [i => i['video_count'], i => i['name'].toLowerCase()], width: 2},
|
||||
{
|
||||
key: 'download_frequency',
|
||||
text: 'Download Frequency',
|
||||
sortBy: [i => i['minimum_frequency'], i => i['name'].toLowerCase()],
|
||||
width: 2
|
||||
},
|
||||
{key: 'size', text: 'Size', sortBy: [i => i['size'], i => i['name'].toLowerCase()], width: 2},
|
||||
{key: 'manage', text: 'Manage', width: 2},
|
||||
];
|
||||
const mobileHeaders = [
|
||||
{key: 'name', text: 'Name', sortBy: [i => i['name'].toLowerCase()]},
|
||||
{key: 'video_count', text: 'Videos', sortBy: [i => i['video_count'], i => i['name'].toLowerCase()]},
|
||||
{key: 'manage', text: 'Manage'},
|
||||
];
|
||||
|
||||
// Empty state
|
||||
if (channels && channels.length === 0) {
|
||||
return <>
|
||||
{header}
|
||||
|
|
@ -617,65 +486,23 @@ export function ChannelsPage() {
|
|||
<Message.Header>No channels exist yet!</Message.Header>
|
||||
<Message.Content><Link to='/videos/channel/new'>Create one.</Link></Message.Content>
|
||||
</Message>
|
||||
</>
|
||||
} else if (channels === undefined) {
|
||||
</>;
|
||||
}
|
||||
|
||||
// Error state
|
||||
if (channels === undefined) {
|
||||
return <>
|
||||
{header}
|
||||
<ErrorMessage>Could not fetch Channels</ErrorMessage>
|
||||
</>
|
||||
}
|
||||
|
||||
let filteredChannels = channels;
|
||||
if (searchStr && Array.isArray(channels)) {
|
||||
const re = new RegExp(_.escapeRegExp(searchStr), 'i');
|
||||
filteredChannels = channels.filter(i => re.test(i['name']));
|
||||
} else if (channels && hideSmall && enoughChannelsToHideSmall) {
|
||||
// Get the top 80% of Channels.
|
||||
let index80 = Math.floor(channels.length * 0.8);
|
||||
const sortedChannels = channels.sort((a, b) => b.video_count - a.video_count);
|
||||
let percentile = sortedChannels[index80].video_count;
|
||||
filteredChannels = channels.filter(i => {
|
||||
return i.video_count > percentile || i.name.toLowerCase() === 'wrolpi'
|
||||
});
|
||||
if (filteredChannels.length < 21) {
|
||||
// Filtering hid too many Channels, show them all.
|
||||
filteredChannels = channels;
|
||||
}
|
||||
</>;
|
||||
}
|
||||
|
||||
return <>
|
||||
{header}
|
||||
<Media at='mobile'>
|
||||
<SortableTable
|
||||
tableProps={{striped: true, size: 'small', unstackable: true}}
|
||||
data={filteredChannels}
|
||||
tableHeaders={mobileHeaders}
|
||||
defaultSortColumn='name'
|
||||
rowKey='id'
|
||||
rowFunc={(i, sortData) => <MobileChannelRow key={i.id} channel={i} sortData={sortData}/>}
|
||||
/>
|
||||
</Media>
|
||||
<Media greaterThanOrEqual='tablet'>
|
||||
<SortableTable
|
||||
tableProps={{striped: true, size: 'large', unstackable: true, compact: true}}
|
||||
data={filteredChannels}
|
||||
tableHeaders={headers}
|
||||
defaultSortColumn='name'
|
||||
rowKey='id'
|
||||
rowFunc={(i, sortData) => <ChannelRow key={i.id} channel={i} sortData={sortData}/>}
|
||||
/>
|
||||
</Media>
|
||||
<Grid textAlign='center'>
|
||||
<Grid.Row>
|
||||
<Grid.Column>
|
||||
<Button
|
||||
style={{marginTop: '1em'}}
|
||||
onClick={() => setHideSmall(!hideSmall)}
|
||||
size='big'
|
||||
disabled={!enoughChannelsToHideSmall}
|
||||
>Show {hideSmall ? 'More' : 'Less'}</Button>
|
||||
</Grid.Column>
|
||||
</Grid.Row>
|
||||
</Grid>
|
||||
</>
|
||||
<CollectionTable
|
||||
collections={channels}
|
||||
metadata={metadata}
|
||||
searchStr={searchStr}
|
||||
/>
|
||||
</>;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -303,6 +303,21 @@ export function secondsToTimestamp(seconds) {
|
|||
}
|
||||
|
||||
export function humanFileSize(bytes, dp = 1) {
|
||||
// Handle null/undefined
|
||||
if (bytes == null) {
|
||||
return '-';
|
||||
}
|
||||
|
||||
// Convert string to number if needed
|
||||
if (typeof bytes === 'string') {
|
||||
bytes = parseFloat(bytes);
|
||||
}
|
||||
|
||||
// Handle invalid numbers
|
||||
if (isNaN(bytes) || !isFinite(bytes)) {
|
||||
return '-';
|
||||
}
|
||||
|
||||
const thresh = 1024;
|
||||
|
||||
if (Math.abs(bytes) < thresh) {
|
||||
|
|
@ -318,7 +333,6 @@ export function humanFileSize(bytes, dp = 1) {
|
|||
++u;
|
||||
} while (Math.round(Math.abs(bytes) * r) / r >= thresh && u < units.length - 1);
|
||||
|
||||
|
||||
return bytes.toFixed(dp) + ' ' + units[u];
|
||||
}
|
||||
|
||||
|
|
@ -596,10 +610,13 @@ export function TabLinks({links}) {
|
|||
return <Menu tabular>
|
||||
{links.map((link) => <NavLink
|
||||
to={getTo(link.to)}
|
||||
className='item'
|
||||
style={{padding: '1em'}}
|
||||
key={link.to}
|
||||
end={link.end === true ? true : null}
|
||||
className={({isActive}) => {
|
||||
const active = link.isActive ? link.isActive() : isActive;
|
||||
return active ? 'item active' : 'item';
|
||||
}}
|
||||
>
|
||||
{link.text}
|
||||
</NavLink>)}
|
||||
|
|
@ -1224,10 +1241,18 @@ export function DirectorySearch({onSelect, value, disabled, required, ...props})
|
|||
}
|
||||
}
|
||||
|
||||
const handleBlur = (e) => {
|
||||
// When user leaves the field, commit the typed value to the form
|
||||
if (onSelect && directoryName !== value) {
|
||||
onSelect(directoryName);
|
||||
}
|
||||
}
|
||||
|
||||
return <Search category
|
||||
placeholder='Search directory names...'
|
||||
onSearchChange={handleSearchChange}
|
||||
onResultSelect={handleResultSelect}
|
||||
onBlur={handleBlur}
|
||||
loading={loading}
|
||||
value={directoryName}
|
||||
results={results}
|
||||
|
|
|
|||
392
app/src/components/Common.test.js
Normal file
392
app/src/components/Common.test.js
Normal file
|
|
@ -0,0 +1,392 @@
|
|||
import React from 'react';
|
||||
import {render, screen, waitFor, act} from '@testing-library/react';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import {DirectorySearch} from './Common';
|
||||
|
||||
// Mock debounce to make tests run faster
|
||||
jest.mock('lodash/debounce', () => jest.fn(fn => {
|
||||
fn.cancel = jest.fn();
|
||||
return fn;
|
||||
}));
|
||||
|
||||
// Mock useSearchDirectories hook to avoid async state updates that cause act() warnings
|
||||
const mockSetDirectoryName = jest.fn();
|
||||
let mockHookState = {
|
||||
directoryName: '',
|
||||
directories: [],
|
||||
channelDirectories: [],
|
||||
domainDirectories: [],
|
||||
isDir: false,
|
||||
loading: false,
|
||||
};
|
||||
|
||||
jest.mock('../hooks/customHooks', () => ({
|
||||
...jest.requireActual('../hooks/customHooks'),
|
||||
useSearchDirectories: (value) => {
|
||||
// Return current mock state - tests control state via setMockHookState
|
||||
return {
|
||||
...mockHookState,
|
||||
setDirectoryName: (newValue) => {
|
||||
mockHookState.directoryName = newValue;
|
||||
mockSetDirectoryName(newValue);
|
||||
},
|
||||
};
|
||||
},
|
||||
}));
|
||||
|
||||
describe('DirectorySearch', () => {
|
||||
const mockOnSelect = jest.fn();
|
||||
|
||||
const mockSearchResults = {
|
||||
directories: [
|
||||
{path: 'videos/nature'},
|
||||
{path: 'videos/tech'}
|
||||
],
|
||||
channelDirectories: [
|
||||
{path: 'videos/channels/news', name: 'News Channel'}
|
||||
],
|
||||
domainDirectories: [
|
||||
{path: 'archive/example.com', domain: 'example.com'}
|
||||
],
|
||||
};
|
||||
|
||||
// Helper to reset mock hook state with specific values
|
||||
const setMockHookState = (overrides = {}) => {
|
||||
mockHookState = {
|
||||
directoryName: '',
|
||||
directories: [],
|
||||
channelDirectories: [],
|
||||
domainDirectories: [],
|
||||
isDir: false,
|
||||
loading: false,
|
||||
...overrides,
|
||||
};
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks();
|
||||
// Reset mock hook state with default search results
|
||||
setMockHookState({
|
||||
...mockSearchResults,
|
||||
isDir: false,
|
||||
});
|
||||
});
|
||||
|
||||
describe('Rendering', () => {
|
||||
it('renders with placeholder text', () => {
|
||||
render(<DirectorySearch onSelect={mockOnSelect} value="" />);
|
||||
|
||||
const input = screen.getByPlaceholderText(/search directory names/i);
|
||||
expect(input).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows initial value when provided', () => {
|
||||
setMockHookState({
|
||||
...mockSearchResults,
|
||||
directoryName: 'videos/test',
|
||||
});
|
||||
|
||||
render(<DirectorySearch onSelect={mockOnSelect} value="videos/test" />);
|
||||
|
||||
const input = screen.getByDisplayValue('videos/test');
|
||||
expect(input).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('applies disabled state correctly', () => {
|
||||
render(<DirectorySearch onSelect={mockOnSelect} value="" disabled />);
|
||||
|
||||
const input = screen.getByPlaceholderText(/search directory names/i);
|
||||
expect(input).toBeDisabled();
|
||||
});
|
||||
|
||||
it('displays with required indicator', () => {
|
||||
const {container} = render(
|
||||
<DirectorySearch onSelect={mockOnSelect} value="" required />
|
||||
);
|
||||
|
||||
// Semantic UI doesn't add required attribute to Search input,
|
||||
// but we verify the prop is passed
|
||||
expect(container.querySelector('.ui.search')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
describe('Search Functionality', () => {
|
||||
it('triggers setDirectoryName on value change', async () => {
|
||||
render(<DirectorySearch onSelect={mockOnSelect} value="" />);
|
||||
|
||||
const input = screen.getByPlaceholderText(/search directory names/i);
|
||||
await userEvent.type(input, 'videos');
|
||||
|
||||
// Verify setDirectoryName was called (via mocked hook)
|
||||
expect(mockSetDirectoryName).toHaveBeenCalled();
|
||||
// Debounce is mocked, so each character triggers a call
|
||||
// Verify it was called 6 times (one per character in "videos")
|
||||
expect(mockSetDirectoryName.mock.calls.length).toBe(6);
|
||||
});
|
||||
|
||||
it('shows loading indicator when loading state is true', () => {
|
||||
setMockHookState({
|
||||
...mockSearchResults,
|
||||
loading: true,
|
||||
});
|
||||
|
||||
render(<DirectorySearch onSelect={mockOnSelect} value="" />);
|
||||
|
||||
const searchContainer = screen.getByPlaceholderText(/search directory names/i)
|
||||
.closest('.ui.search');
|
||||
expect(searchContainer).toHaveClass('loading');
|
||||
});
|
||||
|
||||
it('hides loading indicator when loading state is false', () => {
|
||||
setMockHookState({
|
||||
...mockSearchResults,
|
||||
loading: false,
|
||||
});
|
||||
|
||||
render(<DirectorySearch onSelect={mockOnSelect} value="" />);
|
||||
|
||||
const searchContainer = screen.getByPlaceholderText(/search directory names/i)
|
||||
.closest('.ui.search');
|
||||
expect(searchContainer).not.toHaveClass('loading');
|
||||
});
|
||||
|
||||
it('displays categorized results', async () => {
|
||||
render(<DirectorySearch onSelect={mockOnSelect} value="" />);
|
||||
|
||||
const input = screen.getByPlaceholderText(/search directory names/i);
|
||||
// Click to open dropdown
|
||||
await userEvent.click(input);
|
||||
|
||||
await waitFor(() => {
|
||||
// Should show category names
|
||||
expect(screen.getAllByText(/Directories/i).length).toBeGreaterThan(0);
|
||||
expect(screen.getAllByText(/Channels/i).length).toBeGreaterThan(0);
|
||||
expect(screen.getAllByText(/Domains/i).length).toBeGreaterThan(0);
|
||||
});
|
||||
});
|
||||
|
||||
it('shows "New Directory" when path doesn\'t exist (isDir=false)', async () => {
|
||||
setMockHookState({
|
||||
directories: [],
|
||||
channelDirectories: [],
|
||||
domainDirectories: [],
|
||||
isDir: false,
|
||||
directoryName: 'new/path',
|
||||
});
|
||||
|
||||
render(<DirectorySearch onSelect={mockOnSelect} value="" />);
|
||||
|
||||
const input = screen.getByPlaceholderText(/search directory names/i);
|
||||
await userEvent.click(input);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText(/New Directory/i)).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
it('hides "New Directory" when path exists (isDir=true)', async () => {
|
||||
setMockHookState({
|
||||
directories: [{path: 'videos/nature/wildlife'}],
|
||||
channelDirectories: [],
|
||||
domainDirectories: [],
|
||||
isDir: true,
|
||||
directoryName: 'videos/nature',
|
||||
});
|
||||
|
||||
render(<DirectorySearch onSelect={mockOnSelect} value="" />);
|
||||
|
||||
const input = screen.getByPlaceholderText(/search directory names/i);
|
||||
await userEvent.click(input);
|
||||
|
||||
// "New Directory" should not appear when is_dir=true
|
||||
expect(screen.queryByText(/New Directory/i)).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('debounces rapid typing (verifies setDirectoryName is called)', async () => {
|
||||
render(<DirectorySearch onSelect={mockOnSelect} value="" />);
|
||||
|
||||
const input = screen.getByPlaceholderText(/search directory names/i);
|
||||
|
||||
// Type rapidly
|
||||
await userEvent.type(input, 'abc', {delay: 10});
|
||||
|
||||
// Verify setDirectoryName was called
|
||||
expect(mockSetDirectoryName).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('User Interactions', () => {
|
||||
it('calls onSelect when result is clicked', async () => {
|
||||
render(<DirectorySearch onSelect={mockOnSelect} value="" />);
|
||||
|
||||
const input = screen.getByPlaceholderText(/search directory names/i);
|
||||
await userEvent.click(input);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('videos/nature')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
// Click on a result
|
||||
const result = screen.getByText('videos/nature');
|
||||
await userEvent.click(result);
|
||||
|
||||
expect(mockOnSelect).toHaveBeenCalledWith('videos/nature');
|
||||
});
|
||||
|
||||
it('commits typed value on blur when directoryName differs from value', async () => {
|
||||
// Set up mock state where directoryName differs from the prop value
|
||||
// This simulates what happens after user types in the input
|
||||
setMockHookState({
|
||||
...mockSearchResults,
|
||||
directoryName: 'typed/path', // User has typed this
|
||||
});
|
||||
|
||||
// Render with empty value prop (different from directoryName)
|
||||
const {container} = render(<DirectorySearch onSelect={mockOnSelect} value="" />);
|
||||
|
||||
// Find the Search component container and trigger blur on it
|
||||
const searchComponent = container.querySelector('.ui.search');
|
||||
|
||||
// Blur the Search component - should trigger onBlur which calls onSelect
|
||||
await act(async () => {
|
||||
// Use fireEvent.blur which better simulates the Semantic UI Search blur behavior
|
||||
const {fireEvent} = require('@testing-library/react');
|
||||
fireEvent.blur(searchComponent);
|
||||
});
|
||||
|
||||
// Should call onSelect with directoryName from hook state
|
||||
expect(mockOnSelect).toHaveBeenCalledWith('typed/path');
|
||||
});
|
||||
|
||||
it('does not call onSelect on blur if value unchanged', async () => {
|
||||
setMockHookState({
|
||||
...mockSearchResults,
|
||||
directoryName: 'existing/path',
|
||||
});
|
||||
|
||||
render(<DirectorySearch onSelect={mockOnSelect} value="existing/path" />);
|
||||
|
||||
const input = screen.getByDisplayValue('existing/path');
|
||||
|
||||
// Blur without changing value
|
||||
await act(async () => {
|
||||
input.blur();
|
||||
});
|
||||
|
||||
// Should not call onSelect since value didn't change
|
||||
expect(mockOnSelect).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('disabled state prevents interactions', () => {
|
||||
render(<DirectorySearch onSelect={mockOnSelect} value="" disabled />);
|
||||
|
||||
const input = screen.getByPlaceholderText(/search directory names/i);
|
||||
|
||||
// Input should be disabled
|
||||
expect(input).toBeDisabled();
|
||||
});
|
||||
|
||||
it('handles rapid selection changes', async () => {
|
||||
render(<DirectorySearch onSelect={mockOnSelect} value="" />);
|
||||
|
||||
const input = screen.getByPlaceholderText(/search directory names/i);
|
||||
await userEvent.click(input);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('videos/nature')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
// Click multiple results in succession
|
||||
await userEvent.click(screen.getByText('videos/nature'));
|
||||
await userEvent.click(screen.getByText('videos/tech'));
|
||||
|
||||
// Should call onSelect for each selection
|
||||
expect(mockOnSelect).toHaveBeenCalledWith('videos/nature');
|
||||
expect(mockOnSelect).toHaveBeenCalledWith('videos/tech');
|
||||
});
|
||||
});
|
||||
|
||||
describe('Hook Integration', () => {
|
||||
it('calls setDirectoryName from hook on search change', async () => {
|
||||
render(<DirectorySearch onSelect={mockOnSelect} value="" />);
|
||||
|
||||
const input = screen.getByPlaceholderText(/search directory names/i);
|
||||
await userEvent.type(input, 'archive');
|
||||
|
||||
expect(mockSetDirectoryName).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('displays results from hook state', async () => {
|
||||
render(<DirectorySearch onSelect={mockOnSelect} value="" />);
|
||||
|
||||
const input = screen.getByPlaceholderText(/search directory names/i);
|
||||
await userEvent.click(input);
|
||||
|
||||
await waitFor(() => {
|
||||
// Should display results from mock hook state
|
||||
expect(screen.getByText('videos/nature')).toBeInTheDocument();
|
||||
expect(screen.getByText('videos/tech')).toBeInTheDocument();
|
||||
expect(screen.getByText('News Channel')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('Edge Cases', () => {
|
||||
it('handles null/undefined initial value', () => {
|
||||
setMockHookState({
|
||||
...mockSearchResults,
|
||||
directoryName: '',
|
||||
});
|
||||
|
||||
render(<DirectorySearch onSelect={mockOnSelect} value={null} />);
|
||||
|
||||
const input = screen.getByPlaceholderText(/search directory names/i);
|
||||
expect(input).toHaveValue('');
|
||||
});
|
||||
|
||||
it('clears results display when empty', async () => {
|
||||
setMockHookState({
|
||||
directories: [],
|
||||
channelDirectories: [],
|
||||
domainDirectories: [],
|
||||
isDir: false,
|
||||
directoryName: '',
|
||||
});
|
||||
|
||||
render(<DirectorySearch onSelect={mockOnSelect} value="" />);
|
||||
|
||||
const input = screen.getByPlaceholderText(/search directory names/i);
|
||||
expect(input).toHaveValue('');
|
||||
});
|
||||
|
||||
it('maintains value when component remounts', () => {
|
||||
setMockHookState({
|
||||
...mockSearchResults,
|
||||
directoryName: 'videos/test',
|
||||
});
|
||||
|
||||
const {rerender} = render(
|
||||
<DirectorySearch onSelect={mockOnSelect} value="videos/test" />
|
||||
);
|
||||
|
||||
expect(screen.getByDisplayValue('videos/test')).toBeInTheDocument();
|
||||
|
||||
// Remount with same value
|
||||
rerender(<DirectorySearch onSelect={mockOnSelect} value="videos/test" />);
|
||||
|
||||
expect(screen.getByDisplayValue('videos/test')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('handles special characters in path', async () => {
|
||||
render(<DirectorySearch onSelect={mockOnSelect} value="" />);
|
||||
|
||||
const input = screen.getByPlaceholderText(/search directory names/i);
|
||||
|
||||
// Type path with special characters
|
||||
const specialPath = 'videos/test-folder_2024/v1.0';
|
||||
await userEvent.type(input, specialPath);
|
||||
|
||||
expect(mockSetDirectoryName).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
});
|
||||
446
app/src/components/DomainEditPage.test.js
Normal file
446
app/src/components/DomainEditPage.test.js
Normal file
|
|
@ -0,0 +1,446 @@
|
|||
import React from 'react';
|
||||
import {render, renderInDarkMode, screen, waitFor, createTestForm} from '../test-utils';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import {DomainEditPage} from './Archive';
|
||||
import {createMockDomain, createMockMetadata} from '../test-utils';
|
||||
|
||||
// Mock useParams to return domain ID
|
||||
jest.mock('react-router-dom', () => ({
|
||||
...jest.requireActual('react-router-dom'),
|
||||
useParams: () => ({domainId: '1'}),
|
||||
useNavigate: () => jest.fn(),
|
||||
}));
|
||||
|
||||
// Mock the useDomain hook
|
||||
const mockUseDomain = jest.fn();
|
||||
const mockUseCollectionMetadata = jest.fn();
|
||||
|
||||
jest.mock('../hooks/customHooks', () => ({
|
||||
...jest.requireActual('../hooks/customHooks'),
|
||||
useDomain: (...args) => mockUseDomain(...args),
|
||||
useCollectionMetadata: (...args) => mockUseCollectionMetadata(...args),
|
||||
}));
|
||||
|
||||
// Mock useTitle
|
||||
jest.mock('./Common', () => ({
|
||||
...jest.requireActual('./Common'),
|
||||
useTitle: jest.fn(),
|
||||
}));
|
||||
|
||||
// Mock CollectionEditForm
|
||||
jest.mock('./collections/CollectionEditForm', () => ({
|
||||
CollectionEditForm: ({form, metadata, title, actionButtons}) => (
|
||||
<div data-testid="collection-edit-form">
|
||||
{title && <h1>{title}</h1>}
|
||||
{form?.loading && <div data-testid="loading-indicator">Loading...</div>}
|
||||
{form?.formData && <div data-testid="collection-data">Collection data loaded</div>}
|
||||
{metadata && <div data-testid="metadata-present">Metadata loaded</div>}
|
||||
{actionButtons && <div data-testid="action-buttons">{actionButtons}</div>}
|
||||
</div>
|
||||
),
|
||||
}));
|
||||
|
||||
// Mock CollectionTagModal
|
||||
jest.mock('./collections/CollectionTagModal', () => ({
|
||||
CollectionTagModal: ({open, onClose, currentTagName, originalDirectory, getTagInfo, onSave, collectionName}) => {
|
||||
if (!open) return null;
|
||||
return (
|
||||
<div data-testid="collection-tag-modal">
|
||||
<div data-testid="modal-header">{currentTagName ? 'Modify Tag' : 'Add Tag'}</div>
|
||||
<input type="text" data-testid="directory-input" defaultValue={originalDirectory || ''} />
|
||||
<button data-testid="cancel-button" onClick={onClose}>Cancel</button>
|
||||
<button data-testid="save-button" onClick={() => onSave && onSave(currentTagName, originalDirectory)}>Save</button>
|
||||
</div>
|
||||
);
|
||||
},
|
||||
}));
|
||||
|
||||
// Mock API functions
|
||||
const mockGetCollectionTagInfo = jest.fn();
|
||||
jest.mock('../api', () => ({
|
||||
...jest.requireActual('../api'),
|
||||
getCollectionTagInfo: (...args) => mockGetCollectionTagInfo(...args),
|
||||
tagDomain: jest.fn(),
|
||||
}));
|
||||
|
||||
describe('DomainEditPage', () => {
|
||||
const mockMetadata = createMockMetadata();
|
||||
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks();
|
||||
mockUseCollectionMetadata.mockReturnValue({metadata: mockMetadata});
|
||||
});
|
||||
|
||||
describe('Loading States', () => {
|
||||
it('handles loading state while fetching domain', async () => {
|
||||
// Start with loading state (no domain yet)
|
||||
const form = createTestForm({}, {
|
||||
overrides: {ready: false, loading: false}
|
||||
});
|
||||
|
||||
mockUseDomain.mockReturnValue({
|
||||
domain: null,
|
||||
form,
|
||||
fetchDomain: jest.fn(),
|
||||
});
|
||||
|
||||
render(<DomainEditPage />);
|
||||
|
||||
// Should show Semantic UI Loader with text
|
||||
expect(screen.getByText(/loading domain/i)).toBeInTheDocument();
|
||||
|
||||
// Form should not be visible during initial load
|
||||
expect(screen.queryByTestId('collection-edit-form')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows form when domain is loaded', () => {
|
||||
const mockDomain = createMockDomain({
|
||||
domain: 'test.com',
|
||||
});
|
||||
|
||||
const form = createTestForm(mockDomain, {
|
||||
overrides: {ready: true, loading: false}
|
||||
});
|
||||
|
||||
mockUseDomain.mockReturnValue({
|
||||
domain: mockDomain,
|
||||
form,
|
||||
fetchDomain: jest.fn(),
|
||||
});
|
||||
|
||||
render(<DomainEditPage />);
|
||||
|
||||
// Should NOT show loading message
|
||||
expect(screen.queryByText(/loading domain/i)).not.toBeInTheDocument();
|
||||
|
||||
// Should show domain name (may appear multiple times in header and form)
|
||||
expect(screen.getAllByText(/test\.com/i).length).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
it('passes loading state to form during submission', () => {
|
||||
const mockDomain = createMockDomain({
|
||||
domain: 'example.com',
|
||||
});
|
||||
|
||||
// Domain is loaded but form is submitting
|
||||
const form = createTestForm(mockDomain, {
|
||||
overrides: {ready: true, loading: true}
|
||||
});
|
||||
|
||||
mockUseDomain.mockReturnValue({
|
||||
domain: mockDomain,
|
||||
form,
|
||||
fetchDomain: jest.fn(),
|
||||
});
|
||||
|
||||
render(<DomainEditPage />);
|
||||
|
||||
// Should show loading indicator in form (from mocked component)
|
||||
// Multiple indicators due to Fresnel rendering for mobile and tablet+
|
||||
expect(screen.getAllByTestId('loading-indicator').length).toBeGreaterThan(0);
|
||||
|
||||
// Should also show the domain name
|
||||
expect(screen.getAllByText(/example\.com/i).length).toBeGreaterThan(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('Error States', () => {
|
||||
it('shows loader when form is not ready (fetch fails)', () => {
|
||||
// When form.ready is false (e.g., fetch failed), show loader
|
||||
const form = createTestForm({}, {
|
||||
overrides: {ready: false, loading: false, error: new Error('Domain not found')}
|
||||
});
|
||||
|
||||
mockUseDomain.mockReturnValue({
|
||||
domain: null,
|
||||
form,
|
||||
fetchDomain: jest.fn(),
|
||||
});
|
||||
|
||||
render(<DomainEditPage />);
|
||||
|
||||
// Should show loading screen when not ready
|
||||
expect(screen.getByText(/loading domain/i)).toBeInTheDocument();
|
||||
|
||||
// Form should not be rendered
|
||||
expect(screen.queryByTestId('collection-edit-form')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows form when ready even if there was a submission error', () => {
|
||||
// Form is ready (domain loaded) but submission may have failed
|
||||
const mockDomain = createMockDomain({
|
||||
domain: 'example.com',
|
||||
});
|
||||
|
||||
const form = createTestForm(mockDomain, {
|
||||
overrides: {ready: true, loading: false, error: new Error('Update failed')}
|
||||
});
|
||||
|
||||
mockUseDomain.mockReturnValue({
|
||||
domain: mockDomain,
|
||||
form,
|
||||
fetchDomain: jest.fn(),
|
||||
});
|
||||
|
||||
render(<DomainEditPage />);
|
||||
|
||||
// Should show domain name (form is rendered)
|
||||
// Multiple occurrences due to Fresnel rendering for mobile and tablet+
|
||||
expect(screen.getAllByText(/example\.com/i).length).toBeGreaterThan(0);
|
||||
|
||||
// Should NOT show the initial loading screen
|
||||
expect(screen.queryByText(/loading domain/i)).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
describe('Page Title', () => {
|
||||
it('sets page title with domain name', () => {
|
||||
const {useTitle} = require('./Common');
|
||||
const mockDomain = createMockDomain({
|
||||
domain: 'example.com',
|
||||
});
|
||||
|
||||
const form = createTestForm(mockDomain, {
|
||||
overrides: {ready: true, loading: false}
|
||||
});
|
||||
|
||||
mockUseDomain.mockReturnValue({
|
||||
domain: mockDomain,
|
||||
form,
|
||||
fetchDomain: jest.fn(),
|
||||
});
|
||||
|
||||
render(<DomainEditPage />);
|
||||
|
||||
// useTitle should be called with domain name
|
||||
expect(useTitle).toHaveBeenCalledWith('Edit Domain: example.com');
|
||||
});
|
||||
|
||||
it('sets page title with placeholder while loading', () => {
|
||||
const {useTitle} = require('./Common');
|
||||
|
||||
const form = createTestForm({}, {
|
||||
overrides: {ready: false, loading: false}
|
||||
});
|
||||
|
||||
mockUseDomain.mockReturnValue({
|
||||
domain: null,
|
||||
form,
|
||||
fetchDomain: jest.fn(),
|
||||
});
|
||||
|
||||
render(<DomainEditPage />);
|
||||
|
||||
// useTitle should be called with placeholder
|
||||
expect(useTitle).toHaveBeenCalledWith('Edit Domain: ...');
|
||||
});
|
||||
});
|
||||
|
||||
describe('Theme Integration', () => {
|
||||
it('passes theme context to CollectionEditForm in dark mode', () => {
|
||||
const mockDomain = createMockDomain({
|
||||
domain: 'example.com',
|
||||
});
|
||||
|
||||
const form = createTestForm(mockDomain, {
|
||||
overrides: {ready: true, loading: false}
|
||||
});
|
||||
|
||||
mockUseDomain.mockReturnValue({
|
||||
domain: mockDomain,
|
||||
form,
|
||||
fetchDomain: jest.fn(),
|
||||
});
|
||||
|
||||
// Render in dark mode
|
||||
renderInDarkMode(<DomainEditPage />);
|
||||
|
||||
// CollectionEditForm should be rendered
|
||||
expect(screen.getByTestId('collection-edit-form')).toBeInTheDocument();
|
||||
|
||||
// The title should include the domain name
|
||||
expect(screen.getAllByText(/example\.com/i).length).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
it('renders properly in light mode', () => {
|
||||
const mockDomain = createMockDomain({
|
||||
domain: 'test.com',
|
||||
});
|
||||
|
||||
const form = createTestForm(mockDomain, {
|
||||
overrides: {ready: true, loading: false}
|
||||
});
|
||||
|
||||
mockUseDomain.mockReturnValue({
|
||||
domain: mockDomain,
|
||||
form,
|
||||
fetchDomain: jest.fn(),
|
||||
});
|
||||
|
||||
// Default render (light mode)
|
||||
render(<DomainEditPage />);
|
||||
|
||||
// CollectionEditForm should be rendered
|
||||
expect(screen.getByTestId('collection-edit-form')).toBeInTheDocument();
|
||||
|
||||
// The title should include the domain name
|
||||
expect(screen.getAllByText(/test\.com/i).length).toBeGreaterThan(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('Tag Modal and Directory Suggestions', () => {
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks();
|
||||
mockGetCollectionTagInfo.mockClear();
|
||||
});
|
||||
|
||||
it('suggests directory when tag is selected', async () => {
|
||||
const mockDomain = createMockDomain({
|
||||
domain: 'example.com',
|
||||
id: 1,
|
||||
});
|
||||
|
||||
const form = createTestForm(mockDomain, {
|
||||
overrides: {ready: true, loading: false}
|
||||
});
|
||||
|
||||
mockUseDomain.mockReturnValue({
|
||||
domain: mockDomain,
|
||||
form,
|
||||
fetchDomain: jest.fn(),
|
||||
});
|
||||
|
||||
// Mock successful tag info response
|
||||
mockGetCollectionTagInfo.mockResolvedValue({
|
||||
suggested_directory: 'archive/WROL/example.com',
|
||||
conflict: false,
|
||||
conflict_message: null,
|
||||
});
|
||||
|
||||
render(<DomainEditPage />);
|
||||
|
||||
// Click the Tag button to open modal
|
||||
const tagButton = screen.getByText('Tag');
|
||||
await userEvent.click(tagButton);
|
||||
|
||||
// Wait for modal to open
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText(/Modify Tag|Add Tag/i)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
// Simulate selecting a tag (this would normally be done by TagsSelector)
|
||||
// Since TagsSelector is a real component, we need to wait for the API call
|
||||
// We'll verify the API was called when a tag would be selected
|
||||
// This test validates the structure is in place
|
||||
});
|
||||
|
||||
it('displays conflict warning in modal when directory conflict exists', async () => {
|
||||
const mockDomain = createMockDomain({
|
||||
domain: 'example.com',
|
||||
id: 1,
|
||||
});
|
||||
|
||||
const form = createTestForm(mockDomain, {
|
||||
overrides: {ready: true, loading: false}
|
||||
});
|
||||
|
||||
mockUseDomain.mockReturnValue({
|
||||
domain: mockDomain,
|
||||
form,
|
||||
fetchDomain: jest.fn(),
|
||||
});
|
||||
|
||||
// Mock tag info response with conflict
|
||||
mockGetCollectionTagInfo.mockResolvedValue({
|
||||
suggested_directory: 'archive/WROL/example.com',
|
||||
conflict: true,
|
||||
conflict_message: "A domain collection 'other.com' already uses this directory. Choose a different tag or directory.",
|
||||
});
|
||||
|
||||
render(<DomainEditPage />);
|
||||
|
||||
// Open the modal
|
||||
const tagButton = screen.getByText('Tag');
|
||||
await userEvent.click(tagButton);
|
||||
|
||||
// The modal should be present
|
||||
await waitFor(() => {
|
||||
expect(screen.getByTestId('collection-tag-modal')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
// Verify the modal structure includes the necessary inputs
|
||||
expect(screen.getByTestId('directory-input')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('clears conflict message when tag is changed', async () => {
|
||||
const mockDomain = createMockDomain({
|
||||
domain: 'example.com',
|
||||
id: 1,
|
||||
});
|
||||
|
||||
const form = createTestForm(mockDomain, {
|
||||
overrides: {ready: true, loading: false}
|
||||
});
|
||||
|
||||
mockUseDomain.mockReturnValue({
|
||||
domain: mockDomain,
|
||||
form,
|
||||
fetchDomain: jest.fn(),
|
||||
});
|
||||
|
||||
render(<DomainEditPage />);
|
||||
|
||||
// Open modal
|
||||
const tagButton = screen.getByText('Tag');
|
||||
await userEvent.click(tagButton);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText(/Modify Tag|Add Tag/i)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
// Modal should be open and ready for tag selection
|
||||
// The actual tag selection and conflict clearing would be tested in integration tests
|
||||
// This validates the structure is present
|
||||
});
|
||||
|
||||
it('populates directory input with suggested directory', async () => {
|
||||
const mockDomain = createMockDomain({
|
||||
domain: 'example.com',
|
||||
id: 1,
|
||||
directory: 'archive/example.com',
|
||||
});
|
||||
|
||||
const form = createTestForm(mockDomain, {
|
||||
overrides: {ready: true, loading: false}
|
||||
});
|
||||
|
||||
mockUseDomain.mockReturnValue({
|
||||
domain: mockDomain,
|
||||
form,
|
||||
fetchDomain: jest.fn(),
|
||||
});
|
||||
|
||||
mockGetCollectionTagInfo.mockResolvedValue({
|
||||
suggested_directory: 'archive/WROL/example.com',
|
||||
conflict: false,
|
||||
conflict_message: null,
|
||||
});
|
||||
|
||||
render(<DomainEditPage />);
|
||||
|
||||
// Open modal
|
||||
const tagButton = screen.getByText('Tag');
|
||||
await userEvent.click(tagButton);
|
||||
|
||||
// Wait for modal to open
|
||||
await waitFor(() => {
|
||||
expect(screen.getByTestId('collection-tag-modal')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
// Verify directory input field exists with original directory value
|
||||
const directoryInput = screen.getByTestId('directory-input');
|
||||
expect(directoryInput).toBeInTheDocument();
|
||||
expect(directoryInput).toHaveValue('archive/example.com');
|
||||
});
|
||||
});
|
||||
});
|
||||
345
app/src/components/DomainTagging.test.js
Normal file
345
app/src/components/DomainTagging.test.js
Normal file
|
|
@ -0,0 +1,345 @@
|
|||
import React from 'react';
|
||||
import {render, screen, createTestForm} from '../test-utils';
|
||||
import {CollectionEditForm} from './collections/CollectionEditForm';
|
||||
import {DomainsPage} from './Archive';
|
||||
import {createMockDomain, createMockMetadata, createMockDomains} from '../test-utils';
|
||||
|
||||
// Mock the TagsSelector component and TagsContext
|
||||
jest.mock('../Tags', () => ({
|
||||
TagsSelector: ({selectedTagNames, onChange, disabled}) => (
|
||||
<div data-testid="tags-selector" data-disabled={disabled}>
|
||||
<input
|
||||
data-testid="tags-input"
|
||||
value={selectedTagNames?.join(',') || ''}
|
||||
onChange={(e) => onChange(e.target.value ? [e.target.value] : [])}
|
||||
disabled={disabled}
|
||||
/>
|
||||
</div>
|
||||
),
|
||||
TagsContext: {
|
||||
_currentValue: {
|
||||
SingleTag: ({name}) => <span data-testid="applied-tag">{name}</span>
|
||||
}
|
||||
},
|
||||
}));
|
||||
|
||||
// Mock the DirectorySearch and DestinationForm components
|
||||
jest.mock('./Common', () => ({
|
||||
...jest.requireActual('./Common'),
|
||||
DirectorySearch: ({value, onSelect, placeholder}) => (
|
||||
<input
|
||||
data-testid="directory-search"
|
||||
value={value || ''}
|
||||
onChange={(e) => onSelect(e.target.value)}
|
||||
placeholder={placeholder}
|
||||
/>
|
||||
),
|
||||
SearchInput: ({placeholder, searchStr, onChange, disabled}) => (
|
||||
<input
|
||||
data-testid="search-input"
|
||||
placeholder={placeholder}
|
||||
value={searchStr || ''}
|
||||
onChange={(e) => onChange(e.target.value)}
|
||||
disabled={disabled}
|
||||
/>
|
||||
),
|
||||
ErrorMessage: ({children}) => <div data-testid="error-message">{children}</div>,
|
||||
useTitle: jest.fn(),
|
||||
}));
|
||||
|
||||
// Mock DestinationForm (used for directory field)
|
||||
jest.mock('./Download', () => ({
|
||||
DestinationForm: ({form, label, name}) => (
|
||||
<div data-testid="directory-search">
|
||||
<label>{label}</label>
|
||||
<input
|
||||
value={form.formData[name] || ''}
|
||||
onChange={(e) => form.setValue(name, e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
),
|
||||
}));
|
||||
|
||||
// Mock hooks for DomainsPage tests
|
||||
const mockUseDomains = jest.fn();
|
||||
const mockUseOneQuery = jest.fn(() => ['', jest.fn()]);
|
||||
|
||||
jest.mock('../hooks/customHooks', () => ({
|
||||
...jest.requireActual('../hooks/customHooks'),
|
||||
useDomains: (...args) => mockUseDomains(...args),
|
||||
useOneQuery: (...args) => mockUseOneQuery(...args),
|
||||
}));
|
||||
|
||||
// Mock CollectionTable for DomainsPage tests
|
||||
jest.mock('./collections/CollectionTable', () => ({
|
||||
CollectionTable: ({collections}) => (
|
||||
<div data-testid="collection-table">
|
||||
<table>
|
||||
<tbody>
|
||||
{collections?.map((domain) => (
|
||||
<tr key={domain.id} data-testid={`domain-row-${domain.id}`}>
|
||||
<td data-testid={`domain-name-${domain.id}`}>{domain.domain}</td>
|
||||
<td data-testid={`domain-tag-${domain.id}`}>
|
||||
{domain.tag_name || 'No tag'}
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
),
|
||||
}));
|
||||
|
||||
describe('Domain Tagging Logic', () => {
|
||||
const mockMetadata = createMockMetadata();
|
||||
|
||||
describe('Tag Field Dependency on Directory', () => {
|
||||
it('prevents tagging domain without directory', () => {
|
||||
const domainWithoutDirectory = createMockDomain({
|
||||
directory: '',
|
||||
tag_name: null,
|
||||
can_be_tagged: false
|
||||
});
|
||||
|
||||
const form = createTestForm(domainWithoutDirectory);
|
||||
|
||||
render(
|
||||
<CollectionEditForm
|
||||
form={form}
|
||||
metadata={mockMetadata}
|
||||
/>
|
||||
);
|
||||
|
||||
// Should show dependency warning
|
||||
expect(screen.getByText(/set a directory to enable tagging/i)).toBeInTheDocument();
|
||||
|
||||
// Tag selector should be disabled
|
||||
const tagSelector = screen.getByTestId('tags-selector');
|
||||
expect(tagSelector).toHaveAttribute('data-disabled', 'true');
|
||||
|
||||
const tagInput = screen.getByTestId('tags-input');
|
||||
expect(tagInput).toBeDisabled();
|
||||
});
|
||||
|
||||
it('enables tagging when directory is set', () => {
|
||||
const domainWithDirectory = createMockDomain({
|
||||
directory: 'archive/example.com',
|
||||
tag_name: null,
|
||||
can_be_tagged: true
|
||||
});
|
||||
|
||||
const form = createTestForm(domainWithDirectory);
|
||||
|
||||
render(
|
||||
<CollectionEditForm
|
||||
form={form}
|
||||
metadata={mockMetadata}
|
||||
/>
|
||||
);
|
||||
|
||||
// Dependency warning should not be shown
|
||||
expect(screen.queryByText(/set a directory to enable tagging/i)).not.toBeInTheDocument();
|
||||
|
||||
// Tag selector should be enabled
|
||||
const tagSelector = screen.getByTestId('tags-selector');
|
||||
expect(tagSelector).toHaveAttribute('data-disabled', 'false');
|
||||
|
||||
const tagInput = screen.getByTestId('tags-input');
|
||||
expect(tagInput).not.toBeDisabled();
|
||||
});
|
||||
|
||||
it('shows warning when directory is set (enabling tagging)', () => {
|
||||
const domainWithDirectory = createMockDomain({
|
||||
directory: 'archive/example.com',
|
||||
tag_name: null,
|
||||
can_be_tagged: true
|
||||
});
|
||||
|
||||
const form = createTestForm(domainWithDirectory);
|
||||
|
||||
render(
|
||||
<CollectionEditForm
|
||||
form={form}
|
||||
metadata={mockMetadata}
|
||||
/>
|
||||
);
|
||||
|
||||
// Tag selector should be available (not disabled)
|
||||
const tagSelector = screen.getByTestId('tags-selector');
|
||||
expect(tagSelector).toHaveAttribute('data-disabled', 'false');
|
||||
|
||||
// Dependency message should not appear
|
||||
expect(screen.queryByText(/set a directory to enable tagging/i)).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
describe('Tag Display in Domains List', () => {
|
||||
const {useTitle} = require('./Common');
|
||||
|
||||
beforeEach(() => {
|
||||
// Reset mocks
|
||||
mockUseDomains.mockReset();
|
||||
mockUseOneQuery.mockReset();
|
||||
useTitle.mockReset();
|
||||
|
||||
// Re-setup default mocks
|
||||
useTitle.mockImplementation(() => {});
|
||||
mockUseOneQuery.mockReturnValue(['', jest.fn()]);
|
||||
});
|
||||
|
||||
it('displays tag in domains list after tagging', () => {
|
||||
const mockDomains = [
|
||||
createMockDomain({
|
||||
id: 1,
|
||||
domain: 'example.com',
|
||||
tag_name: 'News', // Tagged domain
|
||||
directory: 'archive/example.com',
|
||||
can_be_tagged: true
|
||||
}),
|
||||
createMockDomain({
|
||||
id: 2,
|
||||
domain: 'test.org',
|
||||
tag_name: null, // Untagged domain
|
||||
directory: '',
|
||||
can_be_tagged: false
|
||||
}),
|
||||
];
|
||||
|
||||
mockUseDomains.mockReturnValue([mockDomains, 2, mockMetadata]);
|
||||
|
||||
render(<DomainsPage />);
|
||||
|
||||
// Tagged domain should display its tag
|
||||
expect(screen.getByTestId('domain-tag-1')).toHaveTextContent('News');
|
||||
|
||||
// Untagged domain should show "No tag"
|
||||
expect(screen.getByTestId('domain-tag-2')).toHaveTextContent('No tag');
|
||||
});
|
||||
|
||||
it('displays multiple tagged domains correctly', () => {
|
||||
const mockDomains = [
|
||||
createMockDomain({
|
||||
id: 1,
|
||||
domain: 'news.com',
|
||||
tag_name: 'News',
|
||||
directory: 'archive/news.com',
|
||||
can_be_tagged: true
|
||||
}),
|
||||
createMockDomain({
|
||||
id: 2,
|
||||
domain: 'tech.com',
|
||||
tag_name: 'Tech',
|
||||
directory: 'archive/tech.com',
|
||||
can_be_tagged: true
|
||||
}),
|
||||
createMockDomain({
|
||||
id: 3,
|
||||
domain: 'science.com',
|
||||
tag_name: 'Science',
|
||||
directory: 'archive/science.com',
|
||||
can_be_tagged: true
|
||||
}),
|
||||
];
|
||||
|
||||
mockUseDomains.mockReturnValue([mockDomains, 3, mockMetadata]);
|
||||
|
||||
render(<DomainsPage />);
|
||||
|
||||
// All domains should display their respective tags
|
||||
expect(screen.getByTestId('domain-tag-1')).toHaveTextContent('News');
|
||||
expect(screen.getByTestId('domain-tag-2')).toHaveTextContent('Tech');
|
||||
expect(screen.getByTestId('domain-tag-3')).toHaveTextContent('Science');
|
||||
});
|
||||
});
|
||||
|
||||
describe('Tag Warning Messages', () => {
|
||||
it('shows "tagging will move files" warning when tag is set', () => {
|
||||
const domainWithTag = createMockDomain({
|
||||
directory: 'archive/example.com',
|
||||
tag_name: 'News',
|
||||
can_be_tagged: true
|
||||
});
|
||||
|
||||
const form = createTestForm(domainWithTag);
|
||||
|
||||
render(
|
||||
<CollectionEditForm
|
||||
form={form}
|
||||
metadata={mockMetadata}
|
||||
/>
|
||||
);
|
||||
|
||||
// Should show move warning when tag is present
|
||||
expect(screen.getByText(/tagging will move files/i)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('does not show move warning when no tag is set', () => {
|
||||
const domainWithoutTag = createMockDomain({
|
||||
directory: 'archive/example.com',
|
||||
tag_name: null,
|
||||
can_be_tagged: true
|
||||
});
|
||||
|
||||
const form = createTestForm(domainWithoutTag);
|
||||
|
||||
render(
|
||||
<CollectionEditForm
|
||||
form={form}
|
||||
metadata={mockMetadata}
|
||||
/>
|
||||
);
|
||||
|
||||
// Should not show move warning when tag is absent
|
||||
expect(screen.queryByText(/tagging will move files/i)).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
describe('Tag Clearing Submission Bug', () => {
|
||||
it('should send empty string (not null) when clearing tag', async () => {
|
||||
// Create a domain with a tag
|
||||
const domainWithTag = createMockDomain({
|
||||
id: 1,
|
||||
domain: 'example.com',
|
||||
directory: 'archive/example.com',
|
||||
tag_name: 'News',
|
||||
can_be_tagged: true
|
||||
});
|
||||
|
||||
// Create form with the domain data
|
||||
const form = createTestForm(domainWithTag);
|
||||
|
||||
// Simulate clearing the tag
|
||||
form.setValue('tag_name', null);
|
||||
|
||||
// Verify form has null
|
||||
expect(form.formData.tag_name).toBe(null);
|
||||
|
||||
// Mock updateDomain to track what it's called with
|
||||
const mockUpdateDomain = jest.fn().mockResolvedValue({ok: true});
|
||||
|
||||
// Mock onSubmit to call updateDomain like useDomain does (with fix)
|
||||
form.onSubmit = jest.fn(async () => {
|
||||
const body = {
|
||||
directory: form.formData.directory,
|
||||
description: form.formData.description,
|
||||
// FIX: Convert null to empty string - backend expects "" to clear tag
|
||||
tag_name: form.formData.tag_name === null ? '' : form.formData.tag_name,
|
||||
};
|
||||
return await mockUpdateDomain(1, body);
|
||||
});
|
||||
|
||||
// Submit the form
|
||||
await form.onSubmit();
|
||||
|
||||
// Verify updateDomain was called
|
||||
expect(mockUpdateDomain).toHaveBeenCalledTimes(1);
|
||||
|
||||
// Verify tag_name is correctly converted from null to "" for the API
|
||||
expect(mockUpdateDomain).toHaveBeenCalledWith(1, {
|
||||
directory: 'archive/example.com',
|
||||
description: '',
|
||||
tag_name: '', // Empty string clears the tag (null is converted)
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
236
app/src/components/DomainsPage.test.js
Normal file
236
app/src/components/DomainsPage.test.js
Normal file
|
|
@ -0,0 +1,236 @@
|
|||
import React from 'react';
|
||||
import {render, screen, waitFor} from '../test-utils';
|
||||
import {DomainsPage} from './Archive';
|
||||
import {createMockDomains, createMockMetadata} from '../test-utils';
|
||||
|
||||
// Mock the custom hooks
|
||||
jest.mock('../hooks/customHooks', () => ({
|
||||
...jest.requireActual('../hooks/customHooks'),
|
||||
useDomains: jest.fn(),
|
||||
useOneQuery: jest.fn(),
|
||||
}));
|
||||
|
||||
// Mock CollectionTable component
|
||||
jest.mock('./collections/CollectionTable', () => ({
|
||||
CollectionTable: ({collections, metadata, searchStr}) => (
|
||||
<div data-testid="collection-table">
|
||||
<div data-testid="collection-count">{collections?.length || 0}</div>
|
||||
<div data-testid="search-filter">{searchStr}</div>
|
||||
{collections?.map((domain) => (
|
||||
<div key={domain.id} data-testid={`domain-${domain.id}`}>
|
||||
<span data-testid={`domain-name-${domain.id}`}>{domain.domain}</span>
|
||||
<button className="ui mini primary button" data-testid={`edit-button-${domain.id}`}>
|
||||
Edit
|
||||
</button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
),
|
||||
}));
|
||||
|
||||
// Mock SearchInput component and useTitle
|
||||
jest.mock('./Common', () => ({
|
||||
...jest.requireActual('./Common'),
|
||||
SearchInput: ({placeholder, searchStr, onChange, disabled}) => (
|
||||
<input
|
||||
data-testid="search-input"
|
||||
placeholder={placeholder}
|
||||
value={searchStr || ''}
|
||||
onChange={(e) => onChange(e.target.value)}
|
||||
disabled={disabled}
|
||||
/>
|
||||
),
|
||||
ErrorMessage: ({children}) => <div data-testid="error-message">{children}</div>,
|
||||
useTitle: jest.fn(),
|
||||
}));
|
||||
|
||||
describe('DomainsPage', () => {
|
||||
const {useDomains, useOneQuery} = require('../hooks/customHooks');
|
||||
const {useTitle} = require('./Common');
|
||||
const mockMetadata = createMockMetadata();
|
||||
|
||||
beforeEach(() => {
|
||||
// Reset mocks before each test
|
||||
jest.clearAllMocks();
|
||||
|
||||
// Default mock implementations
|
||||
useTitle.mockImplementation(() => {});
|
||||
useOneQuery.mockReturnValue(['', jest.fn()]);
|
||||
});
|
||||
|
||||
describe('Page Rendering', () => {
|
||||
it('displays domains page without errors', () => {
|
||||
const mockDomains = createMockDomains(3);
|
||||
useDomains.mockReturnValue([mockDomains, 3, mockMetadata]);
|
||||
|
||||
render(<DomainsPage />);
|
||||
|
||||
// Page should render without crashing
|
||||
expect(screen.getByTestId('search-input')).toBeInTheDocument();
|
||||
expect(screen.getByTestId('collection-table')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('renders CollectionTable component', () => {
|
||||
const mockDomains = createMockDomains(2);
|
||||
useDomains.mockReturnValue([mockDomains, 2, mockMetadata]);
|
||||
|
||||
render(<DomainsPage />);
|
||||
|
||||
expect(screen.getByTestId('collection-table')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows search input', () => {
|
||||
const mockDomains = createMockDomains(1);
|
||||
useDomains.mockReturnValue([mockDomains, 1, mockMetadata]);
|
||||
|
||||
render(<DomainsPage />);
|
||||
|
||||
const searchInput = screen.getByTestId('search-input');
|
||||
expect(searchInput).toBeInTheDocument();
|
||||
expect(searchInput).toHaveAttribute('placeholder', 'Domain filter...');
|
||||
});
|
||||
});
|
||||
|
||||
describe('Domain Display', () => {
|
||||
it('shows all domains from API', () => {
|
||||
const mockDomains = createMockDomains(5);
|
||||
useDomains.mockReturnValue([mockDomains, 5, mockMetadata]);
|
||||
|
||||
render(<DomainsPage />);
|
||||
|
||||
// Should render all 5 domains
|
||||
expect(screen.getByTestId('collection-count')).toHaveTextContent('5');
|
||||
|
||||
mockDomains.forEach((domain) => {
|
||||
expect(screen.getByTestId(`domain-${domain.id}`)).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
it('displays domain names', () => {
|
||||
const mockDomains = [
|
||||
{id: 1, domain: 'example1.com', archive_count: 10, size: 1000},
|
||||
{id: 2, domain: 'example2.com', archive_count: 20, size: 2000},
|
||||
{id: 3, domain: 'example3.com', archive_count: 30, size: 3000},
|
||||
];
|
||||
useDomains.mockReturnValue([mockDomains, 3, mockMetadata]);
|
||||
|
||||
render(<DomainsPage />);
|
||||
|
||||
expect(screen.getByTestId('domain-name-1')).toHaveTextContent('example1.com');
|
||||
expect(screen.getByTestId('domain-name-2')).toHaveTextContent('example2.com');
|
||||
expect(screen.getByTestId('domain-name-3')).toHaveTextContent('example3.com');
|
||||
});
|
||||
|
||||
it('displays Edit buttons in Manage column', () => {
|
||||
const mockDomains = createMockDomains(3);
|
||||
useDomains.mockReturnValue([mockDomains, 3, mockMetadata]);
|
||||
|
||||
render(<DomainsPage />);
|
||||
|
||||
// Each domain should have an Edit button
|
||||
mockDomains.forEach((domain) => {
|
||||
expect(screen.getByTestId(`edit-button-${domain.id}`)).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
it('Edit button has correct styling', () => {
|
||||
const mockDomains = createMockDomains(1);
|
||||
useDomains.mockReturnValue([mockDomains, 1, mockMetadata]);
|
||||
|
||||
render(<DomainsPage />);
|
||||
|
||||
const editButton = screen.getByTestId('edit-button-1');
|
||||
expect(editButton).toHaveClass('ui');
|
||||
expect(editButton).toHaveClass('mini');
|
||||
expect(editButton).toHaveClass('primary');
|
||||
expect(editButton).toHaveClass('button');
|
||||
});
|
||||
});
|
||||
|
||||
describe('Empty and Error States', () => {
|
||||
it('shows "No items yet" message when no domains', () => {
|
||||
// Empty array indicates no domains
|
||||
useDomains.mockReturnValue([[], 0, mockMetadata]);
|
||||
|
||||
render(<DomainsPage />);
|
||||
|
||||
// Should show empty state message
|
||||
expect(screen.getByText(/no domains yet/i)).toBeInTheDocument();
|
||||
expect(screen.getByText(/archive some webpages/i)).toBeInTheDocument();
|
||||
|
||||
// Should not show table
|
||||
expect(screen.queryByTestId('collection-table')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows error message when fetch fails', () => {
|
||||
// undefined indicates error state
|
||||
useDomains.mockReturnValue([undefined, 0, mockMetadata]);
|
||||
|
||||
render(<DomainsPage />);
|
||||
|
||||
// Should show error message
|
||||
expect(screen.getByTestId('error-message')).toBeInTheDocument();
|
||||
expect(screen.getByText(/could not fetch domains/i)).toBeInTheDocument();
|
||||
|
||||
// Should not show table
|
||||
expect(screen.queryByTestId('collection-table')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('does not show "New Domain" button', () => {
|
||||
const mockDomains = createMockDomains(2);
|
||||
useDomains.mockReturnValue([mockDomains, 2, mockMetadata]);
|
||||
|
||||
render(<DomainsPage />);
|
||||
|
||||
// Domains are auto-created, so there should be no "New" button
|
||||
expect(screen.queryByRole('button', {name: /new/i})).not.toBeInTheDocument();
|
||||
expect(screen.queryByRole('button', {name: /create/i})).not.toBeInTheDocument();
|
||||
expect(screen.queryByRole('button', {name: /add/i})).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
describe('Search Integration', () => {
|
||||
it('disables search when no domains', () => {
|
||||
useDomains.mockReturnValue([[], 0, mockMetadata]);
|
||||
|
||||
render(<DomainsPage />);
|
||||
|
||||
const searchInput = screen.getByTestId('search-input');
|
||||
expect(searchInput).toBeDisabled();
|
||||
});
|
||||
|
||||
it('enables search when domains exist', () => {
|
||||
const mockDomains = createMockDomains(3);
|
||||
useDomains.mockReturnValue([mockDomains, 3, mockMetadata]);
|
||||
|
||||
render(<DomainsPage />);
|
||||
|
||||
const searchInput = screen.getByTestId('search-input');
|
||||
expect(searchInput).not.toBeDisabled();
|
||||
});
|
||||
|
||||
it('passes search string to CollectionTable', () => {
|
||||
const mockDomains = createMockDomains(2);
|
||||
useDomains.mockReturnValue([mockDomains, 2, mockMetadata]);
|
||||
|
||||
const mockSetSearchStr = jest.fn();
|
||||
useOneQuery.mockReturnValue(['example', mockSetSearchStr]);
|
||||
|
||||
render(<DomainsPage />);
|
||||
|
||||
// Search string should be passed to table
|
||||
expect(screen.getByTestId('search-filter')).toHaveTextContent('example');
|
||||
});
|
||||
});
|
||||
|
||||
describe('Page Title', () => {
|
||||
it('sets page title correctly', () => {
|
||||
const mockDomains = createMockDomains(1);
|
||||
useDomains.mockReturnValue([mockDomains, 1, mockMetadata]);
|
||||
|
||||
render(<DomainsPage />);
|
||||
|
||||
expect(useTitle).toHaveBeenCalledWith('Archive Domains');
|
||||
});
|
||||
});
|
||||
});
|
||||
253
app/src/components/Download.test.js
Normal file
253
app/src/components/Download.test.js
Normal file
|
|
@ -0,0 +1,253 @@
|
|||
import React from 'react';
|
||||
import {render, screen, waitFor} from '@testing-library/react';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import {DestinationForm} from './Download';
|
||||
import {createTestForm} from '../test-utils';
|
||||
|
||||
// Mock DirectorySearch component - simplified to avoid useState/useEffect warnings
|
||||
jest.mock('./Common', () => {
|
||||
const React = require('react');
|
||||
return {
|
||||
...jest.requireActual('./Common'),
|
||||
DirectorySearch: ({value, onSelect, disabled, required, id}) => (
|
||||
<div data-testid="directory-search-mock">
|
||||
<input
|
||||
data-testid="directory-search-input"
|
||||
defaultValue={value || ''}
|
||||
onChange={(e) => onSelect(e.target.value)}
|
||||
disabled={disabled}
|
||||
required={required}
|
||||
id={id}
|
||||
/>
|
||||
</div>
|
||||
),
|
||||
RequiredAsterisk: () => React.createElement('span', null, '*'),
|
||||
InfoPopup: ({content}) => React.createElement('span', {'data-testid': 'info-popup'}, content),
|
||||
};
|
||||
});
|
||||
|
||||
describe('DestinationForm', () => {
|
||||
describe('Form Integration', () => {
|
||||
it('renders DirectorySearch with form value', () => {
|
||||
const form = createTestForm(
|
||||
{destination: 'videos/test'},
|
||||
{overrides: {ready: true, loading: false}}
|
||||
);
|
||||
|
||||
render(<DestinationForm form={form} />);
|
||||
|
||||
const input = screen.getByTestId('directory-search-input');
|
||||
expect(input).toHaveValue('videos/test');
|
||||
});
|
||||
|
||||
it('calls form onChange when directory is selected', async () => {
|
||||
const form = createTestForm(
|
||||
{destination: ''},
|
||||
{overrides: {ready: true, loading: false}}
|
||||
);
|
||||
|
||||
render(<DestinationForm form={form} />);
|
||||
|
||||
const input = screen.getByTestId('directory-search-input');
|
||||
|
||||
// Type a new directory
|
||||
await userEvent.type(input, 'archive/new');
|
||||
|
||||
// Form data should be updated
|
||||
await waitFor(() => {
|
||||
expect(form.formData.destination).toBe('archive/new');
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
it('displays required indicator when required=true', () => {
|
||||
const form = createTestForm(
|
||||
{destination: ''},
|
||||
{overrides: {ready: true, loading: false}}
|
||||
);
|
||||
|
||||
render(<DestinationForm form={form} required />);
|
||||
|
||||
const input = screen.getByTestId('directory-search-input');
|
||||
expect(input).toHaveAttribute('required');
|
||||
});
|
||||
});
|
||||
|
||||
describe('Props Handling', () => {
|
||||
it('uses custom label when provided', () => {
|
||||
const form = createTestForm(
|
||||
{destination: ''},
|
||||
{overrides: {ready: true, loading: false}}
|
||||
);
|
||||
|
||||
render(<DestinationForm form={form} label="Custom Folder" />);
|
||||
|
||||
expect(screen.getByText(/custom folder/i)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('uses default label when not provided', () => {
|
||||
const form = createTestForm(
|
||||
{destination: ''},
|
||||
{overrides: {ready: true, loading: false}}
|
||||
);
|
||||
|
||||
render(<DestinationForm form={form} />);
|
||||
|
||||
expect(screen.getByText(/destination/i)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('uses custom name/path when provided', () => {
|
||||
const form = createTestForm(
|
||||
{output_dir: 'videos/test'},
|
||||
{overrides: {ready: true, loading: false}}
|
||||
);
|
||||
|
||||
render(
|
||||
<DestinationForm
|
||||
form={form}
|
||||
name="output_dir"
|
||||
path="output_dir"
|
||||
/>
|
||||
);
|
||||
|
||||
const input = screen.getByTestId('directory-search-input');
|
||||
expect(input).toHaveValue('videos/test');
|
||||
});
|
||||
|
||||
it('shows info popup when infoContent provided', () => {
|
||||
const form = createTestForm(
|
||||
{destination: ''},
|
||||
{overrides: {ready: true, loading: false}}
|
||||
);
|
||||
|
||||
render(
|
||||
<DestinationForm
|
||||
form={form}
|
||||
infoContent="This is helpful information"
|
||||
/>
|
||||
);
|
||||
|
||||
expect(screen.getByText(/this is helpful information/i)).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
describe('useForm Integration', () => {
|
||||
it('gets correct props from form.getCustomProps', () => {
|
||||
const form = createTestForm(
|
||||
{destination: 'videos/initial'},
|
||||
{overrides: {ready: true, loading: false}}
|
||||
);
|
||||
|
||||
const getCustomPropsSpy = jest.spyOn(form, 'getCustomProps');
|
||||
|
||||
render(<DestinationForm form={form} required />);
|
||||
|
||||
expect(getCustomPropsSpy).toHaveBeenCalledWith({
|
||||
name: 'destination',
|
||||
path: 'destination',
|
||||
required: true
|
||||
});
|
||||
});
|
||||
|
||||
it('updates form data on selection', async () => {
|
||||
const form = createTestForm(
|
||||
{destination: ''},
|
||||
{overrides: {ready: true, loading: false}}
|
||||
);
|
||||
|
||||
render(<DestinationForm form={form} />);
|
||||
|
||||
const input = screen.getByTestId('directory-search-input');
|
||||
|
||||
// Select a directory
|
||||
await userEvent.type(input, 'videos/new-folder');
|
||||
|
||||
// Form should be updated
|
||||
await waitFor(() => {
|
||||
expect(form.formData.destination).toBe('videos/new-folder');
|
||||
});
|
||||
});
|
||||
|
||||
});
|
||||
|
||||
describe('Edge Cases', () => {
|
||||
|
||||
it('works with nested form paths', () => {
|
||||
const form = createTestForm(
|
||||
{config: {output: {destination: 'videos/nested'}}},
|
||||
{overrides: {ready: true, loading: false}}
|
||||
);
|
||||
|
||||
render(
|
||||
<DestinationForm
|
||||
form={form}
|
||||
path="config.output.destination"
|
||||
name="destination"
|
||||
/>
|
||||
);
|
||||
|
||||
const input = screen.getByTestId('directory-search-input');
|
||||
expect(input).toHaveValue('videos/nested');
|
||||
});
|
||||
|
||||
it('handles concurrent field updates', async () => {
|
||||
const form = createTestForm(
|
||||
{destination: '', title: ''},
|
||||
{overrides: {ready: true, loading: false}}
|
||||
);
|
||||
|
||||
render(<DestinationForm form={form} />);
|
||||
|
||||
const input = screen.getByTestId('directory-search-input');
|
||||
|
||||
// Simulate rapid updates
|
||||
await userEvent.type(input, 'videos/a');
|
||||
form.setValue('title', 'Test Title');
|
||||
await userEvent.type(input, 'bc');
|
||||
|
||||
// Destination should have full value
|
||||
await waitFor(() => {
|
||||
expect(form.formData.destination).toBe('videos/abc');
|
||||
});
|
||||
|
||||
// Title should also be set
|
||||
expect(form.formData.title).toBe('Test Title');
|
||||
});
|
||||
|
||||
it('handles empty string as initial value', () => {
|
||||
const form = createTestForm(
|
||||
{destination: ''},
|
||||
{overrides: {ready: true, loading: false}}
|
||||
);
|
||||
|
||||
render(<DestinationForm form={form} />);
|
||||
|
||||
const input = screen.getByTestId('directory-search-input');
|
||||
expect(input).toHaveValue('');
|
||||
});
|
||||
|
||||
it('handles null as initial value', () => {
|
||||
const form = createTestForm(
|
||||
{destination: null},
|
||||
{overrides: {ready: true, loading: false}}
|
||||
);
|
||||
|
||||
render(<DestinationForm form={form} />);
|
||||
|
||||
const input = screen.getByTestId('directory-search-input');
|
||||
expect(input).toHaveValue('');
|
||||
});
|
||||
|
||||
it('handles undefined as initial value', () => {
|
||||
const form = createTestForm(
|
||||
{},
|
||||
{overrides: {ready: true, loading: false}}
|
||||
);
|
||||
|
||||
render(<DestinationForm form={form} />);
|
||||
|
||||
const input = screen.getByTestId('directory-search-input');
|
||||
expect(input).toHaveValue('');
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
@ -186,9 +186,24 @@ export function NavBar() {
|
|||
/>
|
||||
}
|
||||
|
||||
// Upgrade available notification - only show on native (non-Docker) installs
|
||||
let upgradeIcon;
|
||||
if (status?.update_available && !status?.dockerized) {
|
||||
const commitsBehind = status.commits_behind || 0;
|
||||
const branch = status.git_branch || 'unknown';
|
||||
const icon = <Link to='/admin/settings'>
|
||||
<Icon name='arrow alternate circle up' size='large' color='green'/>
|
||||
</Link>;
|
||||
upgradeIcon = <Popup
|
||||
content={`Upgrade available: ${commitsBehind} commit(s) behind on ${branch}`}
|
||||
trigger={icon}
|
||||
/>;
|
||||
}
|
||||
|
||||
const icons = <React.Fragment>
|
||||
<NavIconWrapper>{apiDownIcon}</NavIconWrapper>
|
||||
<NavIconWrapper>{processingIcon}</NavIconWrapper>
|
||||
<NavIconWrapper>{upgradeIcon}</NavIconWrapper>
|
||||
<NavIconWrapper>{powerIcon}</NavIconWrapper>
|
||||
<NavIconWrapper>{warningIcon}</NavIconWrapper>
|
||||
<NavIconWrapper><ShareButton/></NavIconWrapper>
|
||||
|
|
|
|||
|
|
@ -1,6 +1,7 @@
|
|||
export const API_URI = process.env && process.env.REACT_APP_API_URI ? process.env.REACT_APP_API_URI : `https://${window.location.host}/api`;
|
||||
export const VIDEOS_API = `${API_URI}/videos`;
|
||||
export const ARCHIVES_API = `${API_URI}/archive`;
|
||||
export const COLLECTIONS_API = `${API_URI}/collections`;
|
||||
export const OTP_API = `${API_URI}/otp`;
|
||||
export const ZIM_API = `${API_URI}/zim`;
|
||||
export const DEFAULT_LIMIT = 20;
|
||||
|
|
|
|||
|
|
@ -1,5 +1,6 @@
|
|||
import React from "react";
|
||||
import {postRestart, postShutdown} from "../../api";
|
||||
import {ThemeContext} from "../../contexts/contexts";
|
||||
import {checkUpgrade, postRestart, postShutdown, triggerUpgrade} from "../../api";
|
||||
import {
|
||||
Button,
|
||||
Divider,
|
||||
|
|
@ -30,7 +31,7 @@ import QRCode from "react-qr-code";
|
|||
import {useConfigs, useDockerized} from "../../hooks/customHooks";
|
||||
import {toast} from "react-semantic-toasts-2";
|
||||
import Grid from "semantic-ui-react/dist/commonjs/collections/Grid";
|
||||
import {SettingsContext} from "../../contexts/contexts";
|
||||
import {SettingsContext, StatusContext} from "../../contexts/contexts";
|
||||
import {ConfigsTable} from "./Configs";
|
||||
import {semanticUIColorMap} from "../Vars";
|
||||
|
||||
|
|
@ -85,6 +86,89 @@ export function ShutdownButton() {
|
|||
</APIButton>
|
||||
}
|
||||
|
||||
function UpgradeSegment() {
|
||||
const {status, fetchStatus} = React.useContext(StatusContext);
|
||||
const dockerized = useDockerized();
|
||||
const [upgrading, setUpgrading] = React.useState(false);
|
||||
const [checking, setChecking] = React.useState(false);
|
||||
|
||||
const handleCheckUpgrade = async () => {
|
||||
setChecking(true);
|
||||
try {
|
||||
await checkUpgrade(true); // Force a fresh check
|
||||
toast({
|
||||
type: 'info',
|
||||
title: 'Update Check Complete',
|
||||
description: 'Checked for updates from git remote.',
|
||||
time: 3000,
|
||||
});
|
||||
} finally {
|
||||
setChecking(false);
|
||||
await fetchStatus();
|
||||
}
|
||||
};
|
||||
|
||||
const handleUpgrade = async () => {
|
||||
setUpgrading(true);
|
||||
try {
|
||||
const response = await triggerUpgrade();
|
||||
if (response.ok) {
|
||||
// Redirect to maintenance page
|
||||
window.location.href = '/maintenance.html';
|
||||
}
|
||||
} catch (e) {
|
||||
setUpgrading(false);
|
||||
}
|
||||
};
|
||||
|
||||
// Not available in Docker
|
||||
if (dockerized) {
|
||||
return <Segment>
|
||||
<Header as='h3'>System Upgrade</Header>
|
||||
<p>Upgrades are not available in Docker environments. Please upgrade your Docker images manually.</p>
|
||||
</Segment>;
|
||||
}
|
||||
|
||||
// No update available
|
||||
if (!status?.update_available) {
|
||||
return <Segment>
|
||||
<Header as='h3'>System Upgrade</Header>
|
||||
<p>Your WROLPi is up to date.</p>
|
||||
<p>Version: <strong>v{status?.version}</strong> on branch <strong>{status?.git_branch || 'unknown'}</strong></p>
|
||||
<APIButton
|
||||
color='blue'
|
||||
onClick={handleCheckUpgrade}
|
||||
disabled={checking}
|
||||
>
|
||||
{checking ? 'Checking...' : 'Check for Updates'}
|
||||
</APIButton>
|
||||
</Segment>;
|
||||
}
|
||||
|
||||
// Update available
|
||||
return <Segment>
|
||||
<Header as='h3'>
|
||||
<Icon name='arrow alternate circle up'/>
|
||||
Upgrade Available
|
||||
</Header>
|
||||
<p>Branch: <strong>{status?.git_branch}</strong></p>
|
||||
<p>Current commit: <strong>{status?.current_commit}</strong></p>
|
||||
<p>Latest commit: <strong>{status?.latest_commit}</strong></p>
|
||||
<p><strong>{status?.commits_behind}</strong> commit(s) behind</p>
|
||||
|
||||
<APIButton
|
||||
color='green'
|
||||
size='big'
|
||||
onClick={handleUpgrade}
|
||||
disabled={upgrading}
|
||||
confirmContent='This will upgrade WROLPi. The system will be temporarily unavailable during the upgrade. Are you sure?'
|
||||
confirmButton='Start Upgrade'
|
||||
>
|
||||
{upgrading ? 'Starting Upgrade...' : 'Upgrade Now'}
|
||||
</APIButton>
|
||||
</Segment>;
|
||||
}
|
||||
|
||||
export function RestartButton() {
|
||||
const dockerized = useDockerized();
|
||||
|
||||
|
|
@ -529,6 +613,8 @@ export function SettingsPage() {
|
|||
|
||||
{configsSegment}
|
||||
|
||||
<UpgradeSegment/>
|
||||
|
||||
<Segment>
|
||||
<Header as='h1'>Browser Settings</Header>
|
||||
<APIButton onClick={clearAll}>Show All Hints</APIButton>
|
||||
|
|
|
|||
152
app/src/components/collections/CollectionEditForm.js
Normal file
152
app/src/components/collections/CollectionEditForm.js
Normal file
|
|
@ -0,0 +1,152 @@
|
|||
import React from 'react';
|
||||
import {Button, Form, Grid, Message, TextArea} from 'semantic-ui-react';
|
||||
import {Header, Segment} from '../Theme';
|
||||
import {TagsSelector, TagsContext} from '../../Tags';
|
||||
import {WROLModeMessage} from '../Common';
|
||||
import {DestinationForm} from '../Download';
|
||||
import {InputForm} from '../../hooks/useForm';
|
||||
|
||||
/**
|
||||
* Reusable form component for editing collections (Domains, Channels, etc).
|
||||
*
|
||||
* @param {Object} form - Form object from useForm hook
|
||||
* @param {Object} metadata - Backend-provided metadata containing fields configuration
|
||||
* @param {Function} onCancel - Optional callback when cancel is clicked
|
||||
* @param {String} title - Page title to display in header
|
||||
* @param {String} wrolModeContent - Content to show in WROL mode message (optional)
|
||||
* @param {React.ReactNode} actionButtons - Optional additional action buttons to display in the button row
|
||||
* @param {String} appliedTagName - Optional tag name to display (similar to ChannelEditPage pattern)
|
||||
*/
|
||||
export function CollectionEditForm({
|
||||
form,
|
||||
metadata,
|
||||
onCancel,
|
||||
title,
|
||||
wrolModeContent,
|
||||
actionButtons,
|
||||
appliedTagName
|
||||
}) {
|
||||
const {SingleTag} = React.useContext(TagsContext);
|
||||
if (!metadata) {
|
||||
return <Message warning>
|
||||
<Message.Header>No metadata available</Message.Header>
|
||||
</Message>;
|
||||
}
|
||||
|
||||
const handleSubmit = (e) => {
|
||||
e.preventDefault();
|
||||
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;
|
||||
}
|
||||
};
|
||||
|
||||
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)}
|
||||
</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>
|
||||
</Segment>;
|
||||
}
|
||||
347
app/src/components/collections/CollectionEditForm.test.js
Normal file
347
app/src/components/collections/CollectionEditForm.test.js
Normal file
|
|
@ -0,0 +1,347 @@
|
|||
import React from 'react';
|
||||
import {render, renderInDarkMode, renderInLightMode, hasInvertedStyling, screen, waitFor, createTestForm} from '../../test-utils';
|
||||
import {CollectionEditForm} from './CollectionEditForm';
|
||||
import {createMockMetadata, createMockDomain} from '../../test-utils';
|
||||
|
||||
// Mock the TagsSelector component and TagsContext
|
||||
jest.mock('../../Tags', () => ({
|
||||
TagsSelector: ({selectedTagNames, onChange, disabled}) => (
|
||||
<div data-testid="tags-selector" data-disabled={disabled}>
|
||||
<input
|
||||
data-testid="tags-input"
|
||||
value={selectedTagNames?.join(',') || ''}
|
||||
onChange={(e) => onChange(e.target.value ? [e.target.value] : [])}
|
||||
disabled={disabled}
|
||||
/>
|
||||
</div>
|
||||
),
|
||||
TagsContext: {
|
||||
_currentValue: {
|
||||
SingleTag: ({name}) => <span data-testid="applied-tag">{name}</span>
|
||||
}
|
||||
},
|
||||
}));
|
||||
|
||||
// Mock Common components
|
||||
jest.mock('../Common', () => ({
|
||||
...jest.requireActual('../Common'),
|
||||
WROLModeMessage: () => <div data-testid="wrol-mode-message" />,
|
||||
}));
|
||||
|
||||
// Mock DestinationForm (used for directory field)
|
||||
jest.mock('../Download', () => ({
|
||||
DestinationForm: ({form, label, name}) => (
|
||||
<div data-testid="directory-search">
|
||||
<label>{label}</label>
|
||||
<input
|
||||
value={form.formData[name] || ''}
|
||||
onChange={(e) => form.setValue(name, e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
),
|
||||
}));
|
||||
|
||||
// Mock InputForm (used for text fields)
|
||||
jest.mock('../../hooks/useForm', () => ({
|
||||
...jest.requireActual('../../hooks/useForm'),
|
||||
InputForm: ({form, label, name}) => (
|
||||
<div data-testid={`input-${name}`}>
|
||||
<label>{label}</label>
|
||||
<input
|
||||
value={form.formData[name] || ''}
|
||||
onChange={(e) => form.setValue(name, e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
),
|
||||
}));
|
||||
|
||||
describe('CollectionEditForm', () => {
|
||||
const mockMetadata = createMockMetadata();
|
||||
const mockCollection = createMockDomain();
|
||||
|
||||
describe('Form Rendering', () => {
|
||||
it('renders all configured fields', () => {
|
||||
const form = createTestForm(mockCollection);
|
||||
|
||||
render(
|
||||
<CollectionEditForm
|
||||
form={form}
|
||||
metadata={mockMetadata}
|
||||
/>
|
||||
);
|
||||
|
||||
// Check that all fields from metadata are rendered
|
||||
expect(screen.getByTestId('directory-search')).toBeInTheDocument();
|
||||
expect(screen.getByTestId('tags-selector')).toBeInTheDocument();
|
||||
expect(screen.getByPlaceholderText(/optional description/i)).toBeInTheDocument();
|
||||
|
||||
// Verify Save button exists
|
||||
expect(screen.getByRole('button', {name: /save/i})).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('loads initial values into form', () => {
|
||||
const collectionWithData = createMockDomain({
|
||||
description: 'Test description',
|
||||
directory: 'archive/example.com'
|
||||
});
|
||||
|
||||
const form = createTestForm(collectionWithData);
|
||||
|
||||
render(
|
||||
<CollectionEditForm
|
||||
form={form}
|
||||
metadata={mockMetadata}
|
||||
/>
|
||||
);
|
||||
|
||||
// Check description is loaded
|
||||
expect(screen.getByPlaceholderText(/optional description/i)).toHaveValue('Test description');
|
||||
// Check directory field is rendered with the value
|
||||
const directoryField = screen.getByTestId('directory-search');
|
||||
expect(directoryField).toBeInTheDocument();
|
||||
// The mocked DestinationForm renders an input inside the container
|
||||
const directoryInput = directoryField.querySelector('input');
|
||||
expect(directoryInput).toHaveValue('archive/example.com');
|
||||
});
|
||||
|
||||
it('renders without errors when form is provided', () => {
|
||||
const form = createTestForm(mockCollection);
|
||||
|
||||
render(
|
||||
<CollectionEditForm
|
||||
form={form}
|
||||
metadata={mockMetadata}
|
||||
/>
|
||||
);
|
||||
|
||||
expect(screen.getByRole('button', {name: /save/i})).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
describe('Field Types', () => {
|
||||
it('renders textarea for description field', () => {
|
||||
const form = createTestForm(mockCollection);
|
||||
|
||||
render(
|
||||
<CollectionEditForm
|
||||
form={form}
|
||||
metadata={mockMetadata}
|
||||
/>
|
||||
);
|
||||
|
||||
const descriptionField = screen.getByPlaceholderText(/optional description/i);
|
||||
expect(descriptionField.tagName).toBe('TEXTAREA');
|
||||
});
|
||||
|
||||
it('renders directory field using DestinationForm', () => {
|
||||
const form = createTestForm(mockCollection);
|
||||
|
||||
render(
|
||||
<CollectionEditForm
|
||||
form={form}
|
||||
metadata={mockMetadata}
|
||||
/>
|
||||
);
|
||||
|
||||
expect(screen.getByTestId('directory-search')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('renders tag selector for tag_name field', () => {
|
||||
const form = createTestForm(mockCollection);
|
||||
|
||||
render(
|
||||
<CollectionEditForm
|
||||
form={form}
|
||||
metadata={mockMetadata}
|
||||
/>
|
||||
);
|
||||
|
||||
expect(screen.getByTestId('tags-selector')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
describe('Field Dependencies (tag requires directory)', () => {
|
||||
it('disables tag field when directory is empty', () => {
|
||||
const collectionWithoutDirectory = createMockDomain({
|
||||
directory: '',
|
||||
can_be_tagged: false
|
||||
});
|
||||
|
||||
const form = createTestForm(collectionWithoutDirectory);
|
||||
|
||||
render(
|
||||
<CollectionEditForm
|
||||
form={form}
|
||||
metadata={mockMetadata}
|
||||
/>
|
||||
);
|
||||
|
||||
// Should show dependency warning
|
||||
expect(screen.getByText(/set a directory to enable tagging/i)).toBeInTheDocument();
|
||||
|
||||
// Tag selector should be disabled
|
||||
const tagSelector = screen.getByTestId('tags-selector');
|
||||
expect(tagSelector).toHaveAttribute('data-disabled', 'true');
|
||||
});
|
||||
|
||||
it('enables tag field when directory is set', () => {
|
||||
const collectionWithDirectory = createMockDomain({
|
||||
directory: 'archive/example.com',
|
||||
can_be_tagged: true
|
||||
});
|
||||
|
||||
const form = createTestForm(collectionWithDirectory);
|
||||
|
||||
render(
|
||||
<CollectionEditForm
|
||||
form={form}
|
||||
metadata={mockMetadata}
|
||||
/>
|
||||
);
|
||||
|
||||
// Dependency warning should not be shown
|
||||
expect(screen.queryByText(/set a directory to enable tagging/i)).not.toBeInTheDocument();
|
||||
|
||||
// Tag selector should not be disabled
|
||||
const tagSelector = screen.getByTestId('tags-selector');
|
||||
expect(tagSelector).toHaveAttribute('data-disabled', 'false');
|
||||
});
|
||||
|
||||
it('shows warning when tag is set with directory', () => {
|
||||
const collectionWithDirectoryAndTag = createMockDomain({
|
||||
directory: 'archive/example.com',
|
||||
tag_name: 'News',
|
||||
can_be_tagged: true
|
||||
});
|
||||
|
||||
const form = createTestForm(collectionWithDirectoryAndTag);
|
||||
|
||||
render(
|
||||
<CollectionEditForm
|
||||
form={form}
|
||||
metadata={mockMetadata}
|
||||
/>
|
||||
);
|
||||
|
||||
// Should show tag warning
|
||||
expect(screen.getByText(/tagging will move files/i)).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
describe('Save/Cancel Actions', () => {
|
||||
it('shows Cancel button when onCancel provided', () => {
|
||||
const form = createTestForm(mockCollection);
|
||||
const mockOnCancel = jest.fn();
|
||||
|
||||
render(
|
||||
<CollectionEditForm
|
||||
form={form}
|
||||
metadata={mockMetadata}
|
||||
onCancel={mockOnCancel}
|
||||
/>
|
||||
);
|
||||
|
||||
expect(screen.getByRole('button', {name: /cancel/i})).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('disables form during loading', () => {
|
||||
const form = createTestForm(mockCollection, {
|
||||
overrides: {loading: true, disabled: true}
|
||||
});
|
||||
|
||||
render(
|
||||
<CollectionEditForm
|
||||
form={form}
|
||||
metadata={mockMetadata}
|
||||
/>
|
||||
);
|
||||
|
||||
// Save button should be disabled during loading
|
||||
const saveButton = screen.getByRole('button', {name: /save/i});
|
||||
expect(saveButton).toBeDisabled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('Error States', () => {
|
||||
it('handles missing metadata gracefully', () => {
|
||||
const form = createTestForm(mockCollection);
|
||||
|
||||
render(
|
||||
<CollectionEditForm
|
||||
form={form}
|
||||
metadata={null}
|
||||
/>
|
||||
);
|
||||
|
||||
// Should show warning about missing metadata
|
||||
expect(screen.getByText(/no metadata available/i)).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
describe('Theme Integration', () => {
|
||||
it('applies inverted styling to Segment in dark mode', () => {
|
||||
const form = createTestForm(mockCollection);
|
||||
|
||||
const {container} = renderInDarkMode(
|
||||
<CollectionEditForm
|
||||
form={form}
|
||||
metadata={mockMetadata}
|
||||
/>
|
||||
);
|
||||
|
||||
// Segment should have inverted class in dark mode
|
||||
const segment = container.querySelector('.ui.segment');
|
||||
expect(segment).toBeInTheDocument();
|
||||
expect(hasInvertedStyling(segment)).toBe(true);
|
||||
});
|
||||
|
||||
it('does not apply inverted styling in light mode', () => {
|
||||
const form = createTestForm(mockCollection);
|
||||
|
||||
const {container} = renderInLightMode(
|
||||
<CollectionEditForm
|
||||
form={form}
|
||||
metadata={mockMetadata}
|
||||
/>
|
||||
);
|
||||
|
||||
// Segment should NOT have inverted class in light mode
|
||||
const segment = container.querySelector('.ui.segment');
|
||||
expect(segment).toBeInTheDocument();
|
||||
expect(hasInvertedStyling(segment)).toBe(false);
|
||||
});
|
||||
|
||||
it('applies dark theme styling to Header in dark mode', () => {
|
||||
const form = createTestForm(mockCollection);
|
||||
|
||||
const {container} = renderInDarkMode(
|
||||
<CollectionEditForm
|
||||
form={form}
|
||||
metadata={mockMetadata}
|
||||
title="Test Collection"
|
||||
/>
|
||||
);
|
||||
|
||||
// Header should have dark text color inline style in dark mode
|
||||
const header = container.querySelector('.ui.header');
|
||||
expect(header).toBeInTheDocument();
|
||||
expect(header.style.color).toBe('rgb(238, 238, 238)'); // #eeeeee
|
||||
});
|
||||
|
||||
it('uses theme context from provider', () => {
|
||||
const form = createTestForm(mockCollection);
|
||||
|
||||
const {container} = render(
|
||||
<CollectionEditForm
|
||||
form={form}
|
||||
metadata={mockMetadata}
|
||||
/>
|
||||
);
|
||||
|
||||
const segment = container.querySelector('.ui.segment');
|
||||
expect(segment).toBeInTheDocument();
|
||||
// Should not be inverted by default
|
||||
expect(hasInvertedStyling(segment)).toBe(false);
|
||||
});
|
||||
});
|
||||
});
|
||||
279
app/src/components/collections/CollectionTable.js
Normal file
279
app/src/components/collections/CollectionTable.js
Normal file
|
|
@ -0,0 +1,279 @@
|
|||
import React, {useContext} from 'react';
|
||||
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 {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
|
||||
*/
|
||||
function formatFrequency(frequency) {
|
||||
if (frequency === null || frequency === undefined) {
|
||||
return '-';
|
||||
}
|
||||
const option = allFrequencyOptions[frequency];
|
||||
return option ? option.text : `${frequency}s`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate a search link for a collection based on metadata routing configuration.
|
||||
* Supports both query parameter-based (e.g., ?domain=...) and route-based (e.g., /channel/:id/video) linking.
|
||||
*
|
||||
* @param {Object} collection - The collection object
|
||||
* @param {Object} metadata - Collection metadata with routes configuration
|
||||
* @param {string} primaryKey - The primary column key to use for the value
|
||||
* @returns {string|null} The generated link, or null if no link can be generated
|
||||
*/
|
||||
function getCollectionSearchLink(collection, metadata, primaryKey) {
|
||||
const searchRoute = metadata.routes?.search;
|
||||
if (!searchRoute) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// Check if metadata specifies a query parameter to use
|
||||
if (metadata.routes.searchParam) {
|
||||
// Query parameter-based linking (e.g., /archive?domain=example.com)
|
||||
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';
|
||||
return searchRoute.replace(':id', collection[idField]);
|
||||
}
|
||||
|
||||
// No linking strategy available
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 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 editRoute = metadata.routes?.edit?.replace(':id', collection[idField]);
|
||||
const searchLink = getCollectionSearchLink(collection, metadata, primaryColumn.key);
|
||||
|
||||
return <TableRow verticalAlign='top'>
|
||||
<TableCell width={10} colSpan={2}>
|
||||
{searchLink ? (
|
||||
<Link as='h3' to={searchLink}>
|
||||
<h3>
|
||||
{collection[primaryColumn.key]}
|
||||
</h3>
|
||||
{collection.tag_name && <SingleTag name={collection.tag_name}/>}
|
||||
</Link>
|
||||
) : (
|
||||
<>
|
||||
<h3>{collection[primaryColumn.key]}</h3>
|
||||
{collection.tag_name && <SingleTag name={collection.tag_name}/>}
|
||||
</>
|
||||
)}
|
||||
{metadata.columns
|
||||
.filter(col => col.type !== 'actions' && col.key !== primaryColumn.key && col.key !== 'tag_name')
|
||||
.map(col => {
|
||||
let value = collection[col.key];
|
||||
if (col.format === 'bytes') {
|
||||
value = humanFileSize(value);
|
||||
} else if (col.format === 'frequency') {
|
||||
value = formatFrequency(value);
|
||||
}
|
||||
return (
|
||||
<p key={col.key}>
|
||||
{col.label}: {value || '-'}
|
||||
</p>
|
||||
);
|
||||
})
|
||||
}
|
||||
</TableCell>
|
||||
<TableCell width={6} colSpan={2} textAlign='right'>
|
||||
<p>
|
||||
{editRoute && <Link className="ui button secondary" to={editRoute}>Edit</Link>}
|
||||
</p>
|
||||
</TableCell>
|
||||
</TableRow>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Reusable table component for displaying collections (Domains, Channels, etc).
|
||||
*
|
||||
* @param {Array} collections - Array of collection objects
|
||||
* @param {Object} metadata - Backend-provided metadata containing columns, routes, etc.
|
||||
* @param {String} searchStr - Search filter string (managed by parent)
|
||||
* @param {Function} onRowClick - Optional callback when a row is clicked
|
||||
* @param {String} emptyMessage - Message to display when there are no collections
|
||||
*/
|
||||
export function CollectionTable({collections, metadata, searchStr = '', onRowClick, emptyMessage = 'No items yet'}) {
|
||||
const {inverted} = useContext(ThemeContext);
|
||||
const {SingleTag} = useContext(TagsContext);
|
||||
|
||||
// Loading state
|
||||
if (collections === null) {
|
||||
return <Placeholder>
|
||||
<PlaceholderHeader>
|
||||
<PlaceholderLine/>
|
||||
<PlaceholderLine/>
|
||||
</PlaceholderHeader>
|
||||
</Placeholder>;
|
||||
}
|
||||
|
||||
// Error state
|
||||
if (collections === undefined) {
|
||||
return <Message error>
|
||||
<Message.Header>Could not fetch collections</Message.Header>
|
||||
</Message>;
|
||||
}
|
||||
|
||||
// Empty state
|
||||
if (collections && collections.length === 0) {
|
||||
return <Message>
|
||||
<Message.Header>{emptyMessage}</Message.Header>
|
||||
</Message>;
|
||||
}
|
||||
|
||||
// No metadata available (backward compatibility)
|
||||
if (!metadata) {
|
||||
return <Message warning>
|
||||
<Message.Header>No metadata available</Message.Header>
|
||||
</Message>;
|
||||
}
|
||||
|
||||
// Filter collections by search string
|
||||
let filteredCollections = collections;
|
||||
if (searchStr) {
|
||||
const re = new RegExp(_.escapeRegExp(searchStr), 'i');
|
||||
filteredCollections = collections.filter(collection => {
|
||||
// Search across all string fields
|
||||
return Object.values(collection).some(value => {
|
||||
if (typeof value === 'string') {
|
||||
return re.test(value);
|
||||
}
|
||||
return false;
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
// 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>;
|
||||
};
|
||||
|
||||
// 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,
|
||||
};
|
||||
});
|
||||
|
||||
// Build mobile headers - simplified columns
|
||||
const primaryColumn = metadata.columns[0];
|
||||
const mobileHeaders = [
|
||||
{
|
||||
key: primaryColumn.key,
|
||||
text: primaryColumn.label,
|
||||
sortBy: primaryColumn.sortable ? primaryColumn.key : null
|
||||
},
|
||||
{
|
||||
key: 'manage',
|
||||
text: 'Manage'
|
||||
}
|
||||
];
|
||||
|
||||
// Get default sort column from metadata (first column key)
|
||||
const defaultSortColumn = metadata.columns[0]?.key || 'id';
|
||||
|
||||
|
||||
return <>
|
||||
<Media at='mobile'>
|
||||
<SortableTable
|
||||
tableProps={{striped: true, size: 'small', unstackable: true}}
|
||||
data={filteredCollections}
|
||||
rowFunc={(collection) => <MobileCollectionRow key={collection.id} collection={collection} metadata={metadata}/>}
|
||||
rowKey='id'
|
||||
tableHeaders={mobileHeaders}
|
||||
defaultSortColumn={defaultSortColumn}
|
||||
/>
|
||||
</Media>
|
||||
<Media greaterThanOrEqual='tablet'>
|
||||
<SortableTable
|
||||
tableProps={{striped: true, size: 'large', unstackable: true, compact: true}}
|
||||
data={filteredCollections}
|
||||
rowFunc={(collection) => renderRow(collection)}
|
||||
rowKey='id'
|
||||
tableHeaders={headers}
|
||||
defaultSortColumn={defaultSortColumn}
|
||||
/>
|
||||
</Media>
|
||||
</>;
|
||||
}
|
||||
156
app/src/components/collections/CollectionTagModal.js
Normal file
156
app/src/components/collections/CollectionTagModal.js
Normal file
|
|
@ -0,0 +1,156 @@
|
|||
import React, {useState, useEffect, useCallback} from 'react';
|
||||
import {Grid, Input} from 'semantic-ui-react';
|
||||
import Message from 'semantic-ui-react/dist/commonjs/collections/Message';
|
||||
import {Button, Modal, ModalActions, ModalContent, ModalHeader} from '../Theme';
|
||||
import {TagsSelector} from '../../Tags';
|
||||
import {APIButton, Toggle} from '../Common';
|
||||
|
||||
/**
|
||||
* Reusable modal component for tagging collections (Domains, Channels, etc).
|
||||
* Handles tag selection, directory suggestions, conflict warnings, and state reset on close.
|
||||
*
|
||||
* @param {boolean} open - Whether the modal is open
|
||||
* @param {Function} onClose - Callback when modal is closed
|
||||
* @param {string} currentTagName - The current tag name of the collection (if any)
|
||||
* @param {string} originalDirectory - The original directory of the collection (for reset)
|
||||
* @param {Function} getTagInfo - Async function to fetch tag info: (tagName) => Promise<{suggested_directory, conflict, conflict_message}>
|
||||
* @param {Function} onSave - Async function called when saving: (tagName, directory) => Promise<void>
|
||||
* @param {string} collectionName - Name of the collection for toast messages (e.g., "Domain", "Channel")
|
||||
*/
|
||||
export function CollectionTagModal({
|
||||
open,
|
||||
onClose,
|
||||
currentTagName,
|
||||
originalDirectory,
|
||||
getTagInfo,
|
||||
onSave,
|
||||
collectionName = 'Collection',
|
||||
}) {
|
||||
const [newTagName, setNewTagName] = useState(currentTagName || null);
|
||||
const [moveToTagDirectory, setMoveToTagDirectory] = useState(true);
|
||||
const [newTagDirectory, setNewTagDirectory] = useState(originalDirectory || '');
|
||||
const [conflictMessage, setConflictMessage] = useState(null);
|
||||
|
||||
// Reset state when modal opens or collection changes
|
||||
useEffect(() => {
|
||||
if (open) {
|
||||
setNewTagName(currentTagName || null);
|
||||
setNewTagDirectory(originalDirectory || '');
|
||||
setConflictMessage(null);
|
||||
}
|
||||
}, [open, currentTagName, originalDirectory]);
|
||||
|
||||
// Handle modal close - reset to original values
|
||||
const handleClose = useCallback(() => {
|
||||
setNewTagName(currentTagName || null);
|
||||
setNewTagDirectory(originalDirectory || '');
|
||||
setConflictMessage(null);
|
||||
onClose();
|
||||
}, [currentTagName, originalDirectory, onClose]);
|
||||
|
||||
// Handle tag selection change - fetch tag info
|
||||
const handleTagChange = useCallback(async (tagName) => {
|
||||
setNewTagName(tagName);
|
||||
setConflictMessage(null);
|
||||
|
||||
// Always fetch tag info when tag changes (including removal)
|
||||
try {
|
||||
const tagInfo = await getTagInfo(tagName);
|
||||
if (tagInfo) {
|
||||
// Handle both response formats:
|
||||
// - Object format: {suggested_directory, conflict, conflict_message}
|
||||
// - String format: just the directory path (legacy channel API)
|
||||
if (typeof tagInfo === 'string') {
|
||||
// Legacy format - just a directory string
|
||||
setNewTagDirectory(tagInfo);
|
||||
} else if (tagInfo.suggested_directory) {
|
||||
setNewTagDirectory(tagInfo.suggested_directory);
|
||||
} else if (!tagName) {
|
||||
// If tag removed and no suggestion, reset to original
|
||||
setNewTagDirectory(originalDirectory || '');
|
||||
}
|
||||
|
||||
// Handle conflict message (only in object format)
|
||||
if (typeof tagInfo === 'object' && tagInfo.conflict && tagInfo.conflict_message) {
|
||||
setConflictMessage(tagInfo.conflict_message);
|
||||
}
|
||||
} else if (!tagName) {
|
||||
// If no tag info returned and tag was removed, reset to original
|
||||
setNewTagDirectory(originalDirectory || '');
|
||||
}
|
||||
} catch (e) {
|
||||
console.error(`Failed to get tag info for ${collectionName}`, e);
|
||||
// Don't block the UI if tag info fails
|
||||
}
|
||||
}, [getTagInfo, originalDirectory, collectionName]);
|
||||
|
||||
// Handle save
|
||||
const handleSave = useCallback(async () => {
|
||||
await onSave(newTagName, moveToTagDirectory ? newTagDirectory : null);
|
||||
handleClose();
|
||||
}, [newTagName, moveToTagDirectory, newTagDirectory, onSave, handleClose]);
|
||||
|
||||
const modalTitle = currentTagName ? 'Modify Tag' : 'Add Tag';
|
||||
const saveButtonText = moveToTagDirectory ? 'Move' : 'Save';
|
||||
|
||||
return (
|
||||
<Modal
|
||||
open={open}
|
||||
onClose={handleClose}
|
||||
closeIcon
|
||||
>
|
||||
<ModalHeader>{modalTitle}</ModalHeader>
|
||||
<ModalContent>
|
||||
<Grid columns={1}>
|
||||
<Grid.Row>
|
||||
<Grid.Column>
|
||||
<TagsSelector
|
||||
limit={1}
|
||||
selectedTagNames={newTagName ? [newTagName] : []}
|
||||
onAdd={handleTagChange}
|
||||
onRemove={() => handleTagChange(null)}
|
||||
/>
|
||||
</Grid.Column>
|
||||
</Grid.Row>
|
||||
<Grid.Row>
|
||||
<Grid.Column>
|
||||
<Toggle
|
||||
label='Move to directory: '
|
||||
checked={moveToTagDirectory}
|
||||
onChange={setMoveToTagDirectory}
|
||||
/>
|
||||
</Grid.Column>
|
||||
</Grid.Row>
|
||||
<Grid.Row>
|
||||
<Grid.Column>
|
||||
<Input
|
||||
fluid
|
||||
value={newTagDirectory}
|
||||
onChange={(e, {value}) => setNewTagDirectory(value)}
|
||||
disabled={!moveToTagDirectory}
|
||||
/>
|
||||
</Grid.Column>
|
||||
</Grid.Row>
|
||||
{conflictMessage && (
|
||||
<Grid.Row>
|
||||
<Grid.Column>
|
||||
<Message warning>
|
||||
<Message.Header>Directory Conflict</Message.Header>
|
||||
<p>{conflictMessage}</p>
|
||||
</Message>
|
||||
</Grid.Column>
|
||||
</Grid.Row>
|
||||
)}
|
||||
</Grid>
|
||||
</ModalContent>
|
||||
<ModalActions>
|
||||
<Button onClick={handleClose}>Cancel</Button>
|
||||
<APIButton
|
||||
color='violet'
|
||||
onClick={handleSave}
|
||||
obeyWROLMode={true}
|
||||
>{saveButtonText}</APIButton>
|
||||
</ModalActions>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
442
app/src/components/collections/CollectionTagModal.test.js
Normal file
442
app/src/components/collections/CollectionTagModal.test.js
Normal file
|
|
@ -0,0 +1,442 @@
|
|||
import React from 'react';
|
||||
import {render, screen, waitFor, act} from '../../test-utils';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import {CollectionTagModal} from './CollectionTagModal';
|
||||
|
||||
// Mock Theme components
|
||||
jest.mock('../Theme', () => ({
|
||||
...jest.requireActual('../Theme'),
|
||||
Modal: ({open, onClose, children, closeIcon}) => {
|
||||
if (!open) return null;
|
||||
return (
|
||||
<div data-testid="modal">
|
||||
{closeIcon && <button data-testid="close-icon" onClick={onClose}>×</button>}
|
||||
{children}
|
||||
</div>
|
||||
);
|
||||
},
|
||||
ModalHeader: ({children}) => <div data-testid="modal-header">{children}</div>,
|
||||
ModalContent: ({children}) => <div data-testid="modal-content">{children}</div>,
|
||||
ModalActions: ({children}) => <div data-testid="modal-actions">{children}</div>,
|
||||
Button: ({children, onClick, ...props}) => (
|
||||
<button onClick={onClick} data-testid={`button-${children}`} {...props}>{children}</button>
|
||||
),
|
||||
}));
|
||||
|
||||
// Mock Common components
|
||||
jest.mock('../Common', () => ({
|
||||
...jest.requireActual('../Common'),
|
||||
Toggle: ({label, checked, onChange}) => (
|
||||
<label data-testid="toggle">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={checked}
|
||||
onChange={(e) => onChange(e.target.checked)}
|
||||
data-testid="toggle-checkbox"
|
||||
/>
|
||||
{label}
|
||||
</label>
|
||||
),
|
||||
APIButton: ({children, onClick, ...props}) => (
|
||||
<button onClick={onClick} data-testid={`api-button-${children}`} {...props}>{children}</button>
|
||||
),
|
||||
}));
|
||||
|
||||
// Mock TagsSelector
|
||||
jest.mock('../../Tags', () => ({
|
||||
TagsSelector: ({selectedTagNames, onAdd, onRemove, limit}) => (
|
||||
<div data-testid="tags-selector">
|
||||
<span data-testid="selected-tags">{selectedTagNames?.join(', ') || 'none'}</span>
|
||||
<button data-testid="add-tag" onClick={() => onAdd('test-tag')}>Add Tag</button>
|
||||
<button data-testid="remove-tag" onClick={() => onRemove('test-tag')}>Remove Tag</button>
|
||||
</div>
|
||||
),
|
||||
}));
|
||||
|
||||
describe('CollectionTagModal', () => {
|
||||
const defaultProps = {
|
||||
open: true,
|
||||
onClose: jest.fn(),
|
||||
currentTagName: null,
|
||||
originalDirectory: '/original/directory',
|
||||
getTagInfo: jest.fn(),
|
||||
onSave: jest.fn(),
|
||||
collectionName: 'Test',
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks();
|
||||
});
|
||||
|
||||
describe('Modal Rendering', () => {
|
||||
it('renders modal when open is true', () => {
|
||||
render(<CollectionTagModal {...defaultProps} />);
|
||||
expect(screen.getByTestId('modal')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('does not render modal when open is false', () => {
|
||||
render(<CollectionTagModal {...defaultProps} open={false} />);
|
||||
expect(screen.queryByTestId('modal')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows "Add Tag" header when no current tag', () => {
|
||||
render(<CollectionTagModal {...defaultProps} currentTagName={null} />);
|
||||
expect(screen.getByTestId('modal-header')).toHaveTextContent('Add Tag');
|
||||
});
|
||||
|
||||
it('shows "Modify Tag" header when there is a current tag', () => {
|
||||
render(<CollectionTagModal {...defaultProps} currentTagName="existing-tag" />);
|
||||
expect(screen.getByTestId('modal-header')).toHaveTextContent('Modify Tag');
|
||||
});
|
||||
});
|
||||
|
||||
describe('Directory Input', () => {
|
||||
it('displays original directory in input field', () => {
|
||||
render(<CollectionTagModal {...defaultProps} />);
|
||||
const input = screen.getByRole('textbox');
|
||||
expect(input).toHaveValue('/original/directory');
|
||||
});
|
||||
|
||||
it('updates directory when user types', async () => {
|
||||
render(<CollectionTagModal {...defaultProps} />);
|
||||
const input = screen.getByRole('textbox');
|
||||
await userEvent.clear(input);
|
||||
await userEvent.type(input, '/new/directory');
|
||||
expect(input).toHaveValue('/new/directory');
|
||||
});
|
||||
|
||||
it('disables directory input when move toggle is off', async () => {
|
||||
render(<CollectionTagModal {...defaultProps} />);
|
||||
const toggleCheckbox = screen.getByTestId('toggle-checkbox');
|
||||
await userEvent.click(toggleCheckbox); // Turn off move to directory
|
||||
const input = screen.getByRole('textbox');
|
||||
expect(input).toBeDisabled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('Tag Info Fetching', () => {
|
||||
it('fetches tag info when tag is added', async () => {
|
||||
const mockGetTagInfo = jest.fn().mockResolvedValue({
|
||||
suggested_directory: '/suggested/directory',
|
||||
conflict: false,
|
||||
conflict_message: null,
|
||||
});
|
||||
|
||||
render(<CollectionTagModal {...defaultProps} getTagInfo={mockGetTagInfo} />);
|
||||
|
||||
const addTagButton = screen.getByTestId('add-tag');
|
||||
await userEvent.click(addTagButton);
|
||||
|
||||
// Wait for all async state updates to complete by checking the final result
|
||||
await waitFor(() => {
|
||||
expect(mockGetTagInfo).toHaveBeenCalledWith('test-tag');
|
||||
// Also verify the directory was updated (this ensures async call completed)
|
||||
const input = screen.getByRole('textbox');
|
||||
expect(input).toHaveValue('/suggested/directory');
|
||||
});
|
||||
});
|
||||
|
||||
it('updates directory with suggested directory from tag info', async () => {
|
||||
const mockGetTagInfo = jest.fn().mockResolvedValue({
|
||||
suggested_directory: '/suggested/directory',
|
||||
conflict: false,
|
||||
conflict_message: null,
|
||||
});
|
||||
|
||||
render(<CollectionTagModal {...defaultProps} getTagInfo={mockGetTagInfo} />);
|
||||
|
||||
const addTagButton = screen.getByTestId('add-tag');
|
||||
await userEvent.click(addTagButton);
|
||||
|
||||
await waitFor(() => {
|
||||
const input = screen.getByRole('textbox');
|
||||
expect(input).toHaveValue('/suggested/directory');
|
||||
});
|
||||
});
|
||||
|
||||
it('handles legacy string format from tag info', async () => {
|
||||
const mockGetTagInfo = jest.fn().mockResolvedValue('/legacy/directory');
|
||||
|
||||
render(<CollectionTagModal {...defaultProps} getTagInfo={mockGetTagInfo} />);
|
||||
|
||||
const addTagButton = screen.getByTestId('add-tag');
|
||||
await userEvent.click(addTagButton);
|
||||
|
||||
await waitFor(() => {
|
||||
const input = screen.getByRole('textbox');
|
||||
expect(input).toHaveValue('/legacy/directory');
|
||||
});
|
||||
});
|
||||
|
||||
it('fetches tag info when tag is removed', async () => {
|
||||
const mockGetTagInfo = jest.fn().mockResolvedValue(null);
|
||||
|
||||
render(<CollectionTagModal {...defaultProps} getTagInfo={mockGetTagInfo} currentTagName="existing-tag" />);
|
||||
|
||||
const removeTagButton = screen.getByTestId('remove-tag');
|
||||
await userEvent.click(removeTagButton);
|
||||
|
||||
// Wait for all async state updates to complete
|
||||
await waitFor(() => {
|
||||
expect(mockGetTagInfo).toHaveBeenCalledWith(null);
|
||||
// Also verify the directory was reset (ensures async call completed)
|
||||
const input = screen.getByRole('textbox');
|
||||
expect(input).toHaveValue('/original/directory');
|
||||
});
|
||||
});
|
||||
|
||||
it('updates directory when tag is removed and backend returns suggestion', async () => {
|
||||
const mockGetTagInfo = jest.fn().mockResolvedValue({
|
||||
suggested_directory: '/untagged/directory',
|
||||
conflict: false,
|
||||
conflict_message: null,
|
||||
});
|
||||
|
||||
render(<CollectionTagModal {...defaultProps} getTagInfo={mockGetTagInfo} currentTagName="existing-tag" />);
|
||||
|
||||
const removeTagButton = screen.getByTestId('remove-tag');
|
||||
await userEvent.click(removeTagButton);
|
||||
|
||||
await waitFor(() => {
|
||||
const input = screen.getByRole('textbox');
|
||||
expect(input).toHaveValue('/untagged/directory');
|
||||
});
|
||||
});
|
||||
|
||||
it('resets to original directory when tag is removed and no suggestion', async () => {
|
||||
const mockGetTagInfo = jest.fn().mockResolvedValue(null);
|
||||
|
||||
render(<CollectionTagModal {...defaultProps} getTagInfo={mockGetTagInfo} originalDirectory="/original/path" />);
|
||||
|
||||
// First add a tag - wait for async to complete including state updates
|
||||
const addTagButton = screen.getByTestId('add-tag');
|
||||
await act(async () => {
|
||||
await userEvent.click(addTagButton);
|
||||
});
|
||||
|
||||
// Wait for first getTagInfo call to complete AND directory state to settle
|
||||
// When getTagInfo returns null, the component sets directory to originalDirectory
|
||||
await waitFor(() => {
|
||||
expect(mockGetTagInfo).toHaveBeenCalledWith('test-tag');
|
||||
const input = screen.getByRole('textbox');
|
||||
// After null response, directory is reset to original
|
||||
expect(input).toHaveValue('/original/path');
|
||||
});
|
||||
|
||||
// Then remove the tag - wrap in act to catch async state updates
|
||||
const removeTagButton = screen.getByTestId('remove-tag');
|
||||
await act(async () => {
|
||||
await userEvent.click(removeTagButton);
|
||||
});
|
||||
|
||||
// Verify all state updates completed
|
||||
expect(mockGetTagInfo).toHaveBeenCalledWith(null);
|
||||
const input = screen.getByRole('textbox');
|
||||
expect(input).toHaveValue('/original/path');
|
||||
});
|
||||
});
|
||||
|
||||
describe('Conflict Handling', () => {
|
||||
it('displays conflict warning when tag info indicates conflict', async () => {
|
||||
const mockGetTagInfo = jest.fn().mockResolvedValue({
|
||||
suggested_directory: '/conflict/directory',
|
||||
conflict: true,
|
||||
conflict_message: 'Directory already in use',
|
||||
});
|
||||
|
||||
render(<CollectionTagModal {...defaultProps} getTagInfo={mockGetTagInfo} />);
|
||||
|
||||
const addTagButton = screen.getByTestId('add-tag');
|
||||
await userEvent.click(addTagButton);
|
||||
|
||||
// Wait for all async state updates including conflict message and directory
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('Directory Conflict')).toBeInTheDocument();
|
||||
expect(screen.getByText('Directory already in use')).toBeInTheDocument();
|
||||
// Also check directory was updated (ensures all state updates complete)
|
||||
const input = screen.getByRole('textbox');
|
||||
expect(input).toHaveValue('/conflict/directory');
|
||||
});
|
||||
});
|
||||
|
||||
it('clears conflict warning when tag is changed', async () => {
|
||||
const mockGetTagInfo = jest.fn()
|
||||
.mockResolvedValueOnce({
|
||||
suggested_directory: '/conflict/directory',
|
||||
conflict: true,
|
||||
conflict_message: 'Directory already in use',
|
||||
})
|
||||
.mockResolvedValueOnce({
|
||||
suggested_directory: '/no-conflict/directory',
|
||||
conflict: false,
|
||||
conflict_message: null,
|
||||
});
|
||||
|
||||
render(<CollectionTagModal {...defaultProps} getTagInfo={mockGetTagInfo} />);
|
||||
|
||||
// Add first tag - shows conflict
|
||||
const addTagButton = screen.getByTestId('add-tag');
|
||||
await userEvent.click(addTagButton);
|
||||
|
||||
// Wait for first async call to complete (conflict message AND directory update)
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('Directory Conflict')).toBeInTheDocument();
|
||||
const input = screen.getByRole('textbox');
|
||||
expect(input).toHaveValue('/conflict/directory');
|
||||
});
|
||||
|
||||
// Add different tag - conflict should clear
|
||||
await userEvent.click(addTagButton);
|
||||
|
||||
// Wait for second async call to complete (no conflict AND new directory)
|
||||
await waitFor(() => {
|
||||
expect(screen.queryByText('Directory Conflict')).not.toBeInTheDocument();
|
||||
const input = screen.getByRole('textbox');
|
||||
expect(input).toHaveValue('/no-conflict/directory');
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('Modal Close Behavior', () => {
|
||||
it('calls onClose when cancel button is clicked', async () => {
|
||||
const mockOnClose = jest.fn();
|
||||
render(<CollectionTagModal {...defaultProps} onClose={mockOnClose} />);
|
||||
|
||||
const cancelButton = screen.getByTestId('button-Cancel');
|
||||
await userEvent.click(cancelButton);
|
||||
|
||||
expect(mockOnClose).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('resets directory to original value when modal is closed', async () => {
|
||||
const mockOnClose = jest.fn();
|
||||
const mockGetTagInfo = jest.fn().mockResolvedValue({
|
||||
suggested_directory: '/changed/directory',
|
||||
conflict: false,
|
||||
conflict_message: null,
|
||||
});
|
||||
|
||||
const {rerender} = render(
|
||||
<CollectionTagModal
|
||||
{...defaultProps}
|
||||
onClose={mockOnClose}
|
||||
getTagInfo={mockGetTagInfo}
|
||||
originalDirectory="/original/directory"
|
||||
/>
|
||||
);
|
||||
|
||||
// Change directory by adding a tag
|
||||
const addTagButton = screen.getByTestId('add-tag');
|
||||
await userEvent.click(addTagButton);
|
||||
|
||||
await waitFor(() => {
|
||||
const input = screen.getByRole('textbox');
|
||||
expect(input).toHaveValue('/changed/directory');
|
||||
});
|
||||
|
||||
// Close the modal
|
||||
const cancelButton = screen.getByTestId('button-Cancel');
|
||||
await userEvent.click(cancelButton);
|
||||
|
||||
// Reopen modal
|
||||
rerender(
|
||||
<CollectionTagModal
|
||||
{...defaultProps}
|
||||
open={true}
|
||||
onClose={mockOnClose}
|
||||
getTagInfo={mockGetTagInfo}
|
||||
originalDirectory="/original/directory"
|
||||
/>
|
||||
);
|
||||
|
||||
// Directory should be reset to original
|
||||
await waitFor(() => {
|
||||
const input = screen.getByRole('textbox');
|
||||
expect(input).toHaveValue('/original/directory');
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('Save Behavior', () => {
|
||||
it('calls onSave with tag name and directory when move toggle is on', async () => {
|
||||
const mockOnClose = jest.fn();
|
||||
// Use mockResolvedValue to make onSave async - this helps React batch state updates properly
|
||||
const mockOnSave = jest.fn().mockResolvedValue(undefined);
|
||||
const mockGetTagInfo = jest.fn().mockResolvedValue({
|
||||
suggested_directory: '/suggested/directory',
|
||||
conflict: false,
|
||||
});
|
||||
|
||||
render(
|
||||
<CollectionTagModal
|
||||
{...defaultProps}
|
||||
onSave={mockOnSave}
|
||||
onClose={mockOnClose}
|
||||
getTagInfo={mockGetTagInfo}
|
||||
/>
|
||||
);
|
||||
|
||||
// Add a tag
|
||||
const addTagButton = screen.getByTestId('add-tag');
|
||||
await userEvent.click(addTagButton);
|
||||
|
||||
// Wait for the directory to be updated from getTagInfo
|
||||
await waitFor(() => {
|
||||
const input = screen.getByRole('textbox');
|
||||
expect(input).toHaveValue('/suggested/directory');
|
||||
});
|
||||
|
||||
// Click save/move button and wait for all async operations to complete
|
||||
await act(async () => {
|
||||
await userEvent.click(screen.getByTestId('api-button-Move'));
|
||||
});
|
||||
|
||||
// Verify the save was called
|
||||
expect(mockOnSave).toHaveBeenCalledWith('test-tag', '/suggested/directory');
|
||||
expect(mockOnClose).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('calls onSave with null directory when move toggle is off', async () => {
|
||||
const mockOnClose = jest.fn();
|
||||
// Use mockResolvedValue to make onSave async - this helps React batch state updates properly
|
||||
const mockOnSave = jest.fn().mockResolvedValue(undefined);
|
||||
const mockGetTagInfo = jest.fn().mockResolvedValue({
|
||||
suggested_directory: '/suggested/directory',
|
||||
conflict: false,
|
||||
});
|
||||
|
||||
render(
|
||||
<CollectionTagModal
|
||||
{...defaultProps}
|
||||
onSave={mockOnSave}
|
||||
onClose={mockOnClose}
|
||||
getTagInfo={mockGetTagInfo}
|
||||
/>
|
||||
);
|
||||
|
||||
// Add a tag
|
||||
const addTagButton = screen.getByTestId('add-tag');
|
||||
await userEvent.click(addTagButton);
|
||||
|
||||
// Wait for all async state updates to complete
|
||||
await waitFor(() => {
|
||||
expect(mockGetTagInfo).toHaveBeenCalled();
|
||||
const input = screen.getByRole('textbox');
|
||||
expect(input).toHaveValue('/suggested/directory');
|
||||
});
|
||||
|
||||
// Turn off move toggle
|
||||
const toggleCheckbox = screen.getByTestId('toggle-checkbox');
|
||||
await userEvent.click(toggleCheckbox);
|
||||
|
||||
// Click save button and wait for all async operations to complete
|
||||
await act(async () => {
|
||||
await userEvent.click(screen.getByTestId('api-button-Save'));
|
||||
});
|
||||
|
||||
// Verify the save was called
|
||||
expect(mockOnSave).toHaveBeenCalledWith('test-tag', null);
|
||||
expect(mockOnClose).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
@ -2,6 +2,7 @@ import React, {useContext, useEffect, useRef, useState} from "react";
|
|||
import {
|
||||
ApiDownError,
|
||||
createChannel,
|
||||
fetchChannels,
|
||||
fetchDecoded,
|
||||
fetchDomains,
|
||||
fetchFilesProgress,
|
||||
|
|
@ -10,6 +11,7 @@ import {
|
|||
getChannel,
|
||||
getChannels,
|
||||
getConfigs,
|
||||
getDomain,
|
||||
getDownloads,
|
||||
getFiles,
|
||||
getInventory,
|
||||
|
|
@ -32,6 +34,7 @@ import {
|
|||
setHotspot,
|
||||
setThrottle,
|
||||
updateChannel,
|
||||
updateDomain,
|
||||
} from "../api";
|
||||
import {createSearchParams, useLocation, useSearchParams} from "react-router-dom";
|
||||
import {enumerate, filterToMimetypes, humanFileSize, secondsToFullDuration} from "../components/Common";
|
||||
|
|
@ -191,17 +194,21 @@ export const useAllQuery = (name) => {
|
|||
export const useDomains = () => {
|
||||
const [domains, setDomains] = useState(null);
|
||||
const [total, setTotal] = useState(null);
|
||||
const [metadata, setMetadata] = useState(null);
|
||||
|
||||
const _fetchDomains = async () => {
|
||||
setDomains(null);
|
||||
setTotal(0);
|
||||
setMetadata(null);
|
||||
try {
|
||||
let [domains, total] = await fetchDomains();
|
||||
let [domains, total, metadata] = await fetchDomains();
|
||||
setDomains(domains);
|
||||
setTotal(total);
|
||||
setMetadata(metadata);
|
||||
} catch (e) {
|
||||
setDomains(undefined); // Display error.
|
||||
setTotal(0);
|
||||
setMetadata(undefined);
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -209,7 +216,86 @@ export const useDomains = () => {
|
|||
_fetchDomains();
|
||||
}, []);
|
||||
|
||||
return [domains, total];
|
||||
return [domains, total, metadata];
|
||||
}
|
||||
|
||||
export const useCollectionMetadata = (kind) => {
|
||||
const [metadata, setMetadata] = useState(null);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [error, setError] = useState(null);
|
||||
|
||||
const fetchMetadata = async () => {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
try {
|
||||
if (kind === 'domain') {
|
||||
const [, , metadata] = await fetchDomains();
|
||||
setMetadata(metadata);
|
||||
} else {
|
||||
// Future: Support channels metadata
|
||||
setMetadata(null);
|
||||
}
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
setError(e);
|
||||
setMetadata(null);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
fetchMetadata();
|
||||
}, [kind]);
|
||||
|
||||
return {metadata, loading, error, fetchMetadata};
|
||||
}
|
||||
|
||||
export const useDomain = (domainId) => {
|
||||
const emptyDomain = {
|
||||
domain: '',
|
||||
directory: '',
|
||||
description: '',
|
||||
tag_name: null,
|
||||
};
|
||||
|
||||
const fetchDomain = async () => {
|
||||
if (!domainId) {
|
||||
console.debug('Not fetching domain because no domainId is provided');
|
||||
return;
|
||||
}
|
||||
const d = await getDomain(domainId);
|
||||
// Prevent controlled to uncontrolled
|
||||
d.directory = d.directory || '';
|
||||
d.description = d.description || '';
|
||||
d.tag_name = d.tag_name || null;
|
||||
return d;
|
||||
};
|
||||
|
||||
const submitDomain = async () => {
|
||||
const body = {
|
||||
directory: form.formData.directory,
|
||||
description: form.formData.description,
|
||||
// Convert null to empty string - backend expects "" to clear tag
|
||||
tag_name: form.formData.tag_name === null ? '' : form.formData.tag_name,
|
||||
};
|
||||
return await updateDomain(domainId, body);
|
||||
};
|
||||
|
||||
const form = useForm({
|
||||
fetcher: fetchDomain,
|
||||
emptyFormData: emptyDomain,
|
||||
clearOnSuccess: false,
|
||||
submitter: submitDomain
|
||||
});
|
||||
|
||||
React.useEffect(() => {
|
||||
form.fetcher();
|
||||
}, [domainId]);
|
||||
|
||||
const domain = form.formData;
|
||||
|
||||
return {domain, form, fetchDomain: form.fetcher};
|
||||
}
|
||||
|
||||
export const useArchive = (archiveId) => {
|
||||
|
|
@ -522,23 +608,31 @@ export const useChannel = (channel_id) => {
|
|||
|
||||
export const useChannels = () => {
|
||||
const [channels, setChannels] = useState(null);
|
||||
const [total, setTotal] = useState(null);
|
||||
const [metadata, setMetadata] = useState(null);
|
||||
|
||||
const fetchChannels = async () => {
|
||||
const _fetchChannels = async () => {
|
||||
setChannels(null);
|
||||
setTotal(0);
|
||||
setMetadata(null);
|
||||
try {
|
||||
const c = await getChannels();
|
||||
setChannels(c);
|
||||
let [channels, total, metadata] = await fetchChannels();
|
||||
setChannels(channels);
|
||||
setTotal(total);
|
||||
setMetadata(metadata);
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
setChannels(undefined); // Could not get Channels, display error.
|
||||
setChannels(undefined); // Display error.
|
||||
setTotal(0);
|
||||
setMetadata(undefined);
|
||||
}
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
fetchChannels();
|
||||
_fetchChannels();
|
||||
}, []);
|
||||
|
||||
return {channels, fetchChannels}
|
||||
return [channels, total, metadata];
|
||||
}
|
||||
|
||||
export const useSearchRecentFiles = () => {
|
||||
|
|
|
|||
|
|
@ -113,10 +113,12 @@ export function useForm({
|
|||
reset();
|
||||
}
|
||||
await onSuccess();
|
||||
} catch (error) {
|
||||
await onFailure(error);
|
||||
throw error;
|
||||
} finally {
|
||||
setLoading(false);
|
||||
setDisabled(false);
|
||||
await onFailure();
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
998
app/src/hooks/useForm.test.js
Normal file
998
app/src/hooks/useForm.test.js
Normal file
|
|
@ -0,0 +1,998 @@
|
|||
import React from 'react';
|
||||
import {renderHook, act, waitFor} from '@testing-library/react';
|
||||
import {render, screen, fireEvent} from '@testing-library/react';
|
||||
import {useForm, commaSeparatedValidator, InputForm, NumberInputForm, UrlInput, ToggleForm, UrlsTextarea} from './useForm';
|
||||
import {renderWithProviders} from '../test-utils';
|
||||
|
||||
// Mock lodash debounce to control timing in tests
|
||||
jest.mock('lodash', () => {
|
||||
const actual = jest.requireActual('lodash');
|
||||
return {
|
||||
...actual,
|
||||
debounce: (fn) => {
|
||||
const debounced = (...args) => fn(...args);
|
||||
debounced.cancel = jest.fn();
|
||||
return debounced;
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
describe('useForm', () => {
|
||||
let consoleErrorSpy;
|
||||
let consoleDebugSpy;
|
||||
|
||||
beforeEach(() => {
|
||||
consoleErrorSpy = jest.spyOn(console, 'error').mockImplementation(() => {
|
||||
});
|
||||
consoleDebugSpy = jest.spyOn(console, 'debug').mockImplementation(() => {
|
||||
});
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
consoleErrorSpy.mockRestore();
|
||||
consoleDebugSpy.mockRestore();
|
||||
});
|
||||
|
||||
describe('initialization', () => {
|
||||
it('initializes with defaultFormData', () => {
|
||||
const defaultData = {name: 'test', value: 123};
|
||||
const {result} = renderHook(() => useForm({
|
||||
defaultFormData: defaultData,
|
||||
submitter: jest.fn(),
|
||||
}));
|
||||
|
||||
expect(result.current.formData).toEqual(defaultData);
|
||||
});
|
||||
|
||||
it('starts with correct initial states', () => {
|
||||
const {result} = renderHook(() => useForm({
|
||||
defaultFormData: {},
|
||||
submitter: jest.fn(),
|
||||
}));
|
||||
|
||||
expect(result.current.dirty).toBe(false);
|
||||
expect(result.current.loading).toBe(false);
|
||||
expect(result.current.disabled).toBe(false);
|
||||
// Ready starts true when there are no validators or required fields
|
||||
expect(result.current.ready).toBe(true);
|
||||
});
|
||||
|
||||
it('calls fetcher on mount if provided', async () => {
|
||||
const fetcher = jest.fn().mockResolvedValue({fetched: 'data'});
|
||||
|
||||
renderHook(() => useForm({
|
||||
fetcher,
|
||||
defaultFormData: {},
|
||||
submitter: jest.fn(),
|
||||
}));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(fetcher).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
|
||||
it('updates formData when fetcher resolves', async () => {
|
||||
const fetchedData = {name: 'fetched', value: 456};
|
||||
const fetcher = jest.fn().mockResolvedValue(fetchedData);
|
||||
|
||||
const {result} = renderHook(() => useForm({
|
||||
fetcher,
|
||||
defaultFormData: {name: 'default'},
|
||||
submitter: jest.fn(),
|
||||
}));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.formData).toEqual(fetchedData);
|
||||
});
|
||||
});
|
||||
|
||||
it('initializes with empty object when no defaultFormData provided', () => {
|
||||
const {result} = renderHook(() => useForm({
|
||||
submitter: jest.fn(),
|
||||
}));
|
||||
|
||||
expect(result.current.formData).toEqual({});
|
||||
});
|
||||
});
|
||||
|
||||
describe('submit lifecycle', () => {
|
||||
it('refuses to submit when not ready', async () => {
|
||||
const submitter = jest.fn();
|
||||
const {result} = renderHook(() => useForm({
|
||||
defaultFormData: {},
|
||||
submitter,
|
||||
}));
|
||||
|
||||
// Force ready to false by adding a required field that's empty
|
||||
act(() => {
|
||||
result.current.getInputProps({name: 'required_field', required: true});
|
||||
});
|
||||
|
||||
await act(async () => {
|
||||
await result.current.onSubmit();
|
||||
});
|
||||
|
||||
expect(submitter).not.toHaveBeenCalled();
|
||||
expect(consoleErrorSpy).toHaveBeenCalledWith('Refusing to submit form because it is not ready');
|
||||
});
|
||||
|
||||
it('sets loading and disabled during submission', async () => {
|
||||
let resolveSubmit;
|
||||
const submitter = jest.fn(() => new Promise(resolve => {
|
||||
resolveSubmit = resolve;
|
||||
}));
|
||||
|
||||
const {result} = renderHook(() => useForm({
|
||||
defaultFormData: {name: 'test'},
|
||||
submitter,
|
||||
}));
|
||||
|
||||
// Start submission
|
||||
let submitPromise;
|
||||
act(() => {
|
||||
submitPromise = result.current.onSubmit();
|
||||
});
|
||||
|
||||
// During submission - loading and disabled are set synchronously
|
||||
expect(result.current.loading).toBe(true);
|
||||
expect(result.current.disabled).toBe(true);
|
||||
// Note: ready is set to false in onSubmit, but the useEffect that computes
|
||||
// ready may run after this check. The key assertion is loading/disabled.
|
||||
|
||||
// Complete submission
|
||||
await act(async () => {
|
||||
resolveSubmit();
|
||||
await submitPromise;
|
||||
});
|
||||
|
||||
// After submission - states are reset
|
||||
expect(result.current.loading).toBe(false);
|
||||
expect(result.current.disabled).toBe(false);
|
||||
});
|
||||
|
||||
it('calls submitter with form data', async () => {
|
||||
const formData = {name: 'test', value: 123};
|
||||
const submitter = jest.fn().mockResolvedValue(undefined);
|
||||
|
||||
const {result} = renderHook(() => useForm({
|
||||
defaultFormData: formData,
|
||||
submitter,
|
||||
}));
|
||||
|
||||
await act(async () => {
|
||||
await result.current.onSubmit();
|
||||
});
|
||||
|
||||
expect(submitter).toHaveBeenCalledWith(formData);
|
||||
});
|
||||
|
||||
it('calls onSuccess after successful submit', async () => {
|
||||
const onSuccess = jest.fn();
|
||||
const submitter = jest.fn().mockResolvedValue(undefined);
|
||||
|
||||
const {result} = renderHook(() => useForm({
|
||||
defaultFormData: {name: 'test'},
|
||||
submitter,
|
||||
onSuccess,
|
||||
}));
|
||||
|
||||
await act(async () => {
|
||||
await result.current.onSubmit();
|
||||
});
|
||||
|
||||
expect(onSuccess).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('does not call onFailure on successful submit', async () => {
|
||||
const onSuccess = jest.fn();
|
||||
const onFailure = jest.fn();
|
||||
const submitter = jest.fn().mockResolvedValue(undefined);
|
||||
|
||||
const {result} = renderHook(() => useForm({
|
||||
defaultFormData: {name: 'test'},
|
||||
submitter,
|
||||
onSuccess,
|
||||
onFailure,
|
||||
}));
|
||||
|
||||
await act(async () => {
|
||||
await result.current.onSubmit();
|
||||
});
|
||||
|
||||
expect(onSuccess).toHaveBeenCalled();
|
||||
expect(onFailure).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('clears form when clearOnSuccess is true', async () => {
|
||||
const emptyFormData = {name: '', value: 0};
|
||||
const submitter = jest.fn().mockResolvedValue(undefined);
|
||||
|
||||
const {result} = renderHook(() => useForm({
|
||||
defaultFormData: {name: 'test', value: 123},
|
||||
emptyFormData,
|
||||
submitter,
|
||||
clearOnSuccess: true,
|
||||
}));
|
||||
|
||||
await act(async () => {
|
||||
await result.current.onSubmit();
|
||||
});
|
||||
|
||||
expect(result.current.formData).toEqual(emptyFormData);
|
||||
});
|
||||
|
||||
it('re-fetches when fetchOnSuccess is true', async () => {
|
||||
const fetchedData = {name: 'refetched'};
|
||||
const fetcher = jest.fn().mockResolvedValue(fetchedData);
|
||||
const submitter = jest.fn().mockResolvedValue(undefined);
|
||||
|
||||
const {result} = renderHook(() => useForm({
|
||||
fetcher,
|
||||
defaultFormData: {name: 'initial'},
|
||||
submitter,
|
||||
fetchOnSuccess: true,
|
||||
}));
|
||||
|
||||
// Wait for initial fetch
|
||||
await waitFor(() => {
|
||||
expect(fetcher).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
await act(async () => {
|
||||
await result.current.onSubmit();
|
||||
});
|
||||
|
||||
// Should have been called twice (init + after submit)
|
||||
expect(fetcher).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it('handles submitter errors gracefully', async () => {
|
||||
const submitter = jest.fn().mockRejectedValue(new Error('Submit failed'));
|
||||
const onFailure = jest.fn();
|
||||
|
||||
const {result} = renderHook(() => useForm({
|
||||
defaultFormData: {name: 'test'},
|
||||
submitter,
|
||||
onFailure,
|
||||
}));
|
||||
|
||||
await act(async () => {
|
||||
try {
|
||||
await result.current.onSubmit();
|
||||
} catch (e) {
|
||||
// Expected to throw
|
||||
}
|
||||
});
|
||||
|
||||
// Should still reset loading/disabled states
|
||||
expect(result.current.loading).toBe(false);
|
||||
expect(result.current.disabled).toBe(false);
|
||||
expect(onFailure).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('form data management', () => {
|
||||
it('setValue updates value at path', () => {
|
||||
const {result} = renderHook(() => useForm({
|
||||
defaultFormData: {name: 'original'},
|
||||
submitter: jest.fn(),
|
||||
}));
|
||||
|
||||
act(() => {
|
||||
result.current.setValue('name', 'updated');
|
||||
});
|
||||
|
||||
expect(result.current.formData.name).toBe('updated');
|
||||
});
|
||||
|
||||
it('setValue handles nested paths', () => {
|
||||
const {result} = renderHook(() => useForm({
|
||||
defaultFormData: {config: {nested: {value: 'original'}}},
|
||||
submitter: jest.fn(),
|
||||
}));
|
||||
|
||||
act(() => {
|
||||
result.current.setValue('config.nested.value', 'updated');
|
||||
});
|
||||
|
||||
expect(result.current.formData.config.nested.value).toBe('updated');
|
||||
});
|
||||
|
||||
it('handleInputEvent extracts value from event', () => {
|
||||
const {result} = renderHook(() => useForm({
|
||||
defaultFormData: {username: ''},
|
||||
submitter: jest.fn(),
|
||||
}));
|
||||
|
||||
act(() => {
|
||||
result.current.handleInputEvent({
|
||||
preventDefault: jest.fn(),
|
||||
target: {
|
||||
type: 'text',
|
||||
value: 'newvalue',
|
||||
name: 'username',
|
||||
dataset: {},
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
expect(result.current.formData.username).toBe('newvalue');
|
||||
});
|
||||
|
||||
it('handleInputEvent converts number inputs to integers', () => {
|
||||
const {result} = renderHook(() => useForm({
|
||||
defaultFormData: {count: 0},
|
||||
submitter: jest.fn(),
|
||||
}));
|
||||
|
||||
act(() => {
|
||||
result.current.handleInputEvent({
|
||||
preventDefault: jest.fn(),
|
||||
target: {
|
||||
type: 'number',
|
||||
value: '42',
|
||||
name: 'count',
|
||||
dataset: {},
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
expect(result.current.formData.count).toBe(42);
|
||||
expect(typeof result.current.formData.count).toBe('number');
|
||||
});
|
||||
|
||||
it('handleInputEvent uses data-path attribute when available', () => {
|
||||
const {result} = renderHook(() => useForm({
|
||||
defaultFormData: {nested: {field: ''}},
|
||||
submitter: jest.fn(),
|
||||
}));
|
||||
|
||||
act(() => {
|
||||
result.current.handleInputEvent({
|
||||
preventDefault: jest.fn(),
|
||||
target: {
|
||||
type: 'text',
|
||||
value: 'pathvalue',
|
||||
name: 'ignored',
|
||||
dataset: {path: 'nested.field'},
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
expect(result.current.formData.nested.field).toBe('pathvalue');
|
||||
});
|
||||
|
||||
it('reset restores to emptyFormData when provided', () => {
|
||||
const emptyFormData = {name: '', value: null};
|
||||
const {result} = renderHook(() => useForm({
|
||||
defaultFormData: {name: 'test', value: 123},
|
||||
emptyFormData,
|
||||
submitter: jest.fn(),
|
||||
}));
|
||||
|
||||
act(() => {
|
||||
result.current.setValue('name', 'modified');
|
||||
});
|
||||
|
||||
act(() => {
|
||||
result.current.reset();
|
||||
});
|
||||
|
||||
expect(result.current.formData).toEqual(emptyFormData);
|
||||
});
|
||||
|
||||
it('reset restores to defaultFormData when emptyFormData not provided', () => {
|
||||
const defaultFormData = {name: 'default', value: 100};
|
||||
const {result} = renderHook(() => useForm({
|
||||
defaultFormData,
|
||||
submitter: jest.fn(),
|
||||
}));
|
||||
|
||||
act(() => {
|
||||
result.current.setValue('name', 'modified');
|
||||
});
|
||||
|
||||
act(() => {
|
||||
result.current.reset();
|
||||
});
|
||||
|
||||
expect(result.current.formData).toEqual(defaultFormData);
|
||||
});
|
||||
});
|
||||
|
||||
describe('dirty tracking', () => {
|
||||
it('becomes dirty when formData differs from defaultFormData', async () => {
|
||||
const {result} = renderHook(() => useForm({
|
||||
defaultFormData: {name: 'original'},
|
||||
submitter: jest.fn(),
|
||||
}));
|
||||
|
||||
expect(result.current.dirty).toBe(false);
|
||||
|
||||
act(() => {
|
||||
result.current.setValue('name', 'changed');
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.dirty).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
it('calls onDirty callback when dirty becomes true', async () => {
|
||||
const onDirty = jest.fn();
|
||||
const {result} = renderHook(() => useForm({
|
||||
defaultFormData: {name: 'original'},
|
||||
submitter: jest.fn(),
|
||||
onDirty,
|
||||
}));
|
||||
|
||||
act(() => {
|
||||
result.current.setValue('name', 'changed');
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(onDirty).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
it('uses deep equality for nested objects', async () => {
|
||||
const {result} = renderHook(() => useForm({
|
||||
defaultFormData: {config: {nested: 'value'}},
|
||||
submitter: jest.fn(),
|
||||
}));
|
||||
|
||||
expect(result.current.dirty).toBe(false);
|
||||
|
||||
act(() => {
|
||||
result.current.setValue('config.nested', 'different');
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.dirty).toBe(true);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('validation', () => {
|
||||
it('validates field and sets error when invalid', async () => {
|
||||
const validator = (value) => value.length < 3 ? 'Too short' : null;
|
||||
const {result} = renderHook(() => useForm({
|
||||
defaultFormData: {name: ''},
|
||||
submitter: jest.fn(),
|
||||
}));
|
||||
|
||||
act(() => {
|
||||
result.current.getInputProps({name: 'name', validator});
|
||||
});
|
||||
|
||||
act(() => {
|
||||
result.current.handleInputEvent({
|
||||
preventDefault: jest.fn(),
|
||||
target: {
|
||||
type: 'text',
|
||||
value: 'ab',
|
||||
name: 'name',
|
||||
dataset: {},
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.ready).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
it('clears error when value becomes valid', async () => {
|
||||
const validator = (value) => value.length < 3 ? 'Too short' : null;
|
||||
const {result} = renderHook(() => useForm({
|
||||
defaultFormData: {name: ''},
|
||||
submitter: jest.fn(),
|
||||
}));
|
||||
|
||||
act(() => {
|
||||
result.current.getInputProps({name: 'name', validator});
|
||||
});
|
||||
|
||||
// Set invalid value
|
||||
act(() => {
|
||||
result.current.handleInputEvent({
|
||||
preventDefault: jest.fn(),
|
||||
target: {type: 'text', value: 'ab', name: 'name', dataset: {}},
|
||||
});
|
||||
});
|
||||
|
||||
// Set valid value
|
||||
act(() => {
|
||||
result.current.handleInputEvent({
|
||||
preventDefault: jest.fn(),
|
||||
target: {type: 'text', value: 'valid', name: 'name', dataset: {}},
|
||||
});
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.ready).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
it('handles validator that throws exception', () => {
|
||||
const validator = () => {
|
||||
throw new Error('Validator crashed');
|
||||
};
|
||||
const {result} = renderHook(() => useForm({
|
||||
defaultFormData: {name: ''},
|
||||
submitter: jest.fn(),
|
||||
}));
|
||||
|
||||
act(() => {
|
||||
result.current.getInputProps({name: 'name', validator});
|
||||
});
|
||||
|
||||
// Should not throw, just log error
|
||||
act(() => {
|
||||
result.current.handleInputEvent({
|
||||
preventDefault: jest.fn(),
|
||||
target: {type: 'text', value: 'test', name: 'name', dataset: {}},
|
||||
});
|
||||
});
|
||||
|
||||
expect(consoleErrorSpy).toHaveBeenCalledWith('Failed to validate name');
|
||||
});
|
||||
});
|
||||
|
||||
describe('required fields', () => {
|
||||
it('form is not ready when required field is empty', async () => {
|
||||
const {result} = renderHook(() => useForm({
|
||||
defaultFormData: {name: ''},
|
||||
submitter: jest.fn(),
|
||||
}));
|
||||
|
||||
act(() => {
|
||||
result.current.getInputProps({name: 'name', required: true});
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.ready).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
it('form becomes ready when required field has value', async () => {
|
||||
const {result} = renderHook(() => useForm({
|
||||
defaultFormData: {name: 'has value'},
|
||||
submitter: jest.fn(),
|
||||
}));
|
||||
|
||||
act(() => {
|
||||
result.current.getInputProps({name: 'name', required: true});
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.ready).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
it('addRequires marks field as required', async () => {
|
||||
const {result} = renderHook(() => useForm({
|
||||
defaultFormData: {field: ''},
|
||||
submitter: jest.fn(),
|
||||
}));
|
||||
|
||||
expect(result.current.ready).toBe(true);
|
||||
|
||||
act(() => {
|
||||
result.current.getCustomProps({name: 'field', required: true});
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.ready).toBe(false);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('props generators', () => {
|
||||
describe('getInputProps', () => {
|
||||
it('returns props suitable for input elements', () => {
|
||||
const {result} = renderHook(() => useForm({
|
||||
defaultFormData: {email: 'test@example.com'},
|
||||
submitter: jest.fn(),
|
||||
}));
|
||||
|
||||
const [inputProps] = result.current.getInputProps({name: 'email'});
|
||||
|
||||
expect(inputProps).toHaveProperty('type', 'text');
|
||||
expect(inputProps).toHaveProperty('disabled', false);
|
||||
expect(inputProps).toHaveProperty('value', 'test@example.com');
|
||||
expect(inputProps).toHaveProperty('name', 'email');
|
||||
expect(inputProps).toHaveProperty('onChange');
|
||||
});
|
||||
|
||||
it('includes error when validation fails', async () => {
|
||||
const validator = () => 'Error message';
|
||||
const {result} = renderHook(() => useForm({
|
||||
defaultFormData: {field: 'value'},
|
||||
submitter: jest.fn(),
|
||||
}));
|
||||
|
||||
act(() => {
|
||||
result.current.getInputProps({name: 'field', validator});
|
||||
});
|
||||
|
||||
// Trigger validation
|
||||
act(() => {
|
||||
result.current.handleInputEvent({
|
||||
preventDefault: jest.fn(),
|
||||
target: {type: 'text', value: 'x', name: 'field', dataset: {}},
|
||||
});
|
||||
});
|
||||
|
||||
const [inputProps] = result.current.getInputProps({name: 'field', validator});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(inputProps.error).toBe('Error message');
|
||||
});
|
||||
});
|
||||
|
||||
it('applies URL validator for url type', () => {
|
||||
const {result} = renderHook(() => useForm({
|
||||
defaultFormData: {url: ''},
|
||||
submitter: jest.fn(),
|
||||
}));
|
||||
|
||||
const [inputProps, inputAttrs] = result.current.getInputProps({name: 'url', type: 'url'});
|
||||
|
||||
expect(inputProps.type).toBe('url');
|
||||
});
|
||||
});
|
||||
|
||||
describe('getCustomProps', () => {
|
||||
it('returns props for custom components', () => {
|
||||
const {result} = renderHook(() => useForm({
|
||||
defaultFormData: {tags: ['tag1', 'tag2']},
|
||||
submitter: jest.fn(),
|
||||
}));
|
||||
|
||||
const [customProps, attrs] = result.current.getCustomProps({
|
||||
name: 'tags',
|
||||
type: 'array',
|
||||
});
|
||||
|
||||
expect(customProps).toHaveProperty('disabled', false);
|
||||
expect(customProps).toHaveProperty('value', ['tag1', 'tag2']);
|
||||
expect(customProps).toHaveProperty('onChange');
|
||||
expect(customProps).toHaveProperty('data-path', 'tags');
|
||||
});
|
||||
|
||||
it('initializes undefined array fields to empty array', () => {
|
||||
const {result} = renderHook(() => useForm({
|
||||
defaultFormData: {},
|
||||
submitter: jest.fn(),
|
||||
}));
|
||||
|
||||
act(() => {
|
||||
result.current.getCustomProps({name: 'newArray', type: 'array'});
|
||||
});
|
||||
|
||||
expect(result.current.formData.newArray).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('getSelectionProps', () => {
|
||||
it('returns props for dropdown elements', () => {
|
||||
const {result} = renderHook(() => useForm({
|
||||
defaultFormData: {selected: 'option1'},
|
||||
submitter: jest.fn(),
|
||||
}));
|
||||
|
||||
const [selectionProps] = result.current.getSelectionProps({name: 'selected'});
|
||||
|
||||
expect(selectionProps).toHaveProperty('disabled', false);
|
||||
expect(selectionProps).toHaveProperty('value', 'option1');
|
||||
expect(selectionProps).toHaveProperty('onChange');
|
||||
});
|
||||
|
||||
it('onChange handler extracts value from event correctly', () => {
|
||||
const {result} = renderHook(() => useForm({
|
||||
defaultFormData: {selected: 'option1'},
|
||||
submitter: jest.fn(),
|
||||
}));
|
||||
|
||||
const [selectionProps] = result.current.getSelectionProps({name: 'selected'});
|
||||
|
||||
act(() => {
|
||||
// Semantic UI dropdown passes (event, {value})
|
||||
selectionProps.onChange({}, {value: 'option2'});
|
||||
});
|
||||
|
||||
expect(result.current.formData.selected).toBe('option2');
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('edge cases and error handling', () => {
|
||||
it('logs error when both clearOnSuccess and fetchOnSuccess are true', () => {
|
||||
renderHook(() => useForm({
|
||||
fetcher: jest.fn(),
|
||||
defaultFormData: {},
|
||||
submitter: jest.fn(),
|
||||
clearOnSuccess: true,
|
||||
fetchOnSuccess: true,
|
||||
}));
|
||||
|
||||
expect(consoleErrorSpy).toHaveBeenCalledWith('Cannot use both clearOnSuccess and fetchOnSuccess!');
|
||||
});
|
||||
|
||||
it('logs error when fetchOnSuccess is true without fetcher', () => {
|
||||
renderHook(() => useForm({
|
||||
defaultFormData: {},
|
||||
submitter: jest.fn(),
|
||||
fetchOnSuccess: true,
|
||||
}));
|
||||
|
||||
expect(consoleErrorSpy).toHaveBeenCalledWith('Cannot fetchOnSuccess without fetcher!');
|
||||
});
|
||||
|
||||
it('handles empty defaultFormData', () => {
|
||||
const {result} = renderHook(() => useForm({
|
||||
defaultFormData: {},
|
||||
submitter: jest.fn(),
|
||||
}));
|
||||
|
||||
expect(result.current.formData).toEqual({});
|
||||
expect(result.current.dirty).toBe(false);
|
||||
});
|
||||
|
||||
it('creates path when setting value on undefined nested path', () => {
|
||||
const {result} = renderHook(() => useForm({
|
||||
defaultFormData: {},
|
||||
submitter: jest.fn(),
|
||||
}));
|
||||
|
||||
act(() => {
|
||||
result.current.setValue('deeply.nested.value', 'test');
|
||||
});
|
||||
|
||||
expect(result.current.formData.deeply.nested.value).toBe('test');
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('commaSeparatedValidator', () => {
|
||||
it('returns null for valid comma-separated string', () => {
|
||||
expect(commaSeparatedValidator('a,b,c')).toBeUndefined();
|
||||
});
|
||||
|
||||
it('returns error when string ends with comma', () => {
|
||||
expect(commaSeparatedValidator('a,b,')).toBe('Cannot end with comma');
|
||||
});
|
||||
|
||||
it('returns error when string starts with comma', () => {
|
||||
expect(commaSeparatedValidator(',a,b')).toBe('Cannot start with comma');
|
||||
});
|
||||
|
||||
it('returns error for non-string input', () => {
|
||||
expect(commaSeparatedValidator(123)).toBe('Expected a string');
|
||||
expect(commaSeparatedValidator(null)).toBe('Expected a string');
|
||||
});
|
||||
});
|
||||
|
||||
describe('Form Components', () => {
|
||||
const createMockForm = (formData = {}) => {
|
||||
const mockForm = {
|
||||
disabled: false,
|
||||
formData,
|
||||
getInputProps: jest.fn(({name, path, validator, type, required, onChange}) => {
|
||||
const p = path || name;
|
||||
return [{
|
||||
type: type || 'text',
|
||||
disabled: false,
|
||||
value: formData[p] || '',
|
||||
name,
|
||||
onChange: jest.fn(),
|
||||
error: null,
|
||||
required: required ? null : undefined,
|
||||
'data-path': p,
|
||||
}, {valid: true, path: p, localSetValue: jest.fn()}];
|
||||
}),
|
||||
getCustomProps: jest.fn(({name, path}) => {
|
||||
const p = path || name;
|
||||
return [{
|
||||
disabled: false,
|
||||
value: formData[p],
|
||||
onChange: jest.fn(),
|
||||
'data-path': p,
|
||||
}, {valid: true, path: p, localSetValue: jest.fn()}];
|
||||
}),
|
||||
onSubmit: jest.fn(),
|
||||
};
|
||||
return mockForm;
|
||||
};
|
||||
|
||||
describe('InputForm', () => {
|
||||
it('renders with label', () => {
|
||||
const form = createMockForm({username: ''});
|
||||
|
||||
renderWithProviders(
|
||||
<InputForm
|
||||
form={form}
|
||||
name="username"
|
||||
label="Username"
|
||||
/>
|
||||
);
|
||||
|
||||
expect(screen.getByText('Username')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows required asterisk when required', () => {
|
||||
const form = createMockForm({email: ''});
|
||||
|
||||
renderWithProviders(
|
||||
<InputForm
|
||||
form={form}
|
||||
name="email"
|
||||
label="Email"
|
||||
required={true}
|
||||
/>
|
||||
);
|
||||
|
||||
expect(form.getInputProps).toHaveBeenCalledWith(
|
||||
expect.objectContaining({required: true})
|
||||
);
|
||||
});
|
||||
|
||||
it('passes placeholder to input', () => {
|
||||
const form = createMockForm({name: ''});
|
||||
|
||||
renderWithProviders(
|
||||
<InputForm
|
||||
form={form}
|
||||
name="name"
|
||||
label="Name"
|
||||
placeholder="Enter name"
|
||||
/>
|
||||
);
|
||||
|
||||
expect(screen.getByPlaceholderText('Enter name')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('respects disabled prop', () => {
|
||||
const form = createMockForm({field: ''});
|
||||
|
||||
renderWithProviders(
|
||||
<InputForm
|
||||
form={form}
|
||||
name="field"
|
||||
label="Field"
|
||||
disabled={true}
|
||||
/>
|
||||
);
|
||||
|
||||
const input = screen.getByRole('textbox');
|
||||
expect(input).toBeDisabled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('NumberInputForm', () => {
|
||||
it('renders as number input', () => {
|
||||
const form = createMockForm({count: 0});
|
||||
|
||||
renderWithProviders(
|
||||
<NumberInputForm
|
||||
form={form}
|
||||
name="count"
|
||||
label="Count"
|
||||
/>
|
||||
);
|
||||
|
||||
expect(form.getInputProps).toHaveBeenCalledWith(
|
||||
expect.objectContaining({type: 'number'})
|
||||
);
|
||||
});
|
||||
|
||||
it('applies min and max constraints', () => {
|
||||
const form = createMockForm({value: 5});
|
||||
|
||||
renderWithProviders(
|
||||
<NumberInputForm
|
||||
form={form}
|
||||
name="value"
|
||||
label="Value"
|
||||
min={0}
|
||||
max={100}
|
||||
/>
|
||||
);
|
||||
|
||||
const input = screen.getByRole('spinbutton');
|
||||
expect(input).toHaveAttribute('min', '0');
|
||||
expect(input).toHaveAttribute('max', '100');
|
||||
});
|
||||
});
|
||||
|
||||
describe('UrlInput', () => {
|
||||
it('renders URL input with label', () => {
|
||||
const form = createMockForm({url: ''});
|
||||
|
||||
renderWithProviders(
|
||||
<UrlInput form={form}/>
|
||||
);
|
||||
|
||||
expect(screen.getByText('URL')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('applies URL type', () => {
|
||||
const form = createMockForm({url: ''});
|
||||
|
||||
renderWithProviders(
|
||||
<UrlInput form={form}/>
|
||||
);
|
||||
|
||||
expect(form.getInputProps).toHaveBeenCalledWith(
|
||||
expect.objectContaining({type: 'url'})
|
||||
);
|
||||
});
|
||||
|
||||
it('is required by default', () => {
|
||||
const form = createMockForm({url: ''});
|
||||
|
||||
renderWithProviders(
|
||||
<UrlInput form={form}/>
|
||||
);
|
||||
|
||||
expect(form.getInputProps).toHaveBeenCalledWith(
|
||||
expect.objectContaining({required: true})
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('ToggleForm', () => {
|
||||
it('renders toggle with label', () => {
|
||||
const form = createMockForm({enabled: false});
|
||||
|
||||
renderWithProviders(
|
||||
<ToggleForm
|
||||
form={form}
|
||||
name="enabled"
|
||||
label="Enable Feature"
|
||||
/>
|
||||
);
|
||||
|
||||
expect(screen.getByText('Enable Feature')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('renders with checkbox input', () => {
|
||||
const form = createMockForm({active: true});
|
||||
|
||||
renderWithProviders(
|
||||
<ToggleForm
|
||||
form={form}
|
||||
name="active"
|
||||
label="Active"
|
||||
/>
|
||||
);
|
||||
|
||||
expect(screen.getByRole('checkbox')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
describe('UrlsTextarea', () => {
|
||||
it('renders textarea for multiple URLs', () => {
|
||||
const form = createMockForm({urls: ''});
|
||||
|
||||
renderWithProviders(
|
||||
<UrlsTextarea form={form}/>
|
||||
);
|
||||
|
||||
expect(screen.getByPlaceholderText('Enter one URL per line')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('calls getInputProps with correct name', () => {
|
||||
const form = createMockForm({urls: ''});
|
||||
|
||||
renderWithProviders(
|
||||
<UrlsTextarea form={form} name="urls"/>
|
||||
);
|
||||
|
||||
expect(form.getInputProps).toHaveBeenCalledWith(
|
||||
expect.objectContaining({name: 'urls'})
|
||||
);
|
||||
});
|
||||
});
|
||||
});
|
||||
48
app/src/setupTests.js
Normal file
48
app/src/setupTests.js
Normal file
|
|
@ -0,0 +1,48 @@
|
|||
// Jest setup file for React Testing Library
|
||||
// This file is automatically loaded by Create React App before running tests
|
||||
|
||||
import '@testing-library/jest-dom';
|
||||
|
||||
// Mock window.matchMedia (used by Semantic UI Media components)
|
||||
Object.defineProperty(window, 'matchMedia', {
|
||||
writable: true,
|
||||
value: jest.fn().mockImplementation(query => ({
|
||||
matches: false,
|
||||
media: query,
|
||||
onchange: null,
|
||||
addListener: jest.fn(), // deprecated
|
||||
removeListener: jest.fn(), // deprecated
|
||||
addEventListener: jest.fn(),
|
||||
removeEventListener: jest.fn(),
|
||||
dispatchEvent: jest.fn(),
|
||||
})),
|
||||
});
|
||||
|
||||
// Mock IntersectionObserver (if needed for lazy loading)
|
||||
global.IntersectionObserver = class IntersectionObserver {
|
||||
constructor() {}
|
||||
disconnect() {}
|
||||
observe() {}
|
||||
takeRecords() {
|
||||
return [];
|
||||
}
|
||||
unobserve() {}
|
||||
};
|
||||
|
||||
// Suppress console errors during tests (optional - uncomment if needed)
|
||||
// const originalError = console.error;
|
||||
// beforeAll(() => {
|
||||
// console.error = (...args) => {
|
||||
// if (
|
||||
// typeof args[0] === 'string' &&
|
||||
// args[0].includes('Warning: ReactDOM.render')
|
||||
// ) {
|
||||
// return;
|
||||
// }
|
||||
// originalError.call(console, ...args);
|
||||
// };
|
||||
// });
|
||||
//
|
||||
// afterAll(() => {
|
||||
// console.error = originalError;
|
||||
// });
|
||||
292
app/src/test-utils.js
Normal file
292
app/src/test-utils.js
Normal file
|
|
@ -0,0 +1,292 @@
|
|||
/**
|
||||
* Test utilities for React Testing Library
|
||||
* Provides custom render functions with necessary context providers
|
||||
*/
|
||||
|
||||
import React from 'react';
|
||||
import {render} from '@testing-library/react';
|
||||
import {BrowserRouter} from 'react-router-dom';
|
||||
import {MediaContextProvider, ThemeContext} from './contexts/contexts';
|
||||
|
||||
/**
|
||||
* Custom render function that wraps components with necessary providers
|
||||
* @param {React.Component} ui - Component to render
|
||||
* @param {Object} options - Render options
|
||||
* @param {boolean} options.inverted - Whether to use dark theme
|
||||
* @param {Object} options.themeContext - Custom theme context values
|
||||
* @param {boolean} options.withMedia - Include MediaContextProvider (default: false)
|
||||
* @param {Object} options.renderOptions - Additional React Testing Library options
|
||||
*/
|
||||
export function renderWithProviders(
|
||||
ui,
|
||||
{
|
||||
inverted = false,
|
||||
themeContext = {},
|
||||
withMedia = false,
|
||||
...renderOptions
|
||||
} = {}
|
||||
) {
|
||||
const defaultThemeContext = {
|
||||
inverted,
|
||||
setInverted: jest.fn(),
|
||||
// Theme components use different properties:
|
||||
i: inverted ? {inverted: true} : {inverted: undefined}, // For Semantic UI elements (Segment, Form, etc.)
|
||||
s: inverted ? {style: {backgroundColor: '#1B1C1D', color: '#dddddd'}} : {}, // For style inversion
|
||||
t: inverted ? {style: {color: '#eeeeee'}} : {}, // For text color inversion (Header, etc.)
|
||||
theme: inverted ? 'dark' : 'light',
|
||||
...themeContext
|
||||
};
|
||||
|
||||
function Wrapper({children}) {
|
||||
const content = (
|
||||
<BrowserRouter>
|
||||
<ThemeContext.Provider value={defaultThemeContext}>
|
||||
{children}
|
||||
</ThemeContext.Provider>
|
||||
</BrowserRouter>
|
||||
);
|
||||
|
||||
// Only wrap with MediaContextProvider if explicitly requested
|
||||
// (since it requires window.matchMedia which can be tricky in tests)
|
||||
if (withMedia) {
|
||||
return <MediaContextProvider>{content}</MediaContextProvider>;
|
||||
}
|
||||
|
||||
return content;
|
||||
}
|
||||
|
||||
return render(ui, {wrapper: Wrapper, ...renderOptions});
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a mock collection metadata object for testing
|
||||
*/
|
||||
export function createMockMetadata(kind = 'domain', overrides = {}) {
|
||||
return {
|
||||
kind,
|
||||
columns: [
|
||||
{key: 'domain', label: 'Domain', sortable: true},
|
||||
{key: 'archive_count', label: 'Archives', sortable: true, align: 'right'},
|
||||
{key: 'size', label: 'Size', sortable: true, align: 'right', format: 'bytes'},
|
||||
{key: 'tag_name', label: 'Tag', sortable: true},
|
||||
{key: 'actions', label: 'Manage', sortable: false, type: 'actions'},
|
||||
],
|
||||
fields: [
|
||||
{key: 'directory', label: 'Directory', type: 'text', 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'},
|
||||
],
|
||||
routes: {
|
||||
list: '/archive/domains',
|
||||
edit: '/archive/domain/:id/edit',
|
||||
search: '/archive',
|
||||
},
|
||||
messages: {
|
||||
no_directory: 'Set a directory to enable tagging',
|
||||
tag_will_move: 'Tagging will move files to a new directory'
|
||||
},
|
||||
...overrides
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a mock domain collection object for testing
|
||||
*/
|
||||
export function createMockDomain(overrides = {}) {
|
||||
return {
|
||||
id: 1,
|
||||
domain: 'example.com',
|
||||
archive_count: 42,
|
||||
size: 1024000,
|
||||
tag_name: null,
|
||||
directory: '',
|
||||
can_be_tagged: false,
|
||||
description: '',
|
||||
...overrides
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates multiple mock domains for list testing
|
||||
*/
|
||||
export function createMockDomains(count = 3) {
|
||||
return Array.from({length: count}, (_, i) => createMockDomain({
|
||||
id: i + 1,
|
||||
domain: `example${i + 1}.com`,
|
||||
archive_count: (i + 1) * 10,
|
||||
size: (i + 1) * 1000000,
|
||||
}));
|
||||
}
|
||||
|
||||
/**
|
||||
* Mock fetch implementation for API calls
|
||||
*/
|
||||
export function mockFetch(data, options = {}) {
|
||||
const {
|
||||
ok = true,
|
||||
status = 200,
|
||||
delay = 0,
|
||||
} = options;
|
||||
|
||||
return jest.fn(() =>
|
||||
new Promise((resolve) => {
|
||||
setTimeout(() => {
|
||||
resolve({
|
||||
ok,
|
||||
status,
|
||||
json: async () => data,
|
||||
text: async () => JSON.stringify(data),
|
||||
});
|
||||
}, delay);
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Mock API error response
|
||||
*/
|
||||
export function mockFetchError(error = 'An error occurred', status = 400) {
|
||||
return jest.fn(() =>
|
||||
Promise.resolve({
|
||||
ok: false,
|
||||
status,
|
||||
json: async () => ({error}),
|
||||
text: async () => error,
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Wait for async updates to complete
|
||||
* Useful for testing loading states
|
||||
*/
|
||||
export async function waitForLoadingToFinish() {
|
||||
const {waitFor} = await import('@testing-library/react');
|
||||
await waitFor(() => {}, {timeout: 100});
|
||||
}
|
||||
|
||||
/**
|
||||
* Test helper to render components in dark mode
|
||||
*
|
||||
* Usage:
|
||||
* renderInDarkMode(<MyComponent />)
|
||||
*
|
||||
* Verify inverted styling is applied:
|
||||
* const element = container.querySelector('.ui.segment.inverted');
|
||||
* expect(element).toBeInTheDocument();
|
||||
*/
|
||||
export function renderInDarkMode(ui, options = {}) {
|
||||
return renderWithProviders(ui, {
|
||||
inverted: true,
|
||||
...options
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Test helper to render components in light mode
|
||||
* (This is the default, but provided for explicitness in tests)
|
||||
*/
|
||||
export function renderInLightMode(ui, options = {}) {
|
||||
return renderWithProviders(ui, {
|
||||
inverted: false,
|
||||
...options
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper to check if an element has theme-aware (inverted) styling
|
||||
* Returns true if the element has the 'inverted' class
|
||||
*
|
||||
* Usage:
|
||||
* const segment = container.querySelector('.ui.segment');
|
||||
* expect(hasInvertedStyling(segment)).toBe(true);
|
||||
*/
|
||||
export function hasInvertedStyling(element) {
|
||||
return element && element.classList.contains('inverted');
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a test-friendly form object using real useForm hook
|
||||
*
|
||||
* This uses the actual useForm implementation, making tests more reliable.
|
||||
* The form starts in a "ready" state with the provided data.
|
||||
*
|
||||
* Usage:
|
||||
* const form = createTestForm({domain: 'test.com', directory: '/path'});
|
||||
* render(<CollectionEditForm form={form} metadata={metadata} />);
|
||||
*
|
||||
* // With overrides:
|
||||
* const form = createTestForm(data, {overrides: {loading: true, disabled: true}});
|
||||
*/
|
||||
export function createTestForm(initialData = {}, config = {}) {
|
||||
// Return a plain object that mimics the useForm interface without actual React hooks
|
||||
// This avoids async state updates that cause act() warnings in tests
|
||||
const _ = require('lodash');
|
||||
const formData = {...initialData};
|
||||
|
||||
const setValue = (path, newValue) => {
|
||||
_.set(formData, path, newValue);
|
||||
};
|
||||
|
||||
const form = {
|
||||
formData,
|
||||
ready: true,
|
||||
loading: false,
|
||||
disabled: false,
|
||||
dirty: false,
|
||||
errors: {},
|
||||
// Methods that update formData directly
|
||||
patchFormData: jest.fn((updates) => {
|
||||
Object.assign(formData, updates);
|
||||
}),
|
||||
reset: jest.fn(() => {
|
||||
Object.keys(formData).forEach(key => delete formData[key]);
|
||||
Object.assign(formData, initialData);
|
||||
}),
|
||||
onSubmit: config.submitter || jest.fn(async () => initialData),
|
||||
// Input helpers
|
||||
setError: jest.fn(),
|
||||
setValidator: jest.fn(),
|
||||
setValidValue: jest.fn(),
|
||||
setRequired: jest.fn(),
|
||||
// Property getter for field values
|
||||
get: (path) => _.get(formData, path),
|
||||
setValue: jest.fn((path, value) => setValue(path, value)),
|
||||
// getCustomProps - mimics the real useForm method
|
||||
getCustomProps: ({name, path, required = false, type = 'text'}) => {
|
||||
path = path || name;
|
||||
const value = _.get(formData, path);
|
||||
|
||||
const inputProps = {
|
||||
type,
|
||||
disabled: form.disabled,
|
||||
value: value !== undefined ? value : (type === 'array' ? [] : null),
|
||||
onChange: (newValue) => {
|
||||
setValue(path, newValue);
|
||||
},
|
||||
'data-path': path,
|
||||
};
|
||||
|
||||
const inputAttrs = {
|
||||
valid: true,
|
||||
path,
|
||||
localSetValue: (newValue) => setValue(path, newValue),
|
||||
};
|
||||
|
||||
return [inputProps, inputAttrs];
|
||||
},
|
||||
};
|
||||
|
||||
// Apply any overrides
|
||||
if (config.overrides) {
|
||||
Object.assign(form, config.overrides);
|
||||
}
|
||||
|
||||
return form;
|
||||
}
|
||||
|
||||
// Re-export everything from React Testing Library
|
||||
export * from '@testing-library/react';
|
||||
|
||||
// Override the default render with our custom one
|
||||
export {renderWithProviders as render};
|
||||
Loading…
Add table
Add a link
Reference in a new issue