HonoJS: How to enforce type checking in watch mode

I’ working on a honojs application and the default run command doesn’t enforce type checking

    "dev": "tsx watch src/index.ts"

I changed it to "tsx watch src/index.ts" but it only performs type checking when I first start the server, no type checking is performed in watch mode.

How can I enforce type checking in watch mode?

Uncaught SyntaxError: redeclaration of const navLinks in Javascript

I was writing a simple webpage with a responsive navigation bar. The Navbar works find locally but it did not work any more when I put it on a host.

I saw an error like:
Uncaught SyntaxError: redeclaration of const navLinks
note: Previously declared at line 1, column 7

const navLinks = document.querySelectorAll('.nav-menu .nav-link');
const menuOpenButtion = document.querySelector('#menu-open-button');
const menuCloseButtion = document.querySelector('#menu-close-button');

menuOpenButtion.addEventListener('click', () => {
  // Toggle mobile menu visibility
  document.body.classList.toggle('show-mobile-menu');
});

// Close menu when the close button is clicked
menuCloseButtion.addEventListener('click', () => menuOpenButtion.click());

navLinks.forEach((link) => {
  link.addEventListener('click', () => menuOpenButtion.click());
});

Could sb help me figure out why?

How can I make this image extend while keeping the text aligned?

 A friend asked me to help them with their web page but I can’t quite figure it out. He wants the text to be aligned with the image above (everything is centered as a section with margin: auto; and max-width: 1300px) while the image on the right should extend to the right of the page like in the image, but I can’t make the image be at the right without messing up the alignment of the text.
 I tried using position: relative; on the image but I can’t make it stick to the right of the page. I also tried making the image the background-image of the green section but when I zoom in a bit the text seems to overlap. Any other solution I had messed with the text.

.verde2{
    width: 100%;
    height: 500px;
    background-color: #00824B;
}
.verde-container{
    display: flex;
    max-width: 1300px;
    height: inherit;
    margin: auto;
}
.verde2-text, .verde2-poza{
    
    height: inherit;
}
.verde2-text h3 {
    margin-top: 0;
    font-size: 1.8em;
    display: flex;
    align-items: center;
    gap: 10px;
}
.verde2-text{
    display: flex;
    flex-direction: column;
    padding: 25px;
    padding-left: 0px;
    gap: 25px;
    width: 60%;
}

.verde2-poza{
    width: 40%;
    height: 500px;
    background-image: url("AdobeStock_250597018.png");
    background-repeat: no-repeat;
    background-size: cover;
    background-position: right;
}
<section class="verde2">
    <div class="verde-container">
        <div class="verde2-text">
            <h3>
            <img class="verde-icon" src="Group 15.png" alt="iconss">
            De ce este importanta<br>durabilitatea?</h3>
            <p>Exista multe avantaje pentru durabilitate, atat pe termen scurt, 
            cat si pe termen lung. Nu putem mentine ecosistemele 
            Pamantului sau nu putem continua sa functionam asa cum o 
            facem daca nu se fac alegeri mai durabile.Daca procesele 
            daunatoare sunt mentinute fara nicio modificare, este probabil 
            ca vom ramane fara combustibili fosili, un numar mare de specii de animale vor disparea si atmosfera va fi afectata iremediabil. 
            Aerul curat si conditiile atmosferice netoxice, cresterea resurselor 
            pe care se poate baza, precum si calitatea si curatenia apei sunt 
            toate beneficii ale sustenabilitatii.</p>
    </div>
    <div class="verde2-poza">
    </div>
    </div>
</section>  

enter image description here

How to only show validation errors if a field is touched or modified?

I’m using a form with JSON Form and I’m having trouble performing validations. The problem is that the input fields turn red even before the user types anything. I want the error that the field is mandatory to appear only if the user clicks on the field, leaves it blank and clicks away again, or if the user tries to submit the form. Then it shows in red which fields are mandatory.

Can you tell me how to do this treatment correctly? Thank you

The form already has errors appearing when the page is first loaded:

enter image description here

'use client';

import { useState, useEffect } from 'react';
import { JsonForms } from '@jsonforms/react';
import { materialRenderers } from '@jsonforms/material-renderers';
import { materialCells } from '@jsonforms/material-renderers';
import axios from 'axios';
import { Button } from '@mui/material';

