Rendering a multi-level HTML list of links from a JSON file? (Accessing object grandchildren: 11ty, Nunjucks)

I have some JSON that looks like this (longer with more sections, but this is the jist of the structure):

{
    "navTree": [
        {
            "lvl1Item": "Graphic Design",
            "lvl1Link": "/graphic-design",
            "hasLvl2Items": true,
            "lvl2Items": [
                {
                    "lvl2Item": "Logos",
                    "lvl2Link": "/logos"
                },
                {
                    "lvl2Item": "Digital Graphics",
                    "lvl2Link": "/digital"
                }
            ]
        },
        {
            "lvl1Item": "Illustration",
            "lvl1Link": "/illust",
            "hasLvl2Items": false,
            "lvl2Items": null
        },
        {
            "lvl1Item": "Character Design",
            "lvl1Link": "/characters",
            "hasLvl2Items": false,
            "lvl2Items": null
        }
    ]
}

I went for a JSON like that cause I figured it’d make things easier if I rearranged sections of my portfolio website I’m trying to build.

I’m trying to use it to render a plaintext-HTML navigation menu that’d ultimately look like this, after build and output by 11ty (Eleventy):

<ul>
  <li><a href="/graphic-design" class="sidenav-lvl1">Graphic Design</a></li>
  <ul>
    <li><a href="/graphic-design/logos" class="sidenav-lvl2">Logos</a></li>
    <li><a href="/graphic-design/digital" class="sidenav-lvl2">Digital Graphics</a></li>
  </ul>
  <li><a href="/illust" class="sidenav-lvl1">Illustration</a></li>
  <li><a href="/characters" class="sidenav-lvl1">Character Design</a></li>
</ul>

But for going from JSON→HTML, this is the best I could come up with using Nunjucks…

