Is it required to have the same folder structure as the Package Name in react-native android

I have seen in many react native projects MainActivity.kt file is located at the same path as the package name of app.

If the package name is “com.example.app” then MainActivity.kt file is placed at android/app/src/main/java/com/example/app/MainActivity.kt

and in some projects it is located at android/app/src/main/java/com/appName/MainActivity.kt and package name is different like com.androidexample.appname.

so if I would need to change package name then is it required to change the folder name also ?

Problem escaping string inside JSON-LD with Google Tag Manager

To retrieve the description string from the meta tag:

<meta name="description" content="Impara a creare dati strutturati senza l'uso di plugin">

I use the following JavaScript function:

function() {
     var metaElement = document.querySelector('meta[name="description"]');
    return metaElement ? metaElement.getAttribute('content') : '';
}

Next, I will inject the variable previously saved in a Google Tag Manager trigger into the JSON-LD structured data:

<script type="application/ld+json">
    {
        "@context": "http://schema.org",
        "@type": "BlogPosting",
        "description": "{{MetaDescription blogposting}}"
    }
</script>

However, when the string is injected, this problem occurs:

"description": "Impara a creare dati strutturati senza lx27uso di plugin"

How can I solve this problem, because the data is modified for some reason by something when it is injected into the json-ltd

Prime Vue | Color Picker | When I connect the input with a label it double toggles the open

Hi all I am connecting the colorpicker input to a label via the inputId and when I want to toggle a open it works but when I want to click again to close it opens it again. See video.

Any ideas why this is happening?


<ColorPicker appendTo="self" inputId="123" />
                <label for="123" >
                    <svg v-if="showColorPicker" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor" aria-hidden="true" data-slot="icon" class="h-6 w-6 text-neutral-500">
                        <path fill-rule="evenodd" d="M9.47 6.47a.75.75 0 0 1 1.06 0l4.25 4.25a.75.75 0 1 1-1.06 1.06L10 8.06l-3.72 3.72a.75.75 0 0 1-1.06-1.06l4.25-4.25Z" clip-rule="evenodd"></path>
                    </svg>
                    <svg v-else-if="!showColorPicker" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor" aria-hidden="true" data-slot="icon" class="h-6 w-6 text-neutral-500">
                        <path fill-rule="evenodd" d="M5.22 8.22a.75.75 0 0 1 1.06 0L10 11.94l3.72-3.72a.75.75 0 1 1 1.06 1.06l-4.25 4.25a.75.75 0 0 1-1.06 0L5.22 9.28a.75.75 0 0 1 0-1.06Z" clip-rule="evenodd"></path>
                    </svg>
                </label>

enter image description here

I tried to connect the colorpicker id with a label tag to open and close the overlay. Did not work.

Event listener adds to playerOne even after the turn switches to playerTwo in a tic tac toe game

The turn does switch, and the new picked spot is added to the playerTwo array, but it is also added to playerOne. I’ve moved pieces of the code around but that does not fix it.

const gameBoard = (() => {
    const board = ['topLeft', 'topMiddle', 'topRight',
        'middleLeft', 'middle', 'middleRight',
        'bottomLeft', 'bottomMiddle', 'bottomRight'
    ];

    return board
})();

// gameBoard[0] returns 'topLeft', gameBoard[1] returns topMiddle, and so on...

const createPlayer = (name, marker) => {
    let score = 0;
    const getScore = () => score;
    const giveScore = () => score++;
    let choices = [];

    const pickSpot = function(spot){
        const pickedSpot = gameBoard[spot];
        choices.push(pickedSpot);
    };
    
    return {name, choices, marker, pickSpot, getScore, giveScore};
}


