How to get configuration value from pom.xml to ReactJS when springboot and Reactjs project build together

We have a backend springboot application along with reactjs frontend build together. Currently, the reactjs application is building successfully with the spring boot application.
However,we need to get the configuration value from the pom.xml(OR from application.yml) to the ReactJS project.
Is there anyone who has done these type of configuration reading from the frontend?

Following is part of the pox.xml file which has plugins section

<plugins> 
  <plugin>
        <groupId>com.github.eirslett</groupId>
        <artifactId>frontend-maven-plugin</artifactId>
        <version>${frontend-maven-plugin.version}</version>
        <configuration>
            <workingDirectory>src/main/resources/ui-resources</workingDirectory>
            <!--<nodeDownloadRoot>https://npm.taobao.org/mirrors/node/</nodeDownloadRoot>-->
            <nodeVersion>${node.version}</nodeVersion>
            <npmVersion>${npm.version}</npmVersion>
            <yarnVersion>${yarn.version}</yarnVersion>
            <installDirectory>target</installDirectory>
        </configuration>
        <executions>
            <execution>
                <id>install node and yarn</id>
                <goals>
                    <goal>install-node-and-yarn</goal>
                </goals>
                <phase>generate-resources</phase>
            </execution>
            <execution>
                <id>yarn install</id>
                <goals>
                    <goal>yarn</goal>
                </goals>
                <configuration>
                    <arguments>install --check-cache</arguments>
                </configuration>
            </execution>
            <execution>
                <id>yarn build</id>
                <goals>
                  <goal>yarn</goal>
                </goals>
                <configuration>
                    <arguments>build</arguments>
                </configuration>
            </execution>
        </executions>
    </plugin>
  <plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-resources-plugin</artifactId>
    <version>2.6</version>
    <executions>
      <execution>
        <id>copy-ui-resources</id>
        <phase>prepare-package</phase>
        <goals>
          <goal>copy-resources</goal>
        </goals>
        <configuration>
          <!--
          <outputDirectory>src/main/resources/static</outputDirectory>
          -->
          <outputDirectory>target/classes/static</outputDirectory>
          <resources>          
            <resource>
              <directory>${basedir}/src/main/resources/ui-resources/build</directory>
            </resource>
          </resources>              
        </configuration>            
      </execution>
    </executions>
  </plugin>
  <plugin> 
    <groupId>org.springframework.boot</groupId>  
    <artifactId>spring-boot-maven-plugin</artifactId>  
    <configuration> 
      <excludes> 
        <exclude> 
          <groupId>org.projectlombok</groupId>  
          <artifactId>lombok</artifactId> 
        </exclude> 
      </excludes> 
    </configuration> 
  </plugin>  

</plugins> 

Using OpenAI from broswer client

I’m following freecode camp tutorial on building a chatbot – https://www.freecodecamp.org/news/build-gpt-4-api-chatbot-turorial/

I tried to use their code as is, however is getting the error – Uncaught TypeError: Failed to resolve module specifier "openai". Relative references must start with either "/", "./", or "../".. I looked up some resources at https://platform.openai.com/docs/libraries#node-js-library it seems the usage in the code is similar as in freecode camp code – snippet below.

import { process } from '/env.js'
import { Configuration, OpenAIApi } from 'openai'

const configuration = new Configuration({
    apiKey: process.env.OPENAI_API_KEY
})

const openai = new OpenAIApi(configuration)

I need help on how I can modify freecode camp code if required to make it work. Unfortunately they haven’t given steps on how to launch the app.

How catch and mute “Cross-Origin-Opener-Policy policy would block the window.closed call” error

I’m opening a pop-up from a page (main page). I’m then checking constantly if the pop-up is still open or has been closed. I’m doing that with the code below

const checkForPopUp = async function() {
    try {
        while(!extFrame?.closed) {
            await new Promise(resolve => setTimeout(resolve, 250));
        }
        return true;
    }
    catch (error) {
        console.log(error);
    }
}

