Translation failed TypeError: google_translate_api_x__WEBPACK_IMPORTED_MODULE_0__ is not a function

I attempted to run this code for my translation web app created from react:

import translate from 'google-translate-api-x';

export async function translateText(text, sourceLang, targetLang) {
  try {
    const response = await translate(`${text}`, {
      from: `${sourceLang}`, 
      to: `${targetLang}`, 
      autoCorrect: true
    });

    // Extract the translated text from the response
    return response.text;
  } catch (error) {
    console.error("Error during translation:", error);
    throw error;
  }
}

It keeps giving me the error:
Translation failed TypeError: google_translate_api_x__WEBPACK_IMPORTED_MODULE_0__ is not a function

I read the API README and copied the way that they have used the function and didn’t get the same result. I think this problem may lie in
export async function
I am a JavaScript/React beginner so I do not have much knowledge on how to solve the issue.

how to use CookieStore in Angular in order to listen to cookie change events

I have an angular component where I would like to perform actions when a specific cookie is changed. I read that I can do it via CookieStore Api (https://developer.mozilla.org/en-US/docs/Web/API/CookieStore/change_event)
But when I try to use it in my angular component, the code does not compile:

    ngOnInit() {
   
        if ('cookieStore' in window) {
            // Listen for changes to cookies
            window.cookieStore.addEventListener('change', event => {
                event.changed.forEach(change => {
                    console.log(`Cookie changed: ${change.name} = ${change.value}`);
                }); 
            });
        } else {
            console.log('Cookie Store API is not supported in this browser.');
        }
    }

Error is

TS2339: Property cookieStore does not exist on type Window & typeof globalThis

I am using angular version: 15.2.10. Is there any way I can use the CookieStore Api in my angular code? Either service or component?

Arrow functions with untyped parameters resolve to undefined when inferring their types

I’m trying to create a value resolver for functions and raw values and this function works for 99% of the cases I’m testing but I’m getting an issue when resolving an untyped arrow function.

declare function getValue<TValue>(value: TValue, args?: TValue extends ((...args: infer TArgs) => any) ? TArgs : undefined): TValue | undefined;

const value1 = getValue((c: number) => 23, [23]); // OK

const func1 = (c) => 23;
const value2 = getValue(func1, [23]); // OK

const value3 = getValue((c) => 23, [23]);
                                   ^^^^-ERROR

Playground code

Error:

Argument of type ‘number[]’ is not assignable to parameter of type ‘undefined’

What is the issue here and can it be fixed without losing type safety?

PM2 running script instances concurrently

I am scheduling a script to run every minute using the following command:

pm2 start my-script.js --cron "* * * * *"

This does make the script run every minute, but here is the issue – if the first run of the script takes more than one minute, it seems like PM2 is killing that instance and starting a new one. This script finishes within seconds most of the time but it sometimes needs to run for a few minutes. I expected PM2 to simply run a new instance of the script after a minute has elapsed and let the previous run finish.

I have some logs from this script showing time elapsed every 5 seconds. Checking the live logs for the script with pm2 logs my-script shows that logs from the first run of the script suddenly stop when the second run starts.

How can I tell pm2 to start another instance of the script concurrently if the previous run has not finished yet?

Why my Parcel transpiled file of 159 liner code is more than of 13,000 lines?

The transpiled code i got for my 159 liner JS file is more than 13,000 lines with many let, const and arrow fucntions. A piece of code from that trasnpiled file is this:

 ws.onmessage = async function(event /*: {data: string, ...} */ ) {
        checkedAssets = {} /*: {|[string]: boolean|} */ ;
        assetsToAccept = [];
        assetsToDispose = [];
        var data /*: HMRMessage */  = JSON.parse(event.data);
        if (data.type === 'reload') fullReload();
        else if (data.type === 'update') {
            // Remove error overlay if there is one
            if (typeof document !== 'undefined') removeErrorOverlay();
            let assets = data.assets.filter((asset)=>asset.envHash === HMR_ENV_HASH);
            // Handle HMR Update
            let handled = assets.every((asset)=>{
                return asset.type === 'css' || asset.type === 'js' && hmrAcceptCheck(module.bundle.root, asset.id, asset.depsByBundle);
            });
            if (handled) {
                console.clear();
                // Dispatch custom event so other runtimes (e.g React Refresh) are aware.
                if (typeof window !== 'undefined' && typeof CustomEvent !== 'undefined') window.dispatchEvent(new CustomEvent('parcelhmraccept'));
                await hmrApplyUpdates(assets);
                // Dispose all old assets.
                let processedAssets = {} /*: {|[string]: boolean|} */ ;
                for(let i = 0; i < assetsToDispose.length; i++){
                    let id = assetsToDispose[i][1];
                    if (!processedAssets[id]) {
                        hmrDispose(assetsToDispose[i][0], id);
                        processedAssets[id] = true;
                    }
                }
                // Run accept callbacks. This will also re-execute other disposed assets in topological order.
                processedAssets = {};
                for(let i = 0; i < assetsToAccept.length; i++){
                    let id = assetsToAccept[i][1];
                    if (!processedAssets[id]) {
                        hmrAccept(assetsToAccept[i][0], id);
                        processedAssets[id] = true;
                    }
                }
            } else fullReload();
        }
        if (data.type === 'error') {
            // Log parcel errors to console
            for (let ansiDiagnostic of data.diagnostics.ansi){
                let stack = ansiDiagnostic.codeframe ? ansiDiagnostic.codeframe : ansiDiagnostic.stack;
                console.error("uD83DuDEA8 [parcel]: " + ansiDiagnostic.message + 'n' + stack + 'nn' + ansiDiagnostic.hints.join('n'));
            }
            if (typeof document !== 'undefined') {
                // Render the fancy html overlay
                removeErrorOverlay();
                var overlay = createErrorOverlay(data.diagnostics.html);
                // $FlowFixMe
                document.body.appendChild(overlay);
            }
        }
    };

I used parcel with babel and it did transpile my code fine but this transpile file has tons of code and some of this code contains let, const, arrow functions and promises. Why is that? is this normal? if not then what’s the solution?

Javascript scrollHeight changes when observing the scrollHeight differently

When I observe the scroll height in my project in two different ways, two different numbers come up.

I’m currently working on a project, and i am trying to apply a background to a menu element when it is opened. Because the element can be dynamic in size, i am trying to grab the elements scroll height and trying to apply it to the background’s height.

The issue is that the scroll height comes up short. When inspecting the element itself with a console log and checking its properties, the scroll height is for example 450. When I dump out the scroll height by itself, it changes to 270.

Showing the JavaScript:
Showing the JavaScript

Results of the first console log:
Results of the first console log

Results of the second console log:
Results of the second console log

How do I position the tooltip always at the same distance from the thumb in the range slider?

I have two range sliders, and I need to position the tooltip in them according to the screenshot.

Screen

I placed it, but when moving the slider, the tooltip does not stay at the same distance near it, but moves.

How to solve this problem?

Here is the code –

document.addEventListener('DOMContentLoaded', () => {
  const sliders = document.querySelectorAll('.calculator__slider-item');

  sliders.forEach((slider) => {
    const tooltip = slider.nextElementSibling; // Находим tooltip
    const valueDisplay = slider.parentElement.nextElementSibling; // Находим <span> для отображения значения

    function updateSlider() {
      const sliderRect = slider.getBoundingClientRect(); // Получаем размеры слайдера
      const thumbWidth = 20; // Фиксированная ширина thumb
      const min = parseInt(slider.min);
      const max = parseInt(slider.max);

      // Текущее значение
      const value = parseInt(slider.value);

      // Процентное положение слайдера
      const percent = (value - min) / (max - min);

      // Абсолютная позиция thumb в пикселях
      const thumbPosition = percent * sliderRect.width;

      // Позиционируем tooltip строго по thumb
      tooltip.style.left = `${thumbPosition - tooltip.offsetWidth / 2 + thumbWidth / 2}px`;
      tooltip.textContent = value;

      // Обновляем отображение значения
      valueDisplay.textContent = value;
    }

    // Инициализация
    updateSlider();

    // Обновление при взаимодействии
    slider.addEventListener('input', updateSlider);
  });
});
.slider-group {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  width: 500px;
  flex-direction: column;
}

.calculator__slider-wrapper {
  position: relative;
}

.calculator__tooltip {
  color: red;
  font-size: 16px;
  font-weight: 600;
  line-height: 140%;
  position: absolute;
  bottom: 12%;
  left: 50%;
  transform: translateY(-50%);
}

.calculator__slider-item {
  width: 100%;
  border: 1px solid rgba(0, 0, 0, 0.2);
  -webkit-appearance: none;
  min-height: 40px;
  border-radius: 8px;
  overflow: hidden;
  padding: 0 10px 0 20px;
}

.calculator__slider-item::-webkit-slider-thumb {
  -webkit-appearance: none;
  width: 20px;
  height: 40px;
  background: #fff;
  border: 4px solid #26bb01;
  border-radius: 8px;
  cursor: pointer;
  box-shadow: -410px 0 0 400px #26bb01;
}
<div class="calculator__item slider-group">
  <div class="calculator__slider">
    <label for="hours">Часов в день</label>
    <div class="calculator__slider-wrapper">
      <input type="range" id="hours" min="2" max="12" value="8" class="calculator__slider-item" />
      <div class="calculator__tooltip"></div>
    </div>
    <span class="calculator__slider-value" id="hours-value">8</span>
  </div>
  <div class="calculator__slider">
    <label for="days">Дней в месяц</label>
    <div class="calculator__slider-wrapper">
      <input type="range" id="days" min="3" max="31" value="20" class="calculator__slider-item" />
      <div class="calculator__tooltip"></div>
    </div>
    <span class="calculator__slider-value" id="days-value">20</span>
  </div>
</div>

https://codepen.io/lqwhvtss-the-flexboxer/pen/oNKRydz

I tried different variations of calculating the tooltip position in js – nothing worked

How can I fix the “undefined variable” error in my JavaScript event listener function? [closed]

I’m working on a simple JavaScript project where I want to toggle a “dark mode” theme for my website. I’ve created a button that, when clicked, should switch the page’s background color. However, I keep getting an “undefined variable” error in the console, and I’m not sure why.

I defined the toggleTheme function and added an event listener to the button, but the error keeps occurring whenever I click the button. I’ve checked similar issues on Stack Overflow and reviewed the MDN documentation on JavaScriptfunctions and event listeners, but I still can’t find a solution.

js sparkline-responsive ajax data image ne s’affiche pas

bonjour les amis;
j’essaye de tavailler avec bootstrap admin ,html, php et mysql avec jquery, quand j’ai voulu affiché des statistiques (des courbes, lignes avec jquery.sparkline.min.js)

Uncaught SyntaxError: “undefined” is not valid JSON
at JSON.parse ()
at HTMLDivElement. (app.js:255:25)
at Function.each (jquery.min.js:2:2877)
at o.fn.init.each (jquery.min.js:2:818)
at initResponsiveSparklines (app.js:250:12)
at initSparkline (eval at globalEval (jquery.min.js:2:2533), >:97:17)
at n.indexOf.l..onload (LobiAdmin.min.js:1:8010)
les courbes ne s’affiche que si j’actualise la page plusieurs fois
voici mon code

<script type="text/javascript">
VerifConnexion();
function numVariation(a, b) {
    return Math.round(((b-a)/a) * 100)
  }

                   $.ajax({
                    url: 'php/dashboard.php?NIV=SELECT',
                    success: function(msg){
                         var msg = JSON.parse(msg);
                         var tab1=[];
                         var tab2=[];
                         var tab3=[];
                         var tab4=[];
                         var tab5=[];
                         var tab6=[];
                     for(var i = 0 ; i < msg.length; i++){
                         tab1.push(msg[i]['CadreA']*1);
                         tab2.push(msg[i]['MaitriseA']*1);
                         tab3.push(msg[i]['ExecutionA']*1);
                         tab4.push(msg[i]['CadreI']*1);
                         tab5.push(msg[i]['MaitriseI']*1);
                         tab6.push(msg[i]['ExecutionI']*1);
                     }
                     
                    $('.Cn1').html(JSON.stringify(tab1[0]));
                    $('.Cn2').html(JSON.stringify(tab1[i-1]));
                    if(numVariation(tab1[0],tab1[i-1]) > 0){
                          $('.progPourcentage1').html(numVariation(tab1[0],tab1[i-1])+'<i class="fa fa-level-up text-info"></i>');
                          $(".ProBar1").html('<span class="bg-info" style="width: '+numVariation(tab1[0],tab1[i-1])+'%;"></span>')  ;
                      } else {
                          $('.progPourcentage1').html(numVariation(tab1[0],tab1[i-1])+'<i class="fa fa-level-down text-danger"></i>');
                          $(".ProBar1").html('<span class="bg-danger" style="width: '+(-1*numVariation(tab1[0],tab1[i-1]))+'%;"></span>')  ;
                      }
                      var gg = JSON.stringify(tab1);
                    $('#image1').attr("data-Data",gg);
                    $('.Cn11').html(JSON.stringify(tab2[0]));
                    $('.Cn21').html(JSON.stringify(tab2[i-1]));
                    if(numVariation(tab2[0],tab2[i-1]) > 0){
                          $('.progPourcentage2').html(numVariation(tab2[0],tab2[i-1])+'<i class="fa fa-level-up text-info"></i>');
                          $(".ProBar2").html('<span class="bg-info" style="width: '+numVariation(tab2[0],tab2[i-1])+'%;"></span>')  ;
                      } else {
                          $('.progPourcentage2').html(numVariation(tab2[0],tab2[i-1])+'<i class="fa fa-level-down text-danger"></i>');
                          $(".ProBar2").html('<span class="bg-danger" style="width: '+(-1*numVariation(tab2[0],tab2[i-1]))+'%;"></span>')  ;
                      }
                      var gg1 = JSON.stringify(tab2);
                    $('#image2').attr("data-data",gg1);
                    $('.Cn13').html(JSON.stringify(tab3[0]));
                    $('.Cn23').html(JSON.stringify(tab3[i-1]));
                    if(numVariation(tab3[0],tab3[i-1]) > 0){
                          $('.progPourcentage3').html(numVariation(tab3[0],tab3[i-1])+'<i class="fa fa-level-up text-info"></i>');
                          $(".ProBar3").html('<span class="bg-info" style="width: '+numVariation(tab3[0],tab3[i-1])+'%;"></span>')  ;
                      } else {
                          $('.progPourcentage3').html(numVariation(tab3[0],tab3[i-1])+'<i class="fa fa-level-down text-danger"></i>');
                          $(".ProBar3").html('<span class="bg-danger" style="width: '+(-1*numVariation(tab3[0],tab3[i-1]))+'%;"></span>')  ;
                      }
                      var gg2 = JSON.stringify(tab3);
                    $('#image3').attr("data-data",gg2);
                    },
                    complete: function() {
                        $('#image3').sparkline();
                                            
                    },
                    
                error:function(){
                    alert("failure");
                }
            });
                    


  (function(){
            LobiAdmin.loadScript([
                'js/plugin/highlight/highlight.pack.js'
            ], function(){
                LobiAdmin.highlightCode();
            });

            LobiAdmin.loadScript([
                'js/plugin/sparkline/jquery.sparkline.min.js'
            ], initSparkline);
            
          
            function initSparkline(){
                
                //Initialize lobipanel
                $('.panel').lobiPanel({
                    reload: false,
                    editTitle: false,
                    sortable: true
                });

               /** This code runs when everything has been loaded on the page */
                /* Inline sparklines take their values from the contents of the tag */
                
                
                initSparklineDefaults();
                initResponsiveSparklines();
                
                $('.sparkline').sparkline('html', {
                    enableTagOptions: true
                });
                


                /** 
                ** Draw the little mouse speed animated graph
                ** This just attaches a handler to the mousemove event to see
                ** (roughly) how far the mouse has moved
                ** and then updates the display a couple of times a second via
                ** setTimeout()
                **/
                function drawMouseSpeedDemo() {
                    var mrefreshinterval = 500; // update display every 500ms
                    var lastmousex=-1; 
                    var lastmousey=-1;
                    var lastmousetime;
                    var mousetravel = 0;
                    var mpoints = [];
                    var mpoints_max = 30;
                    $('html').mousemove(function(e) {
                        var mousex = e.pageX;
                        var mousey = e.pageY;
                        if (lastmousex > -1) {
                            mousetravel += Math.max( Math.abs(mousex-lastmousex), Math.abs(mousey-lastmousey) );
                        }
                        lastmousex = mousex;
                        lastmousey = mousey;
                    });
                    var mdraw = function() {
                        var md = new Date();
                        var timenow = md.getTime();
                        if (lastmousetime && lastmousetime!=timenow) {
                            var pps = Math.round(mousetravel / (timenow - lastmousetime) * 1000);
                            mpoints.push(pps);
                            if (mpoints.length > mpoints_max)
                                mpoints.splice(0,1);
                            mousetravel = 0;
                            $('#mousespeed').sparkline(mpoints, { width: mpoints.length*2, tooltipSuffix: ' pixels per second' });
                        }
                        lastmousetime = timenow;
                        setTimeout(mdraw, mrefreshinterval);
                    }
                    // We could use setInterval instead, but I prefer to do it this way
                    setTimeout(mdraw, mrefreshinterval);
                };
                drawMouseSpeedDemo();

                // Composite line charts, the second using values supplied via javascript
                
                // Line charts with normal range marker
            
        
            }
            
        })();
  

    </script>
    

<div id="sparkline">
    <div class="row">
        <div class="col-sm-6 col-lg-3">
            <div class="tile-stat bg-white border-1">
                <div class="tile-body min-h-200 text-center">
                    <h3 class="margin-top-5 text-info font-weight-700">Cadre</h3>
                    <div id="image1" class="sparkline-responsive" data-Type="bar" data-max-width="200" data-Height="70" ></div>
                    <div class="row">
                        <div class="col-xs-6">
                            <h5>N-1</h5>
                            <h5 class="Cn1"><i class="fa fa-level-up text-info"></i></h5>
                        </div>
                        <div class="col-xs-6">
                            <h5>Aujourd'hui</h5>
                            <h5 class="Cn2"><i class="fa fa-level-up text-info"></i></h5>
                        </div>
                     </div>
                </div>
                <div class="tile-progressbar ProBar1">
                    
                </div>
                <div class="tile-footer">
                    <h4 class="progPourcentage1"></h4>
                    
                </div>
            </div>
        </div>
        <div class="col-sm-6 col-lg-3">
            <div class="tile-stat bg-white border-1">
                <div class="tile-body min-h-200 text-center">
                    <h3 class="margin-top-5 text-info font-weight-700">Maitrise</h3>
                    <div id="image2" class="sparkline-responsive" data-Type="bar" data-max-width="200" data-Height="70" ></div>
                    <div class="row">
                        <div class="col-xs-6">
                            <h5>N-1</h5>
                            <h5 class="Cn11"><i class="fa fa-level-up text-info"></i></h5>
                        </div>
                        <div class="col-xs-6">
                            <h5>Aujourd'hui</h5>
                            <h5 class="Cn21"><i class="fa fa-level-up text-info"></i></h5>
                        </div>
                     </div>
                </div>
                <div class="tile-progressbar ProBar2">
                    
                </div>
                <div class="tile-footer">
                    <h4 class="progPourcentage2"></h4>
                    
                </div>
            </div>
        </div>
        <div class="col-sm-6 col-lg-3">
            <div class="tile-stat bg-white border-1">
                <div class="tile-body min-h-200 text-center">
                    <h3 class="margin-top-5 text-info font-weight-700">Execution</h3>
                    <div id="image3" class="sparkline-responsive" data-Type="bar" data-max-width="200" data-Height="70" ></div>
                    <div class="row">
                        <div class="col-xs-6">
                            <h5>N-1</h5>
                            <h5 class="Cn13"><i class="fa fa-level-up text-info"></i></h5>
                        </div>
                        <div class="col-xs-6">
                            <h5>Aujourd'hui</h5>
                            <h5 class="Cn23"><i class="fa fa-level-up text-info"></i></h5>
                        </div>
                     </div>
                </div>
                <div class="tile-progressbar ProBar3">
                    
                </div>
                <div class="tile-footer">
                    <h4 class="progPourcentage3"></h4>
                    
                </div>
            </div>
        </div>
    </div>
 </div>   

    
</div>
enter code here

React Native App taking time to load before registerRootComponent

There some logs which are triggered due which App is taking around 30 seconds to load even before triggering the registerRootComponent(App).

index.js

import { registerRootComponent } from 'expo';
import App from './App';
import messaging from '@react-native-firebase/messaging';
import { onNotificationReceived, registerForegroundService, registerNotificationEvents } from "./src/utils";

messaging().setBackgroundMessageHandler(onNotificationReceived);
registerForegroundService();
registerNotificationEvents();

registerRootComponent(() => {
console.log("Bingo)
return App()
});

Using this command adb logcat | grep -i “reactnative”, I saw some logs before triggering the registerRootComponent(App).

11-19 16:15:22.052  7663  7663 D ReactNativeFirebaseApp: received application context.
11-19 16:15:22.558  7663  7663 W unknown:ReactNative: Packager connection already open, nooping.
11-19 16:15:23.436  7663  7787 V SoLoader: libreactnativejni.so not found on /data/data/cats.user/lib-main
11-19 16:15:23.436  7663  7787 D SoLoader: libreactnativejni.so found on /data/app/~~yM5j9FGE==/cats.user-SsG6JSJVdYvV-aPg==/lib/arm64
11-19 16:15:23.437  7663  7787 D SoLoader: Not resolving dependencies for libreactnativejni.so
11-19 16:15:23.438  7663  7787 D nativeloader: Load /data/app/~~yM5j9FGE==/cats.user-SsG6JSJVdYvV-aPg==/lib/arm64/libreactnativejni.so using ns clns-5 from class loader (caller=/data/app/~~yM5j9FGE==/cats.user-SsG6JSJVdYvV-aPg==/base.apk): ok
11-19 16:15:53.289  7663  7663 W unknown:ReactNative: Packager connection already open, nooping.
11-19 16:15:53.440  7663  7948 W unknown:ViewManagerPropertyUpdater: Could not find generated setter for class 
com.reactnativecommunity.checkbox.ReactCheckBoxManager
11-19 16:15:53.441  7663  7948 W unknown:ViewManagerPropertyUpdater: Could not find generated setter for class 
com.reactnativecommunity.slider.ReactSliderManager
11-19 16:15:53.443  7663  7948 W unknown:ViewManagerPropertyUpdater: Could not find generated setter for class 
com.reactnativecommunity.slider.ReactSliderManager$ReactSliderShadowNode
11-19 16:15:53.444  7663  7948 W unknown:ViewManagerPropertyUpdater: Could not find generated setter for class 
org.reactnative.maskedview.RNCMaskedViewManager
11-19 16:15:53.445  7663  7948 W unknown:ViewManagerPropertyUpdater: Could not find generated setter for class 
com.reactnativecommunity.picker.ReactDialogPickerManager
11-19 16:15:53.448  7663  7948 W unknown:ViewManagerPropertyUpdater: Could not find generated setter for class 
com.reactnativecommunity.picker.ReactPickerShadowNode
11-19 16:15:53.449  7663  7948 W unknown:ViewManagerPropertyUpdater: Could not find generated setter for class 
com.reactnativecommunity.picker.ReactDropdownPickerManager
11-19 16:15:56.397  7663  7947 V SoLoader: libreactnativeblob.so not found on /data/data/cats.user/lib-main

Most of the time is taken between these two logs.

11-19 16:15:23.438  7663  7787 D nativeloader: Load /data/app/~~yM5j9FGE==/cats.user-SsG6JSJVdYvV-aPg==/lib/arm64/libreactnativejni.so using ns clns-5 from class loader (caller=/data/app/~~yM5j9FGE==/cats.user-SsG6JSJVdYvV-aPg==/base.apk): ok
11-19 16:15:53.289  7663  7663 W unknown:ReactNative: Packager connection already open, nooping.

Currently Using

"expo": "^48.0.0"
"react": "18.2.0"  
"react-native": "0.71.8",

All added this in the build.gradle file but didn’t work.

dependencies {
implementation("com.facebook.soloader:soloader:0.10.4")
}

Elementor mobile/tablet menu items don’t differentiate between clicking on the main menu item and the dropdown arrow – how to fix?

This is the structure of my main menu – different main items that link to separate pages and also have their own submenus:

enter image description here

When I first click on the item, no matter if it’s the default dropdown arrow or the name of the main item/main page, it reacts as if the dropdown submenu is being opened. And when I click on it again, it reacts as if I’m opening the page that’s also the main item of the dropdown (so, About Us, Service Area etc.), leaving me no option to open the main page (with the first click) or to otherwise close the dropdown menu (with the second click).

I tried to use the Inspector and write a JS code that would differentiate between the two, but it hasn’t been working properly. I added it to Elementor Custom Codes, the section:

<script>
document.addEventListener('DOMContentLoaded', function () {
var submenuToggles = document.querySelectorAll('.elementor-nav-menu .sub-arrow');

for (var i = 0; i < submenuToggles.length; i++) {
    submenuToggles[i].addEventListener('click', function (e) {
        e.stopPropagation();
        e.preventDefault();

        var submenu = this.parentElement.querySelector(
            '.elementor-242 .elementor-element.elementor-element-bc7c611 .elementor-nav-menu--dropdown .elementor-sub-item'
        );

        if (submenu) {
            submenu.classList.toggle('active');
        }
    });
}
});
</script>

I’m including screenshots of the Inspector tools. This would be the arrow:

enter image description here

And this would be the text: enter image description here

Could someone please help me out?

ngx-slider and angular form control?

I am using two ngx-sliders with an Anuglar form and want the two sliders (a ‘Value’ and a ‘Band’) both with two handles to be connected to each other depending on the mapping. As well as this, I a text input that has the same form control as the value slider. The user can provide a value using either the slider or the value box, and the bands should update correctly for both.

<div class="custom-slider">
                     <ngx-slider
                        [options]="sliderOptionsBands"
                        [value]="sForm.get('minBand')?.value"
                        [highValue]="sForm.get('maxBand')?.value"
                        (valueChange)="onBandChange('minBand', $event)"
                        (highValueChange)="onBandChange('maxBand', $event)"></ngx-slider>
                  </div>
                  <label
                     for="valueInputMin"
                     class="form-label fw-bold mt-4">
                     Value
                  </label>
                  <div class="custom-slider mb-2">
                     <ngx-slider
                        [options]="sliderOptionsValue"
                        [value]="sForm.get('minValue')?.value"
                        [highValue]="sForm.get('maxValue')?.value"
                        (valueChange)="onValueChange('minValue', $event)"
                        (highValueChange)="onValueChange('maxValue', $event)"></ngx-slider>
                  </div>
                  <div class="input-group">
                     <span
                        for="valueInputMin"
                        class="input-group-text">
                        Min
                     </span>
                     <input
                        type="number"
                        min="10"
                        max="1000"
                        step="0.001"
                        class="form-control"
                        formControlName="minValue"
                        id="valueInputMin" />
                     <span
                        for="valueInputMax"
                        class="input-group-text">
                        Max
                     </span>
                     <input
                        type="number"
                        min="10"
                        max="1000"
                        step="0.001"
                        class="form-control"
                        formControlName="maxValue"
                        id="valueInputMax" />
                  </div>

Here are the ngx-slider options:

   sliderOptionsValue: Options = {
      floor: 10,
      ceil: 1000,
      step: 1,
      ticksArray: [0, 50, 100, 150, 200, 250, 300, 350, 400, 450, 500, 550, 600, 650, 700, 750, 800, 850, 900, 950, 1000],
      showTicks: true
   };

   sliderOptionsBands: Options = {
      floor: 1,
      ceil: 10,
      step: 1,
      tickStep: 1,
      showTicks: true,
      showTicksValues: true
   };

   bandToValueMap = [
      {band: 1, min: 10, max: 70},
      {band: 2, min: 71, max: 120},
      {band: 3, min: 121, max: 190},
      {band: 4, min: 191, max: 250},
      {band: 5, min: 251, max: 330},
      {band: 6, min: 331, max: 385}
   ];

I want the two sliders to work interconnected as I said, as well as the text input. Is there a way to do this without getting stuck in recursive loops where the value is set by the user in the text box and then glitches between the entered value and the band min or max. These are the methods I have so far:

   onBandChange(controlName: string, value: number): void {
      if (this.isUpdating) return; // Prevent recursion

      this.isUpdating = true;

      this.sForm.get(controlName)?.setValue(value);

      const minBand = this.sForm.get('minBand')?.value;
      const maxBand = this.sForm.get('maxBand')?.value;

      if (minBand && maxBand) {
         const minValue = this.bandToValueMap.find((b) => b.band === minBand)?.min ?? 10;
         const maxValue = this.bandToFrequencyMap.find((b) => b.band === maxBand)?.max ?? 385;

         const currentMinValue = this.sForm.get('minValue')?.value;
         const currentMaxValue = this.sForm.get('maxValue')?.value;

         // Only update Values if they differ to avoid triggering unnecessary updates
         if (minValue !== currentMinValue) {
            this.sForm.get('minValue')?.setValue(minValue);
         }

         if (maxValue !== currentMaxValue) {
            this.sForm.get('maxValue')?.setValue(maxValue);
         }
      }

      this.isUpdating = false;
   }

   onValueChange(controlName: string, value: number): void {
      if (this.isUpdating) return; // Prevent recursion

      this.isUpdating = true; // Set the flag to prevent future updates

      // Update the value control value
      this.sForm.get(controlName)?.setValue(value);

      // Calculate the bands based on the updated frequency range
      const minValue = this.sForm.get('minValue')?.value;
      const maxValue = this.spForm.get('maxValue')?.value;

      const minBand = this.bandToValueMap.find((b) => b.min <= minValue && b.max >= minValue)?.band ?? 1;
      const maxBand = this.bandToValueMap.find((b) => b.min <= maxValue && b.max >= maxValue)?.band ?? 6;

      // Only update bands if they actually change to avoid triggering unnecessary updates
      const currentMinBand = this.sForm.get('minBand')?.value;
      const currentMaxBand = this.sForm.get('maxBand')?.value;

      if (minBand !== currentMinBand) {
         this.sForm.get('minBand')?.setValue(minBand, { emitEvent: false });
      }

      if (maxBand !== currentMaxBand) {
         this.sForm.get('maxBand')?.setValue(maxBand, { emitEvent: false });
      }

      // Reset the flag after the update
      this.isUpdating = false;
   }

ESLint error “expected to return a value at the end of arrow function”

This function works as expected in react but i get the same ESLint error mentioned in the title. Ive checked similar questions and the format below looks to match those answer but im still getting the same error.

const getDogFields = () => {
        const dogArray = [
            {
                title: 'breed',
                value: name,
            },
        ];
    
        let newDogArray;
    
        if (!editInput?.editDogForm && dogValue?.value === 'lab') {
            newDogArray = [
                ...dogArray,
                {
                    title: 'Who walks the dog?',
                    value: whoWalksDogValue,
                },
                {
                    title: 'How old is the dog?',
                    value: dogWalkValue,
                },
            ];
        } else {
            newDogArray = [...dogArray];
        }
    
        return newDogArray;  
    };
    
   

Use Astro inferRemoteSize() when image is null, with Astro Picture component

I am using Astro Picture component.

I use inferRemoteSize(). To infer the dimensions of remote images.

But sometimes the imageUrl is null.

// MyImageComponent.astro
import { inferRemoteSize, Picture } from 'astro:assets';

const { title, imageUrl, copyright } = Astro.props;
const { width, height } = await inferRemoteSize(imageUrl);

<figure>
  <Picture
        src={imageUrl}
        alt={title}
        width={width}
        height={height}
        formats={['avif', 'webp']}
        widths={[240, 540, 720, width]}
        sizes={`(max-width: 360px) 240px, (max-width: 720px) 540px, (max-width: 1600px) 720px, ${width}px`}
      />
</figure>

How to fix this issue?

Use a tag similar to @deprecated to mark functions with restricted usage

In our app we have a few functions that are public because we need to call them from other classes, but that are meant to be used only in some specific cases because they perform sensitive operations. To decrease human error (developers using these functions when they shouldn’t), I thought it would be nice to display an ESLint error when any of these functions are used, similar to what @deprecated does. But I don’t want to use @deprecated for this because the functions aren’t deprecated.

I was thinking it would be nice to have something like this in the JSDoc of the function:

@restricted-usage Some description of why it's restricted.

When a function with this tag is used, an ESLint error should be displayed, and the dev should add eslint-disable if he really wants to use the function. I looked if I could use no-restricted-syntax for this, but I think it doesn’t capture JSDoc content.

What do you think of this approach? Is there anything I can use to achieve what I want or do I need to implement a custom eslint plugin to do this?