@react-spring/web + children not defined

Running into this strange error using @react-spring/web

import { PropsWithChildren, ReactNode } from 'react'
import { useSpring, animated } from '@react-spring/web'
import useMeasure from 'react-use-measure'

export interface ExpandableCardProps {
    open: boolean
    content: ReactNode
}

export function ExpandableCard({ open, content, children, ...rest }: PropsWithChildren<ExpandableCardProps>) {
    const [ref, { height }] = useMeasure()

    const slideAnimation = useSpring({
        height: open ? height : 0,
        config: {
            tension: 500,
            friction: 50,
        },
    })

    return (
        <div className="shadow-md flex flex-col rounded-size-6 bg-[var(--bg-secondary)] overflow-hidden" {...rest}>
            <div className="rounded-size-6 bg-[var(--bg-primary)] shadow-xs">{children}</div>

Type '{ children: Element; style: { overflow: "hidden"; height: SpringValue<number>; }; }' is not assignable to type 'IntrinsicAttributes & AnimatedProps<{ style?: { accentColor?: AccentColor | undefined; alignContent?: AlignContent | undefined; alignItems?: AlignItems | undefined; ... 841 more ...; matrix3d?: readonly [...] | undefined; } | undefined; }> & { ...; }'.
  Property 'children' does not exist on type 'IntrinsicAttributes & AnimatedProps<{ style?: { accentColor?: AccentColor | undefined; alignContent?: AlignContent | undefined; alignItems?: AlignItems | undefined; ... 841 more ...; matrix3d?: readonly [...] | undefined; } | undefined; }> & { ...; }'

            <animated.div style={{ ...slideAnimation, overflow: 'hidden' }}>
                <div ref={ref} className="rounded-b-size-6">
                    {content}
                </div>
            </animated.div>
        </div>
    )
}

Everytime I try to import animated or a I get the same issue

How to customize a vue.js component, passing through dynamic slots

I’m building a vue.js component that wraps around a vuetify data table. I’ve added props so I can make it fetch data from different sources – and that data will have different columns.

It’s supposed to be used like this:

<FancyTable endpoint="/api/buildings" />
<FancyTable endpoint="/api/persons" />

Here’s a simplified version of the component:

<template>
  <v-data-table-server
    :items="items"
    :items-length="totalItems"
    @update:options="fetchData"
    item-key="id"
  >
    <template #[`item.address_type`]="{ item }">
      <building-icon :icon="item.address_type"></building-icon>
    </template>
  </v-data-table-server>
</template>

<script>
import BuildingIcon from '@/components/BuildingIcon.vue'
import { VDataTableServer } from 'vuetify/components'

export default {
  name: 'FancyTable',
  components: { BuildingIcon, VDataTableServer },
  data: () => ({
    totalItems: 0,
    items: [],
    options: {}
  }),
  props: {
    endpoint: {
      type: String,
      required: true
    }
  },
  watch: {
    options: {
      handler() {
        this.fetchData()
      },
      deep: true
    }
  },
  methods: {
    fetchData: function () {
      const { sortBy, sortDesc, page, itemsPerPage } = this.options
      // here, we would fetch data from an actual backend, using the sort and filter options
      console.log('fetching / faking results from: ', this.endpoint)
      let fake_backend_results = []
      let fake_backend_count = 0
      if (this.endpoint === '/api/buildings')
      {
        fake_backend_results = [
          { id: 0, address_type: 'building', address: 'Berliner Tor 13' },
          { id: 1, address_type: 'building', address: 'Berliner Tor 15' },
          { id: 2, address_type: 'cabinet',  address: 'Berliner Tor 17' },
          { id: 3, address_type: 'cabinet',  address: 'Berliner Tor 19' },
          { id: 4, address_type: 'booth',    address: 'Berliner Tor 21' }
        ]
        fake_backend_count = 27
      } else if (this.endpoint === '/api/persons') {
        fake_backend_results = [
          { id: 35, first_name: 'Jane', last_name: 'Doe' },
          { id: 36, first_name: 'John', last_name: 'Doe' }
        ]
        fake_backend_count = 2
      }
      this.items = fake_backend_results
      this.totalItems = Number(fake_backend_count)
    }
  }
}
</script>

Now, this works fine as it is, but it is not as generic as I like it to be: The <template> block that customizes the .address_type column is the part that I’d like to insert that from the outside, like this:

<FancyTable endpoint="/api/buildings">
  <template #[`item.address_type`]="{ item }">
    <building-icon :icon="item.address_type"></building-icon>
  </template>
</FancyTable>

How would I pass down dynamic slots like these to the VDataTableServer? I assume that a solution would revolve around a v-for with a <template><slot /></template> construct, but I cannot figure out how to do that correctly.

How to change system volume level

Hi I am currently trying to moddify the react-carplay code with a new ui and more fonctionnalities to make a carplay powered radio for my car. This would use a rpi5 and right now what im trying to do is to have 3 buttons to control the volume/mute/unmute of the rpi but all modules that i found like loudness or volume-suppervisor or another one that i cant remember all require child_process which was removed from npm and github so I cant use those

How can I change the system volume in my project ?

Echarts how to capture click on areaStyle of a stacked line chart

As per subject I want to capture the click on the area not the line data point.
Here is an example of the chart I want to capture the click on the area not the line data point of the chart: https://codesandbox.io/p/sandbox/ndzk7l
Example of the AreaStyle
When I click on the line data points I get console logged the params object but not when I click on the area.
Anyone knows how to achieve this with an echarts line chart?

What is the use case for navigator.keyboard.lock() / navigator.keyboard.unlock()?

I was looking through the MDN Web APIs, and I stumbled across navigator.keyboard. I could see a use for Keyboard.getLayoutMap(), with setting up controls for games, or fingerprinting, however, I could not think of a use for Keyboard.lock() / .unlock(). From the MDN Web Docs,

Keyboard.lock() Experimental
The lock() method of the Keyboard interface returns a Promise that resolves after enabling the capture of keypresses for any or all of the keys on the physical keyboard. This method can only capture keys that are granted access by the underlying operating system.
If lock() is called multiple times then only the key codes specified in the most recent call will be locked. Any keys locked by a previous call to lock() are unlocked.

From this, I made the assumption that it would lock key presses from being registered, but upon setting this simple setup, I saw the keys were still being registered.

<input>
<script>navigator.keyboard.lock()</script>

I know that these are still experimental, and are subject to change, but could anyone elaborate on how to use Keyboard.lock() and what use cases it has.

I searched online, but the only thing I could find for Keyboard.lock() was the MDN Web Doc itself.

NextJS generateMetadata is rendering outside of the tag

I’m having SEO issues with a nextJS app where the meta data is being outputted outside of the body tag. I have this bit of code in my page.tsx file

export async function generateMetadata(
    { params, searchParams }: Props,
    parent: ResolvingMetadata
): Promise<Metadata> {
    void searchParams;
    void parent;
    const {business, city, category} = await params

    return await generateBusinessMetadata({
        businessSlug: business,
        city: city,
        category: category,
    });
}

inside generateBusinessMeta data there is a supabase data fetch.

Weirdly, if I hard refresh the meta data shows in the head, but when I do a normal refresh it moves down below the script tags at the bottom of the page. This is causing all sorts of issues with SEO, and my impressions have plummeted, any ideas what is going on?

I’m using the app router on Next 15.2.3

Ipad focus Issue

let isTouching = false;
let lastFocusedInput = null;

document.addEventListener('touchstart', (event) => {
    if ((event.target.matches('input[type="text"]') || event.target.matches('textarea')) && (!event.target.classList.contains('dc-field-alert-flag'))) {
        isTouching = true;
        if (lastFocusedInput !== event.target && lastFocusedInput !== null) {
            lastFocusedInput.blur();
        }
        lastFocusedInput = event.target;
        event.target.focus();
    } else {
        isTouching = false;
    }
});

document.addEventListener('touchend', (event) => {
    isTouching = false;
});

document.addEventListener('focusout', (event) => {
    if (isTouching && (event.target.matches('input[type="text"]') || event.target.matches('textarea')) && (!event.target.classList.contains('dc-field-alert-flag'))) {
        event.preventDefault();
        event.target.focus();
    }
});

this code is blocking the keyboard to come and going when the textare is moved to bottom and touch means but when we move the textarea to up and touch means the keyboard is coming correctly

Playwright Error when clicking Anchor Element

I have following anchor Element on the page for which I am writing Playwright Tests

 <a _ngcontent-ng-c643490139="" mat-menu-item="" tabindex="0" class="mat-mdc-menu-item mat-mdc-focus-indicator ng-tns-c2786309385-2 ng-star-inserted" href="/event-partner" role="menuitem" aria-disabled="false" style="">
