Node.js: make module use local `window` variable

I have such a function with imported module that I cannot edit

function create() {
  const window = {}; // Normally initialized by JSDOM to make fake window
  const appboy = require("@braze/web-sdk");
}

What I want is that appboy sees the local window from create function.

I want to avoid globalThis.window because of race conditions of create function when run concurrently.

Login into Web Server by sending Cookies credential from other Web Server code

I’m using an ASP.MVC .net web app.

This project will display another url inside/embeded the view (.cshtml). But when we display that other web inside our project, the second server embeded displays a prompt asking for the credentials.

enter image description here
We want to avoid that since the user has already login in our web. So, in order to prevent the user to write his credentials twice, we want to send the credentials via embeded url.

.cshtml view:

@{
    string cadena = "https://UserName:UserPassword@URL?rs:embed=true";
}
  
<div class="container">
    <object class="responsive-iframe" data=@cadena></object>
</div>

The problem is that this solution only works on Firefox because Edge/Chrome blocks embeded urls. So the only solution we find is to send the credentials to the server via cookies. But I don’t know how to do it.

This is the controller but it keeps displaying the prompt asking for the credentials:

public ActionResult InformePagares()
{
  //I found this on internet, but it looks incomplete. I don't know how to do it
  HttpClient httpClient = new HttpClient { BaseAddress = new Uri(URL) }; //This url is the same on the view (without "UserName:UserPassword" and without "?rs:embed=true")
  string encoded = System.Convert.ToBase64String(Encoding.GetEncoding("ISO-8859-1").GetBytes($"{Username}:{Password}"));
  httpClient.DefaultRequestHeaders.Add("Authorization", $"Basic {encoded}");

  return View();
}