However, at some point the pop-up redirects to another domain so the browser throws the error Cross-Origin-Opener-Policy policy would block the window.closed call directly when checking if the pop-up is still open or not. The error is not caught by try/catch nor by window.onerror, nor by window.onunhandledrejection.

How can I catch this specific error and handle it differently so that it doesn’t print as an error?

ipcmain.handle parameter has metadata(?) instead of value

I am a beginner to electron and my app does nothing more than unpack a zip and start a .bat file (it’s an installer) i need the user to give a url to a database but when it returns i get in ipcMain: {"sender":{"_windowOpenHandler":null,"ipc":{"_events":{},"_eventsCount":1,"_invokeHandlers":{}},"_events":{"render-process-gone":[null,null]},"_eventsCount":13},"frameId":1,"processId":4}

main.js: (not entire file just handle)

    ipcMain.handle('run-start', async (database) => {
        console.log(`dbUrl in main.js:`, JSON.stringify(database), `Type:`, typeof database);
    const command = path.join(filePath, 'dist', 'setup.bat') + ' ' + database
    try {
        console.log(command)
        // const result = await new Promise((resolve, reject) => {
        //     exec(command, (error, stdout, stderr) => {
        //         if (error) {
        //             reject(`Error: ${stderr}`);
        //         } else {
        //             resolve(stdout);
        //         }
        //     });
        // });
        return result;
    } catch (error) {
        return error;
    }
})

preload.js (entire file):

const { contextBridge, ipcRenderer } = require('electron');

contextBridge.exposeInMainWorld('electron', {
    selectFolder: () => ipcRenderer.invoke('select-folder'),
    runInstall: (destDir) => ipcRenderer.invoke('run-install', destDir),
    runStart: (dbUrl) => {ipcRenderer.invoke('run-start', dbUrl); console.log(dbUrl)}
});

index.html (just the handler for the clicked btn):

        document.getElementById('startButton').addEventListener('click', async () => {
        console.log(dbUrl)
        await window.electron.runStart(dbUrl)
        alert('ClassyBooks is gestart!');
    });

everywhere the dbUrl is correct except in main.js

wait a function to finish

The general use case for waiting for a function to finish is to use async-await and Promise. But somehow I can’t get it to work.

I have a directive and in this directive I have a public function like this:

getCellValue(
    rowField: string,
    rowValue: any,
    columnField: string,
    gridData?: any[]
  ): any {
    setTimeout(() => {
      if (gridData) {
        return methods.getCellValuePrivate(
          rowField,
          rowValue,
          columnField,
          gridData
        );
      } else {
        return methods.getCellValuePrivate(
          rowField,
          rowValue,
          columnField,
          this.config.gridData
        );
      }
    });
  }

It gets a value from the provided gridData argument or from the this.config.gridData. I have to use setTimeout, because in the directive I do some data manipulating and with using setTimeout I ensure, that I get the right data.

Now, in a component, where I use this directive, I simply look for it like this:

  @ViewChild(EnhancedGridDirective) enhancedGridDirective!: EnhancedGridDirective;

And in ngAfterViewInit I call the beforementioned function, f. e.:

const val = this.enhancedGridDirective.getCellValue(
      'category',
      'cat 2',
      'feb'
    );
console.log(val);

Of course I get undefined in the console because of the setTimeout in the function.

But if I change the function like this:

async getCellValue(
    rowField: string,
    rowValue: any,
    columnField: string,
    gridData?: any[]
  ): Promise<any> {
    new Promise((resolve) => {
      setTimeout(() => {
        if (gridData) {
          resolve(
            methods.getCellValuePrivate(
              rowField,
              rowValue,
              columnField,
              gridData
            )
          );
        } else {
          resolve(
            methods.getCellValuePrivate(
              rowField,
              rowValue,
              columnField,
              this.config.gridData
            )
          );
        }
      });
    });
  }

And in the ngAfterViewInit then:

