Files
suwayomi-material-you-webui/webUI/react/src/screens/Sources.tsx

82 lines
2.8 KiB
TypeScript
Raw Normal View History

2021-01-26 23:32:12 +03:30
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
2021-01-22 17:00:33 +03:30
import React, { useContext, useEffect, useState } from 'react';
2021-03-09 16:44:09 +03:30
import ExtensionLangSelect from '../components/ExtensionLangSelect';
2021-01-19 14:47:07 +03:30
import SourceCard from '../components/SourceCard';
2021-03-08 21:04:42 +03:30
import NavbarContext from '../context/NavbarContext';
import client from '../util/client';
2021-03-09 16:44:09 +03:30
import { defualtLangs, langCodeToName, langSortCmp } from '../util/language';
import useLocalStorage from '../util/useLocalStorage';
function sourceToLangList(sources: ISource[]) {
const result: string[] = [];
sources.forEach((source) => {
if (result.indexOf(source.lang) === -1 && langCodeToName(source.lang) !== 'Error') { result.push(source.lang); }
});
result.sort(langSortCmp);
return result;
}
function groupByLang(sources: ISource[]) {
const result = {} as any;
sources.forEach((source) => {
if (result[source.lang] === undefined) { result[source.lang] = [] as ISource[]; }
result[source.lang].push(source);
});
return result;
}
2021-01-19 14:47:07 +03:30
export default function Sources() {
2021-03-09 16:44:09 +03:30
const { setTitle, setAction } = useContext(NavbarContext);
const [shownLangs, setShownLangs] = useLocalStorage<string[]>('shownSourceLangs', defualtLangs());
2021-01-19 14:47:07 +03:30
const [sources, setSources] = useState<ISource[]>([]);
2021-03-07 16:27:13 +03:30
const [fetched, setFetched] = useState<boolean>(false);
2021-01-19 14:47:07 +03:30
2021-03-09 16:44:09 +03:30
useEffect(() => {
setTitle('Sources');
setAction(
<ExtensionLangSelect
shownLangs={shownLangs}
setShownLangs={setShownLangs}
allLangs={sourceToLangList(sources)}
/>,
);
}, [shownLangs, sources]);
2021-01-19 14:47:07 +03:30
useEffect(() => {
client.get('/api/v1/source/list')
.then((response) => response.data)
2021-03-07 16:27:13 +03:30
.then((data) => { setSources(data); setFetched(true); });
2021-01-19 14:47:07 +03:30
}, []);
if (sources.length === 0) {
2021-03-07 16:27:13 +03:30
if (fetched) return (<h3>No sources found. Install Some Extensions first.</h3>);
return (<h3>loading...</h3>);
2021-01-19 14:47:07 +03:30
}
2021-03-09 16:44:09 +03:30
return (
<>
{/* eslint-disable-next-line max-len */}
{Object.entries(groupByLang(sources)).sort((a, b) => langSortCmp(a[0], b[0])).map(([lang, list]) => (
shownLangs.indexOf(lang) !== -1 && (
<React.Fragment key={lang}>
<h1 key={lang} style={{ marginLeft: 25 }}>{langCodeToName(lang)}</h1>
{(list as ISource[]).map((source) => (
<SourceCard
key={source.id}
source={source}
/>
))}
</React.Fragment>
)
))}
</>
);
2021-01-19 14:47:07 +03:30
}