<span class="mat-mdc-menu-item-text"><span _ngcontent-ng-c643490139="">Eventpartner</span></span><div matripple="" class="mat-ripple mat-mdc-menu-ripple"></div>
<!---->
</a>

Its an anchor Tag with a role of menuitem. Accessing it via following locator should work:

await page.getByRole('menuitem', { name: 'Eventpartner' }).click();

But I get the following error in my Test:

Error: locator.click: Test timeout of 30000ms exceeded.

Call log:

  • waiting for getByRole(‘menuitem’, { name: ‘Eventpartner’ })
    • locator resolved to …
  • attempting click action
    2 × waiting for element to be visible, enabled and stable

    • element is visible, enabled and stable
    • scrolling into view if needed
    • done scrolling
    • … from … subtree intercepts pointer events
    • retrying click action
    • waiting 20ms
    • waiting for element to be visible, enabled and stable
  • element was detached from the DOM, retrying

How can I fix this issue?

The website here removes the Element referred to by locator resolved to in the above error message.

<a tabindex="0" role="menuitem" mat-menu-item="" href="/event-partner" aria-disabled="false" _ngcontent-ng-c2888663785="" class="mat-mdc-menu-item mat-mdc-focus-indicator ng-tns-c2786309385-2 ng-star-inserted">…</a>

Trying to use Mutation Observer, handling “dynamic” objects for page-switching effect

I have a mutation observer set up – it’s meant to track changes in the amount of elements added to a div “box” on the page, and if there are too many visible elements added (more than 6), it’s supposed to add page navigation buttons which would allow to switch between page 2 (elements beyond the 6th one) and back to page one (which shows first 6 elements).

This is achieved by first setting up this “storage” object outside of the mutation observer:

storedNodes = {
    nodesToStay: {
    }, 
    nodesToMove: {
    }
}

Then I make an array by using querySelectorAll on all nodes within this box that fit the “visible” requirement like this: const elementsToStay = Array.from(textField.querySelectorAll(":scope > div:not(.gone)")) and get their IDs with this mapping method: idOfStayingElements = elementsToStay.map(node => node.id)

After that, I sort my nodes like this:

if (elementsToStay.length > 0) {
  for (let i = 0; i < Math.min(6, elementsToStay.length); i++) {
      storedNodes["nodesToStay"][elementsToStay[i].id] = elementsToStay[i];
  }
}

if (elementsToStay.length > 6) {
   const elementsToMove = elementsToStay.slice(6);
   idOfMovedElements = elementsToMove.map(node => node.id);

   for (let i = 0; i < elementsToMove.length; i++) {
        storedNodes["nodesToMove"][elementsToMove[i].id] = elementsToMove[i];
        document.getElementById(idOfMovedElements[i])?.remove();
        delete storedNodes["nodesToStay"][elementsToMove[i].id];
   }
}

Once the amount of keys in the storedNodes[“nodesToMove”] gets to 1 or more, I add page navigation with event listeners.

If “page 2” or “page 1” button is clicked, I use the replaceChildren() on the box holding elements to remove all previously present nodes.

Page 1 button is only supposed to be visible if we’re viewing the second ‘page’ (to allow us to go back to ‘staying’ elements), and Page 2 button is only supposed to be visible if we’re on first ‘page’.

When page 1 is clicked, this happens:

pageOne.classList.add("invisible");
pageTwo.classList.remove("invisible");
for (let id of idOfStayingElements) {
    if (storedNodes["nodesToStay"][id]) {
       textField.appendChild(storedNodes["nodesToStay"][id]);
    }
} 

When page 2 is clicked, this happens:

pageOne.classList.remove("invisible");
pageTwo.classList.add("invisible");
for (let id of idOfMovedElements) {
        if (storedNodes["nodesToMove"][id]) {
           textField.appendChild(storedNodes["nodesToMove"][id]);
        }
    }

Invisible class sets opacity to 0 and visibility to hidden.

The problem is, page 1 event listener doesn’t actually do anything, even though page 2 button works as intended.

As I’ve tested this further, I see that the issue lies specifically in this line: elementsToStay = Array.from(textField.querySelectorAll(":scope > div:not(.gone)"))
As once we get to the next page, all child elements of textField get removed, and we’re only left with elements that were previously stored within elementsToMove… so that becomes the new contents of elementsToStay

I’ve tried to fix this logic by instead making an “allElements” array where format the above-mentioned nodeList, and then tried to extract 1 to 6 elements from allElements to our elementsToStay, but that didn’t fix this behavior as it’s doing the same thing that we were doing before, but in more steps.

