How to build the “dist” in Node.js project

Here is the Leaflet Routing Machine:

https://github.com/perliedman/leaflet-routing-machine

The “main” in “package.json” is “./dist/leaflet-routing-machine.js“, but the real source file in the project is “src/index.js“.

Here is the “package.json”:
https://github.com/perliedman/leaflet-routing-machine/blob/master/package.json

{
  "name": "leaflet-routing-machine",
  "version": "3.2.12",
  "description": "Routing for Leaflet",
  "directories": {
    "example": "examples",
    "dist": "dist"
  },
  
  "main": "./dist/leaflet-routing-machine.js",
  
  "dependencies": {
    "@mapbox/corslite": "0.0.7",
    "@mapbox/polyline": "^0.2.0",
    "osrm-text-instructions": "^0.13.2"
  }
}

Here is the “src/index.js”:
https://github.com/perliedman/leaflet-routing-machine/blob/master/src/index.js

var L = require('leaflet'),
    Control = require('./control'),
    Itinerary = require('./itinerary'),

I’m creating my first node.js project, I think the “main” should be like this:

"main": "src/index.js"

What command is used to build the “./dist/leaflet-routing-machine.js” in the “Leaflet Routing Machine” project?

Why style property is not working in javascript

I am a beginner and I am learning JavaScript now. I am trying to make a javascript game. On this project, I am trying to add a style through javascript. On my project, there is a div named “Chick”. When user press any key the row and column will change for the chick. But the style is not working. The style is not added when I press key.

 const chick = document.querySelector('.chick');
let chickRow = 17;
let chickCol = 10;

document.addEventListener('keydown', (e) => {
    if ((e.key === "ArrowUp") && (chickRow > 0)) {
        chickRow -= 1;
    }
    if ((e.key === "ArrowDown") && (chickRow < rows)) {
        chickRow += 1;
    }
    if ((e.key === "ArrowLeft") && (chickCol > 0)) {
        chickCol -= 1;
    }
    if ((e.key === "ArrowRight") && (chickCol < columns)) {
        chickCol += 1;
    }

    chick.style.gridArea= `${chickRow} / ${chickCol}`;
});

how do i do a image display form

I want an image found referring to the person that was searched for (in the people table) to be presented in the html, but at the same time I want it so that if the user wants to change the photo, he just needs to click on it of the image already presented and then the file explorer is opened so that a new image can be chosen. Once the new image has been chosen, the new image must be displayed in the html in place of the old one temporarily.
the program is opening the file explorer, i choose the new image but the old image isn’t change and the new image isn’t displayed in any place of the html too
my code:

<script>

// Quando a imagem da pessoa for clicada
document.getElementById("imagem-pessoa").addEventListener('click', function() {
// Abrir o explorador de arquivos ao clicar no campo de arquivo oculto
document.getElementById("input-imagem").click();
});

// Quando uma nova imagem for selecionada
document.getElementById("input-imagem").addEventListener('change', function(event) {
// Capturar a nova imagem selecionada
const novaImagem = event.target.files[0];
// Atualizar temporariamente a imagem no HTML
const urlNovaImagem = URL.createObjectURL(novaImagem);
document.getElementById("imagem-pessoa").src = urlNovaImagem;
});
</script>

and the html

<img class="rectangle" id="imagem-pessoa" src="{{ pessoa.imagem.url }}" alt="Imagem da Pessoa">>
<input type="file" id="input-imagem" style="display: none;" accept="image/*">

it aren’t working

i tried a lot of things that chatgpt say a many of them make sense, but still don’t work.
what i expected is: “a person registration page is loaded, receiving a number that searches the database and returns a person from the database. It then fills in some elements on the screen with the data found in the database table about that person. Among the people model objects there is a model.ImageField that stores a photo of each person.” What I need is: I want the image found referring to the person that was searched for (in the people table) to be presented in the html, but at the same time I want it so that if the user wants to change the photo, he just needs to click on it of the image already presented and then the file explorer is opened so that a new image can be chosen. Once the new image has been chosen, the new image must be displayed in the html in place of the old one temporarily, but the replacement of the photo in the database must only be carried out after a submit button is clicked

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;