How can I send cookies credentials from a .net web app (MVC) to another web server from controller (#C) or from the view using HTML, javascript, jquery…?

HTMX: on click, update a form input and then submit the form

I’m using htmx in a HTML form in a page basically looking like this:

<form id="my_form" method="post"  hx-post="{{ MY_TARGET_URL }}" hx-trigger="click from:.btn delay:100ms">

   <input type="hidden" name="state" value="" id="id_state">

   <!-- my form contains other inputs as well -->

</form>

<button type="button" class="btn" id="btn1" data-state="1">Submit 1</button>
<button type="button" class="btn" id="btn2" data-state="2">Submit 2</button>

The HTML page also includes the following JavaScript code:

document.querySelectorAll(".btn").forEach((element) => {
  element.addEventListener("click", () =>
    document.getElementById("id_state").value = element.dataset.state;
  );
});

Everything seems to work perfectly well like this: the user can submit the form either by clicking on Submit 1 or on Submit 2, the hidden input gets updated either with the value 1 or 2 and then 100 ms later the form is submitted, sending a POST request to the specified endpoint.

However, I can feel this solution is a bit hacky and inelegant. Do you see a cleaner way to achieve the same thing, without “delay”?

Disabling date selection on react full calendar

I need to disable date selection on my calendar i have used the selectAllow prop of the reactfull calendar to achieve this. this is my code

     const handleSelectAllow = (selectInfo) => {
        const currentDate = new Date();
        const selectedDate = selectInfo.start;
        const threeMonthsAgo = new Date();
        threeMonthsAgo.setMonth(currentDate.getMonth() - 3);
        const threeMonthsFromNow = new Date();
        threeMonthsFromNow.setMonth(currentDate.getMonth() + 3);
    
        if (
          selectedDate >= threeMonthsAgo &&
          selectedDate <= threeMonthsFromNow
        ) {
          return true;
        } else {
          alert('Date selection is not allowed. Please select a date within the range of three months ago and three months from now.');
          return false;
        }
      
        // return (
        //   selectedDate >= threeMonthsAgo && selectedDate <= threeMonthsFromNow
        // );
      };

   

   

  <FullCalendar
          plugins={[dayGridPlugin, timeGridPlugin, interactionPlugin]}
          // headerToolbar={{
          //   left: 'prev,next today',
          //   center: 'title',
          //   right: 'dayGridMonth,timeGridWeek,timeGridDay',
          // }}
          selectAllow={handleSelectAllow}
          selectLongPressDelay={null}
          initialView="dayGridMonth"
          editable={false}
          selectable={true}
          showNonCurrentDates={false}
          // eventClick={handleSelectAllow}
          // eventMouseEnter={handleEventMouseEnter}
          selectMirror={true}
          events={allEvents}
          select={handleDateClick}
          eventContent={renderEventContent}
          eventDidMount={eventDidMount}
          eventWillUnmount={eventWillUnmount}
          // eventRender={eventRender}
        />

the function is working properly but the issue is after the 1st click if i hover through the calendar the alert is continously showing. i need to only show the alert on clicking. Any fixes?, I have used react fullcalendar.

How to use the bootstrap 5 theme for select2

I followed the instructions here but it makes no difference to the look of the select box.

https://apalfrey.github.io/select2-bootstrap-5-theme/

Here is everything I imported as I know the order is important:

<!-- Styles -->
        
        <!-- Bootstrap -->
        <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-rbsA2VBKQhggwzxH7pPCaAqO46MgnOM80zW1RWuH61DGLwZJEdK2Kadq2F9CUG65" crossorigin="anonymous">
        <!-- Select2 -->
        <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/select2.min.css" rel="stylesheet" />
        <!-- Select2 Bootstrap theme -->
        <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/select2-bootstrap-5-theme.min.css" />
        
        <!-- Scripts -->
        
        <!-- jquery -->
        <script src="https://code.jquery.com/jquery-3.5.1.js"></script>
        <!-- Bootstrap -->
        <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-kenU1KFdBIe4zVF0s0G1M5b4hcpxyD9F7jL+jjXkk+Q2h455rYXK/7HAuoJl+0I4" crossorigin="anonymous"></script>
        <!-- Select2 -->
        <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/select2.min.js"></script>

Here is my javascript file:

$(document).ready(function () {
    $('#students').DataTable();
});

$(document).ready(function () {
    $('#grades').DataTable();
});


$(document).ready(function() {
     $('.js-example-basic-single').select2();
});

$(".js-example-theme-single").select2({
    theme: "bootstrap-5"
  });

And here is the select box, that I’m trying to change the look of:

<div class="mb-3">
            <select class="js-example-basic-single" name="student_id">
                <option disabled="" selected="">student</option>
                {% for student in students %}
                    <option value="{{ student.id }}">{{ student.name }} | Class: {{ student.class }}</option>
                {% endfor %}
            </select>
        </div>

Print order details using bulk action in woocommerce

I’m trying to build a print functionality in my Woocommerce website, I’ve created a button that opens a print window when clicked & it’s working fine.Woocommerce order page screenshot with ‘get order details button’ The problem I’m facing when I’m trying to print order’s in bulk by selecting multiple order’s at once, print window opens all orders in a single page Screenshot of print window with multiple orders on same page & I want to fix that, I need single order on single page so I can print orders properly.

add_filter( 'bulk_actions-edit-shop_order', 'add_bulk_action_print_orders' );
function add_bulk_action_print_orders( $actions ) {
   $actions['print_selected'] = __( 'Print selected orders', 'textdomain' );
   return $actions;
}
// Handle the custom bulk action
add_filter( 'handle_bulk_actions-edit-shop_order', 'handle_bulk_action_print_orders', 10, 3 );
function handle_bulk_action_print_orders( $redirect_to, $action, $order_ids ) {
   if ( $action !== 'print_selected' ) {
       return $redirect_to;
   }
$order_ids = isset( $_REQUEST['post'] ) ? $_REQUEST['post'] : array();
   if ( empty( $order_ids ) ) {
       return;
   }
foreach ( $order_ids as $order_id ) {
       $order = wc_get_order( $order_id );
$order_note = $order->get_customer_note();
$order_no = $order->get_order_number();
$order_total = $order->get_total();
$total_tax = $order->get_total_tax();
$subtotal = $order->get_subtotal();
$items=$order->get_items();

$billing_email=$order->get_billing_email();
$billing_phone=$order->get_billing_phone();

//$shipping_email = $order->get_shipping_email();
//$shipping_phone=$order->get_shipping_phone();

  $shipping_address_1 =$order->get_shipping_address_1();
$shipping_address_2 =$order->get_shipping_address_2();
$shipping_city = $order->get_shipping_city();
$shipping_state = $order->get_shipping_state();
$shipping_country = $order->get_shipping_country();
$shipping_postcode = $order->get_shipping_postcode();

  $billing_address_1 =$order->get_billing_address_1();
$billing_address_2 =$order->get_billing_address_2();
$billing_city = $order->get_billing_city();
$billing_state = $order->get_billing_state();
$billing_country = $order->get_billing_country();
$billing_postcode = $order->get_billing_postcode();
echo'<style>.my-button.clicked{background-color:yellow;}</style>';
echo'<style>body{ background-color:#fff;margin: 0;padding: 0;}</style>';
echo'<style> h1,h2,h3,h4,h5,h6{ margin: 0; padding: 0;} p{ margin: 0; padding: 0; } </style>';
echo'<style> .container{ width: 100%; margin-right: auto; margin-left: auto; } .brand-section{ background-color: #b2ac88; padding: 10px 40px;} </style>'; echo'<style>.logo{ width: 50%;} .row{ display: flex; flex-wrap: wrap; } .col-6{ width: 50%; flex: 0 0 auto; } .text-white{ color: #fff; } </style>';
echo'<style> .company-details{ float: right; text-align: right;} .body-section{ padding: 16px; border: 1px solid gray;} </style>';
echo'<style>.heading{ font-size: 20px; margin-bottom: 08px; } .sub-heading{ color: #262626; margin-bottom: 05px; } </style>';
echo'<style> table{ background-color: #fff; width: 100%; border-collapse: collapse; } </style>';
echo'<style> table thead tr{ border: 1px solid #111; background-color: #fff; } table td { vertical-align: middle !important; text-align: center; }</style>';
echo'<style> table th, table td { padding-top: 08px; padding-bottom: 08px; } .table-bordered{box-shadow: 0px 0px 5px 0.5px gray;} </style>';
echo'<style> table-bordered td, .table-bordered th { order: 1px solid #dee2e6; } .text-right{ ext-align: end;} .w-20{ width: 20%;} </style>';
echo'<style>.float-right{float: right; }</style>';
echo'<h3>Inovice</h3>';
echo'<div class="container">';
echo '<div class="brand-section">';
echo '<div class="row">';
echo '<div class="col-6">';
                   echo '<h1 class="text-white">Order No.</h1>'.$order_no.'</div>';
echo '<div class="col-6">';
                   echo '<div class="company-details">';
echo '<h2 class="text-white">Oven Fresh</h2>';
                      echo '<p class="text-white">Unit No. 210 2nd floor,Mahim Industrial Estate,Off Cadel Road Mahim,Mumbai-400016 <br>GST No: 27AAUCA4280D1ZI <br> FSSAI NO:11521004000462 <br>State Name: Maharashtra, Code: 27</p>';
                      echo '<p class="text-white">+91-8080-146666</p>';
                   echo '</div>';
               echo '</div>';
           echo '</div>';
       echo '</div>';
echo '<div class="body-section">';
          echo '<div class="row">';
               echo '<div class="col-6">';
                  echo '<h2 class="heading">Billing Address</h2>';  echo'<br>'.$billing_address_1.$billing_address_2.$billing_city.$billing_state.$billing_country.$billing_postcode ;
                  echo '<p class="sub-heading">Email </p>'.$billing_email;
                  echo '<p class="sub-heading">Phone </p>'.$billing_phone;
                  
             echo '</div>';
echo '<div class="col-6">';
                  echo '<h2 class="heading">Shipping Address</h2>'.$shipping_address_1.$shipping_address_2.$shipping_city.$shipping_state.$shipping_country.$shipping_postcode;
//  echo '<p class="sub-heading">Delivery Date </p>'.$delivery_date;
                //  echo '<p class="sub-heading">Time Slot</p>'.$time_slot;
  foreach ( $order->get_meta_data() as $meta ) {
if ( $meta->key === 'Delivery Date' || $meta->key === 'Time Slot' ) {
           echo '<p><strong>' . $meta->key . ':</strong> ' . $meta->value . '</p>';
       }
}
 echo '<p><strong>Customer Note :</strong>'.$order_note.'</p>';
             echo '</div>';
           echo '</div>';
       echo '</div>';
echo '<div class="body-section">';
          echo '<h3 class="heading">Ordered Items</h3>';
           echo '<br>';
           echo '<table class="table-bordered">';
               echo '<thead>';
                   echo '<tr>';
                       echo '<th>Product Name</th>';
                       echo '<th>Quantity</th>';
                       echo '<th>HSN Code</th>';
                       echo '<th>Price</th>';
echo '<th class="w-20">Grandtotal</th>';
                   echo '</tr>';
               echo '</thead>';
               echo '<tbody>';
        foreach ( $items as $item ) {
$product=$item->get_product();
$product_name = $item->get_name();
$quantity= $item->get_quantity();
$price = $item->get_product()->get_regular_price();
    $hsn_code=$product->get_meta('_hsn_code');
 $grandtotal = wc_price($price * $quantity);
echo '<tr>';
echo '<td>'.$product_name.'</td>';
echo '<td>'.$quantity.'</td>';
echo '<td>'.$hsn_code.'</td>';
echo '<td>'.$price.'</td>';
echo '<td>'.$grandtotal.'</td>';
echo '</tr>';
 }

echo'<tr>';
                      echo '<td colspan="4" class="text-right">Sub Total</td>';
                      echo '<td>'.$subtotal.'</td>';
                  echo '</tr>';
                   echo '<tr>';
                       echo '<td colspan="4" class="text-right">Tax</td>';
                       echo '<td>'.$total_tax.'</td>';
                   echo '</tr>';
                   echo '<tr>';
                       echo'<td colspan="4" class="text-right">Total</td>';
                       echo'<td>'.$order_total.'</td>';
                   echo'</tr>';
echo'</tbody>';
           echo '</table>';
echo '<div>';
           echo '<p>Footer </p>';
       echo '</div>';      
echo '</div>';
}
}

I’m using the code mentioned above, is there something missing or am I doing something wrong here. I need you guys help to solve this as soon as possible. Thank you!

How to send data in ‘GET’ request of XMLHttpRequest in javascript?

and thanks for investing your time in this post.

I want to send a data in GET request in XMLHttpRequest.

function useAjax(url,data){
        const xhttp = new XMLHttpRequest();
        xhttp.onload = function(e) {
            const resData = JSON.parse(xhttp.responseText) ;
            setResponseData(true,resData)
        }
        xhttp.open("GET", url, false);
        xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        xhttp.send(data);
   }

I tried to make change on open function params like xhttp.open(“GET”, url, [false,data]);

but still getting no result

signin_oauth_error azure-ad outgoing request timed out after 3500ms

Describe the issue

I am using SSO Azure AD authentication in my application. Locally (localhost:3000) it works fine. But when I deployed on K8s cluster (internal network of a private company) I get such an error displayed on the Pod logs:

[next-auth][warn][DEBUG_ENABLED]
https://next-auth.js.org/warnings#debug_enabled
[next-auth][error][SIGNIN_OAUTH_ERROR]
https://next-auth.js.org/errors#signin_oauth_error outgoing request timed out after 3500ms {
error: {
message: 'outgoing request timed out after 3500ms',
stack: 'RPError: outgoing request timed out after 3500msn' +
' at /app/node_modules/openid-client/lib/helpers/request.js:137:13n' +
' at async Issuer.discover (/app/node_modules/openid-client/lib/issuer.js:144:24)n' +
' at async openidClient (/app/node_modules/next-auth/core/lib/oauth/client.js:16:14)n' +
' at async getAuthorizationUrl (/app/node_modules/next-auth/core/lib/oauth/authorization-url.js:70:18)n' +
' at async Object.signin (/app/node_modules/next-auth/core/routes/signin.js:38:24)n' +
' at async AuthHandler (/app/node_modules/next-auth/core/index.js:260:26)n' +
' at async NextAuthApiHandler (/app/node_modules/next-auth/next/index.js:22:19)n' +
' at async NextAuth._args$ (/app/node_modules/next-auth/next/index.js:106:14)n' +
' at async Object.apiResolver (/app/node_modules/next/dist/server/api-utils/node.js:372:9)n' +
' at async NextNodeServer.runApi (/app/node_modules/next/dist/server/next-server.js:514:9)',
name: 'RPError'
},
providerId: 'azure-ad',
message: 'outgoing request timed out after 3500ms'
}