At the moment I just need to figure out proper logic for “remembering” what was on the first page, but I’m a bit lost for how I can achieve that at this point.

Here’s the relevant bit of code: https://jsfiddle.net/nj6zk5de/

Here’s the code in bigger scheme of things (starts from line 1477): https://github.com/pilzpuffer/etch-a-sketch/blob/main/script.js

Convert Markdown response to HTML

I am getting the output from API in markdown where it could have nested list data and when I am converting this markdown to html it makes all the (-) in list and do not create nested list if there was my output from API is

so please provide me a js function to convert this md to html

TypeScript errors with react-webcam in React application

I’m encountering TypeScript errors when using react-webcam in my React TypeScript project. I’ve followed the official documentation, but I’m still getting Type errors.

Errors

  1. First webcam error:

    Cannot use namespace 'Webcam' as a type.ts(2709)

  • Source of the error:
const webcamRef = useRef<Webcam>(null);
2. *Second webcam error*:

JSX element type 'Webcam' does not have any construct or call signatures.ts(2604) 'Webcam' cannot be used as a JSX component.

My codes:

import React, { useRef } from 'react';
import Webcam from 'react-webcam';


function MyComponent() {
  // Type errors occur here
  const webcamRef = useRef<Webcam>(null);
  
  
  const captureImage = () => {
    if (webcamRef.current) {
      const imageSrc = webcamRef.current.getScreenshot();
      // Do something with imageSrc
    }
  };
  
  return (
    <div>
      {/* TypeScript complains about these components */}

      <Webcam  {/* Second react-webcom occurs here */}
        audio={false}
        ref={webcamRef}
        screenshotFormat="image/jpeg"
        videoConstraints={{ facingMode: 'environment' }}
      />
    </div>
  );
}

I’ve tried importing the types in various ways but haven’t found a solution. Any ideas what might be causing these TypeScript errors?

Problem with slider(Splidejs) scrolling using touchpad on macOS

I made a slider using splidejs, but ran into a problem: on macOS, the slider doesn’t scroll with a horizontal touchpad swipe, even though everything works fine on Windows. What is the problem? Here is an example on jsfiddle: https://jsfiddle.net/p039k4cu/4/

const splide = document.querySelector('.slider');

const interval = 5000; // The autoplay interval duration in milliseconds 
const speed = 1000; // Slider transition speed in ms
const dragMinThreshold = { // Minimum distance in pixels to start dragging
  mouse: 0,
  touch: 10,
};
const flickPower = 500; // Determine the power of "flick". The larger number this is, the farther the carousel runs.
const wheelMinThreshold = 20; // The threshold to cut off the small delta produced by inertia scroll.
const wheelSleep = 500; // The sleep duration in milliseconds until accepting next wheel.

const splideInstance = new Splide(splide, {
  autoWidth: true,
  arrows: false,
  pagination: false,
  updateOnMove: true,
  autoplay: false,
  interval,
  perPage: 1,
  type: 'loop',
  gap: '1rem',
  drag: true,
  dragMinThreshold,
  flickMaxPages: 1,
  flickPower,
  speed,
  snap: false,
  wheelMinThreshold,
  wheelSleep,
});

let lastTime = 0
function onWheel(e) {
  if (e.cancelable) {
    const { deltaX } = e;
    const backwards = deltaX < 0;
    const timeStamp = e.timeStamp;
    const min = splideInstance.options.wheelMinThreshold || 20;
    const sleep = splideInstance.options.wheelSleep || 300;

    if (Math.abs(deltaX) > min && timeStamp - lastTime > sleep) {
      splideInstance.go(backwards ? '<' : '>');
      lastTime = timeStamp;
    }
  }
}

splide.addEventListener('wheel', onWheel);

splideInstance.mount();

PS: I don’t have any macOS device, so I cannot debug. Any help will be very much appreciated.

How do i resolve this drive error issue on my appscript ? How do i improve this program so it can take more large array (can take 40 index on array)?

i have this code that can copy and edit spreadsheet in the same parent folder. A few months ago it still work but now i get this error message “Exception: Service error: Drive“. Here’s the code

var outlet = [
["p1", "place1", "great place 1"], 
["p2", "place2", "great place 2"],
];

function looping() {
    for (var i = 0; i < outlet.length; i++) {
      duplicate(outlet[i][2], i);
      Logger.log(outlet[i][1]);
    }
}

