How can i implement common new Window Component in Angular 15?

I’m using angular 15.

I want to create a new common window component.
For example

<pop-up-window #windowComponent>
  <div popupContent>
    <div>plz show me the contents...</div>
  </div>
</pop-up-window>

and when the user presses a certain button, I want the something-content component to appear in a new window.

But when I get to the window, I don’t see my component in the new window. Also, ComponentFactoryResolver is deprecated, so I’m not sure how to implement it.

I’d love to hear from anyone who has experience with this.

Someone please help me out…plz…♥

I want a common component that can launch a new window, and that will display the component that each user injects as content in a new window pane.

Synchronous vue components rendering into a string

There is a SFC named Bubble of vue, that contains some simple layout.

Bubble.vue

<script setup lang="ts">

</script>

<template>
  <div hinted-name="wrapper-bubble" class="hinted-bubble-wrapper">
    <div class="hinted-bubble-frame" hinted-name="frame"></div>
  </div>
</template>

<style scoped lang="stylus">

</style>

I also have a class that uses this layout as a base for logic.

export class BubbleStepView extends StepComponentView {
  constructor() {
    super(Bubble.toString);
  }
}

This class needs to receive only an HTML string as a super argument.

Could someone tell me if there’s any way to synchronously convert a Vue component into a string?

The application works on a browser.

I attempted to use the method described in https://v1.test-utils.vuejs.org/api/rendertostring.html, but it didn’t work for me because it returns a Promise.

Is there a Ramda way to merge those two data arrays?

I need to merge two data arrays of the same shape.

My working code is this:

import * as R from 'ramda'

const expected = [
    [
        {
            "zeroData": false,
            "responseCount": [
                0,
                0,
                1,
                9
            ],
            "responsePercent": [
                0,
                0,
                0.1,
                0.9
            ],
            "index": 9.666666666666666,
            "stdDev": 0.9999999999999999,
            "expectedStdDev": 1.651740425387243
        }
    ]
]

const t1 = [
    [
        {
            "zeroData": false,
            "responseCount": [
                0,
                0,
                1,
                9
            ],
            "responsePercent": [
                0,
                0,
                0.1,
                0.9
            ],
            "index": 9.666666666666666,
            "stdDev": 0.9999999999999999
        }
    ]
]

const t2 = [
    [
        {
            "expectedStdDev": 1.651740425387243
        }
    ]
]

test('merge', () => {
    const merged = t1.map((arr1, idx1) => {
        return arr1.map((obj, idx2) => ({...obj, ...t2[idx1][idx2]}))
    })

    expect(merged).toStrictEqual(expected)
})

Is there a simple and elegant Ramda-way to do it? And especially a generic solution that would allow to specify the depth at which the merging should occur.

Tried various combinations of the R functions with no luck

Protecting Routes using React Router DOM v5

import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import { ChakraProvider } from "@chakra-ui/react";
import {BrowserRouter} from "react-router-dom"
import ChatProvider from "./Context/ChatProvider";

const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
  <BrowserRouter>
    <ChatProvider>
      <ChakraProvider>
        <App />
      </ChakraProvider>
    
    </ChatProvider>
  </BrowserRouter>
    
  
);

import './App.css';
import HomePage from "./Pages/HomePage";
import ChatPage from "./Pages/ChatPage";
import TrialPage from "./Pages/TrialPage";
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
import ProtectedRoute from "./utils/ProtectedRoute"
import ProtectedRouteTwo from "./utils/ProtectedRoute"
import { ChatState } from './Context/ChatProvider';
import { useEffect } from 'react';

function App() {
  
  const {user} = ChatState()

  useEffect(()=>{
    console.log("userDSE",user)
  })
  
  return (
    <div className="App">
    
      <Route path="/" component={HomePage} exact />
      <Route path="/chats" component={ChatPage}exact/>
    </div>
  );
}

export default App;

Does anyone have any idea how to protect my routes for “/chats”, I configured my routers this way while following along a YouTube tutorial. I have been trying to look for solutions
online but they were mostly for v6

How to memoize React elements rendered recursively when updating state object

I’m rendering elements that reflects the structure of an object, so each value is an input, each key is a label and the render function is recursive. When changing the value of an input I update the object with the new value and re-render. The problem is that each re-render is rendering all the elements and it is noticeable in the UI (in delay). I want to memoize the elements so it re-render only the changed input but I am having trouble doing so since I am using a spread operator in order to force the re-render after updating the object.

Let’s take an object for example:

{
  "id": "12345",
  "details": {
    "name": "jake",
  },
  "attachments": [
    {"file": "spodjgposg.file"},
    {"file": "sdgidfhoew.file"},
  ],
}

And the component to render the elements base on the object:

// all imports