const schema = {
  type: 'object',
  properties: {
    first_name: { type: 'string', title: 'First Name' },
    last_name: { type: 'string', title: 'Last Name' },
    email: { type: 'string', title: 'Email' },
    linkedin_url: { type: 'string', title: 'LinkedIn URL' },
  },
  required: ['first_name', 'last_name', 'email', 'linkedin_url'],
};

const uischema = {
  type: 'VerticalLayout',
  elements: [
    { type: 'Control', scope: '#/properties/first_name' },
    { type: 'Control', scope: '#/properties/last_name' },
    { type: 'Control', scope: '#/properties/email' },
    { type: 'Control', scope: '#/properties/linkedin_url' },
  ],
};

export default function Home() {
  const [submitted, setSubmitted] = useState(false);
  const [formData, setFormData] = useState({});
  const [isClient, setIsClient] = useState(false);

  useEffect(() => {
    setIsClient(true);
  }, []);

  const validateForm = () => {
    const errors = {};
    const requiredFields = ['first_name', 'last_name', 'email', 'linkedin_url'];

    requiredFields.forEach((field) => {
      if (!formData[field]) {
        errors[field] = 'This field is required';
      }
    });

    return Object.keys(errors).length === 0;
  };

  const onSubmit = async () => {
    if (validateForm()) {
      try {
        await axios.post('/api/leads', formData);
        setSubmitted(true);
      } catch (error) {
        console.error('Submission failed', error);
      }
    }
  };

  if (submitted) {
    return <p>Thank you for submitting your information!</p>;
  }

  return (
    <div
      style={{
        maxWidth: '500px',
        margin: 'auto',
        padding: '20px',
        border: '1px solid #ccc',
        borderRadius: '8px',
        backgroundColor: '#f9f9f9',
      }}
    >
      {isClient && (
        <JsonForms
          schema={schema}
          uischema={uischema}
          data={formData}
          renderers={materialRenderers}
          cells={materialCells}
          onChange={({ data }) => setFormData(data)}
        />
      )}
      <Button
        onClick={onSubmit}
        variant="contained"
        color="primary"
        style={{ marginTop: '10px' }}
      >
        Submit
      </Button>
    </div>
  );
}

Google OAuth Configuration on Live Server

js setup and I used next auth(Google OAuth) before publishing it to production it Google OAuth is perfectly working on local host, however when I tried to upload it on OVH VPS it always says after clicking the login it redirect me to https://exampledomain.com/api/auth/signin/google? and display the error below

Server error There is a problem with the server configuration.

Check the server logs for more information.

the current code that I have is for login for

import Image from "next/image";
import Link from "next/link";
import { FcGoogle } from "react-icons/fc";
import "./loginform.css";
import { auth, signIn } from "@/auth";

const LoginForm = async () => {
  const session = await auth();
  return (
    <div className="login-wrapper">
      <div className="login-container">
        <Image
          src={"/images/logo.png"}
          alt="logo"
          width={300}
          height={300}
          className="logo"
        />
        <h1 className="login-title">Welcome Back</h1>
        {session?.user ? (
          <div className="logged-in-content">
            <p>
              You are already logged in as <span>{session.user.email}</span>
            </p>
            <Link href="/dashboard" className="dashboard-button">
              Go to Dashboard
            </Link>
          </div>
        ) : (
          <form
            className="social-button google-button"
            action={async () => {
              "use server";
              try {
                await signIn("google");
              } catch (error: unknown) {
                if (
                  (error as { digest?: string })?.digest?.includes(
                    "NEXT_REDIRECT"
                  )
                ) {
                  throw error;
                }
                console.error("Login error:", error);
                throw error;
              }
            }}
          >
            <FcGoogle size={24} />
            <button type="submit">Login with Google</button>
          </form>
        )}
      </div>
    </div>
  );
};

export default LoginForm;

and on the auth.ts setup I have this following codes

import NextAuth from "next-auth";
import Google from "next-auth/providers/google";