this.enhancedGridDirective
      .getCellValue('category', 'cat 2', 'feb')
      .then((v) => console.log(v));

I also get undefined.

So, how to solve this issue?

How to Prevent Arrow Rotation from Resetting When Switching Accordion Menus in JavaScript?

Beginner Learner

I’m working on an accordion menu that toggles the visibility of menu items and rotates an arrow icon to indicate the open/closed state. The JavaScript code works as expected in most cases, but I noticed an issue: when switching between accordion sections, the arrow rotation sometimes resets or behaves unexpectedly.

HTML Code

 <div class="accordion" onclick="accordian('section-1')">
                <div id="changemenu" class="accordian-text">Burger</div>
                <i class="down-arrow"></i>
            </div>
            <div class="menu-items" id="section-1">
                <div>
                    <input type="checkbox" name="sec-1" id="sc-1cb-1">
                    <label id="change1" for="sc-1cb-1">Cheese Burger</label>
                </div>
</div>
function accordian(disp) {
    var change = document.getElementById(disp); 
    var allsection = document.getElementsByClassName("menu-items");
    var allarrows = document.getElementsByClassName("down-arrow"); 

    for (let i = 0; i < allsection.length; i++) {
        allarrows[i].style.transform = "rotate(45deg)";
        allarrows[i].style.transition = "transform 100ms linear";
    }

    if (change.style.display === "block") {
        change.style.display = "none";
    } else {
        change.style.display = "block";
        var relatedAccordion = change.previousElementSibling;
        var arrow = relatedAccordion.querySelector(".down-arrow");
        arrow.style.transform = "rotate(225deg)";
        arrow.style.transition = "transform 100ms linear";
    }
}

this logic works but when i click quickly it auto updates or runs a bit slower….

JS deobfuscation with shift-ast

I am trying to convert some obfuscated js code using shift-ast.
I want to replace some CallExpressions with their string values.
So far I’ve been able to get the strings that I should use for the replacement in a stringArray by using the shift-refactor library.
I also have an array of all callExpressions names that I want to replace.
Here is a sample of the code:

function O(t, e) {
    var n = 392,
        r = 584,
        o = 407,
        i = 867,
        a = 392,
        c = 584,
        u = 867,
        s = 633,
        f = 985,
        l = 532,
        p = 392,
        h = 584,
        v = 631,
        d = 988,
        g = 1020,
        m = 677,
        y = I,
        b = Object[y(735)](t);
    if (Object[y(n) + y(r) + y(o) + y(i)]) {
        var w = Object[y(a) + y(c) + y(o) + y(u)](t);
        e && (w = w[y(s)]((function(e) {
            var n = y;
            return Object[n(p) + n(h) + n(v) + n(d)](t, e)[n(g) + n(m)];
        }))),
        b[y(f)][y(l)](b, w);
    }
    return b;
}

The stringArray I mentioned before is the variable I that is assigned to y and n in this sample code. I want to get the callExpressions y() and n().
I am struggling with how to ensure any replacements are in scope because the varaibleDeclarations use the same names. Finally I want to concatenate all strings that have the + sign.

I’ve tried to read up on shift-parser, shift-template and shift-scope but I can’t quite put it all together.
Please help me with this example so I can know how to handle it.

Muuri floating elements

In muuri.js, elements are affected by gravity by default and cannot be moved to any available space. How to allow elements to take up any free space and be unaffected by ‘gravity’?

Here’s an example of how it works in Gridstack.js; this is the
behaviour I want to achieve in muuri.js

Gridstack.js

Here’s how it works in muuri.js

muuri.js

Data Extraction for a Go Application from a JavaScript-Based Website

I’m working on an application to practice my skills, and the goal is to extract data from a website and make it available in an application written in Go. However, I’m running into some issues with the site.

