Sequence diagram – modelling HTTP requests

For my school project, I need to create a sequence diagram. In that sequence diagram I have to represent an API call using simple JavaScript code (fetch() + then() for handling the response).

I’m confused, should I represent this as sync or async communication in a sequence diagram?

In one way, since the web browser is not blocked while waiting for a response I guess it should be async. But in another way, it waits for the response so it can be processed so it’s blocked from executing which means is should be sync?

Thanks for the answers.

Picture that represents sync and async communication

I tried google-ing this problem but didn’t find any answers.

NestJS – Authorization with Tokens vs. HttpOnly Cookies

I’ve created a login system in NestJS based on the documentation, but I have a question regarding the authorization approach. According to the documentation, after logging in, the user receives a token that needs to be sent to the API every time for authorization.

My question is: is this really the correct approach? Would it not be better to use HttpOnly cookies to store the token? How should this be implemented in the context of NestJS?
AuthService:

import { Injectable, UnauthorizedException } from '@nestjs/common';
import { UsersService } from '../users/users.service';
import { JwtService } from '@nestjs/jwt';

@Injectable()
export class AuthService {
  constructor(
    private usersService: UsersService,
    private jwtService: JwtService
  ) {}

  async signIn(
    username: string,
    pass: string,
  ): Promise<{ access_token: string }> {
    const user = await this.usersService.findOne(username);
    if (user?.password !== pass) {
      throw new UnauthorizedException();
    }
    const payload = { sub: user.userId, username: user.username };
    return {
      access_token: await this.jwtService.signAsync(payload),
    };
  }
}

Auth Controller

import {
    Body,
    Controller,
    Get,
    HttpCode,
    HttpStatus,
    Post,
    Request,
    UseGuards
} from '@nestjs/common';
import { AuthService } from './auth.service';
import { AuthGuard } from './auth.guard';

@Controller('auth')
export class AuthController {
  constructor(private authService: AuthService) {}

  @HttpCode(HttpStatus.OK)
  @Post('login')
  signIn(@Body() signInDto: Record<string, any>) {
    return this.authService.signIn(signInDto.username, signInDto.password);
  }

  @UseGuards(AuthGuard)
  @Get('profile')
  getProfile(@Request() req) {
    return req.user;
  }
}

Auth Guard

import {
    CanActivate,
    ExecutionContext,
    Injectable,
    UnauthorizedException,
} from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { jwtConstants } from './constants';
import { Request } from 'express';

@Injectable()
export class AuthGuard implements CanActivate {
  constructor(private jwtService: JwtService) {}

  async canActivate(context: ExecutionContext): Promise<boolean> {
    const request = context.switchToHttp().getRequest();
    const token = this.extractTokenFromHeader(request);
    if (!token) {
      throw new UnauthorizedException();
    }
    try {
      const payload = await this.jwtService.verifyAsync(
        token,
        {
          secret: jwtConstants.secret
        }
      );
      request['user'] = payload;
    } catch {
      throw new UnauthorizedException();
    }
    return true;
  }

  private extractTokenFromHeader(request: Request): string | undefined {
    const [type, token] = request.headers.authorization?.split(' ') ?? [];
    return type === 'Bearer' ? token : undefined;
  }
}

Which approach do you think will be better? Should I follow what’s in the documentation and store the token in React, sending it whenever needed, or use HttpOnly cookies?

Custom carousel component – animation not working as intended

I have a custom carousel component (using React, Typescript and Tailwind) –

import React, { useState } from 'react'

interface Slide {
  content: React.ReactNode
  title: string
  description: string
}

interface CarouselProps {
  slides: Slide[]
}