if (!process.env.AUTH_GOOGLE_ID || !process.env.AUTH_GOOGLE_SECRET) {
  throw new Error("Missing Google OAuth credentials");
}

const allowedEmails = process.env.NEXT_PUBLIC_ALLOWED_EMAILS?.split(",") || [];

export const { handlers, auth, signIn, signOut } = NextAuth({
  providers: [
    Google({
      clientId: process.env.AUTH_GOOGLE_ID,
      clientSecret: process.env.AUTH_GOOGLE_SECRET,
    }),
  ],
  callbacks: {
    async signIn({ profile }) {
      try {
        if (!profile?.email) return false;
        return allowedEmails.includes(profile.email);
      } catch (error) {
        console.error("Sign-in error:", error);
        return false;
      }
    },
  },
  secret: process.env.AUTH_SECRET,
});

the current setup of my .env.production is like this
enter image description here

Thank you so much

Refactoring the following Javascript

I have the following code, repeated 7 times in total for;
Red, Yellow, Green, Blue, Pink, Black
on the basis that repeating code is not good how can I refactor this to make it easier to read without affecting functionality?

    // Add click event listeners to red balls (1 point)
    const redBalls = document.querySelectorAll('.ball-img[src*="red"]');
    redBalls.forEach(ball => {
        ball.addEventListener('click', function() {
            const column = this.closest('.col-4');
            const isPlayerOneColumn = column.contains(document.getElementById('player-one-name'));
            
            if ((activePlayer === 'player-one' && isPlayerOneColumn) ||
                (activePlayer === 'player-two' && !isPlayerOneColumn)) {
                currentBreak += 1;
                document.getElementById('current-break').textContent = currentBreak;
            } else {
                console.log("Not your turn!");
            }
        });
    });

    // Add click event listeners to yellow balls (2 points)
    const yellowBalls = document.querySelectorAll('.ball-img[src*="yellow"]');
    yellowBalls.forEach(ball => {
        ball.addEventListener('click', function() {
            const column = this.closest('.col-4');
            const isPlayerOneColumn = column.contains(document.getElementById('player-one-name'));
            
            if ((activePlayer === 'player-one' && isPlayerOneColumn) ||
                (activePlayer === 'player-two' && !isPlayerOneColumn)) {
                currentBreak += 2;
                document.getElementById('current-break').textContent = currentBreak;
            } else {
                console.log("Not your turn!");
            }
        });
    });

New to JS and struggled to write this so far, not sure what to try

question related to use setInterval and useEffect, what’s the difference between pass function name and anonymous function?

Recently I am reading article related to useInterval, these code works fine:

import React, { useState, useEffect, useRef } from "react";
import ReactDOM from "react-dom";

function Counter() {
  const [count, setCount] = useState(0);
  const savedCallback = useRef();

  function callback() {
    setCount(count + 1);
  }

  useEffect(() => {
    savedCallback.current = () => {
      setCount(count + 1);
    };
  });

  useEffect(() => {
    let id = setInterval(()=>{savedCallback.current()}, 1000);# this line is critical
    return () => clearInterval(id);
  }, []);

  return <h1>{count}</h1>;
}

const rootElement = document.getElementById("root");
ReactDOM.render(<Counter />, rootElement);

However, after I change the critical line to

let id = setInterval(savedCallback.current, 1000);

the code won’t work. I wonder what the difference between savedCallback.current, and ()=>{savedCallback.current()} ?

isssue detecting backspace from mobile keyboards in js

So i am using a <span> with contenteditable="true". onkeydown generates new elements with the key pressed as text. I use preventDefault() to not show the pressed character in the input field. If “backspace” is pressed, the last new element ist deleted.

It works really well on desktop browsers, but it has an issue on mobile.
When testing firefox for android, if I type some letters and then press backspace, none of the events are triggered in js.
The virtual keyboard (default and swiftkey tested) somehow keep the last letters and only remove them within the keyboard – only after these are all gone the events get passed to js again.

It is not easy to describe – the scribble shows it. The problem only exists on mobile!!

Resetting the “contenteditable” attribute prevents this behaviour but it also flashes the keyboard, which is not ideal.

let editableSpan = document.querySelector('#inp');

