How to save a dark mode on local storage?

I made a button for dark mode, but when I leave the page, it goes back to light mode. How can I save the user’s choice so that when they go to another page they can continue in the mode they chose?

Js:

let trilho = document.getElementById('trilho')
let body = document.querySelector('body')

trilho.addEventListener('click', ()=>{
    trilho.classList.toggle('dark')
    body.classList.toggle('dark')

})

Css:

*{
    margin: 0;
    padding: 0;
    font-family: 'Poppins', sans-serif;
    box-sizing: border-box;
}

body {
    height: 100px;
    width: 100%;
    background-color: #fafafa;
}

/* DARK MODE */
.trilho {
    width: 70px;
    height: 30px;
    background-color: #6e6d6d;
    border-radius: 70px;
    position: relative;
    cursor: pointer;
}

.trilho .indicador {
    width: 30px;
    height: 30px;
    background-color: #000;
    border-radius: 50%;
    transform: scale(.8);
    position: absolute;
    left: 0;
    transition: .5s;
}

.trilho.dark {
    background-color: #c3c3c3;
}

.trilho.dark .indicador {
    left: 38px;
    background-color: #fff;
}

body.dark .container {
    background-color: #000;
}

body.dark footer {
    background-color: #000;
}

body.dark header {
    background-color: #000;
}

body.dark h1 {
    color: #fff;
}

body.dark a {
    color: #fff;
}

body.dark form{
    box-shadow: none;
}

body.dark .rodape{
    color: #fff;
}

HTML:


    <!DOCTYPE html>
    <html lang="en">
    
    <head>
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Website</title>
    
        <link rel="stylesheet" type="text/css" href="css/style.css">
        <script src="darkmode.js" async></script>
    
    </head>
    
    <body>
    
        <header>     
            <nav>        
             <ul class="nav-links">
                 <li><a href="/">link</a></li>
                 <li><a href="/">link</a></li>
                 <li><a href="#">link</a></li>
            </ul>    
    
    
          
              <div class="menu-hamb-button hide-on-desktop">
                <div class="btn-line"></div>
                <div class="btn-line"></div>
                <div class="btn-line"></div>
            </div>
           
            </nav>   
    
            <div class="trilho" id="trilho">
                <div class="indicador"></div>
            </div>
     
        </header>
    
        <div class="container">
             <h1>Website</h1>
        </div>
        <footer>
    
        <span class="rodape">Website</span>      
        </footer>
    
    </body>
    </html>

I tried some javascript commands for local storage, but they didn’t work in my html/css, maybe because the way I made my dark mode is different, I don’t know.

Firestore Query Issue: Need Help Fetching Random Documents

I’m currently facing an issue with a Firestore query that requires a composite index, but I’m running into some limitations. Here’s the problem:

The Query: I’m trying to fetch questions from Firestore using the following query:

const questionsQuery = query( questionsRef, where("isVerified", "==", true), where("difficulty", "==", difficultyNumber), where("subCategory.en", "in", selectedChips), where("random", "<=", randomThreshold) );
The Error: When I run this query, I get an error stating that an index is required. I created a composite index with the following fields:

isVerified (Ascending)
difficulty (Ascending)
subCategory.en (Ascending)
random (Ascending)
However, the query only works if I comment out the random condition. It seems that Firestore has limitations on combining the in operator with inequality filters.

What I’ve Tried:

Reordering the query by moving the in condition to the end.
Simplifying the query by removing other conditions.
Splitting the query into two separate steps to fetch data and filter random values in memory.
Using orderBy with endAt for the random field.
Despite these efforts, I’m still encountering issues.

Now, when I successfully run the query without the random condition, I get an array of documents. What I want to achieve is to fetch a random document from the results.

Does anyone have insights or methods to get a random document from an array of fetched documents?

Firestore query successfully without encountering an index error. Specifically, I hoped to fetch a set of questions that meet the specified criteria and ultimately retrieve a random document from that set of results.

How to get a simple map using Leaflet which has only standard country/state borders and names in English (and no topography other than land/water)?

I have a Leaflet map which is giving me this:

enter image description here

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>Leaflet Map with GeoJSON Layer Control</title>
    <link
      rel="stylesheet"
      href="https://unpkg.com/[email protected]/dist/leaflet.css"
    />
    <style>
      #map {
        height: 100vh;
        width: 100%;
      }
    </style>
  </head>

  <body>
    <div id="map"></div>

    <!-- Leaflet Library -->
    <script src="https://unpkg.com/[email protected]/dist/leaflet.js"></script>
    <!-- jQuery for fetching GeoJSON files -->
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

    <script>
      // Initialize the map
      const map = L.map("map").setView([0, 0], 1); // Adjust coordinates and zoom level as needed

      // Add a base map layer
      const baseLayer = L.tileLayer(
        "https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png",
        {
          maxZoom: 19,
          attribution: "© OpenStreetMap",
        }
      ).addTo(map);
    </script>
  </body>
</html>

How do I:

  • remove all roads
  • make sure all labels are in English (not Arabic like seen in this snapshot, and not other languages)
  • only label and draw boundaries for countries (and for USA, the states)
  • show water and land
  • don’t show topography information like trees/mountains/etc..

Basically, a minimal map with minimal country/state boundaries and labels, that’s it (and remove all topography information except what is water and what is land).

How can I accomplish that with Leaflet?

IndexedDB: ConstraintError: Unable to add key to index ‘[index_name]’: at least one key does not satisfy the uniqueness requirements

I’m getting this error while trying to update an existing record’s “title” field, using the put() method inside a transaction. I have one field, named “hotkey”, that has is an index with unique: true constraint.

Below is the pertinent code:

request3.onupgradeneeded = (event) => {
            console.log('INSIDE onupgradeneeded for hotkeys', event);
            handles["db3"] = event.target.result;
            // Create an objectStore to hold information about our hotkeys. 
            const hotkeyStore = handles["db3"].createObjectStore(dbName3, {autoIncrement: true});
            // Create an index to search hotkeys by letter. No duplicates
            hotkeyStore.createIndex("hotkey", "hotkey", { unique: true });
            hotkeyStore.createIndex("sort", "sort", { unique: false });
        };
    async function updateRecord(dbName, payload) {
        return new Promise(async (resolve, reject) => {

            setTable(dbName);            
            // open a read/write db transaction, ready for adding the data
            const transaction = handles[activeDB].transaction([dbName], "readwrite");
            // create an object store on the transaction
            const objectStore = transaction.objectStore(dbName);
            console.log(objectStore.keyPath);
            const keyToUse = objectStore.keyPath !== null ? objectStore.keyPath : 'key';
            console.log(payload);           
            for(let record of payload) {
                console.log("WORKING ON: ", record);
                if (!record.hasOwnProperty(keyToUse)) {
                    console.log('keypath for record not present in record, canceling update', record);
                    resolve(false);
                }
                var id = record[keyToUse];
                if (keyToUse == 'key') id = parseInt(id);
                console.log('Searching for record with keyPath ', id);
                const getRequest = objectStore.get(id);

                getRequest.onsuccess = function () {
                   var obj = getRequest.result;
                   if(!obj) {
                     console.log('no matching object for id, canceling update', id);
                     resolve(false);
                     return;
                   }              
                   console.log('loaded object to modify', obj);              
                   // make some changes to the properties of the object loaded 
                   // in memory
                   Object.keys(record).forEach(key => {
                    if (key !== keyToUse && record[key] !== obj[key]) {
                        console.log('UPDATE TO ' + key);
                        const value = record[key];                        
                        obj[key] = value;    
                    }
                   });                   
                   
                   // now store the new object in place of the old object
                   console.log('storing new object in place of old', obj);
                   objectStore.put(obj);
                };                
            }
            transaction.done;

            transaction.oncomplete = function () {
                console.log("ALL PUT TRANSACTIONS COMPLETE.");
                resolve(true);
            }

            transaction.onerror = function (event) {
                console.log("PROBLEM UPDATING RECORDS.", event.target.error);
                resolve(false);
            }
        });
    }

Here is the console log output:

null
DBManager.js:164 [{…}]0: {title: 'Not Qualified', description: 'Description', hotkey: 'x', sort: '1', key: '2'}length: 1[[Prototype]]: Array(0)
DBManager.js:166 WORKING ON:  {title: 'Not Qualified', description: 'Description', hotkey: 'x', sort: '1', key: '2'}
DBManager.js:173 Searching for record with keyPath  2
DBManager.js:183 loaded object to modify {title: 'N/A', description: 'Description', hotkey: 'x', sort: '1'}
DBManager.js:188 UPDATE TO title
DBManager.js:195 storing new object in place of old {title: 'Not Qualified', description: 'Description', hotkey: 'x', sort: '1'}
DBManager.js:207 PROBLEM UPDATING RECORDS. ConstraintError: Unable to add key to index 'hotkey': at least one key does not satisfy the uniqueness requirements.
configuration.js:252 false
DBManager.js:314 FAILED TO OPEN DB.

Can someone assist with the right way to update a record that has a unique index in IndexedDB?

How to set the color of text entered in a FormKit input in Vue.js using Tailwind CSS?

I’m working on a Vue.js project where I’m using FormKit to manage forms and Tailwind CSS for styling. However, I am facing an issue with the color of text entered into an input. The text I enter in the field appears in the same color as the placeholder, which is a light tone, while I would like the text entered to be darker.

Here is a snippet of code where I am configuring my input:

<script setup lang="ts">
import LogoAgilis from '@icons/LogoAgilis.vue'
import { reactive } from 'vue'
import router from '~/router'
import { useAuthStore } from '~/stores/auth'

const authStore = useAuthStore()

const credentials = reactive({
  email: '',
  password: '',
})

const { execute: login, isFetching: isLoadingLogin } = authStore.login(credentials)

function handleSubmit() {
  login()
    .then(() => {
      router.push('/organizations')
    })
}
</script>

<template>
  <div class="bg-white p-8 shadow rounded-lg w-80">
    <form
      class="space-y-4"
      @submit.prevent="handleSubmit"
    >
      <div class="flex justify-center items-center gap-1">
        <LogoAgilis
          :size="48"
          fill="#8d00ec"
        />
      </div>

      <div>
        <label
          for="email"
          class="block text-sm font-medium leading-6 text-neutral-800"
        >
          Email
        </label>
        <div class="mt-2">
          <InputEmail
            v-model="credentials.email"
            name="email"
            validation="required"
            placeholder="[email protected]"
            class="block w-full rounded-md indent-2 border-0 py-1.5 text-neutral-800 shadow-sm ring-1 ring-inset ring-neutral-300 placeholder:text-neutral-400 focus:outline-2 focus:outline-inset focus:outline-electric-violet-600 sm:text-sm sm:leading-6"
            :inputProps="{ class: 'text-neutral-900' }"
          />
        </div>
      </div>

      <div>
        <label
          for="password"
          class="block text-sm font-medium leading-6 text-neutral-800"
        >
          Senha
        </label>
        <div class="mt-2">
          <InputPassword
            v-model="credentials.password"
            name="password"
            validation="required"
            class="block w-full rounded-md indent-2 border-0 py-1.5 text-neutral-800 shadow-sm ring-1 ring-inset ring-neutral-300 placeholder:text-neutral-400 focus:outline-2 focus:outline-inset focus:outline-electric-violet-600 sm:text-sm sm:leading-6"
          />
        </div>
        <RouterLink
          to="/recover"
          class="font-medium text-sm text-electric-violet-600 hover:text-electric-violet-500"
        >
          Esqueceu sua senha?
        </RouterLink>
      </div>

      <div>
        <button
          :disabled="isLoadingLogin"
          type="submit"
          class="flex w-full justify-center rounded-md bg-electric-violet-500 px-3 py-1.5 text-sm font-medium leading-6 text-white shadow-sm hover:bg-electric-violet-600 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-electric-violet-600"
        >
          Entrar
        </button>
      </div>
    </form>

    <p class="mt-6 text-center text-sm text-neutral-600 font-medium">
      Usuário novo?
      <RouterLink
        to="/register"
        class="font-semibold mx-1 leading-6 text-electric-violet-600 hover:text-electric-violet-500"
      >
        Cadastre-se
      </RouterLink>
    </p>
  </div>
</template>

Currently, I am using the following configurations for FormKit:

import { pt } from '@formkit/i18n';
import { defaultConfig } from '@formkit/vue';
import { rootClasses } from './formkit.theme';

export default defaultConfig({
  locales: { pt },
  locale: 'pt',
  config: {
    rootClasses,
  },
});

What I’ve already tried:

  1. Add different color classes to the input, like text-neutral-900, but this had no effect.
  2. Inspecting the element in the browser to check which styles are being applied, but I couldn’t find the reason why the color of the text I typed is the same as the placeholder.

How can I ensure that the color of the text entered into the FormKit input is different from the placeholder color? Is there a way to set this color correctly using Tailwind CSS in conjunction with FormKit? Any suggestions on how to customize the styles of FormKit inputs?

Thanks in advance for any help

How to take a screenshot of a zoomed in map (of the whole world) in Leaflet?

I have a leaflet map which contains 500MB+ of geojson data (all the earth’s biomes, and mountain ranges).

enter image description here

How can I take a screenshot (or print) the map zoomed as much as pressing the + button on Leaflet’s UI 3 times (which is about zoomed in as much as this second image)?

enter image description here

Can I use puppeteer to somehow take a screenshot of the whole world at 3x zoom? The div the map is contained in is one size (say window viewport size), but with 3x zoom, it seems you need to pan and then take screenshots of sections, then stitch them together, which would be tedious. Is there a way to somehow perhaps make the div that contains the map at 3x, big enough to show the whole world at 3x? Then I could just take a screenshot of the whole div. Something like that…

How can I take a screenshot of a map zoomed in as such?

The goal is to give this to a map illustrator to draw the whole world at 3x detail (using fantasy map style designs). But they are unfamiliar with running a node.js server to load the map, and the 500MB JSON is posing a problem. Perhaps you know of another way to send them the map at 3x zoom, instead of taking a screenshot.

How can I combine multiple javascript functions for star rating system

I am running WAMP installed on a Windows 10 PC for a gallery of video clips stored on a local drive. The gallery pages contain thumbs for each video clip and a 5 star rating system.
The star rating system uses a java script module called ‘rateIt’. When the star rating is changed, the new value of the rating is updated in a mysql database table.

After several weeks of reading the ‘rateIt’ documentation, searching the internet for working examples and much trial & error, I finally have the java script code for the star rating of each thumb working as intended.

My problem is each gallery page contains hundreds of thumbs and the java script code for the star rating of each thumb is very repetitive.
How can I use a function stored either on the same page or used from a local js file to reduce the amount of java script code necessary for the star rating and use it for each thumb.

I am sure this is very elementary coding to someone with more experience in java script coding. I have tried to create a function on the page and pass the necessary variables to it, but every attempt breaks the star rating system.

My code for the first two thumbs:

<div class="thumbContainer">
    <button class="btn-thumb" id="pic10" href="#M1"></button>
    <div class="starContainer">
        <div class="rateit rateit-bg" id="vid147800" data-rateit-step="1" ></div>
        <div><span id="vid147800sid"></span><span id="hover"></span></div>
<script type="text/javascript">
$("#vid147800").data('rateit-value', 3);  //value is updated from database
$('#vid147800').bind('rated reset', function () {
    var rtDivID = '#vid147800';         //values are updated from
    var IDvid = "vid147800";            //database on page load
    var value = $(this).rateit('value');
    var tooltipvalues = ['delete', 'poor', 'ok', 'good', 'excellent'];
    $(rtDivID).bind("over", function (event, value) { 
        $(this).attr("title", tooltipvalues[value - 1]); });
    $(rtDivID).bind('rated', function (event, value) { 
        $("#vid147800sid").text("Rating saved " + value); });
    $(rtDivID).bind("reset", function (event, value) { 
        $("#vid147800sid").text("Rating reset"); });
    $.ajax({
        url: 'assets/includes/update_ratings.php', //your server side script
        data: { IDvid: IDvid, value: value }, //our data
        type: 'POST'
    });
});
</script>
    </div>
</div>

<div class="thumbContainer">
    <button class="btn-thumb" id="pic20" href="#M2"></button>
    <div class="starContainer">
        <div class="rateit rateit-bg" id="vid899128" data-rateit-step="1" ></div>
        <div><span id="vid899128value"></span><span id="hoverVID"></span></div>
