CKEditor 5 – Get X/Y coordinates of cursor

Wanted to be able to get the X and Y coordinates of the cursor (blinking pipe) in relation to the viewport.

The closest I could get to finding a solution was this link:
https://ckeditor.com/old/forums/CKEditor-3.x/Cursor-coordinates-XY-SOLVED

But it seems to be very old and obsolete solution. Couldn’t make it work.

The application I have in mind is: When the user presses a certain key, a popup will show up in the cursos position with some option for him to select.

Thnaks.

await for async function that returns a promise will wait for the promise to resolve aswell

I am writing a function that needs to return a promise to be handled. Inside the function, there is some other async functions that I need to wait before returning my promise.
After calling this function, I need to wait before continuing the code, because function3 depends on what happens inside function 2.

// version 1

function1 () {
 function2().then(selected => {
  // need to define whats happens with the promise here
 })
 function3(){}
}

async function2 () {
  await X
  await Y

  return new Promise(async (resolve, reject) => {}

}


//version 2

async function1 () {
 await function2().then(selected => {
  // need to define whats happens with the promise here
 })
 function3(){}
}

async function2 () {
  await X
  await Y

  return new Promise(async (resolve, reject) => {}

}

The problem here is that on version 1, function3 is being called before function2 has ran all its code.

Version 2 is waiting for both function2 code and the promise it returns to be fullfilled. So basically function3 is not being called.

Is there anyway I can wait for the function 2 to run but still be able to define how to handle its promise?

How to optimize a user-uploaded image before applying it as a texture in Three.js?

I’m building an online product customization tool using Three.js. The user uploads an image (like a logo or artwork), and we apply that image as a texture on a 3D object (a .glb reusable cup model).

However, when the uploaded image has a lot of colors or is large in size (e.g., 2MB, 2000x2000px), the texture application becomes slow, and the user experience degrades significantly.

I would like to optimize this process by reducing the weight of the uploaded image on the client side, before sending it to the server or applying it to the texture.

My questions:
How can I resize and compress the user-uploaded image in the browser before applying it as a Three.js texture?

Is it possible to reduce the number of colors (bit depth) or use something like pngquant or imagequant.js in the browser?

Can I convert the image to WebP using canvas or other client-side tools and still use it in a THREE.Texture?

What’s the best way to integrate image optimization with texture generation in a Three.js workflow?

react delete request not reaching spring boot api, 404 error

My react app successfully gets and posts from/to Spring Boot JPA MySql db. But delete fails with 404, meaning it can find the endpoint.

MedaverterApplication.java

@SpringBootApplication
@ComponentScan(basePackages = { "net.tekknow.medaverter.*" })
@EntityScan(basePackages = "net.tekknow.medaverter.*") 
public class MedaverterApplication {

    public static void main(String[] args) {
        SpringApplication.run(MedaverterApplication.class, args);
    }

      @Bean
      public WebMvcConfigurer corsConfigurer() {
          return new WebMvcConfigurer() {
              @Override
              public void addCorsMappings(CorsRegistry registry) {
                  registry.addMapping("/**")
                          .allowedOrigins("http://localhost:3000") 
                          .allowedMethods("GET", "POST", "PUT", "DELETE")
                          .allowedHeaders("*")
                          .allowCredentials(true);
              }
          };
      }
}

EventController.java

package net.tekknow.medaverter.controllers;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;

import java.util.List;
import net.tekknow.medaverter.models.Event;
import net.tekknow.medaverter.repository.EventRepo;

@CrossOrigin
@RestController
public class EventController {
    @Autowired
    EventRepo eventRepo;

    @GetMapping("/get-events")
    public List<Event> getEvents(int user_id) {
        List<Event> events = eventRepo.findEventsByUserId(user_id);
        return events;
    }

    @PostMapping(path = "/save-event", consumes = MediaType.APPLICATION_JSON_VALUE)
    @ResponseStatus(HttpStatus.OK)
    public ResponseEntity<Event> addEvent(@RequestBody Event event) {
        return ResponseEntity.ok().body(eventRepo.save(event));
    }

    @DeleteMapping("/delete-event/{id}")
    public ResponseEntity<String> deleteEvent(@PathVariable Integer id) {
        try {
            eventRepo.deleteById(id);
            return new ResponseEntity<>("Item deleted successfully", HttpStatus.OK);
        } catch (Exception e) {
            return new ResponseEntity<>("Error deleting item", HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }
}

Note that both GET and POST work, but not DELETE

events.tsx

const deleteEvent = async (id: GridRowId) => {
  const response = await fetch(`/delete-event?id=${id}`, {
    method: 'DELETE',
    headers: {
      'Content-Type': 'application/json' // Or the appropriate content type
    },
  })
    .then((response) => {
      if (!response.ok) {
        throw new Error('Network response was not ok');
      }
      return response.json();
    })
    .then((data) => {
      console.log('Row deleted successfully:', data);
    })
    .catch((error) => {
      console.error('Error deleting row:', error);
    });
}

I also tried:

  const response = await fetch(`http://localhost:3000/delete-event?id=${id}`, {...
  const response = await fetch(`http://localhost:8080/delete-event?id=${id}`, {...

How is it that I can get and save data, but not delete? I thought maybe the browser was blocking due to CORS, but I’ve got that covered. Can anybody see what I am doing wrong?

Just testing UI stack

I’m writing an async test in Jest for a function that fetches user data:

// userService.js
export async function getUser(id) {
  const response = await fetch(`/api/users/${id}`);
  return response.json();
}

// userService.test.js
import { getUser } from './userService';

test('getUser returns correct user name', () => {
  getUser(1).then(user => {
    expect(user.name).toBe('Alice');
  });
});

When I run this, I see:

 PASS  userService.test.js
  ✓ getUser returns correct user name (5 ms)

However, even if I change the expected name to something else (e.g. ‘Bob’), the test still passes. I expected it to fail when the assertion doesn’t match.

Why is the Query Builder in NestJS (TypeORM/Prisma) faster than Laravel 8 Query Builder?

I’m currently working on backend development using both Laravel 8 (with Eloquent and its query builder) and NestJS (with either TypeORM or Prisma). I’ve noticed that database queries in NestJS seem to execute significantly faster than in Laravel 8, even when performing similar operations and on the same database.

Here are some details:

Both applications are querying the same database on the same server.

Laravel uses Eloquent or the query builder.

NestJS uses TypeORM or Prisma (I’ve tried both).

No significant logic overhead in either framework.

My question is:
What factors might explain the performance difference between the NestJS query builder and Laravel’s query builder? Is it due to how each framework handles database connections, query compilation, or some other internal mechanism?

I’m not trying to start a framework war—just genuinely curious about the technical reasons behind the speed difference.

Thanks in advance!

Why is it easy to check .closed on manual RxJS subscriptions, but not with takeUntilDestroyed() in Angular?

I am using RxJS for subscriptions in Angular. I noticed that when I manually subscribe to an observable and store the Subscription, I can easily check if it was unsubscribed using .closed, especially in ngOnDestroy().

But when I use the newer takeUntilDestroyed() utility (from @angular/core/rxjs-interop), I don’t get a Subscription object, so I can’t check if the unsubscription actually happened. This makes it harder to confirm at runtime whether the observable was cleaned up properly.
Here’s current example of Old Subscription approach:

Manual Subscription (with .closed check):

import { Component, OnDestroy, OnInit } from '@angular/core';
import { interval, Subscription } from 'rxjs';
@Component({
  selector: 'app-manual-sub',
  template: `<p>Manual subscription</p>`
})
export class ManualSubComponent implements OnInit, OnDestroy {
  subscription!: Subscription;
ngOnInit(): void {
    this.subscription = interval(1000).subscribe(val => {
      console.log('Manual:', val);
    });
  }
ngOnDestroy(): void {
    this.subscription.unsubscribe();
    console.log('Unsubscribed?', this.subscription.closed); // Easy to check
  }
}

My Question:

Is there a way to confirm at runtime that takeUntilDestroyed() actually unsubscribed — similar to how we can check .closed on a Subscription?
Is there a recommended pattern or function to track this more explicitly when using takeUntilDestroyed() ?

Thanks in advance 🙂

Cannot get Chrome extension context menu to work

I’m trying to make a Chrome extension from selecting a text (eventually, I want to be able to add vocab into a separate website).

Obviously, I have to use the context menu API. But I can’t get it to work. Somehow clicking the context doesn’t make anything happen, not even a console.log.

This is my code:

manifest.json

{
  "name": "Hello Extensions",
  "description": "Base Level Extension",
  "version": "1.0",
  "manifest_version": 3,
  "permissions": ["contextMenus"],
  "background": {
    "service_worker": "service-worker.js"
  } 
}

service-worker.js

chrome.runtime.onInstalled.addListener(() => {
  chrome.contextMenus.create({
    id: "meaning",
    title: "meaning",
    contexts: ["selection"]
  });  
});

chrome.contextMenus.onClicked.addListener((info, tab) => {
  console.log(info);
  console.log(tab);
});

Clicking my context menu (which does show up) won’t log anything to the console! I’ve done everything I can, but can’t get it work for the bane of my life.

Would appreciate some help. Thanks!!

Cannot retrieve value of selected radio button

I used Bootstrap to create the radio buttons:

<div id="heightForm">
  <legend class="h">
    Height:
    <div class="form-check form-check-inline weightChoose commonRadio">
      <div class="form-check form-check-inline kg">
        <input class="form-check-input" type="radio" name="heightButtonS" role="radio" value="METER" id="h1"/>
        <label class="form-check-label lbl" for="h1">Meter</label>
      </div>
      <div class="form-check form-check-inline pound">
        <input class="form-check-input" type="radio" name="heightButtonS" role="radio" value="FEET" id="h2"/>
        <label class="form-check-label lbl" for="h2">Feet</label>
      </div>
    </div>
  </legend>
</div>

i wanted to console.log(heightIn);

where

var heightIn = $('input[name="heightButtonS"]:checked').val();

but it gives undefined.

i also tried:

var heightIn = $('input[name=heightButtonS]:checked').val();
var heightIn = $('input[name="heightButtonS"]:checked').value();

This does return the value when there is an attribute “checked” in one of the buttons. Even on selecting the other button it returns the value of that assigned button. I want it to retrieve value for the button which is selected.

Does this not work anymore?

a problem in regard of using api with html and javascript [closed]

I was given a project to build a site that is used for car renting. I am using frontend: html, css and js, and I am stuck.

I was given this API and I have no idea how to get the attributes, data from this API and use them in HTML. I will use an example:

This is the url to the API:
https://rentcar.stepprojects.ge/swagger/index.html

From this URL there is one GET for popular cars.
In my html I made a horizontal scrolling div for these popular cars amongst the users. I have created a single (empty) <div> in this horizontal scroll, which I want to be used as a template, and every time a new div is added, it just adds the data from the API to the template. Additionally I want to add as many divs as there are popular cars in the API response. (Even though I know that is 4 in this case, let’s consider that I do not know it.)

This is the code for horizontal scroll I have created:

ain {
  section {
    display: flex;
    margin: 2%;
  }

  .advertisment {
    justify-content: center;

    .ad {
      width: 40em;
      height: 30em;
      background-color: black;
      margin: 50px;
    }
  }

  .cars {
    flex-direction: column;
    align-items: center;

    .horizontalCars {
      flex-wrap: nowrap;
      overflow-x: auto;
      width: 90vw;
      white-space: nowrap;
      background-color: #333;

      .experimental {
        display: inline-block;
        min-width: 20vw;
        height: 20vw;
        background-color: red;
        margin: 10px;
        color: white;
        text-align: center;
        text-decoration: none;
      }

      div.scrollmenu a:hover {
        background-color: #777;
      }
    }

    .tableCars {
      width: 90vw;
      flex-wrap: wrap;
      justify-content: center;

      .experimental {
        min-width: 20vw;
        height: 20vw;
        background-color: red;
        margin: 10px;
      }
    }
  }
}
<section id="favouriteCars" class="horizontalCars">
  <div id="container" class="experimental"></div>
</section>

Thanks a lot in advance!

How to filter user input in Angular?

I want to filter user input when they type in an HTML text input.

I can do that in native HTML/JavaScript as shown in the following demo:

<form>
    <label for="tracking">Tracking Number:</label>
    <input
        type="text"
        id="tracking"
        name="tracking"
        pattern="^[A-Z]{2}d{9}[A-Z]{2}$"
        title="Format must be like AB123456789CD"
        required
        minlength="13"
        maxlength="13"
    />
</form>

<script>
    const input = document.getElementById('tracking');

    input.addEventListener('input', () => {
        console.log('input fired');

        // Remove non-alphanumeric chars and force uppercase
        input.value = input.value.replace(/[^a-zA-Z0-9]/g, '').toUpperCase();
    });
</script>

filtering user input with HTML/JS

In the image above, I’m typing a, b, +, – (filtering works like I want).
StackBlitz demo: Filter user input (native)

Now, I’ve done the same thing using Angular (with a template-driven form) as shown in the following demo:

@Component({
  selector: 'app-root',
  template: `
    <form>
      <label for="tracking">Tracking Number:</label>
      <input
        type="text"
        id="tracking"
        name="tracking"
        pattern="^[A-Z]{2}d{9}[A-Z]{2}$"
        title="Format must be like AB123456789CD"
        required
        minlength="13"
        maxlength="13"
        [ngModel]="trackingNumber"
        (ngModelChange)="onTrackingChange($event)"
      />
    </form>
  `,
  imports: [FormsModule],
})
export class App {
  trackingNumber = '';

  onTrackingChange(value: string) {
    console.log('input fired');

    // Remove non-alphanumeric characters and force uppercase
    this.trackingNumber = value.replace(/[^a-zA-Z0-9]/g, '').toUpperCase();
  }
}

filtering user input with Angular

In the image above, I’m typing a, b, +, – (filtering does NOT work like I want). StackBlitz demo: Filter user input (Angular)

As far as my Angular knowledge goes, this happens when the current ngModel value is the same as the new/filtered value, thus Angular does not trigger a change on the HTML text input.

How can I overcome this behavior in Angular?

Can I force Angular to trigger a change?

Is there a way to convert an input value to bold in HTML?

I have the below input value which returns an email address which I’m displaying in a pop up submission box, is there a way to make the input value, ${emailInput.value}, appear bold on my webpage?

function showPopUp() {
  submitBox.classList.toggle("show");
  let successMessage = `A confirmation email has been sent to ${emailInput.value}. Please open it and click the button inside to confirm your subscription`;
  document.querySelector(".confirmation-text").innerText = successMessage;
}

I have tried to use the .bold() method but that isn’t working for me – I’ve read it’s been discontinued for use?

React hook form field resets after submission

The component uses react-hook-form for a two-step form (email then password). After submitting the email address in the first step, the email value appears to be reset to undefined. This prevents the submission of the final form since the email is no longer available.

export default function App() {
  const [inProgress, setInProgress] = useState(false);
  const handleSubmit = (email: string, password: string) => {
    console.log("SimplifiedSignInForTesting submitted:", { email, password });
    setInProgress(true);
    setTimeout(() => {
      setInProgress(false);
    }, 1500);
  };

  return <SignIn submit={handleSubmit} inProgress={inProgress} />;
}

interface SignInProps {
  submit: (email: string, password: string) => void;
  inProgress: boolean;
}

export const SignIn = ({ submit, inProgress }: SignInProps) => {
  const [isEmailSubmitted, setIsEmailSubmitted] = useState(false);

  const schema = z.object({
    email: z.string(),
    password: z.string(),
  });

  type SignInFormData = z.infer<typeof schema>;

  const {
    register,
    handleSubmit,
    setFocus,
    watch,
    formState: { errors, isSubmitting },
  } = useForm<SignInFormData>({
    resolver: zodResolver(schema),
    shouldUnregister: false,
    defaultValues: {
      email: "",
      password: "",
    },
  });

  const onSubmitInternal = useCallback(
    async (data: SignInFormData) => {
      const { email, password } = data;
      console.log(email, password);

      if (!isEmailSubmitted) {
        setIsEmailSubmitted(true);
        setTimeout(() => setFocus("password"), 0);
        return;
      }

      submit(email, password);
    },
    [isEmailSubmitted, setIsEmailSubmitted, submit, setFocus]
  );

  const isLoading = inProgress || isSubmitting;
  const emailErrorMessage = errors.email?.message;

  const email = watch("email");

  React.useEffect(() => {
    console.log(email);
  }, [email]);

  return (
    <form onSubmit={handleSubmit(onSubmitInternal)} noValidate>
      <input
        tabIndex={0}
        autoFocus
        aria-label="email"
        type="email"
        disabled={isLoading || isEmailSubmitted}
        {...register("email")}
      />
      {emailErrorMessage && <span>{emailErrorMessage}</span>}
      <input
        aria-label="password"
        type="password"
        autoComplete="current-password"
        style={{ display: isEmailSubmitted ? "initial" : "none" }}
        disabled={isLoading}
        tabIndex={isEmailSubmitted ? 0 : -1}
        {...register("password")}
      />
      <input
        tabIndex={0}
        type="submit"
        aria-label={isEmailSubmitted ? "login" : "continue"}
      />
    </form>
  );
};

https://codesandbox.io/p/sandbox/affectionate-tu-6fk26l

The form submission should have both the email and password