vs code auto completion

I followed a YouTube tutorial, but I can’t seem to get the autocomplete working as shown.

For example, in the tutorial, when typing app.listen, it automatically shows the expected parameters in gray (with autocompletion). It looks something like this:

enter image description here

However, in my VS Code, it doesn’t behave the same way. When I type app.listen, the autocompletion doesn’t appear, and I have to manually type the rest, like () => {}. It’s quite frustrating and slows me down:

enter image description here

Send a puppeteer screenshot as discord message

I am looking to send a puppeteer screenshot as attachment to discord.

I’ve been looking to posts that talk about this but nothing helped me

Here’s what I got

const url = interaction.options.getString("url");
                
const browser = await puppeteer.launch();
const page = await browser.newPage();

await page.goto(url, { waitUntil: 'networkidle2' });

const screenshot = await page.screenshot();

await browser.close();

//const image = new AttachmentBuilder(screenshot, { name: "image.png" });

await interaction.channel.send({files: [screenshot]})

await interaction.reply({
    content: `done`,
    ephemeral: true
});

When I try to build an attachment I get this

TypeError [ReqResourceType]: The resource must be a string, Buffer or a valid file stream.
    at resolveFile (E:discord botsbeta-botnode_modulesdiscord.jssrcutilDataResolver.js:105:9)
    at MessagePayload.resolveFile (E:discord botsbeta-botnode_modulesdiscord.jssrcstructuresMessagePayload.js:294:41)
    at E:discord botsbeta-botnode_modulesdiscord.jssrcstructuresMessagePayload.js:259:85
    at Array.map (<anonymous>)
    at MessagePayload.resolveFiles (E:discord botsbeta-botnode_modulesdiscord.jssrcstructuresMessagePayload.js:259:56)
    at ChatInputCommandInteraction.reply (E:discord botsbeta-botnode_modulesdiscord.jssrcstructuresinterfacesInteractionResponses.js:111:70)
    at Object.execute (file:///E:/discord%20bots/beta-bot/src/commands/match.js:289:35)
    at async Object.execute (file:///E:/discord%20bots/beta-bot/src/events/interactionCreate.js:17:5) {
  code: 'ReqResourceType'
}

and when I send the screenshot directly (like in the code I pasted above) I get this

TypeError: Cannot read properties of undefined (reading 'path')
    at findName (E:discord botsbeta-botnode_modulesdiscord.jssrcstructuresMessagePayload.js:277:17)
    at MessagePayload.resolveFile (E:discord botsbeta-botnode_modulesdiscord.jssrcstructuresMessagePayload.js:291:31)
    at E:discord botsbeta-botnode_modulesdiscord.jssrcstructuresMessagePayload.js:259:85
    at Array.map (<anonymous>)
    at MessagePayload.resolveFiles (E:discord botsbeta-botnode_modulesdiscord.jssrcstructuresMessagePayload.js:259:56)
    at TextChannel.send (E:discord botsbeta-botnode_modulesdiscord.jssrcstructuresinterfacesTextBasedChannel.js:181:50)
    at Object.execute (file:///E:/discord%20bots/beta-bot/src/commands/match.js:289:43)
    at async Object.execute (file:///E:/discord%20bots/beta-bot/src/events/interactionCreate.js:17:5)

Can somebody tell me what’s wrong ?

Estimate mousemove value input range wrong

I need to show input range value tooltip at cursor (mouse move). But after click value of input range incorrect as i saw.

Here is my code:

<div style="height: 480px; padding-top: 50px">
    <input type="range" name="timeline" id="timeline" step="0.0001" style="width: 416px">
    <div>Mouse move value: <span id="mouse"></span></div>
    <div>Input range Value: <span id="value"></span></div>
</div>
let timeline = document.querySelector('#timeline');
let value = document.querySelector('#value');
let mouse = document.querySelector('#mouse');
timeline.addEventListener("change", function(e) {
    value.innerHTML = this.value;
});
timeline.addEventListener("mousemove", function(e) {
    mouse.innerHTML = e.offsetX * 100 / e.target.clientWidth;
});

Run on jsfiddle

Lets me know where is wrong!!

Touchstart menu link not working on mobile

Burger menu not clickable on mobile. Have added touchstart to my jQuery but no luck. Can emulate on mobile view on Safari and inspect via the console there, but no real idea what I’m looking at. Any issues with my code here?

Website live at www.dannyboxer.com.au

    jQuery('.showhide').on('click touchstart', function(){
    jQuery(this).toggleClass("open");
    jQuery(".mobilenav--wrap").toggleClass( "show--mobilenav" );
    jQuery('body').toggleClass("scroll");
  });

Appointment Maker/Tracker [closed]

I’m trying to create a `script` to take input from a form, and add a `list element` to a list.

To be more specific…
Inputs:

  • Date (dd/mm/yyyy)
  • Name (text)
  • Time (hh:mm)

Results:

  • NameDate (as Tue 10/10), Time (hh:mm)

This is the div with the inputs:

  <div class="prenotazione">
    <div class="titolo">Create Appointment</div>
    <div class="inserimento">
      <label for="eventData">Date:</label>
      <input type="date" id="eventData">
      <div class="spacer"></div>
      <label for="eventPG">Name:</label>
      <input type="text" id="eventPG" placeholder="Your Name">
      <div class="spacer"></div>
      <label for="eventTime">Time:</label>
      <input type="time" id="eventTime">
      <div class="spacer"></div>
      <div class="spacer"></div>
      <div class="spacer"></div>
      <center><button id="addEvent" onclick="addEvent()">SUBMIT</button></center>
    </div>
  </div>

and this is the div with the list:

  <div class="eventi">
    <div class="titolo">Appointments</div>
    <!-- Lista delle prenotazioni -->
    <div class="scroll">
      <ul id="eventList">
        <li>
          <strong>Antonio</strong> - <i>Tue 10/10, 10:30</i>
          <button class="delete" onClick="deleteEvent()"><b>X</b></button>
        </li>
      </ul>
    </div>
  </div>

with an example of how the li should look like.

Hope this time the question is more understandable!

Menu selected item on sidebar doesn’t change background color onClick in antd design React

I have a React app where I have added a sidebar. It works onClick and screen changes perfectly. But when an item is selected in sidebar, the selected background color doesn’t change on click. After pressing on an item, it goes to the default selected item and on second press the background color works. How to fix that? Here’s what i have now:

import React, { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { PieChartOutlined, MailOutlined } from '@ant-design/icons';
import { Menu } from 'antd';
import type { MenuProps } from 'antd';
import { useWindowDimensions } from '../modules/hooks';
import profileIcon from '../assests/profileIcon.png';
import { useSelector } from 'react-redux';
import { RootState } from '~/store';

type MenuItem = Required<MenuProps>['items'][number];

const Sidebar: React.FC<{ showFlowSheets: boolean; patientData: any }> = ({
  showFlowSheets,
  patientData,
}) => {
  const [collapsed, setCollapsed] = useState(false);
  const [selectedKey, setSelectedKey] = useState<string>('1'); // Manage selected key state
  const { height } = useWindowDimensions();
  const navigate = useNavigate();
  const userState = useSelector((state: RootState) => state.user);
  const supervisorState = useSelector((state: RootState) => state.supervisor);

  const items: MenuItem[] = [
    { key: '1', icon: <PieChartOutlined />, label: 'Patients List' },
    ...(showFlowSheets
      ? [
          {
            key: 'sub1',
            label: 'Flow Sheets',
            icon: <MailOutlined />,
            children: [
              {
                key: '2',
                label: 'ADDS Chart',
                children:
                  supervisorState.isSupervisorAuthenticated && !userState.isAuthenticated
                    ? [{ key: '9', label: 'View ADDS Chart' }]
                    : null,
              },
              {
                key: '3',
                label: 'IV Fluids Chart',
                children:
                  supervisorState.isSupervisorAuthenticated && !userState.isAuthenticated
                    ? [
                        { key: '6', label: 'View IV Fluids' },
                        { key: '7', label: 'Add IV Fluids' },
                      ]
                    : null,
              },
              {
                key: 'sub2',
                label: 'Medication Chart',
                children:
                  supervisorState.isSupervisorAuthenticated && !userState.isAuthenticated
                    ? [
                        { key: '4', label: 'PRN Medicine Chart' },
                        { key: '5', label: 'Regular Medicine Chart' },
                        {
                          key: 'sub3',
                          label: 'View Student Records',
                          children: [
                            { key: '12', label: 'PRN Student Records' },
                            { key: '15', label: 'Regular Student Records' },
                          ],
                        },
                      ]
                    : [
                        { key: '10', label: 'PRN Medicine Chart' },
                        { key: '11', label: 'Regular Medicine Chart' },
                      ],
              },
            ],
          },
          {
            key: supervisorState.isSupervisorAuthenticated && !userState.isAuthenticated ? '14' : '13',
            icon: <MailOutlined />,
            label:
              supervisorState.isSupervisorAuthenticated && !userState.isAuthenticated
                ? 'View Progress Notes'
                : 'Progress Notes',
          },
        ]
      : []),
  ];

  const handleMenuClick = (e: { key: string }) => {
    setSelectedKey(e.key);

    switch (e.key) {
      case '1':
        navigate('/private');
        break;
      case '2':
        navigate('/adds-chart', { state: { patientData } });
        break;
      case '3':
        navigate('/iv-fluids-chart', { state: { patientData } });
        break;
      case '4':
        navigate('/prn-chart-sup', { state: { patientData } });
        break;
      case '5':
        navigate('/regular-chart-sup', { state: { patientData } });
        break;
      case '6':
        navigate('/view-iv-fluids', { state: { patientData } });
        break;
      case '7':
        navigate('/add-iv-fluids', { state: { patientData } });
        break;
      case '9':
        navigate('/view-adds-chart', { state: { patientData } });
        break;
      case '10':
        navigate('/prn-chart', { state: { patientData } });
        break;
      case '11':
        navigate('/regular-chart', { state: { patientData } });
        break;
      case '12':
        navigate('/prn-student-records', { state: { patientData } });
        break;
      case '13':
        navigate('/progress-notes', { state: { patientData } });
        break;
      case '14':
        navigate('/view-progress-notes', { state: { patientData } });
        break;
      case '15':
        navigate('/reg-student-records', { state: { patientData } });
        break;
      default:
        break;
    }
  };

  return (
    <div style={{ width: 305, position: 'fixed', alignSelf: 'flex-start' }}>
      <Menu
        mode="inline"
        theme="dark"
        defaultOpenKeys={['sub1','sub2','sub3','3']}
        selectedKeys={[selectedKey]} 
        inlineCollapsed={collapsed}
        items={items}
        onClick={handleMenuClick} 
        style={{ height: height - 120, backgroundColor: '#424242', paddingTop: 50 }}
      />
      <div
        style={{
          width: '100%',
          height: 50,
          backgroundColor: '#000',
          alignItems: 'center',
          display: 'flex',
        }}
      >
        <img src={profileIcon} style={{ width: 49, height: 42, marginLeft: 20 }} />
        <p style={{ color: '#fff', marginLeft: 10 }}>
          {userState.isAuthenticated ? 'Student' : 'Supervisor'}
        </p>
      </div>
    </div>
  );
};

export default Sidebar;

Blend mode difference bug in new versions of safari?

This might be a bit of an edge case, but this website I built has a kind of screensaver with blend mode difference, that gets set to 100% opacity after inactivity:

css:

#bg{
background-image:repeating-linear-gradient(black 10px, gray 16px, white 20px, black 17px);
pointer-events: none;
mix-blend-mode: difference;
width: 100%;
position: fixed;
height: 100vh;
z-index: 10;
opacity: 1;
transition: opacity 1s ease-in-out;
transform: translate3d(0,0,0);
}

script:

function startTimer() {
  clearTimeout(timeoutId);
  timeoutId = setTimeout(() => {
  (x = 1);
  document.getElementById("bg").style.transition = "opacity 1s ease-in-out"
  document.getElementById("bg").style.opacity = (x)

  }, 4000); 
}

This works fine on safari on my macbook (Version 16.1), but on later versions (17 onwards) the blend mode works on load, but after inactivity it reappears as solid despite stating “difference” when inspecting the element.
inspect element in safari

If i change a letter (still in inspect mode) and change it back to difference it updates and the effect works fine. If i change the css of the screensaver to blend-mode multiply the entire code works as it should.

I know safari has a history of trouble with difference, I tried setting background to white and applying the translate3d fix. Any ideas for workarounds? Would something like this get fixed?

Redux getState is not giving the updated state

I’m trying to get the updated state as {loading:true, users:[], error:”} after FETCH_USERS_REQUEST action but I’m getting same as an initial state , Can anyone tell me what is the issue?

const redux = require('redux');
const reduxLogger = require('redux-logger');
const createStore = redux.createStore;
const applyMiddleWare = redux.applyMiddleware
const thunkMiddleWare = require('redux-thunk').thunk
const axios = require('axios');
const logger = reduxLogger.createLogger()


const initialState={
    loading: false,
    users:[],
    error:''
}

const FETCH_USERS_REQUEST='FETCH_USERS_REQUEST';
const FETCH_USERS_SUCCESS='FETCH_USERS_SUCCESS';
const FETCH_USERS_FAILURE='FETCH_USERS_FAILURE'


const fetchUsersRequest = () => {
    console.log("asdfghjk")
    return {
        type:FETCH_USERS_REQUEST
    }
}

const fetchUserSuccess = users => {
    console.log("asdfghjk",users);
    return{
        type: FETCH_USERS_SUCCESS,
        payload: users
    }
}

const fetchUserFailure = error =>{
    return {
        type: FETCH_USERS_FAILURE,
        payload: error
    }
}

const reducer = (state= initialState, action) =>{
    switch(action){
        case FETCH_USERS_REQUEST : 
                return{
                    ...state,
                    loading:true
                }
        case FETCH_USERS_SUCCESS:
                return{
                    loading:false,
                    users: action.payload,
                    error:''
                }
        case FETCH_USERS_FAILURE:
                return{
                    loading:false,
                    users:[],
                    error: action.payload

                }
        default: return state;
    }
}

/**
 * takes a parameter dispatch
 * @returns a function, as a thunk middleware action creator it returns a function instead of action
 */

const fetchUsers =() =>{
    return function(dispatch) {
        dispatch(fetchUsersRequest());
        axios.get('https://jsonplaceholder.typicode.com/users')
            .then((response)=>{
                //response.data is the array of users
                const users = response.data.map(user => user.id);
               // console.log("users====>",users);
                dispatch(fetchUserSuccess(users));
            })
            .catch((error)=>{
                // error.message is the error descriptions
                let errorMessage = error.message;
                dispatch(fetchUserFailure(errorMessage));
            })
    }
}

const store = createStore(reducer , applyMiddleWare(thunkMiddleWare));
store.subscribe(()=>{console.log("state===>", store.getState())});
store.dispatch(fetchUsers())

Below I’m providing the logs

asdfghjk
state===> { loading: false, users: [], error: '' }
asdfghjk [
  1, 2, 3, 4,  5,
  6, 7, 8, 9, 10
]
state===> { loading: false, users: [], error: '' }

You can see the state is not updated even after getting the user data and on action FETCH_USERS_REQUEST, loading is still false, I’m not able to understand what is the issue? can anyone help me to fix this issue?

Cypress – unable to push elements to array

I am new to cypress and exploring its features. I was just trying to extract text from list of elements and save them into array. I was able to successfully extract the text but unable to push them into an array(the array returned is empty). I wasn’t sure what exactly is the issue, can someone help me understand what is the issue in the below code

    /// <reference types="Cypress"/>
    
    class HomePage {
        
        getSearchBox() {
            return cy.get('input[type="search"]')
        }
        
        performSearch(searchTerm) {
            this.getSearchBox().type(searchTerm)
        }
    
        getProductNameElements() {
            return cy.get('h4.product-name')
        }
    
        extractProductNames() {
            var products = []
            this.getProductNameElements().each(function($element) {
                var name = $element.text()
                cy.log(`Adding ${name} to the product array`)
                products.push(name)
            })
            return products
        }
    
    }

export const homepage = new HomePage()

Test that is being executed:

/// <reference types="Cypress"/>
import { homepage } from "../support/pages/homepage"

describe('Home page tests', ()=> {

  beforeEach(function() {
      cy.visit('/')
      cy.fixture('homepage-data').then(function(data) {
        this.data = data 
      })
  }) 

  it('Validate Search functionality on Home Page', function() {
      cy.log('Performing search with search term : ' + this.data.searchTerm)
      homepage.performSearch(this.data.searchTerm)
      cy.wait(1000)
      let products = homepage.extractProductNames()
      cy.log('Length of the array is ' + products.length)
      products.forEach(product => {
        cy.log(product)
      })
  })

})

Can’t use PushAPI on macOS Safari, returned endpoint is an empty string

My code works fine locally and in production with Chrome.

This is my Subscribe() function running in the browser when the user wants to enable notifications (I’m not using Apple’s APN service, but standard PushAPI).

export function Subscribe(vapid: string): Promise<PushSubscription> {
    return new Promise((resolve, reject) => {
        if (!vapid) {
            reject("VAPID not declared")
        }

        navigator.serviceWorker.getRegistration()
        .then((registration) => {  
            if (!registration) {
                return
            }
            registration.pushManager.subscribe({
                userVisibleOnly: true,
                applicationServerKey: urlBase64ToUint8Array(vapid),
            }).then((subscription) => {
                console.log(subscription)
                if (!subscription) {
                    reject(new Error("Unable to subscribe (empty subscription)"))
                }
                if (subscription.endpoint === "") {
                    reject(new Error("Unable to subscribe (empty endpoint)"))
                }
                resolve(subscription)
            })
        })
        .catch((err) => {
            reject(err)
        });
    })
}

The browser asks for user’s permission, no problem there, then when trying to subscribe, the payload I’m getting is this :

PushSubscription {endpoint: "", expirationTime: null, options: PushSubscriptionOptions, getKey: function, unsubscribe: function, …}

Stringified:

{
  "keys":{
    "p256dh":"",
    "auth":""
  }
}

As you can see, there is no error, but the endpoint is empty as well as the keys.

  • It works on a different machine when I ask someone to test
  • I can use this test page without issues : https://www.bennish.net/web-notifications.html (but I couldn’t until I deleted ~/Library/Safari/RemoteNotifications/Permissions.plist), but I think it’s using a different API and those are not server-side pushed notifications.
  • I can not use the following site https://cleverpush.com/en/test-notifications/, I get an “undefined” alert when sending a notification. In debugger I see similarities with the payload being sent to their server :
{
  "endpoint":"",
  "publicKey":"",
  "authSecret":""
}

It looks like a weird issue on my system, but couldn’t figure out what is the problem.

I should add that this machine is under enterprise management, but they say they don’t have policies to block push notifications.

Extract some values from string

I receive text from response:

const prompt = "Generate something in 1:1 format for `Birthday` in an `cheerful, celebratory` mood. The image should be created in an `Graffiti` style. The text `Happy Birthday!` is at the top. At the bottom is the lettering: `Liam`. Graphic elements should visually reflect the terms `stars, balloons`.";

and have string without values ready:

const sub = "Generate something in 1:1 format for in an mood. The image should be created in an style. The text is at the top. At the bottom is the lettering:. Graphic elements should visually reflect the terms.";

Is there a way to extract marked words (which will be used to prefil some input fields)?

I managed to do that only if the words are quoted like:

const sub = "Generate something in 1:1 format for in an mood. The image should be created in an style. The text is at the top. At the bottom is the lettering:. Graphic elements should visually reflect the terms."

const prompt = "Generate something in 1:1 format for 'Birthday' in an 'cheerful, celebratory' mood. The image should be created in an 'Graffiti' style. The text 'Happy Birthday!' is at the top. At the bottom is the lettering: 'Liam'. Graphic elements should visually reflect the terms 'stars, balloons'."

const resolvePrompt = (prompt, sub) => {
  return prompt
    .replaceAll(".", "")
    .split(" ")
    .filter((wd) => !sub.includes(wd))
    .join("")
    .split("''");
};
  
console.log(resolvePrompt(prompt, sub))

svelte page/component caching issue with shared navbar component

I am developing a website currently, and have run into a small problem.

===

Steps to reproduce:

1.npm create svelte@latest test (skeleton, typescript, eslint-prettier-playwright-vitest)

2.cd test

3.npm i

4.npm run dev -- --open (to open in browser for debugging)

5.Create src/components/Navbar.svelte with the following contents:

<script lang="ts">
    import { onMount } from 'svelte';

    function toggleHamburgerMenu() {
        var x = document.getElementById('myLinks') as HTMLDivElement;
        if (x.style.display === 'block') {
            x.style.display = 'none';
        } else {
            x.style.display = 'block';
        }
    }

    function getTranslatedPagePath(): string {
        switch (window.location.pathname) {
            case '/':
                return 'nav.about';
            case '/services':
                return 'nav.services';
            case '/updates':
                return 'nav.updates';
            case '/photos':
                return 'nav.photos';
            case '/contact':
                return 'nav.contact';
            case '/links':
                return 'nav.links';
            default:
                return '';
        }
    }

    $: currentTab = 'nav.about';
    onMount(() => {
        currentTab = getTranslatedPagePath();

        function closeTopnav(this: HTMLAnchorElement) {
            var x = document.getElementById('myLinks') as HTMLDivElement;
            x.style.display = 'none';

            currentTab = this.innerHTML;
        }

        // topnav doesnt close automatically when clicking on a link
        const links = document.getElementsByClassName('topnav_link') as unknown as HTMLAnchorElement[];
        for (let i = 0; i < links.length; ++i) {
            links[i].addEventListener('click', closeTopnav);
        }

        // hide topnav when clicking outside
        document.addEventListener('click', (e: MouseEvent) => {
            var x = document.getElementById('topnav-wrapper') as HTMLDivElement;
            var y: Node = e.target as Node;
            var z = document.getElementById('myLinks') as HTMLDivElement;
            if (!x.contains(y) && z.style.display == 'block') {
                z.style.display = 'none';
            }
        });
    });
</script>

<head>
    <link
        rel="stylesheet"
        href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.2/css/all.min.css"
    />
</head>

<div id="topnav-wrapper">
    <div>
        <a href="/"><img src="" alt="Logo" /></a>
    </div>
    <div class="topnav">
        <div id="content">
            <a href="" class="active">{currentTab}</a>
            <a href="" class="icon" on:click={toggleHamburgerMenu}>
                <i class="fa fa-bars"></i>
            </a>
        </div>
        <div id="myLinks">
            {#each 'about, services, updates, photos, contact, links'.split(', ') as link}
                {#if `nav.${link}` !== currentTab}
                    <a class="topnav_link" href="/{link === 'about' ? '' : link}">{`nav.${link}`}</a>
                {/if}
            {/each}
        </div>
    </div>
</div>

<style>
    #topnav-wrapper {
        display: flex;
        flex-direction: row;
        justify-content: space-between;
        align-items: center;

        position: fixed;
        top: 0;
        left: 0;
        width: 100%;

        overflow: visible;

        z-index: 100;

        /* background-color: rgba(255, 255, 255, 0.6); */
        margin: 0;
        padding: 0;
    }

    .topnav {
        overflow: hidden;
        /* background-color: #333; */

        /* width: fit-content; */
        /* height: fit-content; */

        margin: 1.5rem;
    }

    /* Hide the links inside the navigation menu (except for logo/home) */
    .topnav #myLinks {
        display: none;

        position: absolute;
        top: inherit;
        left: inherit;
        background-color: #333;
        pointer-events: all;
    }

    /* Style navigation menu links */
    .topnav a {
        color: white;
        padding: 14px 16px;
        text-decoration: none;
        display: block;

        /* width: fit-content; */
        background-color: rgba(255, 255, 255, 0.74);
        color: black;
        font-size: 1.5rem;
    }

    /* Style the hamburger menu */
    .topnav a.icon {
        background: black;
        display: block;
    }

    /* Add a grey background color on mouse-over */
    .topnav a:hover {
        background-color: #ddd;
        color: black;
    }

    /* Style the active link (or home/logo) */
    .active {
        background-color: rgb(135, 206, 235);
        color: white;
    }

    img {
        position: absolute;
        top: 0;
        left: 0;
    }

    #content {
        display: flex;
    }

    #logo {
        background-color: white;
        opacity: 70%;
    }

    @media screen and (min-width: 320px) {
        #logo,
        img {
            width: 115px;
            height: 50px;
            margin-left: 15px;
        }
        img {
            top: 20px;
        }
    }

    @media screen and (min-width: 520px) {
        #logo,
        img {
            width: 135px;
            height: 55px;
        }
        img {
            top: 20px;
        }
    }

    @media screen and (min-width: 720px) {
        #logo,
        img {
            width: 155px;
            height: 65px;
            margin-top: 10px;
        }
        img {
            top: 15px;
        }
    }

    @media screen and (min-width: 920px) {
        #logo,
        img {
            width: 175px;
            height: 70px;
        }
        img {
            top: 10px;
        }
    }

    @media screen and (min-width: 1120px) {
        #logo,
        img {
            width: 195px;
            height: 75px;
            margin-top: 20px;
        }
        img {
            top: 10px;
        }
    }

    @media screen and (min-width: 1320px) {
        #logo,
        img {
            width: 215px;
            height: 80px;
        }
        img {
            margin-top: 5px;
        }
    }

    @media screen and (min-width: 1520px) {
        #logo,
        img {
            width: 235px;
            height: 90px;
        }
        img {
            top: 10px;
        }
    }

    @media screen and (min-width: 1720px) {
        #logo,
        img {
            width: 255px;
            height: 100px;
            margin-top: 20px;
        }
        img {
            top: 10px;
        }
    }

    @media screen and (min-width: 1920px) {
        #logo,
        img {
            width: 275px;
            height: 110px;
            margin-top: 20px;
        }
        img {
            top: -10px;
        }
    }

    img {
        top: 0px; /* TODO: responsive */
        margin-top: 0px;
    }

    #content a {
        background-color: transparent;
        color: black;
        font-size: 1.5rem;
    }