The front-end UI display Try signing in with a different account.
screenshot

How to reproduce

In […nextauth].ts:

import NextAuth, { NextAuthOptions } from "next-auth";
import AzureADProvider from "next-auth/providers/azure-ad";
import { HttpsProxyAgent } from "https-proxy-agent";

const authOptions: NextAuthOptions = {
  providers: [
    AzureADProvider({
      id: "azure-ad",
      name: "Azure AD",
      tenantId: process.env.NEXT_PUBLIC_TENANT_NAME as string,
      clientId: process.env.NEXT_PUBLIC_CLIENT_ID as string,
      clientSecret: process.env.NEXTAUTH_SECRET as string,
    }),
  ],
  callbacks: {
    async jwt({ token, account }) {
      var myHeaders = new Headers();
      if (account) {
        myHeaders.append("Authorization", account.access_token);
        let fetchOptions = {
          method: "GET",
          headers: myHeaders,
          redirect: "follow",
          agent: new HttpsProxyAgent("http://proxy.company.com:8080"),
        } as RequestInit;
        token.iNumber = await fetch(
          "https://graph.microsoft.com/v1.0/me?$select=displayName,mail",
          fetchOptions
        )
          .then((response) => response.json())
          .then((response) => response["onPremisesSamAccountName"])
          .catch((error) => console.log("error", error));
      }
      return token;
    },
    async session({ session, token, user }) {
      return {
        ...session,
        user: {
          ...session.user,
          iNumber: token.iNumber,
        },
      };
    },
  },
  debug: true,
};

export default NextAuth(authOptions);

You can see that I added a HttpsProxyAgent agent to the options of the fetch function as indicated here https://next-auth.js.org/tutorials/corporate-proxy

Expected behavior

I expected to be redirected to the root page after authentification.
But here is the URL: https://app-hostname.com/api/auth/signin?error=OAuthSignin

Environment

{
  "name": "my_app",
  "version": "0.1.0",
  "private": true,
  "scripts": {
    "dev": "next dev",
    "build": "next build",
    "start": "next start",
  },
  "dependencies": {
    "@emotion/react": "^11.10.6",
    "@testing-library/react": "^14.0.0",
    "@types/node": "18.15.11",
    "@types/react": "18.0.37",
    "@types/react-dom": "18.0.11",
    "next": "13.2.4",
    "next-auth": "^4.22.1",
    "react": "18.2.0",
    "react-dom": "18.2.0",
    "sharp": "^0.32.0",
    "typescript": "5.0.4"
  }
}

Google is accidently indexing query string URLs parameters of causing my website bandwidth increase [migrated]

Google is currently indexing query strings URLs of my website. Google has currently indexed almost 112k URLs that all are duplicate version of other URLs causing my website to slow down and negaitvilty effecting my SEO.

The structure of query strings url is as follows: https://example.com?te=6.18.1346158.4.18.76.huffy+blue+and+white+bike

I have contacted search community earlier and they have suggested me to add no index meta tags in my .htacces file with the following code

<If “%{QUERY_STRING} =~ /te=/”> Header set X-Robots-Tag noindex

Also, I have tried it using robot.txt file to block those urls but no relief.

It’s been two weeks since I added this code on my .htacces file in my cpanel but still google is indexing those qyery strings parameter URLs.

I am unable to figure out what’s the issue please suggest me a possible solution for this as it hitting my website tremendously day by day 🙁

Resize “area” Tags Dynamically in HTML

Recently I have been working on a kind of interactive image where I needed to map the image and create areas.

I noticed that they do not change dynamically. I created a simple code that change the coords dynamically. I want to hear your thoughts about it since I searched a lot by did not find any related codes.

const getArea = document.querySelectorAll("area");
const getimg = document.querySelector(".myImg");
getArea.forEach(function (area) {
  const scaleWidth = getimg.width / getimg.naturalWidth;
  const scaleHeight = getimg.height / getimg.naturalHeight;
  coords = area.coords.split(",");
  const x = coords[0];
  const y = coords[1];
  const width = coords[2];
  const height = coords[3];
  area.coords = `${x*scaleHeight},${y*scaleWidth},${width* scaleWidth},${height* scaleHeight}`;
});