The website I’m working with is https://projudi.tjgo.jus.br/BuscaProcesso. It seems to be entirely JavaScript-based, and when I inspect the traffic in the Network tab (XHR), I couldn’t find any requests returning JSON — only CSS and JavaScript files. I’ve considered working directly with the returned HTML, but there are some specific data and files that only appear after interacting with elements, like clicking on arrows or buttons.

I’d like to ask:

Is there any tool or technique you recommend to identify where this data might come from?
If there’s no clear endpoint for the data, what are the best practices for extracting information directly from the HTML, especially in cases where interaction with the site is required?
Thanks in advance for any tips or guidance!

Game grid/map display optimization ReactJs

I’m trying to display the map of a game using ReactJs.
The map is 100 tiles per 100 tiles so 10,000 in total like so:
map
Each tile can be colored with a custom color.

I built a store using mobx that holds the grid and the color of each tile and I’m basically looping through it to display the right color for each tiles.

Map.tsx:

const Map = observer(() => {
  const size = 100 * dashboardStore.zoom;
  const marginLeft = size * 0.75 + 2;
  const marginTop = size * 0.5 + 2;

  return (
    <div>
      <div className={styles.controls}>
        <Controls />
      </div>
      <div className={styles.map}>
        {dashboardStore.arrayY.map((_, yAxis) => (
          <div
            key={yAxis}
            className={styles.row}
            style={{
              width: `${(size + marginLeft + 2) * 100 + marginLeft}px`,
              height: `${size + 1}px`,
              marginLeft: yAxis % 2 ? `${marginLeft}px` : 0,
              marginTop: yAxis === 0 ? 0 : `-${marginTop}px`,
            }}
          >
            {dashboardStore.arrayX.map((_, xAxis) => {
              const index = yAxis * 100 + xAxis;
              return <Tile key={xAxis} index={index} color={dashboardStore.getTileColor(index)} />;
            })}
          </div>
        ))}
      </div>
    </div>
  );
});

Tile.tsx:

export type TileProps = {
  color?: string;
  index: number;
};

const Tile = observer(({ color, index }: TileProps) => {
  return (
    <div className={styles.container} onClick={() => dashboardStore.colorTile(index, dashboardStore.currentColor)}>
      <div className={styles.tileBorder} />
      <div className={styles.tile} style={{ backgroundColor: color }}>
        {dashboardStore.displayIndices ? index : ""}
      </div>
    </div>
  );
});

Everything works just fine, I’m rendering, the events trigger well, the colors display properly but I definitely have a performance issue. I can run the webpage on my MacBook Pro but it’s almost unusable on phone and and smaller devices (Basically on any devices since my laptop is quite high specs).

How can I optimize this so it can run on any device?

Thanks a lot.

How to setvalue of a textarea instant and call api after 2 second for efficiency

I’ve a textarea and I’d like to udpate text area text instantly as user enter text but I don’t like to hit api after every keystroke for obvious reason for efficiency.

I’ve tried to use debounce function but function is getting triggered as many times after every keystroke but with some delay that I’ve added in debounce

codesandbox link

export default function App() {
  const [text, setText] = useState("");

  function callAPI(value: string) {
    console.log(value);
    // CALL API HERE
  }

  const debouncedAPI = _.debounce(callAPI, 2000);

  function onChangeText(e) {
    const value = e.target.value;
    console.log(`value inside onChangeText: ${value}`);
    setText(value);
  }

  return (
    <div className="App">
      <textarea
        name="textarea"
        id=""
        value={text}
        onChange={(e) => {
          onChangeText(e); // Update the state
          debouncedAPI(e.target.value); // Call the debounced API with the latest value
        }}
      ></textarea>
    </div>
  );
}

The drilldown is not working after the first animation

I’ve created a drilldown chart to transact the graphs. The first configuration (from pie chart to bar chart) works. But from then on I couldn’t configure the gaugeOn function to make it work.

Code:

<head>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/echarts/5.5.0/echarts.min.js"></script>
</head>

<div class="chart"></div>

<style>
  .chart {
    width: 400px;
    height: 430px;
  }
</style>