const MemoObjectRendererInput = React.memo(ObjectRendererInput);

type Data = Record<any, any>;

type Entry = string | boolean | unknown[] | Data;

type Props = {
  onDataChange: (data: Data) => void;
  data: Data;
};

export const ObjectRenderer: FC<Props> = props => {
  const {data, onDataChange} = props;

  const onValueChange = (value: string, path: string) => {
    const _data = {...data};
    updateByPath(_data, path, value); // the function to update the object
    onDataChange(_data);
  };

  const render = (entry: Entry, label = '', level = -1, parent = 'root') => {
    if (typeof entry === 'string' || typeof entry === 'boolean') {
      const path = parent.replace('root.', '');
      return (
        <MemoObjectRendererInput
          onValueChange={v => onValueChange(v, path)}
          label={label}
          value={entry}
        />
      );
    }

    if (Array.isArray(entry)) {
      return (
        <div>
          <ObjectRendererLabel />
          {entry.map((item, index) => {
            return render(item, index.toString(), level + 1);
          })}
        </div>
      );
    }

    if (typeof entry === 'object') {
      return (
        <div>
          <ObjectRendererLabel />
          {isExpanded && Object.entries(entry).map(([key, value]) => {
            return render(value, key, level + 1, [parent, key].join('.'));
          })}
        </div>
      );
    }
  };

  return (
    <div>
      {render(data)}
    </div>
  );
};

This is the updateByPath function:

const updateByPath = (object: Record<any, any>, path: string, value: string | boolean) => {
  const _path = path.split('.');

  while (_path.length > 1) {
    const key = _path.shift();
    if (key) object = object[key];
  }

  const key = _path.shift();
  if (key) object[key] = value;
};

I tried memoize ObjectRendererInput also tried to use useCallback on the render function but when changing a value on an input all the elements are re-rendered.

How can I solve this? What is the best implementation to achieve this?

. Extension manifest must request permission to access the respective host for a local file

I got this code :

manifest.json

{
  "manifest_version": 3,
  "name": "AutoClicker",
  "version": "1.0",
     "permissions": ["activeTab", "scripting"],
  "background": {
    "service_worker": "background.js"
  },
  "host_permissions": ["*://*/*"],
  "content_scripts": [
    {
      "matches": ["<all_urls>"],
      "js": ["content.js"]
    }
  ],
  "action": {}
}


I’m trying to test it on a local file , but whenever i try it i got this :

Error executing script: Error: Cannot access contents of the page. Extension manifest must request permission to access the respective host.

i searched for the permission and i couldn’t find it , any help ?

I tried to run that script on a local host file , but i get an error that i don’t have permission

Is there a cache library that does this? [closed]

Let’s say there’s a route for fetching projects. Now if we send from the front a request to change a single project (the request return the changed project), it wont update the already cached project.
I’d like a library that somewhat automatically update the get projects cache on a change like this.

I tried looking for a library like this but couldn’t find any, unfortunately.

I want to convert the date object into a different timezone object(remember not a tz string that i know already) to feed in react date picker [closed]

Actually i have a coach-student task management system. In which coach and student may be of different countries . And coach can login to student account directly with a button and assign them a task. So coach should see the time options according to student timezone. I used react-date-picker for selecting time. So it wants date object only to function. but moment().tz(“Asia/Dhaka”) gives me a timezone string but when i convert it using moment().tz(“Asia/Dhaka”).toDate() then it gives me the date object according to my system’s default timezone. i tried all libraries and we cannot programmetically set system timezone to a custom timezone. I want the date object to be converted to “Asia/Dhaka” timezone which is GMT+6:00 not Asia/kolkata which is GMT+5:30.

I tried moment , moment-timezone, luxon to try to get custom timezone object. i tried moment.tz.setDefault to set timezone but its not working . I tried intl.datetimeformat().resolvedoptions().timezone to change system timezone but its constant we cannot change . There are lot of options to get timezone string but no option to get custom timezone object.

How to pass dynamic props to dynamic component in ReactJS Typescript?

Let’s say I have a home page which received array of data as props from nextjs getServierSideProps. And I have a object of component like that

const pages = {
  0: Welcome,
  1: SimType,
  2: NumberSearch,
  3: ShoppingCart,
  4: PersonalInformation,
  5: ShippingAddress,
  6: OrderConfirmation,
}

In home page I’m rendering component from pages based on currentStep(which is a number between 0 to 7). And passing props to rendered component also based on currentStep. Here is my home page demo:

const pages = {
  0: Welcome,
  1: SimType,
  2: NumberSearch,
  3: ShoppingCart,
  4: PersonalInformation,
  5: ShippingAddress,
  6: OrderConfirmation,
}

