How to convert div of html to pdf with selectable text and preserved CSS?

I am trying to build a resume builder using reactjs but the problem that I am facing is that I want the user to get the pdf version of their resume on clicking the download button. But don’t know how to achieve that. I had tried jsPDF and it is converting div to pdf but not preserving CSS. I had also tried jsPDF with html2canvas but again it is converting div to pdf with preserved CSS but that pdf is kind of image and the text in not selectable and links are not clickable which is a bad characteristic for a resume. Please help me with this.

Any resource will be helpful.
Thanks

Javascript rest api tests

const express = require('express');
    const bodyParser = require('body-parser');
    const Sequelize = require('sequelize');
    const { STRING, INTEGER } = require('sequelize');

    const sequelize = new Sequelize({
      dialect: 'sqlite',
      storate: 'homework.db'
    });

    const Student = sequelize.define('student', {
      name: Sequelize.STRING,
      address: Sequelize.STRING,
      age: Sequelize.INTEGER
    }, {
      timestamps: false
    });

    const app = express();
    app.use(bodyParser.json());

    app.get('/create', async (req, res) => {
      try {
        await sequelize.sync({ force: true });
        for (let i = 0; i < 10; i++) {
          const student = new Student({
            name: 'name ' + i,
            address: 'some address on ' + i + 'th street',
            age: 30 + i
          });
          await student.save();
        }
        res.status(201).json({ message: 'created' });
      } catch (err) {
        console.warn(err.stack)
        res.status(500).json({ message: 'server error' });
      }
    });

    app.get('/students', async (req, res) => {
      try {
        const students = await Student.findAll();
        res.status(200).json(students);
      } catch (err) {
        console.warn(err.stack);
        res.status(500).json({ message: 'server error' });
      }
    });

    app.post('/students', async (req, res) => {
      try {
        //TODO
        if (req.body !== null) {
          const student = await Student.create(req.body);
          if (!(typeof(student.name) === STRING && typeof(student.address) === STRING && typeof(student.age) === INTEGER)) {
            if (student.age > 0) {
              return res.status(201).json({ message: "created" });
            } else {
              res.status(400).json({ message: "age should be a positive number" });
            }
          } else {
            res.status(400).json({ message: "malformed request" });
          }
        } else {
          res.status(400).json({ message: "body is missing" });
        }
      } catch (err) {
        console.warn(err.stack);
        res.status(500).json({ message: 'server error' });
      }
    });

    module.exports = app;

Right sooo I have a little school project here with apparently some simple http verbs implemented in node js. The problem is that I have some tests defined(all of them related to the last POST method) and out of five, only two of them pass and idk why. Can anyone tell how should I modify that post in order for the tests to be satisfied? The first code is the app js file and the second one is the server side.

The tests are as follws:

  • if request body is not sent server should respond with status code 400 and {“message”:”body is missing} -> failed

  • if request body is present but did not follow the specified format, server should respond with status code 400 and {“message”:”malformed request”} -> failed

  • age should not be negative -> passed

  • a student can be added -> passed

  • the student list is valid -> failed

    const app = require('./app')
    
    app.listen(8080, () => {
      console.log('Server started on port 8080...')
    })

General Question about API’s and working with them in Node and JavaScript

I have been in a steep learning curve lately, trying to learn as much as possible about NodeJS and Backend-development in general. I have a project set up and I want to be able to flip some switches on a Website, that then tells the Node-Server what to do, which then makes a call to an API and all the way back to displaying it in the browser. I’ve already worked with promises, but I don’t specifically know how to approach this. Could you maybe provide me with an oversimplified example?

Thank you so much in advance and have a great rest of your day!

Run simple js when Component is fully rendered in React functional component

This a (very) simplified version of my component:

export const DynamicComponent: FC<DynamicComponentProps> = (props) => {
  const ref = useRef<HTMLElement>(null);
  const [isSticked, setIsSticked] = useState(false);
  const parentSticked = useContext(StickyContext);
  const [overridedStyles, setOverridedStyles] = useState(props.styles ?? {});
  const [overridedArgs, setOverridedArgs] = useState(props.args ?? {});
  const { config } = useContext(GlobalContext);
  const data = useContext(DataContext);
  const [state, setState] = useContext(StateContext);

  const mountComponent = useMemo(() => {
    if (typeof props.mount === "undefined") return true;
    if (typeof props.mount === "boolean") return props.mount;
    if (typeof props.mount === "number") return props.mount === 1;
    if (typeof props.mount === "string") {
      let mount = stateParser.parse(props.mount, state) as unknown;
      return mount == true;
    }
    return false;
  }, [state, props.mount]);



  useLayoutEffect(() => {
    setTimeout(() => {
      const anchorHash = location.hash;
      if (
        anchorHash &&
        document &&
        document.querySelector(anchorHash) &&
        !document
          .querySelector(anchorHash)
          ?.classList.contains("already-scrolled")
      ) {
        document?.querySelector(anchorHash)?.scrollIntoView();
        document?.querySelector(anchorHash)?.classList.add("already-scrolled");
      }
    }, 50);
  }, []);

  let output = mountComponent ? (
    <StickyContext.Provider value={{ sticked: isSticked }}>
      <StyledDynamicComponent
        {...props}
        ref={ref}
        isSticked={applyStickedStyles}
        args={overridedArgs}
        styles={overridedStyles}
      />
    </StickyContext.Provider>
  ) : null;

  return output;
};

