I need heredate method “get_taxes_after_fp” in js from POS – Odoo v17

I have the following problem, I have the get_taxes_after_fp method of js which is used to obtain some taxes

I have the following problem because when I do the following override I am having problems with the call of the “get_tax_ids_after_fiscal_position_pos” method since even though it returns the values โ€‹โ€‹of the correct method it seems that the information is not reaching the method in js, I think it may be because I am not using await but it does not allow me to inherit the method, how can I make it bring data from a .py method

my method:
enter image description here

result to console.log:
enter image description here

i need heredate method in js

Is there a way to load a random title into a page using an array called from another file? One that is line separated? [duplicate]

I’m trying to get a couple of pages to have random titles.. Yes, yes.. I know in the year of our lord 2025..
I’ve seen examples that show how to do small arrays in page but I’m looking to randomize from a very large line separated file. I could do minimal formatting to allow JS to work but the main thing is that I need to load it from a separate file with the extension JS because JS I guess has issues with externally loading just any file extension.

No, I don’t actually know how to write JS. I do however know what a javascript file that should run looks like.. I know InnerHTML is involved to change the actual title tag itself.

Thanks for any leads anyone may have.

const titles = [
"Welcome to My Website!",
"Discover Amazing Things",
"Check Out Our Latest Offers",
"Your One-Stop Shop",
"Don't Miss Out!"
];

function changeTitleRandomly() {
const randomIndex = Math.floor(Math.random() * titles.length);
document.title = titles[randomIndex];
}

How do I fix an issue getting a virtual FileSystem in java script, [closed]

I have taken on a personal challenge. i want to expand my knowledge by creating a digital, online, custom OS Simulator, Heres how it works and whats my goal.
it will be uploaded online when complete. it uses javascript for functionality, html for GUI, CSS For theming and visuals, and XML For data storage. you will be able to export the XML as a custom user system. heres the kicker, i know how to use alert and const in js. nothing else. i have my reason though. ive been using google gemini to help me make it. except we are both stuck. i want to be able to go back to the code and learn from it. while coding it, were stuck with the virtual file system. it stores it on memory until exported which (hasnt been implimented yet) will be able to be exported into an XML Containing the computer itself. the worse part of the challenge is im not only on chromeos but on a school laptop. i cannot access inspect. a console. or half the online resources i want. im hellbent on dooing it though so im here for help once again.
File structure project
project
here is the code

<!--XML Base System Structure-->
<?xml version="1.0" encoding="UTF-8"?>
<SYSTEM>
    <Boot>
        <EMMEM>8000</EMMEM><!--Simulated memory in KB-->
        <EMSTR>12</EMSTR><!--Simulated Storage in GB-->
        <!--Warn when user exports the system. WARNING:True file size is only apparant when you export your system, if your  using all simulated system space. and you dont have enough storage on your  device. our system may save improporly or not at all-->
        <DevMode>True</DevMode><!--Activated dev mode, on while i code-->
        <!--Any other boot info-->
        <setup>True</setup><!--If this is set to false the setup mode will activate-->
    </Boot>
    <FileSystem><!--Emulated FileSystem-->
        <ROOT>
            <prog>
                <info>
                    <name>Setup</name>
                    <size>???</size>
                    <dates>
                        <created>0/0/0 00:00<!--Users timezone would be here--></created><!--Date file was created w/ time-->
                        <modified>0/0/0 00:00<!--Users timezone would be here--></modified><!--Date file was last modified w/ time-->
                        <!--Dates will be last update to website. ect. ect. these can be left blank for now-->
                    </dates>
                    <flags>
                        <flag>SystemApp</flag>
                        <flag>RunFullScreen</flag>
                        <!--Flags for the system to run by-->
                    </flags>
                </info>
                <progfiles>
                    <html></html>
                    <css></css>
                    <script></script>
                    <xmd></xmd><!--Data stored in an xml format for app specific things.-->
                </progfiles>
            </prog>
            <USERS>
                <Administrator>
                    <DisplayName>Administrator</DisplayName>
                    <Password>0000<!--We will add a encryption and decryption process for this later-->
                    <PERSONALFS>
                        <Desktop>
                            <Shortcut><!--Shortcut like an INK or Symlink file-->
                                <display>Documents</display>
                                <SPath>curusr/Documents</SPath><!--curusr/Documents >> CurrentUser(curusr)/ Documents-->
                            </Shortcut>
                        </Desktop>
                        <Documents>
                            <!--File-->
                            <file>
                                <name>Hello World</name>
                                <type>txt</type>
                                <contents>Hello mighty world!n This simulated os was helped designed by ai cuz im bad at code!!!</contents>
                                <size></size>
                                <dates>
                                    <created>0/0/0 00:00<!--Users timezone would be here--></created><!--Date file was created w/ time-->
                                    <modified>0/0/0 00:00<!--Users timezone would be here--></modified><!--Date file was last modified w/ time-->
                                </dates>
                            </file>
                        </Documents>
                    </PERSONALFS><!--User Specific FileSystem-->
                </Administrator>
            </USERS>
        </ROOT>
    </FileSystem>
</SYSTEM>

HTML

inhtmlconsole = document.getElementById('innerconsole')
window.console = {
    log: function(message) {
         inhtmlconsole.innerText += message + 'n';
    },
    logas: function(thing, message) {
        inhtmlconsole.innerText += "[" + thing + "] > " + message + 'n';
    },
    error: function(message) {
        inhtmlconsole.innerText += "[ERROR] > " + message + 'n';
    },
    warn: function(message) {
        inhtmlconsole.innerText += "[WARN] > " + message + 'n';
    },
    issue: function(message) {
        inhtmlconsole.innerText += "[ISSUE] > " + message + 'n';
    }
};

console.log("Log Working")

