TS error when building Svelte 5 component that renders either anchor or button element based on presence of href prop

I’m trying to create a Svelte 5 component that renders either a button or anchor element based on the presence of a href prop, however I’m running into a TS error.

Button.svelte

<script lang="ts">
  import type { HTMLButtonAttributes, HTMLAnchorAttributes } from 'svelte/elements';

  type Props = HTMLAnchorAttributes | HTMLButtonAttributes;
  
  const {
    href,
    children,
    ...restProps
  }: Props = $props();
</script>

{#if href}
  <a {href} {...restProps}>
    {@render children()}
  </a>
{:else}
  <button {...restProps}>
    {@render children()}
  </button>
{/if}

The above produces two errors:

  1. When destructuring props: href does not exist on Props type.
  2. When spreading restProps: Argument of type … is not assignable to parameter of type ‘HTMLProps<“a”, HTMLAtributes>’

I thought checking for the existence of href would act as a type guard allowing me to spread the correct props on the correct element.

Any insights appreciated. Thanks in advance.

Swapping two children of a parent node in JS

I have a parent div of nine divs, that each has a different background image. My task is to, whenever, I click on any of the divs except the targetDiv, the div gets swapped by the targetDiv in the DOM. So, here is the code:

function swap(e){
    let parent=document.getElementsByClassName('container')[0];
    swapDivsByBackground(parent,e.style.background);
}

function swapDivsByBackground(parent, bgImage1) {

    const children = Array.from(parent.children);
    const moveDiv = children.find(div => div.style.background.includes(bgImage1));
    if(!moveDiv) 
        return;

    const moveIndex = children.indexOf(moveDiv);
    const targetIndex = children.indexOf(targetDiv);

    parent.removeChild(moveDiv);
    parent.removeChild(targetDiv);
    
try{
    parent.insertBefore(moveDiv, children[moveIndex+1] || null);
}
catch(e){
    console.log(moveIndex+1);
    console.log(children[moveIndex+1]);
    console.log(e.message);
}
try{
    parent.insertBefore(targetDiv, children[targetIndex+1] || null);
}
catch(e){
    console.log(targetIndex+1);
    console.log(children[targetIndex+1]);
    console.log(e.message);
}
}

I am seriously facing some issues here. Sometimes, there are no swaps, and sometimes, I even get a error that says:

Failed to execute ‘insertBefore’ on ‘Node’: The node before which the new node is to be inserted is not a child of this node.

But alongside, I also receive the console messages from console.log(moveIndex+1); and console.log(children[moveIndex+1]);, that shows a valid div reference. But, if the node is not a child, then why are these messages shown? They should have shown undefined.

How to drag and drop a div inside another div

I have the following HTML code, which creates a div called “paddle” inside a div called “board”. I’m preparing a small game of Pong and the “paddle” div represents the paddle that will receive the ball.

<!DOCTYPE html>
<html lang="pt-br">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Pong Game</title>
    <link rel="stylesheet" href="estilo.css">
    <script src="script.js"></script>
</head>
<body>
    <div id="board">
        <div id="paddle"></div>
    </div>
</body>
</html>
#board {
    margin: 0 auto;
    background-color: black;
    border-top: 5px solid skyblue;
    border-bottom: 5px solid skyblue;
    width: 500px;
    height: 500px;
    position: relative;
}

#paddle {
    background-color: skyblue;
    width: 10px;
    height: 50px;
    position: absolute;
    top: 250px;
    left: 480px;
    cursor: pointer;
}

I need you to help me with a JavaScript code that Drags and Drops the “paddle” div within the limits of the “board” div and only vertically

Sometimes CSS and JS not loading with error 500 [closed]

I am using ASP.Net Core 8 WebApp. when you open the website, sometimes css and js files not loading and when you see console, all of them has error 500. after you reload the page, all of them load correctly.

what is the problem???

by the way it’s a simple company website and it doesn’t have a lot of c# code for rendering. most of it is static html. it is hosted on shared hosting (Plesk) and sql server 2022. it is not sql problem because this problem existed before any database creation. I searched for this problem and found that maybe this is a server problem or server is on high load! but I don’t think so. because as I mentioned earlier, It doesn’t have heavy process. just a simple webpage. I can see this problem even on pages that has no code and just return View()

by the way I should mention that all the HTML codes loads and just css and js files not loading correctly and with a reload, all loads correctly

middlewares:

app.UseWebOptimizer();
app.UseHttpsRedirection();
app.UseStaticFiles(new StaticFileOptions()
{
    OnPrepareResponse = ctx =>
        {
        var path = ctx.File.PhysicalPath ?? "";

        if (path.EndsWith(".woff2") || path.EndsWith(".webp") || path.EndsWith(".png") || path.EndsWith(".jpeg") || path.EndsWith(".jpg"))
        {
        ctx.Context.Response.Headers.Append("Cache-Control", "max-age=31536000,immutable");
        }
    }
});
app.UseResponseCompression();

you can see it on this url: bineshdev.com

this is what it looks like:

enter image description here

Uncaught (in promise) TypeError: google.maps.importLibrary is not a function – Map not loading

Using google maps API, map seems to load 20% of the time. Currently getting the above error. The following is my php:

<script>
        async function initMap() {
            const { Map, InfoWindow } = await google.maps.importLibrary("maps");
            const { AdvancedMarkerElement, PinElement } = await google.maps.importLibrary(
                "marker",
            );
        }
        document.addEventListener('DOMContentLoaded', (event) => {
                initMap();
        });
</script>

<div class="search">
        <input id="autocomplete" placeholder="Enter address, city, or zip/postal code" type="text">
</div>
<div id="loadMap" style="height: 600px; width: 100%;"></div>

<script src="https://maps.google.com/maps/api/js?v=weekly&key=KEY&libraries=places&loading=async&solution_channel=GMP_guides_locatorplus_v2_a"></script>

Expecting the map to load 100% of the time.

CSS: How to toggle the borders of a specific table column without twitching

function toggleBorders() {
  table.tHead.firstElementChild.children[1].classList.toggle('thick-border');
  Array.from(table.tBodies[0].children).forEach(row => row.children[1].classList.toggle('thick-border'));
}
table {
  border-collapse: collapse;
}

th.thick-border,
td.thick-border {
  border: 3px solid coral;
  border-top: none;
  border-bottom: none;
}
<table id="table">
  <thead>
    <tr>
      <th>h1</th> <th>h2</th> <th>h3</th> <th>h4</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>11</td> <td>12</td> <td>13</td> <td>14</td>
    </tr>
    <tr>
      <td>21</td> <td>22</td> <td>23</td> <td>24</td>
    </tr>
  </tbody>
</table>
<br>
<button id="btn" onclick="toggleBorders()">Click Me!</button>

Is there any way to toggle the column’s borders without twitching?
And without thickening initial border width of other columns?

Maybe with shadows or gradients or somehow else

once audio start playing in brower on pausing it is not getting paused

function stopRingtone() {
    if (!isRingtonePlaying) return;
    if (ringtoneTimeout) {
        clearTimeout(ringtoneTimeout);
        ringtoneTimeout = null;
    }
    if (sourceNode) {
        sourceNode.stop();
        sourceNode.disconnect();
        sourceNode = null;
    }

    if (gainNode) {
        gainNode.disconnect();
        gainNode = null;
    }

    if (audioContext) {
        audioContext.close().then(() => {
            audioContext = null;
            audioBuffer = null;
            console.log("AudioContext closed and reset.");
        }).catch((err) => {
            console.error("Error closing AudioContext:", err);
        });
    }
}

function playAudioLoop() {
 
    sourceNode = audioContext.createBufferSource();
    sourceNode.buffer = audioBuffer;
    sourceNode.connect(gainNode);
    sourceNode.start(0);

    const loopDuration = audioBuffer.duration * 1000; // Convert to milliseconds
    const targetDuration = 12000; // 12 seconds in milliseconds

    ringtoneTimeout = setTimeout(() => {
        if (isRingtonePlaying) {
            const elapsedTime = audioContext.currentTime * 1000; 
            if (elapsedTime < targetDuration) {
                playAudioLoop(); // Continue looping
            } else {
                stopRingtone(); // Stop after target duration
            }
        }
    }, Math.min(loopDuration, targetDuration));
}

Pause the audio when stopRingtone() function is called.on implementing Custom ringtone for call, on accepting or other call events audio should be stopped , here it is not stopping , it continuously keeps on playing

Update order of relation items in Typeorm

is there a way to update order of related items in Typeorm?

For example:

First I’m saving item:

const item = new Item();
item.name = 'item';
item.relations = [related1,related2,related3];

this.dataSource.manager.save(item);

Later I want to update item:

const item = await this.dataSource.getRepository(Item)
            .findOne({
                where: { id: id  }
            });
item.name = 'updatedItem';
item.relations = [related3,related2,related1];

this.dataSource.manager.save(item);

Unfortunatelly, all changes are saved but relation order is still the same.

What am I doing wrong?

How to run a function after a specifik component is rendered in React?

I’m working on my navbar. I have a header with a component within called HeaderSearch. What I want is to run a function each time the user clicks outside of the HeaderSearch. And then add an animation to close it.