export default function Home({homeData}: {homeData: any}) {

  // currentStep will be a number from 0 to 6
  const currentStep = useSelector(selectStep)

  // Select component based on currentStep to render
  const Component = pages[currentStep as keyof typeof pages]

  return (
    <div className='mx-auto h-screen max-w-lg'>
      <Component
        // handleStepClick={handleStepClick}
        data={homeData[currentStep]}
      />
    </div>
  )
}

export const getServerSideProps = wrapper.getServerSideProps(
  (store) => async (context) => {
    try {
      const [homeData] = await Promise.all([getHomeData()])

      return {
        props: {
          homeData,
        },
      }
    } catch (error) {
      console.log('===Error from index.js page===', error)
    }
  }
)

And in the component listed above (Welcome, Simtype e.t.c), I define the props type according to their use case. As an example I define props type for Welcome component like that –

type Props = {
  data: {
    title: string
    subtitle: string
    sim_image: string
    packages: string[]
  }
  handleStepClick: (direction: 'next' | 'prev') => void
}

The problem is: when I hover over the data props in vscode, it shows the type of data is intersection of my Component List.

enter image description here

But I except union rather than intersection. How can I fix that so that type of data will be like that

<Component
    data = WelcomePropsType | SimTypePropsType | NumberSearchPropsType | AndSoOn
/>

Mongoose model.findOne().exec crashes app with response when it can’t find the document

const Article = require('../model/Article');
const User = require('../model/User');
const jwt = require ('jsonwebtoken');
const ROLES_LIST = require('../config/roles_list');
const verifyRoles = require('../middleware/verifyRoles');

// Other methods in this space //

const getArticle = async (req, res) => {
    if (!req?.params?.id) return res.status(400).json({ message: 'Article ID required.'});

    const article = await Article.findOne({ _id: req.params.id}).exec();
    if (!article) {
        return res.status(204).json({ message: `Article ID ${req.params.id} not found.`});
    }
    res.json(article);
    //For some reason, an ID that doesn't exist in the database tries to reply with the structure of the entire database.
};

// One more method here //

module.exports = { 
    handleNewArticle,
    getAllArticles,
    deleteArticle,
    getArticle,
    editArticle
};

This is the relevant piece of code. It returns an article with the id provided in the url parameters. It works perfectly when an _id existing in the database “articles” is provided, returning a json in thunder client. Otherwise, it returns a massive block of text in the terminal, with information I have little understanding of – though I see within it information about how I’m connected to the MongoDB, what address it is, who is the host, what are my connectionOptions, what is the ConnectionString in plaintext (which in itself contains the Admin account’s name and password), and much more.

I make this request via Thunder Client on VSCode, making a GET request with /articles/(id) after the relevant address – expecting a json response.