const Carousel: React.FC<CarouselProps> = ({ slides }) => {
  const [currentIndex, setCurrentIndex] = useState(0)
  const [nextIndex, setNextIndex] = useState<null | number>(null)
  const [animationClass, setAnimationClass] = useState('')

  const goToPrevious = () => {
    setNextIndex(currentIndex === 0 ? slides.length - 1 : currentIndex - 1)
    setAnimationClass('slide-out-right') // Current slide exits to the right
  }

  const goToNext = () => {
    setNextIndex(currentIndex === slides.length - 1 ? 0 : currentIndex + 1)
    setAnimationClass('slide-out-left') // Current slide exits to the left
  }

  const goToSlide = (index: number) => {
    if (index > currentIndex) {
      setAnimationClass('slide-out-left')
      setTimeout(() => setNextIndex(index), 5000)
    } else if (index < currentIndex) {
      setAnimationClass('slide-out-right')
      setTimeout(() => setNextIndex(index), 5000)
    }
  }

  const handleAnimationEnd = () => {
    if (nextIndex !== null) {
      setCurrentIndex(nextIndex)
      setNextIndex(null)
      setAnimationClass(
        nextIndex > currentIndex ? 'slide-in-left' : 'slide-in-right'
      )
    }
  }

  return (
    <div className="carousel-container flex flex-col items-center">
      <div className="relative flex h-[250px] w-[400px] items-center justify-center">
        <button
          onClick={goToPrevious}
          className="absolute left-0 -translate-x-full px-4 py-2 text-lg font-bold text-gray-600"
        >
          ‹
        </button>
        <div className="carousel-content flex size-full items-center justify-center overflow-hidden rounded-lg bg-gray-100">
          <div
            className={`${animationClass} flex size-full items-center justify-center`}
            onAnimationEnd={handleAnimationEnd}
          >
            {slides[nextIndex !== null ? nextIndex : currentIndex].content}
          </div>
        </div>
        <button
          onClick={goToNext}
          className="absolute right-0 translate-x-full px-4 py-2 text-lg font-bold text-gray-600"
        >
          ›
        </button>
      </div>
      <div className="carousel-text mt-4 w-[400px] text-center">
        <h3 className="text-lg font-semibold">{slides[currentIndex].title}</h3>
        <p className="text-gray-600">{slides[currentIndex].description}</p>
      </div>
      <div className="carousel-indicators mt-2 flex space-x-1">
        {slides.map((_, index) => (
          <span
            key={index}
            onClick={() => goToSlide(index)}
            className={`block size-2 cursor-pointer rounded-full ${
              index === currentIndex ? 'bg-black' : 'bg-gray-300'
            }`}
          />
        ))}
      </div>
    </div>
  )
}

export default Carousel

I have these animations defined in my globals.css –

@keyframes slide-in-left {
  from {
    transform: translateX(100%);
  }
  to {
    transform: translateX(0);
  }
}

@keyframes slide-in-right {
  from {
    transform: translateX(-100%);
  }
  to {
    transform: translateX(0);
  }
}

@keyframes slide-out-left {
  from {
    transform: translateX(0);
  }
  to {
    transform: translateX(-100%);
  }
}

@keyframes slide-out-right {
  from {
    transform: translateX(0);
  }
  to {
    transform: translateX(100%);
  }
}

.slide-in-left {
  animation: slide-in-left 0.5s ease-in-out forwards;
}

.slide-in-right {
  animation: slide-in-right 0.5s ease-in-out forwards;
}

.slide-out-left {
  animation: slide-out-left 0.5s ease-in-out forwards;
}

.slide-out-right {
  animation: slide-out-right 0.5s ease-in-out forwards;
}

At the moment, the logic is behaving strangely and I can’t seem to figure out what I’m doing wrong. When the user navigates right, the content should slide out to the left and the new content should slide in from the right. This should work vice versa too. If I navigate left, the content slides out to the right and the new content slides in from the left.

Write a custom indicator for a TradingView chart

I’m trying to create a custom indicator, such as a custom moving average, to display on a TradingView chart. The TradingView documentation provides a simple example for this:

var widget = window.tvWidget = new TradingView.widget({
    // ...
    custom_indicators_getter: function(PineJS) {
        return Promise.resolve([
            // Indicator object
            {
                name: 'Custom Moving Average',
                metainfo: {
                    // ...
                },
                constructor: function() {
                    // ...
                }
            }
        ]);
    },
});

In my HTML page, I’ve implemented it like this:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Custom TradingView Chart</title>
    <script type="text/javascript" src="https://s3.tradingview.com/tv.js"></script>