Here is my HeaderSearch:

//searchBar component
  const HeaderSearch = () => {
    if (location.pathname !== "/") {
      return (
        <div id="search-header" className="search-header">
          <FontAwesomeIcon
            className="search-icon"
            id="search-icon"
            icon={faSearch}
            // onClick={() => searchReqClientSide()}
            onClick={() => searchOpen()}
          />
          <input
            id="search-input"
            type="text"
            value={search}
            onKeyDown={(e) => checkInput(e)}
          />
        </div>
      );
    } else {
      return null;
    }
  };

Here is my onClickOutside function which is a modification of this function

// detect click and then determine whether isclicked inside searchInput or outside
  const onClickOutside = () => {
    console.log("first");
    const searchInput = document.getElementById("search-input");
    if (searchInput.classList.contains("active")) {
      console.log("second,  contains active true");
      document.addEventListener("click", (e) => {
        console.log("third,  beginning click");
        if (!searchInput.contains(e.target)) {
          console.log("fourth, searchInput does not contain clicked element");
          searchInput.classList.remove("active");
          setTimeout(() => {
            searchInput.style.animation = "searchInputClose 0.5s ease";
            console.log("fifth, during timeout");
          }, 500);
        }
      });
    }
    console.log("sixth, after everything");

  };

And here is my searchOpen function :

const searchOpen = () => {
    const searchInput = document.getElementById("search-input");
    const searchHeader = document.getElementById("search-header");
    const searchIcon = document.getElementById("search-icon");
    if (!searchInput.classList.contains("active")) {
      searchInput.style.animation = "searchInputOpen 0.5s ease";
      setTimeout(() => {
        searchInput.classList.add("active");
      }, 500);
    }
  };

Where do I excecute the onClickOutside function. I tried putting it in useEffect(() => { onClickOutside })
and useEffect(() => { onClickOutside },[])

Thank you

How to run a function after a specifik component is rendered in React? [duplicate]

I’m working on my navbar. I have a header with a component within called HeaderSearch. What I want is to run a function each time the user clicks outside of the HeaderSearch. And then add an animation to close it.

Here is my HeaderSearch:

//searchBar component
  const HeaderSearch = () => {
    if (location.pathname !== "/") {
      return (
        <div id="search-header" className="search-header">
          <FontAwesomeIcon
            className="search-icon"
            id="search-icon"
            icon={faSearch}
            // onClick={() => searchReqClientSide()}
            onClick={() => searchOpen()}
          />
          <input
            id="search-input"
            type="text"
            value={search}
            onKeyDown={(e) => checkInput(e)}
          />
        </div>
      );
    } else {
      return null;
    }
  };

Here is my onClickOutside function which is a modification of this function

// detect click and then determine whether isclicked inside searchInput or outside
  const onClickOutside = () => {
    console.log("first");
    const searchInput = document.getElementById("search-input");
    if (searchInput.classList.contains("active")) {
      console.log("second,  contains active true");
      document.addEventListener("click", (e) => {
        console.log("third,  beginning click");
        if (!searchInput.contains(e.target)) {
          console.log("fourth, searchInput does not contain clicked element");
          searchInput.classList.remove("active");
          setTimeout(() => {
            searchInput.style.animation = "searchInputClose 0.5s ease";
            console.log("fifth, during timeout");
          }, 500);
        }
      });
    }
    console.log("sixth, after everything");

  };

And here is my searchOpen function :

const searchOpen = () => {
    const searchInput = document.getElementById("search-input");
    const searchHeader = document.getElementById("search-header");
    const searchIcon = document.getElementById("search-icon");
    if (!searchInput.classList.contains("active")) {
      searchInput.style.animation = "searchInputOpen 0.5s ease";
      setTimeout(() => {
        searchInput.classList.add("active");
      }, 500);
    }
  };

Where do I excecute the onClickOutside function. I tried putting it in useEffect(() => { onClickOutside })
and useEffect(() => { onClickOutside },[])

Thank you

Resize Leaflet map when its container is resized (dash plotly)

I’m having some issues with dash-leaflet; in particular with it’s width when the parent container is resized. I’m using dash-resizable-panels to resize some divs.

Here’s a MRE:

# pip install dash dash-leaflet dash-resizable-panels
import dash
import dash_leaflet as dl
from dash import html
from dash_resizable_panels import PanelGroup, Panel, PanelResizeHandle