function readSingleFile(e) {
    console.logas("DATA LOADER", "readSingleFile function started");
    var file = e.target.files[0];
    if (!file) {
        console.logas("DATA LOADER", "No file selected");
      return;
    }
    var reader = new FileReader();
    reader.onload = function(e) {
        console.logas("DATA LOADER", "File loaded");
        var contents = e.target.result;
        displayContents(contents);
    };
    reader.readAsText(file);
   console.logas("DATA LOADER", "Reading file");
  }
  
  function displayContents(contents) {
    console.logas("DATA DISPLAYER", "displayContents function started");
    var element = document.getElementById('file-content');
    element.textContent = contents;
    parse(contents);
  }
  
    document.getElementById('file-input')
    .addEventListener('change', readSingleFile, false);
    function parse(content) {
        console.logas("BOOTDATAPARSER", "parse function started");
        // Create a parser
        var parser = new DOMParser();
        console.logas("BOOTDATAPARSER", "Parser created");
        xmlDoc = parser.parseFromString(content, "text/xml");
        console.logas("BOOTDATAPARSER", "XML Parsed");
         if(!xmlDoc || !xmlDoc.documentElement) {
             console.error("XML Document could not be parsed", xmlDoc)
          
         }else{
           console.logas("XML", "documentElement: " + xmlDoc.documentElement.nodeName);
           console.logas("XML","xmlDoc.documentElement.children: " + xmlDoc.documentElement.children)
            if(xmlDoc.documentElement.children){
                 const children = Array.from(xmlDoc.documentElement.children);
                children.forEach(child => {
                console.logas("XML", "Child nodeName:" + child.nodeName);
                });
            }
         }
    
        let EMMEM = 'Not found';
        let EMSTR = 'Not found';
        let DEVMODE = 'Not found';
        let SETUP = 'Not found';
    
        try {
            const emmemNode = xmlDoc.evaluate("//SYSTEM/Boot/EMMEM", xmlDoc).iterateNext();
            console.logas("BOOTDATAPARSER", "EMMEM Node retrieved " + emmemNode);
            EMMEM = emmemNode ? emmemNode.textContent : 'Not found';
        } catch (err) {
           console.error("Error getting EMMEM" , err);
        }
        try {
          const emstrNode = xmlDoc.evaluate("//SYSTEM/Boot/EMSTR", xmlDoc).iterateNext();
          console.logas("BOOTDATAPARSER","EMSTR Node retrieved " + emstrNode);
          EMSTR = emstrNode ? emstrNode.textContent : 'Not found';
        } catch (err) {
           console.error("Error getting EMSTR" , err);
        }
        try {
            const devModeNode = xmlDoc.evaluate("//SYSTEM/Boot/DevMode", xmlDoc).iterateNext();
            console.logas("BOOTDATAPARSER","DEVMODE Node retrieved " + devModeNode);
            DEVMODE = devModeNode ? devModeNode.textContent : 'Not found';
        } catch (err) {
          console.error("Error getting Developer Mode State", err);
        }
        try {
           const setupNode = xmlDoc.querySelector("SYSTEM > Boot > setup");
            console.logas("BOOTDATAPARSER", "SETUP Node retrieved " + setupNode?.textContent);
            SETUP = setupNode ? setupNode.textContent : 'Not found';
        } catch (err) {
            console.error("Error getting Setup Status", err);
        }
    
        document.getElementById("EMMEM").innerText = "Simulated Memory: " + EMMEM + "KB";
        document.getElementById("EMSTR").innerText = "Simulated Storage: " + EMSTR + "GB";
        document.getElementById("DevMode").innerText = "Running in DevMode? : " + DEVMODE;
        document.getElementById("Setup").innerText = "Is Setup?: " + SETUP;
        console.logas("BOOTDATAPARSER","After setting InnerText");
//________________The issue code is below________________________
         window.fileSystem = createInMemoryFileSystem(xmlDoc)
         console.logas("FSYS", "File System created: " + JSON.stringify(window.fileSystem, null, 2))
    
         try {
            const helloWorldFile = window.fileSystem.root.USERS.Administrator.Documents["Hello World"];
             console.logas("FSYS","Hello world file: " + helloWorldFile)
              if(helloWorldFile){
                document.getElementById('innerconsole').innerText += "n" + helloWorldFile.content
             }
          } catch (error) {
              console.error("Could not access file:", error)
          }
    }

   function createInMemoryFileSystem(xmlDoc) {
        console.logas("FSYS","createInMemoryFileSystem started");
          let xmlElement;
        if (xmlDoc && xmlDoc.documentElement && xmlDoc.documentElement.nodeName === "HTML") {
          console.logas("FSYS","XML is within HTML element")
           xmlElement  = xmlDoc.querySelector('SYSTEM')
         }else{
           console.logas("FSYS","XML is the root element");
             xmlElement = xmlDoc;
         }
         fileSystem = {};
         const fileSystemRoot = xmlElement.querySelector("FileSystem > ROOT")
         console.logas("FSYS","fileSystemRoot: " + fileSystemRoot);
       if(fileSystemRoot){
             function processElement(element, parent) {
                const nodeType = element.nodeName;
    
                if (nodeType === "ROOT" ) {
                    parent.type = "folder";
                    parent.name = "root";
                    parent.children = {};
                console.logas("FSYS","ROOT Folder Found");
                for (const child of element.children) {
                    processElement(child, parent.children);
                }
                }else if (nodeType === "prog" || nodeType === "USERS" || nodeType === "Administrator" || nodeType === "PERSONALFS" ) {
                console.logas("FSYS","processing Folder: " + nodeType);
                const folder = {};
                folder.type = "folder";
                folder.name = nodeType;
                folder.children = {};
                for (const child of element.children) {
                    processElement(child, folder.children);
                }
                parent[nodeType] = folder
                }else if (nodeType === "Desktop" || nodeType === "Documents" ) {
                 console.logas("FSYS","processing Folder: " + nodeType);
                const folder = {};
                folder.type = "folder";
                folder.name = nodeType;
                folder.children = {};
                for (const child of element.children) {
                    processElement(child, folder.children);
                }
                parent[nodeType] = folder
                }
                else if(nodeType === "file"){
                console.logas("FSYS","processing File: " + nodeType);
                const file = {}
                file.type = "file"
                file.name = element.querySelector('name')?.textContent || 'Unnamed File';
                file.content = element.querySelector('contents')?.textContent || '';
                file.size = element.querySelector('size')?.textContent || '';
                file.dates = {
                    created: element.querySelector('dates > created')?.textContent || '',
                    modified: element.querySelector('dates > modified')?.textContent || ''
                    }
                parent[file.name] = file;
                }else if(nodeType === "Shortcut"){
                console.logas("FSYS","processing Shortcut: " + nodeType);
                const shortcut = {};
                shortcut.type = "file";
                shortcut.name = "shortcut";
                shortcut.content = {
                    display: element.querySelector('display')?.textContent || 'Unnamed File',
                    SPath: element.querySelector('SPath')?.textContent || ''
                }
                parent[shortcut.name] = shortcut;
                }else{
                console.logas("FSYS","other element: " + nodeType)
                }
            }
            processElement(fileSystemRoot, fileSystem);
        }else{
           console.error("Error no file system root found");
        }
    
        console.logas("FSYS","createInMemoryFileSystem finished");
        return fileSystem;
    //___________________problem code end__________________
}

HTML

<!DOCTYPE HTML>
<link href="boot.css" rel="stylesheet">
<p>Booting...</p>
<input type="file" id="file-input" />
<div id="EMMEM">Simulated Memory: </div>
<div id="EMSTR">Simulated storage: </div>
<div id="DevMode">In Dev Mode?: </div>
<div id="Setup">Is Setup?: </div>
<p style="color: aliceblue; background-color: black;" id="innerconsole">Console<br></p>
<h3>Contents of the file:</h3>
<pre id="file-content"></pre>



<script src="boot.js"></script>

CSS

body {
    background-color: blue;
}
text {
    color: aliceblue;
}

since the only way i can view the html of the page without inspect is downloading the page as an mhtml here is the data

From: <Saved by Blink>
Snapshot-Content-Location: ___
Subject: 
Date: Mon, 6 Jan 2025 19:11:00 -0500
MIME-Version: 1.0
Content-Type: multipart/related;
    type="text/html";
    boundary="----MultipartBoundary--AptXrjHXhKeP8Y05qusXmVHzTL2WgLvzs1Yu3FK5LC----"


------MultipartBoundary--AptXrjHXhKeP8Y05qusXmVHzTL2WgLvzs1Yu3FK5LC----
Content-Type: text/html
Content-ID: <[email protected]>
Content-Transfer-Encoding: quoted-printable
Content-Location: ___
<!DOCTYPE html><html><head><meta http-equiv=3D"Content-Type" content=3D"tex=
t/html; charset=3Dwindows-1252"><link href=3D"___" rel=3D"stylesheet">
</head><body><p>Booting...</p>
<input type=3D"file" id=3D"file-input">
<div id=3D"EMMEM">Simulated Memory: 8000KB</div>
<div id=3D"EMSTR">Simulated Storage: 12GB</div>
<div id=3D"DevMode">Running in DevMode? : True</div>
<div id=3D"Setup">Is Setup?: True</div>
<p style=3D"color: aliceblue; background-color: black;" id=3D"innerconsole"=
>Console<br>Log Working<br>[DATA LOADER] &gt; readSingleFile function start=
ed<br>[DATA LOADER] &gt; Reading file<br>[DATA LOADER] &gt; File loaded<br>=
[DATA DISPLAYER] &gt; displayContents function started<br>[BOOTDATAPARSER] =
&gt; parse function started<br>[BOOTDATAPARSER] &gt; Parser created<br>[BOO=
TDATAPARSER] &gt; XML Parsed<br>[XML] &gt; documentElement: SYSTEM<br>[XML]=
 &gt; xmlDoc.documentElement.children: [object HTMLCollection]<br>[XML] &gt=