</style>

6.Create src/routes/+layout.svelte :

<script>
    import Navbar from '../components/Navbar.svelte';
</script>

<Navbar />
<slot />

7.Create /(about), services, updates, photos, contact, links routes with a simple h1 to mention the page title to easily understand which route we are in.

8.Go to the browser tab, open the burger menu on the top right, click through every link. Afterwards, if you try to click any of them, the title will not update, the links list will not update deleting the current page link, and the burger meu will not close(but we will go to correct page).

===

The problem I have is that after the first iteration through every link in the navbar, they get cached (or something along those lines I am not quite sure of the underlying mechanisms of svelte) and when I try to click them again:

  1. The navbar currentTab title doesn’t update,
  2. The links dont get updates, so I see the link of the currentTab which I shouldn’t

The common thing in both those problems is currentTab, I tried to make it a simple var to see if it changes anything but it doesn’t so I kinda run out of ideas.

Anybody knows how to fix this?

Expected:

  1. The navbar component to update on each <a> link click, so the title and the list of links update (and the burger menu to close).

Monaco Editor add javascript display inside json property

I have a json file that contain at some places a “eval” property that contain javascript code. My goal is to be able to have it display like it’s was a javascript file.

This is an example file :

{
  "fn": "zcl:attr",
  "ep": 1,
  "cl": "0x0000",
  "at": "0x000A",
  "eval": "Item.val = Attr.val"
}

