My React code is not showing in the browser with Vite

My code is not showing. I have a Vite site and my .html and .css work correctly but my .jsx is not showing. When I inspect the page something weird appears:

code when I open inspection

My HTML file however is:

<html>
    <head>
        <link rel="preconnect" href="https://fonts.googleapis.com">
        <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
        <link href="https://fonts.googleapis.com/css2?family=Inter:ital,opsz,wght@0,14..32,100..900;1,14..32,100..900&display=swap" rel="stylesheet">
        <link rel="stylesheet" href="/index.css">
    </head>
    <body>
        <div id="root"></div>
        <script src="./src/index.jsx" type="module"></script>
    </body>
</html>

and the index.jsx is:

import ReactDOM from 'react-dom/client';

ReactDOM.createRoot(document.getElementById('root')).render(<h1>Hello</h1>);

Items Removed via AJAX but Totals, Counter, and Buttons Not Updating

I’m working on a WooCommerce-based WordPress theme with a custom mini cart. The mini cart works fine, and I’m using AJAX to remove items without refreshing the page. However, when I click the remove button, the item is removed, but the following issues occur:

  1. The cart total (subtotal) does not update after removal.
  2. The cart item count remains the same instead of decreasing.
  3. The “View Cart” and “Checkout” buttons do not disappear when all items are removed.
    Here’s what I’ve implemented so far:

PHP (functions.php – AJAX Remove Item Handler)

    // Enqueue WooCommerce scripts
function mytheme_enqueue_woocommerce_scripts() {
  if (class_exists('WooCommerce')) {
      wp_enqueue_script('wc-cart-fragments');
  }
}
add_action('wp_enqueue_scripts', 'mytheme_enqueue_woocommerce_scripts');

function mytheme_get_mini_cart() {
  ob_start();
  ?>
  <div class="mini-cart">
      <a href="<?php echo wc_get_cart_url(); ?>" class="cart-contents">
          <span class="cart-icon"><i class="fa fa-shopping-basket"></i></span>
          <span class="cart-count"><?php echo WC()->cart->get_cart_contents_count(); ?></span>
      </a>
      
      <div class="mini-cart-dropdown">
          <?php if ( ! WC()->cart->is_empty() ) : ?>
              <ul class="cart-list">
                  <?php foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) : ?>
                      <?php
                      $_product   = apply_filters( 'woocommerce_cart_item_product', $cart_item['data'], $cart_item, $cart_item_key );
                      $product_id = apply_filters( 'woocommerce_cart_item_product_id', $cart_item['product_id'], $cart_item, $cart_item_key );
                      ?>
                      <li class="cart-item">
                          <div class="cart-item-image">
                              <?php echo $_product->get_image(); ?>
                          </div>
                          <div class="cart-item-details">
                              <h4 class="cart-item-title"><?php echo $_product->get_name(); ?></h4>
                              <p class="cart-item-quantity"><?php echo $cart_item['quantity']; ?> x <?php echo WC()->cart->get_product_price( $_product ); ?></p>
                          </div>
                          <div class="cart-item-remove">
                              <?php
                              echo apply_filters( 'woocommerce_cart_item_remove_link', sprintf(
                                  '<a href="%s" class="remove" aria-label="%s" data-product_id="%s" data-product_sku="%s">&times;</a>',
                                  esc_url( wc_get_cart_remove_url( $cart_item_key ) ),
                                  __( 'Remove this item', 'woocommerce' ),
                                  esc_attr( $product_id ),
                                  esc_attr( $_product->get_sku() )
                              ), $cart_item_key );
                              ?>
                          </div>
                      </li>
                  <?php endforeach; ?>
              </ul>
              <div class="cart-total">
                  <p><?php _e( 'Subtotal', 'woocommerce' ); ?>: <?php echo WC()->cart->get_cart_subtotal(); ?></p>
              </div>
              <div class="cart-actions">
                  <a href="<?php echo wc_get_cart_url(); ?>" class="button view-cart"><?php _e( 'View Cart', 'woocommerce' ); ?></a>
                  <a href="<?php echo wc_get_checkout_url(); ?>" class="button checkout"><?php _e( 'Checkout', 'woocommerce' ); ?></a>
              </div>
          <?php else : ?>
              <p class="empty-cart"><?php _e( 'Your cart is empty.', 'woocommerce' ); ?></p>
          <?php endif; ?>
      </div>
  </div>
  <?php
  return ob_get_clean();
}

function mytheme_ajax_remove_cart_item() {
  if (!isset($_POST['cart_item_key'])) {
      wp_send_json_error(['message' => __('Invalid request.', 'woocommerce')]);
  }

  $cart_item_key = sanitize_text_field($_POST['cart_item_key']);
  WC()->cart->remove_cart_item($cart_item_key);

  // Send updated mini cart back to the frontend
  wp_send_json_success([
      'fragments' => apply_filters('woocommerce_add_to_cart_fragments', [
          '.mini-cart' => mytheme_get_mini_cart()
      ])
  ]);
}
add_action('wp_ajax_woocommerce_remove_cart_item', 'mytheme_ajax_remove_cart_item');
add_action('wp_ajax_nopriv_woocommerce_remove_cart_item', 'mytheme_ajax_remove_cart_item');