editableSpan.onkeydown = function(e){
    console.log('key pressed', e.which, e.key);
    if(e.which === 8){
    var keyEls = document.querySelectorAll('#out .kbd');
    keyEls.length > 0 && keyEls[keyEls.length - 1].remove();
  }else if(e.key.length === 1){
    var keyEl = document.createElement('span');
    keyEl.classList.add('kbd');
    keyEl.textContent = e.key;
    document.querySelector('#out').append(keyEl);
  }
  e.preventDefault();
  
  //editableSpan.removeAttribute('contenteditable');
  //editableSpan.setAttribute('contenteditable', 'true');
}

var arr = ['input', 'keyup', 'keydown', 'keypress', 'beforeinput', 'textInput'];
arr.forEach(eventType => {
  editableSpan.addEventListener(eventType, (e) => {
      console.log(eventType, e.type, e.key || 'no key');
    });
});
#inp {
  background-color: goldenrod;
  border: solid 3px black;
}
.kbd {
  display:inline-block;
  background-color:darkgrey;
  font-size: 2em;
  padding: .5em;
  margin-right: .3em;
  margin-top: .3em;
  border-radius:.3em;
  font-style:monospace;
}
<span id="out"></span>
<span class="kbd" id="inp" contenteditable="true">&nbsp;</span>

PayPal JavaScript SDK Pay by Credit or Debit button not loading form iOS 12.5.7

Just a basic framework to test PayPal – loads 2 buttons: Pay by PayPal and Pay by Credit or Debit Card. Working fine on every device I’ve tested except iOS 12.5.7 on iPad Air (best version I can install on this device). Newer iPhones with ver. 18 work fine.

For some reason, when I click the Pay by Credit or Debit card button, it shows the circle spinner (loading the credit/debit form fields) but then fails with error in console log: Unexpected token “?” and Reference error cannot find variable Zombo.

If I click pay by PayPal, it works fine, just the Credit/Debit option fails.

Tried on Macbook Safari and it works fine. Windows various browsers work fine.

Can’t find anything on this. Any workarounds? Tried a bunch of things, nothing works.

Code for testing:

<!-- PayPal SDK with 'components' parameter to show Credit/Debit option -->
<script src='https://www.paypal.com/sdk/js?client-id=12345&components=buttons&currency=CAD'></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>



<!-- Container for PayPal button -->
<div id="paypal_container"></div>

<script type="text/javascript"> 
$(function() {
    // Define the PayPal button with integrated Credit/Debit card option
    paypal.Buttons({
        style: {
            shape: 'rect',
            color: 'gold',
            layout: 'vertical',
            label: 'pay', // This label will be shown on the button
        },
        createOrder: function (data, actions) {
            // Set up the order details here (amount, currency, etc.)
            return actions.order.create({
                intent: "CAPTURE",
                purchase_units: [{
                    amount: {
                        currency_code: "CAD",
                        value: "100.00" // Replace with your actual value
                    }
                }]
            });
        },
        onApprove: function (data, actions) {
            // Capture the payment when the user approves it
            return actions.order.capture().then(function (details) {
                alert("Payment successful! Thank you, " + details.payer.name.given_name);
            });
        },
        onError: function (err) {
            // Handle any errors during the payment process
            console.error("Payment error:", err);
            alert("There was an issue processing your payment.");
        }
    }).render('#paypal_container'); // Render the button inside the container div
});
</script>

Failing to get status of web server with fetch

I’m trying to make a personal bookmarklet that presents me the appropriate url depending on web server status. So far, I have ..

javascript:(function() {

function checkServer(url) {
  const options = { method: 'HEAD', mode: 'no-cors' };
  return fetch(url, options)
    .then(response => console.log('Check server response:', response.ok))
    .catch(error => console.error('Check server error:', error.message));
}

checkServer('https://www.reddit.com');

})();

I keep getting false returned for response.ok in the logs. Is my request being bot filtered by the websites? Or is there something else I’m not understanding? Is there a better approach?

How to stop :active css click propagation

In our application, users can select a ‘card’ by clicking on it. We use the css :active pseudo selector to present visual confirmation of their selection. This all works fine.

