How to force npm to install a package from dependencies if it’s installing the same package though a nested dependencies

So I have a situation where I have added a package (postcss) in my devDependencies. But there’s another package in devDependencies that is installed before it and that package contains another (deprecated) version of postcss. So what I end up in node_modules is the deprecated one instead of the one that I want to add explicitly through devDependencies.

How should I be able to get that?

P.S I tried the following:

 "overrides": {
    "postcss": "^8.4.35"
  }

But it gives an error that the package already exists in devDependencies.

Here’s to the downvoters:

  • If you think there already exists an answer, link it and then vote to close.
  • If you think this question doesn’t make sense to you, maybe just ignore? Or, perhaps add a comment to explain why you think so?

Pass Ajax File to PHP with js [duplicate]

I have these js. My page can not be reload, but i want to pass the image to my server to process it.
These is my code:

var image = document.getElementById("foto");
    var xhttp = new XMLHttpRequest();       
    xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
        this.responseText;
    }};
    xhttp.open("POST", "changeImage", true);    
    xhttp.send("file=" + image);

Maybe with jquery is easier but i want to use it in a function

Woocommerce free-shopping above a price is not reflecting at view cart

I have a created a website with wordpress and woocommerce.

I want to remove the shippig-rates if the customer buy more than €75.

So I have simple product called A and price is €39,-
I can add this to the mini-cart and than view the cart page,
I see the 39 and the shipping-rate.

but if i add with quantity one more the price is changing to 78, so the shipping price should be removed. But this is not removing the shipping-rate and stay with shipping rate,
I have tried it with peace of code;

function my_hide_shipping_when_free_is_available( $rates ) {
    $free = array();
    foreach ( $rates as $rate_id => $rate ) {
        if ( 'gratis_verzending' === $rate->method_id && $rate->cost == 0 ) {
            $free[ $rate_id ] = $rate;
            break;
        }
    }

    // Output some debug information
    error_log( print_r( $rates, true ) );
    error_log( print_r( $free, true ) );

    return ! empty( $free ) ? $free : $rates;
}
add_filter( 'woocommerce_package_rates', 'my_hide_shipping_when_free_is_available', 100 );

This didn’t work.

So I tried to force to get everything above €75,- bij adding the following code but still not working.

    function my_force_free_shipping_above_75( $rates ) {
        // Get the cart subtotal
        $subtotal = WC()->cart->get_subtotal();
    
        // Check if the subtotal is greater than 75 euros
        if ( floatval( $subtotal ) > 75 ) {
            // Iterate over the rates and force free shipping
            foreach ( $rates as $rate_key => $rate ) {
                if ( 'gratis_verzending' === $rate_key ) {
                    // Set the cost to 0 for free shipping
                    $rates[ $rate_key ]['cost'] = 0;
                }
            }
        }
    
        return $rates;
    }
    
    // Hook the function to the 'woocommerce_package_rates' filter with a priority of 10
    add_fil

ter( 'woocommerce_package_rates', 'my_force_free_shipping_above_75', 10 );

Can anyone point me to the right direction?
Thanks.

B.

libgdx Bilschirmauflösung beim Spielstart auf 1920X1080 umschalten

How do I set the screen resolution when starting my game.
Would like when the game starts to change the screen resolution to 1920×1080 (Full HD).
I’m slowly looking stupid…
I noticed that it doesn’t jump to “isDisplayChangeSupported()”.
And I don’t quite understand the exclusive full-screen mode either. I coded something with “Frame”. But then he opens a new window for me.

I just want to change the resolution in the game code when I start the game.
I could also show my financial appreciation…