const gameOn = (() => {
    const playerOne = createPlayer('Fred', 'X');
    const playerTwo = createPlayer('Barney', 'O');
    let playerOneChoices = playerOne.choices;
    let playerTwoChoices = playerTwo.choices;

    const winConditions = {
        one : ['topLeft', 'topMiddle', 'topRight'],
        two: ['middleLeft', 'middle', 'middleRight'],
        three: ['bottomLeft', 'bottomMiddle', 'bottomRight'],
        four: ['topLeft', 'middleLeft', 'bottomLeft'],
        five: ['topMiddle', 'middle', 'bottomMiddle'],
        six: ['topRight', 'middleRight', 'bottomRight'],
        seven: ['topLeft', 'middle', 'bottomRight'],
        eight: ['topRight', 'middle', 'bottomLeft']
    };


    const checkWinCondition = () => {
        //makes it so two players can't have the same spot picked at the same time
        function noRepeats(firstPick, repeatPick){
            repeatPick.filter(element => {
                if(firstPick.includes(element) === true){
                    repeatPick.splice(repeatPick.indexOf(element), 1);
                }
            })
        }
        
        noRepeats(playerTwoChoices, playerOneChoices);
        noRepeats(playerOneChoices, playerTwoChoices);

        //checks the players' picks to determine if someone wins the game
        const vals = Object.keys(winConditions).map(key => winConditions[key]);
        for(let x of vals) {
            const playerOneCheck = x.every(e => playerOneChoices.includes(e));
            const playerTwoCheck = x.every(e => playerTwoChoices.includes(e));
            if(playerOneCheck === true) {
                playerOne.giveScore();
                playerOneChoices.length = 0;
                playerTwoChoices.length = 0;
                alert(`${playerOne.name} just won the game! His score is now ${playerOne.getScore()}!`);
            } else if(playerTwoCheck === true) {
                playerTwo.giveScore();
                playerOneChoices.length = 0;
                playerTwoChoices.length = 0;
                alert(`${playerTwo.name} just won the game! His score is now ${playerTwo.getScore()}!`);
            } else if(playerOneChoices.length === 5 && playerTwoChoices.length === 4){
                playerOneChoices.length = 0;
                playerTwoChoices.length = 0;
                alert(`It's a tie! Neither ${playerOne.name} nor ${playerTwo.name} gain any points this round!`)
            }
        }
    
    }

    const topLeft = document.querySelector('.top-left');
    const topMiddle = document.querySelector('.top-middle');
    const topRight = document.querySelector('.top-right');
    const middleLeft = document.querySelector('.middle-left');
    const middle = document.querySelector('.middle');
    const middleRight = document.querySelector('.middle-right');
    const bottomLeft = document.querySelector('.bottom-left');
    const bottomMiddle = document.querySelector('.bottom-middle');
    const bottomRight = document.querySelector('.bottom-right');
    const allSquares = document.querySelectorAll('.grid-container > div');

    //variables for chaning turn
    const players = [playerOne, playerTwo];
    let turn = 0;

    //picks corresponding spot on the board for the player that has a turn
    const playerTurn = () => {
        let currentPlayer = players[turn];
        topLeft.addEventListener('click', () => currentPlayer.pickSpot(0));
        topMiddle.addEventListener('click', () => currentPlayer.pickSpot(1));
        topRight.addEventListener('click', () => currentPlayer.pickSpot(2));
        middleLeft.addEventListener('click', () => currentPlayer.pickSpot(3));
        middle.addEventListener('click', () => currentPlayer.pickSpot(4));
        middleRight.addEventListener('click', () => currentPlayer.pickSpot(5));
        bottomLeft.addEventListener('click', () => currentPlayer.pickSpot(6));
        bottomMiddle.addEventListener('click', () => currentPlayer.pickSpot(7));
        bottomRight.addEventListener('click', () => currentPlayer.pickSpot(8));

        //changes player turn
        turn++;
        if(turn === players.length){
            turn = 0;
        }

        checkWinCondition()
    }
    
    playerTurn()
    
    //plays a new turn after any spot is picked
    for(let e of allSquares){
        e.addEventListener('click', playerTurn)
    }
    return {playerOne, playerTwo, playerOneChoices, playerTwoChoices}
})()

It looks to me like it’s a problem with the event listeners not “updating” the turn value or something but I don’t know how to fix it.

When returning the path to a file based on a regex, I can console out the path but when I try to access the value, I get an undefined error

