Javascript Node.js not working on saving a file

I need a help about my code. I get a field BytesBoleto in a Base64 encoded pdf. I need to filter them from a json and save the pdf files on user desktop. How can I do that? What´s wrong with my code?

I got the error; “The “data” argument must be of type string or an instance of Buffer, TypedArray, or DataView. Received an instance of File”

Here is my code:

// Função para decodificar Base64 e criar arquivos PDF
function gerarPDFsDeJson(jsonData) {
    // Verifica se jsonData é um objeto
    if (typeof jsonData !== 'object' || jsonData === null) {
        throw new Error("Entrada inválida: deve ser um objeto JSON.");
    }

    // Array para armazenar os arquivos PDF
    const pdfFiles = [];

    // Função recursiva para percorrer o JSON e encontrar os campos "BytesBoleto"
    function procurarBytesBoleto(obj) {
        for (const key in obj) {
            if (obj.hasOwnProperty(key)) {
                if (key === 'BytesBoleto' && typeof obj[key] === 'string') {
                    // Decodifica a string Base64
                    const byteCharacters = atob(obj[key]);
                    const byteNumbers = new Uint8Array(byteCharacters.length);
                    for (let i = 0; i < byteCharacters.length; i++) {
                        byteNumbers[i] = byteCharacters.charCodeAt(i);
                    }
                    const blob = new Blob([byteNumbers], { type: 'application/pdf' });
                    const pdfFile = new File([blob], `${key}.pdf`, { type: 'application/pdf' });
                    pdfFiles.push(pdfFile);
                } else if (typeof obj[key] === 'object') {
                    procurarBytesBoleto(obj[key]); // Chama a função recursivamente
                }
            }
        }
    }

    procurarBytesBoleto(jsonData);
    return pdfFiles;
}

// Function to save PDF files to desktop
function savePDFsToDesktop(buffers, keys) {
    const desktopPath = path.join(require('os').homedir(), 'Desktop'); // Get user's desktop path

    buffers.forEach((buffer, index) => {
        const filePath = path.join(desktopPath, `${keys[index]}.pdf`);
        fs.writeFile(filePath, buffer, (err) => {
            if (err) {
                console.error(`Error saving ${keys[index]}.pdf:`, err);
            } else {
                console.log(`Successfully saved ${keys[index]}.pdf to ${desktopPath}`);
            }
        });
    });
}

// Function to save files
const fs = require('fs');
const path = require('path');
// Assuming you have an array of Buffer data and keys for the PDF files
const keys = ['file1', 'file2']; // Corresponding keys for file names

// Exemplo de uso
const jsonExample = {
    documentos: [
        { BytesBoleto: "JVBERi0xLjQKJeLjz9MKNCAwIG9iaiA8PC9Qcm9jU2V0IDggMCBSIC9FbmNvZGluZyA8PC9MZW5ndGggNjY1ID4+PgplbmRvYmoK" },
        { BytesBoleto: "JVBERi0xLjQKJeLjz9MKNCAwIG9iaiA8PC9Qcm9jU2V0IDggMCBSIC9FbmNvZGluZyA8PC9MZW5ndGggNjY1ID4+PgplbmRvYmoK" },
    ]
};

const pdfFilesArray = gerarPDFsDeJson(jsonExample);
console.log(pdfFilesArray); // Aqui você terá um array de arquivos PDF

// Call the function to save the PDFs
savePDFsToDesktop(pdfFilesArray, keys);

Thanks for the help

How To Build An Object or Array With Unique Key Names From Unique Array Object Values With All Array Items With Said Unique Key Name [duplicate]

I would like to produce an array (plus, separately, an object, if possible) from the unique ‘custRef’ values in the following array:

[
  {
    "id": 1233,
    "custRef": "ABC1234",
    "somethingElse": 10.0,
    "someRef": "37856394943222"
  },
  {
    "id": 1234,
    "custRef": "ABC1235",
    "somethingElse": 11.0,
    "someRef": "37856394943222"
  },
  {
    "id": 1235,
    "custRef": "ABC1235",
    "somethingElse": 13.0,
    "someRef": "3498537945734567"
  }
]

Preferred results:

I would like to produce this array:

