setting the background to #eeeeee in react

I know this is probably a very stupid question but somehow I couldn’t find any valid answer googling and searching around.

I’m currently using this css on my outer div to mimic the background property:

    function App() {
      const [windowDimension, setWindowDimension] = useState(0);
    
      useEffect(() => {
        setWindowDimension(window.innerHeight);
      }, []);
    
      useEffect(() => {
        function handleResize() {
          setWindowDimension(window.innerHeight);
        }
    
        window.addEventListener("resize", handleResize);
        return () => window.removeEventListener("resize", handleResize);
      }, []);
      return (

          <div
            
            style={{
              backgroundColor: "#eeeeee",
              height: windowDimension,
            }}
          >
[content...]
    </div>
    
    );
}

Is there a proper way to do it? This solution doesn’t feel quite right even tho gets the job done. The thing is that I don’t want to have future unexpected behaviors because of this little gimmick.

Is there any better way to use transliteration function in ACE editor

I am working on project where i need transliteration support in ace editor

Currently my code look like this

editor.container.addEventListener("keydown", (key) => {
  if (toggleBtn.checked) {
    if (key.code == "Space" || key.code == "Enter") {
      let pos = session.selection.getCursor();
      let text = session.doc.$lines[pos.row]
        .slice(0, pos.column)
        .split(" ")
        .pop();
      let transliteratedStr = transliteratorFuction(text); //this is return Eng to Sanskrit transliteration
      editor.session.replace(
        {
          start: {
            row: pos.row,
            column: pos.column - text.length,
          },
          end: pos,
        },
        transliteratedStr
      );
    }
  }
});

Is there any better way to do it.

Any suggestions.

How can I create an array of keys and an array of values from an object in Javascript

I would like to know how could I create two arrays from an object, one array of the keys and other array of the values, like this example:

var obj = { ferrari:80000, porshe:60000, mercedes:50000.99};

// What I need
var keys = ["ferrari","porshe","mercedes"]; //Array of strings
var values = [80000, 60000, 50000.99]; //Array of float

I’m trying to do it using Object.keys(obj), but with no success.

Any suggestion ?

How to dispatch event on Push receive using Workbox?

I have a VueJS component where I listen for pushMessageEvent :

<template>
  <div>
    <VueBotUI
        :options="options"
        :is-open="isOpen"
        :bot-typing="botTyping"
        :input-disable="inputDisable"
        :messages="messages"
        @msg-send="onSend"

    ></VueBotUI>
  </div>

</template>
<script>
export default {
  components: {
    VueBotUI
  },
  data: function () {
    return {
      options: {botTitle: 'test',},
      user: {msg: null,},
      msgRegex: /^[a-zA-Z ]+$/,
      messages: []
    }
  },

  mounted() {
    document.addEventListener('pushMsgEvent', this.printPush);
  },
  beforeDestroy () {
    document.removeEventListener('pushMsgEvent', this.printPush);
  },
  methods: {
    printPush (e) {
      console.log(e)
      console.log("------------------")
      console.log(e.detail)
    },
  }
}
</script>

And I want to fire this pushMessageEvent when I get a Push event in my service-worker:

/* eslint-disable */
importScripts(
  "https://storage.googleapis.com/workbox-cdn/releases/4.3.1/workbox-sw.js"
);

// Load all ENVERYWHERE enviroment variables
importScripts('./env-vars.js')

const PushMsgEvent = new CustomEvent('pushMsgEvent', { detail: null });

workbox.core.skipWaiting();
workbox.core.clientsClaim();

self.__WB_MANIFEST;

// Listen to push event
self.addEventListener("push", (event) => {
  if (event.data) {
    console.log(`[Service Worker] Push had this data: "${event.data.text()}"`);

    PushMsgEvent.detail = event.data.text();
    //document.dispatchEvent(PushMsgEvent);
  }
});

workbox.precaching.precacheAndRoute([]);

but I can’t use document.dispatchEvent since I get document is not defined, is it a workaround to fire this event and catch it in my component ?

I have read about workbox-window but I can’t figure out how to fire my event from the service-worker in order to catch it in the component

Can a some() function replace nested forEach()?

