Insert a value in the content editable field at the lat caret position using ReactJS

I have an app in react js.

import "./styles.css";
import React, { useState } from "react";
const elements = ["123", "45", "test"];

export default function App() {
  const [value, setValue] = useState("hello editable");
  const [selected, setSelected] = useState("");

  const onClick = (e) => {
    const selectedText = e.currentTarget.innerHTML;
    const selection = window.getSelection();
    const range = selection.getRangeAt(0);

    // Delete the current selection and insert the selected text at the caret position
    range.deleteContents();
    range.insertNode(document.createTextNode(selectedText));

    // Move the caret to the end of the inserted content
    range.setStartAfter(range.endContainer);
    range.collapse(true);

    // Update the value state
    setValue(e.currentTarget.innerHTML);
  };

  return (
    <div className="App">
      <p>{selected}</p>
      <ul>
        {elements.map((e) => (
          <li onClick={(e) => onClick(e)}>{e}</li>
        ))}
      </ul>
      <div
        onBlur={(e) => setValue(e.currentTarget.innerHTML)}
        suppressContentEditableWarning
        contentEditable
      >
        {value}
      </div>
    </div>
  );
}

The idea is, when i click on an item from the list to make that text appear in the contentEditable field, but not at the random position, but at the position where the caret was the last time.

EX: i type in the field: “Hello world”, and then i add the caret after hello like: “Hello| world”. And then i click on “123” and as result i should get “Hello123 world”.

I tried to implement using selection but i did not succed, because the text is changed in the clicked item.
Question: How to achieve what i described above?

demo: https://codesandbox.io/p/sandbox/wonderful-dawn-3gfjzk?file=%2Fsrc%2FApp.js

How to do so that the browser prompts the user for the camera just once?

When using the WebRTC Javascript API, I noticed that the browser prompts the user for enabling the camera everytime the page is loaded in Firefox and Safari when calling navigator.mediaDevices.getUserMedia().

My objective is that the browser only prompts once the user, as it does in Chrome. How can I do this?

I have tried using navigator.mediaDevices.enumerateDevices(), thinking that I could use the result in getUserMedia to select the camera, but it doesn’t keep the user approval after the browser is closed.

JS code failing for large inputs in online judge

So, I got a question which as follows:
You’ve given two strings s1 and s2 where

1 <= s1.length <= 100000, s2.length = s1.length+1

both strings have lowercase alphabets only [a-z]. s1 and s2 have same amount of characters just shuffled in any order. But s2 has one extra char, and print it.

Input format as follows:

string1
string2

This is my code in JS(here process.stdin is default code provided in online editor):

const stdin = process.openStdin() ; // default in code editor

let str1, str2 ;
stdin.setEncoding('utf-8') ; // added
stdin.addListener('data', (d) => { // this listener was default
    [str1, str2] = d.split('n') ;
}) ;

stdin.addListener('end', () => { // added
    let code = str2.charCodeAt(0) ;

    for(let i=1; i<str2.length; i++){
        code += (str2.charCodeAt(i) - str1.charCodeAt(i-1)) ;
    }

    console.log(String.fromCharCode(code)) ;
}) ;

For small string lengths let’s say s1: abcd, s2: abcde it shows correctly ‘e’.

But larger strings closing near 10^5 this was giving runtime error.

Same code in C++, was passing all test cases.:

#include <iostream>
using namespace std ;
int main(){
    string s1, s2 ;
    cin >> s1 >> s2 ;
    int code = int(s2[0]) ;
    for(int i=1; s2[i] != ''; i++){
        code += (int(s2[i]) - int(s1[i-1])) ;
    }
    cout << char(code) ;
    return 0 ;
}

So, to check locally ran the same code with file.txt having string s1.length = 10^5-1 and s2.length = 10^5

Ran the command as follows:

Node.js: node script.js < file.txt

failed nodejs screenshot

I want to know the reason why the sdtin stream is undefined for large value and possibly how to tackle these kinds of case.

Javascript mapping and splitting an array within a map

I have some json from an API that I’m trying to process. Here’s an example of the json:

{
  id: 201741,
  first_name: "Kenneth",
  custom_fields: 
    [
      {
        field_id: 17304, 
        name: "Main subject (Max. of 3)", 
        value: "Maths English, Science"
      }
    ]
}

Here’s my current javascript:

fetch("https://api.site.com/v1/employees", requestOptions)
  .then(response => response.json())
  .then(response => console.log(response))
  .then(response => response.filter((e) => e.include_as_teacher = 1 && e.subjects != null && e.status == "Active"))
  .then(
    (response) =>
      (this.employees = this.cloneEmployees = response.map((e) => ({
        id: e.id,
        photo: 'public/img/profiles/' + e.first_name + e.last_name + '.jpg',
        backupphoto: e.photo,
        first_name: e.first_name,
        last_name: e.last_name,
        city: e.city,   
        country: e.country,
        main_subject: e.custom_fields.map((e) => (e.value)),
        subjects: e.subjects.split(","),
        bio: e.bio,
      }))))
      .then((response) => this.subjects = [...new Set(this.cloneEmployees.flatMap(item => item.subjects))].sort())
      .then((response) => console.log(this.employees))

At the moment, ‘main_subject’ is a string. However, I need to split this, much like ‘subjects’ on the line below so that I can display each subject individually in my HTML. I don’t understand how I can do this.

Refresh table dynamically after client received data trough websocket

good day peoples, i want to share about my problems, hopes this will help others with the same problem also. so how can i refresh the table data dynamically without the user refreshing the page. i tried to check if there is a data in the var responses, and if yes it will refresh the table. (the var response is where i get data, that was sent by the other client trough websocket).

this is what i have tried

var conn = new WebSocket('ws://10.43.4.52/websocket/');
    var tables = $('#description-table').DataTable();

    conn.onopen = function(e) {
        console.log('connected to websocket');
    };

    conn.onmessage = function(e) {
        console.log(JSON.parse(e.data));
        var responses = JSON.parse(e.data);
        if (responses.length > 0) {
            tables.ajax.reload();
        }
    };

How do I automatically create checkboxes in Google Sheets if checkbox is checked?

I want to automatically create checkboxes if a checkbox is checked

I have checkboxes in column 1(A)

and I want checkboxes to be made from B1 to E1 if A1 is checked

B2 to E2 if A2 is checked and so on

I also tried adding sheet.getLastRow in the script so it adds new checkboxes until the last row

but I don’t know where I got it wrong. (It’s the first time I tried using any kind of script)

Can you help me? Thanks in advance

Google Spreadsheets

Removing an element from a HTML string

I have string contains svg with some nested <svg></svg> tag like

<?xml version="1.0" encoding="utf-8"?>
<svg width="1" height="1">
  <svg width="2" height="2">
    <svg width="3" height="3"></svg>
  </svg>
</svg>

How can I using regex express to extract svg with result is

<svg width="1" height="1">
  <svg width="2" height="2">
    <svg width="3" height="3"></svg>
  </svg>
</svg>

React setState not updating the state object

Debugging:
Inside the functions declared in AuthProvider, I coded a console.log() and its working. The setState that updates the state object is not updating its value. Why?

Seems like I’m missing something. Can you help me out?

AuthContext.tsx

import React, { useState } from "react";
import { AuthContextType, User } from "../@types/auth";

export const AuthContext = React.createContext<AuthContextType | null>(null);

const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
    const [user, setUser] = useState<User>({
        auth: false,
        currentUrl: "",
    });

    const updateAuth = () => {
        console.log("Hello, world!")
        setUser({ ...user, auth: !user.auth });
    }

    const updateUrl = (url: string) => {
        setUser(user => ({
            ...user,
            currentUrl: url,
        }));
    }

    return (
        <AuthContext.Provider value={{ user, updateAuth, updateUrl }}>
            {children}
        </AuthContext.Provider>
    );
};

export default AuthProvider;

auth.d.ts

export type User = {
    auth: boolean;
    currentUrl: string;
}

export type AuthContextType = {
    user: User;
    updateAuth: () => void;
    updateUrl: (url: string) => void;
}

export type LoginCredentials = {
    email: string;
    password: string;
}

Login.tsx

const { updateAuth } = useContext(AuthContext) as AuthContextType;
if (response.data) {
                updateAuth();
}
**App.tsx**
import AppRouter from "./routes/AppRouter";
import AuthProvider from "./components/AuthContext";

function App() {
  return (
      <AuthProvider>
        <AppRouter />
      </AuthProvider>
  );
}

export default App;

How to compress pictures and keep them sharp [closed]

This is a php project.
The uploaded pictures should be expanded to 20M, and the upload speed should be fast and the pictures should be kept clear. The interface provided supports 20M, but when testing to upload a relatively large picture, it takes about 8 seconds. In order to increase the speed, I need to perform line compression before uploading.
.jpg .png

I use canvas to change the size of the image with quality 0.2. A 15M image will probably overwhelm around 1M, but some images will become blurry.

function CompressPic(file, size, device, myMsg, name, url) {
         const reader = new FileReader();
         reader.readAsDataURL(file);
         reader.onload = ({ target: { result: src } }) => {
             const image = new Image();
             image.src = src;
             const canvas = document.createElement('canvas');
             image.onload = () => {

                 canvas.width = image.width;
                 canvas.height = image.height;

                 canvas.getContext('2d').drawImage(image, 0, 0, image.width, image.height);
                 let canvasUrl, minFile;
                 let quality = 0.2;
                 canvasUrl = canvas.toDataURL('image/jpeg', quality);
                 let blob = dataURLtoBlob(canvasUrl);
                 minFile = blobToFile(blob, 'new' + file.name, file.type);
                 uploadCompressFile(minFile, myMsg, name, url);
             }
         }
     }

The product says this is not possible, the picture must be almost as clear as the original picture.
There is a problem. This compression will oversize images in .png format.
What else can be done?


There is another question. I saved the image directly in the service without compressing it, but the image is blurry. Why is this?

Testing a modal with DETOX that is not in the code of the app

So im trying to add some e2e test with Detox and Jest in react native app made with expo i have some problem with a modal that pops out when the app is lunched

describe('player app Activation screen', () => {
  beforeAll(async () => {
    //new instance makes to close the app and start it again

    await device.launchApp({ newInstance: true });
    debugger;

    await device.openURL({
      url: `exp+next11-reaxt-native-v2://expo-development-client/?url=${encodeURIComponent(
        `http://localhost:8081`
      )}`
    });
  });
  beforeEach(async () => {
    // await device.reloadReactNative();
  });

  it('should display and tap the "Got It" button in the development console ', async () => {
    await waitFor(element(by.text('Got It'))).toBeVisible();
    // .withTimeout(TIMEOUTS.short);

    await element(by.text('Got It')).tap();
  });

  it('should swipe down the development console', async () => {
    // await waitFor(element(by.text('Connected to:'))).toBeVisible();
    // .withTimeout(TIMEOUTS.short);

    await expect(element(by.text('Connected to:'))).toBeVisible();

    await element(by.text('Connected to:')).swipe('down');
  });

This is the modal that pops out

From the code i added before i managed to find the elements to tap the button and swipe down the console but now im experiencing some problems when the test runs i get different results every time and i think its all because of that modal

import { device, element, by, waitFor } from 'detox';

// As a rule of thumb, end every test with an expect line

// Define constants
const TEST_IDS = {
  haveAccountBtn: 'HaveAccountBtn',
  activationCodeInput: 'ActivationCodeInput',
  loginScreenWelcomeText: 'LoginScreenWelcomeText',
  activationNextButton: 'ActivationNextButton'
  // ... other test IDs
};
const TIMEOUTS = {
  short: 2000
  // ... other timeout values
};

describe('player app Activation screen', () => {
  beforeAll(async () => {
    //new instance makes to close the app and start it again

    await device.launchApp({ newInstance: true });
    debugger;

    await device.openURL({
      url: `exp+next11-reaxt-native-v2://expo-development-client/?url=${encodeURIComponent(
        `http://localhost:8081`
      )}`
    });
  });
  beforeEach(async () => {
    // await device.reloadReactNative();
  });

  it('should display and tap the "Got It" button in the development console ', async () => {
    await waitFor(element(by.text('Got It'))).toBeVisible();
    // .withTimeout(TIMEOUTS.short);

    await element(by.text('Got It')).tap();
  });

  it('should swipe down the development console', async () => {
    // await waitFor(element(by.text('Connected to:'))).toBeVisible();
    // .withTimeout(TIMEOUTS.short);

    await expect(element(by.text('Connected to:'))).toBeVisible();

    await element(by.text('Connected to:')).swipe('down');
  });

  it('should display the "Welcome" title', async () => {
    await expect(element(by.text('Welcome!'))).toBeVisible();
  });

  it('should have a disabled button', async () => {
    await expect(element(by.id(TEST_IDS.activationNextButton))).toExist();
  });

  it('should show the activation code input field', async () => {
    // await waitFor(element(by.id(TEST_IDS.activationCodeInput)))
    //   .toBeVisible()
    //   .withTimeout(TIMEOUTS.short);

    await expect(element(by.id(TEST_IDS.activationCodeInput))).toBeVisible();

    // Tap on the input field
    await element(by.id(TEST_IDS.activationCodeInput)).tap();

    // // Type text into the input field
    await element(by.id(TEST_IDS.activationCodeInput)).typeText('123456');

    // // Clear the text
    await element(by.id(TEST_IDS.activationCodeInput)).clearText();
  });

  it('should display and tap the "Already have an account" button', async () => {
    // Assertion

    await expect(element(by.id(TEST_IDS.haveAccountBtn))).toBeVisible();

    // Action
    await element(by.id(TEST_IDS.haveAccountBtn)).tap();

    // Assertion

    await expect(element(by.id(TEST_IDS.loginScreenWelcomeText))).toBeVisible();

    await expect(element(by.id(TEST_IDS.haveAccountBtn))).not.toBeVisible();
  });
});

This are my tests for now the first two it blocks are for closing the modal

D3.js – force directed graph not interactive

I’m trying to build a simple interactive force directed graph using d3.js v5. I’m using this code as a template, and I’m running the code using VSCode’s live server.

The main body of my HTML code looks like this

        <script src="https://d3js.org/d3.v5.min.js"></script>

        <script src="js/graph.js"></script>

and the script itself looks like this

const nodes = [
    { id: 1 }, 
    { id: 2 }, 
    { id: 3 }
];

const links = [
    { source: 1, target: 2 },
    { source: 2, target: 3 },
    { source: 3, target: 1 }
];

// Specify the dimensions of the chart.
const width = 928;
const height = 600;

// Specify the color scale.
const color = d3.scaleOrdinal(d3.schemeCategory10);

// Create a simulation with several forces.
const simulation = d3.forceSimulation(nodes)
    .force("link", d3.forceLink(links).id(d => d.id))
    .force("charge", d3.forceManyBody())
    .force("center", d3.forceCenter(width / 2, height / 2))
    .on("tick", ticked);

// Create the SVG container.
const svg = d3.create("svg")
    .attr("width", width)
    .attr("height", height)
    .attr("viewBox", [0, 0, width, height])
    .attr("style", "max-width: 100%; height: auto;");

// Add a line for each link, and a circle for each node.
const link = svg.append("g")
    .attr("stroke", "#999")
    .attr("stroke-opacity", 0.6)
    .selectAll()
    .data(links)
    .join("line")
    .attr("stroke-width", d => Math.sqrt(d.value));

const node = svg.append("g")
    .attr("stroke", "#fff")
    .attr("stroke-width", 1.5)
    .selectAll()
    .data(nodes)
    .join("circle")
    .attr("r", 5)
    .attr("fill", d => color(d.group));

node.append("title")
    .text(d => d.id);

// Add a drag behavior.
node.call(d3.drag()
        .on("start", dragstarted)
        .on("drag", dragged)
        .on("end", dragended));

// Set the position attributes of links and nodes each time the simulation ticks.
function ticked() {
    link
        .attr("x1", d => d.source.x)
        .attr("y1", d => d.source.y)
        .attr("x2", d => d.target.x)
        .attr("y2", d => d.target.y);

    node
        .attr("cx", d => d.x)
        .attr("cy", d => d.y);
}

// Reheat the simulation when drag starts, and fix the subject position.
function dragstarted(event) {
    if (!event.active) simulation.alphaTarget(0.3).restart();
    event.subject.fx = event.subject.x;
    event.subject.fy = event.subject.y;
}

// Update the subject (dragged node) position during drag.
function dragged(event) {
    event.subject.fx = event.x;
    event.subject.fy = event.y;
}

// Restore the target alpha so the simulation cools after dragging ends.
// Unfix the subject position now that it’s no longer being dragged.
function dragended(event) {
    if (!event.active) simulation.alphaTarget(0);
    event.subject.fx = null;
    event.subject.fy = null;
}
document.body.appendChild(svg.node());

but all I’m getting is this
sad triangle
and I can’t interact with it or anything. What am I missing?

MUI Sparkline: How to add $ symbol to the tooltip data in MUI Sparklinechart

I have the below SparklineChart from MUI

import * as React from 'react';
import Stack from '@mui/material/Stack';
import Box from '@mui/material/Box';
import { SparkLineChart } from '@mui/x-charts/SparkLineChart';

export default function CustomAxis() {
  return (
    <Stack direction="row" sx={{ width: '100%' }}>
      <Box sx={{ flexGrow: 1 }}>
        <SparkLineChart
          data={[1, 4, 2, 5, 7, 2, 4, 6]}
          xAxis={{
            scaleType: 'time',
            data: [
              new Date(2022, 5, 1),
              new Date(2022, 5, 2),
              new Date(2022, 5, 5),
              new Date(2022, 5, 6),
              new Date(2022, 5, 7),
              new Date(2022, 5, 8),
              new Date(2022, 5, 11),
              new Date(2022, 5, 12),
            ],
            valueFormatter: (value) => value.toISOString().slice(0, 10),
          }}
          height={100}
          showTooltip
          showHighlight
        />
      </Box>
    </Stack>
  );
}

And for this, chart gets generated as
enter image description here

I want to add a ‘$’ symbol in the tooltip as ‘$ 7’ instead of just ‘7’.
I tried converting the data which is in integer array to string int array, but the chart render throws an error saying the data should be in integers.

Any help is much appreciated

Thanks,

Why does nothing saves in my state when I tried to select (ShadCN)?

I just switch from ShadCn from MUI, I was just wondering why nothing changes in my select when I tried to change it.

  const handleClick = (e) => {
    console.log(data)
  }

This is my state.

 const [data, setData] = useState({
    from: '',
    end: '',
    year: '',
    college: '',
    type: ''
  })

This is my handle Change

const handleChange = (e) => {
    setData((prev) => ({...prev, [e.target.name]:e.target.value}))
  }

This is my select.

<Select defaultValue={data.from} onChange={handleChange} name="from">
          <SelectTrigger className="w-[180px]">
            <SelectValue placeholder="Start Month" />
          </SelectTrigger>
          <SelectContent>
            <SelectGroup>
              <SelectLabel>Month</SelectLabel>
              {monthsArray.map((item, index) => (
                <SelectItem key={index} value={item.number}>
                  {item.name}
                </SelectItem>
              ))}
            </SelectGroup>
          </SelectContent>
        </Select>

<Button onClick={handleClick}>
        Search
      </Button>