poll embed

This commit is contained in:
PhilReact 2024-11-26 10:12:56 +02:00
parent 8aa5e0cd4c
commit 4e93b597aa
5 changed files with 116 additions and 9 deletions

View File

@ -1142,6 +1142,24 @@ function App() {
}; };
}, []); }, []);
const openGlobalSnackBarFunc = (e) => {
const message = e.detail?.message;
const type = e.detail?.type;
setOpenSnack(true);
setInfoSnack({
type,
message
});
};
useEffect(() => {
subscribeToEvent("openGlobalSnackBar", openGlobalSnackBarFunc);
return () => {
unsubscribeFromEvent("openGlobalSnackBar", openGlobalSnackBarFunc);
};
}, []);
const openPaymentInternal = (e) => { const openPaymentInternal = (e) => {
const directAddress = e.detail?.address; const directAddress = e.detail?.address;
const name = e.detail?.name; const name = e.detail?.name;

View File

@ -182,7 +182,7 @@ const UIQortalRequests = [
'GET_WALLET_BALANCE', 'GET_USER_WALLET_INFO', 'GET_CROSSCHAIN_SERVER_INFO', 'GET_WALLET_BALANCE', 'GET_USER_WALLET_INFO', 'GET_CROSSCHAIN_SERVER_INFO',
'GET_TX_ACTIVITY_SUMMARY', 'GET_FOREIGN_FEE', 'UPDATE_FOREIGN_FEE', 'GET_TX_ACTIVITY_SUMMARY', 'GET_FOREIGN_FEE', 'UPDATE_FOREIGN_FEE',
'GET_SERVER_CONNECTION_HISTORY', 'SET_CURRENT_FOREIGN_SERVER', 'GET_SERVER_CONNECTION_HISTORY', 'SET_CURRENT_FOREIGN_SERVER',
'ADD_FOREIGN_SERVER', 'REMOVE_FOREIGN_SERVER', 'GET_DAY_SUMMARY', 'CREATE_TRADE_BUY_ORDER', 'CREATE_TRADE_SELL_ORDER', 'CANCEL_TRADE_SELL_ORDER', 'IS_USING_GATEWAY', 'ADMIN_ACTION', 'SIGN_TRANSACTION', 'OPEN_NEW_TAB' 'ADD_FOREIGN_SERVER', 'REMOVE_FOREIGN_SERVER', 'GET_DAY_SUMMARY', 'CREATE_TRADE_BUY_ORDER', 'CREATE_TRADE_SELL_ORDER', 'CANCEL_TRADE_SELL_ORDER', 'IS_USING_GATEWAY', 'ADMIN_ACTION', 'SIGN_TRANSACTION', 'OPEN_NEW_TAB', 'CREATE_AND_COPY_EMBED_LINK'
]; ];

View File

@ -22,7 +22,7 @@ import OpenInNewIcon from "@mui/icons-material/OpenInNew";
import { extractComponents } from "../Chat/MessageDisplay"; import { extractComponents } from "../Chat/MessageDisplay";
import { executeEvent } from "../../utils/events"; import { executeEvent } from "../../utils/events";
import { CustomLoader } from "../../common/CustomLoader"; import { CustomLoader } from "../../common/CustomLoader";
import PollIcon from '@mui/icons-material/Poll';
function decodeHTMLEntities(str) { function decodeHTMLEntities(str) {
const txt = document.createElement("textarea"); const txt = document.createElement("textarea");
txt.innerHTML = str; txt.innerHTML = str;
@ -52,7 +52,7 @@ const parseQortalLink = (link) => {
const [key, value] = pair.split("="); const [key, value] = pair.split("=");
if (key && value) { if (key && value) {
const decodedKey = decodeURIComponent(key.trim()); const decodedKey = decodeURIComponent(key.trim());
const decodedValue = decodeURIComponent(value.trim()).replace( const decodedValue = value.trim().replace(
/<\/?[^>]+(>|$)/g, /<\/?[^>]+(>|$)/g,
"" // Remove any HTML tags "" // Remove any HTML tags
); );
@ -115,10 +115,10 @@ export const Embed = ({ embedLink }) => {
const pollRes = await getPoll(parsedData.name); const pollRes = await getPoll(parsedData.name);
setPoll(pollRes); setPoll(pollRes);
if (parsedData?.ref) { if (parsedData?.ref) {
const res = extractComponents(parsedData.ref); const res = extractComponents(decodeURIComponent(parsedData.ref));
const { service, name, identifier, path } = res;
if (service && name) { if (res?.service && res?.name) {
setExternal(res); setExternal(res);
} }
} }
@ -131,6 +131,7 @@ export const Embed = ({ embedLink }) => {
const handleLink = () => { const handleLink = () => {
try { try {
const parsedData = parseQortalLink(embedLink); const parsedData = parseQortalLink(embedLink);
console.log('parsedData', parsedData)
const type = parsedData?.type; const type = parsedData?.type;
switch (type) { switch (type) {
case "POLL": case "POLL":
@ -204,7 +205,7 @@ export const PollCard = ({
const fee = await getFee("VOTE_ON_POLL"); const fee = await getFee("VOTE_ON_POLL");
await show({ await show({
message: `Do you accept this VOTE_ON_POLL transaction?`, message: `Do you accept this VOTE_ON_POLL transaction? POLLS are public!`,
publishFee: fee.fee + " QORT", publishFee: fee.fee + " QORT",
}); });
setIsLoadingSubmit(true); setIsLoadingSubmit(true);
@ -261,6 +262,8 @@ export const PollCard = ({
} }
}, [poll?.info?.owner]); }, [poll?.info?.owner]);
console.log('ownerName', ownerName)
return ( return (
<Card <Card
sx={{ sx={{
@ -277,7 +280,18 @@ export const PollCard = ({
padding: "16px 16px 0px 16px", padding: "16px 16px 0px 16px",
}} }}
> >
<Box
sx={{
display: "flex",
alignItems: "center",
gap: "10px",
}}
>
<PollIcon sx={{
color: 'white'
}} />
<Typography>POLL embed</Typography> <Typography>POLL embed</Typography>
</Box>
<Box <Box
sx={{ sx={{
display: "flex", display: "flex",
@ -389,7 +403,9 @@ export const PollCard = ({
title={poll?.info?.pollName} title={poll?.info?.pollName}
subheader={poll?.info?.description} subheader={poll?.info?.description}
sx={{ sx={{
fontSize: "18px", "& .MuiCardHeader-title": {
fontSize: "18px", // Custom font size for title
},
}} }}
/> />
<CardContent> <CardContent>

View File

@ -1,5 +1,5 @@
import { gateways, getApiKeyFromStorage } from "./background"; import { gateways, getApiKeyFromStorage } from "./background";
import { addForeignServer, addListItems, adminAction, cancelSellOrder, createBuyOrder, createPoll, createSellOrder, decryptData, deleteListItems, deployAt, encryptData, getCrossChainServerInfo, getDaySummary, getForeignFee, getListItems, getServerConnectionHistory, getTxActivitySummary, getUserAccount, getUserWallet, getUserWalletInfo, getWalletBalance, joinGroup, openNewTab, publishMultipleQDNResources, publishQDNResource, removeForeignServer, saveFile, sendChatMessage, sendCoin, setCurrentForeignServer, signTransaction, updateForeignFee, voteOnPoll } from "./qortalRequests/get"; import { addForeignServer, addListItems, adminAction, cancelSellOrder, createAndCopyEmbedLink, createBuyOrder, createPoll, createSellOrder, decryptData, deleteListItems, deployAt, encryptData, getCrossChainServerInfo, getDaySummary, getForeignFee, getListItems, getServerConnectionHistory, getTxActivitySummary, getUserAccount, getUserWallet, getUserWalletInfo, getWalletBalance, joinGroup, openNewTab, publishMultipleQDNResources, publishQDNResource, removeForeignServer, saveFile, sendChatMessage, sendCoin, setCurrentForeignServer, signTransaction, updateForeignFee, voteOnPoll } from "./qortalRequests/get";
import { getData, storeData } from "./utils/chromeStorage"; import { getData, storeData } from "./utils/chromeStorage";
@ -729,6 +729,26 @@ export const isRunningGateway = async ()=> {
} }
break; break;
} }
case "CREATE_AND_COPY_EMBED_LINK": {
try {
const res = await createAndCopyEmbedLink(request.payload, isFromExtension)
event.source.postMessage({
requestId: request.requestId,
action: request.action,
payload: res,
type: "backgroundMessageResponse",
}, event.origin);
} catch (error) {
event.source.postMessage({
requestId: request.requestId,
action: request.action,
error: error?.message,
type: "backgroundMessageResponse",
}, event.origin);
}
break;
}
default: default:
break; break;

View File

@ -3055,3 +3055,56 @@ export const signTransaction = async (data, isFromExtension) => {
throw new Error("User declined request"); throw new Error("User declined request");
} }
}; };
const encode = (value) => encodeURIComponent(value.trim()); // Helper to encode values
export const createAndCopyEmbedLink = async (data, isFromExtension) => {
const requiredFields = [
"type",
"name"
];
const missingFields: string[] = [];
requiredFields.forEach((field) => {
if (!data[field]) {
missingFields.push(field);
}
});
if (missingFields.length > 0) {
const missingFieldsString = missingFields.join(", ");
const errorMsg = `Missing fields: ${missingFieldsString}`;
throw new Error(errorMsg);
}
switch (data.type) {
case "POLL": {
const queryParams = [
`name=${encode(data.name)}`,
data.ref ? `ref=${encode(data.ref)}` : null, // Add only if ref exists
]
.filter(Boolean) // Remove null values
.join("&"); // Join with `&`
const link = `qortal://use-embed/POLL?${queryParams}`
navigator.clipboard.writeText(link)
.then(() => {
executeEvent('openGlobalSnackBar', {
message: 'Copied link to clipboard',
type: 'info'
})
//success
})
.catch((error) => {
executeEvent('openGlobalSnackBar', {
message: 'Failed to copy to clipboard',
type: 'error'
})
// error
});
return link;
}
default:
throw new Error('Invalid type')
}
};