; Child nodeName:parsererror<br>[XML] &gt; Child nodeName:Boot<br>[XML] &gt=
; Child nodeName:FileSystem<br>[BOOTDATAPARSER] &gt; EMMEM Node retrieved [=
object Element]<br>[BOOTDATAPARSER] &gt; EMSTR Node retrieved [object Eleme=
nt]<br>[BOOTDATAPARSER] &gt; DEVMODE Node retrieved [object Element]<br>[BO=
OTDATAPARSER] &gt; SETUP Node retrieved True<br>[BOOTDATAPARSER] &gt; After=
 setting InnerText<br>[FSYS] &gt; createInMemoryFileSystem started<br>[FSYS=
] &gt; XML is the root element<br>[FSYS] &gt; fileSystemRoot: [object Eleme=
nt]<br>[FSYS] &gt; ROOT Folder Found<br>[FSYS] &gt; processing Folder: prog=
<br>[FSYS] &gt; other element: info<br>[FSYS] &gt; other element: progfiles=
<br>[FSYS] &gt; processing Folder: USERS<br>[FSYS] &gt; processing Folder: =
Administrator<br>[FSYS] &gt; other element: DisplayName<br>[FSYS] &gt; othe=
r element: Password<br>[FSYS] &gt; createInMemoryFileSystem finished<br>[FS=
YS] &gt; File System created: {<br>"type": "folder",<br>"name": "root",<br>=
"children": {<br>"prog": {<br>"type": "folder",<br>"name": "prog",<br>"chil=
dren": {}<br>},<br>"USERS": {<br>"type": "folder",<br>"name": "USERS",<br>"=
children": {<br>"Administrator": {<br>"type": "folder",<br>"name": "Adminis=
trator",<br>"children": {}<br>}<br>}<br>}<br>}<br>}<br>[ERROR] &gt; Could n=
ot access file:<br></p>
<h3>Contents of the file:</h3>
<pre id=3D"file-content">&lt;?xml version=3D"1.0" encoding=3D"UTF-8"?&gt;
&lt;SYSTEM&gt;
    &lt;Boot&gt;
        &lt;EMMEM&gt;8000&lt;/EMMEM&gt;&lt;!--Simulated memory in KB--&gt;
        &lt;EMSTR&gt;12&lt;/EMSTR&gt;&lt;!--Simulated Storage in GB--&gt;
        &lt;!--Warn when user exports the system. WARNING:True file size is=
 only apparant when you export your system, if your  using all simulated sy=
stem space. and you dont have enough storage on your  device. our system ma=
y save improporly or not at all--&gt;
        &lt;DevMode&gt;True&lt;/DevMode&gt;&lt;!--Activated dev mode, on wh=
ile i code--&gt;
        &lt;!--Any other boot info--&gt;
        &lt;setup&gt;True&lt;/setup&gt;&lt;!--If this is set to false the s=
etup mode will activate--&gt;
    &lt;/Boot&gt;
    &lt;FileSystem&gt;&lt;!--Emulated FileSystem--&gt;
        &lt;ROOT&gt;
            &lt;prog&gt;
                &lt;info&gt;
                    &lt;name&gt;Setup&lt;/name&gt;
                    &lt;size&gt;???&lt;/size&gt;
                    &lt;dates&gt;
                        &lt;created&gt;0/0/0 00:00&lt;!--Users timezone wou=
ld be here--&gt;&lt;/created&gt;&lt;!--Date file was created w/ time--&gt;
                        &lt;modified&gt;0/0/0 00:00&lt;!--Users timezone wo=
uld be here--&gt;&lt;/modified&gt;&lt;!--Date file was last modified w/ tim=
e--&gt;
                        &lt;!--Dates will be last update to website. ect. e=
ct. these can be left blank for now--&gt;
                    &lt;/dates&gt;
                    &lt;flags&gt;
                        &lt;flag&gt;SystemApp&lt;/flag&gt;
                        &lt;flag&gt;RunFullScreen&lt;/flag&gt;
                        &lt;!--Flags for the system to run by--&gt;
                    &lt;/flags&gt;
                &lt;/info&gt;
                &lt;progfiles&gt;
                    &lt;html&gt;&lt;/html&gt;
                    &lt;css&gt;&lt;/css&gt;
                    &lt;script&gt;&lt;/script&gt;
                    &lt;xmd&gt;&lt;/xmd&gt;&lt;!--Data stored in an xml for=
mat for app specific things.--&gt;
                &lt;/progfiles&gt;
            &lt;/prog&gt;
            &lt;USERS&gt;
                &lt;Administrator&gt;
                    &lt;DisplayName&gt;Administrator&lt;/DisplayName&gt;
                    &lt;Password&gt;0000&lt;!--We will add a encryption and=
 decryption process for this later--&gt;
                    &lt;PERSONALFS&gt;
                        &lt;Desktop&gt;
                            &lt;Shortcut&gt;&lt;!--Shortcut like an INK or =
Symlink file--&gt;
                                &lt;display&gt;Documents&lt;/display&gt;
                                &lt;SPath&gt;curusr/Documents&lt;/SPath&gt;=
&lt;!--curusr/Documents &gt;&gt; CurrentUser(curusr)/ Documents--&gt;
                            &lt;/Shortcut&gt;
                        &lt;/Desktop&gt;
                        &lt;Documents&gt;
                            &lt;!--File--&gt;
                            &lt;file&gt;
                                &lt;name&gt;Hello World&lt;/name&gt;
                                &lt;type&gt;txt&lt;/type&gt;
                                &lt;contents&gt;Hello mighty world!n This =
simulated os was helped designed by ai cuz im bad at code!!!&lt;/contents&g=
t;
                                &lt;size&gt;&lt;/size&gt;
                                &lt;dates&gt;
                                    &lt;created&gt;0/0/0 00:00&lt;!--Users =
timezone would be here--&gt;&lt;/created&gt;&lt;!--Date file was created w/=
 time--&gt;
                                    &lt;modified&gt;0/0/0 00:00&lt;!--Users=
 timezone would be here--&gt;&lt;/modified&gt;&lt;!--Date file was last mod=
ified w/ time--&gt;
                                &lt;/dates&gt;
                            &lt;/file&gt;
                        &lt;/Documents&gt;
                    &lt;/PERSONALFS&gt;&lt;!--User Specific FileSystem--&gt=
;
                &lt;/Administrator&gt;
            &lt;/USERS&gt;
        &lt;/ROOT&gt;
    &lt;/FileSystem&gt;
&lt;/SYSTEM&gt;</pre>



</body></html>
------MultipartBoundary--AptXrjHXhKeP8Y05qusXmVHzTL2WgLvzs1Yu3FK5LC----
Content-Type: text/css
Content-Transfer-Encoding: quoted-printable
Content-Location: ____

@charset "windows-1252";

body { background-color: blue; }

text { color: aliceblue; }
------MultipartBoundary--AptXrjHXhKeP8Y05qusXmVHzTL2WgLvzs1Yu3FK5LC------

built in console output

Console
Log Working
[DATA LOADER] > readSingleFile function started
[DATA LOADER] > Reading file
[DATA LOADER] > File loaded
[DATA DISPLAYER] > displayContents function started
[BOOTDATAPARSER] > parse function started
[BOOTDATAPARSER] > Parser created
[BOOTDATAPARSER] > XML Parsed
[XML] > documentElement: SYSTEM
[XML] > xmlDoc.documentElement.children: [object HTMLCollection]
[XML] > Child nodeName:parsererror
[XML] > Child nodeName:Boot
[XML] > Child nodeName:FileSystem
[BOOTDATAPARSER] > EMMEM Node retrieved [object Element]
[BOOTDATAPARSER] > EMSTR Node retrieved [object Element]
[BOOTDATAPARSER] > DEVMODE Node retrieved [object Element]
[BOOTDATAPARSER] > SETUP Node retrieved True
[BOOTDATAPARSER] > After setting InnerText
[FSYS] > createInMemoryFileSystem started
[FSYS] > XML is the root element
[FSYS] > fileSystemRoot: [object Element]
[FSYS] > ROOT Folder Found
[FSYS] > processing Folder: prog
[FSYS] > other element: info
[FSYS] > other element: progfiles
[FSYS] > processing Folder: USERS
[FSYS] > processing Folder: Administrator
[FSYS] > other element: DisplayName
[FSYS] > other element: Password
[FSYS] > createInMemoryFileSystem finished
[FSYS] > File System created: {
"type": "folder",
"name": "root",
"children": {
"prog": {
"type": "folder",
"name": "prog",
"children": {}
},
"USERS": {
"type": "folder",
"name": "USERS",
"children": {
"Administrator": {
"type": "folder",
"name": "Administrator",
"children": {}
}
}
}
}
}

THE ISSUE,
we are able to access everything up until PersonalFS.
after reviewing it I see that the processElement function is failing to build the PERSONALFS part of the file system structure.

Me and the ai have tried like 50 variations of the code. we CANNOT figure it out :/

How can I improve my problem-solving skills in programming? what finally did “click” for you?

what was the one thing you learned that made programming finally “click” for you? I’m struggling right now and looking for ideas to improve and become a better programmer.

Iโ€™ve been trying different resources like online courses, documentation, and tutorials. I expected to feel more comfortable and confident when coding, but I still feel stuck and struggle to apply what I learn in real projects.

Using the PayPal Donate SDK with my own HTML button

I’ve created a PayPal donation button using their Donate SDK, as documented here:

https://developer.paypal.com/sdk/donate/

The resulting code looks like this:

<div id="donate-button-container">
<div id="donate-button"></div>
<script src="https://www.paypalobjects.com/donate/sdk/donate-sdk.js" charset="UTF-8"></script>
<script>
PayPal.Donation.Button({
env:'production',
hosted_button_id:'MY_ID_HERE',
image: {
src:'https://www.paypalobjects.com/en_US/i/btn/btn_donate_LG.gif',
alt:'Donate with PayPal button',
}
}).render('#donate-button');
</script>
</div>

When the button is clicked, it opens the donation page in a nice pop-up window, which I really like.

However, this solution uses a small, low-quality GIF image for the button, and I’d prefer to use my own HTML button instead, which I can style to match my website – it would look like this:

<div class="button paypal">Donate with PayPal</div>

However, I have no clue how to replace the GIF image within the provided JavaScript, with my own button.

Can someone kindly help me out here? Is it even possible? Maybe using some kind of JS “on click” action that will cause the PayPal popup window to appear?

How to make 2 colour diagonal background flexible without distorting the angle? Tailwind & Javascript

Im trying to make an angled section that will have an image of the application im working on with some text about it, I ended up getting the proper sizes for a polygon and i have it flexing but since im using percentages, the angle likes to distort when being flexed (see images below)

No Flexing:
enter image description here

With Flexing:
enter image description here

Im not sure what would be the best way to handle this specific case while also having the page stay the same size as the display without affecting the angle. The code below is how I’ve been getting the polygon so far.

    function Login() {
    return (
        <>
            <div className="flex flex-col min-h-screen overflow-hidden relative">
                <Navbar />
                <div className="flex-grow flex">
                    <div className="flex-1 flex items-center justify-start bg-white z-10 ml-[5em]">
                        <Form />
                    </div>
                    <div
                        className="flex-1 bg-[#f7f7f7] pr-[5em]"
                        style={{
                            clipPath: `polygon(0 0, 100% 0, 100% 100%, 25% 100%)`,
                        }}
                    >
                        <div className="relative left-[10em] max-w-[675px] top-[8em] rotate-[-15deg] pr-[10em]">
                            <h1 className="text-[24px] font-semibold max-w-[300px] mb-4">This is a Title</h1>
                            <p className="flex font-light">Lorem ipsum dolor sit amet consectetur adipisicing elit. Excepturi adipisci officia enim quas laudantium illo! Ea, temporibus? Provident voluptatem in perspiciatis, a nemo fuga? Magni atque dicta assumenda alias deserunt?</p>
                        </div>
                    </div>
                </div>
                <DarkModeButton />
            </div>
        </>
    );
}

I’ve tried to use a rectangle or different values for the clippath, and even tried to rotate the entire this but unfortunately there was some weird issue with it hiding the corners (not due to overflow-hidden). Any help is appreciated! ๐Ÿ™‚

Why does my script not work as an external file?

I currently have a script that works as expected as a block script at the bottom of the markup. When I try to run the same script as an external js file, it no longer works.

I am probably missing something basic. The only difference between the two scripts was that one was block coded and the other was external. Below is the original page.

<!DOCTYPE html>
<html lang="en-US">
<head>
<meta charset="utf-8">
</head>

<body>
  <select id="opSelect" >
    <option value="Addition">Addition</option>
    <option value="Subtraction">Subtraction</option>
    <option value="Multiplication">Multiplication</option>  
    <option value="Division">Division</option>
  </select>

  <div id="mathCalc">
   <p><h1>this is page 2</h1></p>
   <div class="opChoice" id="opOne">Addition</div>
   <div><button class="gobtn" id="gobtn" type="button">GO</button></div>
  </div>

  <div id="mathScore">
   <p><h1>this is page 3</h1></p>
   <div id="opTwo" class="opChoice">Addition</div>
   <div><button class="gobtn" id="gobtn" type="button">GO</button></div>
  </div>

<script>
document.getElementById("opSelect").onchange = function() {
  let choice=document.getElementById("opSelect").value;

 if (choice == "Addition") {
 document.getElementById("opOne").innerHTML = "Addition";
 document.getElementById("opTwo").innerHTML = "Addition";
}

else if (choice == "Subtraction") {
document.getElementById("opOne").innerHTML = "Subtraction";
document.getElementById("opTwo").innerHTML = "Subtraction";  
}

else if (choice == "Multiplication") {
document.getElementById("opOne").innerHTML = "Multiplication";
document.getElementById("opTwo").innerHTML = "Multiplication";
}

else if (choice == "Division") {
document.getElementById("opOne").innerHTML = "Division";
document.getElementById("opTwo").innerHTML = "Division";
}
};
</script>

</body>
</html>

Stop localStorage Overlap

On my site I am using localStorage so when a User selects a theme it then applies said theme to the relevant pages.

now this works for each individual user, however if you logout of account 1 and login with account 2 on the same device it applies it to all other accounts logged into that device.

Furthermore when the theme has been applied if I was to login on a different device it still shows the default theme?

how would I have it only affect the specific account and have the theme choice shared across devices?

Down below is the Codepen and full code:

However Please go to Codepen to see the script I was unable to upload the code correctly parts of the formatting are being ignored.

Codepen: https://codepen.io/Elixble/pen/RwzZaWB

Follow this link to see the corresponding .php page: https://codepen.io/Elixble/pen/RNbxZvz?editors=1000

'<div id="homepage">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<body id="Background">
    <div id="homepage-row1">
        <div class="sectiontext">Settings</div>
    </div>

    <div id="Settings-Menu-Bar">
        <a href="/SettingsAccountInfo">
            <button id="Account-Info-Button">Account Info</button>
        </a>
        <a href="/Privacy">
            <button id="Privacy-Info-Button">Privacy</button>
        </a>
        <a href="/Notifications">
            <button id="Notifications-Settings-Button">Notifications</button>
        </a>
        <a href="/Themes">
            <button id="Theme-Settings-Button">Themes</button>
        </a>
        <a href="/DMSettings">
            <button id="DirectMessage-Settings-Button">Direct Messages</button>
        </a>
        <div id="ComingSoon">Coming Soon</div>
        <button id="VPN-Settings-Button">VPN</button>
        <button id="Payment-Options">Payment Options</button>
    </div>

    <div class="Embers-Theme-Card" data-class="Embers-Theme-Card-Gradient" onclick="myFunction(this)">
        <h1>Embers</h1>
        <div class="mouse-position-tracker">
            <div></div>
            <div></div>
            <div></div>
            <div></div>
            <div></div>
            <div></div>
            <div></div>
            <div></div>
            <div></div>
        </div>
    </div>

    <div class="Darkmode-Theme-Card" data-class="Darkmode-Theme-Card-Gradient" onclick="myFunction(this)">
        <h1>Darkmode</h1>
        <div class="mouse-position-tracker">
            <div></div>
            <div></div>
            <div></div>
            <div></div>
            <div></div>
            <div></div>
            <div></div>
            <div></div>
            <div></div>
        </div>
    </div>

    <div class="CherryBlossom-Theme-Card" data-class="CherryBlossom-Theme-Card-Gradient" onclick="myFunction(this)">
        <h1>CherryBlossom</h1>
        <div class="mouse-position-tracker">
            <div></div>
            <div></div>
            <div></div>
            <div></div>
            <div></div>
            <div></div>
            <div></div>
            <div></div>
            <div></div>
        </div>
    </div>

    <div class="Mint-Theme-Card" data-class="Mint-Theme-Card-Gradient" onclick="myFunction(this)">
        <h1>Mint</h1>
        <div class="mouse-position-tracker">
            <div></div>
            <div></div>
            <div></div>
            <div></div>
            <div></div>
            <div></div>
            <div></div>
            <div></div>
            <div></div>
        </div>
    </div>

    <div class="Sunrise-Theme-Card" data-class="Sunrise-Theme-Card-Gradient" onclick="myFunction(this)">
        <h1>Sunrise</h1>
        <div class="mouse-position-tracker">
            <div></div>
            <div></div>
            <div></div>
            <div></div>
            <div></div>
            <div></div>
            <div></div>
            <div></div>
            <div></div>
        </div>
    </div>
</body>

Extra challenge: Just being a bit cheeky but the Aux theme is meant to be animated but I dont know how to get gifs to play in the background so feel free to see if you can.

Firebaseauth phone authentication Error (auth/invalid-app-credential) Reactjs

I want to authenticate/verify user phone number by sending OTP using firebase auth.
Getting the error:
“Error sending verification code: FirebaseError: Firebase: Error (auth/invalid-app-credential)”

My App configurations match to the one’s in the console and authentication works with the phone number provided in the testing section but failing when I try to send to my personal number.

Number is well formtted like +countrycode+number(+92334*******) and my payment plan is Blaze(Pay as you go).

code

Firebase.ts:

import { initializeApp } from "firebase/app";
import { getAuth } from "firebase/auth";

const firebaseConfig = {
    .......
};

// Initialize Firebase App
const app = initializeApp(firebaseConfig);

// Export Firebase Auth instance
export const auth = getAuth(app);

firebaseUtils.ts:

import { RecaptchaVerifier, signInWithPhoneNumber, PhoneAuthProvider, signInWithCredential } from "firebase/auth";
import { auth } from "../app/firebase/firebaseConfig";

export const initializeRecaptcha = () => {
    if (!window.recaptchaVerifier) {
        window.recaptchaVerifier = new RecaptchaVerifier(
            auth,
            "recaptcha-container",
            {
                size: "normal", // Use 'invisible' for a hidden reCAPTCHA
                callback: (response: any) => {
                    console.log("reCAPTCHA solved:", response);
                },
                "expired-callback": () => {
                    console.error("reCAPTCHA expired. Please try again.");
                },
            }
        );
    }
    return window.recaptchaVerifier;
};


export const sendCode = async (phoneNumber: string) => {
    debugger
    if (!window.recaptchaVerifier) initializeRecaptcha();
    try {
        if (!window.recaptchaVerifier) {
            throw new Error("ReCAPTCHA verifier not initialized");
        }
        const confirmationResult = await signInWithPhoneNumber(auth, phoneNumber, window.recaptchaVerifier!);
            //.then((confirmationResult) => {
            //  debugger
            //  window.confirmationResult = confirmationResult;
            //  Toast.show("success", "OTP sent successfully");
            //})
            //.catch((error) => {
            //  debugger
            //  console.log(error);
            //});
        return confirmationResult;
    } catch (error) {
        console.error("Error sending verification code:", error);
        throw error;
    }
};

export const verifyCode = async (verificationId: string, verificationCode: string) => {
    const credential = PhoneAuthProvider.credential(verificationId, verificationCode);
    return await signInWithCredential(auth, credential);
};

VerifyToken.ts:

import { useEffect, useRef, useState } from "react";
import { Formik, ErrorMessage } from "formik";
import { Button, Form, Header, Label, Segment } from "semantic-ui-react";
import * as Yup from "yup";
import MyTextInput from "../../app/common/form/MyTextInput";
import Toast from "../../utils/Toast";
import { initializeRecaptcha, sendCode, /*validateRecaptchaToken,*/ verifyCode } from "../../utils/firebaseUtils";

interface Props {
    email?: string; // Optional: for email verification
    phoneNumber?: string; // Optional: for phone number verification
    onSuccess?: () => void; // Callback after successful verification
}

export default function VerifyToken({ email, phoneNumber, onSuccess }: Props) {
    const [timer, setTimer] = useState(120); // 2-minute countdown timer
    const [isTimerActive, setIsTimerActive] = useState(false);
    const [verificationId, setVerificationId] = useState<string | null>(null);
    const hasRun = useRef(false);

    useEffect(() => {
        if (phoneNumber && !hasRun.current) {
            handleCodeRequest();
            hasRun.current = true;
        }
    }, [phoneNumber]);

    useEffect(() => {
        let countdown: NodeJS.Timeout;
        if (isTimerActive && timer > 0) {
            countdown = setInterval(() => setTimer((prev) => prev - 1), 1000);
        } else if (timer <= 0) {
            setIsTimerActive(false);
            setTimer(120);
        }
        return () => clearInterval(countdown);
    }, [isTimerActive, timer]);

    const handleCodeRequest = async () => {
        if (email) {
            Toast.show("info", `A code has been sent to your email: ${maskEmail(email)}`);
        } else if (phoneNumber) {
            
            try {
                debugger
                // Initialize reCAPTCHA
                const recaptchaVerifier = initializeRecaptcha();

                // Wait for reCAPTCHA to be solved
                const recaptchaToken = await recaptchaVerifier.verify();
                //await validateRecaptchaToken(recaptchaToken)
                console.log("reCAPTCHA solved, token:", recaptchaToken);
                debugger
                // Send the verification code after solving reCAPTCHA
                const result = await sendCode(phoneNumber);
                if (result) {
                    setVerificationId(result.verificationId);
                    Toast.show("info", `A verification code was sent to ${phoneNumber}.`);
                    setIsTimerActive(true);
                }
            } catch (error) {
                console.error("Error sending verification code:", error);
                Toast.show("error", "Failed to send verification code. Please try again.");
            }
        }
    };


    const handleSubmit = async (code: string, setErrors: (errors: { error: string }) => void) => {
        if (email) {
            Toast.show("success", "Email verification successful!");
            onSuccess && onSuccess();
            return;
        }

        if (!verificationId) {
            setErrors({ error: "Verification ID not available. Please resend the code." });
            return;
        }

        try {
            const userCredential = await verifyCode(verificationId, code);
            if (userCredential) {
                Toast.show("success", "Phone number verified successfully!");
                onSuccess && onSuccess();
            } else {
                throw new Error("Verification failed.");
            }
        } catch (error: any) {
            console.error("Verification error:", error.message);
            setErrors({ error: "Invalid code. Please try again or resend." });
        }
    };

    const formatTime = () => {
        const minutes = Math.floor(timer / 60);
        const seconds = timer % 60;
        return `${minutes}:${seconds < 10 ? `0${seconds}` : seconds}`;
    };

    const maskEmail = (email: string | null) => {
        if (!email) return "";
        const [localPart, domain] = email.split("@");
        if (localPart.length <= 2) return email;
        return `${localPart[0]}${"*".repeat(localPart.length - 2)}${localPart.slice(-1)}@${domain}`;
    };

    return (
        <Segment padded style={{ maxWidth: 400, margin: "auto", borderRadius: "15px", background: "#f0f5ff" }}>
            <Header as="h2" content={`Verify Your ${email ? "Email" : "Phone Number"}`} color="black" />
            <p>Enter the code we sent to <strong>{email ? maskEmail(email) : phoneNumber}</strong>.</p>
            {phoneNumber && <div id="recaptcha-container" style={{ marginBottom: "10px" }}></div>}
            <Formik
                initialValues={{ code: "", error: "" }}
                validationSchema={Yup.object({ code: Yup.string().required("Code is required") })}
                onSubmit={(values, { setErrors }) => handleSubmit(values.code, setErrors).catch((error) => setErrors({ error: error.message }))}
            >
                {({ handleSubmit, errors, isValid, isSubmitting }) => (
                    <Form className="ui form" onSubmit={handleSubmit} autoComplete="off">
                        <MyTextInput placeholder="Enter code" name="code" type="text" />
                        <ErrorMessage name="error" render={() => <Label style={{ marginBottom: 10 }} basic color="red" content={errors.error} />} />
                        <div style={{ display: "flex", alignItems: "center", marginBottom: "20px", cursor: isTimerActive ? "not-allowed" : "pointer", color: isTimerActive ? "gray" : "#4a90e2" }} onClick={!isTimerActive ? handleCodeRequest : undefined}>
                            {isTimerActive ? <span>Try again in {formatTime()}</span> : <span>Resend Code</span>}
                        </div>
                        <Button disabled={!isValid} loading={isSubmitting} primary content="Verify" type="submit" fluid />
                    </Form>
                )}
            </Formik>
        </Segment>
    );
}

Request that fail:
Request URL:
https://identitytoolkit.googleapis.com/v1/accounts:sendVerificationCode?key=key
Request Method:
POST
Status Code:
400 Bad Request
Remote Address:
address
Referrer Policy:
no-referrer

payload:
{
“phoneNumber”: “+9231********”,
“clientType”: “CLIENT_TYPE_WEB”,
“captchaResponse”: “NO_RECAPTCHA”,
“recaptchaVersion”: “RECAPTCHA_ENTERPRISE”,
“recaptchaToken”: “token”
}
Response:
{
“error”: {
“code”: 400,
“message”: “INVALID_APP_CREDENTIAL”,
“errors”: [
{
“message”: “INVALID_APP_CREDENTIAL”,
“domain”: “global”,
“reason”: “invalid”
}
]
}
}

Is this failing becuase of RECAPTCHA_ENTERPRISE(also tried using RECAPTCHA_ENTERPRISE in the previous firebase project but didn’t work and didn’t enable it in new firebase project)?

I also added the 127.0.0.1 in firebase authentication setting under Authorized domains.
But It does not allow 127.0.0.1:3000.

Is there a way to replace content by clicking on a link?

I’m at a complete and utter loss and it’s really frustrating.

I want to make it so when I click on a certain link, it will only change the content inside one div on the same page so I don’t have to link multiple different pages. It’s impractical to have multiple different HTML pages just for me to change one div’s content. When I click on one of the links, it should hide the default content and switch it with whatever content I want relating to that link.

I’ve tried looking up multiple different videos and questions, but I fear I’m maybe not wording it right or I just don’t understand. Some of the tutorials I followed got me to where the content was hidden but when I would click on the links nothing popped up. I’m assuming this will use some javascript which is fine, I don’t mind learning that. But I have yet to use it for anything so I’m unsure of where to go from here.

This is my HTML:

<!DOCTYPE html>
 <html lang="en">

  <head>
     <title>TEST</title>
     <meta charset="UTF-8">
     <link rel="stylesheet" type="text/css" href="test.css">
  </head>

    <style>
      body {
      font-family: 'Courier New', monospace;
      background-image: url("background.png");
      background-repeat: repeat;
      }

      a:link {
        color: black;
        text-decoration: none;
        font-weight: bold;
      }

      a:visited {
        color: black;
        text-decoration: none;
        font-weight: bold;
      }

      a:hover {
        color: hotpink;
        text-decoration: none;
        font-weight: bold;
      }

      a:active {
        color: black;
        text-decoration: none;
        font-weight: bold;
     }
    </style>

     <body>
          <!--CONTAINER-->
        <div class="container">

           <!--LEFT-->
          <div class="links">
              <ul>
                <li style="list-style-image: url('starblink.gif');" alt="graphic of a green star"><a href="about.html" target="_parent">ABOUT</a></li>
                <li style="list-style-image: url('starblink2.gif');" alt="graphic of a red star"><a href="resources.html" target="_parent">RESOURCES</a></li>
                <li style="list-style-image: url('starblink3.gif');" alt="graphic of a yellow star"><a href="shrines.html" target="_parent">SHRINES</a></li>
                <li style="list-style-image: url('starblink4.gif');" alt="graphic of a blue star"><a href="misc.html" target="_parent">MISC</a></li>
              </ul>
          </div>

                <!--MIDDLE-->
              <div class="main">
                <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut
                  labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris
                   nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit
                    esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt
                     in culpa qui officia deserunt mollit anim id est laborum.</p>
               </div>

        </div>
   </body>
</html>

And my CSS:

/*CONTAINER*/
.container {
  display: flex;
  flex-direction: row;
  justify-content: center;
  align-items: center;
  height: 700px;
  min-height: 700px;
  margin-top: -20px;
}

/*LEFT*/
.links {
  width: 200px;
  min-width: 200px;
  margin-top: -50px;
  margin-left: 50px;
  line-height: 60px;
  font-size: 35px;
}

/*MIDDLE*/
.main {
  width: 400px;
  min-width: 400px;
  height: 600px;
  min-height: 600px;
  margin-top: -10px;
  margin-left: 80px;
  margin-right: 20px;
  padding-left: 20px;
  padding-top: 10px;
  overflow-y: auto;
  overflow-x: hidden;
}

What is the most secured approach to prevent html video download from a django website

I have a website that i want to do the following:

  1. prevent users from downloading the videos. I need the best practice
  2. ensure that my videos can only be played within the website and no where else

I tried to disguise the video source link to blob url object but it’s downloadable. Even when I copy the blob url object in to browser the video still plays, that another thing i need to prevent. PLEASE HELP!

I trying build a small useful js framework jsml but stuck

The problem is that the for Element when it re renders and new dom element is created that means if an element in the for element it unable to do transition when the state changes



import { mergeStringsWithSeparator,stopUnwanted ,stringSplitter} from './JSML/element.js';

import {removeJSMLWrapper,inheritParentStyles} from './JSML/utils.js';



const JSML = (call) => {

  let listeners = new Set();

  let templates = new Map();

  let keysMaps=new Map()

  let componentElement = ['IF', 'ELSEIF', 'CLONEABLE', 'CLONE', 'FOR', 'AWAIT'];



  const createDeepProxy = (target, callback) => {

    return new Proxy(target, {

      get(target, property) {

        const value = target[property];

        if (typeof value === 'object' && value !== null) {

          return createDeepProxy(value, callback);

        }

        return value;

      },

      set(target, property, value) {

        target[property] = value;

        callback();

        return true;

      },

      deleteProperty(target, property) {

        delete target[property];

        callback();

        return true;

      }

    });

  };



  const state = createDeepProxy(call(), () => {

    listeners.forEach(listener => listener());

  });



  const parsePlaceholders = (template, context) => {

  return template.replace(/{{(.*?)}}/g, (_, expression) => {

    try {

      return new Function(...Object.keys(context), `return ${expression}`)(...Object.values(context));

    } catch {

      return ''; // Return empty string for invalid placeholders

    }

  });

};



  const isValidPlaceholder = (value) => value !== undefined && value !== null && value !== '';



  const directives = {

    bind : (el, expression,nu ,context = {}) => {

  const evaluate = () => {

    const processedExp = parsePlaceholders(expression, context);



    // Check if the processed expression resolves in the current context

    try {

      const value = new Function("state", `return state.${processedExp}`)(state);

      el.textContent = value; // Update the DOM with the current value

    } catch (error) {

      console.warn(`Failed to evaluate bind expression: ${expression}`, error);

    }

  };

//console.log(context,nu)

  // Add a watcher to evaluate changes dynamically

  const addDynamicBinding = () => {

    const processedExp = parsePlaceholders(expression, context);



    let value = new Function("state", `return state.${processedExp}`)(state);



    Object.defineProperty(state, processedExp, {

      set(newValue) {

        value = newValue;

        el.textContent = newValue; // Reflect changes in DOM

      },

      get() {

        return value;

      },

    });

  };



  listeners.add(evaluate);

  evaluate();

  addDynamicBinding();

}, 

    click: (el, expression, context = {}) => {

      el.addEventListener('click', () => {

        let processedExp = expression;

        Object.entries(context).forEach(([key, value]) => {

          const replacementValue = typeof value === 'number' ? value : `'${value}'`;

          processedExp = processedExp.replace(new RegExp(`{{${key}}}`, 'g'), replacementValue);

        });

        new Function("state", `state.${processedExp}`)(state);

      });

    },

    xclass: (el, exp, context) => {

  const evaluate = () => {

    // Parse the expression into an object

    //console.log(exp)

    const classMap = new Function("state", ` { return ${exp}; }`)(state);

      //console.log(classMap)

     // return

    if (typeof classMap !== "object" || classMap === null) {

      console.warn(`Invalid xclass value: Expected an object, got ${typeof classMap}`);

      return;

    }



    // Loop through the classMap object

    for (const [className, condition] of Object.entries(classMap)) {

      if (condition) {

        let newClass=stringSplitter.byMultipleDelimiters(className.toString(),[','])

        newClass.forEach( nclass=> {

          el.classList.add(nclass)

        })

        //console.log(e)

      } else {

       let newClass = stringSplitter.byMultipleDelimiters(className.toString(), [','])

newClass.forEach(nclass => {

  el.classList.remove(nclass)

})

      }

    }

  };



  // Re-evaluate whenever the state changes

  listeners.add(evaluate);

  evaluate();

},

    xstyle: (el, expression, context = {}) => {

  const evaluate = () => {

    // Replace placeholders in the expression

   

    let processedExp = parsePlaceholders(expression, context);



    try {

      // Evaluate the processed expression

      const styles = new Function("state", `return ${processedExp}`)(state);

       

      // Apply the evaluated styles to the element

      Object.entries(styles).forEach(([key, value]) => {

        el.style[key] = value;

      });

    } catch (error) {

      console.error(`Error in xstyle directive: ${error.message}`);

    }

  };



  evaluate();

  listeners.add(evaluate);

}, 

    model: (el, expression, context = {}) => {

  const updateState = (value) => {

    //console.log(value)

    const processedExp = parsePlaceholders(expression, context);

    //

    if (Object.keys(context).length >0) {

      const split=stringSplitter.byMultipleDelimiters(processedExp,['.']);

      new Function("state", `return state.${context.arrayName}[${context.outerIndex}].${split[split.length -1]}=${value}`)(state)

      //console.log(processedExp)

    } else {

      new Function("state", `state.${processedExp} = ${value}`)(state);

    }

    

  };



  if (el.type === 'radio') {

    el.addEventListener('click', () => {

      const processedExp = parsePlaceholders(expression, context);

      const split=stringSplitter.byMultipleDelimiters(processedExp,['.']);

   const splitLength=split.length

     // console.log(processedExp,context)

      let currentValue 

      if (Object.keys(context).length > 0) {

        

      currentValue= new Function("state", `return state.${context.arrayName}[${context.outerIndex}].${split[splitLength -1]}`)(state)

      } else {

        currentValue=new Function("state", `return state.${processedExp}`)(state);

      }

       

      //console.log(currentValue)

      updateState(!currentValue); // Toggle the value

    });

  } else {

    el.addEventListener('input', (e) => {

      const value = el.type === 'number' ? parseFloat(e.target.value) : e.target.value;

      updateState(`'${value}'`);

    });

  }



  const evaluate = () => {

    const split=stringSplitter.byMultipleDelimiters(expression,['.']);

   const splitLength=split.length

    const processedExp = parsePlaceholders(expression, context);

   const merged = mergeStringsWithSeparator('.',`${context.arrayName}[${context.index}]`)

   const select=stopUnwanted(merged,/undefined[undefined]/i)

   if (select && Object.keys(context).length > 0) {

     return 

   }

   let value;

   if (Object.keys(context).length > 0) {

     value=new Function("state", `return state.${context.arrayName}[${context.outerIndex}].${split[splitLength -1]}`)(state)

   } else {

     

     if (split.length > 1) {

       return

     }

     

     value = new Function("state", `return state.${processedExp}`)(state);

   }

    

    

    

    if (el.type === 'radio') {

      el.checked = !!value; // Update the "checked" state

      

      //el.style.backgroundColor = value ? 'blue' : 'red'; // Change style based on state

    } else {

      el.value = value !== undefined ? value : '';

    }

  };



  evaluate();

  listeners.add(evaluate);

}

  };



  const ElementCom = {

    if: (el, context) => {

  const expression = el.getAttribute('x');



  const evaluate = () => {

    const processedExp = parsePlaceholders(expression, context);



    try {

      const condition = context ? new Function(...Object.keys(context), `return ${processedExp}`)(...Object.values(context)) : new Function('state', `return ${processedExp}`)(state);



      Array.from(el.children).forEach(child => {

        child.style.display = condition ? '' : 'none';

      });



      // Handle ELSE sibling

      const sibling = el.nextElementSibling;

      if (sibling && sibling.tagName === 'ELSE') {

        Array.from(sibling.children).forEach(child => {

          child.style.display = condition ? 'none' : '';

        });

      }

    } catch (error) {

      console.error(`Error in if directive: ${error.message}`);

    }

    

  };



  evaluate();

  listeners.add(evaluate);

  

},

    for: (el, context) => {

      

  if (!templates.has(el)) {

    templates.set(el, el.innerHTML);

  }

  if (!keysMaps.has(el.getAttribute('key'))) {

   if(el.getAttribute('key')) {

     keysMaps.set(el.getAttribute('key'),el)

   }

  } else {

    console.log(keysMaps.get(el.getAttribute('key')))

    console.log('esits')

    forLoopUpdater(el,keysMaps)

  }

  

  

//console.log(el)

  const template = templates.get(el);

  const [itemNames, , arrayName] = el.getAttribute('x').split(' ');

  let splitloopIndex=stringSplitter.byMultipleDelimiters(itemNames,[','])

const itemName=splitloopIndex[0]

  const hasInvalidPattern = (str) => {

    // Check for the exact pattern '.[].'

    

    const invalidPattern = /[]./;

    if (invalidPattern.test(str)) {

      

      return true;

    }

    return false;

  };



  const evaluate = () => {

    const processedExp = parsePlaceholders(arrayName, context);

    if (hasInvalidPattern(processedExp)) {

      return;

    }

    

    const array = new Function("state", `return state.${processedExp}`)(state);



    if (!Array.isArray(array)) return;



    el.innerHTML = '';



    array.forEach((item, outerIndex) => {

      const wrapper = document.createElement('div');

      wrapper.innerHTML = template;



      const processNode = (node) => {

        if (node.nodeType === 3) { // Text node

          const text = node.textContent;

          const newText = text.replace(

            new RegExp(`{{${itemName}}}`, 'g'),

            item

          ).replace(

            new RegExp(`{{${itemName}\.(.+?)}}`, 'g'),

            (_, prop) => item[prop]

          ).replace(

            new RegExp(`{{index}}`, 'g'),

            outerIndex // Outer index for the current loop

          ).replace(

            new RegExp(`{{${splitloopIndex[1]}}}`, 'g'),

            outerIndex // Outer index for the current loop

          ).replace(

            new RegExp(`{{outerIndex}}`, 'g'),

            outerIndex // Alias for outer index

          );

          node.textContent = newText;

        } else if (node.attributes) {

          Array.from(node.attributes).forEach(attr => {

            const newValue = attr.value

              .replace(new RegExp(`{{${itemName}}}`, 'g'), item)

              .replace(new RegExp(`{{${itemName}\.(.+?)}}`, 'g'),

                (_, prop) => item[prop])

              .replace(new RegExp(`{{index}}`, 'g'), outerIndex).replace(

            new RegExp(`{{${splitloopIndex[1]}}}`, 'g'),

            outerIndex // Outer index for the current loop

          ).replace(new RegExp(`{{outerIndex}}`, 'g'), outerIndex);

            attr.value = newValue;

          });

        }



        Array.from(node.childNodes).forEach(processNode);

      };



      Array.from(wrapper.childNodes).forEach(processNode);



      const children = Array.from(wrapper.children);



      children.forEach(child => {

        const childContext = {

          ...context,

          [itemName]: item,

          outerIndex, 

          arrayName// Alias for outer index

        };



        if (child.tagName === 'FOR') {

          const innerExp = child.getAttribute('x');

          const [innerItemName, , innerArrayName] = innerExp.split(' ');



          childContext[`${itemName}_index`] = outerIndex; // Preserve outer loop index

          applyElement(child, 'for', childContext);



        } else if (child.tagName === 'IF') {

          const exp = child.getAttribute('x');

          applyElement(child, 'if', childContext, exp);

        } else {

          attr.forEach(directive => {

            const exp = child.getAttribute(directive);

            

            if (exp) {

              

              apply(child, directive, exp, childContext);

            }

          });

        }

        const nextAttriToAllChildren=Array.from(child.querySelectorAll('*'))

        nextAttriToAllChildren.forEach(nextedChild =>{

          if (nextedChild.tagName === 'IF') {

            return

          } else if (nextedChild.tagName === 'FOR') {

            

          }

       attr.forEach(directive => {

            const exp = nextedChild.getAttribute(directive);

            

            if (exp) {

              

              apply(nextedChild, directive, exp, childContext);

            }

          });

        })

      });



      while (wrapper.firstChild) {

        el.appendChild(wrapper.firstChild);

      }

    });

  };



  listeners.add(evaluate);

  evaluate();

},

  };

const forLoopUpdater=(el,mapskey) => {

    const node=mapskey.get(el.getAttribute('key'))

    const processNode = (node) => {

  if (node.nodeType === 3) { // Text node

    const text = node.textContent;

    const newText = text.replace(

      new RegExp(`{{${itemName}}}`, 'g'),

      item

    ).replace(

      new RegExp(`{{${itemName}\.(.+?)}}`, 'g'),

      (_, prop) => item[prop]

    ).replace(

      new RegExp(`{{index}}`, 'g'),

      outerIndex // Outer index for the current loop

    ).replace(

      new RegExp(`{{${splitloopIndex[1]}}}`, 'g'),

      outerIndex // Outer index for the current loop

    ).replace(

      new RegExp(`{{outerIndex}}`, 'g'),

      outerIndex // Alias for outer index

    );

    node.textContent = newText;

  } else if (node.attributes) {

    Array.from(node.attributes).forEach(attr => {

      const newValue = attr.value

        .replace(new RegExp(`{{${itemName}}}`, 'g'), item)

        .replace(new RegExp(`{{${itemName}\.(.+?)}}`, 'g'),

          (_, prop) => item[prop])

        .replace(new RegExp(`{{index}}`, 'g'), outerIndex).replace(

          new RegExp(`{{${splitloopIndex[1]}}}`, 'g'),

          outerIndex // Outer index for the current loop

        ).replace(new RegExp(`{{outerIndex}}`, 'g'), outerIndex);

      attr.value = newValue;

    });

  }



  Array.from(node.childNodes).forEach(processNode);

};

}

  const applyElement = (el, Elements, context, expression) => {

    if (ElementCom[Elements]) {

      ElementCom[Elements](el, context, expression);

    }

  };



  const attr = Object.keys(directives);



  const apply = (el, directive, expression, context = {}) => {

    if (directives[directive]) {

      directives[directive](el, expression, context);

    }

  };



  const render = () => {

    const jhtmlElements = document.querySelectorAll('*');

    jhtmlElements.forEach(el => {

      const elements = Array.from(el.children);

      elements.forEach(element => {

        if (componentElement.includes(element.tagName)) {

          componentElement.forEach(com => {

            const AllComElement = document.querySelectorAll(com.toLowerCase());

            AllComElement.forEach(el => {

              applyElement(el, com.toLowerCase());

            });

          });

          return;

        }

        attr.forEach(directive => {

          const expression = element.getAttribute(directive);

          if (expression) {

            apply(element, directive, expression);

          }

        });

      });

    });

    componentElement.forEach(jml => {

      const jsml=document.querySelectorAll(jml)

      jsml.forEach(el => {

        inheritParentStyles(el)

      })

    })

  };



  render();



  return {

    state,

    render

  };

};



export default JSML;



This my library called JSML

<!DOCTYPE html>

<html>



<head>

  <meta charset="UTF-8">

  <meta name="viewport" content="width=device-width, initial-scale=1">

  <title>JSML</title>

  <script src="https://cdn.tailwindcss.com"></script>



</head>



<body>

  <div

      class="h-[35vh] transition-all

      transition duration-300 ease-in-out overflow-hidden bg-red-600 flex items-center justify-center"

      xstyle="{ 

        width: state.itemIndex === 0 ? '100vw' : '0px', 

        transform: state.itemIndex === 0 ? 'scale(1)' : 'scale(0)', 

        backgroundColor: state.itemIndex === 0 ? 'blue' : 'red' 

      }"

    >

  </div>

<div class="flex w-screen h-[35vh]">

  

    <div class=" w-screen h-[35vh]">

  <for x="item,i in items" parent="class" key="forloop">

    <div

      class="h-[35vh] transition-all

      transition duration-300 ease-in-out overflow-hidden bg-red-600 flex items-center justify-center"

      xstyle="{ 

        width: state.itemIndex === {{i}} ? '100vw' : '0px', 

        transform: state.itemIndex === {{i}} ? 'scale(1)' : 'scale(0)', 

        backgroundColor: state.itemIndex === {{i}} ? 'blue' : 'red' 

      }"

    >

      <div>

        <span>{{item}}</span>

        <div>

          <span bind="itemIndex"></span>

        </div>

        <div>

          <if x="state.isTrue">

            <span>istrue</span>

          </if>

        </div>

      </div>

  </for>

</div>

</div>

<script src="./text.js" type="module"></script>

</body>



</html>

That is the html code

import JSML from './index.js';



const app=JSML(()=> ({

  items:['1','2','3'],

  itemIndex:0,

  isTrue:false,

  data:true

  

}))

const carousel= () => {

return  setInterval(() => {

  

     app.state.itemIndex++

     if (app.state.itemIndex >= 3) {

  app.state.itemIndex = 0



  clearInterval(carousel)

}



  },4000)

}

carousel()


This is the text.js code

From the above please help me make the library for loop not to re-render but in stead update the for element because when ever it re-render it set in new dom and by so transition does not work so help for that in my library

I am expecting the for loop to like a robust type like react or vue and

jsPDF 2.5.2 – letter spacing for numbers with font Montserrat

I use the Montserrat Font for creating PDF’s with jsPDF 2.5.2 and I need letter spacing for numbers.
For my website it works when I add: font-feature-settings: “tnum”

@font-face {
    font-family: "Montserrat-Regular";
    font-feature-settings: "tnum";
    font-style: normal;
    font-weight: 400;
}

is it possible to do the same with jsPDF

I tried this but it doesn’t work perfect for me

function addFonts(doc) {
    const montserratRegular = readFile('/fonts/Montserrat-Regular.js');
    doc.addFileToVFS('Montserrat-Regular-normal.ttf', montserratRegular);
    doc.addFont('Montserrat-Regular-normal.ttf', 'Montserrat-Regular', 'normal');
}

doc.setFontSize(10);
doc.setFont('Montserrat-Regular', 'normal');

doc.text('124.11', 100, 50, {align:'right', charSpace:'0.1'});

thanks for nice tips

I am getting an error just creating a fresh Next.js app, without adding ANY code

I am getting an error just creating a fresh Next.js app, without adding any code.

npx [email protected] –ts
enter image description here

enter image description here

enter image description here

enter image description here

Hi. Does not make sense that a fresh app without any code added is having an error.
enter image description here

The error message is:
hook.js:608 A tree hydrated but some attributes of the server rendered HTML didn’t match the client properties. This won’t be patched up. This can happen if a SSR-ed Client Component used:

  • A server/client branch if (typeof window !== 'undefined').
  • Variable input such as Date.now() or Math.random() which changes each time it’s called.
  • Date formatting in a user’s locale which doesn’t match the server.
  • External changing data without sending a snapshot of it along with the HTML.
  • Invalid HTML tag nesting.

Again, this is a fresh app, I don’t add absolutely anything!!

React app componenet, ‘Module not found’, however imports and paths are all correct

The mysterious Error in question:

ERROR in ./src/App.tsx 8:0-49
Module not found: Error: Can't resolve './Components/ItemShop' in 'C:UsersEvan NewmanDesktopGithub ReposDnD-ecommercedndecommerce-frontendsrc'

A screenshot showing where the files are relative to each other

Code from the App component:

import React from "react";
import "./App.css";
// import DisplayDagger from "./Components/DisplayDagger";
import "bootstrap/dist/css/bootstrap.min.css";
import { ItemShop } from "./Components/ItemShop";

function App() {
  return (
    <div className="container p-4">
      <ItemShop />
    </div>
  );
}

export default App;

Code from the imported ItemShop component:

import React, { useState, useEffect } from "react";
import { FaShoppingCart, FaCoins, FaWeight, FaDungeon } from "react-icons/fa";
import { GiDaggers } from "react-icons/gi";

interface DamageType {
  index: string;
  name: string;
  url: string;
}

interface Damage {
  damage_dice: string;
  damage_type: DamageType;
}

interface Cost {
  quantity: number;
  unit: string;
}

interface EquipmentCategory {
  index: string;
  name: string;
  url: string;
}

interface Property {
  index: string;
  name: string;
  url: string;
}

interface DndItem {
  index: string;
  name: string;
  equipment_category: EquipmentCategory;
  weapon_category?: string;
  weapon_range?: string;
  category_range?: string;
  cost: Cost;
  damage?: Damage;
  range?: {
    normal: number;
    long?: number;
  };
  weight: number;
  properties?: Property[];
  throw_range?: {
    normal: number;
    long: number;
  };
  url: string;
}

const ItemShop: React.FC = () => {
  const [items, setItems] = useState<DndItem[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    const fetchItems = async () => {
      try {
        const response = await fetch("https://www.dnd5eapi.co/api/equipment");
        const data: { results: { index: string; url: string }[] } =
          await response.json();

        // Fetch detailed information for each item
        const itemDetails = await Promise.all(
          data.results.slice(0, 6).map(async (item) => {
            const detailResponse = await fetch(
              `https://www.dnd5eapi.co${item.url}`
            );
            return detailResponse.json() as Promise<DndItem>;
          })
        );

        setItems(itemDetails);
        setLoading(false);
      } catch (err) {
        setError("Failed to fetch items");
        setLoading(false);
      }
    };

    fetchItems();
  }, []);

  const addToCart = (item: DndItem) => {
    // TODO: Implement cart functionality
    console.log(`Added ${item.name} to cart`);
  };

  if (loading)
    return (
      <div className="d-flex justify-content-center p-5">
        <div className="spinner-border text-primary" role="status">
          <span className="visually-hidden">Loading items...</span>
        </div>
      </div>
    );

  if (error)
    return (
      <div className="alert alert-danger text-center m-4" role="alert">
        {error}
      </div>
    );

  return (
    <div className="container py-4">
      <div className="row mb-4">
        <div className="col">
          <h1 className="display-4 text-center">
            <FaDungeon className="me-3" />
            Magical Marketplace
          </h1>
        </div>
      </div>

      <div className="row g-4">
        {items.map((item) => (
          <div key={item.index} className="col-12 col-md-6 col-lg-4">
            <div className="card h-100 shadow-sm">
              <div className="card-header bg-primary text-white">
                <h5 className="card-title mb-0 d-flex align-items-center">
                  <GiDaggers className="me-2" />
                  {item.name}
                </h5>
              </div>
              <div className="card-body">
                <div className="mb-3">
                  <p className="d-flex align-items-center mb-2">
                    <FaCoins className="me-2 text-warning" />
                    <strong>Cost:</strong> {item.cost?.quantity}{" "}
                    {item.cost?.unit}
                  </p>
                  <p className="d-flex align-items-center mb-2">
                    <FaWeight className="me-2 text-secondary" />
                    <strong>Weight:</strong> {item.weight} lbs
                  </p>
                  {item.equipment_category && (
                    <p className="d-flex align-items-center mb-2">
                      <FaDungeon className="me-2 text-primary" />
                      <strong>Category:</strong> {item.equipment_category.name}
                    </p>
                  )}
                  {item.damage && (
                    <p className="mb-2">
                      <strong>Damage:</strong> {item.damage.damage_dice}{" "}
                      {item.damage.damage_type.name}
                    </p>
                  )}
                  {item.properties && item.properties.length > 0 && (
                    <div className="mt-2">
                      <strong>Properties:</strong>
                      <div className="mt-1">
                        {item.properties.map((prop) => (
                          <span
                            key={prop.index}
                            className="badge bg-secondary me-1 mb-1"
                          >
                            {prop.name}
                          </span>
                        ))}
                      </div>
                    </div>
                  )}
                </div>
                <button
                  className="btn btn-primary w-100 d-flex align-items-center justify-content-center"
                  onClick={() => addToCart(item)}
                >
                  <FaShoppingCart className="me-2" />
                  Add to Cart
                </button>
              </div>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
};

export default ItemShop;

In Conclusion

This is more of a strange problem that a complicated one. The issue is very simple; The app component cannot find the ItemShop component, despit the pathing being correct. Is there an underlying issue that I am overlooking?