Here the code Item.val = Attr.val is javascript

I tried some suggestion made by copilot but did not get a good result;

    monaco.languages.setMonarchTokensProvider('json', {
      tokenizer: {
        root: [
          [/"eval"s*:s*"(.*)"/, {
            token: 'source.js',
            nextEmbedded: 'javascript',
            log: 'eval detected',
          }],
          [/"[^"]*"/, 'string'],
          [/bd+b/, 'number'],
          [/[{}[],]/, 'delimiter'],
          [/:/, 'delimiter.colon'],
          [/s+/, 'white'],
        ],
      },
    })

I also did some researchs on existing code but found nothing that I was able to make it work

Why does my Chrome Extension’s counter variable not change properly?

I’m working on a chrome extension that simply checks if a webpage is clicked and then adds 1 to a locally stored variable and displays it in the popup. However, the problem that I have is when I reload / install the extension it required for all existing tabs to be reloaded / opened again to actually count the clicks made on those webpages. If I don’t reload the website and click, it returns the error Uncaught (in promise) Error: Extension context invalidated. Even if I reload the website and start clicking, it only is able to edit the badge 1 time no matter how many times I click the webpage. This issue only goes away when I open the popup as a new tab and inspect it for some reason. How can I fix these issues? (Side note: I’m not sure if I actually need to send a message to the service worker in the beginning and I marked with the comment “Probably Useless”. Do I actually need this?)