Jest encountered an unexpected token for SyntaxError: Unexpected token ‘export’

Can someone please help me to fix this error I get when I am running

npm run test

Error –

     FAIL  src/client/AdaptiveCardsDesigner/AdaptiveCardsDesigner.test.js
  ● Test suite failed to run

    Jest encountered an unexpected token

    This usually means that you are trying to import a file which Jest cannot parse, e.g. it's not plain JavaScript.

    By default, if Jest sees a Babel config, it will use that to transform your files, ignoring "node_modules".

    Here's what you can do:
     • If you are trying to use ECMAScript Modules, see https://jestjs.io/docs/en/ecmascript-modules for how to enable it.
     • 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/en/configuration.html

    Details:

    /Users/node_modules/swiper/swiper.esm.js:13
    export { default as Swiper, default } from './core/core.js';
    ^^^^^^

    SyntaxError: Unexpected token 'export'

      at Runtime.createScriptFromCode (node_modules/jest-runtime/build/index.js:1350:14)
      at Object.<anonymous> (node_modules/adaptivecards/src/carousel.ts:26:1)

 FAIL  src/client/AdaptiveCardsDesigner/container.test.js
  ● Test suite failed to run

    Jest encountered an unexpected token

    This usually means that you are trying to import a file which Jest cannot parse, e.g. it's not plain JavaScript.

    By default, if Jest sees a Babel config, it will use that to transform your files, ignoring "node_modules".

    Here's what you can do:
     • If you are trying to use ECMAScript Modules, see https://jestjs.io/docs/en/ecmascript-modules for how to enable it.
     • 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/en/configuration.html

    Details:

    /Users/node_modules/swiper/swiper.esm.js:13
    export { default as Swiper, default } from './core/core.js';
    ^^^^^^

    SyntaxError: Unexpected token 'export'

      at Runtime.createScriptFromCode (node_modules/jest-runtime/build/index.js:1350:14)
      at Object.<anonymous> (node_modules/adaptivecards/src/carousel.ts:26:1)

Test Suites: 2 failed, 1 passed, 3 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        1.441 s
Ran all test suites matching /src/client/AdaptiveCardsDesigner/i.

My package.json file with –

“moduleNameMapper”: {
“.(jpg|jpeg|png|svg|gif|mp4)$”: “/mocks/fileMock.js”,
“^.+.(css|scss)$”: “/node_modules/identity-obj-proxy”,
“monaco-editor”: “/node_modules/react-monaco-editor”
},

I also tried to add transformIgnorePatterns as suggested in error,
but error is not going,

    "transformIgnorePatterns": [
"node_modules/adaptivecards"
]

