clean code

This commit is contained in:
MuslemRahimi 2024-07-30 23:33:36 +02:00
parent 6781ea4ec0
commit 10d0781359
2 changed files with 40 additions and 132 deletions

View File

@ -1,6 +1,6 @@
<script lang='ts'> <script lang='ts'>
import toast from 'svelte-french-toast'; import toast from 'svelte-french-toast';
import {userRegion, screenWidth, openPriceAlert, displayCompanyName, stockTicker, etfTicker, cryptoTicker, assetType} from '$lib/store'; import {screenWidth, openPriceAlert, displayCompanyName, stockTicker, etfTicker, cryptoTicker, assetType} from '$lib/store';
import RangeSlider from 'svelte-range-slider-pips'; import RangeSlider from 'svelte-range-slider-pips';
export let data; export let data;
@ -9,19 +9,6 @@
let values = [0]; let values = [0];
let displayPrice = (currentPrice*(1+values?.at(0)/100))?.toFixed(2); let displayPrice = (currentPrice*(1+values?.at(0)/100))?.toFixed(2);
const usRegion = ['cle1','iad1','pdx1','sfo1'];
let fastifyURL;
userRegion.subscribe(value => {
if (usRegion.includes(value)) {
fastifyURL = import.meta.env.VITE_USEAST_FASTIFY_URL;
} else {
fastifyURL = import.meta.env.VITE_EU_FASTIFY_URL;
}
});
async function handleCreateAlert() async function handleCreateAlert()
{ {
if (values?.at(0) === 0) if (values?.at(0) === 0)
@ -43,7 +30,7 @@
} }
// Make the POST request to the endpoint // Make the POST request to the endpoint
const response = await fetch(fastifyURL+'/create-price-alert', { const response = await fetch(data?.fastifyURL+'/create-price-alert', {
method: 'POST', method: 'POST',
headers: { headers: {
"Content-Type": "application/json" "Content-Type": "application/json"

View File

@ -1,6 +1,6 @@
<script lang='ts'> <script lang='ts'>
import {searchBarData, globalForm, screenWidth, openPriceAlert, currentPortfolioPrice, realtimePrice, isCrosshairMoveActive, currentPrice, priceIncrease, displayCompanyName, traded, stockTicker, isOpen } from '$lib/store'; import {searchBarData, globalForm, screenWidth, openPriceAlert, currentPortfolioPrice, realtimePrice, isCrosshairMoveActive, currentPrice, priceIncrease, displayCompanyName, stockTicker, isOpen } from '$lib/store';
import { onMount, onDestroy, afterUpdate} from "svelte"; import { onMount, onDestroy, afterUpdate} from "svelte";
import { goto } from '$app/navigation'; import { goto } from '$app/navigation';
@ -45,12 +45,13 @@ async function loadSearchData() {
let isScrolled = false; let isScrolled = false;
let y;
let userWatchList = data?.getUserWatchlist ?? []; let userWatchList = data?.getUserWatchlist ?? [];
let isTickerIncluded; let isTickerIncluded;
let userPortfolio = data?.getUserPortfolio ?? []; //let userPortfolio = data?.getUserPortfolio ?? [];
let holdingShares = 0; //let holdingShares = 0;
let availableCash = 0; //let availableCash = 0;
let displaySection = ''; let displaySection = '';
@ -79,7 +80,7 @@ function shareContent(url) {
} }
/*
function handleTypeOfTrade(state:string) function handleTypeOfTrade(state:string)
{ {
if (state === 'buy') if (state === 'buy')
@ -93,9 +94,8 @@ function handleTypeOfTrade(state:string)
const closePopup = document.getElementById("sellTradeModal"); const closePopup = document.getElementById("sellTradeModal");
closePopup?.dispatchEvent(new MouseEvent('click')) closePopup?.dispatchEvent(new MouseEvent('click'))
} }
} }
*/
function scrollToItem(itemId) { function scrollToItem(itemId) {
@ -134,39 +134,17 @@ function changeSection(state, item) {
async function toggleUserWatchlist(watchListId: string) { async function toggleUserWatchlist(watchListId: string) {
try { try {
isTickerIncluded = !isTickerIncluded;
const watchlistIndex = userWatchList?.findIndex(item => item?.id === watchListId); const watchlistIndex = userWatchList?.findIndex(item => item?.id === watchListId);
if (watchlistIndex !== -1) {
const existingTickerIndex = userWatchList[watchlistIndex]?.ticker?.indexOf($stockTicker);
if (existingTickerIndex !== -1) {
// If the $stockTicker exists, remove it from the array
userWatchList[watchlistIndex]?.ticker?.splice(existingTickerIndex, 1);
} else {
// If the $stockTicker doesn't exist, add it to the array
userWatchList[watchlistIndex]?.ticker?.push($stockTicker);
}
// Update the userWatchList
userWatchList = [...userWatchList];
}
const postData = { const postData = {
'userId': data?.user?.id, userId: data?.user?.id,
'watchListId': watchListId, watchListId,
'ticker': $stockTicker, ticker: $stockTicker,
}; };
const response = await fetch(data?.fastifyURL + '/update-watchlist', { const response = await fetch(`${data?.fastifyURL}/update-watchlist`, {
method: 'POST', method: 'POST',
headers: { headers: { "Content-Type": "application/json" },
"Content-Type": "application/json"
},
body: JSON.stringify(postData), body: JSON.stringify(postData),
}); });
@ -176,16 +154,15 @@ async function toggleUserWatchlist(watchListId: string) {
const output = (await response.json())?.items; const output = (await response.json())?.items;
// Update the userWatchList with the response from the server if (watchlistIndex !== -1) {
if( watchlistIndex !== -1)
{
userWatchList[watchlistIndex] = output; userWatchList[watchlistIndex] = output;
userWatchList = [...userWatchList]; } else {
} userWatchList.push(output);
else {
userWatchList = [...userWatchList, output];
} }
userWatchList = [...userWatchList];
isTickerIncluded = !isTickerIncluded;
} catch (error) { } catch (error) {
console.error('An error occurred:', error); console.error('An error occurred:', error);
// Handle the error appropriately (e.g., show an error message to the user) // Handle the error appropriately (e.g., show an error message to the user)
@ -193,6 +170,7 @@ async function toggleUserWatchlist(watchListId: string) {
} }
/*
async function fetchPortfolio() async function fetchPortfolio()
{ {
const postData = {'userId': data?.user?.id}; const postData = {'userId': data?.user?.id};
@ -208,17 +186,11 @@ async function fetchPortfolio()
userPortfolio = (await response.json())?.items; userPortfolio = (await response.json())?.items;
} }
*/
function handleScroll() {
// Check the scroll position
isScrolled = window.scrollY > 0;
}
function sendMessage(message) { function sendMessage(message) {
if (socket && socket.readyState === WebSocket.OPEN) { if (socket && socket.readyState === WebSocket.OPEN) {
socket.send(message); socket.send(message);
@ -300,25 +272,11 @@ onMount(async () => {
PriceAlert = (await import('$lib/components/PriceAlert.svelte')).default; PriceAlert = (await import('$lib/components/PriceAlert.svelte')).default;
} }
//const startTime = currentDateTime.set({ hour: 15, minute: 30 });
//const endTime = currentDateTime.set({ hour: 22, minute: 0 });
// Check if it's not a weekend and the current time is within the specified range
if ($isOpen) //&& currentDateTime > startTime && currentDateTime < endTime if ($isOpen) //&& currentDateTime > startTime && currentDateTime < endTime
{ {
await websocketRealtimeData() await websocketRealtimeData()
} }
// Add a scroll event listener
window.addEventListener('scroll', handleScroll);
return () => {
// Remove the event listener when the component is unmounted
window.removeEventListener('scroll', handleScroll);
};
}); });
afterUpdate( async () => { afterUpdate( async () => {
@ -356,7 +314,7 @@ onDestroy(() => {
$currentPortfolioPrice = null; $currentPortfolioPrice = null;
$currentPrice = null; $currentPrice = null;
$priceIncrease = null; $priceIncrease = null;
$traded = false //$traded = false
}); });
@ -371,30 +329,13 @@ $: {
similarstock = data?.getSimilarStock; similarstock = data?.getSimilarStock;
topETFHolder = data?.getTopETFHolder; topETFHolder = data?.getTopETFHolder;
$currentPortfolioPrice = data?.getStockQuote?.price; $currentPortfolioPrice = data?.getStockQuote?.price;
const asyncFunctions = [
];
Promise.all(asyncFunctions)
.then((results) => {
})
.catch((error) => {
console.error('An error occurred:', error);
});
}
}
$: {
if(userWatchList)
{
isTickerIncluded = userWatchList?.some(item => item.user === data?.user?.id && item?.ticker?.includes($stockTicker));
} }
} }
$: isTickerIncluded = userWatchList?.some(item =>
item.user === data?.user?.id && item.ticker?.includes($stockTicker));
/*
$: { $: {
if(userPortfolio) { if(userPortfolio) {
availableCash = userPortfolio?.at(0)?.availableCash; availableCash = userPortfolio?.at(0)?.availableCash;
@ -412,6 +353,7 @@ $: {
} }
} }
$: { $: {
if(typeof window !== 'undefined' && $traded && data?.user && $stockTicker?.length !== 0) if(typeof window !== 'undefined' && $traded && data?.user && $stockTicker?.length !== 0)
{ {
@ -419,21 +361,10 @@ $: {
$traded = false; $traded = false;
} }
} }
*/
$: charNumber = $screenWidth < 640 ? 12 : 25;
let charNumber = 12;
$: {
if($screenWidth < 640)
{
charNumber = 12;
}
else {
charNumber = 25;
}
}
$: { $: {
if($stockTicker && typeof window !== 'undefined' && $page.url.pathname === `/stocks/${$stockTicker}`) if($stockTicker && typeof window !== 'undefined' && $page.url.pathname === `/stocks/${$stockTicker}`)
@ -458,8 +389,13 @@ $: {
} }
} }
$: isScrolled = y > 0;
</script> </script>
<svelte:window bind:scrollY={y}/>
<body class="bg-[#09090B] pb-40"> <body class="bg-[#09090B] pb-40">
<!-- Page wrapper --> <!-- Page wrapper -->
<div class="flex flex-col min-h-screen overflow-hidden m-auto w-full mt-5 supports-[overflow:clip]:overflow-clip pb-40"> <div class="flex flex-col min-h-screen overflow-hidden m-auto w-full mt-5 supports-[overflow:clip]:overflow-clip pb-40">
@ -833,7 +769,7 @@ $: {
<!--Start Type of Trade--> <!--Start Type of Trade-->
<!--
<input type="checkbox" id="typeOfTrade" class="modal-toggle" /> <input type="checkbox" id="typeOfTrade" class="modal-toggle" />
<dialog id="typeOfTrade" class="modal modal-bottom sm:modal-middle overflow-hidden"> <dialog id="typeOfTrade" class="modal modal-bottom sm:modal-middle overflow-hidden">
@ -897,17 +833,12 @@ $: {
</div> </div>
</div> </div>
</dialog> </dialog>
-->
<!--End Type of Trade--> <!--End Type of Trade-->
<!--Start Add Watchlist Modal--> <!--Start Add Watchlist Modal-->
<input type="checkbox" id="addWatchListModal" class="modal-toggle" /> <input type="checkbox" id="addWatchListModal" class="modal-toggle" />
@ -973,16 +904,6 @@ $: {
<style lang='scss'> <style lang='scss'>