manifest.json:

{
    "manifest_version": 3,
    "version": "1.0",
    "name": "Clicking game",
    "description": "All clicks on Chrome add 1 to a counter in the popup",
    "permissions": ["storage", "scripting", "activeTab"],
    "background": {
        "service_worker": "service-worker.js"
    },
    "action": {
        "default_popup": "index.html",
        "default_popup_open_in_tab": true
    },
    "content_scripts": [{
        "matches": ["<all_urls>"],
        "js": ["content.js"]
    }]
}

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Clicking Game</title>
</head>
<body>
    <h1 id="counter">0</h1>
    <script src="popup.js"></script>
</body>
</html>

content.js

document.onclick = log;

async function log() {
    const response = await chrome.runtime.sendMessage({ type: "click" });
    console.log(response);
    const message = chrome.runtime.sendMessage({ type: "update", count: "5"});
    console.log(message);
}

popup.js

// Grabbing the popup element to display cookies
const countElement = document.getElementById("counter");

// Updating the popup when it is opened
document.addEventListener('DOMContentLoaded', function() {
    chrome.storage.local.get(['count'], function(result) {
        if (result.count) {
            countElement.textContent = result.count;
        }
    });
});

// Updating number of coookies when user clicks something
chrome.runtime.onMessage.addListener(
    async (request, sender, sendResponse) => {
        if (request.type === "update") {
            let cookies = await chrome.runtime.sendMessage({ type: "returnAndAddToCookies" });
            console.log("Update Message Received");
            console.log("Updated Cookies: " + cookies);
            chrome.storage.local.get(["count"]).then((result) => {
                countElement.innerText = result.count;
                console.log("Value is " + result.count);
            });
        }
    }
)

