react-icons/fi#FiPackage JavaScript Examples
The following examples show how to use
react-icons/fi#FiPackage.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: PopularApps.js From winstall with GNU General Public License v3.0 | 6 votes |
PopularApps = ({ apps, all }) => {
const { popular, setPopular } = useContext(PopularContext);
useEffect(() => {
if(popular.length === 0){
setPopular(apps.slice(0, 4));
}
})
return (
<PopularContext.Consumer>
{({ popular }) => (
<div className="homeBlock">
<div className="box">
<h2 className="blockHeader">Popular Apps</h2>
<Link href="/apps">
<a className="button small">
<FiPackage />
View All
</a>
</Link>
</div>
<h3 className="blockSubtitle">
The essentials for your new Windows device. Click to include them on your install script.
</h3>
<ListPackages popular>
{popular.map((app) => (
<PrettyApp app={app} key={app._id} all={all} />
))}
</ListPackages>
</div>
)}
</PopularContext.Consumer>
);
}
Example #2
Source File: RecentApps.js From winstall with GNU General Public License v3.0 | 6 votes |
RecentApps = ({ apps }) => {
return (
<div className="homeBlock">
<div className="box">
<h2 className="blockHeader">Recent Updates</h2>
<Link href="/apps?sort=update-desc">
<a className="button small">
<FiPackage />
View All
</a>
</Link>
</div>
<h3 className="blockSubtitle">
All the newest apps and updates. Click the + sign to include an app on your install script.
</h3>
<ListPackages>
{apps.map((app) => (
<SingleApp app={app} key={app._id} showTime/>
))}
</ListPackages>
</div>
);
}
Example #3
Source File: PackPreview.js From winstall with GNU General Public License v3.0 | 5 votes |
export default function PackPreview({ pack, hideMeta, showDelete=false, auth, deleted}){
const [appIcons, setIcons] = useState([]);
useEffect(() => {
const appIcons = pack.apps.filter(a => a.icon != "" ).map(a => ({ icon: a.icon, _id: a._id }));
setIcons([...appIcons].slice(0, 4));
}, [])
const deletePack = async () => {
if(!auth) return;
const { response } = await fetchWinstallAPI(`/packs/${pack._id}`, {
method: "DELETE",
headers: {
'Authorization': `${auth.accessToken},${auth.refreshToken}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({ creator: pack.creator })
});
if(response && response.msg){
if(deleted) deleted(pack._id);
localStorage.removeItem("ownPacks");
}
}
const handleDelete = async (e) => {
if ('confirm' in window && typeof window.confirm === 'function') {
if (window.confirm("Are you sure you want to delete this pack?")) {
deletePack();
}
} else {
deletePack();
}
}
return (
<div className={styles.packCard}>
<Link href="/packs/[id]" as={`/packs/${pack._id}`} prefetch={false}>
<a>
<header className={`${styles.packIcons} ${appIcons.length <= 2? styles.singleIcon : ""}`} id={pack.accent}>
<ul style={{gridTemplateColumns: `repeat(${appIcons.length > 4 ? "4": appIcons.length},1fr)`}}>
{
appIcons.map((app, index) => <li key={index}><AppIcon icon={app.icon} id={app._id}/></li>)
}
{ appIcons.length === 0 && (
<li><FiPackage/></li>
)}
</ul>
</header>
</a>
</Link>
{!hideMeta && (
<div className={styles.packMeta}>
<Link href="/packs/[id]" as={`/packs/${pack._id}`} prefetch={false}><a><h3>{pack.title}</h3></a></Link>
<p>{pack.desc}</p>
<p className={styles.includes}>Includes {pack.apps.slice(0, 3).map(a => a.name).join(", ")}, and more.</p>
<div className="box fBox">
<Link href="/packs/[id]" as={`/packs/${pack._id}`} prefetch={false}>
<button className="button accent"><FiPackage /> View Pack</button>
</Link>
{ showDelete && (
<div className={styles.packEdit}>
<Link href={`/packs/edit?id=${pack._id}`} prefetch={false}><button title="Edit Pack" className={`button subtle ${styles.delete}`} ><FiEdit /></button></Link>
<button className={`button subtle ${styles.delete}`} title="Delete Pack" onClick={handleDelete}><FiTrash2 /></button>
</div>
)}
</div>
</div>
)}
</div>
)
}
Example #4
Source File: Recommendations.js From winstall with GNU General Public License v3.0 | 5 votes |
Recommendations = ({ packs }) => {
return (
<div className="homeBlock">
<div className="box">
<h2 className="blockHeader">Featured Packs</h2>
<Link href="/packs">
<a className="button small">
<FiPackage />
View All
</a>
</Link>
</div>
<h3 className="blockSubtitle">
Just got a new Windows device? Start with our favourites. Click the +
sign to include an app on your install script.
</h3>
<div className={styles.recommendations}>
<PackList id="A6JzO22Y1" title="Work From Home" packs={packs}>
<FiHome />
</PackList>
<PackList id="z3zuf1vVD" title="Web Browsers" packs={packs}>
<FiGlobe />
</PackList>
<PackList id="ur23Tk6Sf" title="Essential Tools" packs={packs}>
<FiStar />
</PackList>
<PackList id="qO_m22F6k" title="Entertainment" packs={packs}>
<FiMusic />
</PackList>
<PackList id="Jtght2FO5" title="Gaming" packs={packs}>
<FiCrosshair />
</PackList>
<PackList id="3glB-CGXA" title="Developers" packs={packs}>
<FiCode />
</PackList>
<PackList id="NYWPVq9ct" title="Social Media" packs={packs}>
<FiUserPlus />
</PackList>
<PackList id="yphy7XItI" title="School" packs={packs}>
<FiBookOpen />
</PackList>
</div>
</div>
);
}
Example #5
Source File: index.js From winstall with GNU General Public License v3.0 | 5 votes |
function Home({ popular, apps, recommended, error}) {
if(error) {
return <Error title="Oops!" subtitle={error}/>
}
return (
<div>
<MetaTags title="winstall - GUI for Windows Package Manager" />
<div className={styles.intro}>
<div className="illu-box">
<h1>
Bulk install Windows apps quickly with Windows Package Manager.
</h1>
<div className="art">
<img
src="/assets/logo.svg"
draggable={false}
alt="winstall logo"
/>
</div>
</div>
<Search apps={apps} limit={4}/>
</div>
<PopularApps apps={popular} all={apps} />
{/* <RecentApps apps={recents} /> */}
<Recommendations packs={recommended}/>
<FeaturePromoter art="/assets/packsPromo.svg" promoId="packs">
<h3>Introducing Packs</h3>
<h1>Curate and share the apps you use daily.</h1>
<div className="box2">
<Link href="/packs/create"><button className="button spacer accent" id="starWine"><FiPlus/> Create a pack</button></Link>
<Link href="/packs/"><button className="button"><FiPackage/> View packs</button></Link>
</div>
</FeaturePromoter>
<Footer />
</div>
);
}
Example #6
Source File: Nav.js From winstall with GNU General Public License v3.0 | 4 votes |
function Nav() {
const router = useRouter();
const [ddShown, setDDShown] = useState(false);
const navRef = useRef(null);
let handleClickOut = (e) => {
if (navRef.current && !navRef.current.contains(e.target)) {
setDDShown(false);
navRef.current.classList.remove("shown");
}
if (navRef.current && navRef.current.contains(e.target)) {
setDDShown(false);
setTimeout(() => {
navRef.current.classList.remove("shown");
}, 200);
}
};
useEffect(() => {
window.addEventListener("mousedown", handleClickOut);
// cleanup this component
return () => {
window.removeEventListener("mousedown", handleClickOut);
};
}, []);
let switchTheme = () => {
let body = document.querySelector("body");
if (body.classList.contains("light")) {
localStorage.setItem("wiTheme", "dark");
body.classList.replace("light", "dark");
} else {
localStorage.setItem("wiTheme", "light");
body.classList.replace("dark", "light");
}
};
const toggleDD = () => {
if (ddShown) {
navRef.current.classList.remove("shown");
} else {
navRef.current.classList.add("shown");
}
setDDShown(!ddShown);
};
return (
<header>
<div className={styles.brand}>
<Link href="/">
<a>winstall</a>
</Link>
{/* <span className="preview"> (preview)</span> */}
</div>
<div className={styles.nav} ref={navRef}>
<Link href="/apps">
<a>
<FiPackage />
<p>Apps</p>
</a>
</Link>
<Link href="/packs">
<a>
<FiGrid />
<p>Packs</p>
</a>
</Link>
<a
href="https://ko-fi.com/mehedi"
target="_blank"
rel="noopener noreferrer"
className={styles.justIcon}
>
<FiHeart />
<p className={styles.ddOnly}>Support winstall</p>
</a>
<span onClick={switchTheme} className={styles.justIcon}>
<FiMoon className="moon" />
<FiSun className="sun" />
<p className={styles.ddOnly}>Switch theme</p>
</span>
<User />
</div>
<span className={`mobileDD ${styles.dropdown}`} onClick={toggleDD}>
{ddShown ? <FiX /> : <FiChevronDown />}
</span>
</header>
);
}
Example #7
Source File: SingleApp.js From winstall with GNU General Public License v3.0 | 4 votes |
SingleApp = ({ app, all, onVersionChange = false, large = false, showTime = false, pack = false, displaySelect = true, preventGlobalSelect, hideBorder=false, preSelected=false}) => {
const [selected, setSelected] = useState(false);
const { selectedApps, setSelectedApps } = useContext(SelectedContext);
const [version, setVersion] = useState(app.latestVersion);
if (!app.selectedVersion) app.selectedVersion = version;
if (app.versions.length > 1) {
app.versions = app.versions.sort((a, b) =>
compareVersion(b.version, a.version)
);
// make sure latest version is sorted
app.latestVersion = app.versions[0].version;
}
useEffect(() => {
if(preSelected){
setSelected(true);
return;
}
let found = selectedApps.find((a) => a._id === app._id);
if (!found){
if(selected){
setSelected(false);
}
return;
};
if (found.selectedVersion !== app.latestVersion) {
setVersion(found.selectedVersion);
}
setSelected(true);
}, [selectedApps, app._id]);
let handleAppSelect = () => {
if (preventGlobalSelect) {
preventGlobalSelect(app, !selected);
setSelected(!selected);
return;
}
let found = selectedApps.findIndex((a) => a._id === app._id);
if (found !== -1) {
let updatedSelectedApps = selectedApps.filter(
(a, index) => index !== found
);
setSelectedApps(updatedSelectedApps);
setSelected(false);
} else if(app){
setSelected(true);
if (all) {
app = all.find((i) => app._id == i._id);
setSelectedApps([...selectedApps, app]);
} else {
setSelectedApps([...selectedApps, app]);
}
}
};
if (!app && !app.img || !app.name) return <></>;
let VersionSelector = () => {
return (
<div className={styles.versions}>
<select
className={styles.versionSelector}
value={version}
onClick={(e) => e.stopPropagation()}
id="v-selector"
name="Select app version"
onChange={(e) => {
setVersion(e.target.value);
app.selectedVersion = e.target.value;
if (selected) {
let found = selectedApps.find((a) => a._id === app._id);
found.selectedVersion = e.target.value;
if(onVersionChange) onVersionChange();
}
}}
>
{app.versions.map((v) => {
return (
<option key={v.version} value={v.version}>
v{v.version}
</option>
);
})}
</select>
<FiChevronDown/>
{app.versions.length > 1 && (
<span>
<label htmlFor="v-selector">
({app.versions.length - 1} other{" "}
{app.versions.length - 1 > 1 ? "versions" : "version"} available)
</label>
</span>
)}
</div>
);
};
const handleShare = () => {
const link = `https://twitter.com/intent/tweet?text=${encodeURIComponent(`Checkout ${app.name} by ${app.publisher} on @winstallHQ:`)}&url=${encodeURIComponent(`https://winstall.app/apps/${app._id}`)}`
window.open(link)
}
return (
<li
key={app._id}
// onClick={handleAppSelect}
className={`${hideBorder ? styles.noBorder: "" }${large ? styles.large : ""} ${pack ? styles.pack : ""} ${styles.single} ${
selected ? styles.selected : ""
}`}
>
<div className={styles.info}>
<h3>
{large ? (
<>
<AppIcon id={app._id} name={app.name} icon={app.icon} />
{app.name}
</>
) : (
<Link href="/apps/[id]" as={`/apps/${app._id}`} prefetch={false}>
<a>
<AppIcon id={app._id} name={app.name} icon={app.icon} />
<p>{app.name}</p>
</a>
</Link>
)}
{displaySelect && (
<button
className={styles.selectApp}
onClick={handleAppSelect}
aria-label={selected ? "Unselect app" : "Select app"}
>
<FiPlus />
</button>
)}
</h3>
{!pack && <Description desc={app.desc} id={app._id} full={large} />}
</div>
{large && <Copy id={app._id} version={version} latestVersion={app.latestVersion} />}
<ul className={styles.metaData}>
{!large && (
<li>
<Link href="/apps/[id]" as={`/apps/${app._id}`} prefetch={false}>
<a>
<FiInfo />
View App
</a>
</Link>
</li>
)}
{(showTime || large) && (
<li>
<FiClock />
<span>Last updated {timeAgo(app.updatedAt)}</span>
</li>
)}
{!pack && (
<li className={app.versions.length > 1 ? styles.hover : ""}>
<FiPackage />
{app.versions.length > 1 ? (
<VersionSelector />
) : (
<span>v{app.selectedVersion}</span>
)}
</li>
)}
<li>
<Link href={`/apps?q=${`publisher: ${app.publisher}`}`}>
<a>
<FiCode />
Other apps by {app.publisher}
</a>
</Link>
</li>
{app.homepage && large && (
<li>
<a
href={`${app.homepage}?ref=winstall`}
target="_blank"
rel="noopener noreferrer"
onClick={(e) => e.stopPropagation()}
>
<FiExternalLink />
View Site
</a>
</li>
)}
{!pack && (
<li>
<a
href={`${
app.versions.find((i) => i.version === app.selectedVersion)
.installers[0]
}`}
onClick={(e) => e.stopPropagation()}
>
<FiDownload />
Download{" "}
{app.versions[0].installerType
? `(.${app.versions[0].installerType.toLowerCase()})`
: ""}
</a>
</li>
)}
{large && <ExtraMetadata app={app} />}
</ul>
{large && app.tags && app.tags.length > 1 && <Tags tags={app.tags} />}
{large && (
<div className={styles.largeAppButtons}>
<button className={styles.selectApp} onClick={handleAppSelect}>
<FiPlus />
{selected ? "Unselect" : "Select"} app
</button>
<button className={`button ${styles.shareApp}`} onClick={handleShare}>
<FiShare2 />
Share
</button>
</div>
)}
</li>
);
}
Example #8
Source File: [id].js From winstall with GNU General Public License v3.0 | 4 votes |
function PackDetail({ pack, creator, error }) {
const router = useRouter();
const { selectedApps, setSelectedApps } = useContext(SelectedContext);
const [user, setUser] = useState();
const [deleting, setDeleting] = useState(false);
const [deleteLabel, setDeleteLabel] = useState("Delete Pack");
useEffect(() => {
getSession().then(async (session) => {
if (!session) {
return;
}
setUser(session.user);
});
}, []);
const fallbackMessage = {
title: "Sorry! We could not load this pack.",
subtitle: error
? `Recieved error: ${error}`
: "Unfortunately, this pack could not be loaded. Either it does not exist, or something else went wrong. Please try again later.",
};
if (!router.isFallback && !pack) {
return <Error {...fallbackMessage} />;
}
const handleSelectAll = () => {
const updatedList = [...selectedApps, ...pack.apps];
let uniqueList = [
...new Map(updatedList.map((item) => [item["_id"], item])).values(),
];
setSelectedApps(uniqueList);
};
const handleShare = () => {
const link = `https://twitter.com/intent/tweet?text=${encodeURIComponent(
`Checkout the "${pack.title}" pack by @${creator.screen_name}!`
)}&url=${encodeURIComponent(
`https://winstall.app/packs/${pack._id}`
)}&via=winstallHQ`;
window.open(link);
};
const deletePack = async () => {
if (!user) return;
setDeleting(true);
setDeleteLabel("Deleting...");
const { response } = await fetchWinstallAPI(`/packs/${pack._id}`, {
method: "DELETE",
headers: {
Authorization: `${user.accessToken},${user.refreshToken}`,
"Content-Type": "application/json",
},
body: JSON.stringify({ creator: pack.creator }),
});
if (response && response.msg) {
setDeleteLabel("Deleted!");
localStorage.removeItem("ownPacks");
router.push("/packs");
}
};
const handleDelete = async (e) => {
if (deleting) return;
if ("confirm" in window && typeof window.confirm === "function") {
if (window.confirm("Are you sure you want to delete this pack?")) {
deletePack();
}
} else {
deletePack();
}
};
return (
<PageWrapper>
<div className={styles.content}>
{router.isFallback ? (
<AppSkeleton />
) : (
<div>
<MetaTags
title={`${pack.title} - winstall`}
desc={`Includes ${pack.apps[0].name}, ${pack.apps[1].name}, ${pack.apps[2].name}, and more!`}
/>
<h1>{pack.title}</h1>
<Link
href="/users/[id]"
as={`/users/${creator.id_str}`}
prefetch={false}
>
<a
className={styles.author}
title="View other packs by this user"
>
<img
src={creator.profile_image_url_https}
alt="pack creator image"
/>
@{creator.screen_name}
</a>
</Link>
<p>{pack.desc}</p>
<p className={styles.time}>
<FiClock /> Last updated {timeAgo(pack.updatedAt)}{" "}
</p>
<div className={styles.packGet}>
<a
className="button lightText"
href="#packScript"
id={pack.accent}
>
<FiCodepen /> Get Pack
</a>
<a className="button" onClick={handleSelectAll}>
<FiPackage /> Select Apps
</a>
<a className="button" onClick={handleShare}>
<FiShare2 /> Share
</a>
</div>
{user && user.id === pack.creator && (
<div className={styles.packGet}>
<Link href={`/packs/edit?id=${pack._id}`} prefetch={false}>
<a className="button subtle">
<FiEdit /> Edit Pack
</a>
</Link>{" "}
<a className="button subtle" onClick={handleDelete}>
<FiTrash /> {deleteLabel}
</a>
</div>
)}
<PackAppsList providedApps={pack.apps} reorderEnabled={false} />
<ScriptCode apps={pack.apps} />
</div>
)}
{/* <PackAppsList providedApps={packApps} reorderEnabled={false}/> */}
</div>
</PageWrapper>
);
}
Example #9
Source File: main.js From rahat-vendor with GNU Affero General Public License v3.0 | 4 votes |
export default function Main() {
const history = useHistory();
const { hasWallet, wallet, tokenBalance, setTokenBalance, agency, hasBackedUp, contextLoading, hasSynchronized } =
useContext(AppContext);
const authSign = useAuthSignature(wallet);
const [redeemModal, setRedeemModal] = useState(false);
const [redeemTokenModal, setRedeemTokenModal] = useState(false);
const [redeemPackageModal, setRedeemPackageModal] = useState(false);
const [redeemAmount, setRedeemAmount] = useState('');
const [loading, showLoading] = useState(null);
const [selectedRedeemablePackage, setSelectedRedeemablePackage] = useState([]);
const [packageBalanceLoading, setPackageBalanceLoading] = useState(true);
const [packageBalance, setPackageBalance] = useState(null);
const [packages, setPackages] = useState(null);
const [recentTx, setRecentTx] = useState(null);
const cardBody = useRef();
const { width } = useResize(cardBody);
const calcQRWidth = () => {
if (width < 200) return 200;
else return 280;
};
const checkRecentTnx = useCallback(async () => {
let txs = await DataService.listTx();
if (txs && Array.isArray(txs)) {
const arr = txs.slice(0, 3);
setRecentTx(arr);
}
}, []);
const getTokenBalance = useCallback(async () => {
if (!agency) return;
try {
const balance = await TokenService(agency.address).getBalance();
setTokenBalance(balance.toNumber());
} catch (err) {
console.log('Unable to get token Balance');
console.log(err);
}
}, [agency, setTokenBalance]);
const getPackageBalance = useCallback(async () => {
if (!agency) return;
if (!authSign) return;
try {
const nfts = await DataService.listNft();
const walletAddress = await DataService.getAddress();
// Get Token Ids from index db
const tokenIds = nfts.map(item => item?.tokenId);
if (!tokenIds?.length) {
setPackageBalanceLoading(false);
return;
}
const tokenQtys = [];
// get token balances from contract
const address = tokenIds.map(() => walletAddress);
const blnc = await ERC1155_Service(agency?.address).getBatchBalance(address, tokenIds);
if (!blnc) return;
if (blnc?.length) {
blnc.forEach((item, index) => {
tokenQtys.push(item.toNumber());
nfts[index].amount = item.toNumber();
});
}
setPackages(nfts);
// get total-package-balance from Backend server
const totalNftBalance = await calculateTotalPackageBalance({ tokenIds, tokenQtys }, authSign);
setPackageBalance(totalNftBalance);
setPackageBalanceLoading(false);
// let tokens
} catch (err) {
setPackageBalanceLoading(false);
console.log('Unable to get package balance', err);
}
}, [agency, authSign]);
const confirmAndRedeemToken = async data => {
setRedeemModal(false);
const isConfirm = await Swal.fire({
title: 'Are you sure?',
html: `You are sending <b>${redeemAmount}</b> token to redeem it for cash`,
showCancelButton: true,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
confirmButtonText: 'Yes',
cancelButtonText: 'No'
});
if (isConfirm.value) {
redeemToken();
} else {
resetFormStates();
}
};
const redeemToken = async () => {
//TODO choose a financial institute to redeem token
setRedeemTokenModal(false);
let tknService = TokenService(agency.address, wallet);
showLoading('Transferring tokens to redeem. Please wait...');
let receipt = await tknService.transfer(agency.adminAddress, Number(redeemAmount));
resetFormStates();
const tx = {
hash: receipt.transactionHash,
type: CHARGE_TYPES.REDEEMED_TOKEN,
timestamp: Date.now(),
amount: redeemAmount,
to: 'agency',
from: wallet.address,
status: 'success'
};
await DataService.addTx(tx);
await getTokenBalance();
history.push(`/tx/${receipt.transactionHash}`);
};
const redeemPackages = async () => {
if (!selectedRedeemablePackage?.length) return;
showLoading('Transferring packages to redeem. Please wait...');
const ids = [];
const amount = [];
try {
selectedRedeemablePackage.forEach(item => {
ids.push(item.tokenId);
amount.push(item.amount);
});
const trasnaction = await ERC1155_Service(agency?.address, wallet).batchRedeem(
wallet.address,
agency?.adminAddress,
ids,
amount
);
const tx = {
hash: trasnaction.transactionHash,
type: CHARGE_TYPES.REDEEMED_PACKAGE,
timestamp: Date.now(),
amount: amount.reduce((prevVal, curVal) => prevVal + curVal, 0),
to: 'agency',
from: wallet.address,
status: 'success',
tokenId: ids
};
await DataService.addTx(tx);
await DataService.batchDecrementNft(ids, amount);
setSelectedRedeemablePackage([]);
setRedeemPackageModal(false);
await getPackageBalance();
resetFormStates();
await Swal.fire({
icon: 'success',
title: 'Success',
text: 'Successfully Redeemed Pacakages'
});
} catch (err) {
resetFormStates();
Swal.fire({
title: 'Error',
text: `Couldnot redeem package`,
icon: 'error'
});
}
};
const updateRedeemAmount = e => {
let formData = new FormData(e.target.form);
let data = {};
formData.forEach((value, key) => (data[key] = value));
setRedeemAmount(data.redeemAmount);
};
const resetFormStates = () => {
showLoading(null);
setRedeemAmount('');
setRedeemModal(false);
};
const getInfoState = useCallback(async () => {
if (contextLoading) return;
if (!hasWallet) return history.push('/setup');
if (!hasBackedUp) return history.push('/wallet/backup');
if (!hasSynchronized) return history.push('/sync');
if (agency && !agency.isApproved) return history.push('/setup/pending');
await checkRecentTnx();
await getTokenBalance();
await getPackageBalance();
}, [
contextLoading,
agency,
hasSynchronized,
hasWallet,
hasBackedUp,
history,
getTokenBalance,
checkRecentTnx,
getPackageBalance
]);
// Action Sheet togglers
const toggleRedeemModal = () => setRedeemModal(prev => !prev);
const toggleTokenModal = e => {
e?.preventDefault();
toggleRedeemModal();
setRedeemTokenModal(prev => !prev);
};
const togglePackageModal = e => {
e?.preventDefault();
setSelectedRedeemablePackage([]);
toggleRedeemModal();
setRedeemPackageModal(prev => !prev);
};
// Checkbox click handler
const onCheckBoxClick = tokenId => {
const isPresent = isChecked(tokenId);
if (isPresent) setSelectedRedeemablePackage(prev => prev.filter(elm => elm.tokenId !== tokenId));
if (!isPresent) {
const newElm = packages.find(elm => elm.tokenId === tokenId);
setSelectedRedeemablePackage(prev => [...prev, newElm]);
}
};
const isChecked = tknId => {
return selectedRedeemablePackage.some(elm => elm.tokenId === tknId);
};
// UseEffects
useEffect(() => {
let isMounted = true;
if (isMounted) getInfoState();
return () => {
isMounted = false;
};
}, [getInfoState]);
return (
<>
{contextLoading && (
<div id="loader">
<img src="/assets/img/brand/icon-white-128.png" alt="icon" className="loading-icon" />
</div>
)}
<Loading showModal={loading !== null} message={loading} />
{/* Redeem Token Modal Starts */}
<ActionSheet
title="Redeem Token"
buttonName="Redeem"
showModal={redeemTokenModal}
onHide={e => toggleTokenModal(e)}
handleSubmit={confirmAndRedeemToken}
>
<div className="form-group basic">
<div className="input-wrapper">
<label className="label">Enter Amount</label>
<div className="input-group mb-3">
<div className="input-group-prepend">
<span className="input-group-text" id="input14">
Rs.
</span>
</div>
<Form.Control
type="number"
name="redeemAmount"
className="form-control"
placeholder="Redeem"
value={redeemAmount}
onChange={updateRedeemAmount}
required
/>
<i className="clear-input">
<ion-icon name="close-circle"></ion-icon>
</i>
</div>
</div>
</div>
</ActionSheet>
{/* Redeem Token Modal Ends */}
{/* Redeem Package Modal Starts */}
<ActionSheet
title="Redeem Package"
buttonName="Redeem"
showModal={redeemPackageModal}
onHide={e => togglePackageModal(e)}
handleSubmit={redeemPackages}
>
<div className="wide-block pt-2 pb-2 border-0">
{packages?.length > 0 ? (
packages.map(p => {
return (
<div className=" d-flex flex-row align-items-center justify-content-between mb-1 w-100 ">
<div>
<input
type="checkbox"
className="mr-2"
id={`${p.tokenId}`}
onClick={() => onCheckBoxClick(p.tokenId)}
/>
<img
src={p.imageUri || '/assets/img/brand/icon-72.png'}
width="50"
height="50"
alt="asset"
className="image"
/>
<label className="m-0" for={`${p.tokenId}`}>{`${p.name} (${p.symbol}) `}</label>
</div>
<p className="mb-0 ml-3 text-warning font-weight-bold">{p.amount}</p>
</div>
);
})
) : (
<p>You don't own any packages.</p>
)}
</div>
</ActionSheet>
{/* Redeem Package Modal Ends */}
{/* Redeem Modal Start */}
<ActionSheet
title="Redeem"
buttonName="Close"
showModal={redeemModal}
onHide={() => setRedeemModal(false)}
handleSubmit={toggleRedeemModal}
>
<div class="modal-body">
<ul className="listview image-listview flush">
<li>
<button onClick={e => toggleTokenModal(e)} className="item border-0 bg-transparent ">
<div className="icon-box bg-primary">
<GiToken className="ion-icon" />
</div>
<div className="in">
<div>
<div className="mb-05">
<strong>Token</strong>
</div>
</div>
</div>
</button>
</li>
<li>
<button onClick={e => togglePackageModal(e)} className="item border-0 bg-transparent ">
<div className="icon-box bg-primary">
<FiPackage className="ion-icon" />
</div>
<div className="in">
<div>
<div className="mb-05">
<strong>Package</strong>
</div>
</div>
</div>
</button>
</li>
</ul>
</div>
</ActionSheet>
{/* Redeem Modal Ends */}
<div id="appCapsule">
<div className="section wallet-card-section pt-1">
<div className="wallet-card">
<div className="balance">
<div className="left">
<span className="title">Token Balance</span>
<h1 className={`total `}>{tokenBalance || 0}</h1>
</div>
<div className="right">
<span className="title">Package Balance</span>
<h1 className={`total ${packageBalanceLoading && 'loading_text'}`}>
NRS {packageBalance?.grandTotal || 0}
</h1>
</div>
</div>
{wallet && (
<button
className="item button-link"
onClick={() => {
if (isOffline()) return;
setRedeemModal(true);
}}
>
<div className="col">
<div className="action-button">
<IoArrowDownCircleOutline className="ion-icon" style={{ fontSize: '40px' }} />
</div>
</div>
<strong>Redeem</strong>
</button>
)}
</div>
</div>
<div className="section mt-2">
<div className="card">
<div
className="section-heading"
style={{
marginBottom: '0px'
}}
>
<div
className="card-header"
style={{
borderBottom: '0px'
}}
>
Recent Transactions
</div>
<Link to="/transaction" className="link" style={{ marginRight: '16px' }}>
View All
</Link>
</div>
<div
className="card-body"
style={{
paddingTop: '0px'
}}
>
<TransactionList limit="3" transactions={recentTx || []} />
</div>
</div>
</div>
{wallet && (
<div className="section mt-2 mb-4">
<div className="card text-center">
<div className="card-header">Your Address</div>
<div className="card-body">
<div className="card-text" ref={cardBody}>
<QRCode value={wallet.address} size={calcQRWidth()} />
<div className="mt-1" style={{ fontSize: 13 }}>
{wallet.address}
</div>
<div className="mt-2" style={{ fontSize: 9, lineHeight: 1.5 }}>
This QR Code (address) is your unique identity. Use this to receive digital
documents, assets or verify your identity.
</div>
</div>
</div>
</div>
</div>
)}
<div className="text-center mt-4">
{hasWallet && !wallet && <strong>Tap on lock icon to unlock</strong>}
</div>
</div>
</>
);
}