function mytheme_add_to_cart_fragments($fragments) {
  $fragments['.mini-cart'] = mytheme_get_mini_cart();
  return $fragments;
}
add_filter('woocommerce_add_to_cart_fragments', 'mytheme_add_to_cart_fragments');

HTML

<?php echo mytheme_get_mini_cart(); ?>

JavaScript (custom.js – AJAX Remove Item Call)

jQuery(document).ready(function ($) {
    $(document.body).on('added_to_cart', function () {
        updateMiniCart();
    });
    $(document).on('click', '.mini-cart .remove', function (e) {
        e.preventDefault(); 
        var $this = $(this);
        var cartItemKey = $this.attr("href").split("remove_item=")[1].split("&")[0]; 
        $.ajax({
            type: "POST",
            url: wc_cart_fragments_params.ajax_url,
            data: {
                action: "woocommerce_remove_cart_item",
                cart_item_key: cartItemKey
            },
            beforeSend: function () {
                $this.closest(".cart-item").fadeOut(300);
            },
            success: function (response) {
                if (response.fragments) {
                    $(".mini-cart").replaceWith(response.fragments[".mini-cart"]);
                }
            }
        });
    });
    // Function to update mini cart
    function updateMiniCart() {
        $.ajax({
            url: wc_cart_fragments_params.ajax_url,
            type: "POST",
            data: {
                action: "woocommerce_get_refreshed_fragments"
            },
            success: function (response) {
                if (response.fragments) {
                    $(".mini-cart").replaceWith(response.fragments[".mini-cart"]);
                }
            }
        });
    }
});

What I Expect:

  1. When clicking the remove button, the item should be removed, the subtotal should update, and the cart count should decrease.
  2. If the cart becomes empty, the “View Cart” and “Checkout” buttons should disappear, showing only the “Your cart is empty” message.

Issue:

  1. The item is removed, but the cart count, subtotal, and buttons are not updating dynamically.
  2. I suspect WooCommerce may not be refreshing the cart fragments properly.

Example screenshot:

enter image description here

React Quill disappears when i try to add callback in the modules

Problem:

When I try to add a callback function inside the modules prop of ReactQuill, the Quill editor does not render at all. There are no errors or warnings in the console. only the footer section (which I added separately) is rendered.

The div rendered in the DOM for Quill looks like this:
<div class="quill "><div></div></div>

What I’ve Tried:

I tried to write custom modules that takes a callback from the modules options, the quill editor disappeared. Then I tried to use modules that would allow me to pass callbacks like quill-image-uploader the same happened.

Packages used:

  • Quill Blot Formatter : npm i quill-blot-formatter
  • Quill Toggle Fullscreen Button : npm i quill-toggle-fullscreen-button

Code (generalized version):

import React, { useRef, useState } from "react";
import ReactQuill from "react-quill";
import styled from "styled-components";
import { v4 } from "uuid";

// Register custom modules
import BlotFormatter from "quill-blot-formatter";
import QuillToggleFullscreenButton from "quill-toggle-fullscreen-button";
import { Validator } from "./CustomModule"; // with options { updateCountsCallback : ({words: number, chars: number, images: number, videos: number })=> void; }

import { Quill } from "react-quill";

// Register the modules globally
Quill.register("modules/blotFormatter", BlotFormatter);
Quill.register("modules/toggleFullscreen", QuillToggleFullscreenButton);
Quill.register("modules/validator", Validator);

const MyQuillComponent = ({
  placeholder,
  readOnly,
  footerProps,
  value,
  onChange,
  height,
  modules,
}: any) => {
  const quillRef = useRef<ReactQuill | null>(null);
  const updateCounts = (newCounts: { words: number; chars: number; images: number; videos: number }) => {
    setCounts(newCounts);
  };

  const defaultModules = {
    validator: {
      updateCountsCallback: updateCounts,// <- callback here 
    }, 
    blotFormatter: {},
    toggleFullscreen: true,
  };

  return (
      <ReactQuill
        placeholder={placeholder}
        readOnly={readOnly}
        modules={modules ?? defaultModules}
        value={value}
        ref={(el) => {
          if (el) {
            quillRef.current = el;
          }
        }}
        onChange={(value) => onChange && onChange(value)}
      />
      {/* Footer Section */}
      {footerProps && (
        <div className="footer">
          <span>Words: {counts.words}</span>
          <span>Characters: {counts.chars}</span>
        </div>
      )}
  );
};

updateMany setting field to size of filter condition with not in array

I have a document like this:

{
  id: string,
  subDocCount: number,
  subDocs: [
    {
      id: string (not an ObjectId),
      dateField: Date,
      booleanField: boolean
    }
  ]
}

I want to set the subDocCount field to the count of subDocs where:

  • booleanField is false
  • AND (dateField is null OR dateField is in the past)
  • AND subDoc id is not in given array of ids

I have tried with this updateMany query but have not been able to figure out the “not in array” part (mongoosejs by the way):

  await docs.updateMany(
    {},
    [
      {
        $set: {
          subDocCount: {
            $size: {
              $filter: {
                input: '$subDocs',
                as: 'subDoc',
                cond: {
                  $and: [
                    { $eq: ['$$subDoc.booleanField', false] },
                    {
                      $or: [
                        { $eq: ['$$subDoc.dateField', null] },
                        { $lt: ['$$subDoc.dateField', startOfToday()] }
                      ]
                    },
                    // this part doesn't work, but doesn't cause an error
                    { $not: { $in: ["$$subDoc.id", excludedJobIds] } }
                  ]
                }
              }
            }
          }
        }
      }
    ]
  )

Am I able to somehow use a “not in array” type of clause in the filter here?

Why UTC time doesnt seem to work properly in different timezones? [duplicate]

What I am trying to do

I have written the following code, whose sole purpose is to find the difference in days. For example, if the dueDate is tomorrow’s date. Then the diffDays will hold the value 1, if its today’s, then the value will be 0 and if it’s yesterday’s, then the diffDays value will be -1.

const dueDate = "2025-03-20";

// Get today's date in UTC (ignoring time)
const today = new Date();
today.setHours(0, 0, 0, 0);
const todayUTC = Date.UTC(
    today.getUTCFullYear(),
    today.getUTCMonth(),
    today.getUTCDate()
);

// Parse the task's due date
const dueDate = parseDueDate(dueDate);
if (!dueDate) return false;

dueDate.setHours(0, 0, 0, 0);
const dueDateUTC = Date.UTC(
    dueDate.getUTCFullYear(),
    dueDate.getUTCMonth(),
    dueDate.getUTCDate()
);

// Calculate difference in full days
const diffDays = Math.round(
    (dueDateUTC - todayUTC) / (1000 * 3600 * 24)
);

What I am getting

The code works perfectly fine in my timezone (IST), but it behaves very weird in other timezones, like it will always give the value one less than the expected, or some timezones, it will give unexpected value before 19:00, etc.

In EST timezone

Tested through Developers Console Window in EST timezone

In GMT-3

The deffDays, always gives value as 1 less than expected. For, example if `today` date is ‘2025-03-20’ and `dueDate` is ‘2025-03-21’. Then the code should give value as 1. But it gives value as 0.

Help

Why it behaves so differently in different timezones?

Really appreciate if anyone could provide me the optimized code to achieve this.

Resources

Link to the GitHub Issue : https://github.com/tu2-atmanand/Task-Board/issues/130

MongoDB updateMany setting field to size of filter condition with not in array

I have a document like this:

{
  id: string,
  subDocCount: number,
  subDocs: [
    {
      id: string (not an ObjectId),
      dateField: Date,
      booleanField: boolean
    }
  ]
}

I want to set the subDocCount field to the count of subDocs where:

  • booleanField is false
  • AND (dateField is not null OR dateField is in the past)
  • AND subDoc id is not in given array of ids

I have tried with this updateMany query but have not been able to figure out the “not in array” part (mongoosejs by the way):

  await docs.updateMany(
    {},
    [
      {
        $set: {
          subDocCount: {
            $size: {
              $filter: {
                input: '$subDocs',
                as: 'subDoc',
                cond: {
                  $and: [
                    { $eq: ['$$subDoc.booleanField', false] },
                    {
                      $or: [
                        { $eq: ['$$subDoc.dateField', null] },
                        { $lt: ['$$subDoc.dateField', startOfToday()] }
                      ]
                    },
                    // this part doesn't work, but doesn't cause an error
                    { $not: { $in: ["$$subDoc.id", excludedJobIds] } }
                  ]
                }
              }
            }
          }
        }
      }
    ]
  )

Am I able to somehow use a “not in array” type of clause in the filter here?

Why UTC time doesnt seem to work properly in different timezones?

What I am trying to do

I have written the following code, whose sole purpose is to find the difference in days. For example, if the dueDate is tomorrow’s date. Then the diffDays will hold the value 1, if its today’s, then the value will be 0 and if it’s yesterday’s, then the diffDays value will be -1.

const dueDate = "2025-03-20";

// Get today's date in UTC (ignoring time)
const today = new Date();
today.setHours(0, 0, 0, 0);
const todayUTC = Date.UTC(
    today.getUTCFullYear(),
    today.getUTCMonth(),
    today.getUTCDate()
);

// Parse the task's due date
const dueDate = parseDueDate(dueDate);
if (!dueDate) return false;