<script>
  document.addEventListener("DOMContentLoaded", () => {
    const chartUse = echarts.init(document.getElementsByClassName("chart")[0])

    function chartSystem() {
      return {
        source: {
          first: [
            ["x", "y", "childs"],
            ["Cars", 49, "cars"],
            ["Bikes", 65, "bikes"],
            ["Engines", 23, "eng"],
          ],
        },
        drill: {
          bar: [
            ["x", "y", "groups", "childs"],
            ["Mazda", 100, "cars", "bra"],
            ["Mass.", 120, "cars", "bra"],
            ["Accura", 150, "cars", "bra"],
            ["Kaw.", 20, "bikes", "arg"],
            ["Honda", 50, "bikes", "arg"],
            ["Yamaha", 80, "bikes", "arg"],
            ["V8", 60, "eng", "ned"],
            ["V10", 120, "eng", "ned"],
            ["V12", 20, "eng", "ned"],
          ],
          gauge: [
            ["name", "value", "groups"],
            ["Joao", 100, "bra"],
            ["Maria", 120, "bra"],
            ["Carlos", 20, "arg"],
            ["Bruna", 50, "arg"],
            ["Fabricio", 120, "ned"],
            ["Giovana", 20, "ned"],
          ],
        },
      }
    }

    let pullDataset = []
    let pullData = []
    let pullDrillBar = []
    let pullDrillGauge = []

    function chartSend() {
      const dfInit = chartSystem()
      const sourceIndex = dfInit.source
      const drillName = dfInit.drill

      pullDataset = [
        {
          source: sourceIndex.first, // Acessa "first"
          sourceHeader: true,
        },
      ]

      // Todos os dados de drill
      pullDrillBar = drillName.bar

      pullDrillGauge = drillName.gauge
    }

    chartSend()

    function chartFrameSwitch0() {
      const series0 = {
        type: "pie",
        color: ["#008cba", "#ff7400", "#00ff00"],
        radius: ["80%", "60%"],
        padAngle: 4,
        animationDurationUpdate: 1000,
        universalTransition: {
          enabled: true,
          divideShape: "split",
        },
        itemStyle: {
          borderRadius: 10,
          borderWidth: 1,
          borderColor: "#242832",
        },
        datasetIndex: 0,
        encode: {
          itemName: 0,
          value: 1,
          itemChildGroupId: 2,
        },
      }

      const option = {
        dataset: [pullDataset[0]],
        series: [series0],
      }

      // Define o gráfico inicial
      chartUse.setOption(option, { notMerge: true })
    }

    chartFrameSwitch0()

    // Evento de clique no gráfico de pizza
    function barOn() {
      chartUse.on("click", (params) => {
        if (params.seriesType === "pie") {
          const filtered = pullDrillBar.filter((row) => {
            return row[2] === params.data[2]
          })

          if (filtered.length) {
            const preparedData = [...filtered]
            drillCarrierBar(preparedData) // Gera o gráfico com o cabeçalho incluído
          }
        }
      })
    }

    barOn()

    // Evento de clique no gráfico de gauge
    function gaugeOn() {
      chartUse.on("click", (params) => {
        if (params.seriesType === "gauge") {
        
          const filtered = pullDrillGauge.filter((row) => {
            return row[2] === params.data[2]
          })

          if (filtered.length) {
            const prepared = filtered.slice(1).map((row) => ({
              name: row[0],
              value: row[1],
              groupId: row[2],
            }))
            drillCarrierGauge(prepared)
          }
        }
      })
    }

    gaugeOn()

    function drillCarrierGauge(data) {
      const series0 = {
        type: "gauge",
        data: [...data],
        universalTransition: {
          enabled: true,
          divideShape: "split",
        },
      }

      const option = {
        series: [series0],
      }

      chartUse.setOption(option, { notMerge: true })
    }

    function drillCarrierBar(data) {
      const xAxis0 = {
        type: "category",
        axisLabel: {
          color: "#000",
          fontSize: 14,
        },
      }
      const yAxis0 = {
        type: "value",
      }

      const series0 = {
        type: "bar",
        datasetIndex: 0,
        encode: {
          x: 0,
          y: 1,
          itemGroupId: 2,
          itemChildGroupId: 3,
        },
        color: ["#008cba", "#ff7400", "#00ff00"],
        animationDurationUpdate: 1000,
        universalTransition: {
          enabled: true,
          divideShape: "split",
        },
      }

      const option = {
        dataset: [
          {
            source: [...data],
            sourceHeader: false,
          },
        ],
        xAxis: [xAxis0],
        yAxis: [yAxis0],
        series: [series0],
      }

      // Atualiza o gráfico com as barras
      chartUse.setOption(option, { notMerge: true })
    }
  })
