finished app info

This commit is contained in:
PhilReact 2024-10-20 03:00:25 +03:00
parent 4a026bccc7
commit ba53e83b13
5 changed files with 349 additions and 240 deletions

View File

@ -1,13 +1,14 @@
import { Box } from "@mui/material"; import { Box } from "@mui/material";
export const Spacer = ({ height, width }: any) => { export const Spacer = ({ height, width, ...props }: any) => {
return ( return (
<Box <Box
sx={{ sx={{
height: height ? height : '0px', height: height ? height : '0px',
display: 'flex', display: 'flex',
flexShrink: 0, flexShrink: 0,
width: width ? width : '0px' width: width ? width : '0px',
...(props || {})
}} }}
/> />
); );

View File

@ -11,6 +11,11 @@ import {
AppInfoSnippetMiddle, AppInfoSnippetMiddle,
AppInfoSnippetRight, AppInfoSnippetRight,
AppInfoUserName, AppInfoUserName,
AppsCategoryInfo,
AppsCategoryInfoLabel,
AppsCategoryInfoSub,
AppsCategoryInfoValue,
AppsInfoDescription,
AppsLibraryContainer, AppsLibraryContainer,
AppsParent, AppsParent,
AppsWidthLimiter, AppsWidthLimiter,
@ -22,88 +27,111 @@ import LogoSelected from "../../assets/svgs/LogoSelected.svg";
import { Spacer } from "../../common/Spacer"; import { Spacer } from "../../common/Spacer";
import { executeEvent } from "../../utils/events"; import { executeEvent } from "../../utils/events";
import { AppRating } from "./AppRating";
export const AppInfo = ({ app }) => { export const AppInfo = ({ app, myName }) => {
const isInstalled = app?.status?.status === "READY";
const isInstalled = app?.status?.status === 'READY'
return ( return (
<AppsLibraryContainer> <AppsLibraryContainer>
<AppsWidthLimiter> <AppsWidthLimiter>
<AppInfoSnippetContainer> <AppInfoSnippetContainer>
<AppInfoSnippetLeft sx={{ <AppInfoSnippetLeft
flexGrow: 1,
gap: '18px'
}}>
<AppCircleContainer sx={{
width: 'auto'
}}>
<AppCircle
sx={{ sx={{
border: "none", flexGrow: 1,
height: '100px', gap: "18px",
width: '100px'
}} }}
> >
<Avatar <AppCircleContainer
sx={{ sx={{
height: "43px", width: "auto",
width: "43px",
'& img': {
objectFit: 'fill',
}
}} }}
alt={app?.name}
src={`${getBaseApiReact()}/arbitrary/THUMBNAIL/${
app?.name
}/qortal_avatar?async=true`}
> >
<img <AppCircle
style={{ sx={{
width: "43px", border: "none",
height: "auto", height: "100px",
width: "100px",
}} }}
src={LogoSelected} >
alt="center-icon" <Avatar
/> sx={{
</Avatar> height: "43px",
</AppCircle> width: "43px",
</AppCircleContainer> "& img": {
<AppInfoSnippetMiddle> objectFit: "fill",
},
<AppInfoAppName > }}
{app?.metadata?.title || app?.name} alt={app?.name}
</AppInfoAppName> src={`${getBaseApiReact()}/arbitrary/THUMBNAIL/${
<Spacer height="6px" /> app?.name
<AppInfoUserName> }/qortal_avatar?async=true`}
{ app?.name} >
</AppInfoUserName> <img
<Spacer height="3px" /> style={{
width: "43px",
</AppInfoSnippetMiddle> height: "auto",
}}
</AppInfoSnippetLeft> src={LogoSelected}
<AppInfoSnippetRight> alt="center-icon"
/>
</AppInfoSnippetRight> </Avatar>
</AppInfoSnippetContainer> </AppCircle>
<Spacer height="11px" /> </AppCircleContainer>
<AppDownloadButton onClick={()=> { <AppInfoSnippetMiddle>
executeEvent("addTab", { <AppInfoAppName>
data: app {app?.metadata?.title || app?.name}
}) </AppInfoAppName>
}} sx={{ <Spacer height="6px" />
backgroundColor: isInstalled ? '#0091E1' : '#247C0E', <AppInfoUserName>{app?.name}</AppInfoUserName>
width: '100%', <Spacer height="3px" />
maxWidth: '320px', </AppInfoSnippetMiddle>
height: '29px' </AppInfoSnippetLeft>
}}> <AppInfoSnippetRight></AppInfoSnippetRight>
<AppDownloadButtonText>{isInstalled ? 'Open' : 'Download'}</AppDownloadButtonText> </AppInfoSnippetContainer>
<Spacer height="11px" />
<AppDownloadButton
onClick={() => {
executeEvent("addTab", {
data: app,
});
}}
sx={{
backgroundColor: isInstalled ? "#0091E1" : "#247C0E",
width: "100%",
maxWidth: "320px",
height: "29px",
}}
>
<AppDownloadButtonText>
{isInstalled ? "Open" : "Download"}
</AppDownloadButtonText>
</AppDownloadButton> </AppDownloadButton>
</AppsWidthLimiter> </AppsWidthLimiter>
<Spacer height="20px" />
<AppsWidthLimiter>
<AppsCategoryInfo>
<AppRating ratingCountPosition="top" myName={myName} app={app} />
<Spacer width="16px" />
<Spacer height="40px" width="1px" backgroundColor="white" />
<Spacer width="16px" />
<AppsCategoryInfoSub>
<AppsCategoryInfoLabel>Category:</AppsCategoryInfoLabel>
<Spacer height="4px" />
<AppsCategoryInfoValue>
{app?.metadata?.categoryName || "none"}
</AppsCategoryInfoValue>
</AppsCategoryInfoSub>
</AppsCategoryInfo>
<Spacer height="30px" />
<AppInfoAppName>
About this Q-App
</AppInfoAppName>
</AppsWidthLimiter>
<Spacer height="20px" />
<AppsInfoDescription>
{app?.metadata?.description || "No description"}
</AppsInfoDescription>
</AppsLibraryContainer> </AppsLibraryContainer>
); );
}; };

View File

@ -1,202 +1,251 @@
import { Box, Rating, Typography } from "@mui/material"; import { Box, Rating, Typography } from "@mui/material";
import React, { useCallback, useContext, useEffect, useRef, useState } from "react"; import React, {
useCallback,
useContext,
useEffect,
useRef,
useState,
} from "react";
import { getFee } from "../../background"; import { getFee } from "../../background";
import { MyContext, getBaseApiReact } from "../../App"; import { MyContext, getBaseApiReact } from "../../App";
import { CustomizedSnackbars } from "../Snackbar/Snackbar"; import { CustomizedSnackbars } from "../Snackbar/Snackbar";
import { StarFilledIcon } from "../../assets/svgs/StarFilled"; import { StarFilledIcon } from "../../assets/svgs/StarFilled";
import { StarEmptyIcon } from "../../assets/svgs/StarEmpty"; import { StarEmptyIcon } from "../../assets/svgs/StarEmpty";
import { AppInfoUserName } from "./Apps-styles"; import { AppInfoUserName } from "./Apps-styles";
import { Spacer } from "../../common/Spacer";
export const AppRating = ({app, myName, ratingCountPosition = 'right'}) => { export const AppRating = ({ app, myName, ratingCountPosition = "right" }) => {
const [value, setValue] = useState(0); const [value, setValue] = useState(0);
const { show } = useContext(MyContext); const { show } = useContext(MyContext);
const [hasPublishedRating, setHasPublishedRating] = useState<null | boolean>(null) const [hasPublishedRating, setHasPublishedRating] = useState<null | boolean>(
const [pollInfo, setPollInfo] = useState(null) null
const [votesInfo, setVotesInfo] = useState(null) );
const [openSnack, setOpenSnack] = useState(false); const [pollInfo, setPollInfo] = useState(null);
const [infoSnack, setInfoSnack] = useState(null); const [votesInfo, setVotesInfo] = useState(null);
const hasCalledRef = useRef(false) const [openSnack, setOpenSnack] = useState(false);
console.log(`pollinfo-${app?.service}-${app?.name}`, value) const [infoSnack, setInfoSnack] = useState(null);
const hasCalledRef = useRef(false);
console.log(`pollinfo-${app?.service}-${app?.name}`, value);
console.log('hasPublishedRating', hasPublishedRating) console.log("hasPublishedRating", hasPublishedRating);
const getRating = useCallback(async (name, service)=> { const getRating = useCallback(async (name, service) => {
try { try {
hasCalledRef.current = true;
const pollName = `app-library-${service}-rating-${name}`;
const url = `${getBaseApiReact()}/polls/${pollName}`;
hasCalledRef.current = true const response = await fetch(url, {
const pollName = `app-library-${service}-rating-${name}` method: "GET",
const url = `${getBaseApiReact()}/polls/${pollName}`; headers: {
"Content-Type": "application/json",
},
});
const response = await fetch(url, { const responseData = await response.json();
method: "GET", console.log("responseData", responseData);
headers: { if (responseData?.message?.includes("POLL_NO_EXISTS")) {
"Content-Type": "application/json", setHasPublishedRating(false);
}, } else if (responseData?.pollName) {
}); setPollInfo(responseData);
setHasPublishedRating(true);
const responseData = await response.json();
console.log('responseData', responseData)
if(responseData?.message?.includes('POLL_NO_EXISTS')){
setHasPublishedRating(false)
} else if(responseData?.pollName){
setPollInfo(responseData)
setHasPublishedRating(true)
const urlVotes = `${getBaseApiReact()}/polls/votes/${pollName}`; const urlVotes = `${getBaseApiReact()}/polls/votes/${pollName}`;
const responseVotes = await fetch(urlVotes, { const responseVotes = await fetch(urlVotes, {
method: "GET", method: "GET",
headers: { headers: {
"Content-Type": "application/json", "Content-Type": "application/json",
}, },
}); });
const responseDataVotes = await responseVotes.json();
setVotesInfo(responseDataVotes)
const voteCount = responseDataVotes.voteCounts
// Include initial value vote in the calculation
const ratingVotes = voteCount.filter(vote => !vote.optionName.startsWith("initialValue-"));
const initialValueVote = voteCount.find(vote => vote.optionName.startsWith("initialValue-"));
console.log('initialValueVote', initialValueVote)
if (initialValueVote) {
// Convert "initialValue-X" to just "X" and add it to the ratingVotes array
const initialRating = parseInt(initialValueVote.optionName.split("-")[1], 10);
console.log('initialRating', initialRating)
ratingVotes.push({
optionName: initialRating.toString(),
voteCount: 1,
});
}
// Calculate the weighted average const responseDataVotes = await responseVotes.json();
let totalScore = 0; setVotesInfo(responseDataVotes);
let totalVotes = 0; const voteCount = responseDataVotes.voteCounts;
// Include initial value vote in the calculation
ratingVotes.forEach(vote => { const ratingVotes = voteCount.filter(
const rating = parseInt(vote.optionName, 10); // Extract rating value (1-5) (vote) => !vote.optionName.startsWith("initialValue-")
const count = vote.voteCount; );
totalScore += rating * count; // Weighted score const initialValueVote = voteCount.find((vote) =>
totalVotes += count; // Total number of votes vote.optionName.startsWith("initialValue-")
}); );
console.log('ratingVotes', ratingVotes, totalScore, totalVotes) console.log("initialValueVote", initialValueVote);
if (initialValueVote) {
// Calculate average rating (ensure no division by zero) // Convert "initialValue-X" to just "X" and add it to the ratingVotes array
const averageRating = totalVotes > 0 ? (totalScore / totalVotes) : 0; const initialRating = parseInt(
setValue(averageRating); initialValueVote.optionName.split("-")[1],
} 10
} catch (error) { );
console.log('error rating', error) console.log("initialRating", initialRating);
if(error?.message?.includes('POLL_NO_EXISTS')){ ratingVotes.push({
setHasPublishedRating(false) optionName: initialRating.toString(),
voteCount: 1,
});
} }
// Calculate the weighted average
let totalScore = 0;
let totalVotes = 0;
ratingVotes.forEach((vote) => {
const rating = parseInt(vote.optionName, 10); // Extract rating value (1-5)
const count = vote.voteCount;
totalScore += rating * count; // Weighted score
totalVotes += count; // Total number of votes
});
console.log("ratingVotes", ratingVotes, totalScore, totalVotes);
// Calculate average rating (ensure no division by zero)
const averageRating = totalVotes > 0 ? totalScore / totalVotes : 0;
setValue(averageRating);
}
} catch (error) {
console.log("error rating", error);
if (error?.message?.includes("POLL_NO_EXISTS")) {
setHasPublishedRating(false);
}
} }
}, []);
useEffect(() => {
if (hasCalledRef.current) return;
if (!app) return;
getRating(app?.name, app?.service);
}, [getRating, app?.name]);
const rateFunc = async (event, newValue) => {
}, [])
useEffect(()=> {
if(hasCalledRef.current) return
if(!app) return
getRating(app?.name, app?.service)
}, [getRating, app?.name])
const rateFunc = async (event, newValue)=> {
try { try {
if(!myName) throw new Error('You need a name to rate.') if (!myName) throw new Error("You need a name to rate.");
if(!app?.name) return if (!app?.name) return;
console.log('newValue', newValue) console.log("newValue", newValue);
const fee = await getFee("ARBITRARY"); const fee = await getFee("ARBITRARY");
await show({ await show({
message: `Would you like to rate this app a rating of ${newValue}?`, message: `Would you like to rate this app a rating of ${newValue}?`,
publishFee: fee.fee + " QORT", publishFee: fee.fee + " QORT",
}); });
if(hasPublishedRating === false){ if (hasPublishedRating === false) {
const pollName = `app-library-${app.service}-rating-${app.name}` const pollName = `app-library-${app.service}-rating-${app.name}`;
const pollOptions = [`1, 2, 3, 4, 5, initialValue-${newValue}`] const pollOptions = [`1, 2, 3, 4, 5, initialValue-${newValue}`];
await new Promise((res, rej)=> { await new Promise((res, rej) => {
chrome?.runtime?.sendMessage({ chrome?.runtime?.sendMessage(
action: 'CREATE_POLL', type: 'qortalRequest', payload: { {
pollName: pollName , pollDescription: `Rating for ${app.service} ${app.name}`, pollOptions: pollOptions , pollOwnerAddress : myName action: "CREATE_POLL",
type: "qortalRequest",
payload: {
pollName: pollName,
pollDescription: `Rating for ${app.service} ${app.name}`,
pollOptions: pollOptions,
pollOwnerAddress: myName,
},
},
(response) => {
console.log("response", response);
if (response.error) {
rej(response?.message);
return;
} else {
res(response);
setInfoSnack({
type: "success",
message:
"Successfully rated. Please wait a couple minutes for the network to propogate the changes.",
});
setOpenSnack(true);
}
} }
}, (response) => { );
console.log('response', response);
if (response.error) {
rej(response?.message)
return
} else {
res(response)
setInfoSnack({
type: "success",
message:
"Successfully rated. Please wait a couple minutes for the network to propogate the changes.",
});
setOpenSnack(true);
}
});
})
} else {
const pollName = `app-library-${app.service}-rating-${app.name}`
const optionIndex = pollInfo?.pollOptions.findIndex((option)=> +option.optionName === +newValue)
if(isNaN(optionIndex) || optionIndex === -1) throw new Error('Cannot find rating option')
await new Promise((res, rej)=> {
chrome?.runtime?.sendMessage({
action: 'VOTE_ON_POLL', type: 'qortalRequest', payload: {
pollName: pollName , optionIndex
}
}, (response) => {
console.log('response', response);
if (response.error) {
rej(response?.message)
return
} else {
res(response)
setInfoSnack({
type: "success",
message:
"Successfully rated. Please wait a couple minutes for the network to propogate the changes.",
});
setOpenSnack(true);
}
});
})
}
} catch (error) {
setInfoSnack({
type: "error",
message: error.message || "An error occurred while trying to rate.",
}); });
setOpenSnack(true); } else {
const pollName = `app-library-${app.service}-rating-${app.name}`;
const optionIndex = pollInfo?.pollOptions.findIndex(
(option) => +option.optionName === +newValue
);
if (isNaN(optionIndex) || optionIndex === -1)
throw new Error("Cannot find rating option");
await new Promise((res, rej) => {
chrome?.runtime?.sendMessage(
{
action: "VOTE_ON_POLL",
type: "qortalRequest",
payload: {
pollName: pollName,
optionIndex,
},
},
(response) => {
console.log("response", response);
if (response.error) {
rej(response?.message);
return;
} else {
res(response);
setInfoSnack({
type: "success",
message:
"Successfully rated. Please wait a couple minutes for the network to propogate the changes.",
});
setOpenSnack(true);
}
}
);
});
}
} catch (error) {
setInfoSnack({
type: "error",
message: error.message || "An error occurred while trying to rate.",
});
setOpenSnack(true);
} }
} };
console.log('vvotes', (votesInfo?.totalVotes ?? 0 ) + votesInfo?.voteCounts?.length === 6 ? 1 : 0, votesInfo) console.log(
"vvotes",
(votesInfo?.totalVotes ?? 0) + votesInfo?.voteCounts?.length === 6 ? 1 : 0,
votesInfo
);
return ( return (
<div> <div>
<Box sx={{ <Box
display: 'flex',
gap: '5px',
alignItems: 'center'
}}>
<Rating
value={value}
onChange={rateFunc}
precision={1}
readOnly={hasPublishedRating === null}
size="small"
icon={<StarFilledIcon />}
emptyIcon={<StarEmptyIcon />}
sx={{ sx={{
display: "flex", display: "flex",
gap: "2px", alignItems: "center",
}} flexDirection: ratingCountPosition === "top" ? "column" : "row",
/> }}
{ratingCountPosition && ( >
<AppInfoUserName> {ratingCountPosition === "top" && (
{ (votesInfo?.totalVotes ?? 0) + (votesInfo?.voteCounts?.length === 6 ? 1 : 0)} <>
</AppInfoUserName> <AppInfoUserName>
{(votesInfo?.totalVotes ?? 0) +
(votesInfo?.voteCounts?.length === 6 ? 1 : 0)}{" "}
{" RATINGS"}
</AppInfoUserName>
<Spacer height="6px" />
<AppInfoUserName>{value?.toFixed(1)}</AppInfoUserName>
<Spacer height="6px" />
</>
)} )}
</Box>
<Rating
<CustomizedSnackbars value={value}
onChange={rateFunc}
precision={1}
readOnly={hasPublishedRating === null}
size="small"
icon={<StarFilledIcon />}
emptyIcon={<StarEmptyIcon />}
sx={{
display: "flex",
gap: "2px",
}}
/>
{ratingCountPosition === "right" && (
<AppInfoUserName>
{(votesInfo?.totalVotes ?? 0) +
(votesInfo?.voteCounts?.length === 6 ? 1 : 0)}
</AppInfoUserName>
)}
</Box>
<CustomizedSnackbars
duration={2000} duration={2000}
open={openSnack} open={openSnack}
setOpen={setOpenSnack} setOpen={setOpenSnack}

View File

@ -277,4 +277,35 @@ import {
color: 'white', color: 'white',
fontWeight: 600, fontWeight: 600,
fontSize: '10px' fontSize: '10px'
}));
export const AppsCategoryInfo = styled(Box)(({ theme }) => ({
display: "flex",
alignItems: 'center',
width: '100%',
}));
export const AppsCategoryInfoSub = styled(Box)(({ theme }) => ({
display: "flex",
flexDirection: 'column',
}));
export const AppsCategoryInfoLabel = styled(Typography)(({ theme }) => ({
fontSize: '12px',
fontWeight: 700,
lineHeight: 1.2,
color: '#8D8F93',
}));
export const AppsCategoryInfoValue = styled(Typography)(({ theme }) => ({
fontSize: '12px',
fontWeight: 500,
lineHeight: 1.2,
color: '#8D8F93',
}));
export const AppsInfoDescription = styled(Typography)(({ theme }) => ({
fontSize: '13px',
fontWeight: 300,
lineHeight: 1.2,
width: '90%',
textAlign: 'start'
})); }));

View File

@ -267,7 +267,7 @@ export const Apps = ({ mode, setMode, show , myName}) => {
hasPublishApp={!!(myApp || myWebsite)} hasPublishApp={!!(myApp || myWebsite)}
/> />
)} )}
{mode === "appInfo" && <AppInfo app={selectedAppInfo} />} {mode === "appInfo" && <AppInfo app={selectedAppInfo} myName={myName} />}
{mode === "publish" && <AppPublish names={myName ? [myName] : []} categories={categories} />} {mode === "publish" && <AppPublish names={myName ? [myName] : []} categories={categories} />}
{tabs.map((tab) => { {tabs.map((tab) => {