service-worker.js

// Cookies Variable
let cookies = 0;

// Updating cookies if there is already a value in local storage
chrome.storage.local.get(["count"]).then((result) => {
    if (result.count !== undefined) {
        cookies = result.count;
    }
    console.log("Cookie is " + cookies);
});

// Updating the badge text on reloading / installing / restarting the extension
chrome.runtime.onStartup.addListener(() => {
    chrome.action.setBadgeText({
        text: cookies.toString()
    });
});

chrome.runtime.onInstalled.addListener(() => {
    chrome.action.setBadgeText({
        text: cookies.toString()
    });
});

// Function to activate the service worker, probably useless
chrome.runtime.onMessage.addListener(
    function (request, sender, sendResponse) {
        if (request.type === "click") {
            console.log("Click request received");
            sendResponse({farewell: "goodbye"});
            // Returning the value of cookies for the service worker to display on the badge
        }
    }
)

chrome.runtime.onMessage.addListener(async (request, sender, sendResponse, tab) => {
    // Changing the badge text
    if (request.type === "update") {
        await chrome.action.setBadgeText({
            text: (cookies + 1).toString()
        })
    } else if (request.type === "returnAndAddToCookies") {
        cookies++;
        chrome.storage.local.set({ count: cookies }).then(() => {
            console.log("Updated Value");
        });
        sendResponse(cookies);
    }
})