</head>
<body>
    <div id="tradingview-chart" style="height: 600px; width: 100%;"></div>

    <script type="text/javascript">
        var widget = window.tvWidget = new TradingView.widget({
            container_id: "tradingview-chart",
            autosize: true,
            symbol: "BINANCE:BTCUSDT",
            interval: "D",
            timezone: "Etc/UTC",
            theme: "light",
            style: "1",
            locale: "en",
            toolbar_bg: "#f1f3f6",
            enable_publishing: false,
            allow_symbol_change: true,
            hideideas: true,
            custom_indicators_getter: function(PineJS) {
                return Promise.resolve([
                    {
                        name: 'Custom Moving Average',
                        metainfo: {
                            _metainfoVersion: 51,
                            id: 'custom-moving-average@tv-basicstudies-1',
                            name: 'Custom Moving Average',
                            description: 'Custom Moving Average',
                            shortDescription: 'CMA',
                            is_hidden_study: false,
                            is_price_study: true,
                            isCustomIndicator: true,
                            plots: [{ id: 'plot_0', type: 'line' }],
                            defaults: {
                                styles: {
                                    plot_0: {
                                        linestyle: 0,
                                        linewidth: 2,
                                        plottype: 2, // Line plot
                                        trackPrice: true,
                                        color: '#FF0000' // Red color for the custom MA line
                                    }
                                },
                                precision: 2,
                                inputs: {
                                    length: 14 // Default length for the custom MA
                                }
                            },
                            inputs: [
                                {
                                    id: 'length',
                                    name: 'Length',
                                    defval: 14,
                                    type: 'integer',
                                    min: 1,
                                    max: 100
                                }
                            ]
                        },
                        constructor: function() {
                            this.init = function(context, inputCallback) {
                                this.context = context;
                                this.input = inputCallback;
                                this.length = this.input('length', 14);
                                this.prices = [];
                            };
                            
                            this.main = function(context, inputCallback) {
                                this.context = context;
                                this.input = inputCallback;
                                
                                var close = this.context.new_var(PineJS.Std.close(this.context));
                                this.prices.push(close);

                                if (this.prices.length > this.length) {
                                    this.prices.shift(); // Maintain the window size for the moving average
                                }

                                var sum = this.prices.reduce((acc, val) => acc + val, 0);
                                var ma = sum / this.prices.length;

                                return [ma];
                            };
                        }
                    }
                ]);
            }
        });
    </script>
</body>
</html>

However, I can’t see my custom moving average indicator on the chart. Could you help me figure out the best way to properly display custom indicators on a TradingView chart?

Unwanted Not Found Screen Shows after Splash Screen in APK builds

I am developing an app in react native expo, which is working perfectly well in my development area. However, after building my apk and installing the app, my splash screen will display and next, is a black not-found screen. Once I click on the “go back” on the not found screen, that’s when I see my app’s first screen.

Please, I need help in debugging this issue because all my routes are correct.

[this is my index page, the first screen that is supposed to show after the splash screen] 1 2 3

Using loadDocumentNode in Forge viewer API only returning single element when array passed in

Hi I would really like to know why I can only display a single item when I try to load elements by specific dbIds. I am passing in an array like so [12345, 6789] and it will only display a single element. Ive checked that the external ids i pass in correctly return the objectIds and I have also ensured that the js is receiving the correct data structure for the dbId array. What is also strange and maybe related is the the element loads and is not fit to view.
Here my code:

async function loadAndInitializeForgeViewer(urn, accessToken, dbIds) {
    if (typeof Autodesk === 'undefined') {
        console.log("Autodesk namespace not found, loading Forge Viewer scripts...");

        try {
            // Load Forge Viewer CSS
            await new Promise((resolve, reject) => {
                var link = document.createElement('link');
                link.rel = 'stylesheet';
                link.href = 'https://developer.api.autodesk.com/modelderivative/v2/viewers/style.min.css';
                link.onload = resolve;
                link.onerror = reject;
                document.head.appendChild(link);
            });

            // Load Forge Viewer JS
            await new Promise((resolve, reject) => {
                var script = document.createElement('script');
                script.src = 'https://developer.api.autodesk.com/modelderivative/v2/viewers/viewer3D.min.js';
                script.onload = resolve;
                script.onerror = reject;
                document.head.appendChild(script);
            });

            console.log("Forge Viewer scripts loaded successfully.");
        } catch (error) {
            console.error("Error loading Forge Viewer scripts:", error);
            return;
        }
    } else {
        console.log("Forge Viewer scripts already loaded.");
    }

    await initializeForgeViewer(urn, accessToken, dbIds);
}

let globalViewer = null;

