Skip to content

Commit

Permalink
Add some data to hooks to simplify code
Browse files Browse the repository at this point in the history
  • Loading branch information
UncleSamSwiss committed Jan 10, 2025
1 parent 8d93a05 commit e7280f0
Show file tree
Hide file tree
Showing 12 changed files with 61 additions and 78 deletions.
12 changes: 6 additions & 6 deletions express/frontend/src/components/dashboard/AddWatchDialog.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,3 @@
import { useEffect, useState } from "react";
import { useUserContext } from "../../contexts/UserContext";
import { getAdapterInfos, getLatest } from "../../lib/ioBroker";
import { GitHubComm } from "../../lib/gitHub";
import {
Autocomplete,
Button,
Expand All @@ -13,6 +9,10 @@ import {
InputAdornment,
TextField,
} from "@mui/material";
import { useEffect, useState } from "react";
import { useUserToken } from "../../contexts/UserContext";
import { GitHubComm } from "../../lib/gitHub";
import { getAdapterInfos, getLatest } from "../../lib/ioBroker";

export function AddWatchDialog({
open,
Expand All @@ -21,7 +21,7 @@ export function AddWatchDialog({
open?: boolean;
onClose: (repo?: string) => void;
}) {
const { user } = useUserContext();
const token = useUserToken();

const [repoNames, setRepoNames] = useState<string[]>([]);
const [repoName, setRepoName] = useState("");
Expand All @@ -48,7 +48,7 @@ export function AddWatchDialog({
const validate = async () => {
setValidating(true);
try {
const gitHub = GitHubComm.forToken(user!.token);
const gitHub = GitHubComm.forToken(token);
const [owner, repo] = repoName.split("/", 2);
const latest = await getLatest();
const infos = await getAdapterInfos(
Expand Down
5 changes: 4 additions & 1 deletion express/frontend/src/contexts/AdapterContext.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { createContext, useContext } from "react";
import { AdapterInfos } from "../lib/ioBroker";

export interface IAdapterContext {
name: string;
infos: AdapterInfos;
}

Expand All @@ -21,13 +22,15 @@ export function useAdapter() {

export function AdapterProvider({
children,
name,
infos,
}: {
children: React.ReactNode;
name: string;
infos: AdapterInfos;
}) {
return (
<AdapterContext.Provider value={{ infos }}>
<AdapterContext.Provider value={{ name, infos }}>
{children}
</AdapterContext.Provider>
);
Expand Down
9 changes: 9 additions & 0 deletions express/frontend/src/contexts/UserContext.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,15 @@ export function useUserContext() {
return context;
}

export function useUserToken() {
const { user } = useUserContext();
const token = user?.token;
if (!token) {
throw new Error("User token missing");
}
return token;
}

export function UserProvider({ children }: { children: React.ReactNode }) {
const [cookies, , removeCookie] = useCookies([gitHubTokenCookie]);
const [user, setUser] = useState<User>();
Expand Down
10 changes: 9 additions & 1 deletion express/frontend/src/lib/ioBroker.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import axios from "axios";
import { AdapterStats } from "../../../backend/src/global/adapter-stats";
import {
AdapterRatings,
AllRatings,
Expand Down Expand Up @@ -177,14 +178,21 @@ export const getWeblateAdapterComponents = AsyncCache.of(async () => {
return result.data;
});

export async function getStatistics(adapterName: string) {
const result = await axios.get<AdapterStats>(
getApiUrl(`adapter/${uc(adapterName)}/stats`),
);
return result.data;
}

const discoverySupports = new Map<string, Promise<boolean>>();
export function hasDiscoverySupport(adapterName: string): Promise<boolean> {
if (!discoverySupports.has(adapterName)) {
const checkDiscoverySupport = async () => {
try {
await axios.get(
`https://cdn.jsdelivr.net/npm/iobroker.discovery/lib/adapters/` +
`${encodeURIComponent(adapterName)}.js`,
`${uc(adapterName)}.js`,
);
return true;
} catch {
Expand Down
15 changes: 3 additions & 12 deletions express/frontend/src/tools/AdapterCheck.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,7 @@ import { OverridableComponent } from "@mui/material/OverridableComponent";
import { useEffect, useState } from "react";
import Chart from "react-google-charts";
import { useLocation } from "react-router-dom";
import { useUserContext } from "../contexts/UserContext";
import { User } from "../lib/gitHub";
import { useUserToken } from "../contexts/UserContext";
import { checkAdapter, CheckResult, getMyAdapterRepos } from "../lib/ioBroker";

const iconStyles = {
Expand Down Expand Up @@ -91,28 +90,20 @@ export interface AdapterCheckLocationState {
repoFullName?: string;
}

export interface AdapterCheckProps {
user: User;
}

export function AdapterCheck() {
const { user } = useUserContext();
const token = useUserToken();
let location = useLocation();
const [repoNames, setRepoNames] = useState<string[]>([]);
const [repoName, setRepoName] = useState("");
const [busy, setBusy] = useState(false);
const [messages, setMessages] = useState<Message[]>([]);
useEffect(() => {
const loadData = async () => {
const token = user?.token;
if (!token) {
return;
}
const repos = await getMyAdapterRepos(token);
setRepoNames(repos.map((r) => r.full_name));
};
loadData().catch(console.error);
}, [user]);
}, [token]);

const incomingState = location.state as
| AdapterCheckLocationState
Expand Down
13 changes: 6 additions & 7 deletions express/frontend/src/tools/adapter/AdapterDashboard.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,10 @@ import {
Typography,
} from "@mui/material";
import { useEffect, useState } from "react";
import { useParams } from "react-router-dom";
import { CardButton } from "../../components/CardButton";
import { CardGrid, CardGridProps } from "../../components/dashboard/CardGrid";
import { DashboardCardProps } from "../../components/dashboard/DashboardCard";
import { useAdapter } from "../../contexts/AdapterContext";
import { getAllRatings, getLatest } from "../../lib/ioBroker";

const CATEGORY_GENERAL = "General";
Expand All @@ -20,20 +20,19 @@ const EMPTY_CARDS = {
};

export function AdapterDashboard() {
const { name } = useParams<{ name: string }>();
const { name } = useAdapter();
const [categories, setCategories] =
useState<Record<string, CardGridProps>>(EMPTY_CARDS);
const [collapsed, setCollapsed] = useState<boolean[]>([]);

useEffect(() => {
setCategories(EMPTY_CARDS);
const loadCards = async () => {
const latest = await getLatest();
const ratings = await getAllRatings();
const [latest, ratings] = await Promise.all([
getLatest(),
getAllRatings(),
]);
const generalCards: DashboardCardProps[] = [];
if (!name) {
throw new Error("No adapter name provided");
}
generalCards.push({
title: "Releases",
text: "Manage releases of your adapter.",
Expand Down
13 changes: 6 additions & 7 deletions express/frontend/src/tools/adapter/AdapterDetails.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ import {
useParams,
} from "react-router-dom";
import { AdapterProvider } from "../../contexts/AdapterContext";
import { useUserContext } from "../../contexts/UserContext";
import { useUserToken } from "../../contexts/UserContext";
import { GitHubComm } from "../../lib/gitHub";
import {
AdapterInfos,
Expand All @@ -28,7 +28,7 @@ import {
const LinkRouter = (props: any) => <Link {...props} component={RouterLink} />;

export function AdapterDetails() {
const { user } = useUserContext();
const token = useUserToken();
const matches = useMatches();
const pathNames = matches[matches.length - 1].pathname
.split("/")
Expand All @@ -40,8 +40,7 @@ export function AdapterDetails() {

useEffect(() => {
const loadInfos = async () => {
const token = user?.token;
if (!token || !name) {
if (!name) {
return;
}
const myAdapters = await getMyAdapterInfos(token);
Expand Down Expand Up @@ -76,7 +75,7 @@ export function AdapterDetails() {
setInfos(`Couldn't find ioBroker.${name}`);
};
loadInfos().catch(console.error);
}, [name, user]);
}, [name, token]);

const toText = (value: string) => {
const sentence = value.replace(/([A-Z])/g, " $1");
Expand Down Expand Up @@ -112,8 +111,8 @@ export function AdapterDetails() {
<AlertTitle>Error</AlertTitle>
{infos}
</Alert>
) : infos?.info ? (
<AdapterProvider infos={infos}>
) : infos?.info && name ? (
<AdapterProvider name={name} infos={infos}>
<Outlet />
</AdapterProvider>
) : (
Expand Down
8 changes: 2 additions & 6 deletions express/frontend/src/tools/adapter/AdapterRatings.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,11 @@ import {
Typography,
} from "@mui/material";
import { Fragment, useEffect, useState } from "react";
import { useParams } from "react-router-dom";
import {
Rating as IoBrokerRating,
RatingComment,
} from "../../../../backend/src/global/iobroker";
import { useAdapter } from "../../contexts/AdapterContext";
import { getAdapterRatings, getAllRatings } from "../../lib/ioBroker";

const sxList: SxProps<Theme> = {
Expand Down Expand Up @@ -52,8 +52,7 @@ function GlobalRating(props: { title: string; rating: IoBrokerRating }) {
}

export function AdapterRatings() {
const { name } = useParams<{ name: string }>();

const { name } = useAdapter();
const [overallRating, setOverallRating] = useState<IoBrokerRating>();
const [currentRating, setCurrentRating] = useState<
IoBrokerRating & { version: string }
Expand All @@ -62,9 +61,6 @@ export function AdapterRatings() {

useEffect(() => {
const loadRatings = async () => {
if (!name) {
return;
}
try {
const [allRatings, adapterRatings] = await Promise.all([
getAllRatings(),
Expand Down
18 changes: 4 additions & 14 deletions express/frontend/src/tools/adapter/AdapterStatistics.tsx
Original file line number Diff line number Diff line change
@@ -1,14 +1,10 @@
import { Box, Paper } from "@mui/material";
import axios from "axios";
import ReactECharts from "echarts-for-react";
import { useEffect, useState } from "react";
import { useParams } from "react-router";
import { coerce } from "semver";
import sort from "semver/functions/sort";
import { AdapterStats } from "../../../../backend/src/global/adapter-stats";
import { getApiUrl } from "../../lib/utils";

const uc = encodeURIComponent;
import { useAdapter } from "../../contexts/AdapterContext";
import { getStatistics } from "../../lib/ioBroker";

const chartDefaults = {
title: {
Expand Down Expand Up @@ -63,21 +59,15 @@ const chartDefaults = {
export interface AdapterStatisticsProps {}

export function AdapterStatistics(props: AdapterStatisticsProps) {
const { name } = useParams<"name">();
const { name } = useAdapter();
const [option, setOption] = useState<any>();
const [showLoading, setShowLoading] = useState(true);

useEffect(() => {
if (!name) {
return;
}

setOption(undefined);
setShowLoading(true);
const loadStatistics = async () => {
const url = getApiUrl(`adapter/${uc(name)}/stats`);
const { data: stats } = await axios.get<AdapterStats>(url);

const stats = await getStatistics(name);
const versions = new Set<string>();
for (const date of Object.keys(stats.counts)) {
Object.keys(stats.counts[date].versions)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ import {
TextField,
} from "@mui/material";
import { useEffect, useState } from "react";
import { useParams } from "react-router-dom";
import useWebSocket from "react-use-websocket";
import * as semver from "semver";
import {
Expand Down Expand Up @@ -93,8 +92,7 @@ function SelectVersion(props: { onSelected: (type?: ReleaseType) => void }) {
}

export function CreateReleaseDialog() {
const { name } = useParams<{ name: string }>();
const { infos } = useAdapter();
const { name, infos } = useAdapter();

const webSocket = useWebSocket(getWebSocketUrl("release"));

Expand Down
15 changes: 5 additions & 10 deletions express/frontend/src/tools/adapter/releases/Releases.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ import {
} from "@mui/material";
import axios from "axios";
import { useEffect, useState } from "react";
import { Outlet, useLocation, useParams } from "react-router-dom";
import { Outlet, useLocation } from "react-router-dom";
import { coerce } from "semver";
import { AuthConsentDialog } from "../../../components/AuthConsentDialog";
import {
Expand All @@ -27,7 +27,7 @@ import {
NpmIcon,
} from "../../../components/Icons";
import { useAdapter } from "../../../contexts/AdapterContext";
import { useUserContext } from "../../../contexts/UserContext";
import { useUserToken } from "../../../contexts/UserContext";
import { GitHubComm } from "../../../lib/gitHub";
import { getLatest } from "../../../lib/ioBroker";
import { getPackage as getPackageMetaData } from "../../../lib/npm";
Expand Down Expand Up @@ -121,9 +121,8 @@ const sxButton: SxProps = {
};

export function Releases() {
const { user } = useUserContext();
const { infos } = useAdapter();
const { name } = useParams<"name">();
const token = useUserToken();
const { name, infos } = useAdapter();
const location = useLocation();
const [canPush, setCanPush] = useState<boolean>();
const [rows, setRows] = useState<ReleaseInfo[]>();
Expand All @@ -142,10 +141,6 @@ export function Releases() {
}
};
const loadReleases = async () => {
const token = user?.token;
if (!token || !name) {
return;
}
const gitHub = GitHubComm.forToken(token);
const repo = gitHub.getRepo(infos.repo);
const [npm, fullRepo, tags, latest, defaultHead] =
Expand Down Expand Up @@ -221,7 +216,7 @@ export function Releases() {
console.error(e);
setRows([]);
});
}, [name, user, infos]);
}, [name, token, infos]);

useEffect(() => {
const checkPackageInfo = async () => {
Expand Down
Loading

0 comments on commit e7280f0

Please sign in to comment.