dueDate.setHours(0, 0, 0, 0);
const dueDateUTC = Date.UTC(
    dueDate.getUTCFullYear(),
    dueDate.getUTCMonth(),
    dueDate.getUTCDate()
);

// Calculate difference in full days
const diffDays = Math.round(
    (dueDateUTC - todayUTC) / (1000 * 3600 * 24)
);

What I am getting

The code works perfectly fine in my timezone (IST), but it behaves very weird in other timezones, like it will always give the value one less than the expected, or some timezones, it will give unexpected value before 19:00, etc.

In EST timezone

Tested through Developers Console Window in EST timezone

In GMT-3

The deffDays, always gives value as 1 less than expected. For, example if `today` date is ‘2025-03-20’ and `dueDate` is ‘2025-03-21’. Then the code should give value as 1. But it gives value as 0.

Help

Why it behaves so differently in different timezones?

Really appreciate if anyone could provide me the optimized code to achieve this.

Resources

Link to the GitHub Issue : https://github.com/tu2-atmanand/Task-Board/issues/130

NeCKEditor Security Warning After Updating to Latest Version

I was using CKEditor 4.16.0 and received a security warning:

This CKEditor 4.16.0 version is not secure. Consider upgrading to the latest one, 4.25.1.

To fix this, I downloaded the latest version (4.25.1) and replaced the old CKEditor files via cPanel File Manager. However, when I checked the editor, the same security warning still appears.

I have already tried the following:

Cleared browser cache
Cleared server-side cache
Hard refreshed the page (Ctrl + Shift + R)
Ensured that all CKEditor files were properly replaced
But the issue persists.

Is there something else I need to do to fully update CKEditor and remove this security warning? Any help would be appreciated.

Text not displaying calculated numbers in PDF where console logging correctly

I am using jsPDF in a Vue 2 project to generate a PDF report. The issue I’m facing is that my calculated numbers are not appearing in the generated PDF, even though they print correctly in the console.The data type of totalNumberOfLicense.USED and FREE are long(as per server side).

const totalBind = Number(this.totalNumberOfLicense.USED);
const totalAvailable = Number(this.totalNumberOfLicense.FREE);
const newLicenseIssued = totalAvailable + totalBind;


console.log("totalBind : ", totalBind);
console.log("Free: ", totalAvailable);
console.log("New License Issued: ", newLicenseIssued);

const licenseSummary = `Base License (New License Issued): ${newLicenseIssued},Total Bind: ${totalBind}, Total Available: ${totalAvailable}`;

doc.text(licenseSummary, leftMargin, imgY + imgHeight + 44);

Console output

totalBind :  536
Free:  13525
New License Issued:  14061

However, in the generated PDF, the text appears as:

Base License (New License Issued): , Total Bind: , Total Available: 

How to fix this issue ?

Problem with js function for Leaflet Marker Cluster

var clusterM = L.markerClusterGroup();

var geojsonPoints = new L.GeoJSON.AJAX("Files/Coordinates/coordonate_rk.geojson", {
    pointToLayer: function (feature, latlng) {
        if (type== 'All') {
            switch (feature.properties.Servicii) {
                case 'A': return L.circleMarker(latlng, geojsonMarkerOptions1);
                case 'B': return L.circleMarker(latlng, geojsonMarkerOptions2);
                default : return L.circleMarker(latlng, geojsonMarkerOptions3);
            }
        }
        if (type == 'A') {
            switch (feature.properties.Servicii) {
                case 'A': return L.circleMarker(latlng, geojsonMarkerOptions1);
                default :
            }
        }
        if (type == 'B') {
            switch (feature.properties.Servicii) {
                case 'B': return L.circleMarker(latlng, geojsonMarkerOptions2);
                default :
            }
        }
        if (type == 'Undefined') {
            switch (feature.properties.Servicii) {
                case '': return L.circleMarker(latlng, geojsonMarkerOptions3);
                default :
            }
        }
    
    
    },
    onEachFeature: function (feature, layer) {
        let popupContent = "<p style="font-size: 12px">Drum : " + feature.properties.Indicativ + "<br/>" + feature.properties.Obiectiv + "<br/>" + "Tip proiect : " + feature.properties.Servicii + "</p>";
        layer.on(
            {
                click: whenClicked 
            }
        ),
        layer.bindPopup(popupContent, {closeButton: false, offset: L.point(0, -20)});
        layer.on('mouseover', function() { layer.openPopup(); });
        layer.on('mouseout', function() { layer.closePopup(); });
    }
});

geojsonPoints.on('data:loaded', function () {
    console.log('Hello1');
    clusterM.addLayer(geojsonPoints);
    map.addLayer(clusterM);

});


//geojsonPoints.addTo(map);

I ran into the problem with Leaflet having a maximum number of markers it can display, and was trying out the cluster solution I found. Problem is, I can’t figure out why the on(‘data:loaded’) part is not working. It isn’t called at all. Initially I thought there was a problem with the markerClusterGroup, but the consol.log() isnt fired either. The geojsonPoints work, given how the commented geojsonPoints.addTo(map); function works. What am I missing?