I have an express server running. I send an ID of a picture to find and I am using that ID in conjunction with FindFiles from file-regex.

app.get('/images/icons/:id', async (req, res) => {
    const result = await FindFiles('/Users/greg/server/data/', `.*${req.params.id}_1done.tif`);

    let filename = '/Users/greg/server/data/' + result[0].file;
    console.log(filename);
    res.sendFile(filename);
});

When I hit this endpoint in my tests it passes as expected but when I run it locally, and hit it from my react site. I see the following in the console


Server is running on port 3001
/Users/greg/server/data/Amaranthus_dubius_41_1done.tif
file:///Users/greg/server/server.mjs:62
    let filename = '/Users/greg/server/data/' + result[0].file;
                                                                                   ^

TypeError: Cannot read properties of undefined (reading 'file')
    at file:///Users/greg/server/server.mjs:62:84

Node.js v22.7.0

So the console.log outputs the correct filename but errors when trying to access it. I have a feeling it’s something to do when when filename is defined vs used.

I’m tried different combinations of extra variables and console logs.

Assertion failing when trying to assert an ID number in a URL Path

I am trying to do the following:
Assert the URL path after being redirected.

Here is an example of the Url: https://www.hello.com/test/test-result?testId=100

cy.location("pathname").should("eq", "/test/test-result"
cy.location("search").should("eq","/?testId=/d+/)

The first assertion passes, but the second one fails.

The error I get is the following: expected ?testId=100 to equal /?testId=/d+/

Can someone tell me what I am doing wrong? I thought using d+ would be good since it will match any number.

I Have an error I hope someone well help me [closed]

error 029: invalid expression, assumed zero
error 001: expected token: “;”, but found “]”
error 029: invalid expression, assumed zero
fatal error 107: too many error messages on one line

line: 88281 if(GreenZoneInfo[x][szid] == 0)

I hope my errors are solved correctly THANK YOU and Advance

What does && in javascript mean when used on html elements?

When updating Google Tag Manager to support CSP and nonce, they say to use this script:

(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
'https://www.googletagmanager.com/gtm.js?id='+i+dl;var n=d.querySelector('[nonce]');
n&&j.setAttribute('nonce',n.nonce||n.getAttribute('nonce'));f.parentNode.insertBefore(j,f);
})(window,document,'script','dataLayer','GTM-XXXXXX');

The n&&j.setAttribute() is confusing to me; not sure if it’s just a lack of Javascript knowledge or something else weird going on here. n and j are both Html Elements. setAttribute() adds the nonce attribute to element j and has no return value. What does the n&& do or mean? Doesn’t this just take the “and” of element n and the return value of setAttribute? But then it doesn’t do anything with the value of that and?

Or, is it that n&&j is actually evaluated first, and this script actually calls setAttribute on both n and j? That seems like a weird behavior to me if it does.

When I paste this code into Visual Studio, it automatically adds some whitespace. I was assuming that n && j.setAttribute() is the same as n&&j.setAttribute() but are they actually different?

Is There a Javascript Touch Event That Detects Key Presses?

I recently recreated a website that has a search filter that narrows down a list of search results as the user types. The code in the markup of the component looks like this

<label for="searchBar" className={`srcryBox ${styles.searchLabel}`}>

    <input
        id="searchBar"
        type="search"
        className={ styles.searchBar }
        placeholder="search for groups"
        onKeyUp={ ( event ) => detectEnterKey( event ) }
        onChange={ ( event ) => handleKeyStrokes( event.target.value ) }
    />

    <button
        type="button"
        className={ styles.searchButton }
        onClick={ handleSearch }
    >
        search
    </button>

</label>

As you can see I use the onKeyup method to detect if the enter key is pressed which I use to perform a search and the onChange method to detect the current value inside the input. I also use an onClick event on a button to detect when the user taps it so a search is performed on the text they entered into the search bar. The detectEnterKey function just checks the event.key value and if it equals Enter it passes the current search value up to the parent component to filter results that match or start with the characters in the text. The handleKeyStrokes function updates a useState() hook with the current value of the search bar which is what gets passed up to the parent when the Enter key is detected in the detectEnterKey function. The handleSearch function also passes the current value up to the parent through the same prop when clicked.