I’ve tried manually injecting the scripts into all tabs when the extension is installed / reloaded / updated etc. (Maybe this works? If so, could someone send a code snippet?) I’ve tried removing the console logs to solve the second problem.

Mongoose how to paginate with id using $lt

I’m working on a pagination implementation using MongoDB’s aggregation pipeline. Specifically, I want to paginate articles by fetching only documents with _id values less than a given after value (for “load more” behavior). I implemented this using $match with a filter like { _id: { $lt: new ObjectId(after) } }, and it works fine with find() but returns an empty array when applied inside an aggregation pipeline.

Here’s my current pipeline:

const query = after ? { _id: { $lt: new mongoose.Types.ObjectId(after) } } : {};

articleModel.aggregate([
  { $match: query },
  { $sort: { createdAt: -1 } },
  { $limit: 10 },
  {
    $lookup: {
      from: 'users',
      localField: 'owner',
      foreignField: '_id',
      as: 'doctorInfo'
    }
  },
  { $unwind: { path: '$doctorInfo', preserveNullAndEmptyArrays: true } }
]);

This setup results in an empty response, even though there are documents with _id values less than the specified after value. I’m not sure why this is happening since the same logic works perfectly with find() queries.

I initially thought the issue might be with how I’m constructing the $match query, so I hardcoded it like this:

{ _id: { $lt: new mongoose.Types.ObjectId('64f1b28bfaf999c9a7bf3d21') } }

Still, I got an empty array even though documents with _id values less than that one exist in the collection.

I checked if the issue was related to the order of stages in my aggregation pipeline. I also tried moving the $match stage to different positions in the pipeline, but the result remained the same.

I expected the aggregation query to return documents like how it works with find(), but it seems the pipeline doesn’t respect the _id filtering when used with aggregation.

I found this discussion suggesting facet-based pagination, but I’m not sure if that’s the best approach or how exactly to implement it for my use case.