async function initializeForgeViewer(encodedUrn, accessToken, dbIds) {
    let options = {
        env: 'AutodeskProduction',
        getAccessToken: (callback) => {
            callback(accessToken, 3600); // Access token expires in 3600 seconds (1 hour)
        }
    };

    Autodesk.Viewing.Initializer(options, async () => {
        let viewerDiv = document.getElementById('forgeViewerContainer');
        globalViewer = new Autodesk.Viewing.GuiViewer3D(viewerDiv);

        globalViewer.start();

        let documentId = 'urn:' + encodedUrn;
        Autodesk.Viewing.Document.load(documentId, async (doc) => {
            let viewables = doc.getRoot().getDefaultGeometry();

            if (!viewables) {
                console.error("No viewable geometry found in the document.");
                return;
            }

            // Define options to load specific elements by their dbIds
            const loadOptions = {
                ids: dbIds // Use the dynamic dbIds array to load all specified elements
            };
            console.log("Loading model with specified element IDs:", dbIds);

            try {
                await globalViewer.loadDocumentNode(doc, viewables, loadOptions);
                console.log("Model loaded with specified element IDs only.");

                if (dbIds && dbIds.length > 0) {
                        globalViewer.fitToView(dbIds);
                        console.log("Fitting view to the specified elements.");
                }
            } catch (error) {
                console.error("Error loading document node:", error);
            }
        }, (errorCode) => {
            console.error("Could not load document. Error code:", errorCode);
        });
    });
}

window.showDirectoryPicker() not allowed error file picker already active

const btn = document.getElementById('btn');
const pre = document.getElementById('pre');

btn.addEventListener('click', async (e) => {

  try {
      const dirHandle = await window.showDirectoryPicker();

      pre.innerHTML = `${dirHandle.name}`;

    } 
  catch (error) {       
      console.log(error);      
    }

  });

When I click “Open” without selecting any directory and close the window, and after this , when I click the button again (btn), it gives “file already active” every time and does not open the directory window. Any solutions?

Creating Pixel Stars Using Canvas

I’m looking for a person who will help refine the code that displays the stars.
I recently saw the factorio update and their website – https://factorio.com/galaxy. I was interested in the concept of stars, namely how they are arranged. I tried to make similar stars myself, but it didn’t work out. I tried to use ChatGPT, but it doesn’t give out the right or poignant questions.
galaxy
Here is one example, as we see in the middle we have a square and the star itself is made using a square and highlights. I didn’t have any problems with the first one for rendering, but it doesn’t work very well with the second one. It is not entirely clear how to draw further.

import { useEffect, useRef, useState } from "react";
import Head from "next/head";
import styles from './star.module.css'; 
import starImage5 from '../public/star/5.png'; 
import starImage4 from '../public/star/4.png'; 
import starImage3 from '../public/star/3.png';
import starImage2 from '../public/star/2.png'; 
import starImage1 from '../public/star/1.png'; 


const generateRandomCoordinates = (numStars, offsetRange) => {
  const coordinates = [];
  const positions = [];

  for (let i = 0; i < numStars; i++) {
    const x = Math.random() * (offsetRange * 2) - offsetRange; 
    const y = Math.random() * (offsetRange * 2) - offsetRange; 

    coordinates.push(x);
    positions.push(y);
  }

  return { coordinates, positions };
};