<ul>
  {% for lvl1Item in navTree %}
    <li>
      <a href="{{ lvl1Item.lvl1Link }}" class="sidenav-lvl1">{{ lvl1Item.lvl1Label }}</a>
      <ul>
        {% if lvl1Item.hasLvl2Items %}
          <li>Lvl 2 True!</li> {# Just testing to see if it found anything. #}
          {% for lvl2Items in lvl1Item %}
          <li>
            <a href="{{ lvl1Item.lvl1Link }}/{{ lvl1Item.lvl2Items.lvl2Link }}" class="sidenav-lvl2">{{ lvl1Item.lvl2Items.lvl2Label }}</a>
          </li>
          {% endfor %}
        {% endif %}
      </ul>
    </li>
  {% endfor %}
</ul>

…because I made a lot of clumsy attempts to access object grandchildren/subchildren to no results. I’m not fluent in Nunjucks, and I’m only recently learning more javascript, so I’m starting to wonder if it’s possible to interact with object grandchildren in the way that I’m trying to.

Anyway, here’s the HTML result, the 11ty output:

<ul>
  <li>
    <a href="/graphic-design" class="sidenav-lvl1">Graphic Design</a>
    <ul>
      <li>Lvl 2 True!</li>
    </ul>
  </li>
  <li>
    <a href="/illust" class="sidenav-lvl1">Illustration</a>
    <ul></ul>
  </li>
  <li>
    <a href="/characters" class="sidenav-lvl1">Character Design</a>
    <ul></ul>
  </li>
</ul>

I don’t mind the empty <ul>s for non-existent subchildren unless they’re an accessibility problem(?). I’m able to make code that detects the existence of subchildren by me reporting it through the true/false hasLvl2Items in the JSON (my little Lvl 2 True! firing off), but how do I make something that starts outputting the submenu items? Or a better Nunjucks/JSON setup for my malleable site nav menu altogether?

How to get the absolute position on the Mackbook trackpad in a browser?

I want to build a website that allows users to map their trackpad input directly to an SVG element on the screen. On this website, we can turn on a mode: Touching a point on the trackpad should move the pointer to the corresponding point on the SVG. For example, touching the top-left corner of the trackpad would move the pointer to the top-left corner of the SVG.

This is similar to using the trackpad as a tablet. However, I cannot figure out how to access absolute trackpad coordinates from the browser. There is an old post about it but without any solution. There are also other similar questions, but they are for applications rather than website.

Ideally, I’d like this to work cross-platform via a website. Is it possible to get the absolute position on the trackpad in the browser?

Jetbrains Scratches and Version Control?

I have created series of trivial single file JavaScript apps using the IntelliJ Scrathes mechanism. I want to version control them without all the hoopla of setting a project per file. Really these are trivial bits of code. (Ex Pull all my completed backlog items from KanbanZone; Pull Planned items from the Upcoming week from KanbanZone).

Is there an elegant way to version control? If not, what is the normal JavaScript approach for tiny applets like this? Do people really go and create a full project for each file?

Uncaught ReferenceError: test is not defined in Twig Template with Symfony

I’m encountering an

Uncaught ReferenceError: test is not defined

error in my Symfony application when clicking a button in a Twig template. The button’s onclick event calls a JavaScript function test(patientId), but the browser cannot find the function, even though it’s defined in the template.

 {% extends 'base.html.twig' %}
 
{% block body %} <script>
    function test(patientId) {
         console.log('test',patientId);
     }
   </script>
 <div style="background-color: white; border: 1px solid #ddd; border-radius: 10px; padding: 20px; width: 100%;">
     ..................
         <tbody>
             {% for patient in patients %}
                 <tr style="border-bottom: 1px solid #ddd;">
                     <td style="padding: 10px;">{{ patient.patient_id }}</td>
                     <td style="padding: 10px;">{{ patient.full_name }}</td>
                     <td style="padding: 10px;">{{ patient.gender }}</td>
                     <td style="padding: 10px;">{{ patient.mobile_number }}</td>
                     <td style="padding: 10px;">{{ patient.date ? patient.date|date('Y-m-d') : '' }}</td>
                     <td style="padding: 10px; justify-content: center; display: flex; gap: 5px;">
                         <button style="background-color: #1e5f74; color: white; border: none; padding: 5px 10px; border-radius: 5px;
 margin-right: 5px; cursor: pointer;" onclick="test('{{ patient.id
 }}')">Create New Program</button>
                       
                 </tr>
             {% else %}
                 <tr>
                     <td colspan="9" style="padding: 10px; text-align: center;">No patients found.</td>
                 </tr>
             {% endfor %}
         </tbody>
     </table> </div>
  ............
 {% endblock%}

i tried to set the script block inised {% block javascripts %} {% endblock %} but always i got the same problem

SVN File Commit Fails but SVN Status shows that file is to be added

I’m currently working on adding a script that needs to be deployed and trying to commit it to svn.

$ ls -al
total 308
drwxrwxr-x.  3 idf_svc    domain users  4096 May 12 17:34 .
drwxrwxr-x. 11 idf_svc    domain users  4096 May  9 14:01 ..
-rwxrwxr-x.  1 idf_svc    domain users 26244 May 14  2021 amcCrypto.js
-rwxrwxr-x.  1 idf_svc    domain users 57692 Mar  4  2022 amc.js
-rwxrwxr-x.  1 idf_svc    domain users  7626 Jan 15  2020 commonMatch.js
-rwxrwxr-x.  1 idf_svc    domain users  4441 Nov 22  2019 crypto.js
-rwxr-xr-x.  1 silvat_prv domain users  4664 May 12 17:34 duo.js
-rwxrwxr-x.  1 idf_svc    domain users 75221 Nov 22  2019 lodash4.js
-rwxrwxr-x.  1 idf_svc    domain users  9454 Nov 22  2019 md5.js
-rwxrwxr-x.  1 idf_svc    domain users 15601 Sep 28  2021 misc.js
-rwxrwxr-x.  1 idf_svc    domain users 51599 Nov 22  2019 moment.js
-rwxrwxr-x.  1 idf_svc    domain users  1474 Feb 24  2021 slack.js
drwxrwxr-x.  6 idf_svc    domain users  4096 May 12 17:34 .svn
-rwxrwxr-x.  1 idf_svc    domain users 20574 Jun  3  2021 wd.js
$ svn status duo.js
A       duo.js
$ svn commit -m "Attemtpting commit for Duo integration"
Adding         lib/duo.js
Transmitting file data .svn: Commit failed (details follow):
svn: Server sent unexpected return value (200 OK) in response to PUT request for '/svn/OpenIDM/!svn/wrk/ab9c271e-dba1-4e83-b75a-abb922e553f7/trunk/script/lib/duo.js'