Everything works perfectly fine on a computer with a keyboard. As I type I can see the search results narrowing down in the pane I have beneath the search bar. When I press enter or click the search button the search results appear or my no results text. However on mobile devices nothing happens as I type or press the return key and the search button doesn’t seem to do anything which I’m guessing is because the value in the search bar isn’t being updated through the onChange method.

I’ve been googling everything I can think of to try to find relevant info on this issue and have come across a few results where people were having this problem however they were using jquery or java. I looked into the touch api for javascript but it was a lot of stuff mainly about detecting where a user touches on the screen and being able to move draggable elements around. Is there a way to detect events from a mobile keyboard in javascript?

How to dynamically generate components using a configuration object in ReactTS?

I’ve been trying to come up with a way to dynamically generate components using a configurable object, ideally one that can be store in a .JSON file. The current solution I’ve come up with works in this exact way but produces an implicit any type, leading me to believe something isn’t entirely correct.

Types

export type InputFieldTypes = "string" | "number" | "date" | "dropdown" | "object";

export interface BaseComponentProps<TType extends InputFieldTypes, TValue> {
  fieldKey: string;
  type: TType;
  readonly?: boolean;
  value: TValue;
  onChange: (value: TValue) => void;
}

export type InputField = StringInputComponentProps | NumberInputComponentProps;
export type InputConfig = Omit<InputField, "value" | "onChange">;

export interface StringInputComponentProps extends BaseComponentProps<"string", string> {}
export interface NumberInputComponentProps extends BaseComponentProps<"number", number> {}

Component

export function DynamicInputField(props: InputField) {
  switch (props.type) {
    case "string":
      return <StringField {...props} />;
    case "number":
      return <NumberField {...props} />;
  }
}

Calling works as followed:

<DynamicInputField
  {...field}
  value={_.get(profile, field.fieldKey)}
  onChange={(newValue) => { // <====== TS error occurs here
    const newProfile= _.set({ ...profile }, field.fieldKey, newValue);
    setProfile(newProfile);
  }}
/>

The band aid solution would be to alter the tsconfig or whack a unknown type as followed (test: unknown) => on the property value. What I’d like though is for TS to automatically understand that the parameter for onChange should, in the example, take the form of string | number. I believe its related to the use of an anonymous function being passed which TS doesn’t understand is actually the type we want and the value being pulled from an external object.

Why is React component losing state sometime between setting state and keydown?

I have here a subset of my code – it won’t run as is but outlines what I am doing. Essentially I am placing a floormap image on the floor, checking the size and adjusting for scale of physical size to screen size (getScale()). Then when scale is updated I load the desks to position on that floorplan, passing in the scale. I am also adding the desk to an array of Refs so I can access the div to adjust the border.

Up until this point, everything works and the border is adjusted when I click the desk. But pressing an arrow key and bringing up the keypress function, none of my state variables is populated.

Why not?