handle = {"height": "100%", "width": "3px", "backgroundColor": "#51ada6"}
layout = html.Div([
    PanelGroup(id="panel-group", 
               children=[
                    Panel(id="panel-1",children=[html.Div([html.P("Dummy component")])]),
                    PanelResizeHandle(html.Div(style=handle)),
                    Panel(id="panel-2",
                          children=[
                            dl.Map(center=[45.81, 15.98], zoom=12, children=[
                                dl.TileLayer(),
                                dl.FeatureGroup([dl.EditControl()]),
                            ], style={'height': '100%', 'width': '100%'})]
                    )], direction="horizontal",),
], style={"height": "100vh"})

app = dash.Dash(__name__)
app.layout = layout
if __name__ == "__main__":
    app.run_server()

The initial layout is fine:

1

However, when I resize the map container I’m left with an un-rendered part of the map (gray part on the right) which looks like this:

2

Is there any way (be it through python or js) to resize or rerender the leaflet map when the container is resized so that the map fills (renders) the full width of its container?

in node js body.id doesnt working on server [duplicate]

When I access the server with postman, I get an error like a id not found or some thing like this.

Here is my code on get-routs.js :

<div class="main">
        <ul>${tasks
            .map((item) => {
                return `            <li data-id="${item.Id}">
                <span>
                    <lable>${item.Title}</lable>
                    <span class="${item.complited ? "com" : "uncom"}">${
                    item.complited ? "complited" : "in progress"
                }</span>
                    <button class="toggle-btn">toggle</button>
                    <button class="edit-btn" >edit</button>
                    <button class="delete-btn">delete</button>
                </span>

            </li>`;
            })
            .join("")}
        </ul>  

and here its post-route.js :

router.post("/toggle-task", (req, res) => {
    if (req.body.Id) {
        const task = Task.getTaskById(req.body.Id);
        console.log(req.body.Id);
        if (task) {
            task.complited = !task.complited;
            task.save();
            res.send("1");
        } else {
            res.status(404).send("<h1> task not foundd</h1>");
        }
    } else {
        res.status(400).send("error");
    }
});

export default router;

Despite in json file id number 2 exists post man gives error or doesn’t work

and here is my database :

[
    {
        "id": 1,
        "title": "Learn js",
        "complited": false
    },
    {
        "id": 2,
        "title": "Nodejs",
        "complited": false
    },
    {
        "id": 3,
        "title": "SQl",
        "complited": true
    }
]

Why onmessage never triggers in my BroadcastChannel?

I’m trying to use BroadcastChannel API but it seems that onmessage event is never triggered (or its handler is not working correctly).

const channel = new BroadcastChannel('foobar')

if (channel) {
  channel.onmessage = onMessage
}

export async function onMessage(event: MessageEvent) {
  alert('onMessage') // never triggers
}

export function post(message: Message) {
  alert('post') // works until this point
  channel?.postMessage(message)
}

In other file:

import * as BroadcastChannel from '@/utils/broadcastChannel/core'

BroadcastChannel.post('test')

Am I doing something incorrectly? Am I missing something?

Sorting an object by more than one value [duplicate]

I have a JSON file, that want to interrogate and return values.

On load the HTML page is populated with all the names.

persons = [
   {nationality: "GB",  code: 1004, initial: "J", surname: "Smith"},
   {nationality: "DEN", code: 1002, initial: "J", surname: "Smith"},
   {nationality: "GB",  code: 1003, initial: "A", surname: "Jones"},
   {nationality:" BEL", code: 1000, initial: "C", surname: "Down"}
];
    

This is how I have set it out so far:

As the user types in a surname in the Input box on each keyup it would query the filter the results from the data-attributes in the following way.

  1. surname > 2. initial > 3. nationality > 4. code.

So if a user starts to type in “Smith” the following result would appear in this order:

DEN. 1002, J. Smith. – would come first as the country name D is before E;
GB. 1004, J. Smith

The hierarchy of the filter would be:

Nationality (alphabetical order) > Surname (alphabetical Order) > Initial (alphabetical Order) > Code (numerical order).

I have seen a number of ways online to do this when wishing to filter and return the result on one object key but not on multiple ones.

This is something similar :
text.

Unable to group parts of the regex together to make the intended operator precedence explicit

The current regex /^(W)|([^a-zA-Z0-9_.]+)|(W)$/g is causing issues in SonarQube, and I need to group it properly. However, after grouping, it’s not working as expected.

The regex should meet the following conditions:

  1. Ensure there is a dot(s) at the start, end, or both ends of the string.
  2. In between, there can be anything except a-z, A-Z, 0-9, underscore, and dot (dots should not appear in the middle).

I tried this /^(.)|([^a-zA-Z0-9_.]+)|(.*.$)/g but i think it will again create an issue in SonarCube