function duplicate(nama, i) {
  const ss = SpreadsheetApp.getActiveSpreadsheet();
  const ssid = ss.getId();
  const ssdrive = DriveApp.getFileById(ssid);
  const parent = ssdrive.getParents().next();

  const newss = ssdrive.makeCopy(nama, parent);
  const newurl = newss.getUrl();

  modify(newurl, i);
  debugger;
}

function modify(url, i) {
  const ssopen = SpreadsheetApp.openByUrl(url);
  const range1 = ssopen.getRange("A1");
  const range2 = ssopen.getRange("A2");
  const toko = ssopen.getDataRange();
  const real = outlet[i][1].replace("SPOKE SMG ","").replace(" ","")

  range1.setValue(outlet[i][0]);
  range2.setValue(outlet[i][1]);
  ssopen.setNamedRange(real, toko);
  Logger.log(outlet[i][0]);
  debugger;
}

sorry for the messy language

Scenario reads old data from the previous run

What I am trying to achieve is that it should filter users’ data in the first scenario which is currently working well and save in csv file which is also working.
When the 2nd scenario execution begins, it should read filtered data and run tests. This is not working as expected as it reads old data from the previous run. I have to run test twice for the desired result.

I am currently facing this challenge and wondering if you might be able to help me out. I’d appreciate any guidance or advice you could offer. Please suggest some better way of doing it. I have an alternative approach to handle this using

gauge.dataStore.scenarioStore.put("filteredUsers", filteredUsers).

But I want to see if the same can be achieved with csv as DataStore makes troubleshooting harder if there are many rows in a table. Thanks.

This is my spec file written in Gauge.

The problem lies in scenario 2
table: test_dataQA3users.csv

# Verify users
tags: filter

// scenario 1
## Populate CSV with users based on role
* Filter users data based on role
    |id     |name       |role       |
    |-------|-----------|-----------|
    |1      |Alice      |admin      |
    |2      |John       |editor     |
    |3      |Bob        |admin      |
    |4      |Shawn      |subscriber |
    |5      |Eve        |admin      |
    |6      |Tom        |editor     |
    |7      |Jenny      |author     |   

// scenario 2
## Verify the filtered users
table: test_dataQA3users.csv
* Show filtered users based on role on the console <id>, <name>, <role>

———————STEP IMPLEMENTATION———————-

"use strict"

const fs = require('fs');
const path = require('path');
const csv = require('csv-parser');

const filePath = path.join(process.cwd(), "test_data/QA3/users.csv");

beforeSpec(() => {
    if(fs.existsSync(filePath)) {
        // delete the existing file if it exists
        fs.unlinkSync(filePath);
        console.log("Deleted existing csv file");
    }
}, {tags: ["filter"]});

step("Filter users data based on role <table>", async (table) => {
    let testData = [];

    for(let i=0;i<table.rows.length;i++) {
        let obj = {
            id: table.rows[i].cells[0],
            name: table.rows[i].cells[1],
            role: table.rows[i].cells[2]
        }
        
        testData.push(obj);
    }

    console.log(testData)

    console.log(`ROLE from env: ${process.env.ROLE}`);

    let selectedRoles = process.env.ROLE ? process.env.ROLE.split(",").map(role => role.trim().toLowerCase()) : [];

    let filteredUsers;
    if(selectedRoles.length === 0) {
        console.log("No Role specified. Loading all users data");
        filteredUsers = testData; // Run all users data
    }else {
        console.log(`Filtering users based on roles: ${selectedRoles.join(",")}`);
        filteredUsers = testData.filter(user => selectedRoles.includes(user.role.toLowerCase()))
    }

    let csvContent = "id,name,rolen" + filteredUsers.map(u => `${u.id},${u.name},${u.role}`).join("n");

    try {
        // write filtered data to csv file synchronously
        fs.writeFileSync(filePath, csvContent, "utf8");
        console.log("Filtered data saved");
    } catch (err) {
        console.log("Error writing to CSV file", err);
    }

    new Promise(resolve => setTimeout(resolve, 300));
})

step("Show filtered users based on role on the console <id>, <name>, <role>", async (id,name,role) => {
    console.log(`ID is ${id}`);
    console.log(`Name is ${name}`);
    console.log(`Role is ${role}`);
});

——————————x—————————–

I am using following command to run test

set ROLE=editor && gauge run specsVerify_users2.spec --tags "filter"

ROLE is defined in properties file.