How would you create an app like this outfit creator? [closed]

I was about to have a back and forth with ChatGpt about this but thought I’d come here and maybe get some different solutions.

I’ve come across this outfit maker by Uniqlo where you select clothing items from a collection and drag them onto a canvas to make an outfit. The images can be dragged, resized and manipulated.

I have some experience with Javascript to the point that I know how to dynamically render the products in the collections, but has anyone got any ideas on how to implement the canvas with the images that can be manipulatable? I will be working with React

Uniqlo’s outfit maker

Infinite loop with array.includes in while loop

I’m struggling with this script, trying to push new set of data in an array (‘occupes’), while checking that it is not already in that array.
I use a while loop to do so, but it crashes (infinite loop), when the condition is true i guess, as if ‘other_p_ligne’ and ‘other_p_col’ were not updated to rerun the test ?

function randomize(min, max) {
  return Math.floor(Math.random() * (max - min + 1) + min);
}

var ligne_min = 1;
var ligne_max = 8;
var col_min = 1;
var col_max = 8;
var occupes = ["1,3", "3,2", "4,6"];
var other_p_ligne;
var other_p_col;

for (let i = 1; i <= 6; i++) {
  other_p_ligne = randomize(ligne_min, ligne_max);
  other_p_col = randomize(col_min, col_max);
  
  while (occupes.includes(other_p_ligne + "," + other_p_col) === true) {
    other_p_ligne = randomize(ligne_min, ligne_max);
    other_p_col = randomize(col_min, col_max);
  }
  
  occupes.push(other_p_ligne + "," + other_p_col);
}

Get data from html form to Google sheet

I have a simple web for users submitting data from HTML form to Google sheet for my company like this repo https://github.com/levinunnink/html-form-to-google-sheet

But when I config the app. My web app can only be used by anyone in my company so when I submit data the API response 401.

I want to know if there is any way for the users to submit data to our company’s google sheet or any keyword to search about this.

Swiper.js: Second slide overlaps the first with the “fade” effect

I am trying to implement Swiper.js and the error I am getting is that the second carousel item is overlapping over the first one. The issue persists even when I use the fade effect.

I’ve tried adjusting the space between and setting it to 0, but it didn’t solve the issue. Also ensuring that the height of the swiper container and the images is correct.

I’ve tried different Swiper modules like EffectFade, Autoplay, and Pagination.

What might be causing the overlapping issue with the second carousel item? How can I ensure that the slides transition smoothly without overlapping? Is there any missing configuration or CSS that’s causing this issue?

import { Swiper, SwiperSlide } from 'swiper/react';
import { EffectFade, Navigation, Autoplay, Pagination } from 'swiper/modules';
import 'swiper/css';
import 'swiper/css/effect-fade';
import 'swiper/css/navigation';
import 'swiper/css/pagination';

import '../../../src/styles.css';
// import { useRef } from 'react';

const Hero = () => {
  const cakeData = [
    {
      image: "/images/Category/wedding.png",
      title: "Elegance in Every Layer",
      subtitle: "Wedding Cakes to Remember Forever",
      description:
        "Celebrate your love story with a cake that’s as beautiful and unique as your special day. Handcrafted with love, our wedding cakes are designed to impress."
    },    {
      image: "/images/Landing/BirthdayCake-removebg.png",
      title: "A Slice of Happiness",
      subtitle: "Custom Cakes for Birthday Magic",
      description:
        "Brighten someone’s birthday with a cake tailored to their favorite flavors and styles. From kids' parties to milestone celebrations, we’ve got you covered!"
    },]
  // const swiperRef = useRef(null);


  return (
    <div className="bg-[#FEF2F5] ">
      <Swiper
        spaceBetween={30}
        effect={'fade'}
        navigation={false}
        autoplay={{
          delay: 3000,
          disableOnInteraction: false,
        }}
        pagination={{
          clickable: true,
        }}
        // onSwiper={(swiper) => {
        //   swiperRef.current = swiper; // Store the Swiper instance
        // }}
        modules={[EffectFade, Autoplay, Navigation, Pagination]}
        className="mySwiper"
      >

        {cakeData.map((landing, index) =>
          <SwiperSlide key={index}>

<div className="container flex flex-col-reverse gap-10 text-[#333333] items-center py-14 md:flex-row md:gap-32 md:pr-0">
              <div className="md:flex-1 ">
                <h1 className="font-semibold font- text-4xl text-[#A55668]  leading-loose md:text-5xl">{landing.title}</h1>
                <h2 className="py-4 font-semibold text-sm md:text-lg">
                  {landing?.subtitle}
                </h2>
                <p className="pb-8 text-sm font-poppins md:text-base">
                  {landing.description}            </p>
                <button className=" rounded-full bg-[#ED6A77] text-white p-2 px-8">Order Now</button>
              </div>
              <div className="md:flex-1">
                <img src={landing.image} className="lg:h-[80vh] object-cover" alt="" />
              </div>

            </div>
          </SwiperSlide>
        )}
        </Swiper>
    </div>
  )
}

