Skip to content

Commit

Permalink
rework backend types
Browse files Browse the repository at this point in the history
  • Loading branch information
sinamics committed Aug 4, 2023
1 parent 3c02021 commit fe1505a
Show file tree
Hide file tree
Showing 12 changed files with 377 additions and 65 deletions.
53 changes: 50 additions & 3 deletions src/components/modules/networkDescription.tsx
Original file line number Diff line number Diff line change
@@ -1,15 +1,53 @@
import { useState, useEffect } from "react";
import React from "react";
import { api } from "~/utils/api";
import { useRouter } from "next/router";
import { useTranslations } from "next-intl";
import { type RouterInputs, type RouterOutputs, api } from "~/utils/api";
import {
type QueryClient,
useQueryClient,
type Query,
} from "@tanstack/react-query";
import { type CentralNetwork } from "~/types/central/network";
import { type NetworkEntity } from "~/types/local/network";

interface IProp {
central?: boolean;
}

const updateCache = ({
client,
data,
input,
}: {
client: QueryClient;
input: RouterInputs["network"]["getNetworkById"];
data: NetworkEntity | Partial<CentralNetwork>;
}) => {
client.setQueryData(
[
["network", "getNetworkById"],
{
input,
type: "query",
},
],
(oldData) => {
const newData = oldData as Query<
RouterOutputs["network"]["getNetworkById"]
>;
if ("network" in newData && newData.network && typeof data === "object") {
return {
...newData,
network: { ...(newData.network as object), ...(data as object) },
};
}
return newData;
}
);
};
const NetworkDescription = ({ central = false }: IProp) => {
const t = useTranslations("networkById");
const client = useQueryClient();
const { query } = useRouter();
const [state, setState] = useState({
toggleDescriptionInput: false,
Expand All @@ -34,7 +72,16 @@ const NetworkDescription = ({ central = false }: IProp) => {
}, [networkById?.network?.description]);

const { mutate: networkDescription } =
api.network.networkDescription.useMutation();
api.network.networkDescription.useMutation({
onSuccess: (data) => {
const input = {
nwid: query.id as string,
central,
};
// void refecthNetworkById();
updateCache({ client, data, input });
},
});

const toggleDescriptionInput = () => {
setState({
Expand Down
7 changes: 5 additions & 2 deletions src/components/modules/networkFlowRules.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ export const NetworkFlowRules = () => {
const { mutate: updateFlowRoute } = api.network.setFlowRule.useMutation({
onSuccess: () => {
void fetchFlowRoute({ nwid: query.id as string, reset: false });
void toast.success("Flow rules updated successfully");
},
onError: ({ message }) => {
try {
Expand Down Expand Up @@ -81,7 +82,7 @@ export const NetworkFlowRules = () => {
return (
<div
tabIndex={0}
className="collapse collapse-arrow w-full border border-base-300 bg-base-200"
className="collapse-arrow collapse w-full border border-base-300 bg-base-200"
>
<input type="checkbox" />
<div className="collapse-title">Flow Rules</div>
Expand All @@ -104,8 +105,10 @@ export const NetworkFlowRules = () => {
<button
onClick={() =>
void updateFlowRoute({
flowRoute: flowRoute || "#",
nwid: query.id as string,
updateParams: {
flowRoute: flowRoute || "#",
},
})
}
className="btn my-3 bg-base-300"
Expand Down
47 changes: 46 additions & 1 deletion src/components/modules/networkName.tsx
Original file line number Diff line number Diff line change
@@ -1,17 +1,54 @@
import { useEffect, useState } from "react";
import EditIcon from "~/icons/edit";
import Input from "~/components/elements/input";
import { api } from "~/utils/api";
import toast from "react-hot-toast";
import { useRouter } from "next/router";
import { useTranslations } from "next-intl";
import { type RouterInputs, type RouterOutputs, api } from "~/utils/api";
import {
type QueryClient,
type InfiniteData,
useQueryClient,
} from "@tanstack/react-query";
import { type CentralNetwork } from "~/types/central/network";
import { type NetworkEntity } from "~/types/local/network";

interface IProp {
central?: boolean;
}

const updateCache = ({
client,
data,
input,
}: {
client: QueryClient;
input: RouterInputs["network"]["getNetworkById"];
data: NetworkEntity | Partial<CentralNetwork>;
}) => {
client.setQueryData(
[
["network", "getNetworkById"],
{
input,
type: "query",
},
],
(oldData) => {
const newData = oldData as InfiniteData<
RouterOutputs["network"]["getNetworkById"]
>;
return {
...newData,
network: { ...data },
};
}
);
};

const NetworkName = ({ central = false }: IProp) => {
const t = useTranslations("networkById");
const client = useQueryClient();
const [state, setState] = useState({
editNetworkName: false,
networkName: "",
Expand All @@ -36,6 +73,14 @@ const NetworkName = ({ central = false }: IProp) => {
}, [networkById?.network?.name]);

const { mutate: updateNetworkName } = api.network.networkName.useMutation({
onSuccess: (data) => {
const input = {
nwid: query.id as string,
central,
};
// void refecthNetworkById();
updateCache({ client, data, input });
},
onError: (e) => {
void toast.error(e?.message);
},
Expand Down
6 changes: 3 additions & 3 deletions src/components/modules/networkPrivatePublic.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import {
useQueryClient,
} from "@tanstack/react-query";
import { type NetworkEntity } from "~/types/local/network";
import { type CentralNetwork } from "~/types/central/network";

interface IProp {
central?: boolean;
Expand All @@ -21,7 +22,7 @@ const updateCache = ({
}: {
client: QueryClient;
input: RouterInputs["network"]["getNetworkById"];
data: NetworkEntity;
data: NetworkEntity | Partial<CentralNetwork>;
}) => {
client.setQueryData(
[
Expand Down Expand Up @@ -61,7 +62,6 @@ export const NetworkPrivatePublic = ({ central = false }: IProp) => {
void toast.error(e?.message);
},
});

const privateHandler = (privateNetwork: boolean) => {
privatePublicNetwork(
{
Expand All @@ -70,7 +70,7 @@ export const NetworkPrivatePublic = ({ central = false }: IProp) => {
central,
},
{
onSuccess: (data: NetworkEntity) => {
onSuccess: (data) => {
const input = {
nwid: query.id as string,
central,
Expand Down
159 changes: 159 additions & 0 deletions src/components/modules/ztCentral/centralFlowRules.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,159 @@
import { toast } from "react-hot-toast";
import { api } from "~/utils/api";
import CodeMirror from "@uiw/react-codemirror";
import { okaidia } from "@uiw/codemirror-theme-okaidia";
import { classname } from "@uiw/codemirror-extensions-classname";
import { python } from "@codemirror/lang-python";
import { useEffect, useState } from "react";
import { EditorView } from "@codemirror/view";
// import { useDebounce } from "usehooks-ts";
import { type CustomBackendError } from "~/types/errorHandling";
import { useRouter } from "next/router";

interface IProp {
central?: boolean;
}

const initialErrorState = { error: null, line: null };
export const CentralFlowRules = ({ central = true }: IProp) => {
const { query } = useRouter();

const {
data: defaultFlowRoute,
// isLoading,
mutate: fetchFlowRoute,
} = api.network.getFlowRule.useMutation();

// Local state to store changes to the flow route
const {
data: networkById,
isLoading: loadingNetwork,
error: errorNetwork,
refetch: refetchNetworkById,
} = api.network.getNetworkById.useQuery({
nwid: query.id as string,
central,
});

const [flowRoute, setFlowRoute] = useState(networkById?.network?.rulesSource);
const [ruleError, setRuleError] = useState(initialErrorState);
// const debouncedFlowRoute = useDebounce(flowRoute, 500);

const { mutate: updateFlowRoute } = api.network.setFlowRule.useMutation({
onSuccess: () => {
void refetchNetworkById();
void toast.success("Flow rules updated successfully");
},
onError: ({ message }) => {
try {
const err = JSON.parse(message) as CustomBackendError;
setRuleError({ error: err.error, line: err.line });
void toast.error(err.error);
} catch (error) {
// eslint-disable-next-line no-console
console.log(error);
}
},
});

useEffect(() => {
setFlowRoute(defaultFlowRoute);
}, [defaultFlowRoute]);

useEffect(() => {
setFlowRoute(networkById?.network?.rulesSource);
}, [networkById?.network?.rulesSource]);

// Handle changes in CodeMirror
const handleFlowRouteChange = (value: string) => {
setFlowRoute(value);
setRuleError(initialErrorState);
// debouncedUpdateFlowRoute();
};
// Reset the flow route to the default value
const handleReset = () => {
fetchFlowRoute({
nwid: query.id as string,
central,
});
setRuleError(initialErrorState);
};
const classnameExt = classname({
add: (lineNumber) => {
if (lineNumber === ruleError.line) {
return "first-line";
}
},
});
const errorColorTheme = EditorView.baseTheme({
"&dark .first-line": { backgroundColor: "#AB2204" },
"&light .first-line": { backgroundColor: "#AB2204" },
});

if (loadingNetwork) {
// add loading progress bar to center of page, vertially and horizontally
return (
<div className="flex flex-col items-center justify-center">
<h1 className="text-center text-2xl font-semibold">
<progress className="progress progress-primary w-56"></progress>
</h1>
</div>
);
}
if (errorNetwork) {
return (
<div className="flex flex-col items-center justify-center">
<h1 className="text-center text-2xl font-semibold">
{errorNetwork.message}
</h1>
</div>
);
}
return (
<div
tabIndex={0}
className="collapse-arrow collapse w-full border border-base-300 bg-base-200"
>
<input type="checkbox" />
<div className="collapse-title">Flow Rules</div>
<div className="collapse-content" style={{ width: "100%" }}>
<CodeMirror
tabIndex={0}
value={flowRoute}
onChange={handleFlowRouteChange}
maxHeight="1500px"
width="100%"
theme={okaidia}
extensions={[python(), errorColorTheme, classnameExt]}
basicSetup={{
lineNumbers: true,
highlightActiveLineGutter: false,
highlightActiveLine: false,
}}
/>
<div className="space-x-4">
<button
onClick={() =>
void updateFlowRoute({
central,
nwid: query.id as string,
updateParams: {
flowRoute: flowRoute || "#",
},
})
}
className="btn my-3 bg-base-300"
>
Save Changes
</button>
<button
onClick={() => handleReset()}
className="btn btn-outline my-3 "
>
Reset
</button>
</div>
</div>
</div>
);
};
4 changes: 2 additions & 2 deletions src/pages/central/[id].tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import CopyIcon from "~/icons/copy";
import toast from "react-hot-toast";
// import { DeletedNetworkMembersTable } from "~/components/modules/deletedNetworkMembersTable";
import { useModalStore } from "~/utils/store";
import { NetworkFlowRules } from "~/components/modules/networkFlowRules";
import { CentralFlowRules } from "~/components/modules/ztCentral/centralFlowRules";
import { NetworkDns } from "~/components/modules/networkDns";
import { NetworkMulticast } from "~/components/modules/networkMulticast";
import cn from "classnames";
Expand Down Expand Up @@ -237,7 +237,7 @@ const CentralNetworkById = () => {
</div>

<div className="w-5/5 mx-auto flex px-4 py-4 text-sm sm:w-4/5 sm:px-10 md:text-base">
<NetworkFlowRules />
<CentralFlowRules />
</div>
<div className="w-5/5 divider mx-auto flex px-4 py-4 text-sm sm:w-4/5 sm:px-10 md:text-base">
Network Actions
Expand Down
Loading

0 comments on commit fe1505a

Please sign in to comment.