I keep ending up with this 200 OK but the commit failing.

I haven’t had trouble with previous scripts or versions before, but I’m unsure what I can do to remedy this.

+++++++++++++++++ [HERE’S WHAT I’VE TRIED] +++++++++++++

I tried cycling the file:

svn revert duo.js

rm duo.js

cp ~/duo_working_script.js ./duo.js

svn add duo.js

svn commit -m "Some Message"

And it still ends up with that same line.

I’ve changed the owner to match the directory.

Copied a file from that directory and wrote the script in there and try to commit it, Nothing seems to be working.

The script is connector that creates user in Duo mobile, and I use ansible variables to obscure the integration key, the secret key, our host link, and any group ID’s we need to associate that user with.

Настоящие детективы / Neighborhood Watch — напряженный триллер с непредсказуемым сюжетом

Фильм «Настоящие детективы» (оригинальное название — Neighborhood Watch) переносит зрителя в мрачный мир тайны и психических искажений. Главный герой, Саймон, недавно вышедший из психиатрической клиники, становится свидетелем похищения девушки. Чтобы распутать это загадочное дело, он обращается за помощью к бывшему полицейскому Эду, который страдает манией преследования. Вместе им предстоит пройти через лабиринт галлюцинаций и реальности, чтобы найти истину.

Кино на грани безумия и реальности
Уникальная атмосфера фильма держит в напряжении до последнего кадра. Саймону и Эду предстоит разобраться, что действительно произошло, и каким образом в дело замешаны мрачные тайны прошлого. Спасение похищенной зависит от того, удастся ли героям разгадать хитросплетения сознания Саймона и отличить вымысел от реальных улик.

Смотрите фильм на KinokongPro
Окунитесь в захватывающий мир интриг и непредсказуемых поворотов сюжета! Смотрите «Настоящие детективы» / Neighborhood Watch онлайн на сайте KinokongPro.

how to create/position elements easily [closed]

I am currently coding a game, and I am planning to add “upgrades” where every time a specific condition is met 2 pieces of text and 2 images are created. each upgrade would be in rows of 3. I really need some help with the creating and positioning of elements, I currently have this:

function createupgrade(title, price, unlockcondition, effect, icon) {
   if (condition = true) {
      //code would go here
   }
}

Google Apps Script doPost(e): e.postData is Undefined for POST Request from Netlify with application/json

I’m building a website hosted on Netlify that submits a form to a Google Apps Script web app. The form data is sent as JSON with the Content-Type: application/json header using the fetch API.

The issue I’m encountering is that within my Google Apps Script’s doPost(e) function, the e.postData property is consistently undefined. This is preventing me from accessing the data sent from my Netlify site.

My Google Apps Script web app is deployed with the following settings:

Execute as: Me (my Google account email)
Who has access: Anyone with the link
The web app URL is:

https://script.google.com/macros/s/AKfycbx8tg0J8GmI7gGvYu2iIiqB6JQK2PxbpBpGTLioS_Jv7i09LVZAvK1jbymkN3A048Vd/exec

Here are the relevant code snippets:

JavaScript (Netlify – Form Submission):

JavaScript

document.getElementById('requestForm').addEventListener('submit', async function(e) {
  e.preventDefault();
  const form = e.target;
  const data = Object.fromEntries(new FormData(form).entries());
  data.ip = userIP;
  try {
    const response = await fetch(
      "https://script.google.com/macros/s/AKfycbx8tg0J8GmI7gGvYu2iIiqB6JQK2PxbpBpGTLioS_Jv7i09LVZAvK1jbymkN3A048Vd/exec",
      { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(data) }
    );
    // ... (rest of your fetch handling - if relevant, you can include a brief summary) ...
  } catch (err) {
    console.error("Submit error:", err);
    // ...
  }
});
Google Apps Script (doOptions(e)):