export default function Home() {
  const canvasRef = useRef(null);
  const [offset, setOffset] = useState({ x: 0, y: 0 }); 
  const [isDragging, setIsDragging] = useState(false); 
  const [lastMousePosition, setLastMousePosition] = useState({ x: 0, y: 0 });
  
  const starData = {
    colors: [...Array(100).keys()].map(() => Math.floor(Math.random() * 16777215)),
    ids: [...Array(100).keys()].map(() => Math.floor(Math.random() * 1000000000)), 
    names: [...Array(100).keys()].map((_, i) => `Star ${i + 1}`), 
  };
  
  const { coordinates, positions } = generateRandomCoordinates(100, 200); 

  useEffect(() => {
    const images = [starImage1, starImage2, starImage3, starImage4, starImage5].map(src => {
      const img = new Image();
      img.src = src.src;
      return img;
    });

    Promise.all(images.map(img => new Promise(resolve => img.onload = resolve)))
      .then(() => {
        const canvas = canvasRef.current;
        const ctx = canvas.getContext("2d");

        canvas.width = window.innerWidth; 
        canvas.height = window.innerHeight; 

        ctx.imageSmoothingEnabled = false; 

        const drawStars = () => {
          ctx.clearRect(0, 0, canvas.width, canvas.height);

          const numStars = Math.min(starData.colors.length, coordinates.length, positions.length);

     
          for (let index = 0; index < numStars; index++) {
            const x = coordinates[index]; 
            const y = positions[index];
            const color = `#${starData.colors[index].toString(16).padStart(6, '0')}`; 

            const starX = x + offset.x + canvas.width / 2;
            const starY = y + offset.y + canvas.height / 2; 
            
            const randomStarIndex = Math.floor(Math.random() * images.length);
            const starImage = images[randomStarIndex];

            const tempCanvas = document.createElement('canvas');
            const tempCtx = tempCanvas.getContext('2d');

            tempCanvas.width = starImage.width;
            tempCanvas.height = starImage.height;
            
            tempCtx.drawImage(starImage, 0, 0);

            tempCtx.globalCompositeOperation = 'source-in';
            tempCtx.fillStyle = color;
            tempCtx.fillRect(0, 0, tempCanvas.width, tempCanvas.height);
            
            const starSize = 16; 
            ctx.drawImage(tempCanvas, starX - starSize / 2, starY - starSize / 2, starSize, starSize);
          }
        };
        drawStars();

        const handleMouseMove = (event) => {
          if (isDragging) {
            const dx = event.clientX - lastMousePosition.x;
            const dy = event.clientY - lastMousePosition.y;
            setOffset(prev => ({
              x: prev.x + dx,
              y: prev.y + dy,
            }));
            setLastMousePosition({ x: event.clientX, y: event.clientY });
            drawStars(); // Переотрисовываем звезды
          }
        };

        const handleMouseDown = (event) => {
          setIsDragging(true);
          setLastMousePosition({ x: event.clientX, y: event.clientY });
        };

        const handleMouseUp = () => {
          setIsDragging(false);
        };

        canvas.addEventListener("mousemove", handleMouseMove);
        canvas.addEventListener("mousedown", handleMouseDown);
        canvas.addEventListener("mouseup", handleMouseUp);
        canvas.addEventListener("mouseleave", handleMouseUp);

        return () => {
          canvas.removeEventListener("mousemove", handleMouseMove);
          canvas.removeEventListener("mousedown", handleMouseDown);
          canvas.removeEventListener("mouseup", handleMouseUp);
          canvas.removeEventListener("mouseleave", handleMouseUp);
        };
      });
  }, [offset.x, offset.y]);
  return (
    <>
      <div className={styles.imageContainer}>
        <canvas ref={canvasRef} className={styles.pixelCanvas} />
      </div>
    </>
  );
}

The developers themselves did it using Three.js

I tried to create highlights by applying layers on top, it didn’t work out very well

entersource code of the star
I also noticed the source code of the star on the site, through the developer console (Network)

Issue in updating the nested array object in MongoDB using mongoose

Here is my code for my API endpoint api/admin/changeStock in Next.js app

import connectToDb from "@/lib/mongodb";
import { Coco, Brand } from "@/models/model";
import { NextResponse } from "next/server";

export async function POST (req) {
    const { brand, modelname, stockNum } = await req.json();
    await connectToDb();
    const selectedBrandModel = await Coco.findOne({ brand });
    const model = selectedBrandModel.models.find(model => model.modelname === modelname); // version A
    console.log("model from /changeStock: " + model) // shows version A

    if (!model?.productIDs) {
        console.log("In if from /changeStock");
        model.productIDs = ["d1", "d2"]; // version B
        console.log("model from /changeStock after inserting: " + model); // shows version A
        console.log("model.productIDs from /changeStock after inserting: " + model.productIDs); // shows the correct model.productIDs from version B
        selectedBrandModel.markModified("models");
        await selectedBrandModel.save(); // does not save the updated version still remain version A in database
        return NextResponse.json({ message: "changed1"}, { status: 200 });
    } else {
        console.log("in else /changeStock");
        model.productIDs = ["s1", "s2", "s3", "s4"];
        selectedBrandModel.markModified("models");
        await selectedBrandModel.save();
        return NextResponse.json({ message: "changed2"}, { status: 200 });
    }
}

I do not get it that why the console logs are not giving me the updated model which is an object in the selectedBrandModel.models array also await selectedBrandModel.save() does not save the updated version B of models in database. Right now no object (model) inside the models array in brand have a property model.productIDs so if(!model?.productIDs) is always true.

Also for some reason when i just try to change the modelname like model.modelname = modelname + " |Modified"; instead of adding a property like i was above model.productIDs = ["d1", "d2"]; then that works totally fine.

React native Keyboard covering the UI,Elements and dynamically not adjusting

Aa you can see here this is my design and here keyboard is not actived

This is the image when i click on the textinput filled which open the key and the problem i faced was 1.the open of keyboard doesnot have good visual transition when keyboard is appearing
2.The other problem is the keyboard is block the input how can to arrage the keyboard ??