The code inside the useLayoutEffect won’t run correctly without the setTimeout because the component is not fully rendered and document?.querySelector(anchorHash) does not exist yet..

Tried with a window.onload but the code inside it will never run..

Is there a way to prevent using that horrendous setTimeout?

What’s wrong with the piece of JS Code to toggle between classes?

I want to use JavaScript code to toggle between two classes.

What’s wrong with this code that I finally got:

<script>
function tog() {
    var para = document.querySelector(".tn, .on");

    if(para.classList.contains("tn")) {
        para.classList.remove("tn");
        para.classList.add("on");
    }
    else if (para.classList.contains("on")) {
        para.classList.remove("on");
        para.classList.add("tn");

    }
}
</script>

Dynamic minmax values inside styled component

I’m trying to make the 250px number inside the minmax function dynamic inside a styled component.

Normally I could just use something like this:

minmax(${props => props.minWidth}, 1fr)

But this breaks instantly and won’t even render because it’s invalid syntax.

This is my code right now without it being dynamic. Any ideas much appreciated 🙂

const GridContainer = styled.div`
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  grid-auto-rows: auto;
  grid-gap: 20px;
  width: 100%;
`;

merge 3 different json array objects into a single json array based on key values in javascript

I am trying to merge 3 different json array objects as a single object based on key values in the base json object in JavaScript. I haven’t tried anything like this before.
Data looks something like this.

var baseObj = [
  { "miId": 1, "val": 2, "smiList": [ { "smiId": '1a', "val": 3 }, { "smiId": '1b', "val": 4 } ] },
  { "miId": 2, "val": 22, "smiList": [ { "smiId": '2a', "val": 33 }, { "smiId": '2b', "val": 43 } ] }
]

var obj1 = [ 
    { "miId": 1, "val": 23, "smiList": [ { "smiId": '1a', "val": 13 }, { "smiId": '1c', "val": 14 } ] },
     { "miId": 4, "val": 24, "smiList": [ { "smiId": '2a', "val": 33 }, { "smiId": '2b', "val": 43 } ] }
]

var obj2 = [ 
    { "miId": 11, "val": 22, "smiList": [ { "smiId": '1a', "val": 53 }, { "smiId": '1c', "val": 14 } ] },
    { "miId": 2, "val": 43, "smiList": [ { "smiId": '2a', "val": 6 }, { "smiId": '2b', "val": 7 } ] }
]

My result has to be based on the base json and its key values. its basically like a left of obj1 and obj2 with baseobj array. I need to get all the objects of baseObj along with matched values of obj1 and obj2 based on their keys.

The result has to be:

var resultObj = [
  { "miId": 1, "val": 2, "obj1Val" :23, "smiList": [ {"smiId": '1a', "val": 3, "obj1Val": 13}, { "smiId": '1b', "val": 4 } ] },
  { "miId": 2, "val": 22, "obj2Val" :43, "smiList": [ { "smiId": '2a', "val": 33, "obj2Val" :6}, { "smiId": '2b', "val": 43, "obj2Val" :7, } ] }
]

can anyone please help me in how to achieve the above result. Thanks in advance.

CRUD application testing with mocha chai

I am new to JavaScript/JavaScript testing and was doing a course on mocha test framework with chai. how to test simple CRUD application? I want to write unit tests for all of them. I tried looking at questions here, but all of them were very advanced and i did not understand them. can you please help me it would be appreciated. the question was

module.exports = {
  
  addDetails: function() {
    let data =[]
    data.push("one");
    return data
  },

  deleteDetails: function() {
    let data =["one" , "two"]
    data.splice(0 , 1)
    return data
  },

  editDetails: function() {
    let data =["one"]
    data.splice(0 , 1 , "three")
    return data
  },

  updateDetails: function() {
    let data = ["one" , "three"]
    data.splice(1 , 0 , "two")
    return data
  },

  detailsPop: function() {
    let numb = ["one" , "two"]
    numb.pop()
    return numb
  },

  concatData: function() {
    let data1 = ["one"]
    let data2 = ["two"]
    let result = data1.concat(data2)
    return result
  }
 }

