Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Make alerts general purpose #72

Merged
merged 5 commits into from
Feb 23, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Binary file modified bun.lockb
Binary file not shown.
36 changes: 36 additions & 0 deletions components/alert/alert-container.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import { FC } from "react";
import { useAlertContext } from "@/context/AlertContext";
import { AlertCard, AlertVariant } from "@aragon/ods";
import { IAlert } from "@/utils/types";

const AlertContainer: FC = () => {
const { alerts } = useAlertContext();

return (
<div className="fixed bottom-0 right-0 w-96 m-10">
{alerts.map((alert: IAlert) => (
<AlertCard
className="mt-4 drop-shadow-lg"
key={alert.id}
message={alert.message}
description={alert.description}
variant={resolveVariant(alert.type)}
/>
))}
</div>
);
};

function resolveVariant(type: IAlert["type"]) {
let result: AlertVariant;
switch (type) {
case "error":
result = "critical";
break;
default:
result = type;
}
return result;
}

export default AlertContainer;
18 changes: 0 additions & 18 deletions components/alert/alerts.tsx

This file was deleted.

54 changes: 0 additions & 54 deletions components/alert/index.tsx

This file was deleted.

64 changes: 52 additions & 12 deletions context/AlertContext.tsx
Original file line number Diff line number Diff line change
@@ -1,29 +1,69 @@
import React, { createContext, useState, useContext } from 'react';
import { IAlert } from '@/utils/types'
import React, { createContext, useState, useContext } from "react";
import { IAlert } from "@/utils/types";
import { usePublicClient } from "wagmi";

const DEFAULT_ALERT_TIMEOUT = 7 * 1000;

export type AlertOptions = {
type?: "success" | "info" | "error";
description?: string;
txHash?: string;
timeout?: number;
};

export interface AlertContextProps {
alerts: IAlert[];
addAlert: (message: string, txHash: string) => void;
removeAlert: (id: number) => void;
addAlert: (message: string, alertOptions?: AlertOptions) => void;
}

export const AlertContext = createContext<AlertContextProps | undefined>(undefined);
export const AlertContext = createContext<AlertContextProps | undefined>(
undefined
);