</script>

I just need to adjust the structure below to make it work when there is no dataset resource, as is the case with type: 'gauge'.

    function gaugeOn() {
      chartUse.on("click", (params) => {
        if (params.seriesType === "gauge") {
        
          const filtered = pullDrillGauge.filter((row) => {
            return row[2] === params.data[2]
          })

          if (filtered.length) {
            const prepared = filtered.slice(1).map((row) => ({
              name: row[0],
              value: row[1],
              groupId: row[2],
            }))
            drillCarrierGauge(prepared)
          }
        }
      })
    }

What is equivalent of `JSX.IntrinsicElements`?

I have crafted a library for next.js themes. Recently, I found this error here.

The latest version of Typescript 5.7.2 complains – TS2503: Cannot find namespace 'JSX'. What is the equivalent of JSX.IntrinsicElements that can be used to set the type of HTML Tags in React components?

How to calculate the value of CSS property ‘transform: rotateY (α)’ through JavaScript?

Let’s assume there is a style like the following:

.main{
    margin: 0;
    padding: 0;
    box-sizing: border-box;
    display: flex;
    position: relative;
    height: 100vh;
    perspective: 1000px;
}
.page-L{
    position: relative;
    height: 100%;
    width: 30%;
    transform-origin: left;
    transform: rotateY(α);
}
.page-R{
    position: relative;
    margin: auto;
    height: 100%;
    width: 70%;
}

enter image description here

These two elements are children of “main”.

As you can see, you can clearly see that the element ‘page-L’ will undergo a deformation, and this will cause a visual change to its right side.

What should I do to obtain its changed value (height) through JavaScript and apply it to the element ‘page-R’?

Mobile pre-loader not centered in NextJS

I am facing issue understanding how mobile pre-loader works. So I have a pre-loader which is centered perfectly fine vertically and horizontally on Desktop screen. I can open up dev tools and see the same on all layouts it is perfectly centered and responsive.

Now the issue happens on my own phone. If I hit the url (My ip + port), the page loads and the pre-loader/text is not centered vertically but a bit to the bottom. If I touch the screen and interact with it then suddenly it comes into the centre. If I refresh the page then on first load it is centered. The issue only happens when I hit the url for the first time even a simple text won’t be centered no matter what style I apply.

It leads me to believe that I lack information on how mobile browser layout works and need some help understanding it.

I thought it might be an issue with my project but I created a fresh NextJS project.

This is my root page.js:

import Loading from “./components/Loading”;

export default function Home() {
  return (
    <Loading />
  );
}

And this is my Loading component:

import styles from "./Loading.module.css";

const Loading = () => {
  return (
    <div className={styles.landingLoadingDiv}>
      <p className={styles.loadingText}>NextJS</p>
    </div>
  );
};

export default Loading;

Loading.module.css:

.landingLoadingDiv {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    height: 100vh;
    width: 100%;
  }
  
  .loadingText {
    font-size: 2rem;
    font-weight: 600;
    margin: 0;
  }

I know styling is not an issue, this is something that I don’t understand with how mobile rendering is working.

Here is what it visually looks like:
https://imgur.com/a/8hQhEHD