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) => }, {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 ; } if (!repo.head_sha) { return ; } return null; } function RepoName({repo}) { return {repo.name} ; } 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 = setSearchStr('')} onChange={setSearchStr} onSubmit={null} inputRef={searchInputRef} /> ; return <> {header} ; } /** 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 <>
{repo.name} {repo.tag_name && }
{repo.description &&

{repo.description}

} {upstream && {repo.url} } {branch && {branch} {!repo.branch && (default)} } {repo.mode === 'snapshot' ? 'Snapshot' : 'Full history'} {repo.size ? ` ยท ${humanFileSize(repo.size)}` : ''} {repo.head_sha && {repo.head_sha.slice(0, 7)} {repo.head_message} {repo.head_date && {isoDatetimeToAgoPopup(repo.head_date)}} } ; } /** Explains a Repo that has not been downloaded, or whose last update failed. */ export function RepoStatusMessage({repo}) { if (repo.download_error) { return

The files below are from the last successful update. The update will be tried again.

                {repo.download_error.trim().split('\n').slice(-8).join('\n')}
            
; } if (!repo.head_sha) { return

This repo will be cloned soon. Its progress is on the Downloads page.

; } 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) => onNavigate(target)}>{label}; return
{parts.length ? crumb(name, '', 'root') : {name}} {parts.map((part, idx) => / {idx === parts.length - 1 ? {part} : crumb(part, parts.slice(0, idx + 1).join('/'), idx)} )}
; } /** 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) => {children} ; return {parent !== null && {link(() => onOpenDirectory(parent), <>..)} } {entries.map(entry => {entry.is_dir ? link(() => onOpenDirectory(entry.path), <>{entry.name}) : link(() => onOpenFile(entry), <>{entry.name})} {entry.is_dir ? '' : humanFileSize(entry.size)} )} {entries.length === 0 && This directory is empty }
; } 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 Could not read the README: {error}; } if (text === null) { return ; } return
{text}
; } /** 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
{name}
{isMarkdownFile('text/plain', readmePath.toLowerCase()) ? : }
; } 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 Could not fetch the repo; } if (repo === null) { return ; } 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 = Could not list the repo's files; } else if (tree === null) { files = ; } else { files = <> {tree.readme_path && } ; } } return <>
Update Now
{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 <>
New Repo

WROLPi clones the repository, then keeps it up to date. Only https:// URLs are supported.

setUrl(e.currentTarget.value)} /> setName(e.currentTarget.value)} /> setTagName(null)} />