Trying to use TempusDominus date time picker version 6 but the class is undefined

I am trying to use date time picker which is named “Tempus Dominus” (in version 6, as I understand it was named “getdatepicker” earlier). I can reference the scripts according to example here https://getdatepicker.com/6/installing.html#cdn, and trying to do a simple initialization as here https://getdatepicker.com/6/repl.html .

Here is the fiddle, basically copy-paste from those examples: https://jsfiddle.net/kurtevich/4g867eu9/6/

The problem is that “TempusDominus is not defined”. I think this is because I am not using the “import” line, but I can’t use it because it’s “only allowed in a module”, besides I am not sure what to put for that path part. I haven’t use import before, from the information I found I understood that it’s used for structured projects, but I have just an HTML page, is it even possible to use that component in this case? In the earlier versions it was just $(element).datetimepicker();, but this doesn’t work any more.

I was investigating source of the example page, but couldn’t find how that is setup. I have also tried to access that class through some other object which I saw somewhere, like “tempusDominus”, “exports”, “global”, “globalThis” with no luck. I also looked into the component script itself, the classes there look more or less clear, but they are wrapped in a function which must be what’s hiding them, and I don’t understand what is going on in here:

(function (global, factory) {
  typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
  typeof define === 'function' && define.amd ? define(['exports'], factory) :
  (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.tempusDominus = {}));
})(this, (function (exports) { 'use strict';

// All classes are in here

exports.DateTime = DateTime;
  exports.DefaultEnLocalization = DefaultEnLocalization;
  exports.DefaultOptions = DefaultOptions;
  exports.Namespace = Namespace;
  exports.TempusDominus = TempusDominus;
  exports.extend = extend;
  exports.loadLocale = loadLocale;
  exports.locale = locale;
  exports.version = version;

  Object.defineProperty(exports, '__esModule', { value: true });

}));

How to change the color of each marker APEXCHARTS chart in next js

Do you know if there is a way to define the color of each point? Ex: { x: ‘Yellow’, y: [2100, 3000], colors: ‘#808080’,} because it is set by default for all markers: plotOptions > dumbbellColors, I would like a color for each marker. documentation is confusing

Example:
[enter image description here]
(https://i.stack.imgur.com/26IUq.png)
……………………………………………………………………………………………………………………………………………………………………………

'use client';
import Image from 'next/image';
import ReactApexChart from 'react-apexcharts';
import React, { Component } from 'react';
import { Show } from '@chakra-ui/react';
import { Colors } from 'chart.js';

interface GraficoDumbbleState {
  series: {
    data: { x: string; y: [number, number] }[];
    dataLabels?: {
      enabled: boolean;
    };
  }[];
  options: {
    chart: {
      height: number;
      type: string;
      zoom: {
        enabled: boolean;
      };
    };
    colors: string[];
    plotOptions: {
      bar: {
        horizontal: boolean;
        isDumbbell: boolean;
        dumbbellColors: string[][];
      };
    };
    legend: {
      show: boolean;
      showForSingleSeries: boolean;
      position: string;
      horizontalAlign: string;
      customLegendItems: string[];
    };
    fill: {
      type: string;
      gradient: {
        gradientToColors: string[];
        inverseColors: boolean;
        stops: number[];
      };
    };
    grid: {
      xaxis: {
        lines: {
          show: boolean;
        };
      };
      yaxis: {
        lines: {
          show: boolean;
        };
        yaxis: {
          lines: {
            show: boolean;
          };
        };
      };
    };
  };
}

export default class GraficoDumbble extends Component<{}, GraficoDumbbleState> {
  constructor(props: any) {
    super(props);

    this.state = {
      series: [
        {
          data: [
            { x: 'Amarela', y: [2100, 3000], colors: "#808089"},
            { x: 'Amarela', y: [3000, 5000]},
            { x: 'Amarela', y: [5000, 6500]},
            { x: 'Amarela', y: [6500, 8000]},

            {x: 'Branca', y: [2100, 5000],},
            {x: 'Branca', y: [5000, 8000],},
            {
              x: 'Indígina',
              y: [2100, 8000],
            },
            {
              x: 'Parda',
              y: [2100, 8000],
            },
            {
              x: 'Preta',
              y: [2100, 8000],
            },
          ],
          dataLabels: {
            enabled: false,
          },
        },
      ],
      options: {
        chart: {
          height: 390,
          type: 'rangeBar',
          zoom: {
            enabled: false,
          },
        },
        
        colors: ['#808080', '#808080'],
        plotOptions: {
          bar: {
            horizontal: true,
            isDumbbell: true,
          },
        },
        legend: {
          show: false,
          showForSingleSeries: false,
          position: 'top',
          horizontalAlign: 'left',
          customLegendItems: ['Female', 'Male'],
        },
        fill: {
          type: 'gradient',
          gradient: {
            gradientToColors: ['#808080'],
            inverseColors: false,
            stops: [0, 100],
          },
        },
        grid: {
          xaxis: {
            lines: {
              show: false,
            },
            labels: {
              show: false,
            },
          },
          yaxis: {
            lines: {
              show: false,
            },
            yaxis: { lines: { show: false } },
          },
        },
        xaxis: {
          labels: {
            show: false,
          },
        },
      },
    };
  }

  render() {
    return (
      <div>
        <div id="chart">
          <ReactApexChart
            options={this.state.options as any}
            series={this.state.series}
            type="rangeBar"
            height={390}
          />
        </div>
        <div id="html-dist"></div>
      </div>
    );
  }
}

Homemade Javascript Chrome Extension not working on pdfs open in chrome browser

First time poster and amateur programmer who’s run into a problem they can’t solve, so be gentle…

I have a Javascript Chrome Extension running in Manifest v3 and I’ve been trying to make a screenshot extension where you first draw an overlay over the desired area on the chrome browser, this is then drawn onto a canvas which is then saved out.

I’ve slowly worked out the nuances of foreground, background scripts etc, and it works on websites. But it doesn’t work on pdfs which are opened in the browser. No errors are thrown, it just doesn’t produce an overlay. I really want this to work on pdfs as well for a different application I have in mind for auto uploading parts of a pdf to a google sheet from the chrome extension.

I’ve tried googling to no avail, but I’m hoping it’s something to do with permissions. I’ve tried messing with the manifest.json to give host permissions, but no joy. Is it even possible to run an extension like this on a pdf open in a chrome browser?

Any help or advice would be greatly appreciated on how to do this! Ive copied the manifest.json and foreground.js script below:

foreground.js



var selectionOverlay = document.createElement('div');
selectionOverlay.style.position = 'absolute'; // Set overlay position to absolute
selectionOverlay.style.border = '2px solid red'; // Set border style
selectionOverlay.style.background = 'rgba(255, 0, 0, 0.3)'; // Set background color with alpha
selectionOverlay.style.pointerEvents = 'none'; // Make overlay ignore mouse events


// Initialize variables for tracking the selection
var selectionStarted = false;
var startX, startY, endX, endY;
var screenshotDataUrl = 0;

// Event handler for the start of the selection
function handleSelectionStart(event) {

  if (selectionStarted) {
  
    // Append the overlay to the body of the document
    document.body.appendChild(selectionOverlay);
    // Set the starting coordinates of the selection
    startX = event.clientX;
    startY = event.clientY;

    // Set initial position of the overlay
    updateOverlayPosition(startX, startY);
  }
}

// Event handler for the movement of the selection
function handleSelectionMove(event) {
  if (selectionStarted) {
    // Update overlay position as the mouse moves
    updateOverlayPosition(event.clientX, event.clientY);
  }
}

// Event handler for the end of the selection
function handleSelectionEnd(event) {
  console.log("Test2");
  if (selectionStarted) {
    // Reset the selection flag
    endX = event.clientX;
    endY = event.clientY;
    selectionStarted = false;
    console.log("Test2.5");
    // Get the selection range and its bounding rectangle
    var selection = window.getSelection();
    var range = selection.getRangeAt(0).getBoundingClientRect();
    captureSelectedArea(range);
    // Capture the selected area and send the data to the popup script
    // Remove the overlay after the selection is complete
    removeOverlay();
  }
}

// Update the overlay position based on mouse coordinates
function updateOverlayPosition(x, y) {
  selectionOverlay.style.left = Math.min(startX, x) + 'px';
  selectionOverlay.style.top = Math.min(startY, y) + 'px';
  selectionOverlay.style.width = Math.abs(startX - x) + 'px';
  selectionOverlay.style.height = Math.abs(startY - y) + 'px';
}

// Remove the overlay from the DOM
function removeOverlay() {
  selectionOverlay.parentNode.removeChild(selectionOverlay);
}

// Capture the selected area and send a message to the background script
function captureSelectedArea(range) {
  console.log("Test3");
  console.log(range);
  var img = new Image();
  img.src = screenshotDataUrl;
  img.onload = function () {
    var canvas = document.createElement('canvas');
    canvas.width = Math.abs(endX-startX);
    canvas.height = Math.abs(endY-startY);
  
    var context = canvas.getContext('2d');
    context.drawImage(img, startX-20, startY-20, canvas.width +20, canvas.height+20, 20, 20, canvas.width+5, canvas.height+20);
    
    var resultDataUrl = canvas.toDataURL('image/png');
    chrome.runtime.sendMessage({ action: 'downloadImage', dataUrl: resultDataUrl });
  }
  };

// Add event listeners for mouse events
document.addEventListener('mousedown', handleSelectionStart);
document.addEventListener('mousemove', handleSelectionMove);
document.addEventListener('mouseup', handleSelectionEnd);

// Listen for messages from the background script
chrome.runtime.onMessage.addListener(function (message, sender, sendResponse) {
  if (message.action === 'startSelection') {
    selectionStarted = true;
    screenshotDataUrl = message.dataUrl;
    
    console.log("Reached here!");
  }
});

Manifest.json


{ // Comments are allowed even though it's
    // Manifest version 3 is specified for the Chrome extension.
    "manifest_version": 3,

    // Extension name.
    "name": "Chrome Extension v3 Starter",

    // Description of the extension.
    "description": "A minimal example of a chrome extension using manifest v3",

    // Version of the extension.
    "version": "0.0.1",

    // Icons for different sizes.
    "icons": {
        "16": "logo/logo-16.png",
        "48": "logo/logo-48.png",
        "128": "logo/logo-128.png"
    },

    // Options page for settings.
    "options_page": "settings/settings.html",

    // Action details for the extension.
    "action": {
        "default_title": "Chrome Addon v3 Starter",
        "default_popup": "popup/popup.html"
    },

    // Permissions required by the extension.
    "permissions": ["activeTab","downloads","storage","tabs"],

    // Host permissions for the extension, allowing access to all URLs.
    "host_permissions": [
        "*://*/*",
        "file://*/*.pdf"
    ],

    // Background service worker for handling background tasks.
    "background": {
        "service_worker": "service-worker.js"
    },

    // Content scripts to be injected into specific matches (e.g., GitHub pages).
    "content_scripts": [{
        "js": ["foreground.js"],
        "matches": ["<all_urls>", "file://*/*.pdf","*://*/*.pdf"],
        "run_at": "document_end"
    }]
}


How to use gRPC reflection in a browser client without Node.js?

I would like my React.js web application to be able to connect to my gRPC server implementing the gRPC Server Reflection Protocol.

Using gRPC reflection would allow the web app to discover and use methods dynamically instead of having to import proto files.

I took a look at some libraries like grpc-js-reflection-api-client and gprc-reflection-js, but these assume a Node.js runtime through their dependency on @grpc/grpc-js, and it doesn’t seem feasible to run them from a browser application.

Is there another way to use gRPC reflection, using libraries like grpc-web perhaps?

How to remove out of dates with large range in range selector buttons in Plotly.JS?

I have a line plot with date in x-axis. My data is dynamic, so the range of dates always change. Sometimes it’s 1 year, some time 10 years, etc.

enter image description here

I add this code block for arrange x axis:

xaxis: {
  rangeselector: {buttons:[{step:"all",label:"MAX"},{count:10,label:"10Y",step:"year",stepmode:"backward"},{count:5,label:"5Y",step:"year",stepmode:"backward"},{count:1,label:"1Y",step:"year",stepmode:"backward"},{count:1,label:"YTD",step:"year",stepmode:"todate"},{count:6,label:"6M",step:"month",stepmode:"backward"},{count:1,label:"1M",step:"month",stepmode:"backward"}]},
  type: 'date',
  linecolor: '#D8D8D8',
  linewidth: 1,
  mirror: true,
  tickfont: {color: '#8f8f8f'},
  tickformat: '%B %Y',
  hoverformat: '%d %B %Y',
}

That works great but when I click time range which bigger than my data, there are empty space in the left of the chart.

enter image description here
I know that is expected, but I want to update this chart with minimum date of my data, even when more range selected.

Is there any way to handle this?

Maybe I can set start and end dates in range selector buttons instead of “1 year”, “5 year”. I couldn’t any way to it.

How can I render icon if my column, if I have condition?

I have a Primereact v9 ReactJS code

 <DataTable
                
                <Column field="status" header="Status"
                        style={{
                            maxWidth: '150px',
                            overflow: 'hidden',
                            textOverflow: 'ellipsis',
                            whiteSpace: 'nowrap'
                        }}
                        sortable>
                    {(field) => {
                        console.log(field)
                    }}
                </Column>
            </DataTable>

I want to check if field “status” contains numeric values, and render with status text an icon

I’ve tried to

<Column field="status" header="Статус"
                        style={{
                            maxWidth: '150px',
                            overflow: 'hidden',
                            textOverflow: 'ellipsis',
                            whiteSpace: 'nowrap'
                        }}
                        sortable>
                    {(field) => {
                        console.log(field)
                    }}
                </Column>

but nothing happened

how to make successful google login on vercel/render using puppeteer in headless mode?

I am trying to make google login using puppeteer in headless: true mode on vercel/render but getting this error after browser is launched successfully.

TimeoutError: waiting for selector `input[type="password"]:not([aria-hidden="true"])` failed: timeout 60000ms exceeded
    at new WaitTask (/vercel/path0/node_modules/puppeteer/lib/cjs/puppeteer/common/IsolatedWorld.js:445:34)
    at IsolatedWorld._waitForSelectorInPage (/vercel/path0/node_modules/puppeteer/lib/cjs/puppeteer/common/IsolatedWorld.js:335:26)
    at Object.internalHandler.waitFor (/vercel/path0/node_modules/puppeteer/lib/cjs/puppeteer/common/QueryHandler.js:46:83)
    at Frame.waitForSelector (/vercel/path0/node_modules/puppeteer/lib/cjs/puppeteer/common/Frame.js:420:36)
    at Page.waitForSelector (/vercel/path0/node_modules/puppeteer/lib/cjs/puppeteer/common/Page.js:2318:39)
    at login (/vercel/path0/node_modules/youtube-videos-uploader/dist/upload.js:974:25)
    at processTicksAndRejections (node:internal/process/task_queues:96:5)
    at async loadAccount (/vercel/path0/node_modules/youtube-videos-uploader/dist/upload.js:838:13)
    at async upload (/vercel/path0/node_modules/youtube-videos-uploader/dist/upload.js:52:9)

upon printing the content of the page i got to know that it is not going to password page and it is showing the browser is insecure on console.but the same thing works perfectly on local system in both headless and headful mode. also already using stealth plugin for not getting detected.

PFA code for login:

async function login(localPage, credentials, messageTransport, useCookieStore = true) {
    var _a;
    await localPage.goto(uploadURL);
    if (!useCookieStore) {
        try {
            // Check if already logged in if we don't use normal cookie store
            await localPage.waitForSelector('button#avatar-btn', {
                timeout: 15 * 1000
            });
            messageTransport.log(`Account already logged in`);
            return;
        }
        catch (_b) { }
    }
    await changeLoginPageLangIfNeeded(localPage);
    const emailInputSelector = 'input[type="email"]';
    await localPage.waitForSelector(emailInputSelector);
    await localPage.type(emailInputSelector, credentials.email, { delay: 50 });
    await localPage.keyboard.press('Enter');
    // check if 2fa code was sent to phone
    await localPage.waitForNavigation();
    await localPage.waitForTimeout(1000);
    await page.screenshot({ path: `./bee_homepage1.jpg` });
    const googleAppAuthSelector = 'samp';
    const isOnGoogleAppAuthPage = await localPage.evaluate((authCodeSelector) => document.querySelector(authCodeSelector) !== null, googleAppAuthSelector);
    if (isOnGoogleAppAuthPage) {
        const codeElement = await localPage.$('samp');
        const code = (_a = (await (codeElement === null || codeElement === void 0 ? void 0 : codeElement.getProperty('textContent')))) === null || _a === void 0 ? void 0 : _a.toString().replace('JSHandle:', '');
        code && messageTransport.userAction('Press ' + code + ' on your phone to login');
    }
    // password isnt required in the case that a code was sent via google auth
    else {
        await page.screenshot({ path: `./bee_homepage.jpg` });
        console.log("hii");
        await page.screenshot({ path: `./bee_homepage2.jpg` });
        const passwordInputSelector = 'input[type="password"]:not([aria-hidden="true"])';
        await localPage.waitForSelector(passwordInputSelector);
        await localPage.waitForTimeout(3000);
        await localPage.type(passwordInputSelector, credentials.pass, { delay: 50 });
        await localPage.keyboard.press('Enter');
    }
    try {
        await localPage.waitForNavigation();
        await localPage.waitForTimeout(1000);
        // check if sms code was sent
        const smsAuthSelector = '#idvPin';
        const isOnSmsAuthPage = await localPage.evaluate((smsAuthSelector) => document.querySelector(smsAuthSelector) !== null, smsAuthSelector);
        if (isOnSmsAuthPage) {
            try {
                if (!messageTransport.onSmsVerificationCodeSent)
                    throw new Error('onSmsVerificationCodeSent not implemented');
                let code = await messageTransport.onSmsVerificationCodeSent();
                if (!code)
                    throw new Error('Invalid SMS Code');
                await localPage.type(smsAuthSelector, code.trim());
                await localPage.keyboard.press('Enter');
            }
            catch (error) {
                await browser.close();
                throw error;
            }
        }
    }
    catch (error) {
        const recaptchaInputSelector = 'input[aria-label="Type the text you hear or see"]';
        const isOnRecaptchaPage = await localPage.evaluate((recaptchaInputSelector) => document.querySelector(recaptchaInputSelector) !== null, recaptchaInputSelector);
        if (isOnRecaptchaPage) {
            throw new Error('Recaptcha found');
        }
        throw new Error(error);
    }
    //create channel if not already created.
    try {
        await localPage.click('#create-channel-button');
        await localPage.waitForTimeout(3000);
    }
    catch (error) {
        messageTransport.log('Channel already exists or there was an error creating the channel.');
    }
    try {
        const uploadPopupSelector = 'ytcp-uploads-dialog';
        await localPage.waitForSelector(uploadPopupSelector, { timeout: 70000 });
    }
    catch (error) {
        if (credentials.recoveryemail)
            await securityBypass(localPage, credentials.recoveryemail, messageTransport);
    }
    if (useCookieStore) {
        const cookiesObject = await localPage.cookies();
        await fs_extra_1.default.mkdirSync(cookiesDirPath, { recursive: true });
        // Write cookies to temp file to be used in other profile pages
        await fs_extra_1.default.writeFile(cookiesFilePath, JSON.stringify(cookiesObject), function (err) {
            if (err) {
                messageTransport.log('The file could not be written. ' + err.message);
            }
            messageTransport.log('Session has been successfully saved');
        });
    }
    else {
        messageTransport.log('Account logged in successfully');
    }
}

PrismaClientKnownRequestError: Invalid `prisma.expense.create()` invocation:

I’m learning Remix, and in the toturial I’m learning with, i got the problem working with Prisma and MongoDB.

I’m trying to POST data to db and i think the problem has nothing to do with the js code because is the same as toturial said.

Here’s the complete error:

PrismaClientKnownRequestError: 
Invalid `prisma.expense.create()` invocation:


Raw query failed. Code: `unknown`. Message: `Kind: Transactions are not supported by this deployment, labels: {}`
    at si.handleRequestError (E:RemixPracticeremix-expense-newnode_modules@prismaclientruntimelibrary.js:125:6817)
    at si.handleAndLogRequestError (E:RemixPracticeremix-expense-newnode_modules@prismaclientruntimelibrary.js:125:6151)
    at si.request (E:RemixPracticeremix-expense-newnode_modules@prismaclientruntimelibrary.js:125:5859)
    at l (E:RemixPracticeremix-expense-newnode_modules@prismaclientruntimelibrary.js:130:9805)
    at addExpense (file:///E:/Remix/Practice/remix-expense-new/app/data/expenses.server.js:5:16)
    at action (file:///E:/Remix/Practice/remix-expense-new/app/routes/_expensesLayout.expenses.add.jsx:24:5)
    at Object.callRouteActionRR (E:RemixPracticeremix-expense-newnode_modules@remix-runserver-runtimedistdata.js:35:16)
    at callLoaderOrAction (E:RemixPracticeremix-expense-newnode_modules@remix-runrouterrouter.ts:4011:16)
    at submit (E:RemixPracticeremix-expense-newnode_modules@remix-runrouterrouter.ts:3131:16)
    at queryImpl (E:RemixPracticeremix-expense-newnode_modules@remix-runrouterrouter.ts:3066:22)

and i think the problem is that prisma can’t connect with mongodb.

but here’s the code that i use ‘prisma.expense.create()’:

import { prisma } from "./database.server";

export async function addExpense(expenseData){
    try{
        return await prisma.expense.create({
            data: {
                title: expenseData.title,
                amount: +expenseData.amount,
                date: new Date(expenseData.date),
            } 
        })
    }
    catch (error){
        console.log(error);
        throw error;
    }
}

React Router using createBrowserRouter vs BrowserRouter

I am starting a new React project and want to use the latest version of React Router. The docs recommend using createBrowserRouter for all web projects. They don’t say why it is better than using BrowserRouterother than it enables some data APIs. Is this the only advantage.

Additionally there is a note in the docs saying

Due to the decoupling of fetching and rendering in the design of the data APIs, you should create your router outside of the React tree with a statically defined set of routes. For more information on this design, please see the Remixing React Router blog post and the When to Fetch conference talk.

I’m not exactly sure what they mean by outside the React tree isn’t everything in my project in the React tree.

Currently I am implementing my router like this:

Main.tsx

ReactDOM.createRoot(document.getElementById('root')!).render(
  <GenReMsal>
    <React.StrictMode>
      <App />
    </React.StrictMode>
  </GenReMsal>
)

App.js

function App({ msalContext }: AppProps) {
  return (
    <>
      <AuthenticatedTemplate>
        <Router currentUser={msalContext.accounts[0]} />
      </AuthenticatedTemplate>
    </>
  )
}

Router.js

function Router({ currentUser }: Props) {
  const userInfo = { name: currentUser.name }

  const router = createBrowserRouter([
    {
      path: '/:appTypeId?',
      element: <AppLayout currentUser={userInfo} />,
      loader: defaulNewAPIs,
      children: [
        {
          index: true,
          element: <ReferralDetails status="new" />,
        },
      ],
    },
  ])

  return <RouterProvider router={router} />
}

This doesn’t seem to be outside the React tree but I am not exactly sure what would.

syntax error nextjs using react-testing-library and jest as test runner

I am using react-testing-library and jest for testing in a nextjs project. But I got this error while running the test.
Importing things are excluded since stackoverflow calimed , there is so much code without details!

  x Expression expected
      5 |
      6 | describe('Page is working', () => {
      7 |   it('renders a heading', () => {
      8 |     render(<RootLayout/>)
        :                         ^
      9 |     const heading = screen.getByRole('heading', { level: 1 })
     10 |
     11 |     // expect(heading).toBeInTheDocument()
        `----
    Caused by:
        Syntax Error

jest setup below . I followed the official docs of nextjs.

// jest.config.ts

const createJestConfig = nextJest({
  // Provide the path to your Next.js app to load next.config.js and .env files in your test environment
  dir: './',
})

// Add any custom config to be passed to Jest
const config: Config = {
  coverageProvider: 'v8',
  testEnvironment: 'jsdom',
  // Add more setup options before each test is run
  setupFilesAfterEnv: ['<rootDir>/jest.setup.ts'],

}

// createJestConfig is exported this way to ensure that next/jest can load the Next.js config which is async
export default createJestConfig(config)

and the jest setup file also implemented following the nextjs docs.

// jest.setup.ts
import type { Config } from 'jest'
import nextJest from 'next/jest.js'

const createJestConfig = nextJest({
  // Provide the path to your Next.js app to load next.config.js and .env files in your test environment
  dir: './',
})

// Add any custom config to be passed to Jest
const config: Config = {
  coverageProvider: 'v8',
  testEnvironment: 'jsdom',
  // Add more setup options before each test is run
  setupFilesAfterEnv: ['<rootDir>/jest.setup.ts'],

}

// createJestConfig is exported this way to ensure that next/jest can load the Next.js config which is async
export default createJestConfig(config)

and the test file is here

// /home/raihan/Projects/Code/Blog/client/__tests__/profile/register.ts


import '@testing-library/jest-dom'
import { render, screen } from '@testing-library/react'
import React from 'react'
import Page from '@/app/users/page'
import RootLayout from '@/app/layout'
describe('Page is working', () => {
  it('renders a heading', () => {
    render(<RootLayout/>)
    const heading = screen.getByRole('heading', { level: 1 })

    // expect(heading).toBeInTheDocument()

  })
})

Why I am getting the syntax Error? why the render function is not working? I have searched in google and also stackoverflow but didn’t get the correct answer.

uncaught referenceError my function is not defined at onload

I am trying to draw rectangles on top of eachother with a delay using canvas. But I keep getting “uncaught referenceError: drawShapes is not defined at onload. Does anyone know how to fix the error?

I’ve seen some other posts about this but none of the solutions have fixed my problem.

<head>
<title> Nested Circles Within Nested Rectangles </title>
<script type="text/javascript">
    
function drawShapes() { 
var canvas = document.getElementById("Rectangle");

if (canvas.getContext) {
var rectangle = canvas.getContext("2d");

setTimeout(function(){

rectangle.fillStyle = "red";
rectangle.rect(0, 0, 150, 75);

}, 1000);
setTimeout(function(){

Draw a blue rectangle here...

}, 2000);
setTimeout(function(){

Draw a yellow rectangle here...

}, 3000);
setTimeout(function(){

Draw the first red circle here...

}, 4000);
setTimeout(function(){

Draw the first blue circle here...

}, 5000);
setTimeout(function(){

Draw the first yellow circle here...

}, 6000);
setTimeout(function(){

Draw the second red circle here...

}, 7000);
setTimeout(function(){

Draw the second blue circle here...

}, 8000);
setTimeout(function(){

Draw the second yellow circle here...

}, 9000);
}
}
</script>
</head>
<body onload="drawShapes()">
<h1> Nested Circles Within Nested Rectangles </h1>
<canvas id="Rectangle" width="650" height="300" style="border: 1px solid black; background-color: black">
Your browser does not support the Canvas tag.
</canvas>
</body>

How to re render component when the argument changes from the table component in Ember.js?

Im a beginner in Ember.js framework, and Im having trouble updating a component from another one.

I have this table component with the checkbox rows, and everytime the number of checked rows its updating I need to update a button in another component.

This is the code for the table and also in this code its called the component that I need to change MultiGiftAllocationForm

        <table class="table table-sm mb-lg" role="table">
            <thead>
              <tr>
                <th>Donor</th>
                {{#unless (or this.hasOneChecked this.hasMultipleChecked)}}
                  <th>Fund
                  </th>{{/unless}}

                <th>Check #</th>
                <th class="!pl-0 !text-right">Amount</th>
              </tr>
            </thead>
            <tbody>
              {{#each this.allocatedGifts as |row|}}
                <tr>
                  <td class="!pr-0">
                    <div class="flex items-center justify-start">
                      <span
                        class="mr-sm h-[8px] w-[8px] rounded-full bg-y400"
                      ></span>
                      <KitCheckbox
                        @click={{fn this.updateCheckedRows row}}
                        @checked={{row.isChecked}}
                        @classNames="checkbox mr-md"
                      />
                      <span>{{row.donor}}</span>
                    </div>
                  </td>
                  {{#unless (or this.hasOneChecked this.hasMultipleChecked)}}
                    <td>
                      <div>{{row.fund}}</div>
                    </td>
                  {{/unless}}
                  <td>{{row.checkNumber}}</td>
                  <td class="!pl-0 text-right">
                    {{format-currency row.amount}}
                  </td>
                </tr>
              {{/each}}
            </tbody>
          </table>
        </div>
      </div>
      <div
        class={{concat
          (if
            (or this.hasOneChecked this.hasMultipleChecked)
            " col-span-3"
            " col-span-2"
          )
        }}
      >
        {{#if this.hasMultipleChecked}}
          <GiftEntry::MultiGiftAllocationForm
            @giftsNumber={{this.selectedGifts}}
          />

and the ts file for this code

import Controller from '@ember/controller';
import { action, set } from '@ember/object';
import RouterService from '@ember/routing/router-service';
import { inject as service } from '@ember/service';
import { tracked } from '@glimmer/tracking';
import config from 'giving/config/environment';
import UnleashService from 'giving/services/unleash';

export interface MockDataAllocationRow {
  id: number;
  donor: string;
  fund: string;
  checkNumber: string;
  amount: number;
  isChecked: boolean;
}

export default class OrgGiftEntryIndexController extends Controller {
  // -------------------------------------------------------------------------
  // Dependencies

  @service router: RouterService;
  @service unleash: UnleashService;

  // -------------------------------------------------------------------------
  // Properties

  // table state
  @tracked hasOneChecked = false;
  @tracked hasMultipleChecked = false;
  @tracked selectedGifts: MockDataAllocationRow[] = [];

  // table arrays
  @tracked allocatedGifts: MockDataAllocationRow[] = [
    {
      id: 1,
      donor: 'Beatrice Brito',
      fund: 'Building',
      checkNumber: '5045',
      amount: 300,
      isChecked: false,
    },
    {
      id: 2,
      donor: 'Lisanne Viscaal',
      fund: 'Assign a fund',
      checkNumber: '5045',
      amount: 300,
      isChecked: false,
    },
  ];
  @tracked unallocatedGifts: MockDataAllocationRow[] = [
    {
      id: 3,
      donor: 'Assign a donor',
      fund: 'Two funds',
      checkNumber: '1506',
      amount: 15,
      isChecked: false,
    },
    {
      id: 4,
      donor: 'Assign a donor',
      fund: 'Assign a fund',
      checkNumber: '1013',
      amount: 85.24,
      isChecked: false,
    },
    {
      id: 5,
      donor: 'Assign a donor',
      fund: 'Assign a fund',
      checkNumber: '5045',
      amount: 300,
      isChecked: false,
    },
    {
      id: 6,
      donor: 'Assign a donor',
      fund: 'Assign a fund',
      checkNumber: '5045',
      amount: 300,
      isChecked: false,
    },
  ];
  @tracked needsReviewGifts: MockDataAllocationRow[] = [
    {
      id: 7,
      donor: 'Beatrice Britana',
      fund: 'Assign a fund',
      checkNumber: '5045',
      amount: 300,
      isChecked: false,
    },
    {
      id: 8,
      donor: 'Lisanne Vischer',
      fund: 'Assign a fund',
      checkNumber: '5045',
      amount: 300,
      isChecked: false,
    },
    {
      id: 9,
      donor: 'Warren Kindler',
      fund: 'Assign a fund',
      checkNumber: '5045',
      amount: 300,
      isChecked: false,
    },
    {
      id: 10,
      donor: 'Carole Chimako',
      fund: 'Assign a fund',
      checkNumber: '5045',
      amount: 300,
      isChecked: false,
    },
  ];

  // -------------------------------------------------------------------------
  // Getters / Setters

  // -------------------------------------------------------------------------
  // Events

  // -------------------------------------------------------------------------
  // Actions

  /** Route to batches if they don't have the bulk check scan unleash flag. */
  @action
  checkUnleash(): void {
    if (!this.unleash.bulkCheckScan && config.environment !== 'local') {
      this.router.transitionTo('org.batches');
    }
  }

  /** Simple toggle on/off of checkboxes while data is not real. */
  @action
  updateCheckedRows(row: MockDataAllocationRow, evt: Event): void {
    evt.preventDefault();

    const clickedElementIndex = this.selectedGifts.findIndex(
      (g) => g.id === row.id
    );

    if (clickedElementIndex > -1) {
      // item is already checked; uncheck it and remove from tracking array
      set(this.selectedGifts[clickedElementIndex], 'isChecked', false);
      this.selectedGifts.splice(clickedElementIndex, 1);
    } else {
      // item is not checked; check it and add to tracking array
      const selectedGiftsLength = this.selectedGifts.length;
      this.selectedGifts.push(row);
      set(this.selectedGifts[selectedGiftsLength], 'isChecked', true);
    }

    this.hasOneChecked = this.selectedGifts.length === 1;
    this.hasMultipleChecked = this.selectedGifts.length > 1;
  }

  // -------------------------------------------------------------------------
  // Methods
}

And the component that I want to update MultiGiftAllocationForm everytime the checked list its updating this button value should be updated to <button class="btn btn-primary ml-md" type="button"> Update {{@giftsNumber.length}} gifts </button>
The code component

<div class="lg frame">
  <label class="text-base font-semibold text-n900">Allocate gifts</label>
  <label class="mb-xs mt-md block text-n500">
    Campus
  </label>
  <select id="campus" class="select mb-lg">
    <option selected disabled>--</option>
  </select>

  <div class="mb-lg">
    <label class="mb-xs block text-n500" for="fund">
      Fund
    </label>
    <select id="fund" class="select">
      <option selected disabled>--</option>
    </select>
  </div>
  <div class="mb-lg">
    <label class="mb-xs block text-n500" for="fund">
      Date received
    </label>
    <waves-date-picker value="11/15/2023"></waves-date-picker>
  </div>
  <div class="flex justify-end">
    <button class="btn" type="button">
      Cancel
    </button>
    <button class="btn btn-primary ml-md" type="button">
      Update
      {{@giftsNumber.length}}
      gifts
    </button>
  </div>
</div>

The ts file :

import Component from '@glimmer/component';

type Args = {
  // batch?: Batch | null;
  // onBatchSaved(batch: Batch): void;
  // onCancel(): void;
  giftsNumber: number;
};

/** Right sidebar form when 2 or more gifts are selected, to allocate fund, campus, and date */
export default class MultiGiftAllocationForm extends Component<Args> {
 
}

ws does not working from the electron main process? ws does not work in the browser?

code:

import WebSocket from 'ws';

const ws = new WebSocket();

error:

ws does not work in the browser. Browser clients must use the native WebSocket object

The error comes from ./browser.js.

ws package.json :

  "exports": {
    ".": {
      "browser": "./browser.js",
      "import": "./wrapper.mjs",
      "require": "./index.js"
    },
    "./package.json": "./package.json"
  }

Why did use browser.js, nstead of using wrapper.mjs ?

HTML Canvas not accepting bold font on mobile

I have a simple HTML5 canvas on the page

<canvas class="wapf-canvas"></canvas>

Whenever I set the font to bold, it works on desktop but not on mobile:

var ctx = document.querySelector('.wapf-canvas').getContext('2d')
ctx.font = "bold 12px sans-serif";

console.log(ctx.font) shows 12px sans-serif, so it ommited the bold font-weight for some reason. Here is the output from Safari mobile:

enter image description here

Why is that and how can it be fixed?