<script type="text/javascript">
$("#vid899128").data('rateit-value', 2);  //value is updated from database
$("#vid899128").bind('rated reset', function () {
    var rtDivID = '#vid899128';         //values are updated from
    var IDvid = "vid899128";            //database on page load
    var value = $(this).rateit('value');
    var tooltipvalues = ['delete', 'poor', 'ok', 'good', 'excellent'];
    $(rtDivID).bind("over", function (event, value) { 
        $(this).attr("title", tooltipvalues[value - 1]); });
    $(rtDivID).bind('rated', function (event, value) { 
        $("#vid899128value").text("Rating saved " + value); });
    $(rtDivID).bind("reset", function (event, value) { 
        $("#vid899128value").text("Rating reset"); });
    $.ajax({
        url: 'assets/includes/update_ratings.php', //your server side script
        data: { IDvid: IDvid, value: value }, //data
        type: 'POST'
    });
});
</script>
    </div>
</div>

Any help you can offer will be greatly appreciated 🙂

User Messages and Bot Messages Displayed Twice in Chatbot Interface

I’m working on creating an AI chatbot. While the backend is almost complete, I’m struggling with the UI implementation.

Problem

Messages from both the bot and the user are displayed twice. For example, if I enter “hello there” as a user message, the chat displays it twice, as shown below:

If the bot replies with “hello there,” it also appears twice, identical to the user’s input.

hello there result

What I’ve Tried

Since the message class is divided into message.user and message.bot, I tried modifying message.draw() to conditionally call message.user.draw() or message.bot.draw() based on the message’s side, but it didn’t work.

I also tried adding a message counter or a boolean flag to prevent duplicate display, but that didn’t solve the issue either.

Code

Here’s my JavaScript code:

function Message(arg) {
    this.text = arg.text;
    this.message_side = arg.message_side;
    this.draw = function (_this) {
        return function () {
            let $message;
            $message = $($('.message_template').clone().html());
            $message.addClass(_this.message_side).find('.text').html(_this.text);
            $('.messages').append($message);

            return setTimeout(function () {
                return $message.addClass('appeared');
            }, 0);
        };
    }(this);
    return this;
}

function getMessageText() {
    let $message_input;
    $message_input = $('.message_input');
    return $message_input.val();
}

function sendMessage(text, message_side) {
    let $messages, message;
    $('.message_input').val('');
    $messages = $('.messages');
    message = new Message({
        text: text,
        message_side: message_side
    });
    message.draw();
    $messages.animate({scrollTop: $messages.prop('scrollHeight')}, 300);
}

Here’s my CSS:

.messages {
    list-style: none;
    padding: 20px;
    margin: 0;
    flex: 1;
    overflow-y: auto;
    background-color: #e6e9ef;
}

.messages .message .content {
    background-color: #ffffff;
    padding: 10px 15px;
    border-radius: 6px;
    max-width: 80%;
    box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
    word-break: keep-all;
    white-space: normal;
    font-size: 14px;
}

.messages .message {
    display: flex;
    align-items: flex-start;
    margin-bottom: 15px;
    font-size: 14px;
}

.messages .message.bot .avatar {
    width: 40px;
    height: 40px;
    border-radius: 50%;
    background-color: #3a539b;
    background-image: url('kitugi.png');
    background-size: cover;
    background-position: center;
    margin-right: 10px;
    flex-shrink: 0;
}

.messages .message.user .avatar,
.messages .message.user .username {
    display: none;
}

.messages .message.user {
    flex-direction: row-reverse;
    text-align: right;
}

.messages .message .content_wrapper {
    display: flex;
    flex-direction: column;
}

.messages .message .username {
    font-size: 12px;
    color: #666666;
    margin-bottom: 3px;
}

.messages .message.bot .content {
    display: inline-block;
    background-color: #ecf0f1;
    padding: 10px 20px;
    line-height: 1.5;
    border-radius: 6px;
    max-width: 80%;
    min-height: 24px;
    max-width: 80%;
    box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
    color: #34495e;
    text-align: left;
    word-break: normal;
    margin-left: 10px;
    margin-right: auto;
}