export default Hero
#app { height: 100% }

html,
body {
  position: relative;
  height: 100%;
}

body {
 
  font-size: 14px;
  color: #000;
  margin: 0;
  padding: 0;
}

.swiper {
  width: auto;
  height: auto;
}

.swiper-slide {
  background-position: center;
  background-size: cover;
}

.swiper-slide img {
  display: block;
  width: auto;
}

Validate a text string using Regex in Javascript [closed]

I am trying to validate a text if it matches a pattern using Regular expression, however facing some issues. It is always returning false.

The text string is “ABC 6766576” . The first word can contain multiple characters, and the second word can contain any numbers

So, this is what I did

let value = 'ABC 64647674';

let rex = /^[a-zA-Z]{0-9}+s+d{0-9}$/;

console.log(rex.test(value));

The result is false. What I am missing here?

Thanks

How to explain the this pointer in JavaScript? [duplicate]

I try to print this in two ways. But get different results. How to explain this.

function A(executor){
    this.data = 1;
    this.executor = executor;
    this.executor();

}


function printThis(){
    console.log(this);
    
}



let a = new A(()=>{
    console.log(this);
})

let b = new A(printThis);

In a, this = {}
In b, this = A{data:1, executor:[Function:printThis]}

The executor function are used in A. But why, the results are different?

Is there a way to only have one instance of THREE when using Threebox

I am using Threebox with Mapbox, I define threebox like so:

(window as any).tb = new Threebox(this, gl, { defaultLights: true });

but I am also importing THREE like so:

import * as THREE from 'three';

So that I can use it for things like raycasting.

I am getting this warning in my app:

“WARNING: Multiple instances of Three.js being imported.”

I am wondering if there is a way to get threebox to use the same instance of THREE, or be able to use the threebox instance of THREE somehow, without importing THREE again.

Angular 19 ssr Domino sloppy.js with in strict mode

I am trying to update my angular version from 18 to 19.0.1

Domino library causing issue and angular not able to compile. I have domino-ext in my server.ts

Domino error

My server.ts


import 'zone.js/node';


import { enableProdMode } from "@angular/core";
(global as any).WebSocket = require('ws');
(global as any).XMLHttpRequest = require('xhr2');
// import 'zone.js/dist/zone-node';
const domino = require('domino-ext');
const fs = require('fs');
const path = require('path');


import { CommonEngine } from '@angular/ssr/node';
import * as express from 'express';
import { existsSync } from 'node:fs';
import { join } from 'node:path';
const dotenv = require('dotenv');
dotenv.config();
const distFolder = join(process.cwd(), 'dist/ss/browser');
const template = fs.readFileSync(path.join(distFolder, 'index.html')).toString();
const win = domino.createWindow(template.toString());
global['window'] = win;
global['document'] = win.document;
global['DOMTokenList'] = win.DOMTokenList;
global['Node'] = win.Node;
global['Text'] = win.Text;
global['HTMLElement'] = win.HTMLElement;
global['navigator'] = win.navigator;
global['getComputedStyle'] = win.getComputedStyle;
// The Express app is exported so that it can be used by serverless Functions.
enableProdMode();
import AppServerModule from './main.server';
import { APP_BASE_HREF } from '@angular/common';