const componponent=()=>{
const mapRef = useRef();
const desksRef = useRef([]);

const [mapScale, setMapScale] = useState();
const [desks, setDesks] = useState({ past: [], present: [], future: [] });
const [currentDesk, setDesk] = useState(-1);
const [currentMap, setCurrentMap] = useState(-1);
const [maps, setMaps] = useState({ maps: [] });
const [editMode, setEditMode] = useState(false);
    
useEffect(() => {
    window.addEventListener('resize', updateSize);
    window.addEventListener('keydown', keyDown);
    return () => {
        window.removeEventListener('resize', updateSize);
        window.removeEventListener('keydown', keyDown);
    }
}, [])

    useEffect(() => {
        const desks = buildDesks();
        setDesks({ ...desks, present: maps.maps[currentMap]?.desks });
        setDeskComponents(desks);
    }, [editMode])

    useEffect(() => {
        const desks = buildDesks();
        setDesks({ present: maps.maps[currentMap]?.desks });
        setDeskComponents(desks);
    }, [mapScale]);

    const getScale = () => {
        const site = maps.maps[currentMap] //the id on the select
        if (!site) return;
        let map = mapRef.current;
   
        let rect = map?.getBoundingClientRect();
   
        let mapWidth = rect.width;
        let mapHeight = rect.height;
        let scaleW = (mapWidth && site?.wMM) ? (mapWidth / site.wMM) : 1;
        let scaleH = (mapHeight && site?.hMM) ? (mapHeight / site.hMM) : 1;
        setMapScale({ height: scaleH, width: scaleW });
   
   
    }
   
    const buildDesk = (desk, index) => {
        const res =
            <Desk key={desk.id}
                desk={desk}
                isEditing={editMode}
                desks={desks.present}
                scale={mapScale}
                deskTypes={deskTypes}
                currentDesk={currentDesk}
                fns={DeskFns}
                ref={el => desksRef.current[index] = el}
                index={index}
            />
        return res;
    }
   
    const buildDesks = () => {
        //getScale();
        try {
            let res = maps.maps[currentMap]?.desks.map((desk, index) => buildDesk(desk, index));
            //let res = desks.present.map(desk => buildDesk(desk);
            return res
        } catch (error) {
            console.error('Error building desks:', error);
            return null;
        }
    };


    function keyDown(e) {
        if (currentDesk > -1 && editMode == true) {
            e.preventDefault();
            var key = e.key;
   
            const desk = desks.present[currentDesk];
   
            if (editMode == true) {
                switch (key) {
                    case 'ArrowLeft': //left
                        desk.x -= 5 / mapScale.width;
                        break;
                    case 'ArrowUp': //up
                        desk.y -= 5 / mapScale.height;
                        break;
                    case 'ArrowRight': //right
                        desk.x += 5 / mapScale.width;
                        break;
                    case 'ArrowDown'://down
                        desk.y += 5 / mapScale.height;
                        break;
                    default: break;
                }
                updateDesk(desk);
            }
        }
    }

    return <React.Fragment>{deskComponents}</React.Fragment>
}
export const Desk = forwardRef(({ desk, isEditing, scale, deskTypes, fns, index }, ref) => {
    
        //const [rd, setRedraw] = useState(false);
        const [scl,] = useState(scale); //used to correct earlier issue - not necessary now
        const [rotation, setRotation] = useState(desk?.rotation ?? 0);
        const [size, setSize] = useState(() => {
    
            let deskImg = null;
            var dImg = deskTypes?.find(dsk => dsk.deskType === desk.deskType);
            let top = parseInt(desk.y * scl.height);
            const left = parseInt(desk.x * scl.width);
            let width = 0;
            let height = 0;
            try {
                if (dImg) {
                    deskImg = dImg.deskImage;
                    width = parseInt(dImg.wMM * scl.width);
                    height = parseInt(dImg.hMM * scl.height);
                }
    
                let imgStyle = {
                    boxSizing: "border-box",
                    width: `${width}px`,
                    height: `${height}px`,
                }
    
                const url = `data:image/jpeg;base64,${deskImg}`;
                return { url: url, style: imgStyle, left: left ?? 0, top: top ?? 0 };
            }
            catch (ex) {
                console.log(ex);
            }

            return { left: left, top: top };
        });
    
        const handleImageClick = (e) => {
            e.stopPropagation();
            fns.Set_Current(index);
        };
    
       return (
           //located in a <Draggable container...>
                <div >
                    <img ref={ref}
                        alt={`X=${size.left} Y=${size.top} ID=${desk.id} Rotation=${rotation}`}
                        src={size.url}
                        style={{
                            ...size.style,
                            position: 'absolute',
                            transform: `rotate(${rotation}deg)`,
                            cursor: 'move',
                        }}
                        onClick={(e) => handleImageClick(e)} // Ensure clicks are handled
                        onKeyDown={fns.onKeyDown}
                    />
                </div>
        )
    });

As a thought, is this happening because the keydown event is called from the child, so is getting the child state and not the parent where the function is located?

Reproducing WordPress < 6.5.5 Contributor+ Stored XSS Vulnerability