I have looked into the following :

How to use leaflet markerclusterGroup?

Leaflet MarkerCluster with GeoJson

On a separate note, is there a way in Leaflet to edit the number of Markers that can be displayed? Or at least know what that number is?

Axios 0.25.0 to 1.8.2 Migration: failed on not being able to import axios

I updated the Axios from “axios”: “^0.25.0” to “axios”: “^1.8.2”, and Jest tests are not working anymore and app fails to start. Even after I add “jest”: { “transformIgnorePatterns”: [“node_modules/(?!axios)/”] } in package.json, jest still fails on importing axios.

1. Jest tests are not working with the following error:

    FAIL  src/domain/package/package-confirmation/__tests__/FileListItem.test.js
  ● Test suite failed to run

    Jest encountered an unexpected token

    Jest failed to parse a file. This happens e.g. when your code or its dependencies use non-standard JavaScript syntax, or when Jest is not configured to support such syntax.

    Out of the box Jest supports Babel, which will be used to transform your files into valid JS based on your Babel configuration.

    By default "node_modules" folder is ignored by transformers.

    Here's what you can do:
     • If you are trying to use ECMAScript Modules, see https://jestjs.io/docs/ecmascript-modules for how to enable it.
     • If you are trying to use TypeScript, see https://jestjs.io/docs/getting-started#using-typescript
     • To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config.
     • If you need a custom transformation specify a "transform" option in your config.
     • If you simply want to mock your non-JS modules (e.g. binary assets) you can stub them out with the "moduleNameMapper" config option.

    You'll find more details and examples of these config options in the docs:
    https://jestjs.io/docs/configuration
    For information about custom transformations, see:
    https://jestjs.io/docs/code-transformation

    Details:

    C:devjagjag-file-submission-devsrcfrontendefiling-frontendnode_modulesaxiosindex.js:1
    ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){import axios from './lib/axios.js'; // This module is intended to unwrap Axios default export as named.
                                                                                      ^^^^^^

    SyntaxError: Cannot use import statement outside a module

    > 1 | import axios from "axios";
        | ^
      2 | import FileSaver from "file-saver";
      3 |
      4 | /**

      at Runtime.createScriptFromCode (node_modules/jest-runtime/build/index.js:1728:14)
      at Object.<anonymous> (src/domain/documents/DocumentService.js:1:1)

2. yarn start fails with the following error:

ERROR in ./node_modules/axios/lib/utils.js 714:91-98
Module not found: Error: Can't resolve 'process/browser' in 'C:devjagjag-file-submission-devsrcfrontendefiling-frontendnode_modulesaxioslib'
Did you mean 'browser.js'?
BREAKING CHANGE: The request 'process/browser' failed to resolve only because it was resolved as fully specified
(probably because the origin is strict EcmaScript Module, e. g. a module with javascript mimetype, a '*.mjs' file, or a '*.js' file where the package.json contains '"type": "module"').
The extension in the request is mandatory for it to be fully specified.
Add the extension to the request.

ERROR in ./node_modules/axios/lib/utils.js
Cannot read properties of undefined (reading 'module')

webpack compiled with 2 errors and 2 warnings

3. package.json

{
  "name": "efiling-frontend",
  "version": "1.5.1",
  "private": true,
  "homepage": "/efilinghub",
  "dependencies": {
    "@babel/plugin-syntax-jsx": "^7.16.5",
    "@babel/preset-react": "^7.18.6",
    "@bcgov/bootstrap-theme": "github:bcgov/bootstrap-theme",
    "assert": "^2.0.0",
    "axios": "^0.25.0",
    "axios-auth-refresh": "^2.2.8",
    "babel-plugin-transform-export-extensions": "^6.22.0",
    "bootstrap": "^4.5.3",
    "browserslist": "^4.19.1",
    "buffer": "^6.0.3",
    "crypto-browserify": "^3.12.0",
    "dinero.js": "^1.8.1",
    "file-saver": "^2.0.2",
    "glob-parent": "^5.1.2",
    "history": "^5.0.0",
    "https-browserify": "^1.0.0",
    "install-peerdeps": "^3.0.3",
    "jsonwebtoken": "^9.0.0",
    "jwa": "^2.0.0",
    "jws": "^4.0.0",
    "keycloak-js": "^25.0.6",
    "moment": "^2.29.4",
    "object-hash": "^3.0.0",
    "object-path": "0.11.8",
    "os-browserify": "^0.3.0",
    "postcss-normalize": "^10.0.1",
    "process": "^0.11.10",
    "prop-types": "^15.7.2",
    "query-string": "^7.1.1",
    "react": "^16.13.1",
    "react-app-polyfill": "^3.0.0",
    "react-dom": "^16.13.1",
    "react-dropzone": "^11.3.2",
    "react-icons": "^4.1.0",
    "react-moment": "^1.1.1",
    "react-router-dom": "^6.1.1",
    "react-scripts": "^5.0.1",
    "reactstrap": "^8.9.0",
    "regenerator-runtime": "^0.13.7",
    "shared-components": "https://github.com/bcgov/react-shared-components/releases/download/v1.3.0/shared-components-1.3.0.tgz",
    "stream": "^0.0.2",
    "stream-browserify": "^3.0.0",
    "stream-http": "^3.2.0",
    "typescript": "^4",
    "url": "^0.11.0",
    "util": "^0.12.4",
    "validator": "^13.7.0"
  },
  "scripts": {
    "start": "react-app-rewired start",
    "build": "react-app-rewired build",
    "test": "jest --env='jsdom'",
    "eject": "react-app-rewired eject",
    "storybook": "start-storybook -p 9009 -s public",
    "build-storybook": "build-storybook -s public",
    "lint": "eslint .",
    "lint:fix": "eslint --fix .",
    "coverage": "jest --coverage --env='jsdom'",
    "precommit": "pretty-quick --staged"
  },
  "eslintConfig": {
    "extends": "react-app"
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  },
  "devDependencies": {
    "@babel/core": "^7.14.3",
    "@babel/plugin-syntax-typescript": "^7.12.13",
    "@babel/preset-env": "^7.14.4",
    "@storybook/addon-actions": "^6.4.19",
    "@storybook/addon-links": "^6.4.19",
    "@storybook/addon-storyshots": "^6.4.19",
    "@storybook/addon-viewport": "^6.4.19",
    "@storybook/addons": "^6.4.19",
    "@storybook/preset-create-react-app": "^4.1.2",
    "@storybook/react": "^6.4.19",
    "@testing-library/jest-dom": "^5.12.0",
    "@testing-library/react": "^11.2.7",
    "@testing-library/react-hooks": "7.0.2",
    "@testing-library/user-event": "^12.8.1",
    "axios-mock-adapter": "^1.19.0",
    "babel-loader": "8.2.3",
    "enzyme": "^3.11.0",
    "enzyme-adapter-react-16": "^1.15.6",
    "enzyme-to-json": "^3.6.1",
    "eslint-config-airbnb": "19.0.4",
    "eslint-config-prettier": "8.3.0",
    "eslint-plugin-airbnb": "^0.0.1-security",
    "eslint-plugin-import": "^2.25.3",
    "eslint-plugin-jsx-a11y": "^6.5.1",
    "eslint-plugin-prettier": "4.0.0",
    "eslint-plugin-react": "^7.31.11",
    "eslint-plugin-react-hooks": "^4.3.0",
    "fetch-mock-jest": "^1.5.1",
    "jest-environment-jsdom-sixteen": "^2.0.0",
    "jest-sonar-reporter": "^2.0.0",
    "moment-timezone": "^0.5.40",
    "prettier": ">=2.0.0",
    "pretty-quick": "^3.1.0",
    "react-app-rewired": "^2.2.1",
    "react-test-renderer": "^16.12.0",
    "sass": "^1.44.0"
  },
  "resolutions": {
    "immer": "^9.0.6",
    "trim": "^0.0.3",
    "glob-parent": "^5.1.2",
    "loader-utils": "^2.0.4",
    "nth-check": "^2.0.1",
    "terser": "^5.14.2",
    "json5": "^2.2.2",
    "minimatch": "^3.0.5",
    "webpack": "^5.76.0",
    "braces": "^3.0.3",
    "webpack-dev-middleware": "^5.3.4",
    "browserify-sign": "4.2.2",
    "ws": "^8.17.1",
    "rollup": "^2.79.2",
    "body-parser": "^1.20.3",
    "path-to-regexp": "^0.1.10",
    "http-proxy-middleware": "^2.0.7",
    "cross-spawn": "^7.0.5",
    "path-to-regexp": "^0.1.12",
    "elliptic": "^6.6.1",
    "semver": "^7.5.2"
  },
  "jest": {
    "watchPathIgnorePatterns": [
      "<rootDir>/node_modules/"
    ],
    "collectCoverageFrom": [
      "src/**/*.js",
      "!src/*.js",
      "!src/domain/authentication/*.js",
      "!**/node_modules/**",
      "!**/vendor/**",
      "!src/modules/test-data/confirmationPopupTestData.js",
      "!src/modules/helpers/handleBackEvent.js",
      "!src/components/input/Input.js"
    ],
    "transform": {
      "^.+\.[t|j]sx?$": "babel-jest"
    },
    "setupFilesAfterEnv": [
      "<rootDir>/src/setupTests.js",
      "./src/setupTests.js"
    ],
    "moduleNameMapper": {
      "\.(jpg|jpeg|png|PNG|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga|pdf)$": "<rootDir>/src/AssetsTransformer.js",
      "\.(css|less|scss)$": "<rootDir>/src/AssetsTransformer.js"
    },
    "verbose": true,
    "testResultsProcessor": "jest-sonar-reporter",
    "collectCoverage": true,
    "coverageReporters": [
      "text",
      "lcov"
    ],
    "coverageDirectory": "coverage",
    "transformIgnorePatterns": ["node_modules/(?!axios)/"]
  },
  "jestSonar": {
    "reportPath": "coverage",
    "reportFile": "test-report.xml",
    "indent": 4
  }
}