The Other thing i want to mention is i have tried using KeyBoardAvoidingview,KeyBoardAvoidScrollView but it did not workout or i may not have implement it properly even if that is the case i realised that developing with RN is like am jumping from one thing to another, solving one problem and and another problem arise form the previous solution and to solve that i have to jump to another thing to solve that problem, also there is no transition animation when the keyboard appear and the Formwrapper changes it position and there is also no any transition effect,that leads to bad user UI/UX .
i have seen many react native mobile application but i don’t see any problem out there and the animation is smooth and appealing, Like they been saying instram is made using reactnative however through my research i found out that its not entirely build on reactnative only some part of that app is used react native and remaining they built using native code.
I have been trying to make an app and searching this keyboard problem for like 3days and still haven’t found out the proper solution it only give a buch of package which in most case the app is either not compatilbe with expo go or should use only native react native.
I think this is the case where many developer will face problem ,and am thinking about to swith from react native to flutter. and asking to different developers i found flutter provide solution out of the box . or it has handled the problem properly
Even in the react native documentation there is not proper solution mentioned.
Below is the layout code of the screenshots i have provided

import {
  Animated,
  Keyboard,
  Text,
  TextInput,
  TouchableOpacity,
  View,
  Easing,
  StyleSheet,
  KeyboardAvoidingView,
} from "react-native";
import React, { useEffect, useRef, useState } from "react";
import { navigationProps } from "../SplashScreen";
import colors from "../../Constant/color";

import Icon from "react-native-vector-icons/Feather";

const Signup = ({ navigation }: navigationProps) => {
  const [form, setForm] = useState({
    firstname: "",
    lastname: "",
    phonenumber: null,
    address: "",
    email: "",
    password: "",
    confirmpassword: "",
  });
  const [secureText, setSecureText] = useState({
    password: true,
    confirmpassword: true,
  });
  const [expanded, setExpanded] = useState(false);
  const translateY = useRef(new Animated.Value(0)).current;

  const animateFormWrapper = (toValue: number) => {
    Animated.timing(translateY, {
      toValue,
      duration: 600, // Adjust duration as needed
      easing: Easing.bezier(0.68, -0.55, 0.27, 1.55),
      useNativeDriver: true,
    }).start();
  };

  useEffect(() => {
    const keyboardShowListener = Keyboard.addListener(
      "keyboardDidShow",
      (e) => {
        animateFormWrapper(-e.endCoordinates.height / 4);
        Animated.timing(translateY, {
          toValue: 0, // Adjust the position based on keyboard height
          duration: 100,
          easing: Easing.bezier(0.39, 0.57, 0.56, 1),
          useNativeDriver: true,
        }).start();
      }
    );

    const keyboardHideListener = Keyboard.addListener("keyboardDidHide", () => {
      Animated.timing(translateY, {
        toValue: 0,
        duration: 300,
        useNativeDriver: true,
      }).start();
    });

    return () => {
      keyboardShowListener.remove();
      keyboardHideListener.remove();
    };
  }, [translateY]);

  return (
    <View style={styles.container}>
      <View style={styles.formWrapper}>
        <View>
          <Text style={styles.title}>Set up your profile</Text>
          <Text style={styles.subtitle}>The shop you need</Text>
        </View>
        <View style={styles.form}>
          <View style={styles.input}>
            <TextInput
              autoCapitalize="none"
              autoCorrect={false}
              style={styles.inputControl}
              placeholder="First Name"
              placeholderTextColor={"#5c5c5b"}
              value={form.email}
              onChangeText={(email) => setForm({ ...form, email })}
            />
          </View>
          <View style={styles.input}>
            <TextInput
              autoCapitalize="none"
              autoCorrect={false}
              style={styles.inputControl}
              placeholder="Last Name"
              placeholderTextColor={"#5c5c5b"}
              value={form.email}
              onChangeText={(lastname) => setForm({ ...form, lastname })}
            />
          </View>
          <View style={styles.input}>
            <TextInput
              autoCapitalize="none"
              autoCorrect={false}
              keyboardType="email-address"
              style={styles.inputControl}
              placeholder="Email"
              placeholderTextColor={"#5c5c5b"}
              value={form.email}
              onChangeText={(email) => setForm({ ...form, email })}
            />
          </View>
          <View style={styles.input}>
            <TextInput
              secureTextEntry={secureText.password}
              autoCapitalize="none"
              autoCorrect={false}
              style={styles.inputControlPassword}
              placeholder="********"
              placeholderTextColor={"#5c5c5b"}
              value={form.password}
              onChangeText={(password) => setForm({ ...form, password })}
            />
            <TouchableOpacity
              style={styles.iconContainer}
              onPress={() =>
                setSecureText((prev) => ({
                  ...prev,
                  password: !prev.password,
                }))
              } // Toggle secureTextEntry
            >
              <Icon
                name={secureText.password ? "eye" : "eye-off"} // Icon changes based on visibility
                size={20}
                color="#b9b8b6"
              />
            </TouchableOpacity>
          </View>
          <View style={styles.input}>
            <TextInput
              secureTextEntry={secureText.confirmpassword}
              autoCapitalize="none"
              autoCorrect={false}
              style={styles.inputControlPassword}
              placeholder="confirm Password"
              placeholderTextColor={"#5c5c5b"}
              value={form.confirmpassword}
              onChangeText={(confirmpassword) =>
                setForm({ ...form, confirmpassword })
              }
            />
            <TouchableOpacity
              style={styles.iconContainer}
              onPress={() =>
                setSecureText((prev) => ({
                  ...prev,
                  confirmpassword: !prev.confirmpassword,
                }))
              } // Toggle secureTextEntry
            >
              <Icon
                name={secureText.confirmpassword ? "eye" : "eye-off"} // Icon changes based on visibility
                size={20}
                color="#b9b8b6"
              />
            </TouchableOpacity>
          </View>
          <View>
            <TouchableOpacity
              style={styles.btn}
              onPress={() => navigation.goBack()}
            >
              <Text style={styles.btnText}>Continue</Text>
            </TouchableOpacity>
          </View>
        </View>
      </View>
    </View>
  );
};