[
  {
    "custRef": "ABC1234",
    "items": [
      {
        "id": 1233,
        "custRef": "ABC1234",
        "somethingElse": 10.0,
        "someRef": "37856394943222"
      }
    ]
  },
  {
    "custRef": "ABC1235",
    "items": [
      {
        "id": 1234,
        "custRef": "ABC1235",
        "somethingElse": 11.0,
        "someRef": "37856394943222"
      },
      {
        "id": 1235,
        "custRef": "ABC1235",
        "somethingElse": 13.0,
        "someRef": "3498537945734567"
      }
    ]
  }
]

… and additionally, if possible, this object:

{
  "ABC1234": [
    {
      "id": 1233,
      "custRef": "ABC1234",
      "somethingElse": 10.0,
      "someRef": "37856394943222"
    }
  ],
  "ABC1235": [
    {
      "id": 1234,
      "custRef": "ABC1235",
      "somethingElse": 11.0,
      "someRef": "37856394943222"
    },
    {
      "id": 1235,
      "custRef": "ABC1235",
      "somethingElse": 13.0,
      "someRef": "3498537945734567"
    }
  ]
}

I assume that this would be some kind of combination of .filter() and .map (or maybe .reduce()) but I don’t really know what I’m doing, and so don’t really know what I am supposed to be looking for.

Assuming that I plop the above source array into a variable named ‘orderItems‘ I have managed to produce a simple array of the unique ‘custRef‘ values, with the below javascript. However, I’m failing to find a way use that effectively … or knowing if I should be using it at all?

var uniqueOrdersWtItms = Object.keys(orderItems.reduce((r,{oh_cust_order_ref}) => (r[oh_cust_order_ref]='', r) , {}));

Like I say, I can’t stress this enough, I don’t really know what I need to look for, so whilst I have tried to build this through any number of search results both here and elsewhere … it’s hard to know what to ask for. If anyone can help, that’d be amazing.

stackoverflow’s suggestion gave this answer:
Creating new array with unique key while mapping through given array
But it doesn’t seem to do what I want, or I cannot understand it well enough. 🙁

How to use getStaticProps in app/ Page component

I think that Page.tsx belongs to app/.

In src/app/Page.tsx, the MRE:

export default function Home({ images: { poze } }: {
  images: {
    poze: string;
  }
}) {
  return poze;
};

export const revalidate = 60;
export const dynamicParams = true;

export const getStaticProps = async () => {
  return {
    props: {
      images: {
        poze: "abc",
      }
    },
  };
};

Expected: “abc” is displayed.

Error:

./src/app/page.tsx
Error:   × "getStaticProps" is not supported in app/. Read more: https://nextjs.org/docs/app/building-your-application/data-fetching
  │ 
  │ 
    ╭─[/home/silviub/Desktop/Pro/home-gh-pages/src/app/page.tsx:12:1]
  9 │ export const revalidate = 60;
 10 │ export const dynamicParams = true;
 11 │ 
 12 │ export const getStaticProps = async () => {
    ·              ──────────────
 13 │   return {
 14 │     props: {
 15 │       images: {
    ╰────

The link in the error did not help. The original relevant SSG source is here.

Populating elements live when events happen not happening

I have the following template with two dropdowns. When an item is selected in the first dropdown it dynamically populates the second. It works, but not how I would expect. It takes a couple selections for the second select to populate.

<select class="select input input-bordered" (change)="onStudentChange($event)" >
        <option disabled selected value="0">Choose Student</option>
        <option *ngFor="let student of studentsByUser$ | async" value="{{student._id}}">{{ student.name }}</option>
      </select>
      <select *ngIf="selectedStudentId != ''" class="select input input-bordered" (change)="onMonthChange($event)" >
        <option disabled selected>Choose Month</option>
        <option *ngFor="let month of months" value="{{month}}">{{month}}</option>
      </select>

Here is the event:

onStudentChange(event: any): void {
    this.selectedStudentId = event.target.value;
    // Get the available months with published meals for selected student
    this.studentsByUser$.subscribe((students) => {
      const selectedStudent = students.find((student) => student._id === this.selectedStudentId);
      this.mealService.getMealsBySchool(selectedStudent?.school?._id!).subscribe((meals) => {
        const months: string[] = [];
        meals.map(meal => meal.date).map((dateString) => {
          months.push(new Date(dateString).getFullYear() + '-' + new Date(dateString).getMonth());
        })
        this.months = months
      });

    });
  }

this.months is getting the current values on debugging, but not reflected in the UI until the event is called again

Regex – get comma if it does not have an escaped quote at some point in front of it

I’m struggling with a regex expression. I have a string like this:

700,"some text, and more text",False,0000000000,text,"806,474.72"

And I need to split it into fields by commas, unless the comma is preceded by an escaped quote. The desired output is:

[0] 700
[1] Some text, and more text
[2] False
[3] 0000000000
[4] text
[5] 806,474.72

What would be the right Regex expression for this?

Request header field content-type is not allowed by Access-Control-Allow-Headers in preflight response, with chrome extension

enter image description here

I’m working on a chrome devtools panels extension. In it I have:

const toDbBtn = document.getElementById("toDbBtn");

toDbBtn.addEventListener("click", async () => {
  const dbName = document.getElementById("textBox").value;

  // const result = await chrome.storage.local.get(["yourKey"]);

  const storedJSON = await chrome.storage.local.get(["yourKey"]);
  console.log("Result from storage:", storedJSON);

  if (storedJSON.yourKey) {

    const parsedArray = JSON.parse(storedJSON.yourKey);
    console.log("Parsed Array:", parsedArray);
    const partArray = parsedArray.slice(0, 30);
    console.log("partArray", partArray);
    const data = {
      dbName: dbName,
      savedArray: partArray,
    };

    const postable = JSON.stringify(data);
    console.log("postable", postable);
    // http://localhost:8888/.netlify/functions//updateCollection.js

    const response = await fetch(
      "http://localhost:8888/.netlify/functions/updateCollection",
      {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          // "Access-Control-Allow-Origin": "*",
          // "Access-Control-Allow-Methods": "POST",
          // "Access-Control-Allow-Headers": "Content-Type",
        },
        body: postable,
      }
    );

    const result = await response.json();
    console.log("Response from server:", result);
  } else {
    console.log("Value not found in storage for key: yourKey");
  }
});

I’m planning to send some data to a netlify function, and so decided to test locally using “NTL DEV” command.

my target function is:

const headers = {
  "Cache-Control": "no-cache",
  "Cross-Origin-Opener-Policy": "unsafe-none",
  "Cross-Origin-Embedder-Policy": "unsafe-none",
  "Access-Control-Allow-Origin": "*",
  "Access-Control-Allow-Private-Network": "true",
  "Access-Control-Allow-Headers": "Access-Control-Request-Private-Network",
  "Access-Control-Allow-Methods": "OPTIONS,POST,GET,HEAD,QUERY,query",
};

exports.handler = async function (event, context) {

  console.log("context: ", context);
  console.log("event: ", event);

  if (event.httpMethod !== "OPTIONS" && event.httpMethod !== "POST") {
    console.log("event.httpMethod: ", event.httpMethod);
    return {
      statusCode: 405,
      body: JSON.stringify({ message: "Method Not Allowed" }),
    };
  } else if (event.httpMethod === "OPTIONS") {
    return {
      statusCode: 204,
      headers: headers,
      body: null,
    };
    
  } 
  if (event.httpMethod === "POST") {
    console.log("event.httpMethod: ", event.httpMethod);
    console.log("event.body: ", event.body);
    const data = JSON.parse(event.body);
    console.log("data: ", data);
  }

I’m getting the error in the title .What am I doing wrong?

How do I optimize my code for Climbing the Leaderboard on Hackerrank using JavaScript? [closed]

I used a Binary Search implementation and caching to try to solve the problem, but I still can’t pass two test cases: 6 and 8. Any help on what I should do next would greatly be appreciated.

My code is as follows:

function climbingLeaderboard(ranked, player) {
    // Write your code here
    
    ranked = [...new Set(ranked)]
    
    let cache = {};
    
    
    let finalRank = player.map((p) => {
        
        let first = 0;
        let last = ranked.length - 1;
        
        if (cache[p]) {
            return cache[p];
        }
        
        
        
        while (first <= last) {
            let mid = first + Math.floor((last - first)/2);
            console.log("Made It!")
            
            console.log(`mid: ${mid}, p: ${p}`)
            
            if (ranked[mid] == p) {
                cache[p] = mid + 1;
                return mid + 1;
            }else if (ranked[mid] < p) {
                last = mid - 1;
            }else {
                first = mid + 1;
            }
        }
        
        cache[p] = first + 1;
        return first + 1;
    });
    
    return finalRank;

}

For reference, I previously tried turning the map function into a for loop but that made me fail all my tests, so I reverted back to the map function.

How to use useState without “use client” in Next.js when I use generateStaticParams

I need this in an SSG to send to photo galleries the image files’ dimensions. I expected no error.

Error of “npm run dev”:

21:23:44 ~/Desktop/Pro/home-gh-pages main $ npm run dev

> home-gh-pages@0.1.0 dev
> next dev

   ▲ Next.js 15.2.5
   - Local:        http://localhost:3000
   - Network:      http://192.168.1.100:3000

 ✓ Starting...
 ✓ Ready in 1593ms
 ○ Compiling / ...
 ⨯ ./src/app/page.tsx
Error:   × You're importing a component that needs `useState`. This React hook only works in a client component. To fix, mark the file (or its parent) with the `"use client"` directive.
  │ 
  │  Learn more: https://nextjs.org/docs/app/api-reference/directives/use-client
  │ 
  │ 
    ╭─[/home/silviub/Desktop/Pro/home-gh-pages/src/app/page.tsx:14:1]
 11 │ import Thumbnails from "yet-another-react-lightbox/plugins/thumbnails";
 12 │ import Zoom from "yet-another-react-lightbox/plugins/zoom";
 13 │ import "yet-another-react-lightbox/plugins/thumbnails.css";
 14 │ import { useState } from "react";
    ·          ────────
 15 │ 
 16 │ import LiteYouTubeEmbed from 'react-lite-youtube-embed';
 17 │ import 'react-lite-youtube-embed/dist/LiteYouTubeEmbed.css';
    ╰────

Import trace for requested module:
./src/app/page.tsx
 ⨯ ./src/app/page.tsx
Error:   × You're importing a component that needs `useState`. This React hook only works in a client component. To fix, mark the file (or its parent) with the `"use client"` directive.
  │ 
  │  Learn more: https://nextjs.org/docs/app/api-reference/directives/use-client
  │ 
  │ 
    ╭─[/home/silviub/Desktop/Pro/home-gh-pages/src/app/page.tsx:14:1]
 11 │ import Thumbnails from "yet-another-react-lightbox/plugins/thumbnails";
 12 │ import Zoom from "yet-another-react-lightbox/plugins/zoom";
 13 │ import "yet-another-react-lightbox/plugins/thumbnails.css";
 14 │ import { useState } from "react";
    ·          ────────
 15 │ 
 16 │ import LiteYouTubeEmbed from 'react-lite-youtube-embed';
 17 │ import 'react-lite-youtube-embed/dist/LiteYouTubeEmbed.css';
    ╰────

Import trace for requested module:
./src/app/page.tsx
 ⨯ ./src/app/page.tsx
Error:   × You're importing a component that needs `useState`. This React hook only works in a client component. To fix, mark the file (or its parent) with the `"use client"` directive.
  │ 
  │  Learn more: https://nextjs.org/docs/app/api-reference/directives/use-client
  │ 
  │ 
    ╭─[/home/silviub/Desktop/Pro/home-gh-pages/src/app/page.tsx:14:1]
 11 │ import Thumbnails from "yet-another-react-lightbox/plugins/thumbnails";
 12 │ import Zoom from "yet-another-react-lightbox/plugins/zoom";
 13 │ import "yet-another-react-lightbox/plugins/thumbnails.css";
 14 │ import { useState } from "react";
    ·          ────────
 15 │ 
 16 │ import LiteYouTubeEmbed from 'react-lite-youtube-embed';
 17 │ import 'react-lite-youtube-embed/dist/LiteYouTubeEmbed.css';
    ╰────

Import trace for requested module:
./src/app/page.tsx
 ⨯ ./src/app/page.tsx
Error:   × You're importing a component that needs `useState`. This React hook only works in a client component. To fix, mark the file (or its parent) with the `"use client"` directive.
  │ 
  │  Learn more: https://nextjs.org/docs/app/api-reference/directives/use-client
  │ 
  │ 
    ╭─[/home/silviub/Desktop/Pro/home-gh-pages/src/app/page.tsx:14:1]
 11 │ import Thumbnails from "yet-another-react-lightbox/plugins/thumbnails";
 12 │ import Zoom from "yet-another-react-lightbox/plugins/zoom";
 13 │ import "yet-another-react-lightbox/plugins/thumbnails.css";
 14 │ import { useState } from "react";
    ·          ────────
 15 │ 
 16 │ import LiteYouTubeEmbed from 'react-lite-youtube-embed';
 17 │ import 'react-lite-youtube-embed/dist/LiteYouTubeEmbed.css';
    ╰────

Import trace for requested module:
./src/app/page.tsx
 GET / 500 in 326ms

If I use “use client” page.tsx (tested from new index.tsx too) I get error:

21:33:49 ~/Desktop/Pro/home-gh-pages main $ npm run dev

> home-gh-pages@0.1.0 dev
> next dev

   ▲ Next.js 15.2.5
   - Local:        http://localhost:3000
   - Network:      http://192.168.1.100:3000

 ✓ Starting...
 ✓ Ready in 1627ms
 ○ Compiling /_not-found ...
 ✓ Compiled /_not-found in 1323ms (660 modules)
 ⚠ Fast Refresh had to perform a full reload due to a runtime error.
 GET /_next/static/webpack/93bd01d6b78ae12e.webpack.hot-update.json 404 in 1595ms
 ⨯ [Error: Page "/page" cannot use both "use client" and export function "generateStaticParams()".]
 ○ Compiling /_error ...
 ✓ Compiled /_error in 788ms (989 modules)
 GET / 500 in 1194ms

Minimum, reproducible example: page.tsx:

"use client";

import { useState } from "react";

export default function Home() {
  const [x, setX] = useState(-1);
  return <p onClick={() => {
    setX(x + 1);
  }}>{x}</p>;
}

export const revalidate = 60;
export const dynamicParams = true;

export const generateStaticParams = async () => {
  return { data: 100 };
};

Throws Error: Page "/page" cannot use both "use client" and export function "generateStaticParams()".

how can i remove percentage from vue url

how do i remove the % from my url

this what my url returns

http://localhost:8080/product/We-Vibe%2520Sync%2520O%2520Remote%2520and%2520App%2520Controlled%2520Rechargeable%2520latern's

when i click this

   goToProduct(productTitle) {
      console.log("Product Title:", productTitle);
      this.$router.push({
        name: "ProductDetails",
        params: { title: productTitle }, // Pass raw title directly to URL
      });
    },

this how i get the data

    try {
      const productTitle = this.$route.params.title;
      const response = await axios.get(
        `https://ve.onrender.com/api/products/${encodeURIComponent(
          productTitle
        )}`
      );

      this.product = response.data.product || {};
    } catch (error) {
     
    }

this how the backend meant to get the data We-Vibe Sync O Remote and App Controlled Rechargeable latern's

so how do i remove the % from the url without altering the data sent to the backend

Criação de library em react [closed]

Oi, estou com uma dúvida, no meu trabalho eu preciso fazer uma lib em react, que vai consumir relatório, e devolver um dashboard, eu tenho uma api em node.js que gera relatórios com base no aggregate então eu envio um post no insomnia com o header com as labels e nome de cada coluna que transforma em base64 pra formar um pdf ou xls, daí estava precisando fazer uma lib pra consumir eles e transformar em dashboards, no caso é a empresa que eu trabalho que precisa, eles já possuem o front end deles em react.js, só que não possuem os dashboards, então eu precisaria criar essa lib que consome uma api, que recebe um endpoint post, com o headers no body do json aí sim geraria o relatório em base 64, um exemplo de um post que eu faco no json do body na porta post http://localhost:5000/report/:report, eu acho que a lib não precisa enviar um post, mas receber o json desse body do post, mesmo que eu tenha que colocar manualmente, pois eu possuo mais de um relatório e dependendo o json desse body muda, em vez de colocar um json, a minha api de relatório gera um código em base64, que seria o relatório, será que teria como pegar essa base64 e transformar num dashboard?

How to animate Table display: none / block? [duplicate]

CodePen: https://codepen.io/C3ISR-Everything-Cybersecurity/pen/azbeOEK

what I’m trying to do is to have a little bit of animation or transition reveal when the user clicks on the accordion to display the table, full code below HTML CSS JS, I want to animate the open and close transition of the tables under accordion.

Full Code:

HTML:

            var acc = document.getElementsByClassName("accordion");
            var i;

            for (i = 0; i < acc.length; i++) {
                acc[i].addEventListener("click", function() {
                    this.classList.toggle("active");
                    var panel = this.nextElementSibling;
                    if (panel.style.display === "block") {
                        panel.style.display = "none";
                    } else {
                        panel.style.display = "block";
                    }
                });
            }
       body {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            background-color: White;
            font-family: Sakkal Majalla;
            direction: rtl;
            position: relative;
            z-index: -2;
            -ms-overflow-style: none;
            
        }
        body::-webkit-scrollbar, body::-webkit-scrollbar-button { display: none; } /* Chrome */


        li {
            list-style: none;
        }

        a {
            text-decoration: none;
        }

        .main{    
            display: grid;
            grid-template-columns: 1fr;
            justify-items: center;
            margin-top: 2rem;
            margin-bottom: 1rem;
        }

        table {
            border: 1px solid #dededf;  
            table-layout: fixed;
            border-collapse: collapse;
            border-spacing: 1px;
            text-align: center;
        }

        th {
            border: 1px solid #dededf;
            background-color: #eceff1;
            color: #000000;
            padding: 5px;
        }

        td {
            border: 1px solid #dededf;
            background-color: #ffffff;
            color: #000000;
            padding: 5px;  
        }
        th:nth-child(1) {  
            width: 30.9rem;
        }

        th:nth-child(2) {  
            width: 10rem;
        }
        th:nth-child(3) {  
            width: 7rem;
        }

        .accordion {
            background-color: #ffffff;
            color: black;
            font-weight: bold;
            cursor: pointer;
            margin-top: 20px;
            padding: 18px;
            border: none;
            text-align: right;
            outline: none;
            font-size: 20px;
            transition: 0.4s;
            width: 50rem;
            border: 1px solid rgb(219, 219, 219);
            border-radius: 8px;
            box-shadow: rgba(100, 100, 111, 0.123) 0px 7px 29px 0px;
        }

        .active, .accordion:hover {
            border-radius: 8px 8px 0px 0px;
            border-color:  rgb(0, 128, 255);
        }

        .accordion span{
            float: left;
            font-size: 15px;
            color: #116ce4;
        }

        .panel {
            display: none;
            overflow: hidden;  
        }
   <div class="main">
            <button class="accordion">
                John Doe
            </button>
            <div class="panel">
                <table>
                    <th>company</th>
                    <th>department</th>
                    <th>2025?</th>
                    <tr>
                        <td>COMPANY A</td>
                        <td>FINANCE</td>
                        <td>&#9989;</td>
                    </tr>
                    <tr>
                        <td>COMPANY Z</td>
                        <td>PMO</td>
                        <td>&#10060;</td>
                    </tr>
                </table>
            </div>
                 <button class="accordion">
                John Doe
            </button>
            <div class="panel">
                <table>
                    <th>company</th>
                    <th>department</th>
                    <th>2025?</th>
                    <tr>
                         <td>company A</td>
                        <td>HR</td>
                        <td>&#10060;</td>
                    </tr>
                    <tr>
                       <td>company B</td>
                        <td>HR</td>
                        <td>&#10060;</td>
                    </tr>
                    <tr>
                          <td>company C</td>
                        <td>HR</td>
                        <td>&#10060;</td>
                    </tr>
                </table>
            </div>
                 <button class="accordion">
                John Doe
            </button>
            <div class="panel">
                <table>
                    <th>company</th>
                    <th>department</th>
                     <th>2025?</th>
                    <tr>
                        <td>company A</td>
                        <td>HR</td>
                        <td>&#9989;</td>
                    </tr>
                </table>
            </div>       
    </div>

Need Help Running a Command in Minecraft Bedrock’s 2.0.0-beta Scripting API

The Issue
I’m trying to learn Bedrock’s scripting API so that I can use it to make a minigame. To do this, I’d really like to run commands, as that is the easiest way to get a lot of stuff done.

What I’ve tried and why I’m here
I’ve tried a number of ways to get this to work. This is the main.js I’m currently working with:

"use strict";

import { world, system } from "@minecraft/server";

world.beforeEvents.chatSend.subscribe((event) => {
    event.cancel = true;
    let player = event.sender;
    player.sendMessage('say hello');
    player.runCommand("say hello");
});

This is a very simple program, but it shows the innate problem. When running it, this is the output:An error message showing player.runCommand does not work

After a bit of research, the issue here is simple. Entity.runCommand does not have the required permissions because it cannot be run in read-only mode.
The runCommand description on the microsoft docs

Showing it says read only mode
This is because server.world is read-only:
World description from the site
This ultimately means that I’m at a loss for how I’m supposed to do this. Even the Bedrock Fan Wiki doesn’t work (the code doesn’t run, as runCommandAsync does not exist).

I’m running on server 2.0.0-beta, so that’s not the issue either.

"dependencies": [
    {
        "module_name": "@minecraft/server",
        "version": "2.0.0-beta"
    },
    {
        "module_name": "@minecraft/server-ui",
        "version": "2.0.0-beta"
    }
]

I could use world.afterEvents, as that is read-write, but I was hoping to be able to cancel a chat message and run a command to do something based on it, which ChatSendAfterEvent cannot do. Any help, or work around, would be appreciated.

Scrollview in react-native jumps when clicking content, if useAnimatedStyle is used in parent pages

I recently implemented a DraggableListView for my React-Native app.

The MovableListViewItem use a animatedStyle from react-native-reanimated.
Now on the page where is use this DraggableListView I navigate via router.push() to a different page.
On the second page there is a normal ScrollView. Now when the content of the ScrollView is longer than the screen I scroll to the bottom to see the last item. Now when I click on any item in the ScrollView it jumps up, about the size of the header of the page.

So now when I either:

  • disable the header for the page
  • use router.replace() instead of router.push() on page one
  • remove the animated styles in the MovableListViewItem
  • only render the DraggableListView when isFocused of useIsFocused() is set

the ScrollView in page 2 doesn’t jump anymore.

Why is the Animated.ScrollView in a different page affecting a ScrollView on another page?

Versions:

  • “expo”: “~52.0.36”,
  • “expo-router”: “~4.0.17”
  • “react-native”: “0.76.7”
  • “react-native-reanimated”: “~3.16.1”

Page1:

    <Animated.ScrollView
      removeClippedSubviews={true}
      style={[{
        flex: 1
      }, style
      ]}
      contentContainerStyle={{
        height: data.length * (height + (gap ?? 0)),
      }}
    >
      {data.map((item, idx) =>
        <MovableListItem
          key={keyExtractor(item)}
          itemKey={keyExtractor(item)}
          itemCnt={data.length}
          positionDict={positionDict}
          height={height + (gap ?? 0)}
          gap={gap ?? 0}
          onDragRelease={() => handleReorder(positionDict.get())}
          renderItem={itemRenderer(item, idx)}
          onPress={onItemPress !== undefined ? (() => onItemPress(item)) : undefined}
        />
      )}
    </Animated.ScrollView>

MovableListItem:

      <Animated.View style={{ ...animatedStyle, shadowOffset: { height: 0, width: 0 } }}>
        <TouchableOpacity
          disabled={onPress === undefined}
          onPress={onPress}
          style={{ flex: 1 }}
        >
          <View style={styles.exerciseCard}>
            <View
              style={{
                flexDirection: 'row',
                alignItems: 'center',
                alignSelf: 'stretch',
                flex: 1,
                justifyContent: 'space-between'
              }}>
              {renderItem}
              <GestureDetector
                gesture={panGesture}
              >
                <View collapsable={false}>
                  <Ionicons size={24} name="menu-outline" color={theme.text} />
                </View>
              </GestureDetector>
            </View>
          </View>
        </TouchableOpacity>
      </Animated.View>

the animatedStyle is used to set the absolute top position of the element.