export const AlertProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
export const AlertProvider: React.FC<{ children: React.ReactNode }> = ({
children,
}) => {
const [alerts, setAlerts] = useState<IAlert[]>([]);
const client = usePublicClient();

// Add a new alert to the list
const addAlert = (message: string, alertOptions?: AlertOptions) => {
// Clean duplicates
const idx = alerts.findIndex((a) => {
if (a.message !== message) return false;
else if (a.description !== alertOptions?.description) return false;
else if (a.type !== alertOptions?.type) return false;

return true;
});
if (idx >= 0) removeAlert(idx);

const newAlert: IAlert = {
id: Date.now(),
message,
description: alertOptions?.description,
type: alertOptions?.type ?? "info",
};
if (alertOptions?.txHash && client) {
newAlert.explorerLink =
client.chain.blockExplorers?.default.url + "/tx/" + alertOptions.txHash;
}
setAlerts(alerts.concat(newAlert));

// Function to add a new alert
const addAlert = (message: string, txHash: string) => {
setAlerts([...alerts, { message, txHash, id: Date.now() }]);
// Schedule the clean-up
const timeout = alertOptions?.timeout ?? DEFAULT_ALERT_TIMEOUT;
setTimeout(() => {
removeAlert(newAlert.id);
}, timeout);
};

// Function to remove an alert
const removeAlert = (id: number) => {
setAlerts(alerts?.filter((alert) => alert.id !== id));
setAlerts(alerts.filter((alert) => alert.id !== id));
};

return (
<AlertContext.Provider value={{ alerts, addAlert, removeAlert }}>
<AlertContext.Provider value={{ alerts, addAlert }}>
{children}
</AlertContext.Provider>
);
Expand All @@ -33,7 +73,7 @@ export const useAlertContext = () => {
const context = useContext(AlertContext);

if (!context) {
throw new Error('useThemeContext must be used inside the AlertProvider');
throw new Error("useContext must be used inside the AlertProvider");
}

return context;
Expand Down
2 changes: 0 additions & 2 deletions context/index.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import { AlertProvider } from "./AlertContext";
import Alerts from "@/components/alert/alerts";
import { ReactNode } from "react";
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { config } from "@/context/Web3Modal";
Expand All @@ -22,7 +21,6 @@ export function RootContextProvider({ children, initialState }: { children: Reac
<QueryClientProvider client={queryClient}>
<AlertProvider>
{children}
<Alerts />
</AlertProvider>
</QueryClientProvider>
</WagmiProvider>
Expand Down
2 changes: 2 additions & 0 deletions pages/_app.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { RootContextProvider } from "@/context";
import { Layout } from "@/components/layout";
import AlertContainer from "@/components/alert/alert-container";
import { Manrope } from "next/font/google";
import "@aragon/ods/index.css";
import "@/pages/globals.css";
Expand All @@ -22,6 +23,7 @@ export default function AragonetteApp({ Component, pageProps }: any) {
<Layout>
<Component {...pageProps} />
</Layout>
<AlertContainer />
</RootContextProvider>
</div>
);
Expand Down
90 changes: 65 additions & 25 deletions plugins/dualGovernance/components/proposal/header.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,13 @@ import { Proposal } from "@/plugins/dualGovernance/utils/types";
import { AlertVariant } from "@aragon/ods";
import { Else, If, IfCase, Then } from "@/components/if";
import { AddressText } from "@/components/text/address";
import { useWriteContract } from "wagmi";
import { useWaitForTransactionReceipt, useWriteContract } from "wagmi";
import { OptimisticTokenVotingPluginAbi } from "../../artifacts/OptimisticTokenVotingPlugin.sol";
import { AlertContextProps, useAlertContext } from "@/context/AlertContext";
import { useProposalVariantStatus } from "../../hooks/useProposalVariantStatus";
import { PUB_CHAIN, PUB_DUAL_GOVERNANCE_PLUGIN_ADDRESS } from "@/constants";
import { PleaseWaitSpinner } from "@/components/please-wait";
import { useRouter } from "next/router";

const DEFAULT_PROPOSAL_TITLE = "(No proposal title)";

Expand All @@ -28,23 +29,62 @@ const ProposalHeader: React.FC<ProposalHeaderProps> = ({
transactionLoading,
onVetoPressed,
}) => {
const { writeContract: executeWrite, data: executeResponse } = useWriteContract()
const { reload } = useRouter();
const { addAlert } = useAlertContext() as AlertContextProps;
const proposalVariant = useProposalVariantStatus(proposal);

const {
writeContract: executeWrite,
data: executeTxHash,
error,
status,
} = useWriteContract();
const { isLoading: isConfirming, isSuccess: isConfirmed } =
useWaitForTransactionReceipt({ hash: executeTxHash });

const executeButtonPressed = () => {
executeWrite({
chainId: PUB_CHAIN.id,
abi: OptimisticTokenVotingPluginAbi,
address: PUB_DUAL_GOVERNANCE_PLUGIN_ADDRESS,
functionName: 'execute',
args: [proposalNumber]
})
}
functionName: "execute",
args: [proposalNumber],
});
};

useEffect(() => {
if (executeResponse) addAlert('Your execution has been submitted', executeResponse)
}, [executeResponse])
if (status === "idle" || status === "pending") return;
else if (status === "error") {
if (error?.message?.startsWith("User rejected the request")) {
addAlert("Transaction rejected by the user", {
timeout: 4 * 1000,
});
} else {
console.error(error);
addAlert("Could not execute the proposal", { type: "error" });
}
return;
}

// success
if (!executeTxHash) return;
else if (isConfirming) {
addAlert("Proposal submitted", {
description: "Waiting for the transaction to be validated",
type: "info",
txHash: executeTxHash,
});
return;
} else if (!isConfirmed) return;

addAlert("Proposal executed", {
description: "The transaction has been validated",
type: "success",
txHash: executeTxHash,
});

setTimeout(() => reload(), 1000 * 2);
}, [status, executeTxHash, isConfirming, isConfirmed]);

return (
<div className="w-full">
Expand All @@ -54,13 +94,13 @@ const ProposalHeader: React.FC<ProposalHeaderProps> = ({
{/** bg-info-200 bg-success-200 bg-critical-200
* text-info-800 text-success-800 text-critical-800
*/}
<div className="flex">
<Tag
className="text-center text-critical-800"
label={proposalVariant.label}
variant={proposalVariant.variant as AlertVariant}
/>
</div>
<div className="flex">
<Tag
className="text-center text-critical-800"
label={proposalVariant.label}
variant={proposalVariant.variant as AlertVariant}
/>
</div>
<span className="text-xl font-semibold text-neutral-700 pt-1">
Proposal {proposalNumber + 1}
</span>
Expand All @@ -76,8 +116,8 @@ const ProposalHeader: React.FC<ProposalHeaderProps> = ({
size="lg"
variant="primary"
onClick={() => onVetoPressed()}
>
Veto
>
Veto
</Button>
</Then>
<Else>
Expand All @@ -88,15 +128,15 @@ const ProposalHeader: React.FC<ProposalHeaderProps> = ({
</IfCase>
</Then>
<Else>
<If condition={proposalVariant.label === 'Executable'}>
<If condition={proposalVariant.label === "Executable"}>
<Button
className="flex h-5 items-center"
size="lg"
variant="success"
onClick={() => executeButtonPressed()}
>
Execute
</Button>
className="flex h-5 items-center"
size="lg"
variant="success"
onClick={() => executeButtonPressed()}
>
Execute
</Button>
</If>
</Else>
</IfCase>
Expand Down
Loading
Loading