AngularJS component/controller JavaScript files loads in series not parallel (specific to Chrome compiled for AMD)

I am looking at performance improvements for first-load (non-cached) for a Flask/AngularJS delivered webpage (transition to Angular and better route design is in the works, looking for a temporary fix).

This page includes a ton (250+) of JavaScript files on load. We are noticing on that these files are being loaded in series vs in parallel on some machines and not others.

The issue seems to be specific to the Chrome on an AMD machine (v 96.0.4664.93). We are not seeing this on Firefox on the same machine or on Chrome on Intel machines. This difference causes an increase in load time of nearly 15 seconds.

Question is can we force the problematic browser to download these in parallel to the cache? We attempted to use the async attribute in the script tag, but it causes some files to be loaded out of order.

i want to build e-commerce application with react and redux

i was devide the data and state of the application into slice,i used the sliceReducer in this project because it have so many component and have a lot of products categories to buy so when i try to make the first components which is about mechanics product this error always display “Ă—
Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:

  1. You might have mismatching versions of React and the renderer (such as React DOM)
  2. You might be breaking the Rules of Hooks
  3. You might have more than one copy of React in the same app
    See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.”
    so this mecanicsSliceProducts:
import {createSlice} from '@reduxjs/toolkit';

const mecanicsProducts = [{name:"aprilia404", description: "Aprilia404 cylindres en V longitudinal de 65° 4 temps,refroidissement au liquide distribution bi-arbre à cames (DOHC) quatre soupapes par cylindre ", img: 'C:/Users/ADMIN/Desktop/Bike project/banner/aprilia404', number: 12 ,moteur:"4 cylindres", vitesseMax: "140km/h", reservoir: '55l', price: 3000, quantity: 0, id: 0}, 
{name: "Aprilia Dosudoro", description:"L’Aprilia Dorsoduro est la moto fun par excellence.Née d'une intuition brillante d’Aprilia, elle a été créée dans le seul but de donner autant de plaisir que possible  ", img: 'C:/Users/ADMIN/Desktop/Bike project/banner/apriliascooter', number: 8 ,moteur:"bicylindre", vitesseMax:"260km/h", reservoir: "12l" ,price: 12500, quantity: 0, id:1}, 
{name: 'Aprilia Sr 50', description:"Estampillée du numéro 3 et peinte aux couleurs de l’Aprilia Alitalia Racing Team, l’engin ne devrait pas passer inaperçu.", img: 'C:/Users/ADMIN/Desktop/Bike project/banner/aprilia sr 50', number: 12, moteur:"monocylindre", vitesseMax: '100km/h',reservoir: '7l', price: 4000, quantity: 0, id:2}, 
{name: "Ducati monter", description: "Ducati Monster est une gamme de motos du constructeur italien Ducati de type roadster lancée en 1992", img: 'C:/Users/ADMIN/Desktop/Bike project/banner/ducati monster 110s2009 modele3d', number: 12, moteur: "2 cylindres", vitesseMax: '260km/h', reservoir: "14l" ,price: 14500, quantity: 0, id: 3},
{name: "Honda cbr 600", description:"La Honda CBR600RR est une moto de 599 cmÂł, de la famille des CBR introduite par Honda en 2003", img: 'C:/Users/ADMIN/Desktop/Bike project/banner/honda 623 cbr bike', number: 5, vitesseMax: '260km/h', moteur: "4 cylindres, 4temps, refroidissement liquide", reservoir:"18.1l", price: 23400, quantity: 0, id:4}, 
{name: "Forza ftm", description: "Cyclomoteur FORZA-FTM ,Cylindrage 110CC , Charge utile : 110 Kg , Vitesse Max : 160 Km/h , RĂ©servoir : 4.5Litres.", img: 'C:/Users/ADMIN/Desktop/Bike project/banner/forzaftm', number: 15, moteur: "monocylindre", vitesseMax: "160km/h", price: 2400, quantity: 0, id: 5}];

export const mecanicSliceProducts = createSlice({
    name: 'mecanicsProducts',
    initialState: mecanicsProducts,
    reducers: {
        changeQuantity: (state, action) => {
          let {name, newQuantity} = action.payload;
          let findProductName = state.find(product => product.name === name);
          if (findProductName) {
            findProductName.quantity = newQuantity;
          }
         return state;
        },
      buyProduct: (state, action) => {
        const purchasedProduct = state.find(product=> product.id === action.payload.id);
        if(purchasedProduct) {
            purchasedProduct.quantity += 1;
            purchasedProduct.number = purchasedProduct.number - purchasedProduct.quantity;             
        }
        return [...state, purchasedProduct]
      }
    

    }

});