In case none of the options is what the user is looking for, the last card allows for the user to enter a custom value in a text box. Unfortunately, clicking inside the text box fires the parent’s :active selector, making it appear like the user has already selected an option before they have even entered their text.

Here is a minimal fiddle that shows the issue:

https://jsfiddle.net/nh3kazcu/2/

As you can see from the fiddle, we have tried both event.stopPropagation() and event.preventDefault(), with no success:

body {
  background-color:#000000;
}
.card {
  background-color: #8f97a3;
  width:200px;
  height:200px;
  margin:10px;
}
.card div, .card input {
  margin:6px;
  padding:6px;
}
.card:active {
  background-color:#b9bec5;
  margin:10px 6px 10px 14px;
}
<div class="card">
  <div>1</div>
</div>
<div class="card">
  <div>2</div>  
</div>
<div class="card">
  <input type='text' onclick='event.stopPropagation();event.preventDefault();' value='pick a number'></input>
</div>

How do we keep the card’s selection logic, and add a simple text-box to it so the user can enter a custom value?

This seems like it should be simple, but we can’t figure it out.

Replace file input image with URL image before form submission

I have a file input that accepts images:

<div class="pictures-input">
  <label for="input-pictures">
     <input id="input-pictures" type="file" accept="image/*" multiple>
     <span>Add pictures</span>
  </label>
</div>

I have several image URLs and I want to add them programmatically to this input as if they were selected by the user. How can I achieve this with JavaScript?

I want the URLs to appear as selected files in the input, just like when a user manually selects images.

I managed to select a real image through the input, and then I tried to replace its URL with one from my URL array. While the preview shows my new image correctly, when I submit the form, it still sends the original image that was selected, not the one I tried to replace it with.

How do I calculate an AWS S3 compatible SHA-256 hash from a Blob in Angular?

I am trying to upload an image from the client side (Angular app) using a presigned upload URL that is generated in the backend. When doing a PUT request to an Amazon S3 bucket using this presigned URL, a x-amz-content-sha256 signed header must be included with a valid SHA-256 value that is calculated from the image blob that will be uploaded using the presigned URL.

Currently I am calculating this SHA-256 hash using the following TypeScript code:

  private getSHA256ChecksumFromBlobAndCacheBoth(imageBlob: Blob): Promise<string> {
    return imageBlob.arrayBuffer()
      .then(arrayBuffer => crypto.subtle.digest("SHA-256", arrayBuffer))
      .then(arrayBuffer => { 
        let SHA256Checksum: string = this.convertSHA256ChecksumToHexString(arrayBuffer);
        return SHA256Checksum;
      });
  }
  
  private convertSHA256ChecksumToHexString(buffer: ArrayBuffer): string {
    return Array.from(new Uint8Array(buffer))
      .map((byte) => byte.toString(16).padStart(2, "0"))
      .join("");
  }

This produces a valid SHA-256 hash. Here’s an example of one: ce48c8f1eebbfdfd811d2e8fbb07d7a4fa9e0ab382934d2010b336e2a2b41730

Despite it being valid, it is still rejected by S3; it causes a signature mismatch error. When I remove the actual hash value and replace it with UNSIGNED-PAYLOAD the upload request is accepted.

So Amazon calculates the SHA-256 of the same blob differently than how it’s normally done.

How do I create an Amazon S3 compatible SHA-256 hash of an image blob in TypeScript/JavaScript?

Using SetTtimeout() in an ajax call, if-else statement executes both

When the following jquery ajax function is called:

let ajax_call = function (endpoint, request_parameters) {
        $.getJSON(endpoint, request_parameters)
            .done(response => {
                if(response['success']){
                    setTimeout(function(){

                        $('div#validation_result').html('<span class="validate_answer" style="color:green;"><i class="fas fa-check fa-2x"></i><span>');
                        }, 150);
                else{
                    setTimeout(function(){
                        $('div#validation_result').html('<span class="validate_answer" style="color:red;"><i class="fas fa-times fa-2x"></i><span>');
                    }, 150);
                }
            }
}

Using the browser debugger, I am going line by line and to my great surprise, the response success settimeout executes AND the else settimeout executes after that. I cannot believe my eyes, but this is actually happening. Any ideas what could cause this?