.messages .message.user .content {
    display: inline-block;
    background-color: #2980b9;
    color: #ffffff;
    padding: 10px 20px;
    line-height: 1.5;
    border-radius: 6px;
    max-width: 80%;
    min-height: 24px;
    max-width: 80%;
    margin-left: auto;
    box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
    margin-right: 10px;
    word-break: normal;
}

And my HTML:

<div class="message_template">
    <li class="message bot">
      <div class="avatar"></div>
      <div class="content_wrapper">
        <div class="username">CHATBOT</div>
        <div class="content">
          <div class="text">CHATBOT Message</div>
        </div>
      </div>
    </li>

    <li class="message user">
      <div class="content_wrapper">
        <div class="username">USER</div>
        <div class="content">
          <div class="text">USER Message</div>
        </div>
      </div>
    </li>
  </div>

Thank you for reading the long question.

Javascript replace tag using createRange()

In a contenteditable div, there is bingo <br><br> and is total of 10 indexes.

Using document.createRange(), replace the content between index 6 and index 10 to the word bingo.

The expected result is bingo<br>bingo.

I tried alot, but did not manage to replace a tag like <br>.

fetch method being ignored in React [closed]

I’m attempting to make a call to an api that I’m also running locally from a react app and it seems like the fetch is being skipped over.

export const doCreateUserWithEmailAndPassword = async (email, password) => {
    await createUserWithEmailAndPassword(auth, email, password)
    .then((userCred) => {
      console.log("HIT")
      fetch("http://localhost:8080/users/createUser", {
      method: 'POST',
      headers: {
      Accept: 'application/json',
      'Content-Type': 'application/json',
      },  body: JSON.stringify({
          name: userCred.user.displayName,
          email: userCred.user.email,
          user_id: userCred.user.uid
    }),
  })
  .then((response) => {
    console.log("HIT RESPONSE")
      switch(response.status){
      case 201:
        console.log("User record created")
        break;
      case 409:
        console.log("A user with that name already exists")
        break;
      case 400:
        console.log("Bad request")
        break;
      case 403:
        console.log("Forbidden")
        break;  
      case 500:
        console.log("Internal server error")
        break;
      }
       return response        
  }).catch(error => {
          console.error(error);
        })});
  console.log("HIT 2")
};

The API itself works when I hit it from postman but when making the call from the react app I can see “HIT” and “HIT 2” in the console in my browser but nothing indicating that the fetch was made. No errors or logs anywhere. Is there something I’m missing?

Why is Next.js throwing Error: WEBPACK_IMPORTED_MODULE is not a function?

I’m unable to figure out the problem. I’m exporting a function that serves the current authenticated user object (if present). I’m then using this user object to determine the addition of a nav link. This error won’t go away no matter how much I’ve reformed the reference.

This is the function definition @/app/hooks/use-auth-user.ts

'use client';
import {
    fetchAuthSession,
    fetchUserAttributes,
    getCurrentUser,
} from 'aws-amplify/auth';
import { useEffect, useState } from 'react';

export default function UseAuthUser() {
    const [user, setUser] = useState<Record<string, any>>();

useEffect(() => {
    async function getUser() {
        const session = await fetchAuthSession();
        if (!session.tokens) {
            return;
        }

        const user = {
            ...(await getCurrentUser()),
            ...(await fetchUserAttributes()),
            isAdmin: false,
        };

        const groups = session.tokens.accessToken.payload['cognito:groups'];
        // @ts-ignore
        user.isAdmin = Boolean(groups && groups.includes('administrators'));
        setUser(user);
    }

    getUser();
}, []);

return user;
}

And Here is the function that I’m referencing it from @/app/lib/menus.ts

export function getResourceMenu(): Menu {
const user = UseAuthUser();
let links: Menu = [
    { name: 'Privacy Policy', href: '/privacy' },
    { name: 'Terms & Conditions', href: '/terms-and-conditions' },
    { name: 'Member Portal', href: '/auth/login' },
];

if (user) {
    links.push({ name: 'Dashboard', href: '/dashboard' });
}

return links;
}

I’m attaching a screenshot of the error here:

Error: (0 , _app_hooks_use_auth_user__WEBPACK_IMPORTED_MODULE_0__.default) is not a function

This is the error output