I am trying to reproduce the WordPress vulnerability WordPress < 6.5.5 – Contributor+ Stored XSS in Template-Part Block.

The WPScan report description mentions that WordPress does not properly escape the “tagName” attribute in the “Template Part block,” allowing high-privileged users to perform Stored Cross-Site Scripting (XSS) attacks.

The proof of concept states that to reproduce this vulnerability, as a contributor, you should:

Add a "Template Part" block to a post.
Click "Start Blank" and then "Create."
Go into Editor mode and add the following to the wp:template-part block:
"tagName":"img src=x onerror=alert(1) title=x"

I have a WordPress site running version 6.5.3, which is vulnerable. I am using the Twenty Twenty-Four theme, and as a contributor, I created a new post. However, in the block editor, I can’t find the “Template Part” option. That feature only appears in the site-editor.php, which is accessible only by administrators.

Image

I am confused because the WPScan report says contributors can execute this vulnerability. Could you clarify how to reproduce the PoC under these conditions?

References:
https://wpscan.com/vulnerability/7c448f6d-4531-4757-bff0-be9e3220bbbb/

I tried reproducing the vulnerability by adding a “Template Part” block as a contributor on a WordPress site version 6.5.3 with the Twenty Twenty-Four theme. I expected to find the “Template Part” block in the block editor as described in the PoC.

Redux-toolkit Reselect rerendering after any state change

I tried to create selector that select two variables from state and unites and returns them. But I encountered a problem, that selector causes rerendering after any state change.

import { createSelector } from 'reselect';
import { RootState } from 'store/store.ts';

const selectWallet = (state: RootState, id: string | null) => {
  if (!id) return undefined;
  return state.wallets.list[id] || undefined;
};

const selectTotal = (state: RootState, id: string | null) => {
  if (!id) return 0;
  return state.transactions.walletsTransactionsTotals[id] || 0;
};

export const reselectWalletWithTotalBalance = createSelector([selectWallet, selectTotal], (wallet, total) => {
  if (!wallet) {
    return undefined;
  }

  if (!total) {
    return wallet;
  }

  return { ...wallet, balance: wallet.balance + total };
});

export const selectWalletWithTotalBalance = (id: string | null) => {
  return (state: RootState) => reselectWalletWithTotalBalance(state, id);
};

I know that return { ...wallet, balance: wallet.balance + total }; causes rerenders, Buuut mutation selectors returning data is the point of the Reselect library (in other cases, for example when returning filtered array, no unexpected rerenders).

How to solve problem and create selector? I tryed all methods, all problems arise from creating a new object, but creating a new a object is a one of features Reselect library and I need create new object.

I tryed to reselect selectWallets and selectTotal, but nothing changed

const selectWallet = createSelector(
  [(state: RootState) => state.wallets.list, (_, id: string | null) => id],
  (walletsList, id): WalletType | undefined => {
    if (!id) return undefined;
    return walletsList[id] || undefined;
  }
);

Sweet Alert 2 v7.26.28 -> Aria hidden error in F12

(Yes, there is a new version, but right now we are not able to upgrade)

I’m using a SweetAlert2 in our Dev Express Reporting Module.

The steps are:

  1. Display Sweet Alert asking for a Report Name
  2. Do a check to the server to verify that name is not already in use
  3. If it is, show Sweet Alert message as an error
  4. On OK, then start the process again.
  5. If they hit cancel after the first run, then I see this error:

Blocked aria-hidden on a <div> element because the element that just received focus must not be hidden from assistive technology users. Avoid using aria-hidden on a focused element or its ancestor. Consider using the inert attribute instead, which will also prevent focus. For more details, see the aria-hidden section of the WAI-ARIA specification at https://w3c.github.io/aria/#aria-hidden.

It almost seems that it is an error from Sweet Alert 2, but an impact on the Dev Express Reporting Dashboard:

Error

Does anyone know a way around this or if upgrade would fix it?

All functionality seems to work, except it shows in F12 as an error.

When you hit Cancel, that the F12 Aria error does not occur.