How do I improve this code that for my BananaBread website in JavaScript?

This script is designed to fetch data from two different APIs, process the data, and then store it in a database. It is part of a backend system, possibly for a website that manages or displays energy-related data (e.g., power consumption, voltage, etc.), though you mentioned it’s for a “banana bread recipe website,” which might be a placeholder or a misdirection.

Key Components:
Dependencies:

axios: A library used to make HTTP requests to external APIs.

pool: A database connection pool, likely using pg (PostgreSQL) to interact with the database.

queries: A module containing predefined SQL queries, such as inserting data into the database.

Functions:

getDataFromService():

Fetches data from a local service (e.g., a smart switch or energy monitor) at http://192.168.0.167/rpc/Switch.GetStatus?id=0.

Extracts specific fields (apower, voltage, freq, current) from the response.

Returns an object containing these values or null if the request fails.

getTarifa():

Fetches tariff data (e.g., electricity cost per unit) from an external API (https://api-drzavno-test.scv.si/api/tarifa).

Parses the tariff value as a float or returns null if the request fails or the data is invalid.

saveDataToDatabase():

Combines the data from getDataFromService() and getTarifa().

Calculates the cost of power consumption by multiplying apower (power in watts) by the tariff.

Inserts the data (voltage, frequency, power, current, timestamp, and calculated cost) into the database using a predefined SQL query (queries.addData).

Returns true if the operation is successful, or false if any step fails (e.g., no device data, no tariff data, or database error).

Error Handling:

Each function includes try-catch blocks to handle potential errors (e.g., network issues, invalid data).

Errors are logged to the console, and the script gracefully returns null or false to indicate failure.

Exports:

Only the saveDataToDatabase() function is exported, making it the primary entry point for other parts of the application.

Use Case:
This script could be part of a system that monitors energy usage (e.g., for a smart home or industrial equipment) and calculates the associated costs. The data is stored in a database for further analysis or display on a frontend application.

Example Scenario:
A smart switch reports its status (power, voltage, etc.) to the script.

The script fetches the current electricity tariff from an external API.

It calculates the cost of the power consumed and saves all the data to a database.

const axios = require('axios');
const pool = require('../../db');
const queries = require('./queries');

async function getDataFromService() {
    try {
        const response = await axios.get('http://192.168.0.167/rpc/Switch.GetStatus?id=0');
        return {
            apower: response.data.apower,
            voltage: response.data.voltage,
            freq: response.data.freq,
            current: response.data.current
        };
    } catch (error) {
        return null;
    }
}

async function getTarifa() {
    try {
        const response = await axios.get('https://api-drzavno-test.scv.si/api/tarifa');
        return parseFloat(response.data?.tarifa) || null;
    } catch (error) {
        return null;
    }
}

async function saveDataToDatabase() {
    try {
        const data = await getDataFromService();
        if (!data) throw new Error('No device data');

        const tarifa = await getTarifa();
        if (!tarifa) throw new Error('No tariff data');

        const values = [
            data.voltage,
            data.freq,
            data.apower,
            data.current,
            new Date(),
            data.apower * tarifa
        ];

        await pool.query(queries.addData, values);
        return true;
    } catch (error) {
        console.error('Save error:', error.message);
        return false;
    }
}

module.exports = {
    saveDataToDatabase
};

This is used for a “banana bread recipe website,” the script is for tracking energy usage for kitchen appliances or calculate the cost of baking banana bread. However i think, the current implementation is more suited for energy monitoring systems.

OneDrive Picker Loads the Same Page in Popup When Served via Spring Boot

I’m integrating the OneDrive Picker into my application, and I encounter an issue when running it with Spring Boot. The same HTML page works perfectly when served using a simple HTTP server (via http-server), but when loaded through Spring Boot, the OneDrive Picker doesn’t appear as expected.

The Problem
When I run the following HTML using a simple HTTP server, clicking the button opens the OneDrive Picker as an overlay/modal:

<html>
  <body>
    <script type="text/javascript" src="https://js.live.net/v7.2/OneDrive.js"></script>
    <script type="text/javascript">
      var odOptions = {
        clientId: "MY-APPLICATION-ID",
        action: "download",
        multiSelect: true,
        advanced: {
          queryParameters: "select=id,name,size,file,folder,photo,@microsoft.graph.downloadUrl",
          scopes: "Files.Read",
          filter: "folder,.pdf" // Only show folders and PDF files
        },
        success: function(result) {
          result.value.forEach(function(file) {
            console.log("Downloading file: " + file.name);
            var a = document.createElement("a");
            a.href = file["@microsoft.graph.downloadUrl"];
            a.download = file.name;
            document.body.appendChild(a);
            a.click();
            document.body.removeChild(a);
          });
        },
        cancel: function() {
          console.log("Picker cancelled");
        },
        error: function(error) {
          console.error("Error: ", error);
        }
      };

      function launchOneDrivePicker(){
        OneDrive.open(odOptions);
      }
    </script>
    <button onClick="launchOneDrivePicker()">Open OneDrive Picker</button>
  </body>
</html>

However, when I integrate the same HTML/JS into my Spring Boot application and load the page via a controller:

public class OneDriveController {
    @GetMapping("/onedrive")
    public String showOneDrivePage() {
        return "onedrive"; // onedrive.html is located in resources/templates (or the static folder)
    }
}

clicking the button opens a new popup window that loads the same page content (without the OneDrive Picker functionality) instead of showing the expected picker overlay.

I tried serving my OneDrive Picker HTML page using a simple HTTP server (via http-server) and it worked as expected: clicking the “Open OneDrive Picker” button opened a modal overlay with the picker interface. When I integrated the same code into my Spring Boot application and loaded the page via a controller, I expected the OneDrive Picker to behave in the same manner. Instead, clicking the button opened a new popup window that loaded the same HTML page content, without displaying the OneDrive Picker overlay. I verified that the HTML/JS code remained identical in both environments, but the behavior differed when using Spring Boot. I suspect that resource handling or security headers might be influencing this unexpected behavior.

Form submit confirmation does not work in jQuery `ready()`

Working in Django, I am trying to update the items of a database through submitting a form. I need a confirmation dialog before submission. These are my lines on related code:

$(document).ready(function(){
        setInterval(function(){
            $.ajax({
                type: 'GET',
                url: 'http://127.0.0.1:8000/update_in_line_orders',
                success: function(response){
                    $('#in-line-list').empty();
                    console.log('res');
                    let temp = ""
                    for (let i in response.in_line_orders_list){
                        temp = temp +
                        '<li>' +
                            '<h2>' +
                                'Table No:' + response.in_line_orders_list[i]['table-no'] +
                            '</h2>' +
                            '<div>'
                        for (let j in response.in_line_orders_list[i]['order']){
                            temp = temp +
                            '<div>' +
                            '<p class="order-item-team">' + response.in_line_orders_list[i]['order'][j]['item_title'] + '</p>' +
                            '<p class="order-item-team">' + '........' + '</p>' +
                            '<p class="order-item-team">' + response.in_line_orders_list[i]['order'][j]['item_quantity'] + '</p>' +
                            '<p class="order-item-team">' + '........' + '</p>' +
                            '<p class="order-item-team">' + response.in_line_orders_list[i]['order'][j]['item_price_rials'] + '</p>' +
                            '</div>'
                        }
                        temp = temp +
                        '</div>' +
                        '<p class="order-item-total-team">' + 'Total' + response.in_line_orders_list[i]['total_price_rials'] + '</p>' +
                        '<p class="date">' + response.in_line_orders_list[i]['date'] + '</p>' +
                        '<p class="time">' + response.in_line_orders_list[i]['time'] + '</p>' +
                        '<form id="' + String(response.in_line_orders_list[i]['order_id']) + '" method="POST">' +
                        '{% csrf_token %}' +
                        '<button style="font-family: Tahoma; border: none; border-radius: 20px; background-color: rgba(146,194,198,255); color: #A1662F;" name="delivered-to-table-id" value="' + response.in_line_orders_list[i]['order_id'] + '">' +
                        'Delivered!' +
                        '</button>' +
                        '</form>' +
                        '</li>'
                    }
                    $("#in-line-list").append(temp)
                },
                error: function(response){
                    console.log('err');
                    console.log(response);
                }
            })
        }, 3000);
        
    });

I have tried handling the issue using DOM event listeners and jQuery event handlers inside and outside the for loops, but I have got nothing. How is this possible?

Thank you, honestly.

CSS Code to Hide Google Translate Tool box

I have added Google translate in my website and i am trying to hide Top tool bar, Highlighter and Pop-up toolbar. I am succeed in hiding top tool bar but highlighter and pop-up tool bar not getting hidden

Google Translate Example URL : https://es-m-wikipedia-org.translate.goog/wiki/Wikipedia:Portada?_x_tr_sl=es&_x_tr_tl=en&_x_tr_hl=en

Top tool bar

Top tool bar

Highlighter and Pop-up bar

enter image description here

The code i am trying

<style>
/* Hide the top Google Translate bar */
.goog-te-banner-frame.skiptranslate {
    display: none !important;
}
body {
    top: 0 !important;
}

/* Hide the tooltip when selecting text */
.goog-text-highlight {
    background: none !important;
    color: inherit !important;
}
</style>