mirror of
https://github.com/lrnselfreliance/wrolpi.git
synced 2026-11-25 01:16:18 -05:00
repos: add the Repos UI
* Repos table (CollectionTable), New Repo and Edit pages (frequency, mode, branch, description, tag, delete with an optional "also delete its files"). * A GitHub-like repo page: upstream, branch, latest commit, a status message when not yet downloaded or the last update failed, the file tree (directories through ?path=, files in the file preview), and each directory's README. * Global search: a Repos section under Other with escaped README headlines, Repos in the suggestions, and the search text sent to the Other estimate. * Settings: the Repos Directory field. * CollectionTable columns may `render` their cell. * Theme gallery: the repo summary, tree, and status icons. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
5506dc0a88
commit
0d1a988fa6
17 changed files with 1362 additions and 33 deletions
|
|
@ -1,5 +1,5 @@
|
|||
/*
|
||||
* The five Special Directories fields on /admin/settings.
|
||||
* The six Special Directories fields on /admin/settings.
|
||||
*
|
||||
* These are the fields that shipped printing their own prefix over their own value, and the
|
||||
* ones whose visible labels were never associated with their inputs. Both faults were
|
||||
|
|
@ -19,6 +19,7 @@ describe('Special Directories settings', () => {
|
|||
['Map Directory', 'map'],
|
||||
['Zims Directory', 'zims'],
|
||||
['Playlists Directory', 'playlists'],
|
||||
['Repos Directory', 'repos/%(repo_tag)s/%(repo_name)s'],
|
||||
];
|
||||
|
||||
beforeEach(() => {
|
||||
|
|
@ -38,8 +39,8 @@ describe('Special Directories settings', () => {
|
|||
|
||||
it('names every directory field, so they can be told apart', () => {
|
||||
/*
|
||||
* All five fields sit in one grid, hold similar-looking relative paths, and share the
|
||||
* same prefix. Without a name attached to the input, a screen reader user hears five
|
||||
* All six fields sit in one grid, hold similar-looking relative paths, and share the
|
||||
* same prefix. Without a name attached to the input, a screen reader user hears six
|
||||
* fields described only as "/media/wrolpi/" and cannot tell which one saves videos.
|
||||
*/
|
||||
directories.forEach(([label, value]) => {
|
||||
|
|
|
|||
|
|
@ -326,6 +326,13 @@ pre.wrap-text {
|
|||
padding: 0 0.25em;
|
||||
}
|
||||
|
||||
/* A repo's README is part of its page, not a modal; it grows with its content. */
|
||||
.repo-readme .markdown-preview {
|
||||
height: auto;
|
||||
min-height: 0;
|
||||
overflow: visible;
|
||||
}
|
||||
|
||||
.markdown-raw {
|
||||
margin: 0;
|
||||
white-space: pre-wrap;
|
||||
|
|
|
|||
|
|
@ -30,6 +30,7 @@ import {FilePreviewProvider} from "./components/FilePreview";
|
|||
import {TagsProvider} from "./Tags";
|
||||
import {ZimRoute} from "./components/Zim";
|
||||
import {PlaylistsRoute} from "./components/Playlists";
|
||||
import {ReposRoute} from "./components/Repos";
|
||||
import {DocsRoute} from "./components/Docs";
|
||||
import {FlasherRoute} from "./components/Flasher";
|
||||
import ErrorBoundary from "./components/ErrorBoundary";
|
||||
|
|
@ -117,6 +118,7 @@ const router = createBrowserRouter(createRoutesFromElements(<Route
|
|||
<Route path='map/*' element={<ErrorBoundary><MapRoute/></ErrorBoundary>}/>
|
||||
<Route path='zim/*' element={<ErrorBoundary><ZimRoute/></ErrorBoundary>}/>
|
||||
<Route path='playlists/*' element={<ErrorBoundary><PlaylistsRoute/></ErrorBoundary>}/>
|
||||
<Route path='repos/*' element={<ErrorBoundary><ReposRoute/></ErrorBoundary>}/>
|
||||
<Route path='files/*' element={<ErrorBoundary><FilesRoute/></ErrorBoundary>}/>
|
||||
<Route path='flasher/*' element={<ErrorBoundary><FlasherRoute/></ErrorBoundary>}/>
|
||||
</Route>));
|
||||
|
|
|
|||
|
|
@ -7,6 +7,7 @@ import {
|
|||
COLLECTIONS_API,
|
||||
DEFAULT_LIMIT,
|
||||
Downloaders,
|
||||
REPOS_API,
|
||||
VIDEOS_API,
|
||||
ZIM_API
|
||||
} from "./components/Vars";
|
||||
|
|
@ -406,6 +407,7 @@ export async function getSettings() {
|
|||
nav_color: content.nav_color,
|
||||
media_directory: content.media_directory,
|
||||
playlists_destination: content.playlists_destination,
|
||||
repos_destination: content.repos_destination,
|
||||
require_cookies_unlocked: content.require_cookies_unlocked,
|
||||
require_media_mounted: content.require_media_mounted,
|
||||
save_ffprobe_json: content.save_ffprobe_json,
|
||||
|
|
@ -927,6 +929,21 @@ export async function getCollectionTagInfo(collectionId, tagName) {
|
|||
}
|
||||
}
|
||||
|
||||
// Tag any Collection (and optionally move its directory).
|
||||
export async function tagCollection(collectionId, tagName, directory) {
|
||||
const body = {tag_name: tagName};
|
||||
if (directory) {
|
||||
body['directory'] = directory;
|
||||
}
|
||||
const response = await apiPost(`${COLLECTIONS_API}/${collectionId}/tag`, body);
|
||||
if (response.ok) {
|
||||
return await response.json();
|
||||
}
|
||||
const message = await getErrorMessage(response, 'Unable to tag. See server logs.');
|
||||
toast({type: 'error', title: 'Tag Error', description: message, time: 5000});
|
||||
throw new Error(message);
|
||||
}
|
||||
|
||||
export async function tagDomain(domainId, tagName, directory) {
|
||||
const body = {
|
||||
tag_name: tagName,
|
||||
|
|
@ -2051,6 +2068,7 @@ export async function searchSuggestions(search_str) {
|
|||
domains: content.domains,
|
||||
authors: content.authors || [],
|
||||
subjects: content.subjects || [],
|
||||
repos: content.repos || [],
|
||||
}
|
||||
} else {
|
||||
console.error('Failed to get file search suggestions!');
|
||||
|
|
@ -2089,8 +2107,8 @@ export async function searchEstimateZims(search_str, tagNames) {
|
|||
}
|
||||
}
|
||||
|
||||
export async function searchEstimateOthers(tagNames) {
|
||||
const body = {tag_names: tagNames};
|
||||
export async function searchEstimateOthers(tagNames, searchStr) {
|
||||
const body = {tag_names: tagNames, search_str: searchStr || null};
|
||||
const response = await apiPost(`${API_URI}/search_other_estimates`, body);
|
||||
if (response.ok) {
|
||||
const content = await response.json();
|
||||
|
|
@ -2488,3 +2506,79 @@ export async function moveBookmark(nodeId, parent_id, position = null) {
|
|||
export async function deleteBookmark(nodeId) {
|
||||
return await bookmarksModify(apiDelete(`${API_URI}/bookmarks/${nodeId}`), 'Could not delete bookmark');
|
||||
}
|
||||
|
||||
async function reposError(response, fallbackMessage) {
|
||||
const message = await getErrorMessage(response, fallbackMessage);
|
||||
toast({type: 'error', title: 'Repos Error', description: message, time: 5000});
|
||||
throw Error(message);
|
||||
}
|
||||
|
||||
export async function fetchRepos() {
|
||||
const response = await apiGet(REPOS_API);
|
||||
if (response.ok) {
|
||||
return (await response.json())['repos'];
|
||||
}
|
||||
await reposError(response, 'Failed to fetch repos.');
|
||||
}
|
||||
|
||||
export async function getRepo(repoId) {
|
||||
const response = await apiGet(`${REPOS_API}/${repoId}`);
|
||||
if (response.ok) {
|
||||
return (await response.json())['repo'];
|
||||
}
|
||||
await reposError(response, 'Failed to fetch repo.');
|
||||
}
|
||||
|
||||
// `repo`: {url, name?, tag_name?, frequency?, mode?, branch?, description?}
|
||||
export async function createRepo(repo) {
|
||||
const response = await apiPost(REPOS_API, repo);
|
||||
if (response.ok) {
|
||||
return (await response.json())['repo'];
|
||||
}
|
||||
await reposError(response, 'Failed to add repo.');
|
||||
}
|
||||
|
||||
// `changes`: {description?, frequency?, mode?, branch?}. An empty branch follows the remote's default branch.
|
||||
export async function updateRepo(repoId, changes) {
|
||||
const response = await apiPut(`${REPOS_API}/${repoId}`, changes);
|
||||
if (response.ok) {
|
||||
return (await response.json())['repo'];
|
||||
}
|
||||
await reposError(response, 'Failed to update repo.');
|
||||
}
|
||||
|
||||
export async function deleteRepo(repoId, deleteFiles = false) {
|
||||
const response = await apiDelete(`${REPOS_API}/${repoId}?delete_files=${deleteFiles ? 'true' : 'false'}`);
|
||||
if (!response.ok) {
|
||||
await reposError(response, 'Failed to delete repo.');
|
||||
}
|
||||
}
|
||||
|
||||
// Download the repo's updates now.
|
||||
export async function updateRepoNow(repoId) {
|
||||
const response = await apiPost(`${REPOS_API}/${repoId}/update`);
|
||||
if (!response.ok) {
|
||||
await reposError(response, 'Failed to start the repo update.');
|
||||
}
|
||||
}
|
||||
|
||||
// One directory of a repo's files: {path, entries: [{name, path, is_dir, size}], readme_path}.
|
||||
export async function getRepoTree(repoId, path) {
|
||||
const query = path ? `?path=${encodeURIComponent(path)}` : '';
|
||||
const response = await apiGet(`${REPOS_API}/${repoId}/tree${query}`);
|
||||
if (response.ok) {
|
||||
return await response.json();
|
||||
}
|
||||
await reposError(response, 'Failed to list the repo files.');
|
||||
}
|
||||
|
||||
// Repos matching the search (name and README) and/or the tags. Each has an escaped `readme_headline`.
|
||||
export async function searchRepos(searchStr, tagNames) {
|
||||
const body = {search_str: searchStr || null, tag_names: tagNames || []};
|
||||
const response = await apiPost(`${REPOS_API}/search`, body);
|
||||
if (response.ok) {
|
||||
const content = await response.json();
|
||||
return {repos: content.repos, total: content.totals.repos};
|
||||
}
|
||||
await reposError(response, 'Failed to search repos.');
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1121,7 +1121,7 @@ describe('a row of buttons', () => {
|
|||
* the two had been inline before.
|
||||
*
|
||||
* A row fixes it without touching the stack: the row is the stretched child, and it lays
|
||||
* its buttons out at their own width. Nine sites, so this scan rather than nine
|
||||
* its buttons out at their own width. Twelve sites, so this scan rather than twelve
|
||||
* assertions -- and a scan because a stretched button is still a working button.
|
||||
*/
|
||||
const offenders = [];
|
||||
|
|
@ -1140,8 +1140,8 @@ describe('a row of buttons', () => {
|
|||
}
|
||||
}
|
||||
|
||||
// Nine renders. Common.js declares it, and a declaration is not a `<BackButton`.
|
||||
expect(found).toBe(9);
|
||||
// Twelve renders. Common.js declares it, and a declaration is not a `<BackButton`.
|
||||
expect(found).toBe(12);
|
||||
|
||||
expect(offenders).toEqual([]);
|
||||
});
|
||||
|
|
|
|||
|
|
@ -61,6 +61,7 @@ const allLinks = [
|
|||
{text: 'Files', to: '/files', key: 'files'},
|
||||
{text: 'Playlists', to: '/playlists', key: 'playlists'},
|
||||
{text: 'Zim', to: '/zim', key: 'zim'},
|
||||
{text: 'Repos', to: '/repos', key: 'repos'},
|
||||
{text: 'Inventory', to: '/inventory', key: 'inventory'},
|
||||
// No `end` on these two: a tab stays current for the pages beneath it, and `end` would
|
||||
// drop the mark the moment either grows a sub-page.
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
import React from 'react';
|
||||
import {act, render, screen} from '../test-utils';
|
||||
import {OtherSearchView} from './Search';
|
||||
import {searchChannels} from '../api';
|
||||
import {searchChannels, searchRepos} from '../api';
|
||||
|
||||
// What the search page's Other tab shows for each state of useSearchChannels. "No Channels"
|
||||
// must only appear once the server has confirmed there are none.
|
||||
|
|
@ -9,11 +9,16 @@ import {searchChannels} from '../api';
|
|||
jest.mock('../api', () => ({
|
||||
...jest.requireActual('../api'),
|
||||
searchChannels: jest.fn(),
|
||||
searchRepos: jest.fn(),
|
||||
}));
|
||||
|
||||
const NO_CHANNELS = /No Channels/;
|
||||
|
||||
beforeEach(() => searchChannels.mockReset());
|
||||
beforeEach(() => {
|
||||
searchChannels.mockReset();
|
||||
searchRepos.mockReset();
|
||||
searchRepos.mockResolvedValue({repos: [], total: 0});
|
||||
});
|
||||
|
||||
test('pending: shows a loader, not "No Channels"', () => {
|
||||
searchChannels.mockReturnValue(new Promise(() => {
|
||||
|
|
@ -54,3 +59,61 @@ test('loaded: lists the channels', async () => {
|
|||
expect(screen.getByText('Cooking')).toBeInTheDocument();
|
||||
expect(screen.queryByText(NO_CHANNELS)).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
describe('Repos', () => {
|
||||
test('pending: the Repos section loads while Channels are shown', async () => {
|
||||
searchChannels.mockResolvedValue({channels: []});
|
||||
searchRepos.mockReturnValue(new Promise(() => {
|
||||
}));
|
||||
const {container} = render(<OtherSearchView loading={false}/>);
|
||||
await act(async () => {
|
||||
});
|
||||
expect(screen.getByText(NO_CHANNELS)).toBeInTheDocument();
|
||||
expect(container.querySelector('.wrolpi-loading')).toBeInTheDocument();
|
||||
expect(screen.queryByText('No Repos')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
test('empty: shows "No Repos"', async () => {
|
||||
searchChannels.mockResolvedValue({channels: []});
|
||||
render(<OtherSearchView loading={false}/>);
|
||||
await act(async () => {
|
||||
});
|
||||
expect(screen.getByText('No Repos')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
test('failed: shows an error only in the Repos section', async () => {
|
||||
searchChannels.mockResolvedValue({channels: [{id: 1, name: 'Cooking'}]});
|
||||
searchRepos.mockRejectedValue(new Error('boom'));
|
||||
const spy = jest.spyOn(console, 'error').mockImplementation(() => {
|
||||
});
|
||||
try {
|
||||
render(<OtherSearchView loading={false}/>);
|
||||
await act(async () => {
|
||||
});
|
||||
expect(screen.getByText('Cooking')).toBeInTheDocument();
|
||||
expect(screen.getByText(/Could not fetch the repos/)).toBeInTheDocument();
|
||||
} finally {
|
||||
spy.mockRestore();
|
||||
}
|
||||
});
|
||||
|
||||
test('loaded: lists repos by the search, with their README headline', async () => {
|
||||
searchChannels.mockResolvedValue({channels: []});
|
||||
searchRepos.mockResolvedValue({
|
||||
total: 1, repos: [{
|
||||
id: 7, name: 'kiwix-tools', tag_name: null,
|
||||
// The server escapes the README; only the highlight is markup.
|
||||
readme_headline: 'Serve <b>Zim</b> files <script>',
|
||||
}],
|
||||
});
|
||||
const searchParams = new URLSearchParams('q=zim&tag=Software');
|
||||
const {container} = render(<OtherSearchView loading={false}/>, {query: {searchParams}});
|
||||
await act(async () => {
|
||||
});
|
||||
expect(searchRepos).toHaveBeenCalledWith('zim', ['Software']);
|
||||
expect(screen.getByText('kiwix-tools').closest('a')).toHaveAttribute('href', '/repos/7');
|
||||
expect(container.querySelector('u').textContent).toBe('Zim');
|
||||
expect(container.querySelector('script')).toBeNull();
|
||||
expect(screen.getByText(/files <script>/)).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
|
|
|||
722
app/src/components/Repos.js
Normal file
722
app/src/components/Repos.js
Normal file
|
|
@ -0,0 +1,722 @@
|
|||
import React, {useContext, useEffect, useState} from "react";
|
||||
import {Link, Route, Routes, useNavigate, useParams} from "react-router";
|
||||
import {IconBrandGit, IconFile, IconFolder, IconGitBranch, IconGitCommit} from "@tabler/icons-react";
|
||||
import {
|
||||
Anchor,
|
||||
Button,
|
||||
Checkbox,
|
||||
Grid,
|
||||
Group,
|
||||
Header,
|
||||
Icon,
|
||||
Loading,
|
||||
Message,
|
||||
Modal,
|
||||
Panel,
|
||||
Select,
|
||||
Table,
|
||||
Textarea,
|
||||
TextInput,
|
||||
toast,
|
||||
Tooltip,
|
||||
} from "./ui";
|
||||
import {
|
||||
APIButton,
|
||||
BackButton,
|
||||
encodeMediaPath,
|
||||
ErrorMessage,
|
||||
humanFileSize,
|
||||
InfoPopup,
|
||||
isoDatetimeToAgoPopup,
|
||||
PageContainer,
|
||||
SearchInput,
|
||||
useTitle,
|
||||
} from "./Common";
|
||||
import {useOneQuery, useWROLMode} from "../hooks/customHooks";
|
||||
import {CollectionTable} from "./collections/CollectionTable";
|
||||
import {CollectionTagModal} from "./collections/CollectionTagModal";
|
||||
import {
|
||||
createRepo,
|
||||
deleteRepo,
|
||||
fetchRepos,
|
||||
getCollectionTagInfo,
|
||||
getFile,
|
||||
getRepo,
|
||||
getRepoTree,
|
||||
tagCollection,
|
||||
updateRepo,
|
||||
updateRepoNow,
|
||||
} from "../api";
|
||||
import {TagsContext, TagsSelector} from "../Tags";
|
||||
import {FilePreviewContext} from "./FilePreview";
|
||||
import {isMarkdownFile, MarkdownPreview} from "./MarkdownPreview";
|
||||
import {longFrequencyOptions, weeklyOption} from "./Vars";
|
||||
|
||||
export const REPO_MODE_OPTIONS = [
|
||||
{value: 'full', label: 'Full history'},
|
||||
{value: 'snapshot', label: 'Snapshot (latest commit only)'},
|
||||
];
|
||||
|
||||
const FREQUENCY_OPTIONS = longFrequencyOptions.map(i => ({value: String(i.value), label: i.text}));
|
||||
|
||||
// The "Name" column links to the repo's page; the "Edit" button links to the edit page.
|
||||
const REPO_ROUTES = {search: '/repos/:id', edit: '/repos/:id/edit', id_field: 'id'};
|
||||
|
||||
export const REPO_COLUMNS = [
|
||||
{key: 'name', label: 'Name', sortable: true, width: 4, render: (repo) => <RepoName repo={repo}/>},
|
||||
{key: 'tag_name', label: 'Tag', sortable: true, width: 2},
|
||||
{
|
||||
key: 'branch', label: 'Branch', sortable: false, width: 2, hideOnMobile: true,
|
||||
render: (repo) => repo.branch || repo.default_branch,
|
||||
},
|
||||
{
|
||||
key: 'head_date', label: 'Last Commit', sortable: true, width: 2,
|
||||
render: (repo) => repo.head_date ? isoDatetimeToAgoPopup(repo.head_date) : null,
|
||||
},
|
||||
{key: 'size', label: 'Size', sortable: true, align: 'right', format: 'bytes', width: 2, hideOnMobile: true},
|
||||
{
|
||||
key: 'frequency', label: 'Download Frequency', sortable: true, format: 'frequency', width: 2,
|
||||
hideOnMobile: true,
|
||||
},
|
||||
{key: 'actions', label: 'Manage', sortable: false, type: 'actions', width: 1},
|
||||
];
|
||||
|
||||
/** A repo URL is only ever shown as a link when it is https (the API refuses anything else). */
|
||||
export function safeRepoHref(url) {
|
||||
try {
|
||||
const parsed = new URL(url);
|
||||
return parsed.protocol === 'https:' ? parsed.href : null;
|
||||
} catch (e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** The media URL of a file in a repo; `path` is relative to the repo. */
|
||||
export function repoFileURL(repo, path) {
|
||||
return `/media/${encodeMediaPath(`${repo.directory}/${path}`)}`;
|
||||
}
|
||||
|
||||
export function RepoStatusIcon({repo}) {
|
||||
if (repo.download_error) {
|
||||
return <Tooltip label='The last update failed'>
|
||||
<span><Icon name='warning sign' style={{color: 'var(--warning)'}}/></span>
|
||||
</Tooltip>;
|
||||
}
|
||||
if (!repo.head_sha) {
|
||||
return <Tooltip label='Not downloaded yet'>
|
||||
<span><Icon name='download' style={{color: 'var(--muted)'}}/></span>
|
||||
</Tooltip>;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function RepoName({repo}) {
|
||||
return <span style={{display: 'inline-flex', alignItems: 'center', gap: '0.4em'}}>
|
||||
{repo.name}
|
||||
<RepoStatusIcon repo={repo}/>
|
||||
</span>;
|
||||
}
|
||||
|
||||
function useRepos() {
|
||||
const [repos, setRepos] = useState(null); // null=loading, []/[...]=ok, undefined=error
|
||||
|
||||
const refetch = async () => {
|
||||
try {
|
||||
setRepos(await fetchRepos());
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
setRepos(undefined);
|
||||
}
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
refetch();
|
||||
}, []);
|
||||
|
||||
return {repos, refetch};
|
||||
}
|
||||
|
||||
function useRepo(repoId) {
|
||||
const [repo, setRepo] = useState(null); // null=loading, undefined=error
|
||||
|
||||
const refetch = async () => {
|
||||
try {
|
||||
setRepo(await getRepo(repoId));
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
setRepo(undefined);
|
||||
}
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
setRepo(null);
|
||||
refetch();
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [repoId]);
|
||||
|
||||
return {repo, refetch};
|
||||
}
|
||||
|
||||
function useRepoTree(repoId, path, enabled) {
|
||||
const [tree, setTree] = useState(null); // null=loading, undefined=error
|
||||
|
||||
useEffect(() => {
|
||||
if (!enabled) {
|
||||
return;
|
||||
}
|
||||
let current = true;
|
||||
setTree(null);
|
||||
getRepoTree(repoId, path)
|
||||
.then(newTree => current && setTree(newTree))
|
||||
.catch(e => {
|
||||
console.error(e);
|
||||
if (current) setTree(undefined);
|
||||
});
|
||||
return () => {
|
||||
current = false;
|
||||
};
|
||||
}, [repoId, path, enabled]);
|
||||
|
||||
return tree;
|
||||
}
|
||||
|
||||
export function ReposPage() {
|
||||
useTitle('Repos');
|
||||
const {repos} = useRepos();
|
||||
const [searchStr, setSearchStr] = useOneQuery('name');
|
||||
const searchInputRef = React.useRef();
|
||||
|
||||
const header = <Group justify='space-between' align='flex-end' wrap='wrap'>
|
||||
<SearchInput
|
||||
placeholder='Repo filter...'
|
||||
size='large'
|
||||
searchStr={searchStr}
|
||||
disabled={!Array.isArray(repos) || repos.length === 0}
|
||||
onClear={() => setSearchStr('')}
|
||||
onChange={setSearchStr}
|
||||
onSubmit={null}
|
||||
inputRef={searchInputRef}
|
||||
/>
|
||||
<Button role='primary' component={Link} to='/repos/new'>New Repo</Button>
|
||||
</Group>;
|
||||
|
||||
return <>
|
||||
{header}
|
||||
<CollectionTable
|
||||
collections={repos}
|
||||
columns={REPO_COLUMNS}
|
||||
routes={REPO_ROUTES}
|
||||
searchStr={searchStr}
|
||||
emptyMessage='No repos yet. Add a git repository to keep a copy of it.'
|
||||
/>
|
||||
</>;
|
||||
}
|
||||
|
||||
/** The name, upstream, branch and latest commit of a Repo. */
|
||||
export function RepoSummary({repo}) {
|
||||
const {SingleTag} = useContext(TagsContext);
|
||||
const upstream = safeRepoHref(repo.url);
|
||||
const branch = repo.branch || repo.default_branch;
|
||||
const muted = {color: 'var(--muted)'};
|
||||
const meta = {display: 'inline-flex', alignItems: 'center', gap: '0.3em'};
|
||||
|
||||
return <>
|
||||
<Header as='h1'>
|
||||
<span style={{display: 'inline-flex', alignItems: 'center', gap: '0.4em', flexWrap: 'wrap'}}>
|
||||
<IconBrandGit size={28}/>
|
||||
<span style={{overflowWrap: 'anywhere'}}>{repo.name}</span>
|
||||
{repo.tag_name && <SingleTag name={repo.tag_name}/>}
|
||||
</span>
|
||||
</Header>
|
||||
{repo.description && <p>{repo.description}</p>}
|
||||
<Group gap='lg' wrap='wrap' style={{marginBottom: '0.5em'}}>
|
||||
{upstream && <a href={upstream} target='_blank' rel='noopener noreferrer'
|
||||
style={{...meta, overflowWrap: 'anywhere'}}>
|
||||
<Icon name='external' size='small'/>{repo.url}
|
||||
</a>}
|
||||
{branch && <span style={meta}>
|
||||
<IconGitBranch size={16}/>{branch}
|
||||
{!repo.branch && <span style={muted}>(default)</span>}
|
||||
</span>}
|
||||
<span style={muted}>
|
||||
{repo.mode === 'snapshot' ? 'Snapshot' : 'Full history'}
|
||||
{repo.size ? ` · ${humanFileSize(repo.size)}` : ''}
|
||||
</span>
|
||||
</Group>
|
||||
{repo.head_sha && <Panel style={{display: 'flex', alignItems: 'center', gap: '0.5em', flexWrap: 'wrap'}}>
|
||||
<IconGitCommit size={18}/>
|
||||
<code>{repo.head_sha.slice(0, 7)}</code>
|
||||
<span style={{flex: '1 1 200px', overflowWrap: 'anywhere'}}>{repo.head_message}</span>
|
||||
{repo.head_date && <span style={muted}>{isoDatetimeToAgoPopup(repo.head_date)}</span>}
|
||||
</Panel>}
|
||||
<RepoStatusMessage repo={repo}/>
|
||||
</>;
|
||||
}
|
||||
|
||||
/** Explains a Repo that has not been downloaded, or whose last update failed. */
|
||||
export function RepoStatusMessage({repo}) {
|
||||
if (repo.download_error) {
|
||||
return <Message kind='warning' title='The last update failed'>
|
||||
<p>The files below are from the last successful update. The update will be tried again.</p>
|
||||
<pre style={{whiteSpace: 'pre-wrap', overflowWrap: 'anywhere', maxHeight: '12em', overflow: 'auto'}}>
|
||||
{repo.download_error.trim().split('\n').slice(-8).join('\n')}
|
||||
</pre>
|
||||
</Message>;
|
||||
}
|
||||
if (!repo.head_sha) {
|
||||
return <Message kind='info' title='Not downloaded yet'>
|
||||
<p>This repo will be cloned soon. Its progress is on the <Link to='/admin'>Downloads</Link> page.</p>
|
||||
</Message>;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** The path within a repo, each directory a link back to it. */
|
||||
export function RepoBreadcrumb({name, path, onNavigate}) {
|
||||
const parts = path ? path.split('/') : [];
|
||||
const crumb = (label, target, key) => <Anchor key={key} component='button' type='button'
|
||||
onClick={() => onNavigate(target)}>{label}</Anchor>;
|
||||
return <div style={{display: 'flex', flexWrap: 'wrap', gap: '0.3em', overflowWrap: 'anywhere'}}>
|
||||
{parts.length ? crumb(name, '', 'root') : <strong>{name}</strong>}
|
||||
{parts.map((part, idx) => <React.Fragment key={idx}>
|
||||
<span style={{color: 'var(--muted)'}}>/</span>
|
||||
{idx === parts.length - 1
|
||||
? <strong>{part}</strong>
|
||||
: crumb(part, parts.slice(0, idx + 1).join('/'), idx)}
|
||||
</React.Fragment>)}
|
||||
</div>;
|
||||
}
|
||||
|
||||
/** One directory of a repo's files: directories first, then files. */
|
||||
export function RepoTreeTable({path, entries, onOpenDirectory, onOpenFile}) {
|
||||
const parent = path ? path.split('/').slice(0, -1).join('/') : null;
|
||||
const link = (onClick, children) => <Anchor component='button' type='button' onClick={onClick}
|
||||
style={{display: 'inline-flex', alignItems: 'center', gap: '0.4em',
|
||||
overflowWrap: 'anywhere', textAlign: 'left'}}>
|
||||
{children}
|
||||
</Anchor>;
|
||||
|
||||
return <Table striped>
|
||||
<Table.Body>
|
||||
{parent !== null && <Table.Row>
|
||||
<Table.Cell>{link(() => onOpenDirectory(parent), <><IconFolder size={18}/>..</>)}</Table.Cell>
|
||||
<Table.Cell/>
|
||||
</Table.Row>}
|
||||
{entries.map(entry => <Table.Row key={entry.path}>
|
||||
<Table.Cell>
|
||||
{entry.is_dir
|
||||
? link(() => onOpenDirectory(entry.path), <><IconFolder size={18}/>{entry.name}</>)
|
||||
: link(() => onOpenFile(entry), <><IconFile size={18}/>{entry.name}</>)}
|
||||
</Table.Cell>
|
||||
<Table.Cell style={{textAlign: 'right', color: 'var(--muted)', whiteSpace: 'nowrap'}}>
|
||||
{entry.is_dir ? '' : humanFileSize(entry.size)}
|
||||
</Table.Cell>
|
||||
</Table.Row>)}
|
||||
{entries.length === 0 && <Table.Row>
|
||||
<Table.Cell colSpan={2}>This directory is empty</Table.Cell>
|
||||
</Table.Row>}
|
||||
</Table.Body>
|
||||
</Table>;
|
||||
}
|
||||
|
||||
function PlainTextPreview({url}) {
|
||||
const [text, setText] = useState(null);
|
||||
const [error, setError] = useState(null);
|
||||
|
||||
useEffect(() => {
|
||||
const controller = new AbortController();
|
||||
setText(null);
|
||||
setError(null);
|
||||
fetch(url, {signal: controller.signal})
|
||||
.then(response => {
|
||||
if (!response.ok) {
|
||||
throw new Error(`${response.status} ${response.statusText}`);
|
||||
}
|
||||
return response.text();
|
||||
})
|
||||
.then(setText)
|
||||
.catch(e => e.name !== 'AbortError' && setError(e.message));
|
||||
return () => controller.abort();
|
||||
}, [url]);
|
||||
|
||||
if (error) {
|
||||
return <ErrorMessage>Could not read the README: {error}</ErrorMessage>;
|
||||
}
|
||||
if (text === null) {
|
||||
return <Loading/>;
|
||||
}
|
||||
return <pre style={{whiteSpace: 'pre-wrap', overflowWrap: 'anywhere'}}>{text}</pre>;
|
||||
}
|
||||
|
||||
/** A repo's README, formatted when it is markdown. */
|
||||
export function RepoReadme({repo, readmePath}) {
|
||||
const url = repoFileURL(repo, readmePath);
|
||||
const name = readmePath.split('/').pop();
|
||||
return <Panel className='repo-readme'>
|
||||
<Header as='h4'>
|
||||
<span style={{display: 'inline-flex', alignItems: 'center', gap: '0.4em'}}>
|
||||
<Icon name='book' size='small'/>{name}
|
||||
</span>
|
||||
</Header>
|
||||
{isMarkdownFile('text/plain', readmePath.toLowerCase())
|
||||
? <MarkdownPreview url={url}/>
|
||||
: <PlainTextPreview url={url}/>}
|
||||
</Panel>;
|
||||
}
|
||||
|
||||
export function RepoViewPage() {
|
||||
const {repoId} = useParams();
|
||||
const {repo, refetch} = useRepo(repoId);
|
||||
const [path, setPath] = useOneQuery('path');
|
||||
const {setPreviewFile} = useContext(FilePreviewContext);
|
||||
const tree = useRepoTree(repoId, path || '', !!repo?.head_sha);
|
||||
|
||||
useTitle(repo?.name ? `${repo.name} Repo` : 'Repo');
|
||||
|
||||
if (repo === undefined) {
|
||||
return <ErrorMessage>Could not fetch the repo</ErrorMessage>;
|
||||
}
|
||||
if (repo === null) {
|
||||
return <Loading/>;
|
||||
}
|
||||
|
||||
const handleUpdate = async () => {
|
||||
await updateRepoNow(repoId);
|
||||
toast({type: 'info', title: 'Updating repo', description: repo.name, time: 3000});
|
||||
await refetch();
|
||||
};
|
||||
|
||||
const openFile = async (entry) => {
|
||||
const file = await getFile(`${repo.directory}/${entry.path}`, true);
|
||||
if (file) {
|
||||
setPreviewFile(file);
|
||||
}
|
||||
};
|
||||
|
||||
let files = null;
|
||||
if (repo.head_sha) {
|
||||
if (tree === undefined) {
|
||||
files = <ErrorMessage>Could not list the repo's files</ErrorMessage>;
|
||||
} else if (tree === null) {
|
||||
files = <Loading/>;
|
||||
} else {
|
||||
files = <>
|
||||
<Panel>
|
||||
<RepoBreadcrumb name={repo.name} path={tree.path} onNavigate={setPath}/>
|
||||
<RepoTreeTable path={tree.path} entries={tree.entries} onOpenDirectory={setPath}
|
||||
onOpenFile={openFile}/>
|
||||
</Panel>
|
||||
{tree.readme_path && <RepoReadme repo={repo} readmePath={tree.readme_path}/>}
|
||||
</>;
|
||||
}
|
||||
}
|
||||
|
||||
return <>
|
||||
<div className='wrolpi-button-row'>
|
||||
<BackButton/>
|
||||
<Button component={Link} to={`/repos/${repoId}/edit`} icon='edit'>Edit</Button>
|
||||
<APIButton color='blue' icon='refresh' onClick={handleUpdate} obeyWROLMode={true}>Update Now</APIButton>
|
||||
</div>
|
||||
<RepoSummary repo={repo}/>
|
||||
{files}
|
||||
</>;
|
||||
}
|
||||
|
||||
/** The URL's last path segment, which the API uses as the default name. */
|
||||
export function repoNameFromURL(url) {
|
||||
try {
|
||||
const parts = new URL(url).pathname.replace(/\/tree\/.*$/, '').split('/').filter(Boolean);
|
||||
return (parts.pop() || '').replace(/\.git$/, '');
|
||||
} catch (e) {
|
||||
return '';
|
||||
}
|
||||
}
|
||||
|
||||
export function RepoNewPage() {
|
||||
useTitle('New Repo');
|
||||
const navigate = useNavigate();
|
||||
const wrolMode = useWROLMode();
|
||||
const [url, setUrl] = useState('');
|
||||
const [name, setName] = useState('');
|
||||
const [tagName, setTagName] = useState(null);
|
||||
const [frequency, setFrequency] = useState(String(weeklyOption.value));
|
||||
const [mode, setMode] = useState('full');
|
||||
const [branch, setBranch] = useState('');
|
||||
const [description, setDescription] = useState('');
|
||||
const [submitting, setSubmitting] = useState(false);
|
||||
|
||||
const urlIsValid = !!safeRepoHref(url.trim());
|
||||
|
||||
const handleSubmit = async (e) => {
|
||||
e.preventDefault();
|
||||
if (!urlIsValid) return;
|
||||
setSubmitting(true);
|
||||
try {
|
||||
const repo = await createRepo({
|
||||
url: url.trim(),
|
||||
name: name.trim() || null,
|
||||
tag_name: tagName,
|
||||
frequency: parseInt(frequency),
|
||||
mode,
|
||||
branch: branch.trim() || null,
|
||||
description: description.trim() || null,
|
||||
});
|
||||
toast({type: 'success', title: 'Repo added', description: repo.name, time: 3000});
|
||||
navigate(`/repos/${repo.id}`);
|
||||
} catch (e) {
|
||||
// Error toast already shown by the API client.
|
||||
} finally {
|
||||
setSubmitting(false);
|
||||
}
|
||||
};
|
||||
|
||||
return <>
|
||||
<div className='wrolpi-button-row'><BackButton/></div>
|
||||
<Panel>
|
||||
<Header as='h1'>New Repo</Header>
|
||||
<p>
|
||||
WROLPi clones the repository, then keeps it up to date. Only <code>https://</code> URLs are
|
||||
supported.
|
||||
</p>
|
||||
<form onSubmit={handleSubmit}>
|
||||
<Grid>
|
||||
<Grid.Col span={12}>
|
||||
<TextInput
|
||||
autoFocus
|
||||
required
|
||||
label='URL'
|
||||
placeholder='https://github.com/kiwix/kiwix-tools'
|
||||
value={url}
|
||||
error={url && !urlIsValid ? 'Must be an https:// URL' : null}
|
||||
onChange={(e) => setUrl(e.currentTarget.value)}
|
||||
/>
|
||||
</Grid.Col>
|
||||
<Grid.Col span={{base: 12, sm: 6}}>
|
||||
<TextInput
|
||||
label='Name'
|
||||
placeholder={repoNameFromURL(url) || 'From the URL'}
|
||||
value={name}
|
||||
onChange={(e) => setName(e.currentTarget.value)}
|
||||
/>
|
||||
</Grid.Col>
|
||||
<Grid.Col span={{base: 12, sm: 6}}>
|
||||
<label style={{display: 'flex', alignItems: 'center', gap: '0.3em', marginBottom: '0.3em'}}>
|
||||
Tag
|
||||
<InfoPopup content='Optional. A tagged repo lives under its tag in the Repos Directory.'/>
|
||||
</label>
|
||||
<TagsSelector
|
||||
limit={1}
|
||||
selectedTagNames={tagName ? [tagName] : []}
|
||||
onAdd={setTagName}
|
||||
onRemove={() => setTagName(null)}
|
||||
/>
|
||||
</Grid.Col>
|
||||
<RepoSettingsFields frequency={frequency} setFrequency={setFrequency} mode={mode}
|
||||
setMode={setMode} branch={branch} setBranch={setBranch}/>
|
||||
<Grid.Col span={12}>
|
||||
<Textarea
|
||||
label='Description'
|
||||
placeholder='Optional description'
|
||||
value={description}
|
||||
onChange={(e) => setDescription(e.currentTarget.value)}
|
||||
rows={2}
|
||||
/>
|
||||
</Grid.Col>
|
||||
<Grid.Col span={12}>
|
||||
<Button role='save' type='submit' disabled={!urlIsValid || submitting || wrolMode}>
|
||||
Add Repo
|
||||
</Button>
|
||||
</Grid.Col>
|
||||
</Grid>
|
||||
</form>
|
||||
</Panel>
|
||||
</>;
|
||||
}
|
||||
|
||||
/** The update frequency, mode and branch of a Repo; shared by the new and edit pages. */
|
||||
export function RepoSettingsFields({frequency, setFrequency, mode, setMode, branch, setBranch, disabled}) {
|
||||
return <>
|
||||
<Grid.Col span={{base: 12, sm: 4}}>
|
||||
<Select
|
||||
label='Download Frequency'
|
||||
description='How often to check for updates'
|
||||
data={FREQUENCY_OPTIONS}
|
||||
value={frequency}
|
||||
onChange={(value) => value && setFrequency(value)}
|
||||
allowDeselect={false}
|
||||
disabled={disabled}
|
||||
/>
|
||||
</Grid.Col>
|
||||
<Grid.Col span={{base: 12, sm: 4}}>
|
||||
<Select
|
||||
label='Mode'
|
||||
description={mode === 'full' ? 'Every branch, tag and commit' : 'Uses the least space'}
|
||||
data={REPO_MODE_OPTIONS}
|
||||
value={mode}
|
||||
onChange={(value) => value && setMode(value)}
|
||||
allowDeselect={false}
|
||||
disabled={disabled}
|
||||
/>
|
||||
</Grid.Col>
|
||||
<Grid.Col span={{base: 12, sm: 4}}>
|
||||
<TextInput
|
||||
label='Branch'
|
||||
description='Empty follows the default branch'
|
||||
placeholder='Default branch'
|
||||
value={branch}
|
||||
onChange={(e) => setBranch(e.currentTarget.value)}
|
||||
disabled={disabled}
|
||||
/>
|
||||
</Grid.Col>
|
||||
</>;
|
||||
}
|
||||
|
||||
export function RepoEditPage() {
|
||||
const {repoId} = useParams();
|
||||
const {repo, refetch} = useRepo(repoId);
|
||||
const navigate = useNavigate();
|
||||
const wrolMode = useWROLMode();
|
||||
const [frequency, setFrequency] = useState(String(weeklyOption.value));
|
||||
const [mode, setMode] = useState('full');
|
||||
const [branch, setBranch] = useState('');
|
||||
const [description, setDescription] = useState('');
|
||||
const [tagModalOpen, setTagModalOpen] = useState(false);
|
||||
const [deleteModalOpen, setDeleteModalOpen] = useState(false);
|
||||
const [deleteFiles, setDeleteFiles] = useState(false);
|
||||
|
||||
useTitle(repo?.name ? `Edit ${repo.name} Repo` : 'Edit Repo');
|
||||
|
||||
// Seed the form once the repo loads (keyed on id so a refetch doesn't clobber edits).
|
||||
const repoDbId = repo?.id;
|
||||
useEffect(() => {
|
||||
if (repoDbId) {
|
||||
setFrequency(String(repo.frequency || weeklyOption.value));
|
||||
setMode(repo.mode || 'full');
|
||||
setBranch(repo.branch || '');
|
||||
setDescription(repo.description || '');
|
||||
}
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [repoDbId]);
|
||||
|
||||
if (repo === undefined) {
|
||||
return <ErrorMessage>Could not fetch the repo</ErrorMessage>;
|
||||
}
|
||||
if (repo === null) {
|
||||
return <Loading/>;
|
||||
}
|
||||
|
||||
const handleSave = async (e) => {
|
||||
e.preventDefault();
|
||||
try {
|
||||
await updateRepo(repoId, {
|
||||
description: description.trim(),
|
||||
frequency: parseInt(frequency),
|
||||
mode,
|
||||
branch: branch.trim(),
|
||||
});
|
||||
toast({type: 'success', title: 'Repo Updated', description: repo.name, time: 3000});
|
||||
await refetch();
|
||||
} catch (e) {
|
||||
// Error toast already shown by the API client.
|
||||
}
|
||||
};
|
||||
|
||||
const handleTagSave = async (tagName, directory) => {
|
||||
try {
|
||||
await tagCollection(repo.collection_id, tagName, directory);
|
||||
} catch (e) {
|
||||
// Error toast already shown by the API client.
|
||||
} finally {
|
||||
setTimeout(refetch, 500);
|
||||
}
|
||||
};
|
||||
|
||||
const handleDelete = async () => {
|
||||
try {
|
||||
await deleteRepo(repoId, deleteFiles);
|
||||
toast({type: 'success', title: 'Repo deleted', description: repo.name, time: 3000});
|
||||
navigate('/repos');
|
||||
} catch (e) {
|
||||
// Error toast already shown by the API client.
|
||||
}
|
||||
};
|
||||
|
||||
const deleteModal = <Modal open={deleteModalOpen} onClose={() => setDeleteModalOpen(false)} size='tiny'>
|
||||
<Modal.Header>Delete Repo?</Modal.Header>
|
||||
<Modal.Content>
|
||||
<p>WROLPi will stop updating <strong>{repo.name}</strong>.</p>
|
||||
<Checkbox
|
||||
label={`Also delete its files (${repo.directory})`}
|
||||
checked={deleteFiles}
|
||||
onChange={(e) => setDeleteFiles(e.currentTarget.checked)}
|
||||
/>
|
||||
</Modal.Content>
|
||||
<Modal.Actions>
|
||||
<Button role='cancel' onClick={() => setDeleteModalOpen(false)}>Cancel</Button>
|
||||
<Button role='danger' onClick={handleDelete}>Delete</Button>
|
||||
</Modal.Actions>
|
||||
</Modal>;
|
||||
|
||||
return <>
|
||||
<div className='wrolpi-button-row'>
|
||||
<BackButton/>
|
||||
<Button component={Link} to={`/repos/${repoId}`}>View</Button>
|
||||
</div>
|
||||
<Panel>
|
||||
<Header as='h1'>Edit {repo.name}</Header>
|
||||
<p style={{overflowWrap: 'anywhere'}}>
|
||||
<code>{repo.url}</code><br/>
|
||||
Directory: <code>{repo.directory}</code>
|
||||
</p>
|
||||
{wrolMode && <Message kind='info' title='Repo editing is disabled while in WROL Mode.'/>}
|
||||
<form onSubmit={handleSave}>
|
||||
<Grid>
|
||||
<RepoSettingsFields frequency={frequency} setFrequency={setFrequency} mode={mode}
|
||||
setMode={setMode} branch={branch} setBranch={setBranch}
|
||||
disabled={wrolMode}/>
|
||||
<Grid.Col span={12}>
|
||||
<Textarea
|
||||
label='Description'
|
||||
placeholder='Optional description'
|
||||
value={description}
|
||||
onChange={(e) => setDescription(e.currentTarget.value)}
|
||||
rows={2}
|
||||
disabled={wrolMode}
|
||||
/>
|
||||
</Grid.Col>
|
||||
<Grid.Col span={12}>
|
||||
<div className='wrolpi-button-row'>
|
||||
<Button role='save' type='submit' disabled={wrolMode}>Save</Button>
|
||||
<Button type='button' color='violet' disabled={wrolMode}
|
||||
onClick={() => setTagModalOpen(true)}>Tag</Button>
|
||||
<Button type='button' role='danger' disabled={wrolMode}
|
||||
onClick={() => setDeleteModalOpen(true)}>Delete</Button>
|
||||
</div>
|
||||
</Grid.Col>
|
||||
</Grid>
|
||||
</form>
|
||||
</Panel>
|
||||
{deleteModal}
|
||||
<CollectionTagModal
|
||||
open={tagModalOpen}
|
||||
onClose={() => setTagModalOpen(false)}
|
||||
currentTagName={repo.tag_name}
|
||||
originalDirectory={repo.directory}
|
||||
getTagInfo={(tagName) => getCollectionTagInfo(repo.collection_id, tagName)}
|
||||
onSave={handleTagSave}
|
||||
collectionName='Repo'
|
||||
hasDirectory={!!repo.directory}
|
||||
/>
|
||||
</>;
|
||||
}
|
||||
|
||||
export function ReposRoute() {
|
||||
return <PageContainer>
|
||||
<Routes>
|
||||
<Route path='/' element={<ReposPage/>}/>
|
||||
<Route path='new' element={<RepoNewPage/>}/>
|
||||
<Route path=':repoId' element={<RepoViewPage/>}/>
|
||||
<Route path=':repoId/edit' element={<RepoEditPage/>}/>
|
||||
</Routes>
|
||||
</PageContainer>;
|
||||
}
|
||||
237
app/src/components/Repos.test.js
Normal file
237
app/src/components/Repos.test.js
Normal file
|
|
@ -0,0 +1,237 @@
|
|||
import React from 'react';
|
||||
import {Route, Routes} from 'react-router';
|
||||
import {act, fireEvent, render, screen, within} from '../test-utils';
|
||||
import {
|
||||
RepoEditPage,
|
||||
repoNameFromURL,
|
||||
RepoNewPage,
|
||||
ReposPage,
|
||||
RepoViewPage,
|
||||
safeRepoHref,
|
||||
} from './Repos';
|
||||
import {createRepo, deleteRepo, fetchRepos, getFile, getRepo, getRepoTree, updateRepo} from '../api';
|
||||
import {FilePreviewContext} from './FilePreview';
|
||||
|
||||
jest.mock('../api', () => ({
|
||||
...jest.requireActual('../api'),
|
||||
createRepo: jest.fn(),
|
||||
deleteRepo: jest.fn(),
|
||||
fetchRepos: jest.fn(),
|
||||
getFile: jest.fn(),
|
||||
getRepo: jest.fn(),
|
||||
getRepoTree: jest.fn(),
|
||||
updateRepo: jest.fn(),
|
||||
}));
|
||||
|
||||
// The README is fetched from the media server; its rendering is MarkdownPreview's own spec.
|
||||
jest.mock('./MarkdownPreview', () => ({
|
||||
...jest.requireActual('./MarkdownPreview'),
|
||||
MarkdownPreview: ({url}) => <div data-testid='markdown-preview'>{url}</div>,
|
||||
}));
|
||||
|
||||
const repoFixture = (overrides = {}) => ({
|
||||
id: 1, collection_id: 10, name: 'kiwix-tools', tag_name: null, description: null,
|
||||
url: 'https://github.com/kiwix/kiwix-tools', mode: 'full', branch: null, default_branch: 'main',
|
||||
head_sha: '3f9c2a1e7b', head_message: 'Fix the mimetype', head_date: '2026-09-30T14:02:00Z',
|
||||
size: 1000, directory: 'repos/kiwix-tools', frequency: 604800, download_error: null,
|
||||
...overrides,
|
||||
});
|
||||
|
||||
const treeFixture = {
|
||||
path: '',
|
||||
readme_path: 'README.md',
|
||||
entries: [
|
||||
{name: 'src', path: 'src', is_dir: true, size: null},
|
||||
{name: 'README.md', path: 'README.md', is_dir: false, size: 120},
|
||||
],
|
||||
};
|
||||
|
||||
const flush = () => act(async () => {
|
||||
});
|
||||
|
||||
beforeEach(() => jest.clearAllMocks());
|
||||
|
||||
describe('safeRepoHref', () => {
|
||||
it('only links https URLs', () => {
|
||||
expect(safeRepoHref('https://github.com/a/b')).toBe('https://github.com/a/b');
|
||||
expect(safeRepoHref('javascript:alert(1)')).toBeNull();
|
||||
expect(safeRepoHref('http://github.com/a/b')).toBeNull();
|
||||
expect(safeRepoHref('file:///etc/passwd')).toBeNull();
|
||||
expect(safeRepoHref('not a url')).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('repoNameFromURL', () => {
|
||||
it('is the last path segment, without .git or a branch', () => {
|
||||
expect(repoNameFromURL('https://github.com/kiwix/kiwix-tools.git')).toBe('kiwix-tools');
|
||||
expect(repoNameFromURL('https://github.com/kiwix/kiwix-tools/tree/dev')).toBe('kiwix-tools');
|
||||
expect(repoNameFromURL('https://gitlab.com/group/sub/project/')).toBe('project');
|
||||
expect(repoNameFromURL('nope')).toBe('');
|
||||
});
|
||||
});
|
||||
|
||||
describe('ReposPage', () => {
|
||||
it('lists repos, linking each to its page', async () => {
|
||||
fetchRepos.mockResolvedValue([
|
||||
repoFixture(),
|
||||
repoFixture({id: 2, name: 'gone', download_error: 'git ls-remote failed', head_sha: null}),
|
||||
]);
|
||||
render(<ReposPage/>, {route: '/repos'});
|
||||
await flush();
|
||||
expect(screen.getAllByText('kiwix-tools')[0].closest('a')).toHaveAttribute('href', '/repos/1');
|
||||
expect(screen.getAllByText('gone')[0].closest('a')).toHaveAttribute('href', '/repos/2');
|
||||
expect(screen.getByText('New Repo').closest('a')).toHaveAttribute('href', '/repos/new');
|
||||
});
|
||||
|
||||
it('explains an empty list', async () => {
|
||||
fetchRepos.mockResolvedValue([]);
|
||||
render(<ReposPage/>, {route: '/repos'});
|
||||
await flush();
|
||||
expect(screen.getByText(/No repos yet/)).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
function renderViewPage({repo, tree = treeFixture, query = {}, setPreviewFile = jest.fn()} = {}) {
|
||||
getRepo.mockResolvedValue(repo);
|
||||
getRepoTree.mockResolvedValue(tree);
|
||||
return render(<Routes><Route path='/repos/:repoId' element={<RepoViewPage/>}/></Routes>, {
|
||||
route: '/repos/1',
|
||||
query,
|
||||
contexts: [[FilePreviewContext, {setPreviewFile}]],
|
||||
});
|
||||
}
|
||||
|
||||
describe('RepoViewPage', () => {
|
||||
it('shows the latest commit, the files, and the README', async () => {
|
||||
renderViewPage({repo: repoFixture()});
|
||||
await flush();
|
||||
expect(getRepoTree).toHaveBeenCalledWith('1', '');
|
||||
expect(screen.getByText('3f9c2a1')).toBeInTheDocument();
|
||||
expect(screen.getByText('Fix the mimetype')).toBeInTheDocument();
|
||||
expect(screen.getByText('main')).toBeInTheDocument();
|
||||
expect(screen.getByText('(default)')).toBeInTheDocument();
|
||||
expect(screen.getByText('https://github.com/kiwix/kiwix-tools').closest('a'))
|
||||
.toHaveAttribute('href', 'https://github.com/kiwix/kiwix-tools');
|
||||
expect(screen.getByText('src')).toBeInTheDocument();
|
||||
expect(screen.getByTestId('markdown-preview')).toHaveTextContent('/media/repos/kiwix-tools/README.md');
|
||||
});
|
||||
|
||||
it('opens a directory through the URL, and a file in the preview', async () => {
|
||||
const updateQuery = jest.fn();
|
||||
const setPreviewFile = jest.fn();
|
||||
const file = {path: 'repos/kiwix-tools/README.md', mimetype: 'text/markdown', size: 120};
|
||||
getFile.mockResolvedValue(file);
|
||||
renderViewPage({repo: repoFixture(), query: {updateQuery}, setPreviewFile});
|
||||
await flush();
|
||||
|
||||
fireEvent.click(screen.getByText('src'));
|
||||
expect(updateQuery).toHaveBeenCalledWith({path: 'src'}, false);
|
||||
|
||||
fireEvent.click(screen.getAllByText('README.md')[0]);
|
||||
await flush();
|
||||
expect(getFile).toHaveBeenCalledWith('repos/kiwix-tools/README.md', true);
|
||||
expect(setPreviewFile).toHaveBeenCalledWith(file);
|
||||
});
|
||||
|
||||
it('lists the directory in the URL, with a way back up', async () => {
|
||||
const tree = {path: 'src/lib', readme_path: null, entries: [{name: 'a.c', path: 'src/lib/a.c', is_dir: false}]};
|
||||
const updateQuery = jest.fn();
|
||||
renderViewPage({repo: repoFixture(), tree, query: {searchParams: new URLSearchParams('path=src/lib'), updateQuery}});
|
||||
await flush();
|
||||
expect(getRepoTree).toHaveBeenCalledWith('1', 'src/lib');
|
||||
expect(screen.queryByTestId('markdown-preview')).not.toBeInTheDocument();
|
||||
|
||||
fireEvent.click(screen.getByText('..'));
|
||||
expect(updateQuery).toHaveBeenCalledWith({path: 'src'}, false);
|
||||
// The breadcrumb's root.
|
||||
fireEvent.click(screen.getAllByText('kiwix-tools').find(i => i.tagName === 'BUTTON'));
|
||||
expect(updateQuery).toHaveBeenCalledWith({path: ''}, false);
|
||||
});
|
||||
|
||||
it('explains a repo that is not downloaded yet', async () => {
|
||||
renderViewPage({repo: repoFixture({head_sha: null, head_message: null, head_date: null})});
|
||||
await flush();
|
||||
expect(screen.getByText('Not downloaded yet')).toBeInTheDocument();
|
||||
expect(getRepoTree).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('keeps showing the files when the last update failed', async () => {
|
||||
renderViewPage({repo: repoFixture({download_error: 'Traceback...\nDownloadError: git ls-remote failed (128)'})});
|
||||
await flush();
|
||||
expect(screen.getByText('The last update failed')).toBeInTheDocument();
|
||||
expect(screen.getByText(/git ls-remote failed/)).toBeInTheDocument();
|
||||
expect(screen.getByText('src')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('never links an upstream that is not https', async () => {
|
||||
renderViewPage({repo: repoFixture({url: 'javascript:alert(1)'})});
|
||||
await flush();
|
||||
expect(screen.queryByText('javascript:alert(1)')).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
describe('RepoNewPage', () => {
|
||||
it('adds a repo, then opens it', async () => {
|
||||
createRepo.mockResolvedValue(repoFixture({id: 5}));
|
||||
render(<Routes>
|
||||
<Route path='/repos/new' element={<RepoNewPage/>}/>
|
||||
<Route path='/repos/:repoId' element={<div>repo page</div>}/>
|
||||
</Routes>, {route: '/repos/new'});
|
||||
|
||||
const add = screen.getByText('Add Repo').closest('button');
|
||||
expect(add).toBeDisabled();
|
||||
fireEvent.change(screen.getByLabelText(/URL/), {target: {value: 'git@github.com:a/b'}});
|
||||
expect(add).toBeDisabled();
|
||||
expect(screen.getByText('Must be an https:// URL')).toBeInTheDocument();
|
||||
|
||||
fireEvent.change(screen.getByLabelText(/URL/), {target: {value: 'https://github.com/kiwix/kiwix-tools'}});
|
||||
expect(screen.getByPlaceholderText('kiwix-tools')).toBeInTheDocument();
|
||||
fireEvent.change(screen.getByLabelText('Branch'), {target: {value: ' dev '}});
|
||||
fireEvent.click(add);
|
||||
await flush();
|
||||
|
||||
expect(createRepo).toHaveBeenCalledWith({
|
||||
url: 'https://github.com/kiwix/kiwix-tools', name: null, tag_name: null, frequency: 604800,
|
||||
mode: 'full', branch: 'dev', description: null,
|
||||
});
|
||||
expect(screen.getByText('repo page')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
describe('RepoEditPage', () => {
|
||||
function renderEditPage(repo) {
|
||||
getRepo.mockResolvedValue(repo);
|
||||
return render(<Routes>
|
||||
<Route path='/repos/:repoId/edit' element={<RepoEditPage/>}/>
|
||||
<Route path='/repos' element={<div>repos page</div>}/>
|
||||
</Routes>, {route: '/repos/1/edit'});
|
||||
}
|
||||
|
||||
it('saves the settings', async () => {
|
||||
updateRepo.mockResolvedValue(repoFixture());
|
||||
renderEditPage(repoFixture({branch: 'dev', description: 'Tools'}));
|
||||
await flush();
|
||||
expect(screen.getByLabelText('Branch')).toHaveValue('dev');
|
||||
|
||||
fireEvent.change(screen.getByLabelText('Branch'), {target: {value: ''}});
|
||||
fireEvent.click(screen.getByText('Save'));
|
||||
await flush();
|
||||
expect(updateRepo).toHaveBeenCalledWith('1', {
|
||||
description: 'Tools', frequency: 604800, mode: 'full', branch: '',
|
||||
});
|
||||
});
|
||||
|
||||
it('deletes the repo, and its files only when asked', async () => {
|
||||
deleteRepo.mockResolvedValue(undefined);
|
||||
renderEditPage(repoFixture());
|
||||
await flush();
|
||||
|
||||
fireEvent.click(screen.getByText('Delete'));
|
||||
const dialog = await screen.findByRole('dialog');
|
||||
fireEvent.click(within(dialog).getByLabelText(/Also delete its files/));
|
||||
fireEvent.click(within(dialog).getByText('Delete'));
|
||||
await flush();
|
||||
expect(deleteRepo).toHaveBeenCalledWith('1', true);
|
||||
expect(screen.getByText('repos page')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
|
@ -1,7 +1,15 @@
|
|||
import React, {useState} from "react";
|
||||
import {Link, Route, Routes, useLocation, useNavigate} from "react-router";
|
||||
import {FilesSearchView, SearchViewButton} from "./Files";
|
||||
import {useLatestRequest, usePages, useSearchChannels, useSearchDate, useSearchDeep, useSearchFilter} from "../hooks/customHooks";
|
||||
import {
|
||||
useLatestRequest,
|
||||
usePages,
|
||||
useSearchChannels,
|
||||
useSearchDate,
|
||||
useSearchDeep,
|
||||
useSearchFilter,
|
||||
useSearchRepos,
|
||||
} from "../hooks/customHooks";
|
||||
import {ShortcutHint} from "./ShortcutHint";
|
||||
import {ZimSearchView} from "./Zim";
|
||||
import {MapSearchView} from "./MapSearchView";
|
||||
|
|
@ -12,6 +20,7 @@ import {TagsContext} from "../Tags";
|
|||
import {Accordion, Header, Icon, Label, Loading, Panel, Stack} from "./ui";
|
||||
import {QueryContext} from "../contexts/contexts";
|
||||
import {KeyboardShortcutsContext} from "../contexts/KeyboardShortcutsContext";
|
||||
import {HeadlineText} from "./Headline";
|
||||
|
||||
const SUGGESTED_APPS = [
|
||||
{location: '/admin', title: 'Downloads', description: 'View and control your downloads'},
|
||||
|
|
@ -139,6 +148,7 @@ export function useSuggestions(searchStr, tagNames, filter, anyTag) {
|
|||
domains: null,
|
||||
authors: null,
|
||||
subjects: null,
|
||||
repos: null,
|
||||
zimsEstimates: [],
|
||||
}
|
||||
const [suggestions, setSuggestions] = React.useState(defaultSuggestions);
|
||||
|
|
@ -163,7 +173,7 @@ export function useSuggestions(searchStr, tagNames, filter, anyTag) {
|
|||
// The files estimate always uses deep search server-side, so users know results are possible.
|
||||
sendFilesRequest(async () => await searchEstimateFiles(searchStr, tagNames, mimetypes, months, dateRange, anyTag));
|
||||
sendZimRequest(async () => await searchEstimateZims(searchStr, tagNames));
|
||||
sendOtherRequest(async () => await searchEstimateOthers(tagNames));
|
||||
sendOtherRequest(async () => await searchEstimateOthers(tagNames, searchStr));
|
||||
}
|
||||
}, [
|
||||
searchStr,
|
||||
|
|
@ -185,6 +195,7 @@ export function useSuggestions(searchStr, tagNames, filter, anyTag) {
|
|||
domains: generalData.domains,
|
||||
authors: generalData.authors,
|
||||
subjects: generalData.subjects,
|
||||
repos: generalData.repos,
|
||||
}
|
||||
});
|
||||
}
|
||||
|
|
@ -312,6 +323,13 @@ export function useSearchSuggestions(defaultSearchStr, defaultTagNames, anyTag)
|
|||
})
|
||||
}
|
||||
}
|
||||
if (newSuggestions.repos && newSuggestions.repos.length > 0) {
|
||||
results.repos = {
|
||||
name: 'Repos', results: newSuggestions.repos.map(i => {
|
||||
return {type: 'repo', title: i.name, id: i.id, location: `/repos/${i.id}`}
|
||||
})
|
||||
}
|
||||
}
|
||||
if (newSuggestions.authors && newSuggestions.authors.length > 0) {
|
||||
results.authors = {
|
||||
name: 'Authors', results: newSuggestions.authors.map(i => {
|
||||
|
|
@ -407,6 +425,7 @@ export function useSearchSuggestions(defaultSearchStr, defaultTagNames, anyTag)
|
|||
domains: newSuggestions.domains?.length,
|
||||
authors: newSuggestions.authors?.length,
|
||||
subjects: newSuggestions.subjects?.length,
|
||||
repos: newSuggestions.repos?.length,
|
||||
tags: matchingTags?.length,
|
||||
apps: matchingApps?.length,
|
||||
});
|
||||
|
|
@ -543,12 +562,47 @@ function SearchChannelPreview({channel}) {
|
|||
</div>
|
||||
}
|
||||
|
||||
// `channels` follows useSearchChannels: null = pending, undefined = fetch failed, [] = none.
|
||||
function SearchRepoPreview({repo}) {
|
||||
const {SingleTag} = React.useContext(TagsContext);
|
||||
return <div>
|
||||
<span style={{display: 'inline-flex', alignItems: 'center', gap: 8, flexWrap: 'wrap'}}>
|
||||
<Link to={`/repos/${repo.id}`}>{repo.name}</Link>
|
||||
{repo.tag_name && <SingleTag name={repo.tag_name}/>}
|
||||
</span>
|
||||
{/* The server escapes the README; only its <b> highlights are markup. */}
|
||||
{repo.readme_headline && <div><small><HeadlineText headline={repo.readme_headline}/></small></div>}
|
||||
</div>
|
||||
}
|
||||
|
||||
function OtherSearchSection({value, title, items, preview, emptyText, errorText}) {
|
||||
let body;
|
||||
if (items === null) {
|
||||
body = <Loading/>;
|
||||
} else if (items === undefined) {
|
||||
body = <ErrorMessage>{errorText}</ErrorMessage>;
|
||||
} else {
|
||||
body = <Stack gap='xs'>{!_.isEmpty(items) ? items.map(preview) : emptyText}</Stack>;
|
||||
}
|
||||
return <Accordion.Item value={value}>
|
||||
<Accordion.Control>
|
||||
<span style={{display: 'inline-flex', alignItems: 'center', gap: 8}}>
|
||||
<Header as='h3' style={{margin: 0}}>{title}</Header>
|
||||
{Array.isArray(items) && <Label>{normalizeEstimate(items.length)}</Label>}
|
||||
</span>
|
||||
</Accordion.Control>
|
||||
<Accordion.Panel>{body}</Accordion.Panel>
|
||||
</Accordion.Item>
|
||||
}
|
||||
|
||||
// `channels` follows useSearchChannels and `repos` follows useSearchRepos: null = pending,
|
||||
// undefined = fetch failed, [] = none.
|
||||
export function OtherSearchView({loading}) {
|
||||
const {searchParams} = React.useContext(QueryContext);
|
||||
const [activeValue, setActiveValue] = React.useState('channels');
|
||||
const [activeValues, setActiveValues] = React.useState(['channels', 'repos']);
|
||||
const activeTags = searchParams.getAll('tag');
|
||||
const searchStr = searchParams.get('q') || '';
|
||||
const {channels, loading: channelsLoading} = useSearchChannels(activeTags);
|
||||
const {repos} = useSearchRepos(searchStr, activeTags);
|
||||
|
||||
if (loading || channelsLoading || channels === null) {
|
||||
return <Panel><Loading/></Panel>
|
||||
|
|
@ -556,21 +610,22 @@ export function OtherSearchView({loading}) {
|
|||
return <Panel><ErrorMessage>Could not fetch the channels.</ErrorMessage></Panel>
|
||||
}
|
||||
|
||||
return <Accordion value={activeValue} onChange={setActiveValue}>
|
||||
<Accordion.Item value='channels'>
|
||||
<Accordion.Control>
|
||||
<span style={{display: 'inline-flex', alignItems: 'center', gap: 8}}>
|
||||
<Header as='h3' style={{margin: 0}}>Channels</Header>
|
||||
<Label>{normalizeEstimate(channels.length)}</Label>
|
||||
</span>
|
||||
</Accordion.Control>
|
||||
<Accordion.Panel>
|
||||
<Stack gap='xs'>
|
||||
{!_.isEmpty(channels) ?
|
||||
channels.map(i => <SearchChannelPreview key={i.id} channel={i}/>)
|
||||
: 'No Channels'}
|
||||
</Stack>
|
||||
</Accordion.Panel>
|
||||
</Accordion.Item>
|
||||
return <Accordion multiple value={activeValues} onChange={setActiveValues}>
|
||||
<OtherSearchSection
|
||||
value='channels'
|
||||
title='Channels'
|
||||
items={channels}
|
||||
preview={i => <SearchChannelPreview key={i.id} channel={i}/>}
|
||||
emptyText='No Channels'
|
||||
errorText='Could not fetch the channels.'
|
||||
/>
|
||||
<OtherSearchSection
|
||||
value='repos'
|
||||
title='Repos'
|
||||
items={repos}
|
||||
preview={i => <SearchRepoPreview key={i.id} repo={i}/>}
|
||||
emptyText='No Repos'
|
||||
errorText='Could not fetch the repos.'
|
||||
/>
|
||||
</Accordion>
|
||||
}
|
||||
|
|
|
|||
|
|
@ -103,3 +103,37 @@ test('Channels rows once the server found some', async () => {
|
|||
});
|
||||
expect(results().channels.results.map(i => i.title)).toEqual(['Food']);
|
||||
});
|
||||
|
||||
test('Repos rows link to each repo, and the Other estimate gets the search', async () => {
|
||||
let resolve;
|
||||
searchSuggestions.mockReturnValue(new Promise(res => resolve = res));
|
||||
renderProbe();
|
||||
act(() => {
|
||||
hook.setSearchStr('kiwix');
|
||||
});
|
||||
act(() => {
|
||||
jest.advanceTimersByTime(DEBOUNCE);
|
||||
});
|
||||
await act(async () => {
|
||||
resolve({channels: [], domains: [], authors: [], subjects: [], repos: [{id: 4, name: 'kiwix-tools'}]});
|
||||
});
|
||||
expect(results().repos.results).toEqual([{type: 'repo', title: 'kiwix-tools', id: 4, location: '/repos/4'}]);
|
||||
// Repos count toward the Other tab by their name and README, not only by tag.
|
||||
expect(searchEstimateOthers).toHaveBeenCalledWith([], 'kiwix');
|
||||
});
|
||||
|
||||
test('no Repos group when none match', async () => {
|
||||
let resolve;
|
||||
searchSuggestions.mockReturnValue(new Promise(res => resolve = res));
|
||||
renderProbe();
|
||||
act(() => {
|
||||
hook.setSearchStr('foo');
|
||||
});
|
||||
act(() => {
|
||||
jest.advanceTimersByTime(DEBOUNCE);
|
||||
});
|
||||
await act(async () => {
|
||||
resolve({channels: [], domains: [], authors: [], subjects: [], repos: []});
|
||||
});
|
||||
expect(results().repos).toBeUndefined();
|
||||
});
|
||||
|
|
|
|||
|
|
@ -49,6 +49,7 @@ import {contrastingColor} from './Common';
|
|||
import {navBarStyle, navColorNames, useNavColors} from '../themes/navColors';
|
||||
import {IconMenu2} from '@tabler/icons-react';
|
||||
import {BookmarkAddForms, BookmarkMenuItems, BookmarkTable} from './Bookmarks';
|
||||
import {RepoBreadcrumb, RepoStatusIcon, RepoSummary, RepoTreeTable} from './Repos';
|
||||
|
||||
/*
|
||||
* A gallery of every component in the library, in the current theme.
|
||||
|
|
@ -170,6 +171,23 @@ const sampleBookmarks = [
|
|||
];
|
||||
const noBookmarkActions = {edit: () => null, move: () => null, remove: () => null};
|
||||
|
||||
const sampleRepo = {
|
||||
id: 1, name: 'kiwix-tools', tag_name: null, url: 'https://github.com/kiwix/kiwix-tools',
|
||||
description: 'Command line tools for Kiwix and Zim files.', mode: 'full', branch: null, default_branch: 'main',
|
||||
head_sha: '3f9c2a1e7b', head_message: 'Serve Zim files with the correct mimetype', head_date: '2026-09-30T14:02:00Z',
|
||||
size: 18_400_000, directory: 'repos/kiwix-tools', download_error: null,
|
||||
};
|
||||
const sampleFailedRepo = {
|
||||
...sampleRepo, name: 'gone-upstream', branch: 'release', mode: 'snapshot',
|
||||
download_error: "git ls-remote failed (128): remote: Repository not found.\nfatal: repository " +
|
||||
"'https://github.com/example/gone-upstream/' not found",
|
||||
};
|
||||
const sampleRepoEntries = [
|
||||
{name: 'docs', path: 'src/docs', is_dir: true, size: null},
|
||||
{name: 'kiwix-serve.cpp', path: 'src/kiwix-serve.cpp', is_dir: false, size: 48_210},
|
||||
{name: 'README.md', path: 'src/README.md', is_dir: false, size: 2_104},
|
||||
];
|
||||
|
||||
export function ThemeSamplePage() {
|
||||
const {theme, mediaFilterEnabled} = useContext(ThemeContext);
|
||||
const [confirmOpen, setConfirmOpen] = useState(false);
|
||||
|
|
@ -1127,6 +1145,26 @@ export function ThemeSamplePage() {
|
|||
</Panel>
|
||||
</Section>
|
||||
|
||||
<Section label='Repos'>
|
||||
<Panel>
|
||||
<p style={{fontSize: '0.75rem', color: 'var(--muted)', marginTop: 0}}>
|
||||
A git repo's page: its summary, then its files. A repo whose last update failed keeps
|
||||
its files and explains why. The status icons appear beside a repo's name in the Repos
|
||||
table: <RepoStatusIcon repo={sampleFailedRepo}/> failed,{' '}
|
||||
<RepoStatusIcon repo={{...sampleRepo, head_sha: null}}/> not downloaded yet.
|
||||
</p>
|
||||
<RepoSummary repo={sampleRepo}/>
|
||||
<div style={{marginTop: 12}}>
|
||||
<RepoBreadcrumb name={sampleRepo.name} path='src' onNavigate={() => null}/>
|
||||
<RepoTreeTable path='src' entries={sampleRepoEntries} onOpenDirectory={() => null}
|
||||
onOpenFile={() => null}/>
|
||||
</div>
|
||||
<div style={{marginTop: 12}}>
|
||||
<RepoSummary repo={sampleFailedRepo}/>
|
||||
</div>
|
||||
</Panel>
|
||||
</Section>
|
||||
|
||||
<Section label='Danger zone'>
|
||||
<Panel danger>
|
||||
<h2 style={{color: 'var(--danger)', fontSize: '0.875rem', margin: '0 0 4px'}}>Danger zone</h2>
|
||||
|
|
|
|||
|
|
@ -3,6 +3,7 @@ export const VIDEOS_API = `${API_URI}/videos`;
|
|||
export const ARCHIVES_API = `${API_URI}/archive`;
|
||||
export const COLLECTIONS_API = `${API_URI}/collections`;
|
||||
export const ZIM_API = `${API_URI}/zim`;
|
||||
export const REPOS_API = `${API_URI}/repos`;
|
||||
export const DEFAULT_LIMIT = 20;
|
||||
export const NAME = process.env && process.env.REACT_APP_NAME ? process.env.REACT_APP_NAME : null;
|
||||
|
||||
|
|
|
|||
|
|
@ -499,6 +499,7 @@ export function SettingsPage() {
|
|||
videos_destination: settings.videos_destination,
|
||||
zims_destination: settings.zims_destination,
|
||||
playlists_destination: settings.playlists_destination,
|
||||
repos_destination: settings.repos_destination,
|
||||
save_ffprobe_json: settings.save_ffprobe_json,
|
||||
});
|
||||
}, [JSON.stringify(settings), settingsLoaded, settingsFailed]);
|
||||
|
|
@ -849,6 +850,31 @@ export function SettingsPage() {
|
|||
onChange={e => handleInputChange('playlists_destination', e.currentTarget.value)}
|
||||
/>
|
||||
</Grid.Col>
|
||||
<Grid.Col span={{base: 12, sm: 6}}>
|
||||
<PathInput
|
||||
label={<>
|
||||
Repos Directory
|
||||
<InfoPopup
|
||||
content={<>
|
||||
<p>Variables:</p>
|
||||
<ul>
|
||||
<li><code>%(repo_name)s</code> - Repo name</li>
|
||||
<li><code>%(repo_tag)s</code> - Tag name for the repo (empty if no tag)
|
||||
</li>
|
||||
<li><code>%(repo_owner)s</code> - Owner from the repo URL</li>
|
||||
<li><code>%(repo_host)s</code> - Host from the repo URL</li>
|
||||
</ul>
|
||||
<p>Files in the <code>repos</code> directory are never indexed.</p>
|
||||
</>}
|
||||
position='top'
|
||||
/>
|
||||
</>}
|
||||
prefix={mediaDirectoryLabel}
|
||||
value={state.repos_destination}
|
||||
disabled={!editSpecialDirectories}
|
||||
onChange={e => handleInputChange('repos_destination', e.currentTarget.value)}
|
||||
/>
|
||||
</Grid.Col>
|
||||
<Grid.Col span={12}>
|
||||
<Toggle
|
||||
label='Edit Directories'
|
||||
|
|
|
|||
|
|
@ -77,7 +77,9 @@ function renderRow(collection, columns, routes, SingleTag, onRowClick) {
|
|||
}
|
||||
|
||||
// Format the value based on column configuration
|
||||
if (col.format === 'bytes') {
|
||||
if (col.render) {
|
||||
value = col.render(collection);
|
||||
} else if (col.format === 'bytes') {
|
||||
value = humanFileSize(value);
|
||||
} else if (col.format === 'frequency') {
|
||||
value = formatFrequency(value);
|
||||
|
|
@ -134,7 +136,9 @@ function MobileCollectionRow({collection, mobileColumns, routes}) {
|
|||
.filter(col => col.type !== 'actions' && col.key !== primaryColumn.key && col.key !== 'tag_name')
|
||||
.map(col => {
|
||||
let value = collection[col.key];
|
||||
if (col.format === 'bytes') {
|
||||
if (col.render) {
|
||||
value = col.render(collection);
|
||||
} else if (col.format === 'bytes') {
|
||||
value = humanFileSize(value);
|
||||
} else if (col.format === 'frequency') {
|
||||
value = formatFrequency(value);
|
||||
|
|
@ -157,7 +161,8 @@ function MobileCollectionRow({collection, mobileColumns, routes}) {
|
|||
* Reusable table component for displaying collections (Domains, Channels, etc).
|
||||
*
|
||||
* @param {Array} collections - Array of collection objects
|
||||
* @param {Array} columns - Column configurations for the table
|
||||
* @param {Array} columns - Column configurations for the table. A column's optional `render(collection)` displays
|
||||
* the cell; the column still sorts by `collection[key]`.
|
||||
* @param {Object} routes - Routes configuration for navigation (edit, search, etc.)
|
||||
* @param {String} searchStr - Search filter string (managed by parent)
|
||||
* @param {Function} onRowClick - Optional callback when a row is clicked
|
||||
|
|
|
|||
|
|
@ -68,6 +68,27 @@ const DOMAIN_ROUTES = {
|
|||
describe('CollectionTable', () => {
|
||||
const mockCollections = createMockDomains(3);
|
||||
|
||||
describe('Column render', () => {
|
||||
it('displays what a column renders, in the desktop and mobile rows', () => {
|
||||
const columns = [
|
||||
{key: 'name', label: 'Name', render: (c) => <em data-testid='rendered-name'>{c.name}!</em>},
|
||||
{key: 'branch', label: 'Branch', render: (c) => c.branch || c.default_branch},
|
||||
];
|
||||
render(<CollectionTable
|
||||
collections={[{id: 1, name: 'kiwix-tools', branch: null, default_branch: 'main'}]}
|
||||
columns={columns}
|
||||
routes={{search: '/repos/:id', id_field: 'id'}}
|
||||
/>);
|
||||
|
||||
// Desktop: the rendered name is still the link to the collection.
|
||||
expect(screen.getByTestId('rendered-name')).toHaveTextContent('kiwix-tools!');
|
||||
expect(screen.getByTestId('rendered-name').closest('a')).toHaveAttribute('href', '/repos/1');
|
||||
expect(screen.getByText('main')).toBeInTheDocument();
|
||||
// Mobile lists the other columns by label.
|
||||
expect(screen.getByText('Branch: main')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
describe('Loading and Error States', () => {
|
||||
it('renders loading placeholder when collections is null', () => {
|
||||
const {container} = render(
|
||||
|
|
|
|||
|
|
@ -38,6 +38,7 @@ import {
|
|||
searchChannels,
|
||||
searchDirectories,
|
||||
searchDocs,
|
||||
searchRepos,
|
||||
searchVideos,
|
||||
searchZim,
|
||||
updateChannel,
|
||||
|
|
@ -2156,6 +2157,27 @@ export const useSearchChannels = (defaultTagNames) => {
|
|||
}
|
||||
}
|
||||
|
||||
// Repos matching the search (their name and README) and/or the tags. `repos`: null = pending,
|
||||
// undefined = fetch failed, [] = none. Only the newest request may write state.
|
||||
export const useSearchRepos = (searchStr, tagNames) => {
|
||||
const [repos, setRepos] = useState(null);
|
||||
const requestGen = useRef(0);
|
||||
const tagKey = JSON.stringify(tagNames || []);
|
||||
|
||||
useEffect(() => {
|
||||
const gen = ++requestGen.current;
|
||||
setRepos(null);
|
||||
searchRepos(searchStr, JSON.parse(tagKey))
|
||||
.then(result => gen === requestGen.current && setRepos(result ? result.repos : undefined))
|
||||
.catch(e => {
|
||||
console.error(e);
|
||||
if (gen === requestGen.current) setRepos(undefined);
|
||||
});
|
||||
}, [searchStr, tagKey]);
|
||||
|
||||
return {repos};
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Detect whether the WROLPi browser extension is installed AND has this
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue