AceEditor’ cannot be used as a JSX component. Its type ‘typeof ReactAce’ is not a valid JSX element type

I have this project that mostly uses jsx extensions despite being setup with typescript. When creating a new component, I decided to go with the tsx extension and ran into this error:

'AceEditor' cannot be used as a JSX component.
  Its type 'typeof ReactAce' is not a valid JSX element type.
    Types of construct signatures are incompatible.
      Type 'new (props: IAceEditorProps) => ReactAce' is not assignable to type 'new (props: any, deprecatedLegacyContext?: any) => Component<any, any, any>'.
        Construct signature return types 'ReactAce' and 'Component<any, any, any>' are incompatible.
          The types returned by 'render()' are incompatible between these types.
            Type 'Element' is not assignable to type 'ReactNode'.ts(2786)

I searched and found nothing and tried type assertion: as unknown as JSX.Element, but that didn’t work either.

My code:

import React from 'react';
import AceEditor from 'react-ace';

// Import necessary modes and themes from ace-builds
import 'ace-builds/src-noconflict/mode-javascript';
import 'ace-builds/src-noconflict/mode-python';
// Add more modes here as needed

import 'ace-builds/src-noconflict/theme-github'; // You can change the theme if you wish
import 'ace-builds/src-noconflict/theme-monokai'; // You can change the theme if you wish

interface CodeEditorProps {
    language: string;
    starterCode: string;
    code: string;
    onChange: (newValue: string) => void;
    fontSize?: number; // Make fontSize an optional prop
}

const CodeEditorAce: React.FC<CodeEditorProps> = ({
    language,
    starterCode,
    code,
    onChange,
    fontSize = 14,
}) => {
    // Default fontSize is set to 14, but can be overridden by props

    const getMode = (language: string) => {
        switch (language.toLowerCase()) {
            case 'javascript':
                return 'javascript';
            case 'python':
                return 'python';
            // Add more cases for other languages you support
            default:
                return 'text';
        }
    };

    let value = code ? code : starterCode;

    return (
        <AceEditor
            placeholder="Do not edit the starter code."
            mode={getMode(language)}
            theme="monokai"
            value={value}
            onChange={onChange}
            name={`code-editor-${Math.random()}`} // Ensures a unique ID
            editorProps={{ $blockScrolling: true }}
            showPrintMargin={true}
            showGutter={true}
            highlightActiveLine={true}
            setOptions={{
                enableBasicAutocompletion: true,
                enableLiveAutocompletion: true,
                enableSnippets: true,
                showLineNumbers: true,
                tabSize: 2,
            }}
            fontSize={fontSize} // Set the font size here
            height="100%"
            width="100%"
        />
    );
};

export default CodeEditorAce;

I also get the same issue if I use code mirror instead of Ace Editor:

'CodeMirror' cannot be used as a JSX component.
  Its type 'ForwardRefExoticComponent<ReactCodeMirrorProps & RefAttributes<ReactCodeMirrorRef>>' is not a valid JSX element type.
    Type 'ForwardRefExoticComponent<ReactCodeMirrorProps & RefAttributes<ReactCodeMirrorRef>>' is not assignable to type '(props: any, deprecatedLegacyContext?: any) => ReactNode'.
      Type 'ReactElement<any, string | JSXElementConstructor<any>> | null' is not assignable to type 'ReactNode'.ts(2786)
        "react": "^18.2.0",
        "react-ace": "^10.1.0",
        "ace-builds": "^1.32.7",
        "react-dom": "^18.2.0",

I installed the types for ace and didn’t do much either.

canvg canvas getting slower with each edit/ memory usage increase

I have developed a scientific application to measure the area of shapes drawn on a scanned paper using canvg (version 3. something). The application works mostly fine (in Chrome), but gets really slow after a lot of small areas are selected.

var s = canvg('canvas', inp_xmls, {ignoreMouse: true, ignoreAnimation: true});

Each click inside an area performs a bucket fill using the canvg bucket-fill:

var bucket = Bucket(canvas, cfg, event, color);