export function app(): express.Express {
  const server = express();
  const distFolder = join(process.cwd(), 'dist/ss/browser');
  const indexHtml = existsSync(join(distFolder, 'index.original.html'))
    ? join(distFolder, 'index.original.html')
    : join(distFolder, 'index.html');

  const commonEngine = new CommonEngine();

  server.set('view engine', 'html');
  server.set('views', distFolder);

  // Example Express Rest API endpoints
  // server.get('/api/**', (req, res) => { });
  // Serve static files from /browser

  const cors = require('cors');
  
  
  const corsOptions = {
    origin: ['https://*.example.com', 'https://example.com', "localhost:4200"], // Whitelist your domains
    methods: 'GET,HEAD,PUT,PATCH,POST,DELETE',
    credentials: true, // Include cookies for authentication
  };
  
  server.use(cors(corsOptions));

  server.get('*.*', express.static(distFolder, {
    maxAge: '1y'
  }));
  let routesPath = ['/invite', 'login', '/invite/**','/lm', '/dashboard', '/dashboard/**', '/public/**', '/public', '/pre'];
  server.get(routesPath, (req, res) => {
    // console.log(req);
    res.sendFile(distFolder + '/index.html');
  });

  // All regular routes use the Angular engine
  server.get('*', (req, res, next) => {
    const { protocol, originalUrl, baseUrl, headers } = req;

    commonEngine
      .render({
        bootstrap : AppServerModule,
        documentFilePath: indexHtml,
        url: `${protocol}://${headers.host}${originalUrl}`,
        publicPath: distFolder,
        providers: [
          { provide: APP_BASE_HREF, useValue: baseUrl },
          { provide: 'customConfig', useValue: req.get('host') }
        ],
          
      })
      .then((html) => res.send(html))
      .catch((err) => next(err));
  });

  return server;
}

function run(): void {
  const port = process.env['PORT'] || 8000;

  // Start up the Node server
  const server = app();
  server.listen(port, () => {
    console.log(`Node Express server listening on http://localhost:${port}`);
  });
}

// Webpack will replace 'require' with '__webpack_require__'
// '__non_webpack_require__' is a proxy to Node 'require'
// The below code is to ensure that the server is run only when not requiring the bundle.
declare const __non_webpack_require__: NodeRequire;
const mainModule = __non_webpack_require__.main;
const moduleFilename = mainModule && mainModule.filename || '';
if (moduleFilename === __filename || moduleFilename.includes('iisnode')) {
  run();
}

export * from './main.server';

Problem with navigator.serial of SPP bluetooth using Windows 11

I developed a web app that connects to my ESP32 bluetooth as it was a serial port, this is called SPP (Serial Port Profile).

It was working on my PC with Windows 10, but as I was testing it in different computers I realise this isn’t working anymore in Windows 11.

The console just gives an output “Cannot connect with the serial port”, no further information…. It is really weird, because nothing has changed more than the OS, from W10 to W11.

As I said before, in the W10 it just got connected perfectly, once I try it on a W11 computer it always gives the error.

Do you know why it is happening? I have tried to get more information about the connection but I couldn’t get anything else than unable to connect…

This is the code of the connection:

const connectToESP32 = async () => {
let newPort = null
let readers = null
let writers = null
try {
  // @ts-ignore
  newPort = await navigator.serial.requestPort({
    filters: [{ bluetoothServiceClassId: btClass }],
  })
  if ("serial" in navigator) {
    toast.loading("Connected", {
      id: "1",
    })
  } else {
    toast.error("Not compatible", {
      id: "1",
    })
  }
  await newPort.open({ baudRate: 115200 })
  setPort(newPort)
  console.debug("Port info: ", newPort.getInfo())

  const textDecoder = new TextDecoder()
  readerRef.current = newPort.readable?.getReader()
  writerRef.current = newPort.writable?.getWriter()

  readers = readerRef.current
  writers = writerRef.current

}} catch (error) {
  console.error("Error connecting:", error)
  setStopProg(true)
  toast.error("Error connecting", {
    id: "1",
  })
  if (newPort) {
    try {
      // @ts-ignore
      readers.releaseLock()
      // @ts-ignore
      writers.releaseLock()
      await newPort.close()
    } catch (error) {
      console.error("Error al cerrar puerto:", error)
    }
    setPort(null)
  }
}
}

The application was working perfectly in Windows 10, so I am worried it might be something related with a layer behind….

Can’t get JsDiff to work properly for custom diffing in vscode

I tried creating a custom diffing functionality for my vscode extension because vscode doesn’t support showing all diffs in file at once,i think git uses it’s own code for diffing too so i had to implement mine using the library jsdiff but currently the diff doesn’t include the added lines and only displays the original text and also adds an orange decorator all over the place when i only have a added and removed text decorations which are green and red which has really left me confused,here’s my implementation:

async function showInlineDiff(fileUri: vscode.Uri, newCode: string) {
    const currentFileContent = await vscode.workspace.fs.readFile(fileUri);
    const originalText = Buffer.from(currentFileContent).toString('utf-8');

    // Normalize line endings
    const normalizedOriginalText = originalText.replace(/rn/g, 'n');
    const normalizedNewCode = newCode.replace(/rn/g, 'n');

    console.log("normal normal",normalizedNewCode,"broker",normalizedOriginalText);

    const diffs = diffLines(normalizedOriginalText, normalizedNewCode);

    const editor = await vscode.window.showTextDocument(fileUri);

    const addedDecorationType = vscode.window.createTextEditorDecorationType({
        backgroundColor: 'rgba(0,255,0,0.3)',
        isWholeLine: true,
    });

    const removedDecorationType = vscode.window.createTextEditorDecorationType({
        //textDecoration: 'line-through',
        backgroundColor: 'rgba(255,0,0,0.3)',
        isWholeLine: true,
    });

    const addedRanges: vscode.Range[] = [];
    const removedRanges: vscode.Range[] = [];
    let lineNumber = 0;

    for (const part of diffs) {
        const lines = part.value.split('n');

        if (part.added) {
            lines.forEach((line, i) => {
                if (i < lines.length - 1) {
                    addedRanges.push(
                        new vscode.Range(lineNumber + i, 0, lineNumber + i, line.length)
                    );
                }
            });
        } else if (part.removed) {
            lines.forEach((line, i) => {
                if (i < lines.length - 1) {
                    removedRanges.push(
                        new vscode.Range(lineNumber + i, 0, lineNumber + i, line.length)
                    );
                }
            });
        }

        if (!part.removed) {
            
            lineNumber += lines.length - 1;
        }
    }

    

    editor.setDecorations(addedDecorationType, addedRanges);
    editor.setDecorations(removedDecorationType, removedRanges);

    vscode.window.showInformationMessage('Changes have been highlighted.');
}

Finding all ‘free’ text in a HTML

I have a bunch of local html pages containing free (not enclosed in any tags) text.

<body>
<div> ... </div>
Lorem ipsum dolor sit amet, consectetur adipiscing elit,
sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.<br>
Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip.<br>
...
</body>

I’m looking for a way to select and live-manipulate these chunks of text (and only these, not text in any other container).
The page is displayed in a WebView2 browser, so the access to the DOM is limited to javascript or the WebView2.DevTools.DOM library.

I tried to find an appropriate selector, without success.

Tool to format or beautify JS code as Golang practice

Here is a TypeScript code:

enum MyEnum {
    FIRST = 'first',
    SECOND_ELEMENT = 'second',
}

If this was written in Go, it would look like this:

enum MyEnum {
    FIRST          = 'first',
    SECOND_ELEMENT = 'second',
}

Do we have any tool for formatting the JavaScript/TypeScript/NodeJS ecosystem like in Golang?

How to format and display streaming Markdown data on the fly in TypeScript using Showdown?

Problem Description:
I am building a chat application in TypeScript that streams Markdown data from an API. The data is received in chunks, and I need to format and display it in real-time using Showdown.js. However, the streamed Markdown data does not format properly as it is displayed incrementally.

Issues Encountered:
Incomplete Formatting: The streamed Markdown data does not format correctly in real-time. For example, headers (#), line breaks, and lists often don’t render as expected.
Real-Time Conversion: Since the content is received in parts, Showdown seems to struggle with incremental conversion.

Questions:
How can I correctly format and display Markdown data as it streams in real-time?
Is Showdown.js suitable for this use case, or should I consider an alternative Markdown parser?
Are there any specific techniques or configurations in Showdown.js that can handle this scenario better?

let accumulatedResponse = ''; // Accumulates chunks

for await (const chunk of streamChatCompletion(params)) {
    if (chunk.includes("[DONE]")) continue; // Ignore completion marker

    const cleanChunk = chunk.replace(/^data:s*/g, '').trim();

    accumulatedResponse += cleanChunk;

    if (!messageBubble) {
        // Create the initial message
        messageBubble = displayMessage(chatWindow, accumulatedResponse, "bot", false);
    } else {
        // Update the message with accumulated content
        updateMessage(messageBubble, accumulatedResponse, "bot", false);
    }
}
public updateMessage(
  messageElement: HTMLElement,
  newContent: string,
  sender: 'user' | 'bot'
): HTMLElement {
    const converter = new showdown.Converter({ tables: true });
    const htmlMessage = converter.makeHtml(newContent);

    const messageContent = messageElement.querySelector('.messageContent');
    if (messageContent) {
        messageContent.innerHTML = htmlMessage; // Replace content with formatted HTML
    }
    return messageElement;
}