JavaScript

function doOptions(e) {
  Logger.log("doOptions called");
  Logger.log(JSON.stringify(e));
  const output = ContentService.createTextOutput('');
  output.setMimeType(ContentService.MimeType.TEXT);
  output.setHeader('Access-Control-Allow-Origin', 'https://sanibelsong.com');
  output.setHeader('Access-Control-Allow-Methods', 'GET,POST,OPTIONS');
  output.setHeader('Access-Control-Allow-Headers', 'Content-Type');
  return output;
}
Google Apps Script (doPost(e) - with logging):

JavaScript

function doPost(e) {
  Logger.log("doPost called");
  Logger.log("e.postData: " + JSON.stringify(e.postData));
  try {
    const data = JSON.parse(e.postData.contents || '{}');
    // ... (rest of your doPost logic) ...
  } catch (err) {
    Logger.log("Error in doPost: " + err);
    // ... (your error handling) ...
  }
}

Troubleshooting Steps Already Taken:

Verified the Google Apps Script web app URL in the fetch request.
Checked the deployment settings in Google Apps Script.
Implemented and confirmed that the doOptions(e) function is being called (initially saw a 400 on OPTIONS, but now it seems to be 200).
Tried simplifying the doOptions(e) function.
Confirmed that a simple doGet(e) function works.
Logged the e object in doPost(e) (unfortunately, e.postData is logged as undefined, and the error occurs before we can see the entire e object).
Tried inlining CORS headers directly in doPost(e).
Created and deployed from a brand new Google Apps Script project.
Reviewed Netlify DNS records, which appear standard.
Error Message:

The error I consistently receive in the Google Apps Script Execution Log is: TypeError: Cannot read properties of undefined (reading ‘postData’)

Browser Network Tab:

The OPTIONS request to the Apps Script URL now seems to be returning a 200 OK status with the expected CORS headers. The POST request to the same URL also returns a 200 OK status in the browser, but the Google Apps Script logs indicate that e.postData is undefined.

My Question:

Why is e.postData consistently undefined in my doPost(e) function despite sending a POST request with application/json content from my Netlify website? Is there a configuration issue I’m overlooking on either the Netlify or Google Apps Script side? Could there be a subtle header issue or a limitation in how Google Apps Script handles POST requests from external domains in this specific scenario?

Any insights or suggestions would be greatly appreciated!

The Snarkjs groth16 fullprove function is not generating a proof. There are 0 errors to tell me what exactly is happening

So I am creating a project in next.js that requires me to generate some zk-proofs. I created a circom circuit, compiled it, and got my .wasm and .zkey files which are needed for generating a proof. I then created an api route that took the inputs to the circuit in its body, and passed it in the function snarkjs.groth16.fullProve(). It looked like this.

snarkjs.groth16.fullProve(input, 'circuit.wasm', 'circuit.zkey')

It did not work. There were 0 errors to tell me what was happening. So I had no other choice than to isolate the issue. I took those same two .wasm and .zkey files and tried generating a proof in the command line. I copied the same exact inputs from my console logs and created a .json file that had them. I then generated the proof from the command line and it worked. So I knew the .wasm and .zkey files were not the issue. So it was the inputs.

But its so weird because the inputs were the exact same, in the same format. Both parsed JSON objects. Anybody can help me here? I will include my api route file below. The json variable hardcodedInput is for reference what the input looks like from the body.

import { NextResponse } from "next/server";
import * as snarkjs from "snarkjs"

export async function POST(req: Request) {
    try {
        const { input } = await req.json();
        if (!input) {
            return NextResponse.json({ error: "Missing input" }, { status: 400 });
        }


        const hardcodedInput = {
            "contentHash": "23748046920731303012514512855494239778709157780815252236245687205377158920756",
            "zkCommitment": "6033632646747773138621792429970683725344213359328420058984739492752664992348"
        };

        const { proof, publicSignals } = await snarkjs.groth16.fullProve(input, './public/zkp/TE.wasm', './public/zkp/TE_final.zkey');

        console.log("Here is the proof", proof);
        console.log("Here is the publicSignals", publicSignals);


        return NextResponse.json({ success: true, proof, publicSignals });
    } catch (error: any) {
        console.error("Proof generation failed:", error);
        return NextResponse.json({ success: false, error: error.message }, { status: 500 });
    }
}