I’d love some input on where I’m going wrong here because obviously – I am.

Is it possible to select an element on a page using the mouse if there is a div wrapper on top of it?

I am developing a browser extension in which the user has the ability to select an element on the page using the mouse (like in the browser inspector). After hovering over the page element, a highlight block will appear on top of it.

Image

Having studied the information on the network, I came to the following implementation option. After clicking on the extension icon, the functionality will be enabled, and by moving the cursor across the page, the active element will be highlighted.

It turns out that there is a basic structure of any page and a container with a highlighting block, which I will add through the extension.

HTML

<html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
  </head>
  <body>
    <header class="header">...</header>
    <main class="content">...</main>
    <footer class="footer">...</footer>

    <div class="extension_container"> // will be added via script
      <div class="extension_item"></div>
    </div>
  </body>
</html>

Browser extension – content.css

.extension_container {
  position: absolute;
  z-index: 1000000;
}

.extension_item {
  background-color: green;
  opacity: .5;
}

Browser extension – content.js

const container = document.createElement("div");
const item = document.createElement("div");

container.classList.add("extension_container");
item.classList.add("extension_item");

container.append(item);
document.body.append(container);

document.addEventListener("mouseover", e => {
  selectElement(e.target); // we calculate the size and position of the element, and then update the styles of extension_item
});

document.addEventListener("mouseout", e => {
  unselectElement(e.target); // hide extension_item (reset size and position)
});

Here I run into the problem that the container overlaps the page and does not allow receiving elements in the mouseover event.

Image

After searching for solutions online, I found two options:

  1. Use the CSS property pointer-events: none for the container and its contents.

  2. Replace the mouseover event with mousemove and hide the container in the handler using the visability: hidden property, then get the element by the current coordinates and return the original visability property to the container again.

Unfortunately, these two options do not suit me. The first one is because all events and CSS effects on the page will remain available. For example, when hovering over an element, the color may change or a tooltip may open, which we would like to avoid.

Image

The second option demonstrated poor performance due to the large number of mousemove event triggers. Tracking the element under the wrapper and updating the extension_item causes delays in case of fast mouse movement.

I would like to know if it is possible to implement similar functionality without using the pointer-events: none property? Or, if this is not possible, then leave pointer-events: none, but prevent element events and css effects. I would appreciate any suggestions and advice.

Vite + React + TS error TS2307: Cannot find module ‘shared/api/request.ts’ or its corresponding type declarations

When running jest test:

src/shared/api/request.test.ts:1:24 – error TS2307: Cannot find module ‘shared/api/request.ts’ or its corresponding type declarations.

1 import { getUrl } from ‘shared/api/request.ts’;

My files look like:

tsconfig.app.json

{
  "compilerOptions": {
    "target": "ES2020",
    "useDefineForClassFields": true,
    "lib": ["ES2020", "DOM", "DOM.Iterable"],
    "module": "ESNext",
    "skipLibCheck": true,
    "esModuleInterop": true,
    "moduleResolution": "Bundler",
    "allowImportingTsExtensions": true,
    "isolatedModules": true,
    "moduleDetection": "force",
    "noEmit": true,
    "jsx": "react-jsx",
    "strict": true,
    "noUnusedLocals": true,
    "noUnusedParameters": true,
    "noFallthroughCasesInSwitch": true,
    "noUncheckedSideEffectImports": true,
    "baseUrl": ".",
    "paths": {
      "src/*": ["./src/*"],
      "shared/*": ["./src/shared/*"],
      "entities/*": ["./src/entities/*"]
    }
  },
  "include": ["src", "./jest.setup.ts"]
}

jest.config.js

import { pathsToModuleNameMapper } from 'ts-jest';
import tsConfig from './tsconfig.app.json' with { type: "json" };

console.log(pathsToModuleNameMapper(tsConfig.compilerOptions.paths))

/**@type {import('ts-jest').JestConfigWithTsJest} */
export default {
  testEnvironment: "jsdom",
  transform: {
    "^.+\.tsx?$": "ts-jest",
  },
  roots: ['<rootDir>'],
  modulePaths: [tsConfig.compilerOptions.baseUrl],
  moduleNameMapper: pathsToModuleNameMapper(
    tsConfig.compilerOptions.paths),
  setupFilesAfterEnv: ['<rootDir>/jest.setup.ts'],
};