public BaseScreen()
{

    GraphicsDevice dev = GraphicsEnvironment.getLocalGraphicsEnvironment()
            .getDefaultScreenDevice();
    GraphicsConfiguration gc = dev.getDefaultConfiguration();
    DisplayMode[] dms = dev.getDisplayModes();
    for (DisplayMode dm : dms) {
        System.out.println(dm.getHeight() + "x" + dm.getWidth());
    }
    DisplayMode mode = new DisplayMode(1920, 1080, 32, DisplayMode.REFRESH_RATE_UNKNOWN);
    if (dev.isDisplayChangeSupported()) {
        dev.setDisplayMode(mode);
        System.out.println("Hell Yeah");
    }

Infinite Loop Animation with GSAP in React Ends with Empty Space Instead of Seamless Continuation

I’m working on a React project where I want to create an infinite loop animation using GSAP. I have a row of elements that animate from bottom left to top right. The desired effect is for the animation to seamlessly continue by inserting new elements after the last one, creating an endless scroll effect. However, when the animation reaches the last element, it continues to show an empty space instead of starting over seamlessly.

Here’s the code snippet for the animation logic:

import { useEffect, useRef } from "react";
import gsap from "gsap";

export default function MoreAboutMe() {
  const tagReelRowRefs = useRef([]);

  useEffect(() => {
    const w = tagReelRowRefs.current[0].scrollWidth;

    tagReelRowRefs.current.forEach((e, i) => {
      if (e) {
        gsap.set(e, { rotate: 45, y: 0, x: 0 });

        let duration = 20 * (i + 1);

        const tl = gsap.timeline();
        tl.to(e, {
          duration: duration,
          y: -w,
          x: -w,
          ease: "none",
          repeat: -1,
        });
      }
    });
  }, []);

  return (
    <div
      className="relative z-10 w-full h-full gap-4 overflow-hidden cursor-default"
    >
      <div
        className="relative flex text-center whitespace-nowrap"
        ref={(el) => (tagReelRowRefs.current[0] = el)}
      >
        {[...Array(6)].map((_, index) => (
          <div
            key={index}
            className={`relative line-height[100%] text-[3.75vw] px-[58px] flex-none uppercase`}
          >
            <div className="w-[300px] h-[200px] bg-white rounded-2xl relative z-10 inline-block text-black">
              l {index}
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

Implementing Auto-suggestion and Auto-completion Features for a Website Clone [closed]

I’m currently working on a project to clone FootyFortunes.com, a sports betting website, and I’m looking to add some advanced features similar to what they have on their platform. Specifically, I’m interested in implementing auto-suggestion and auto-completion features for the user input fields.

Here’s what I’m trying to achieve:

  • Auto-suggestion: As the user types in an input field, I want to provide suggestions based on the input, such as player names or team names.
  • Auto-completion: When the user starts typing a player or team name, I want to automatically complete the input with the best matching suggestion.

I’m using React for the frontend of my project, and I’ve already set up a basic structure for the input fields and the data source for suggestions.

Here are my specific question:

  • How can i implement it so that the suggestions appear in place of input placeholder and how can i navigate among diffrent suggestion?

Implemented code:

import { useState, useEffect, useRef } from "react";
import { PLAYERS } from "../assets/sheet"; // Import your player data

const Keyboard = () => {
  const [inputValue, setInputValue] = useState('');
  const [bestSuggestion, setBestSuggestion] = useState('');
  const [showSuggestions, setShowSuggestions] = useState(false); // Track if suggestions should be shown
  const inputRef = useRef(null); // Reference to input element

  useEffect(() => {
    // Focus the input field on component mount
    inputRef.current.focus();
  }, []);

  const keyboardLayout = [
    ['Q', 'W', 'E', 'R', 'T', 'Y', 'U', 'I', 'O', 'P'],
    ['A', 'S', 'D', 'F', 'G', 'H', 'J', 'K', 'L'],
    ['Z', 'X', 'C', 'V', 'B', 'N', 'M', 'Backspace'],
    ['Hint', 'Space', 'Enter']
  ];

  const handleKeyPress = (key) => {
    if (key === 'Backspace') {
      setInputValue(inputValue.slice(0, -1));
      setBestSuggestion('');
    } else if (key === 'Space') {
      setInputValue((prevValue) => prevValue + " ");
      setBestSuggestion('');
    } else if (key === 'Enter') {
      alert(`You entered: ${inputValue}`);
      setInputValue('');
      setBestSuggestion('');
    } else {
      const newValue = inputValue + key;
      const filtered = PLAYERS.filter(player =>
        player.playerName.toLowerCase().includes(newValue.toLowerCase())
      );
      setInputValue(newValue);
      setShowSuggestions(true); // Show suggestions when typing
      if (filtered.length > 0) {
        setBestSuggestion(filtered[0].playerName);
      } else {
        setBestSuggestion('');
      }
    }

    // Always focus the input and show suggestions
    inputRef.current.focus();
    setShowSuggestions(true);
  };

  const handleSuggestionClick = (playerName) => {
    setInputValue(playerName);
    setShowSuggestions(false);
    setBestSuggestion('');
  };

  const handleAutoComplete = () => {
    if (bestSuggestion) {
      setInputValue(bestSuggestion);
      setShowSuggestions(false);
      setBestSuggestion('');
    }
  };

  return (
    <div className="keyboard">
      <input
        ref={inputRef}
        type="text"
        value={inputValue}
        onChange={(e) => setInputValue(e.target.value)}
        onKeyDown={(e) => {
          if (e.key === 'Tab') {
            e.preventDefault();
            handleAutoComplete();
          }
        }}
        placeholder={inputValue || showSuggestions ? bestSuggestion : "Enter Player Name"}
        name="guess"
        className={showSuggestions ? "suggestions" : ""}
      />
      {keyboardLayout.map((row, rowIndex) => (
        <div key={rowIndex} className="keyboard-row">
          {row.map((key, keyIndex) => (
            <button
              key={keyIndex}
              onClick={() => handleKeyPress(key)}
              className={key === "Space" ? "space-key" : ""}
            >
              {key}
            </button>
          ))}
        </div>
      ))}
      {showSuggestions && (
        <div className="suggestions-list">
          {PLAYERS.filter(player =>
            player.playerName.toLowerCase().includes(inputValue.toLowerCase())
          ).map((player, index) => (
            <div key={index} onClick={() => handleSuggestionClick(player.playerName)}>
              {player.playerName}
            </div>
          ))}
        </div>
      )}
    </div>
  );
};  


export default Keyboard;

i want this feature to look something like this.

enter image description here

Here is repo: GitHub

How to use global state with reactQuery

I have one main page where Im calling GET endpoint with reactQuery.

const { data} = MyApi({
        //enabled: clientId != null
    }).get.useUserData(clientId);

It works OK.

But there is a need to read this data on some other indepedent function which is located in separate file (tranlsation.js)

What is the best way doing it with global state of reactQUery? (passing data object is not an option)

I tried to use in App.jsx wrapper like this:

import Translate from 'components/Translate';
import { QueryClient,QueryClientProvider } from '@tanstack/react-query';

const queryClient = new QueryClient();
const Routes = lazy(() => import('routes/routes'));

const App = () => {
    return (
        
                <QueryClientProvider client={queryClient}>
                <NavigationBlocker>
                    <page-content id="content-main">
                        <Translate namespace="some">
                            {(t) => (
                                <section className="section pt-5 px-5 pb-0">
                                    <span className="page-title">{t('sometranslation')}</span>
                                </section>
                            )}
                        </Translate>
                        <Routes />
                    </page-content>
                </NavigationBlocker>
                <InitGlobalSwitcher />
                </QueryClientProvider>
    );
};

export default App;

in my translation.jsx Im trying to call the state using useQuery function:

    const queryClient = useQueryClient();
    const test = queryClient;
    console.log('test');
    console.log(test);

This code presents me the structure, but I cant find anywhere data.
enter image description here

Solution that I didn’t like:

I tried with GLobalStateProvider component, which was using react context etc. and it works, but I would like to have global state functionality with react-query because Im already using this library.

Unable to Fetch Posts by Search Criteria in React Application Using Redux and Express.js Backend

I’m building a React application with Redux for state management and an Express.js backend for handling API requests. I’m trying to implement a search functionality to fetch posts based on search criteria entered by the user. However, I’m encountering an issue no posts are fetched. It returns this json data instead of posts with specified search query

const useQuery = () => {
    return new URLSearchParams(useLocation().search)
}
export default function Home() {
    const classes = useStyles()
    const dispatch = useDispatch();
    const [search, setSearch] = useState('')
    const [tags, setTag] = useState([])
    const [currentId, setCurrentId] = useState(null)
    const liked = useSelector((state) => state.posts.isLiked)
    const del = useSelector((state) => state.posts.isDeleted)
    const query = useQuery()
    const navigate = useNavigate()
    const page = query.get('page') || 1
    const searchQuery = query.get('searchQuery')



    useEffect(() => {
        console.log('Effect triggered');
        dispatch(getPosts())
    }, [currentId, dispatch, liked, del])

    console.log(search)

    const searchingPost = () => {
        if (search.trim() || tags.length > 0) {
            dispatch(searchPost({ search, tags: tags.join(',') }))
            console.log("this is in in the search",search)

        } else {
            navigate('/')
        }
    }

    const handleKeyPress = (e) => {
        console.log("outside the if condition")
        if (e.keyCode === 'Enter') {
            searchingPost()
            console.log('inside the handlekeypress')
        }
    }

    const handleChange = (newChips) => {
        setTag(newChips)
    }

    const handleAdd = (tag) => {
        setTag([...tags, tag])

    }

    const handleDelete = (tagToDelete) => {
        setTag(tags.filter((tag) => tag !== tagToDelete))


    }


    return (
        <>
            <Grow in>
                <Container maxWidth='xl'>
                    <Grid container justify='space-between' alignItems='stretch' spacing={3} className={classes.gridContainer}>
                        <Grid item xs={12} sm={6} md={9}  >
                            <Posts currentId={currentId} setCurrentId={setCurrentId} />
                        </Grid>
                        <Grid item xs={12} sm={6} md={3}   >
                            <AppBar className={classes.appBar} position='static' color='inherit'>
                                <TextField
                                    name='search'
                                    label='Search Memories'
                                    fullWidth
                                    value={search}
                                    onChange={(e) => setSearch(e.target.value)}
                                    onKeyPress={handleKeyPress}
                                    variant='outlined'
                                />
                                <MuiChipsInput
                                    style={{ margin: '10px 0' }}
                                    value={tags}
                                    onChange={handleChange}
                                    // onAdd = {handleAdd}

                                    // onDelete = {handleDelete}
                                    label='Search Tags'
                                    variant='outlined'
                                ></MuiChipsInput>
                                <Button onClick={searchingPost} className={classes.searchButton} color='primary'>Search</Button>
                            </AppBar>
                            <Form currentId={currentId} setCurrentId={setCurrentId} />
                            <br />
                            <Paper className={classes.pagination} elevation={6}>
                                <Paginate />
                            </Paper>
                        </Grid>
                    </Grid>
                </Container>
            </Grow>

        </>
    )
}
import { createSlice, createAsyncThunk } from "@reduxjs/toolkit";
import { fetchPostsBySearch ,fetchPosts, createPost as apiCreatePost, updatePost as apiUpdatePost, likePost, deletePost } from '../api/index.js';

const initialState = {
    isDeleted: false,
    posts: [],
    searchResults : [],
    isLiked: false
}

const postSlice = createSlice({
    name: 'posts',
    initialState,
    reducers: {
        setPosts(state, action) {
            state.posts = action.payload;
        },

        searchPost(state,action) {
            state.searchResults = action.payload;
        },
        addPost(state, action) {
            state.posts = [...state.posts, action.payload]
        },
        update(state, action) {
            const updatedPost = action.payload;
            // Find the post in the state by ID and update it

            state.posts = state.posts.map(post => (post._id === updatedPost._id ? updatedPost : post));
            // if post id equal to updated post id return updatedpost else return the previous post
            
        },
        like(state, action) {
            const postliked = action.payload;
            // Find the post in the state by ID and update it

            state.posts = state.posts.map(post => (post._id === postliked._id ? postliked : post));
            // state.posts = [...state.posts];
            state.isLiked = true;
            
            

        },
        deletepost(state, action) {
            console.log(action.payload)

            state.posts = state.posts.filter((post) => post._id !== action.payload)  
            console.log('inside the reducer',state.posts)
            // state.posts = [...state.posts];
            state.isDeleted = true

        },
        resetFlags(state) {
            state.isDeleted = false;
            state.isLiked = false;
        }




    },
});

export const { setPosts, addPost, update, like, deletepost,resetFlags,searchPost } = postSlice.actions;
export default postSlice.reducer;

export const getPosts = createAsyncThunk('posts/getPosts', async (_, { dispatch }) => {
    try {
        const { data } = await fetchPosts();
        dispatch(setPosts(data));
    } catch (error) {
        console.log(error.message);
    }
});


export const searchPosts = createAsyncThunk('posts/searchPosts', async ({searchQuery}, { dispatch }) => {
    try {
        const { data   } = await fetchPostsBySearch(searchQuery);
        dispatch(searchPost(data));
        console.log(data)
    } catch (error) {
        console.log(error.message);
    }
});


// api index.js
export const fetchPostsBySearch = (searchQuery) => API.get(`/posts/search?searchQuery=${searchQuery.search || 'none'}&tags=${searchQuery.tags}`)

query is actually reaching the backend but requesting i’m getting from backend it this
‘{search: ‘Trek’, tags: ”} [[Prototype]] ‘

export const getPostBySearch = async (req,res) => {
    const {searchQuery,tags} = req.query
    console.log(req.body)

    try {
        console.log(searchQuery)
        const title = new RegExp(searchQuery,'i') // i stands for ignore case
        const posts = await PostMessage.find({ $or: [{title}, {tags : { $in:  tags.split(',')}}]} )
        res.json({data : posts})

        console.log("this is for searchings posts",posts)

    } catch(error) {
        res.status(404).json({message : error.message })

    }
}

How to resolve this error i want to fetch posts based on their title, but response is returing nothing and it shows no error.

Tabs content active on scroll and also active tab

I want to show each tab content on scroll on same screen position. For example when user scroll to tabs section first tab and its content show and scroll down 2nd tab active and show its content and so on.

Here is the code https://codepen.io/Nasir-Kamal/pen/XWGPxpd

 $(document).ready(function () {
        $('body').scrollspy({ target: '#v-pills-tabContent' });

   
        $('#v-pills-tab a').on('click', function (e) {
            e.preventDefault();
            var target = $(this).attr('href');
            $('html, body').animate({
                scrollTop: $(target).offset().top
            }, 800);
        });

        
        $(window).on('scroll', function () {
            var scrollPos = $(window).scrollTop();
            $('#v-pills-tab a').each(function () {
                var currLink = $(this);
                var refElement = $(currLink.attr('href'));
                if (refElement.position().top <= scrollPos && refElement.position().top + refElement.height() > scrollPos) {
                    $('#v-pills-tab a').removeClass('active');
                    currLink.addClass('active');
                } else {
                    currLink.removeClass('active');
                }
            });
        });
    });

Custom Webpack plugin: how to properly generate new asset

So I have a JS library that has CSS bundled in JS (it used rollup and postCSS plugin to inline all the CSS in JS). So if I open JS code I could find things like this:

var css_248z$$ = ".some-component-123{color:red; background: pink}";
__INJECT_CSS(css_248z$$);

Where __INJECT_CSS is a function that would create a STYLE tag and insert it into HTML head. It works ok, but my task is to extract all those injected css from js into separate CSS asset.

Below is nearly complete of webpack 5 plugin that I made. Except for extractInjectedCSS function that actually extracts CSS from JS, but that’s out of scope of my question.

class FooBarPlugin {

  extractedCss = [];

  apply(compiler) {
    const pluginName = 'GetRidOfThatCSSinJS';

    const { webpack } = compiler;
    const { Compilation } = webpack;
    const { RawSource } = webpack.sources;

    let cssExtracted = false;

    // on the second pass we make sure to trigger cssExtracted flag
    compiler.hooks.additionalPass.tap(pluginName, () => {
      cssExtracted = true;
    });

    compiler.hooks.compilation.tap(pluginName, (compilation) => {

      // this will trigger second pass
      compilation.hooks.needAdditionalPass.tap(pluginName, () => {
        if (!cssExtracted) {
          return true;
        }
        return false;
      });

      // here we process JS sources
      compilation.hooks.processAssets.tap(
        {
          name: pluginName,
          stage: Compilation.PROCESS_ASSETS_STAGE_PRE_PROCESS,
          additionalAssets: false,
        },
        (assets) => {
          for (let i in assets) {
            if (i.endsWith('.js')) {
              const asset = compilation.getAsset(i);
              const contents = asset.source.source();

              const [updatedSrc, cleanCss] = extractInjectedCSS(contents);

              // update JS asset 
              compilation.updateAsset(i, new RawSource(updatedSrc));

              if (!cssExtracted) {
                this.extractedCss.push(cleanCss);
              }
            }
          }
        }
      );

      // here comes hacks. This adds extracted.css and makes main chunk depend on it
      compilation.hooks.renderManifest.tap(pluginName, (result, { chunk }) => {
        if (cssExtracted && chunk.name === 'main') {
          result.push({
            render: () => new RawSource(this.extractedCss.join('n'), 'extracted.css'),
            filenameTemplate: 'extracted.css',
            pathOptions: {
              chunk,
              contentHashType: 'css/compiled',
            },
            identifier: `${pluginName}.${chunk.id}`,
          });
        }
      });
    });
  }
}

module.exports = {
  default: FooBarPlugin,
};

It does work. Sort of. First of all it works only if stats option is disabled in webpack config. Otherwise if will crash when webpack tries to calculate size of that ‘extracted.css’ chunk. That’s my first problem.

Second problem: that solution with 2 passes of compilation seems like a hack. I had to use renderManifest hook that is missing in webpack documentation and probably isn’t supposed to be used like that.

I tried to use compilation.emitAsset() instead of compilation.hooks.renderManifest.tap hack. And while it does creates new asset, that asset isn’t being added as dependency to main. Thus it never gets loaded. And I need that extracted CSS assets to be added as dependencies, so that generated JS would load them automatically.

So here’s my main question: how to implement my task properly (without 2 passes of compilation and crashes when stats option is on).

Memorized webpack documentation. Read sources of couple of webpack plugins. Googled for hours. Cried. Googled again. Read some more sources. Came up with solution that seems to work, but need to be improved

Creating DB of Keepass returns Error InvalidArg: data using kdbxweb Library

I’m trying to put the Keepass Information in variables (JS). In the last step when I’m storing de DB information I got the “InvalidArg: data” Error

The version of kdbxweb is 2.1.1

The version of Node.js is v20.11.0

The version of Keepass is 2.50 (64 bits)

OS: Windows 10

The extension of the file is .mjs

The code is:

import kdbxweb from 'kdbxweb';
import { promises as fs } from 'fs';

// DB PATH
const ruta = 'genericRoute';

// DB PASSWORD
const clave = 'genericPassword';

// Loading DB
async function cargarBaseDeDatos(){
    try{
        
        const datos = await fs.readFile(ruta);
        console.log('Informacion de datos:', datos);
        let credenciales = new kdbxweb.Credentials(kdbxweb.ProtectedValue.fromString(clave));
        
        await credenciales.ready;
        console.log('Informacion de credenciales:', credenciales);

        const db = await kdbxweb.Kdbx.load(datos, credenciales);

    } catch (error){
        console.error('Error al cargar la base de datos', error.message);
    }
    
    
}

cargarBaseDeDatos();

The result of running this code is:

Informacion de datos: <Buffer 03 d9 a2 9a 67 fb 4b b5 01 00 03 00 02 10 00 31 c1 f2 e6 bf 71 43 50 be 58 05 21 6a fc 5a ff 03 04 00 01 00 00 00 04 20 00 ed 08 87 7b f1 1b f1 52 e3 … 2460 more bytes>

Informacion de credenciales: <ref *1> KdbxCredentials {

keyFileHash: undefined,

_challengeResponse: undefined,

ready: Promise { [Circular *1] },

passwordHash: ProtectedValue {

value: Uint8Array(32) [
  229, 142, 255, 116, 165, 223,  87, 124,
   32, 212,   8,  15, 131, 147, 248, 132,
   92,  54,  70, 180, 225, 154, 110, 232,
   48, 106,  57, 168, 245,  59, 152,  67
],

salt: Uint8Array(32) [
  169, 158, 109, 236,  58,  71, 49,   7,
    9, 109, 148,  43,  41, 128, 76, 120,
  146, 141, 114, 168,  43, 221, 77,  37,
  175,  79, 201, 210, 107,  33, 45, 219
]

}
}

Error al cargar la base de datos Error InvalidArg: data

Doesn’t matter if you change the value of clave you will keep having the same result of the running. Doesn’t matter if it is the correct pasword or not.

I trid all the configuration of a .JS extension

Encountered in Developing Dynamic Product Page Logic Using PHP CodeIgniter 4

I’m creating a page project to add products dynamically using CodeIgniter 4.4.4 like on Shopify but I’m having problems creating the controller logic, but I’ve prepared a simple logic in JavaScript form. Maybe I can find the answer here

below is My Css Code:

#addOptions,
.Options .addOptionsValue,
.Options .removeOptions,
.Options .removeOptionsValue {
    background-color: black;
    border-radius:15px;
    color: white;
    border: none;
    padding: 5px 10px;
    cursor: pointer;
    margin-top:5px;
}

.Options input[type="text"],
.Options input[type="number"],
.Options select {
    width: 160px;
    margin: 3px 0px;
    padding: 5px;
}

.Options .removeOptionsValue {
    display: inline-block;
    vertical-align: top;
    margin-top: 5px;
}


.Options-container .form-group {
    margin: 15px 0px;
}

below is My html code:

<link href='https://unpkg.com/[email protected]/css/boxicons.min.css' rel='stylesheet'>
<div class="Options-container">
    <div class="form-group">
        <div id="OptionssContainer"></div>
        <button id="addOptions" class="Options-button">Add Varian</button>
    </div>
</div>
<div id="itemproductsContainer"></div>

<button type="submit" class="submit-btn">Add Product</button>

below is My Script code:

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
        $(document).ready(function() {
            $('#addOptions').click(function() {
                addOptions();
            });

            $(document).on('click', '.removeOptions', function() {
                $(this).closest('.Options').remove();
                updateitemproducts();
            });

            $(document).on('click', '.addOptionsValue', function() {
                var valueContainer = $(this).siblings('.OptionsValues');
                valueContainer.append('<div><input type="text" class="OptionsValue" placeholder="Tambah nilai"><button class="removeOptionsValue"><i class="bx bx-minus"></i></button></div>');
            });

            $(document).on('click', '.removeOptionsValue', function() {
                $(this).parent().remove();
                updateitemproducts();
            });

            $(document).on('input', '.OptionsValue', updateitemproducts);

            function addOptions() {
                var OptionsHtml = `
                <label for="Options">Variant Option</label>
                    <div class="Options">
                        <select class="OptionsType">
                            <option value="Color">Color</option>
                            <option value="Size">Size</option>
                        </select>
                        <div class="OptionsValues">
                            <div><input type="text" class="OptionsValue" placeholder="Add Value"><button class="removeOptionsValue"><i class="bx bx-minus"></i></button></div>
                        </div>
                        <button class="addOptionsValue"><i class='bx bx-plus'></i></button>
                        <button class="removeOptions"><i class='bx bx-trash'></i></button>
                    </div>`;
                $('#OptionssContainer').append(OptionsHtml);
            }

            function generateitemproducts(Optionss, index = 0, currentitemproduct = [], itemproducts = []) {
                if (index === Optionss.length) {
                    itemproducts.push(currentitemproduct.slice());
                    return itemproducts;
                }

                var values = Optionss[index].value.filter(value => value !== '');
                if (values.length === 0) values.push("");

                values.forEach(value => {
                    currentitemproduct[index] = value;
generateitemproducts(Optionss, index + 1, currentitemproduct, itemproducts);
});

     return itemproducts;
        }

        function displayitemproducts(itemproducts) {
            var html = '<table class="tabledata"><tr><th style="width:200px;">Item Product</th><th>Price</th><th>Stock</th></tr>';
            itemproducts.forEach(itemproduct => {
                var itemproductId = itemproduct.join('-').replace(/s+/g, '_').toLowerCase();
                html += `
                    <tr>
                        <td>${itemproduct.join(' / ')}</td>
                        <td><input type="number" name="price_${itemproductId}" placeholder="Price"></td>
                        <td><input type="number" name="stock_${itemproductId}" placeholder="Stock"></td>
                    </tr>`;
            });
            html += '</table>';
            $('#itemproductsContainer').html(html);
        }

        function updateitemproducts() {
            var Optionss = $('.Options').map(function() {
                var values = $(this).find('.OptionsValue').map(function() {
                    return $(this).val().trim();
                }).get();
                return {
                    type: $(this).find('.OptionsType').val(),
                    value: values
                };
            }).get();

           if (Optionss.length === 0) {
        $('#itemproductsContainer').empty();
    } else {
        var itemproducts = generateitemproducts(Optionss);
        displayitemproducts(itemproducts);
    }
        }
    });
</script>

I will add a little explanation with the expectations in my code, in adding variants of course you can have a single variant, and you can add multiple variants too

and when the product is displayed on the views product detail page, the variant will appear as below like

Color:

(Blue) (Red)

Size:

(XL) (M) (S)

Of course, users can choose according to their choice based on the Variant on each Label

by preparing my code in creating logic in the controller I want to store “Label”, “Item Product”, “Price” and “Stock” into a mysql table ,and some questions, does the logic in my script need improvement, especially in the “Item Product” table in sending data to the database with ajax?

create a view to add products and display products dynamically with codeigniter 4.4.4

Is it possible to automatically generate other drop-down menu items when you select a Google Form drop-down menu?

I am creating a business application for renting products using spreadsheets and GAS, and I am thinking of accepting the rental process using Google Forms.
Therefore, I would like to select the product to rent from the Google Form drop-down menu, and then select the number of items to rent from the drop-down menu, but the number of products in stock should be updated in real time.
Therefore, when the item to be rented is selected from the drop-down menu, I would like to refer to the number of items in stock listed in the spreadsheet and set that number to the item in the drop-down menu.
However, I don’t know how to dynamically create a drop-down menu (triggered by selecting the item to rent drop-down menu).

How can I dynamically set the dropdown menu items?

My firebase google authentication stopped working suddenly and gives me this error “Cannot read properties of null (reading ‘user’)”

I implemented google auth in my firebase project using the signInWithRedirect method and it has been working normally until today and i can’t see where the issue is coming from suddenly

this is my code

 const googleBtn = document.querySelector('#googleSignup')

  const signInWithGoogle = () => {
    const provider = new GoogleAuthProvider();

    signInWithRedirect(auth, provider);
  };

  getRedirectResult(auth)
    .then((result) => {
      const user = result.user;
      console.log('Successfully signed in with Google:', user);

      window.location.href = '/dist/pages/food_options.html';
    })
    .catch((error) => {
      console.error('Error signing in with Google:', error.message);
    });

  googleBtn.addEventListener('click', signInWithGoogle);

and here is the full error it’s giving me index.js:74 Error signing in with Google: Cannot read properties of null (reading ‘user’)