export const selectPurchasedProducts = (state) => {
    return state.mecanicsProducts.filter(product => product.quantity !== 0).map(product => product.id)
};
    export const selectmecanicsProductsToDisplay = (state) => {
        return state.mecanicsProducts.map(product => ({
            name: product.name,
            img: product.img,
            price: product.price,
            id: product.id
        }))
    };
    console.log(selectmecanicsProductsToDisplay)

    export const {changeQuantity, buyProduct} = mecanicSliceProducts.actions;

export default mecanicSliceProducts.reducer;

this is the mecanicsProduct.js file:

import React from 'react';
import { selectmecanicsProductsToDisplay } from './mecanicSliceProducts';
import {useSelector} from 'react-redux';
import { Product } from '../Product.js'


export const MecanicProducts = () => {
    const mecanicsProducts = useSelector(selectmecanicsProductsToDisplay);
    console.log(mecanicsProducts);

return (
<div className="mecanics" >
<h2> Motors selections</h2>
{mecanicsProducts.map(product => <Product product={product} key={product.id} />
)}
</div>
    )
}

this is the store.js file :

import { configureStore } from '@reduxjs/toolkit';
import  mecanicSliceProductsReducer   from '../../features/mecanicsProducts/mecanicSliceProducts';

export const store = configureStore({
    reducer: {
        mecanicsProducts: mecanicSliceProductsReducer,
    }
})

this is the index.js file:

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import { App } from './App';
import { Provider } from 'react-redux';
import { store } from './components/App/store.js';


ReactDOM.render(
  
  <Provider store={store} >
    <App />
    </Provider >,
 
  document.getElementById('root')
);

this is the App.js file :

import React from 'react';
import { Navbar } from './components/Navbar/Navbar';
import {MecanicProducts} from './features/mecanicsProducts/mecanicsProducts'
 

export function App() {
  return (
    <div className="App">
      <Navbar />
      <MecanicProducts />
    </div>
  );
}

How do I parse the indentation level of a string into a JSON Object?

I’d like to be able to parse a string into a JSON Object, something like this (the text can be anything, I’m just putting them like this so you can see the structure):

A
  A-A
  A-B
    A-B-A
    A-B-B
  A-C
    A-C-A
B

into a json object, structured like this:

[
  {
    "root": "A",
    "content": [
      { "root": "A-A", "content": [] },
      {
        "root": "A-B",
        "content": [
          { "root": "A-B-A", "content": [] },
          { "root": "A-B-B", "content": [] }
        ]
      },
      {
        "root": "A-C",
        "content": [
          { "root": "A-C-A", "content": [] }
        ]
      }
    ]
  },
  { "root": "B", "content": [] }
]

So far, I have the following, but I’m not sure if this is the best way of doing it. Maybe a recursive approach would be better?

  let body = [];
  let indentStack = [0];
  for (let line of input.split('n')) { // input is the string I'd like to parse
    if (line.trim() == '') continue; // skips over empty lines
    let indent = line.match(/^ +/);
    indent = indent ? indent[0].length : 0; // matches the first group of spaces with regex, gets the indent level of this line
    if (indentStack[indentStack.length-1] != indent) 
      if (indentStack.includes(indent)) indentStack.length = indentStack.indexOf(indent)+1; // remove all indent levels after it as it's returned back to a higher level
      else stack.push(indent);
    console.log(`${(indent + '[' + indentStack.join() + ']').padEnd(10, ' ')}: ${line}`); // debugging
      
    if (indentStack.length == 1) body.push({ root: line, content: [] });
    else {
      body[body.length-1].content.push({ root: line.substring(indent), content: [] })
    }
  }
  console.log(body)

Dynamically changing the variable name inside 2 for loops [duplicate]

So I’m working in babylon.js (but is more a js problem at this time) my problem is that I need to change a variable name dynamically but taking the index of both for that.

Here, let me show you the array in fact:

    for (let i = 0; i < torresIndex; i++) {
                for (let j = 0; j < repTorre[i]; j++) {
                    piso = BABYLON.MeshBuilder.ExtrudePolygon("piso"+i+j, {shape:torre[i], depth: 1, sideOrientation: -1 }, scene);
                    piso.position.y = factorTamano++;
                    factorTamano = factorTamano++;
                    piso.material  = materialforSolidPolygon;
                    piso.enableEdgesRendering(); 
                    piso.edgesWidth = 4.0;
                    piso.edgesColor = new BABYLON.Color4(0, 0, 0);
  }
}

“piso” is an array variable outside of the loop.

So the idea in question is that the name of the variable “piso” change dynamically according to the position of “i” and “j”

The expected result is this:

i=0 j=1
piso01
i=0 j=2
piso02
......... and so on.

The end result in general that I want is that I can call the shape in question and take their vertices to work it out individually in another for loop.