export default Signup;

const styles = StyleSheet.create({
  container: {
    flex: 1,
    borderColor: "red",
    borderWidth: 1,
    backgroundColor: colors.background,
    justifyContent: "flex-start",
    paddingHorizontal: 15,
    maxHeight: "100%",
  },

  title: {
    fontSize: 35,
    fontWeight: "800",
    color: colors.headerText,
  },
  subtitle: {
    fontSize: 18,
    marginTop: 5,
    color: colors.text,
    fontWeight: "400",
  },
  formWrapper: {
    height: "80%",
    borderColor: "green",

    borderWidth: 1,
    justifyContent: "flex-start",

    gap: 30,
  },
  form: {
    padding: 10,
  },
  input: { marginBottom: 16 },
  inputLabel: {
    fontSize: 17,
    fontWeight: "600",
    color: colors.text,
    marginBottom: 8,
  },
  inputControlPassword: {
    height: 55,
    position: "relative",
    backgroundColor: "white",
    paddingVertical: 10,
    paddingHorizontal: 16,
    borderRadius: 45,
    borderColor: "#e8e7e4",
    borderWidth: 1,
    fontWeight: "500",
    color: "#222",
  },
  inputControl: {
    height: 55,
    backgroundColor: "white",
    paddingVertical: 10,
    paddingHorizontal: 16,
    borderRadius: 25,
    borderColor: "#e8e7e4",
    borderWidth: 1,
    fontWeight: "500",
    color: "#222",
  },
  iconContainer: {
    right: 15,
    top: 15,
    alignItems: "center",
    alignSelf: "center",
    position: "absolute",
  },
  btn: {
    marginTop: 30,
    backgroundColor: colors.button,
    paddingHorizontal: 28,
    borderColor: "gray",
    borderRadius: 25,
    paddingVertical: 15,
  },
  btnText: {
    fontSize: 15,
    fontWeight: "400",
    color: colors.buttonText,
    textAlign: "center",
  },
});

Puppeteer clicking Reddit login button

I’m running into trouble with Puppeteer with selecting a button during a login process. I’m trying to have it log in to Reddit but the login button has no name or ID and there are other buttons that might get selected. It’s also wrapped in other elements so I’m not even sure which one to select. I’ll include my code below. Does anyone know what I can do to press the login button on Reddit.com after it enters the username and password? Selecting the other elements was easy because they have ids.

const puppeteer = require ('puppeteer');

function sleep(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
}

async function loginToReddit(usernameText, passwordText){
    const browser = await puppeteer.launch({
        headless: false,
        defaultViewport: false,
        userDataDir: "./tmp"
    });
    const page = await browser.newPage();
    await page.goto('https://www.reddit.com/');
    await page.click('#login-button');

    sleep(2000).then(() => {
        enterCredentials(usernameText, passwordText, page);
    });
}

async function enterCredentials(usernameText, passwordText, page){
    await page.click('#login-username');
    await page.keyboard.type(usernameText,{
        delay: 50,
    });
    await page.click('#login-password');
    await page.keyboard.type(passwordText,{
        delay: 50,
    });
    sleep(2000).then(() => {
        selectLoginButton(page);
    });
}