I need to replace two (nested) forEach loops with a some function. The purpose of the code block is to check if the [1] elements in arrayOne are within the max & min of arrayTwo.

The code currently works fine and looks like this:

    var result = false;
    arrayOne.forEach((arrayOneElement) => {
      arrayTwo.forEach((arrayTwoElement) => {
        if (arrayOneElement[1] > arrayTwoElement[1].max || arrayOneElement[1] < arrayTwoElement[1].min) {
          result = true;
        }
      });
    }); 

Let me know if it isn’t clear enough. Really appreciate your help.

Adding Const Data Array to HTML and using the data source

So I’m new to JS and doing an exercise where I wanna create a shopping cart. The requirement is to use “dynamic data source” and not hardcode attributes into the HTML so I’ve created this object that I want to just display in my HTML, for example the description, the image etc.. I got everything to work with “static” attributes in the HTML following a tutorial, but I wanna use a data-source instead since that is a more real case, where you’d update the data source and that would then automatically be updated on the webpage.

const products =
    [
        {
           {
            "name": "Purple Haze",
            "origin": "Netherlands",
            "description": "420",
            "height": "50-100cm",
            "image": "something",
            "price": "something"
        },  
        {
            "name": "Hemp",
            "origin": "Netherlands",
            "description": "420",
            "height": "50-100cm",
            "image": "something",
            "price": "something"
        }
    ];
<div id="products">
<button class="btn btn-primary shop-item-button" type="button">ADD TO CART</button>
</div>

Modal alert window not opening nor displaying message

I’m working on an admin dashboard. The file in question is called client-edit.php that contains a form which gets updated in client-update.php. I can update all fields no problem, but I’m stuck at display a modal alert. Here’s a snippet of my code:

client-edit.php

<!DOCTYPE html>
<html lang="en">
<head>
  <title></title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <!--custom style-->
  <link rel="stylesheet" href="../bootstrap/4.4.1/css/bootstrap.min.css">
  <link rel="stylesheet" href="../css/style2.css">

 <!-- required for tooltips -->
  <script src="../ajax/libs/jquery/3.5.1/jquery.min.js"></script>
  <link rel="stylesheet" href="../vendors/ti-icons/css/themify-icons.css">
  <link rel="stylesheet" href="../vendors/base/vendor.bundle.base.css">  
  
  
<!-- modal window editor   -->
<script src="../ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<link rel="stylesheet" href="modal.min.css" />  
<script src="../bootstrap/3.3.6/js/bootstrap.min.js"></script>  

</head>
<body>

<form name="clientupdate" id="form1" method="post">
<!-- FORM ELEMENTS IN HERE -->
<button class="btn btn-success" type="submit" >Save</button>
</form>



<!-- Alert Dialog -->
<div class="modal fade" id="myModal"  role="dialog">
<div class="modal-dialog">
    <div class="modal-content">
            <div class="modal-body">
                <div id="messages"></div>
            </div>
    </div>
</div>
</div>
<!-- End alert dialog box -->


</body>
</html>


        <script>
            $('#form1').submit(function(e) {

                var form = $(this);
                var formdata = false;
                if(window.FormData){
                    formdata = new FormData(form[0]);
                }

                var formAction = form.attr('action');

                $.ajax({
                    type        : 'POST',
                    url         : 'client-update.php',
                    cache       : false,
                    data        : formdata ? formdata : form.serialize(),
                    contentType : false,
                    processData : false,
                    dataType: 'json',

                    success: function(response) {
                        //TARGET THE MESSAGES DIV IN THE MODAL
                        if(response.type == 'success') {
                           $('#messages').addClass('alert alert-success').text(response.message);
                            $('#myModal').modal('toggle');
                        } else {
                            $('#messages').addClass('alert alert-danger').text(response.message);
                             $('#myModal').modal('toggle');
                        }

                    }
                });
                e.preventDefault();
            });
        </script>

client-update.php


// if successfully updated. 
$success = true;

if($success == true) {
   // $output = json_encode(array('type'=>'success', 'message' => 'Successfully Updated.'));
   $output = "successful";
} else {
    $output = json_encode(array('type'=>'error', 'message' => 'There was an error saving.'));
}

//die($output);
echo json_encode($output);

Not sure where the problem lies.

Strange output when converting SVG to PDF javascript mermaid.js example

I’m trying to output this SVG to a pdf. The SVG is generated by mermaid.js

I found an existing answer on stack for converting SVG to PDF. This answer defined a function downloadPDF which converts SVG to PDF and triggers the PDF download.

When I run this function in the below minimal example, I get output, but the output looks all grayed-out. Can someone help me output the given SVG to PDF correctly?

Here is a minimal example:

<!DOCTYPE html>
<html lang="en" style="height: auto;">
<head>
</head>

<body>
    <div class="mermaid">
        graph TD;
        A-->B;
        A-->C;
        B-->D;
        C-->D;
    </div>
</body>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/mermaid/8.13.4/mermaid.min.js"></script>

<script src="https://cdn.jsdelivr.net/npm/[email protected]/js/pdfkit.standalone.js"></script>
<script src="https://bundle.run/[email protected]"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/source.js"></script>

<script>
mermaid.init({
    flowchart: { useMaxWidth: false },
    "theme": "default",
    "themeVariables": {
        "fontFamily": "Helvetica"
    },
    "sequence": {
        "actorFontFamily": "Helvetica",
        "noteFontFamily": "Helvetica",
        "messageFontFamily": "Helvetica"
    },
    "journey": {
        "taskFontFamily": "Helvetica"
    }
}, document.querySelectorAll(".mermaid"));
</script>

<script>
function downloadPDF(svg, outFileName) {
    let doc = new PDFDocument({compress: false});
    SVGtoPDF(doc, svg, 0, 0);
    //SVGtoPDF(doc, svg, doc.x, doc.y, { useCSS: true });
    let stream = doc.pipe(blobStream());
    stream.on('finish', () => {
      let blob = stream.toBlob('application/pdf');
      const link = document.createElement('a');
      link.href = URL.createObjectURL(blob);
      link.download = outFileName + ".pdf";
      link.click();
    });
    doc.end();
}
var svg = document.querySelector('svg');
</script>

To produce the PDF, paste this into the browser development console: downloadPDF(svg, "test")

Here is the svg image produced by minimal example:
Original SVG

Here is the image output from the downloadPDF function:

pdf made from SVG

Note: I’m getting this same output with Firefox and Edge browsers.

Table row selection with pagination using Laravel + Inertia + React

I’m trying to display a table that has selectable rows that I will later send with a form to my controller.

For now I got it working but my problem is that in the same table I got a search box and a pagination. They both work together ok but when I have selected rows and then try to search or paginate I lose the state of my selected rows.

This is my component:

import React, {useState} from 'react';
import Input from "@/Components/Form/Input";
import { Inertia } from "@inertiajs/inertia";
import {usePage, useForm, useRemember} from "@inertiajs/inertia-react";
import Main from "../../Layouts/Main"
import Table from "@/Components/Table/Table";
import Search from "@/Components/Search";
import ErrorForm from "@/Components/Form/ErrorForm";
import Paginator from "@/Components/Table/Paginator";
import {usePrevious} from "react-use";

const Create = () => {
    const cuentas = usePage().props.cuentas.data
    const links = usePage().props.cuentas.links
    const { data, processing, errors } = useForm({
        codigoPartida : '',
        nombrePartida : '',
        tipoPartida : 'gasto',
        cuentas : []
    })

    function submit(e) {
        e.preventDefault()
        data.codigoPartida = document.getElementById('codigoPartida').value
        data.nombrePartida = document.getElementById('nombrePartida').value
        document.querySelectorAll('.row-select').forEach(function(item){
            if(!data.cuentas.includes(item)){
                if(item.checked){
                    data.cuentas.push(item.value)
                }
            }
        });
        console.log(data)
        //Inertia.post('/nueva-partida-presupuestaria',data)
    }

    function handleChange(e){
        if(e.target.checked){
            document.querySelectorAll('.row-select').forEach(function(item){
                item.checked = true
            })
        }else{
            document.querySelectorAll('.row-select').forEach(function(item){
                item.checked = false
            })
        }
    }

    return (
        <>
            <div className="flex justify-between mb-2">
                <h2>Alta Partida Presupuestaria</h2>
            </div>

            <form className="create-form" id="create-form" onSubmit={submit}>
                <Input
                    name="codigoPartida"
                    type="text"
                    id="codigoPartida"
                    placeholder="Código"
                />
                {errors.codigoPartida &&
                    <ErrorForm
                        content={errors.codigoPartida}
                    />
                }
                <Input
                    name="nombrePartida"
                    type="text"
                    id="nombrePartida"
                    placeholder="Descripción"
                />
                {errors.codigoPartida &&
                    <ErrorForm
                        content={errors.codigoPartida}
                    />
                }
                <button className="btn-consejo" type="submit" disabled={processing}>Crear</button>
            </form>
            <h2>Agregar Cuenta Contable</h2>
            <div className="flex justify-between">
                <Search />
            </div>
            <table className="min-w-full">
                <thead>
                <tr>
                    <th>
                        <input
                            id="select-all"
                            name="select-all"
                            type="checkbox"
                            onChange={handleChange}
                        />
                    </th>
                    <th className="px-6 py-3 text-xs font-medium leading-4 tracking-wider text-left text-gray-500 uppercase border-b border-gray-200 bg-gray-504">Codigo</th>
                    <th className="px-6 py-3 text-xs font-medium leading-4 tracking-wider text-left text-gray-500 uppercase border-b border-gray-200 bg-gray-504">Cuenta</th>
                    <th className="px-6 py-3 text-xs font-medium leading-4 tracking-wider text-left text-gray-500 uppercase border-b border-gray-200 bg-gray-504">Clase</th>
                </tr>
                </thead>
                <tbody>
                {cuentas.map(({ id, COD_CUENTA, DESC_CUENTA, ID_CLASE_CUENTA }) => {
                    return (
                        <tr key={id}>
                            <td><input type="checkbox" value={id} name="row-select" className="row-select" /></td>
                            <td>{COD_CUENTA}</td>
                            <td>{DESC_CUENTA}</td>
                            <td>{ID_CLASE_CUENTA}</td>
                        </tr>
                    )
                })}
                {cuentas.length === 0 && (
                    <tr>
                        <td colSpan="4">
                            No se encontraron cuentas disponibles.
                        </td>
                    </tr>
                )}
                </tbody>
            </table>
            <Paginator links={links} />
        </>
    );
}

Create.layout = page => <Main title="Alta Partida Presupuestaria" children={page} />

export default Create

And also my Paginator and Search Components:

import React from 'react';
import { InertiaLink } from '@inertiajs/inertia-react';

const PageLink = ({ active, label, url }) => {
    return (
        <InertiaLink href={url} preserveState>
            <span dangerouslySetInnerHTML={{ __html: label }}></span>
        </InertiaLink>
    );
};

// Previous, if on first page
// Next, if on last page
// and dots, if exists (...)
const PageInactive = ({ label }) => {
    return (
        <div dangerouslySetInnerHTML={{ __html: label }} />
    );
};

export default ({ links = [] }) => {
    // dont render, if there's only 1 page (previous, 1, next)
    if (links.length === 3) return null;

    return (
        <div className="flex flex-wrap mt-6 -mb-1">
            {links.map(({ active, label, url }) => {
                return url === null ? (
                    <PageInactive key={label} label={label} />
                ) : (
                    <PageLink key={label} label={label} active={active} url={url} />
                );
            })}
        </div>
    );
};

import React, { useState, useEffect, useRef } from 'react';
import { Inertia } from '@inertiajs/inertia';
import {usePage, useRemember} from '@inertiajs/inertia-react';
import { usePrevious } from 'react-use';
import pickBy from 'lodash/pickBy';

export default () => {
    const { filters } = usePage().props;

    const [values, setValues] = useState({
        search: filters.search || '',
    });

    const prevValues = usePrevious(values);

    useEffect(() => {
        // https://reactjs.org/docs/hooks-faq.html#how-to-get-the-previous-props-or-state
        if (prevValues) {
            const query = pickBy(values)
            Inertia.get(route(route().current()), query, {
                replace: true,
                preserveState: true
            });
        }
    }, [values]);

    function handleChange(e) {
        const key = e.target.name;
        const value = e.target.value;

        setValues(values => ({
            ...values,
            [key]: value
        }));
    }

    return (
        <div className="flex items-center w-full max-w-md mr-4">
            <div className="relative flex w-full bg-white rounded shadow">
                <input
                    className="relative w-full px-6 py-3 rounded-r focus:outline-none focus:ring-2 focus:ring-indigo-400"
                    autoComplete="off"
                    type="text"
                    name="search"
                    name="search"
                    value={values.search}
                    onChange={handleChange}
                    placeholder="Search…"
                />
            </div>
        </div>
    )
}

How would I go to get the expected behaviour. I’m kind of new to react.

I would really appreciate the help!

Image of the UI

Error when submitting form “TypeError: Cannot read properties of undefined (reading ‘firstName’)”

I tried to submitted the input from my add.ejs to send it to my mongodb.

add.ejs

<body>
<div class="container">
    <div class="row my-3 justify-content-md-center">
        <div class="col-md-8 mb-4">
            <form class="form-horizontal" method="POST" action="/insert" enctype="multipart/form-data">
                <div class="form-group">
                    <div style="height: 125px;"></div>
                    <label class="control-label col-sm-2">Picture: </label>
                    <div class="col-sm-10">
                        <input type="file" class="form-control" style= "background-color: #1E0E81;
                        color: white; " name="image">
                    </div>
                </div>
                <div class="form-group">
                    <label class="control-label col-sm-2">First Name: </label>
                    <div class="col-sm-10">
                        <input type="text" class="form-control" style= "background-color: #1E0E81;
                        color: white;" name="firstName">
                    </div>
                </div>
                <div class="form-group">
                    <label class="control-label col-sm-2">Last Name: </label>
                    <div class="col-sm-10">
                        <input type="text" class="form-control" style= "background-color: #1E0E81;
                        color: white; " name="lastName">
                    </div>
                </div>
                <div class="form-group">
                    <label class="control-label col-sm-2">Email: </label>
                    <div class="col-sm-10">
                        <input type="text" class="form-control" style= "background-color: #1E0E81;
                        color: white; " name="email">
                    </div>
                </div>
                <div class="form-group">
                    <label class="control-label col-sm-2">Telephone: </label>
                    <div class="col-sm-10">
                        <input type="text" class="form-control" style= "background-color: #1E0E81;
                        color: white; " name="telephone">
                    </div>
                </div>
                <div class="form-group">
                    <label class="control-label col-sm-2">Description: </label>
                    <div class="col-sm-10">
                        <input type="text" class="form-control" style= "background-color: #1E0E81;
                        color: white; " name="description">
                    </div>
                </div><br>
                <div class="form-group">
                    <div class="col-sm-offset-2 col-sm-10">
                        <button type="submit" class="btn btn-primary">Submit</button>
                    </div>
                </div>
            </form>
        </div>
    </div>
</div>

Now and then, I got an error “Cannot POST /insert“. So I tried to console.log first to see what the error is and I got error message “TypeError: Cannot read properties of undefined (reading ‘firstName’)

Here is my routes file.

myRouter.js

const express =require('express')
const router = express.Router()


const Gallery = require('../models/gallery') 


const multer = require('multer')

const storage = multer.diskStorage({
    destination:function(req,file,cb){
        cb(null,'./public/image/galleries') 
    },
    filename:function(req,file,cb){
        cb(null,Date.now()+".jpg") 
    }
})


const upload = multer({
    storage:storage
})

router.get('/',(req,res)=>{
    Gallery.find().exec((err,doc)=>{
        res.render('home.ejs',{gallery:doc})
    })
})

router.get('/donate',(req,res)=>{
    res.render('donate.ejs')
})

router.get('/add',(req,res)=>{
    res.render('add.ejs')
})

router.post('/insert'),upload.single("image"),(req,res)=>{
    let data = new Gallery({
        firstName:req.body.firstName,
        lastName:req.body.lastName,
        email:req.body.email,
        telephone:req.body.telephone,
        description:req.body.description,
        image:req.file.filename
    })
    Gallery.saveGallery(data,(err)=>{
        if(err) console.log(err)
        res.redirect('/')
    }) 
}
// router.post('/insert',(req,res)=>{
//     console.log(req.body.firstName),
//     console.log(req.body.lastName),
//     console.log(req.body.email),
//     console.log(req.body.telephone),
//     console.log(req.body.description),
//     console.log(req.body.image)
//     res.render('add')
// })

module.exports = router

Please help me find out what the problems is

XDSoft Datetimepicker Decrements Time One Hour After Clicking Out of Input Field

I am using the XDSoft Datetimepicker. I can choose a datetime, but when I click out of the input field, the hour of the time decrements by one hour. Here is an example:

This is when I pick a datetime (successfully):
step 1

And this is what is looks like immediately after choosing a datetime:
step 2

Finally, this is what it looks like when the input loses focus, i.e. when I click outside of the input:
step 3

Any ideas what could be causing this and how to fix this?

Looping through objects in arrays to compare values

I have two arrays composed of objects. One array is made of restaurant objects with properties name and averagePrice. The other array is made of price objects (cheap, medium, expensive) with properties label, lowEnd, and highEnd. lowEnd and highEnd represent the thresholds that determine if the restaurant is cheap, medium, or expensive. I want to create a function that loops through the restaurants, and returns the restaurant whose average price lands within the given price range. I get an error that says:

Cannot read properties of undefined (reading: lowEnd)

I know that this is because I am not properly targeting the array object property of the price. Can someone help me figure out how to properly target an array object property? Thanks

Here is my code

    const priceArray = [
    cheap = {label: '$', lowEnd: 10, highEnd: 20},
    medium = {label: '$$', lowEnd: 21, highEnd: 30},
    expensive = {label: '$$$', lowEnd: 31, highEnd: 40},

];


const restaurants = [
    McDonalds = {name: 'Mcdonalds', averagePrice: 12},
    Sushi = {name: 'Sushi', averagePrice: 25},
    Steak = {name: 'Steak', averagePrice: 35}
];




function showRestaurants(price) {
    for (let restaurant of restaurants) {
    //if the average price is cheap, log that restaurant
            if (restaurant.averagePrice >= priceArray.price.lowEnd && restaurant.averagePrice < priceArray.price.highEnd)
                console.log(restaurant);
        }
};

showRestaurants(medium);

Heroku Blank Screen on Deploy: React, and Ruby on Rails

I have a Heroku test environment with a Ruby on Rails backend and React front-end. Recently, I pushed out some changes to the test environment and am now getting a blank screen with one of two errors. Either:

<body><noscript>You need to enable JavaScript to run this app.</noscript><div id="root"></div><script type="text/javascript" src="/static/js/main.d825ec61.js"></script></body>

or:

Uncaught TypeError: Cannot read properties of undefined (reading 'apply')
    at redux.js:523:1
    at o (redux.js:87:1)
    at Object.<anonymous> (store.js:14:15)
    at t (bootstrap 145a692a3e0162c12867:19:1)
    at Object.<anonymous> (main.d825ec61.js:30447:65)
    at t (bootstrap 145a692a3e0162c12867:19:1)
    at Object.<anonymous> (main.d825ec61.js:29463:18)
    at t (bootstrap 145a692a3e0162c12867:19:1)
    at bootstrap 145a692a3e0162c12867:62:1
    at bootstrap 145a692a3e0162c12867:62:1

depending upon who is trying to open the app.

Here is a link to the test site on Heroku: https://alutiiq-lang-test.herokuapp.com/ Please note that it is a free dyno, so takes a minute to load (if it loads for you!), and here is the repo I am working in https://github.com/migobach/alutiiqLang.

When I do roll back to a previous version, it works fine, but I cannot figure out what the difference is aside from on package that I added: "react-contenteditable": "^3.3.5", which I need for admin privileges.

TypeError : Cannot read properties of null

TypeError : Cannot read properties of null ( reading ‘ textContent ‘ ) at Object.23383

Error 01, click to check

error 02, click to check

Getting this error while working on WordPress anybody has any solution?
Here’s the files links: https://evimna.com/clv/wp-content/themes/clv/s2/_next/static/chunks/main-c8ccad8e4d4a6a17cfea.js?ver=5.9.3

https://evimna.com/clv/wp-content/themes/clv/s2/_next/static/chunks/webpack-fb6e33ffc99c851eebfc.js?ver=5.9.3