Subsequently, the image is updated to view the new filled area:

    var lowerimg = svg.image(can.toDataURL());
    console.log(lowerimg)

    lowerimg.node.onload = function () {
        drawDown();

function drawDown() {
    inp_xmls = XMLS.serializeToString(svg.node);
    s.loadXml(ctx, inp_xmls);
    s.stop();
}

function undo() {
    var last = svg.last();

    if(svg.index(last) > 1) {
        last.remove();
        drawDown();
        s.draw();
    }
    undoAddArea();
}

Using the memory snapshots I can see ‘strings’ are increasing in size significantly (and image + #document).

The application is available online here:
https://limo.mni.thm.de/
Clicking on “Beispiel” on the right open an example slide in the drawing board.

My questions:

  • How can I reduce memory usage of the filling/ drawing on the canvas? Is there a function in canvg to ‘clear’ older layers?
  • I need the possibility to ‘undo’ clicks, so I need to store some of them. How do I access the old images like in the ‘undo’ function to remove everything older than 5 edits for example?

I need the pause and play functionality of the lightningchart lib curves in JavaScript

enter image description here
The back sends me an array of numbers and I take these numbers and display the ‘ECG’ type curves in the same way as in the documentation, perfect! This works, but I need the functionality to pause (stop the display of the curves) and play (unlock the display of the curves and the function continues consuming the array of numbers where it was paused). I’m asking you to help me with this… do you have a ready-made feature? If not, could you give me an idea of how to do it?

I tried this output from this example:
https://github.com/Arction/lcjs-showcase-audio
But unfortunately without success

React table updating with websocket

I have connection to WebSocket that sends me a message every 0.1s, than i write it to useState. Then react rerender whole table with new element. Is there any method to add new element to table or a part of a table, avoiding rerendering of all other elements?

I tried to use MillionJS library to optimise table rendering, but it’s not enough. It continue rerendering the whole table

JS – Create object from the object name in a var – ES6

This question was already asked and answered here.

Unfortunately it seems that this does not work with a ES6 classes.

Relevant Code of the classes involved:

class ORM {
  construct() {
    let className = 'Task';
    new this[className]; //throws: ORM.js:25 Uncaught TypeError: this[className] is not a constructor
    new window[className]; //throws: ORM.js:26 Uncaught TypeError: window[className] is not a constructor
    new this[className](1); //throws: ORM.js:27 Uncaught TypeError: this[className] is not a constructor
    new window[className](1); //throws: ORM.js:28 Uncaught TypeError: window[className] is not a constructor
  }
}
class Task extends ORM {
    constructor(id = null) {}
}

Is there any equivilant for ES6? Am I just missing something?

And no I would like to not use eval. Except if it is my last resort.

“Struggling to Develop Projects Independently After Learning HTML, CSS, JavaScript, and React: Should I Start Learning Backend Development?” [closed]

“Hello Stack Overflow community,

I’ve been learning HTML, CSS, JavaScript, and React for the past eight months, and I’ve even developed some projects by following tutorials on YouTube. However, I’ve been facing difficulties when trying to develop projects independently. Despite my efforts, I’m unable to come up with my own project ideas or execute them successfully.

I’m seeking advice on whether I should start learning backend development to enhance my skills and broaden my opportunities. If yes, I would appreciate guidance on how to begin.

Thank you for your help.”

stubborn problem: prompt an error when install express

[when I try to install package on my project that opened in vs code,like express or npm i, it’s alway prompt the error “The URL http://username:password@ip:port is invalid. Future versions of Node.js will throw an error.” I have no idea about this error. ](https://i.stack.imgur.com/HEsQZ.png)enter image description here

I try to change the environment by connecting with vpn in my windows 11, then. I have tried to delete the file
“npmrcby ” and tying ” npm cache clean –force” in the CMD, I also try ” npm install express -g ” and “npm install express –save” but fail. with the same prompt ” http://username:password@ip:port is invalid.”

Regex for fast JSON escape for string [closed]

The purpose of this regex is to have a very fast check for strings that do not need escaping while not being much slower than JSON.stringify() in case the input requires escaping. In summary, this regular expression is used to match and handle surrogate pairs correctly in Unicode strings, ensuring proper validation and handling of UTF-16 encoded characters

/[u0000-u001fu0022u005cud800-udfff]|[ud800-udbff](?![udc00-udfff])|(?:[^ud800-udbff]|^)[udc00-udfff]/

the real word usage is:

const strEscapeSequencesRegExp = /[u0000-u001fu0022u005cud800-udfff]|[ud800-udbff](?![udc00-udfff])|(?:[^ud800-udbff]|^)[udc00-udfff]/

/**
 * Fast JSON escape for string
 * @param {string} str
 * @returns {string}
 */
function strEscape (str) {
  if (typeof str !== 'string') {
    throw new TypeError(`Expected input to be of type string, received type ${typeof str} (${str})`)
  }
  // Only use the regular expression for shorter input. The overhead is otherwise too much.
  if (str.length < 5000 && !strEscapeSequencesRegExp.test(str)) {
    return `"${str}"`
  }
  return JSON.stringify(str)
}

I’m trying to optimize it and it seem the first part of the regex always check for the other parts and can be simplified in:

/[u0000-u001fu0022u005cud800-udfff]/

I’m correct? I have miss some test case?

const NEW = /[u0000-u001fu0022u005cud800-udfff]/;
const OLD = /[u0000-u001fu0022u005cud800-udfff]|[ud800-udbff](?![udc00-udfff])|(?:[^ud800-udbff]|^)[udc00-udfff]/;

const STRS = [
    'huaishdPUHAUShduiasuZ9172387AUihausihdu',
    'nrftb"\jiOJIjaiushdnrftb"\KJoa',
    'jiOJIjaiushdnrftb"\KJoanrftb"\',
    'nsiojIOJnu"hu9nasd8"\jiOJIjaiushd"\KJoa',
    'huaishdPUHAUShduiasu6d7nhqmpshejy0fZ9172387AUihausih6d83jb9y0qajusidhnjasnj'.repeat(40),
    'nrftb"\jiOJIjaiushdnrf6d9gmtb"\Kiusu8unrf8ajgshdnrf7tb"\KJoa'.repeat(40),
    'nsiojIOJnu"hu9na7d9\9qjgml1\sd8"\jiOJIjaius"hiushd"\Kd"\KJ'.repeat(40)
];

let allSame = true;
for(const STR of STRS){
  const resOld = OLD.test(STR);
  const resNew = NEW.test(STR);
  if( resOld !== resNew ) {
    allSame = false;
    console.log('Error on: ' + STR, {resOld, resNew}) 
  }
}
if(allSame){
  console.log('the new regex check the same things') 
}

Get width/height of pixels array in Uint8ClampedArray

I am using TypeScript on Deno. I am trying to use blurhash.

This is my code:

const response = await fetch(url);
if (!response.body) {
throw new Error("Body null");
}

const clamped = new Uint8ClampedArray(await response.arrayBuffer());
var blurhash: string = encode(clamped, width, height, 4, 4,);

where width and height is known beforehand. But I get this error:

Width and height must match the pixels array

I read this issue and it seems like the alpha channel is missing or something. The problem is, that all solutions are fixing it by using sharp with ensureAlpha(). But sharp is not running on Deno, so I can’t use it.

Does anyone know how I could fix this?

Data fetched in Client Component not showing in Nexjs 14 when deployed

I am using Nextjs 14 client component to fetch and render data from my headless wordpress cms, this works in my local environment, however, when I deployed the app on aws amplify. The data does not show. Please i would like to know why this is happening and to know a better oh handling this. Here is my code below.

'use client'

function Faqs() {
  const [data, setData] = useState([]);
  const [search, setSearch] = useState(null);
  const [searchResults, setSearchResults] = useState([]);
  const [activeState, setActiveState] = useState({ title: null, index: null });
  const [isSearchPerformed, setIsSearchPerformed] = useState(false);
  const [searchQuery, setSearchQuery] = useState("");
  const [searchWords, setSearchWords] = useState([]);

  const searchResultsRef = useRef(null);

  useEffect(() => {
    async function getFaqData() {
      let receivedData = await getFaqs();
      console.log(receivedData);

      const flattenData = receivedData.flatMap((edge) =>
        edge.node.cta.questionAndAnswer.map((qa) => ({
          id: `${edge.node.id}`,
          title: edge.node.title,
          question: qa.question,
          answer: qa.answer,
        }))
      );
      console.log(flattenData);
      const newSearch = new JsSearch.Search("id");
      newSearch.indexStrategy = new JsSearch.PrefixIndexStrategy();
      newSearch.sanitizer = new JsSearch.LowerCaseSanitizer();
      newSearch.searchIndex = new JsSearch.TfIdfSearchIndex("id");

      // Add indices and documents
      newSearch.addIndex("question");
      newSearch.addIndex("answer");
      newSearch.addDocuments(flattenData);

      // Update state with new search instance
      setSearch(newSearch);
      setData(receivedData);
    }
    getFaqData();
  }, []);

  useEffect(() => {
    setIsSearchPerformed(false);
  }, [searchQuery]);

  const performSearch = () => {
    setIsSearchPerformed(true);
    if (searchQuery === "") {
      setSearchResults([]);
      setIsSearchPerformed(false);
    } else {
      const words = searchQuery.trim().toLowerCase().split(/s+/);
      setSearchWords(words); // Update searchWords state

      let combinedResults = new Set();
      words.forEach((word) => {
        const results = search.search(word);
        results.forEach((result) => combinedResults.add(result));
      });

      setSearchResults(Array.from(combinedResults));

      if (searchResultsRef.current) {
        searchResultsRef.current.scrollIntoView({ behavior: "smooth" });
      }
    }
  };

  function highlightSearchTerm(text, searchWords) {
    let highlightedText = text;
    for (const word of searchWords) {
      if (word.trim() === "") continue;
      const escapedWord = word.replace(/[-/\^$*+?.()|[]{}]/g, "\$&");
      highlightedText = highlightedText.replace(
        new RegExp(escapedWord, "gi"),
        (match) => `<span class="highlight">${match}</span>`
      );
    }
    return DOMPurify.sanitize(highlightedText);
  }
  console.log(searchResults, "SEARCH RESULTS");
  console.log(data, "FAQ data");
  return (
    <>
      {" "}
      <Hero
        leftContent={
          <HeroLeftComponent
            data={data}
            onSearchChange={setSearchQuery}
            onSearch={performSearch}
          />
        }
        rightContent={""}
        leftColW={"1fr"}
        rightColW={"0.2fr"}
        minHeight={"60rem"}
        bgImg={faqsBg}
        bgPosition={"50% 20%"}
      />
      <Container>
        <CustomContainer>
          <Box sx={{ margin: "3rem 0" }}>
            <HomeIcon>
              <Link href={"/faqs"}>
                {" "}
                <Typography
                  variant="body1"
                  fontSize={{ mobile: "1.6rem", portraitTab: "1.4rem" }}
                  fontWeight={"500"}
                >
                  FAQs{" "}
                </Typography>
              </Link>
            </HomeIcon>
          </Box>
          <Box ref={searchResultsRef}>
            {searchQuery !== "" && isSearchPerformed ? (
              searchResults.length > 0 ? (
                searchResults.map((item) => {
                  const highlightedQuestion = highlightSearchTerm(
                    item.question,
                    searchWords
                  );
                  const highlightedAnswer = highlightSearchTerm(
                    item.answer,
                    searchWords
                  );
                  return (
                    <Box margin={"5rem 0"}>
                      <Typography
                        variant="h3"
                        fontSize={{ mobile: "2.8rem", portraitTab: "2.4rem" }}
                        className="color-primary-light"
                        fontWeight={"500"}
                        paddingBottom={"2rem"}
                      >
                        {item.title}
                      </Typography>
                      <Typography
                        variant="h5"
                        fontSize={{ mobile: "2.7rem", portraitTab: "1.8rem" }}
                        fontWeight={"600"}
                        textTransform={"capitalize"}
                        sx={{
                          cursor: "pointer",

                          "&:hover": {
                            color: "#3768b0",
                          },
                        }}
                        className={`text-midnight-blue ${openSans.className}`}
                        dangerouslySetInnerHTML={{
                          __html: highlightedQuestion,
                        }}
                      ></Typography>
                      <Typography
                        variant="h5"
                        fontSize={{ mobile: "1.9rem", portraitTab: "1.6rem" }}
                        fontWeight={"normal"}
                        lineHeight={"1.6"}
                        padding={"1rem 0"}
                        className={`text-midnight-blue ${openSans.className}`}
                        dangerouslySetInnerHTML={{
                          __html: highlightedAnswer,
                        }}
                      ></Typography>
                    </Box>
                  );
                })
              ) : (
                <Box
                  display={"flex"}
                  height={"40vh"}
                  justifyContent={"center"}
                  alignItems={"center"}
                  className="flex min-h-[20vh] items-center justify-center"
                >
                  <Typography
                    variant="h3"
                    fontSize={{ mobile: "2.8rem", portraitTab: "2.4rem" }}
                    className="color-primary-light"
                    fontWeight={"500"}
                    paddingBottom={"2rem"}
                  >
                    No question found
                  </Typography>
                </Box>
              )
            ) : (
              <AccordionWrapper data={data} />
            )}
          </Box>
        </CustomContainer>
      </Container>
    </>
  );
}

export default Faqs;

How to use Rangy with PDFjs text layer?

I’m using Rangy library to select text and apply highlight class on it, the problem is when is select a partial of text the rest become unselectable!

My highlight function:

  applyHighlight() {
   rangy.init()
   let selection = rangy.getSelection();
   if (selection.rangeCount > 0) {
   let highlighter = rangy.createHighlighter();
   highlighter.addClassApplier(rangy.createClassApplier('highlight-yellow'));
   highlighter.highlightSelection('highlight-yellow');
   rangy.getSelection().removeAllRanges();
}}

CSS class

 .highlight-yellow {
  margin: -1px !important;
  padding: 1px !important;
  background-color: rgb(252, 238, 124) !important;
  border-radius: 4px !important;
  opacity: 50%;
  cursor: pointer;}

A screenshots to describe the issue..

here is the highlighted spans
enter image description here

and this is what it looks like from the console
enter image description here

As you can see the “copies are not made or distributed” part is becomes unselectable and it goes out from the span scope.

How to perform this dynamic Find and replace in Javascript over user generated data?

I have an app that allows user to generate text with HTML code in the folowing format:

<h2>User generated Dynamic Data 1</h2>
    <h3>User generated text 1.1</h3>
    <h3>User generated text 1.2</h3>


<h2>User generated Dynamic Data 2</h2>
    <h3>User generated text 2.1</h3>
    <h3>User generated text 2.2</h3>
    <h3>User generated text 2.3</h3>
    
<h2>User generated Dynamic Data 3</h2>
    <h3>User generated text 3.1</h3>
    <h3>User generated text 3.2</h3>

This is how it looks like in a browser:

This is how it looks like in a browser

Is there any way to replace what user generated with the one below, using javascript?

<h2>User generated Dynamic Data 1 <button class="something" onclick="bubble_fn_add_headers({output1: 'User generated Dynamic Data 1', output2: 'User generated text 1.1nUser generated text 1.2'});">Save</button></h2>
    <h3>User generated text 1.1</h3>
    <h3>User generated text 1.2</h3>


<h2>User generated Dynamic Data 2 <button class="something" onclick="bubble_fn_add_headers({output1: 'User generated Dynamic Data 2', output2: 'User generated text 2.1nUser generated text 2.2nUser generated text 2.3'});">Save</button></h2>
    <h3>User generated text 2.1</h3>
    <h3>User generated text 2.2</h3>
    <h3>User generated text 2.3</h3>
    
    
<h2>User generated Dynamic Data 3 <button class="something" onclick="bubble_fn_add_headers({output1: 'User generated Dynamic Data 3', output2: 'User generated text 3.1nUser generated text 2.2'});">Save</button></h2>
    <h3>User generated text 3.1</h3>
    <h3>User generated text 3.2</h3>    

This is how the above would look like in a browser:

This is how the above would look like in a browser

The situation is very trickey because:

  • All the texts surrounded by <h2></h2> and <h3></h3> tags are user generated.
  • Users can generate any number of <h2> Texts followed by any or even zero number of <h3> texts.

Can you guys suggest any work around this using javascript?

Thanks

I would have tried

s.replace('<h2>', '<h2>User generated Dynamic Data 1 <button class="something" onclick="bubble_fn_add_headers({output1: 'User generated Dynamic Data 1', output2: 'User generated text 1.1nUser generated text 1.2'});">Save</button></h2>')

But it just isn’t possible because the texts are dynamically generated and are unique each time.

Cycling through iframes and minimising loading

I have a sequence of embedded excel iframes that I would like to cycle through. Each iframe must be refreshed to show the latest data, but this takes several seconds. I have tried to run this in the background by refreshing the iframes in the background and waiting to display them, but I am quite new to javascript. Will this script perform correctly?

<script>
// Array of iframe IDs
var iframes = ['iframe1', 'iframe2', 'iframe3', 'iframe4','iframe5','iframe6','iframe7'];
var currentIframeIndex = 0;

function reloadAndSwitchIframes() {
    var currentIframe = document.getElementById(iframes[currentIframeIndex]);
    var nextIframeIndex = (currentIframeIndex + 1) % iframes.length;
    var futureIframeIndex = (currentIframeIndex + 2) % iframes.length;

    var nextIframe = document.getElementById(iframes[nextIframeIndex]);
    var futureIframe = document.getElementById(iframes[futureIframeIndex]);

    futureIframe.src = futureIframe.src; 

    currentIframe.style.display = 'none';
    nextIframe.style.display = 'block';

    
    currentIframeIndex = nextIframeIndex;
}

// Call reloadAndSwitchIframes function when page loads
window.onload = function() {
    setInterval(reloadAndSwitchIframes, 20000);
};
</script>