async function selectLoginButton(page) {
    page.waitForNavigation();
    //const xp = 'faceplate-tracker button';
    const xp = 'faceplate-tracker > button';
    const el = await page.waitForSelector(xp);
    await el.click();
}

loginToReddit('username', 'password');

Listening to content changes in Ace editor

I have to listen to content changes in an Ace editor. I figured out many ways to do it, and I would like to know the best / most adequate / canonical way to do it.

  • I am only interested in content changes. The event handler should be fired when user types/deletes characters, and I don’t need to know the content.
  • There is no “multi-editor”: single editor session, no tabs. Though, for the future, supporting multiple sessions may be interesting, if there is no additional cost.

Questions:

  • Should I use Editor or EditSession?
  • If using the edit session, should I access it using the getter or directly the property? (getter should be the recommended one, but the property is exposed as well…)
  • Should I listen to “change” or “input”? Notes:
    • Native <textarea>’s use “input”.
    • There are editor.on('input', ...), editor.on('change', ...), editSession.on('change', ...), but not editSession.on('input', ...).

API references:

Additional question: when trying editSession.on('change', () => ...), I noticed the callback receives a “delta” object, whereas the callback is expected to provide no parameters. If someone has an explanation for this…

Why does updating the state array in reactjs is not reflecting in my child component UI

After I receive the response from an API, I am trying to update my child component based on the response data. But the below code is not able to update the UI, and also when I added console in the child component, it looked like the child component is not getting re-rendered. Changes in props are only reflecting but not from the state array object.

Below code I am using from parent to render the child component based on array variable – dataSource

<div id='row-item-container'>
<p>This will render the tabular part</p>
{ this.state.dataSource.length>0 && <div id='trxBox'>
    {this.state.dataSource.map(exp=>(
        <ExpenseEditableBlock data={exp} onDataChange={this.handleDataChange}
        key={exp.TrxID} 
        onExpSelect={this.selectThisExpItem}
        readonly={this.state.validationRenderer}
        validFlag={exp.ValidFlag}
        style={{marginBottom: '5px'}}/>
    ))}
</div>}

Below setState I am using to update the dataSource variable in parent component for the child component

this.setState({dataSource: itemsParam});

Child Component:

import React, { Component } from "react";
import '../../CompCss/ExpenseEditableBlock.css';
import 'react-dropdown/style.css';
import { Utils } from './../Utils';

const utils = Utils();

class ExpenseEditableBlock extends Component {

    constructor(props){
        super(props);
        this.state = {
            expenseData: props.data,
            categoryArray: [],
            _otherVarName_ : null,
            checked: false
        }

       console.log('props ----->',props,'nProps data:',this.state.expenseData);

        utils.expCategories().forEach((item) => {
            this.state.categoryArray.push(item.label);
        });
    }

  render() {
    return (
      <div className={(this.state.expenseData.ValidFlag === "FAIL")?"exp-block-box-one disabled-item":"exp-block-box-one"} style={this.props.style}>
        <div id="exp-item-head-section">
            <div className="display-inline-block">
                <p>Trx ID: {this.state.expenseData.TrxID}</p>
                <p>{this.state.expenseData.ValidFlag}</p>  /*THIS IS NOT REFLECTING THE VALUE */
                <p>{this.props.validFlag}</p>  /*whereas THIS IS REFLECTING THE VALUE */
            </div>
        </div>
        <div>
            <div className="exp-date-block">{this.state.expenseData.TrxDate}</div>
            <div>
                <p>{this.state.expenseData.TrxTitle}</p>
            </div>
        </div>
        
        <div style={{height: '3px'}}>
            {/* <TextField id="standard-basic" label="Standard" variant="standard" /> */}
        </div>
      </div>
    )
  }
}

export default ExpenseEditableBlock;

Below image for what I am trying to achieve
enter image description here

Why is WebAssembly execution not notably faster than JavaScript execution?

I stumbled upon this interesting speed comparison of JavaScript and WebAssembly:
enter image description here

I wondered why the difference in speed is relatively low, I expected the speed difference to be in magnitude of hundreds. Doing the FFT (Fast-Fourier-Transform) algorithm the JavaScript code even seems to execute faster.

Other tests found on the web show similar results, many result in JavaScript and WebAssembly executing at roughly the same speed.

I am very surprised by this! Why wouldn’t code which is basically already machine code run magnitudes faster than JavaScript code, which has to be interpreted at runtime?