I tried generating the zk-proof in the cli with the same .wasm and .zkey files, as well as the same inputs from the code and it worked, but when generating the zk-proof from in the code it failed. Keep in mind, same two files (.wasm and .zkey) as well as the same exact inputs.

How can I fill in missing pixels in a javascript canvas object by interpolation?

I am using javascript to reproject an unusual map to plate-carree.
my crude function leaves gaps in the canvas (I apply a function to each pixel one at a time). I have been filling the blank pixels in by smearing pixels from left to right over the empty ones but that leaves artifacts. Is there a javascript library function that already exists? Am I missing something obvious?

Here is a typical image canvas output with no interpolation and a sample of my smearing code:

re-projected map with missing pixels

var imagedata = ctxOUTmap.getImageData(0,0,outputwidth,outputheight);
var dataxy = imagedata.data;
dataxy[0] = 255;dataxy[1] = 255;dataxy[2] = 255;dataxy[3] = 255; // SET FIRST PIXEL TO OPAQUE WHITE
for(var xy = 4; xy < dataxy.length; xy += 4 )
{
    if(dataxy[xy + 3] == 0) // IS IT BLANK ? SET IT TO THE LEFT PIXEL
    {
        dataxy[xy] = dataxy[xy - 4];
        dataxy[xy + 1] = dataxy[xy - 3];
        dataxy[xy + 2] = dataxy[xy - 2];
        
    }
    dataxy[xy + 3] = 255;   // set all pixels to opaque
}

How to generate and render images fast in react?

I am developing a react-ts application with tailwind

I have a table where I also have button for each row, which initiates image generation. Here is the flow;

  • User clicks the related cell
  • Opening a modal to render the images
  • 4 different image generation flow started (using html-to-image)
  • Immediately after first image generated, I am rendering it
  • In background other images continues and resolves after their generation completed

Image generation process is;

  1. Render it in a portal without showing it to user
  2. Generate image from this component

I am looking for a way to increase the performance, currently it takes ~800ms – ~1sec to generate first image, by using which techniques I can make generation & rendering faster?

many thanks in advance

JavaScript prompt to open specific file from user’s device

I am trying to make a JavaScript application which will work on or offline. The application stores the user’s data in localStorage. However I want the application to be able to show the user images which are stored on their device for example in a gallery application. localStorage would not be enough space to store the necessary images.

I thought that <input type="file"> could be used so that JavaScript could store the file name of an image in localStorage. I would not actually upload the file anywhere. Then when the user wanted to see that image they could click on an HTML element which would then prompt them to open the image. I can’t see this would be a security problem as they would be deciding whether or not to open the image.

I could of course just show them the file name and they could then navigate to the file using the device’s mechanism for that. That would be a rather slow and irritating user experience compared to what I am hoping is possible: They click on something within the JavaScript application and that prompts them to open the specific image file in their default image viewer.

As an example: The user uploads a photo, 20250512_105737.jpg to the app. The app ignores the file itself but stores the file name along with other user data in localStorage. From that point on the app can display some element which, when clicked, prompts them to open that specific image without them having to search for that file name themselves. Obviously it would rely on the user not moving the file or deleting it but they would be made aware of that. I can see it may be necessary for the user to supply the path to their image files but that could be a one off thing which would be fine.

I have been reading about the File System API on MDN but have not worked out if that would enable me to do what I want or not.

Slick click on slide to open link don’t work

I am trying to use this code to make a slider with slick. Everything works fine, but I can’t get the link to work by clicking on the center slider. You can see in CODEPEN running.
Thank you very much for your help or suggestion.

Codepen LINK