My jest config –

  "jest": {
    "testURL": "",
    "setupFiles": [
      "./.jest/requestAnimationFrameShim.js",
      "./.jest/jestsetup.js",
      "jest-localstorage-mock"
    ],
    "roots": [
      "<rootDir>/src/server/libs",
      "<rootDir>/src/client",
      "<rootDir>/__mocks__"
    ],
    "verbose": true,
    "collectCoverageFrom": [
      "**/src/client/**/*.{js,jsx}",
      "!**/node_modules/**"
    ],
    "coverageDirectory": "coverage/client",
    "coverageThreshold": {
      "global": {
        "statements": 99.36,
        "branches": 99.87,
        "functions": 99.22,
        "lines": 99.33
      }
    },
    "globals": {
      "__DEVELOPMENT__": false,
      "__DEVTOOLS__": false,
      "__CLIENT__": true,
      "__SERVER__": false,
      "__INITIAL_STATE__": {}
    },
    "moduleNameMapper": {
      "\.(jpg|jpeg|png|svg|gif|mp4)$": "<rootDir>/__mocks__/fileMock.js",
      "^.+\.(css|scss)$": "<rootDir>/node_modules/identity-obj-proxy",
      "monaco-editor": "<rootDir>/node_modules/react-monaco-editor"
    },
    "snapshotSerializers": [
      "enzyme-to-json/serializer",
      "jest-serializer-html"
    ]
  },

Can someone help ?

How should I transition from ZedGraph to d3js?

I have an asp classic with vbscript application. When I click an image I change the window.location to a page with an onload function. The only purpose of this function is to make a post request to an aspx page passing some parameters that will be used to retrieve some info from the database and create a graph using ZedGraphs. Then, it will become an image and returned to the client with Response.write().

Now i need to modernize the graphs using d3js.

My approach was to create an nodejs app that will recieve the post request (replacing the aspx page). However, since I don’t know d3js, I don’t know if I can make the same approach of creating a graph using it on server-side and serving it to an asp classic cliente-side…

Please, help me create a strategy before crafting unnecessary code!

How can I use the locale service provided by Angular to set the tooltip label in Chart.js when using the tooltip call function?

    const config: any = {
      type: 'bar',
      data: {
        localNumberPipe : this.localNumberPipe,
        labels: this.labels,
        datasets: [{
          minBarLength: 5,
          maxBarThickness: 50,
          label: 'Waterfall Chart',
          elements: {
            bar: {
              backgroundColor: this.color,
              borderColor: this.color,
            }
          },
          data: this.data,
          borderWidth: 1,
          borderSkipped: false
        }]
      },
      options: {
        maintainAspectRatio: false,
        plugins: {
          tooltip: {
            callbacks: {
              context: {
                _this: this,
              },
              label: function (context) {
                var bar = JSON.parse(context.formattedValue);
                var label = [];
                if (bar) {
                  var l=  this.locale;
                  const diff = Number.parseFloat(bar[1]) - Number.parseFloat(bar[0]);
                  label.push('Difference: ' + formatNumber(diff, 'en-US', '1.0-0'));
                  label.push('Start: ' + formatNumber(bar[0], 'en-US', '1.0-0'));
                  label.push('End: ' + formatNumber(bar[1], 'en-US', '1.0-0'));
                }
                return label;
              }
            }
          }
        },
        scales: {
          y: {
            beginAtZero: true
          }
        }
      },
      plugins: [connectorLines]
    };

In the constructor I have this code where I am getting localy as ‘an-US’

  constructor(private localeService: LocaleService) {
    this.localNumberPipe = new LocalNumberPipe(localeService);
    Chart.register(...registerables);
     **this.locale** = this.localeService.locale ;
    console.log(this.locale);
  }

but if I try to access this.locale in tooltip callback function it returns undefine. Is it something related to this scope? if so is any way to add locale in chart config as a property so I can access it in tooltip callback function.

In the developer console this return the tooltip details.

 label: function (context) {
                var bar = JSON.parse(context.formattedValue);
                debugger /// execute this at this stage  

enter image description here

Thank you for your support!

Preact and React in a single project

I work on a huge React code base having multiple packages. I want to try to migrate the components of a single package to Preact and rest continue with react components. How to achieve this kind of programming pattern?

How to ensure smooth communication in the case of

 <ReactComponent>
     <PreactComponent>
          <ReactComponent/>
      </PreactComponent>
   </ReactComponent>

Project Structure is of like: Lets consider we have to convert package2 react components to preact and then use React components with packages of 1 and 3.

ProjectName
| - packages
|   | - package1 (React)
|   |   |- package.json
|   | - package2  (Preact)
|   |   |- package.json
|   | - package3  (React)
|   |   |- package.json
| - package.json