jest –show-config

      "moduleNameMapper": [
        [
          "^src/(.*)$",
          "./src/$1"
        ],
        [
          "^shared/(.*)$",
          "./src/shared/$1"
        ],
        [
          "^entities/(.*)$",
          "./src/entities/$1"
        ]
      ],

How can I resolve this error?

I expect to fix my routes in runtime

Hiding other elements in a collapsible list

What I want to achieve:

I am making a list where I want each item to be collapsible, but I want to hide all of the other list elements when one is collapsed.

When one list item <div> is “collapsed” and showing, I want to toggle the display of the collapsible to be none and be able to “uncollapse or return to the original collapsible” by a click on the collapsed <div>.

enter image description here

What I have so far:

var coll = document.getElementsByClassName("collapsecontent");
var i;

for (i = 0; i < coll.length; i++) {
  coll[i].addEventListener("click", function() {
    this.classList.toggle("active");
    var content = this.nextElementSibling;
    if (content.style.display === "block") {
      content.style.display = "none";
    } else {
      content.style.display = "block";
    }
  });
}
button.collapsecontent {
  display: block;
  background-color: orange;
  border-color: blue;
  border-radius: 20px;
  width: 87.5%;
  margin-left: 6.2%;
  margin-top: 1%;
  transition: ease-out 10s;
  /*transition broken*/
  cursor: pointer;
}

div.content {
  display: none;
  background-color: orange;
  margin-left: 6.2%;
  margin-right: 6.2%;
  padding: 5%;
  border: 2px solid blue;
  border-radius: 20px;
  cursor: pointer;
}
<ul class="contentbox">
  <!--content boxes-->
  <button class="collapsecontent" type="button"><li class="contentbox"><h1>Works</h1></li></button>
  <div class="content">
    <p>Example</p>
  </div>


  <button class="collapsecontent" type="button"><li class="contentbox"><h1>Other</h1></li></button>
  <div class="content">
    <p>Example2</p>
  </div>


  <button class="collapsecontent" type="button"><li class="contentbox"><h1>About</h1></li></button>
  <div class="content">
    <p>Example3</p>
  </div>


  <button class="collapsecontent" type="button"><li class="contentbox"><h1>Placeholder</h1></li></button>
  <div class="content">
    <p>Example4</p>
  </div>

</ul>

I am also willing to explore ways other than collapsibles if it achieves the same results, but this was the only way I could think of.

Opentelemetry context propagation in nestjs app

there. I bumped into a problem with configuration of OTEL for NestJS. I want to add additional information into the span attributes and propagate it over all trace. I use baggage. My entry point is nest interceptor.

@Injectable()
export class TracingInterceptor implements NestInterceptor {

    intercept(reqContext: ExecutionContext, next: CallHandler): Observable<any> {
        const oldContext = context.active()
        const tracer = trace.getTracer('controller-tracer');
        const currentBaggage = propagation.getBaggage(oldContext) ?? propagation.createBaggage();
        // Add entries to baggage
        const updatedBaggage = currentBaggage
            .setEntry('custom', {
                value: 'my value',
            })

        // Set the updated baggage in context
        const baggageContext = propagation.setBaggage(context.active(), updatedBaggage);

        // Start a new span with the baggage context
        const span = tracer.startSpan(
            'Tracing: add auth entity',
            { kind: SpanKind.SERVER },
            baggageContext,
        );

        const newContext = trace.setSpan(baggageContext, span);

        return context.with(newContext, () => {
            return next.handle().pipe(
                tap({
                    next: () => {
                        span.setStatus({ code: SpanStatusCode.OK });
                        span.end();
                    },
                    error: (error) => {
                        span.recordException(error);
                        span.setStatus({ code: SpanStatusCode.ERROR, message: error.message });
                        span.end();
                    }
                }),
            )
        });
    }
}

My problem is – I can create span with my custom baggage attributes but new context is spred on Observable object only. All data in stream are emitted with older/previous context.

And my trace tree looks like: enter image description here
But I need that spans Tracing: get stat and GET were children for Tracing: add auth entity. Not siblings.