hml with the html element

     <div class="item">
       <a href="https://google.com">LINK
       <img src="https://url.com/image.jpg"
 alt=""></a>
     </div>

java with all the code

$('.slider').slick({
  slidesToShow: 3,
  slidesToScroll: 1,
  infinite: true,
  autoplay: true,
  autoplaySpeed: 2000,
  arrows: false,
  dots: false,
  centerMode: true,
  variableWidth: true,
  infinite: true,
  cssEase: 'linear',
   

var imgs = $('.slider img');
imgs.each(function(){
  var item = $(this).closest('.item');
  item.css({
    'background-image': 'url(' + $(this).attr('src') + ')', 
    'background-position': 'center',            
    '-webkit-background-size': 'cover',
    'background-size': 'cover', 
  });
  $(this).hide();
});

css with all the information

.wrap {
  position: relative;
  z-index: 100;
  width: 100%;
  height: 100%;
  padding: 0 1px;
  background: url(https://images.jpg) center no-repeat;
  -webkit-background-size: cover;
  background-size: cover;
  overflow: hidden;
}

.wrap:after {
  content:'';
  position: absolute;
  z-index: 2;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0,0,0,.5);
}

.slider {
  position: relative;
  z-index: 200;
  padding: 0 0px;
  margin: 5rem auto;
  max-width: 1000px;
  width: 100%;
}

.slick-arrow {
  position: absolute;
  top: 50%;
  width: 40px;
  height: 50px;
  line-height: 50px;
  margin-top: -25px;
  border: none;
  background: transparent;
  color: #fff;
  font-family: monospace;
  font-size: 5rem;
  z-index: 300;
  outline: none;
}

.slick-prev {
  left: -50px;
  text-align: left;
}

.slick-next {
  right: -50px;
  text-align: right;
}



.item.slick-slide {
  width: 380px;
  height: 180px !important;
  transition: transform .4s;
  position: relative; 
}

.slick-slide:after {
  content:'';
  position: absolute;
  z-index: 2;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0,0,0,.5);
  transition: transform .4s;
}

.item.slick-slide {
  transform: scale(0.7)  translate(640px);
}

.item.slick-slide.slick-center + .slick-slide {
  transform: scale(0.8) translate(-250px);
  z-index: 10;
}

.item.slick-slide.slick-center + .slick-slide + .item.slick-slide {
  transform: scale(0.7)  translate(-640px);
  z-index: 5;
}

.item.slick-slide.slick-active {
  transform: scale(0.8) translate(250px);
}

.item.slick-slide.slick-center {
  /* margin: 0 -10%; */
  transform: scale(1);
  z-index: 30;
}

.slick-center:after {
  opacity: 0;
}

How to add and remove border on an element when an event occurs?

I want a border to be added and removed for an element when a certain event occurs.

In the example below, how do I make so that when I click on the p element a border is added to div which stays for a second and goes away.

The reason I am doing this is to draw the users attention to the element when an event takes place.

document.querySelector(".clickedelement").addEventListener("click", function (e) {
  // add and remove border on div
});
div {
  width: 100px;
  height: 100px;
  background-color: yellow;
  border-radius: 50%;
}
<p class="clickedelement">when this is clicked i want border added and removed (after 1s) on div below</p>
<div class=""></div>

When using window.fetch is there a way to actually “submit()” the form?

Say I have a web page and I want it to automatically “go to” some form. This sort of thing works fine:

script(type = 'text/javascript').
    var ff = document.createElement("form")
    document.body.appendChild(ff)

    var ii = document.createElement("input")
    ii.setAttribute("type","hidden")
    ii.setAttribute("height", 69)
    ff.appendChild(ii)

    ff.method = "POST"
    ff.action = window.location + "/someform"
    ff.submit()

However, it’s much easier to use fetch to send a form:

script(type = 'text/javascript').
    fetch("/someform", {
    method: "POST",
    headers: {'Content-Type': 'application/json'},
    body: JSON.stringify({height: 69})
    })

However that does not actually “go to” the new page, /someform.

Is there actually a way to make fetch “go to” the form in question, rather than just fetch the results behind the scene?