Sanitized DATABASE_URI for connecting to Mongodb
`DATABASE_URI=mongodb+srv://:@..mongodb.net/<database_name>?retryWrites=true&w=majority

I’ve tried to see if expanding my DATABASE_URI link from just the database inside the Cluster to the whole Cluster would work, but it only creates a new, empty “test” database with the articles and users models inside.

I’ve tried searching the mongoose docs for findOne syntax errors, but I didn’t find anything obvious, And I don’t know why an existing ID would gives a correct response, while an Id that doesn’t exist doesn’t return the expected “null”.

Searching for a solution on google (results on stack overflow) gives me either people who “always Only Get Null” which is not my problem, Or a post i’ve seen that looked promising, but they were using try into await model.then, and got told to not use Then. As you can see, it doesn’t seem applicable to me.

I’ve also come across a post from 11 years ago, having a similar odd response. But. They solve it by putting a Console.log in the functions callback, and if you check mongoosejs docs – // Model.findOne() no longer accepts a callback.

The Mongoose Docs on “model.findOne” informs us to use “findById” if we’re searching for _id, but when I replaced the line with const article = await Article.findById(req.params.id).exec();, the same odd behavior happens. Of course, a correct ID with this method ALSO returns a correct response, so, the issue does not lay with me using “findOne” instead of “findById” as recommended by mongoose documentation.

I’ve tried changing the if(!article) to if (article === null), but that didn’t change anything.
similarly if i wrote if(article !== null), if an id that doesn’t exist in the database is searched for, it writes the same stuff into the terminal in VSCode.

how to set boundary for tooltip in react-tooltip

Inside the box, there is a list of element each of them has a tooltip, if an item content is big, the tooltip show far a way from box
tooltip far a way from the box

import { Tooltip } from "react-tooltip"
const TestTooltip = () => {
  return (
    <div
      style={{
        display: "flex",
        alignItems: "center",
        justifyContent: "center",
        width: "100vw",
        height: "100vh",
      }}
    >
      <div
        style={{
          width: "300px",
          height: "400px",
          position: "relative",
          border: "1px solid gray",
          padding: "3px",
        }}
      >
        <div
          style={{
            overflow: "hidden",
            overflowY: "scroll",
            height: "100%",
            width: "100%",
          }}
        >
          <p data-tooltip-id="my-tooltip" style={{ width: "50%" }}>
            Lorem ipsum dolor sit amet, consectetur adipiscing elit.
            Pellentesque feugiat erat vel maximus tincidunt. Vivamus vitae
            lectus eros. Aenean lacus dolor, condimentum vitae felis vitae,
            congue molestie felis. Morbi aliquam neque ut aliquam 
          </p>
          <Tooltip
            style={{
              backgroundColor: "rgb(0, 255, 30)",
              color: "#222",
              position: "absolute !important",
            }}
            id="my-tooltip"
            content="Hello world!"
          />
        </div>
      </div>
    </div>
  )
}

export default TestTooltip

I want the tooltip to show next to the box if content is big

Javascript – calling a function with parameters [closed]

I am doing some POC on a javascript code below which is calling another function with parameters.

When i remove the parameters and hard code the value in the function ResendDeadletterToMain(), it works fine.

however when i send the parameters from the calling function it errors out with the below error.

ReferenceError: error is not defined
at ResendDeadletterToMain ((index):213:28)
at HTMLAnchorElement.onclick ((index):1:1)

Code that doesnot work

Code that works

My question is then how we can pass the parameters in this case ?

How can we pass the parameters in this case ?

JS, Problem with the draggable half circle being able to go inside the bar

<html>
<style>
#bar {
  position: fixed; /* Fixed position to stay in place on scroll */
  top: 0;
  bottom: 0;
  left: 0;
  width: 3px; /* Initial width of the bar */
  background-color: #f1f1f1; /* Background of the bar */
  border-right: 1px solid #d3d3d3; /* Border of the bar */
  z-index: 9;


  
}

#handle {
  width: 100px; /* Diameter of the handle circle */
  height: 100px; /* Height of the handle circle */
  background-color: #2196F3;
  border-radius: 50%; /* Make it round */
  position: absolute; /* Absolute position within the bar div */
  top: 50%; /* Center it vertically */
  right: -50px; /* Align to the right of the bar */
  transform: translateY(-50%); /* Adjust vertical position */
  cursor: pointer; /* Change cursor to indicate it's draggable */
  z-index: 10;
  clip-path: inset(0 0 0 50%); /* Clip left half of the circle */
}
</style>
<body>



<div id="bar">
  <!-- This is the draggable handle -->
  <div id="handle"></div>
</div>

<script>
// Make the handle draggable
dragElement(document.getElementById("handle"));

function dragElement(elmnt) {
  var startPosX = 0, currentPosX = 0;
  var maxBarWidth = window.innerWidth  - (elmnt.offsetWidth /16); // Tarayıcı penceresinin genişliğini kullan , Set the maximum width for the bar.

  elmnt.onmousedown = dragMouseDown;

  function dragMouseDown(e) {
    e = e || window.event;
    e.preventDefault();
    startPosX = e.clientX;
    document.onmouseup = closeDragElement;
    document.onmousemove = elementDrag;
  }

  function elementDrag(e) {
  e = e || window.event;
  e.preventDefault();
  currentPosX = e.clientX - startPosX;
  startPosX = e.clientX;
  var bar = document.getElementById("bar");
  var newWidth = bar.offsetWidth + currentPosX;

  // Define the minimum width to keep the handle from entering the bar area
  var minBarWidth = 3; // This is the initial width of the bar

  // Define the maximum width as a percentage of the window's width
  var maxBarWidth = window.innerWidth- elmnt.offsetWidth / 16;

  // Restrict the width within the minimum and maximum bounds
  newWidth = Math.max(minBarWidth, Math.min(newWidth, maxBarWidth));

  // Set the new width
  bar.style.width = newWidth + "px";

  // If the new width is at the minimum, keep the handle from going into the bar
  if(newWidth <= minBarWidth) {
    elmnt.style.right = "0px"; // This keeps the handle from entering the bar area
  } else {
    elmnt.style.right = "-50px"; // This is for when the handle is not at the minimum width
  }
}

  function closeDragElement() {
    // stop moving when mouse button is released:
    document.onmouseup = null;
    document.onmousemove = null;
  }
}
</script>

</body>
</html>

Hello friends, when I initially try to pull the semicircle from its end to the left, it goes into the bar in a way I don’t want and appears there. I actually have minBarWidth set to 3 which is the bar width but still this didn’t solve the problem

Undesired condition:

enter image description here

view that should be valid even if forced to move to the left:enter image description here