import React, { useState, useEffect, useRef } from 'react';
import {
Link,
Grid,
Stack,
Input,
Container,
Image,
SimpleGrid,
Text,
HStack,
InputGroup,
InputRightElement,
Button,
Heading,
Flex,
Tag,
Spinner,
Card,
CardBody,
CardFooter,
CardHeader,
Stat,
StatLabel,
StatNumber,
StatHelpText,
StatArrow,
StatGroup,
Alert,
AlertIcon,
AlertTitle,
Spacer,
FormControl,
Box,
Tooltip,
Modal,
ModalOverlay,
ModalContent,
ModalHeader,
ModalFooter,
ModalBody,
ModalCloseButton,
AlertDescription,
CloseButton,
VStack,
useDisclosure,
} from '@chakra-ui/react';
import ColorModeSwitcher from './components/ColorModeSwitcher';
import { CheckIcon, WarningTwoIcon } from '@chakra-ui/icons';
import QCCard from './components/QCCard';
import { useSearchParams } from 'react-router-dom';
import { useCookies } from 'react-cookie';
const API_ITEM_URL = 'https://product2.rep.ninja/item';
const API_KEY = 'public1989';
/* constants */
const urlRegex =
/((([A-Za-z]{3,9}:(?://)?)(?:[-;:&=+$,\w]+@)?[A-Za-z0-9.-]+(:[0-9]+)?|(?:www.|[-;:&=+$,\w]+@)[A-Za-z0-9.-]+)((?:/[+~%/.\w-_]*)???(?:[-+=&;%@.\w_]*)#?(?:[\w]*))?)/;
function decodeArray(array) {
try {
return JSON.parse(decodeURIComponent(array));
} catch (error) {
return [];
}
}
function encodeArray(array) {
return encodeURIComponent(JSON.stringify(array));
}
function evaluateVolume(measurementString) {
return (
measurementString
?.split('*')
?.map(parseFloat)
?.reduce((a, b) => a * b, 1) || undefined
);
}
function calcArrayAverage(array) {
return parseInt(array?.reduce((a, b) => a + b, 0) / array?.length) || undefined;
}
function cleanUrlParams(url) {
try {
const urlObj = new URL(url);
[...urlObj.searchParams.keys()].forEach((key) => {
if (!['itemid', 'id'].includes(key.toLowerCase())) urlObj.searchParams.delete(key);
});
return urlObj.toString();
} catch (error) {
return url;
}
}
function Section(props) {
return (
{props.title && {props.title}}
{props.children}
);
}
const apiStatusCodes = {
loading: 0,
success: 1,
fail: 2,
};
function Content() {
/* states */
const [searchParams, setSearchParams] = useSearchParams();
const [cookies, setCookie, removeCookie] = useCookies([]);
const [historyArray, setHistoryArray] = useState(() => decodeArray(cookies.history));
const [apiStatus, setApiStatus] = useState({
pandaBuy: undefined,
superBuy: undefined,
cssBuy: undefined,
});
const [itemUrl, setItemUrl] = useState(() =>
cleanUrlParams(decodeURIComponent(searchParams.get('url') || ''))
);
const [isItemUrlInvalid, setIsItemUrlInvalid] = useState(false);
const [itemInfo, setItemInfo] = useState({
name: undefined,
thumbnail: undefined,
volume: [],
weight: [],
qc_images: [],
});
const [activeQcIndex, setActiveQcIndex] = useState();
/* effects */
// auto submit item URL on load
useEffect(() => {
if (itemUrl && !isItemUrlInvalid) handleSubmit(null);
}, []);
// update history cookie
useEffect(() => {
if (historyArray.length) {
setCookie('history', encodeArray(historyArray), { path: '/' });
} else {
removeCookie('url');
}
}, [historyArray, setHistoryArray]);
/* refs */
const selectedSectionRef = useRef(null);
const qcArray = itemInfo?.qc_images;
/* components */
function StatusIcon() {
if (isItemLoading) {
return ;
} else if (Object.values(apiStatus).includes(apiStatusCodes.fail)) {
return ;
} else if (Object.values(apiStatus).every((v) => v === apiStatusCodes.success)) {
return ;
}
}
function agentApiFetch(agent, itemUrl) {
fetch(${API\_ITEM\_URL}/${agent}?key=${API\_KEY}&url=${encodeURIComponent(itemUrl)})
.then((response) => (response.ok ? response.json() : Promise.reject()))
.then((data) => {
if (data?.state === 0 && data?.universal_data) {
setItemInfo((prevInfo) => {
const nextInfo = {};
for (const [key, value] of Object.entries(prevInfo)) {
if (Array.isArray(value)) {
if (Array.isArray(data.universal_data[key])) {
nextInfo[key] = [...value, ...data.universal_data[key]];
} else if (data.universal_data[key]) {
nextInfo[key] = [...value, data.universal_data[key]];
} else {
nextInfo[key] = prevInfo[key];
}
} else if (value === undefined) {
nextInfo[key] = data.universal_data[key];
} else {
nextInfo[key] = prevInfo[key];
}
}
return nextInfo;
});
setApiStatus((prevStatus) => ({ ...prevStatus, [agent]: apiStatusCodes.success }));
// return Promise.resolve(data.universal_data);
} else {
return Promise.reject();
}
})
.catch((error) => {
console.error(error);
setApiStatus((prevStatus) => ({ ...prevStatus, [agent]: apiStatusCodes.fail }));
});
}
function handleSubmit(e) {
// prevent refresh
if (e) e.preventDefault();
// clean item URL
const cleanItemUrl = cleanUrlParams(itemUrl);
if (itemUrl !== cleanItemUrl) setItemUrl(cleanItemUrl);
// update history
if (!historyArray.includes(cleanItemUrl) && urlRegex.test(cleanItemUrl)) {
setHistoryArray((prevArray) => [cleanItemUrl, ...prevArray].slice(0, 5));
}
//if (Object.values(itemInfo).some((v) => v !== true)) {
setItemInfo({
name: undefined,
thumbnail: undefined,
volume: [],
weight: [],
qc_images: [],
});
setApiStatus({
pandabuy: apiStatusCodes.loading,
superbuy: apiStatusCodes.success,
cssbuy: apiStatusCodes.success,
});
agentApiFetch('pandabuy', cleanItemUrl);
agentApiFetch('superbuy', cleanItemUrl);
agentApiFetch('cssbuy', cleanItemUrl);
}
function handleHistoryClick(e) {
setItemUrl(e.target.innerText || '');
}
function handleItemUrlClearClick() {
setItemUrl('');
}
function handleHistoryClearClick() {
setHistoryArray([]);
}
function handleItemUrlChange(event) {
const value = event.target.value;
setItemUrl(value);
if (value) {
setIsItemUrlInvalid(!urlRegex.test(value));
setSearchParams({ url: value });
} else {
setIsItemUrlInvalid(false);
setSearchParams();
}
}
const isItemLoading = Object.values(apiStatus).includes(apiStatusCodes.loading);
return (
{itemUrl && (
}
/>
)}
View
{Object.values(apiStatus).some((v) => v !== undefined) && (
<>
{itemInfo?.name && (
{itemInfo.name}
)}
{!!itemInfo?.weight?.length && (
Weight
{calcArrayAverage(itemInfo.weight)} g
)}
{!!itemInfo?.volume?.length && (
Volume
{calcArrayAverage(
itemInfo.volume.map(evaluateVolume)
)}{' '}
cm
3
)}
{Object.values(apiStatus).every((v) => v !== undefined) && (
QCs {qcArray.length}
}
{!!qcArray.length && (
{qcArray.map((qc, index) => {
return (
);
})}
)}
{Object.values(apiStatus).some((v) => v !== apiStatusCodes.success) &&
!isItemLoading && (
No QCs found
Try another link or check back later
)}
)}
)}
{activeQcIndex != null && (
Selected}>
{qcArray[activeQcIndex].images.map((image, index) => (
))}
)}
{false && (
History{' '}
Clear
}
{historyArray.map((link) => (
{link}
))}
)}
Discord
TOS
Privacy Policy
);
}
export default function App() {
return ;
}
I want to add a pandabuy affiliate link to the top of this page, how do I do that?