EJS isn’t being rendered

I’m making a rock, scissors, paper game on the backend of Node.js with express server, frontend.js client-side, index.ejs and main.css files. I firstly want to render a string line of the result of your decision (won, lost, the same – try again).
However, it doesn’t render the result. I tried to use console.log to detect if the data is passed between the routes, which indeed happens and it literally shows that the data is in the ejs template, but it still doesn’t render.
I tried to use chat GPT to figure it out and it failed…

backend.js:

    import express from "express";
import bodyParser from "body-parser";
import pg from "pg";
import ejs from "ejs";
import axios from "axios";
import { dirname } from "path";
import { fileURLToPath } from "url";


// import icons from "bootstrap-icons";
const __dirname = dirname(fileURLToPath(import.meta.url));
const app = express();
const port = 3000;


let gameResult = [];

app.set('view engine', 'ejs');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static("public"));


app.get("/", (req, res) => {

   const results = [...gameResult];
    gameResult = [];

    console.log("Result from session:", results);

    res.render("index", {results});
});

app.post("/add", (req,res) => {

    const {targetedId, dataIdList} = req.body;

    let compSelector = dataIdList[Math.floor(Math.random() * dataIdList.length)];

    console.log(`Chosen by client: ${targetedId}`);
    console.log(`Chosen by computer: ${compSelector}`);



  function determineResult(targetedId, compSelector) {

    switch (targetedId) {
        case "paper":
            if(compSelector === "scissors") {
                return "You lost";
                
            } else if(compSelector === "rock") {
                return "You won!";
                
            } else {
                return "The same, try again";
                
            }
            break;

        case "scissors":
            if(compSelector === "rock") {
                return "You lost";

            } else if(compSelector === "paper") {
                return "You won!"

            } else {
                return "The same, try again";
            }
            break;

            case "rock":
                if(compSelector === "paper") {
                    return "You lost";
    
                } else if(compSelector === "scissors") {
                    return "You won!"
    
                } else {
                    return "The same, try again";
                }
            break;

        default:
            console.log("Error");
            break;
    }

 }

 try {
    const result = determineResult(targetedId, compSelector);
    console.log(result);
   
    gameResult = [result];
   
    res.redirect("/");
 } catch (error) {
    console.error("Error handling POST /add request:", error);
        res.status(500).send("Internal Server Error");
 }




});



app.listen(port, () => {
    console.log(`Listening on port ${port}`);
});

frontend.js:

console.log("Frontend.js is loaded");

function myFrontFunction(event) {

    const selectedImage = event.target;
    const targetedId = selectedImage.getAttribute("data-id");
    const images = document.querySelectorAll(".image");
    const dataIdList = [];

    images.forEach(dataId => {
       dataIdList.push(dataId.getAttribute("data-id"));
    });

    console.log(`Data list: ${dataIdList}`);


// console.log(typeof(idData));


    console.log(targetedId);

    fetch("/add", {
        method: "POST",
        headers: {"Content-Type": "application/json"},
        body: JSON.stringify({targetedId, dataIdList}),
    })
    .then(response => {

        if(response.ok) {
        console.log("Data sent successfully");
        response.text().then(text => console.log(text));
        console.log("All images:", images); 

        images.forEach(image => {
            if(image !== selectedImage){
                console.log("Hiding image:", image);
                image.classList.add('hidden'); // Use class to hide
            }
        });
        } else {
            console.error("Failed to send data to the server");
        }

        

    })
    .catch(error => console.error("Error:", error));

}

index.ejs:

<%- include('partials/header.ejs') %>


<h1>The RSP App!</h1>

<h2>Choose Rock, Scissors or Paper:</h2>

<img class="image" src="/images/paper.png" alt="A piece of paper" width="400px" height="400px" data-id="paper" onclick="myFrontFunction(event)">
<img class="image" src="/images/rock.png" alt="A rock" width="400px" height="400px" data-id="rock" onclick="myFrontFunction(event)">
<img class="image" src="/images/scissors.png" alt="Scissors" width="400px" height="400px" data-id="scissors" onclick="myFrontFunction(event)">


<div>
<% if (results.length > 0) { %>
    <% results.forEach( result => { %>
       <p> <%= result %></p>
    <% }) %>
<% } %>
</div>






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

<%- include('partials/footer.ejs') %>

main.css:

.hidden {
    display: none;
}

Responsiveness problem with my div using Vue and Tailwind (Keeping the width when it should shrink)

<div class="flex flex-col bg-sky-600 bg-opacity-35 w-full overflow-y-hidden h-auto max-h-64 px-5 rounded-lg shadow-md pt-5 text-white shrink scroll-smooth">
        <h1>TODAY'S FORECAST</h1>
        <div v-if="data" class="flex overflow-x-scroll overflow-y-hidden scrollbar scrollbar-thumb-sky-200 pb-3">
            <div v-for="(hour, index) in data.forecast.forecastday[0].hour" :key="hour.time_epoch" :class="['flex flex-col w-32 h-40 shrink-0 items-center justify-center hover:bg-sky-500 transition-all', index < data.forecast.forecastday[0].hour.length - 1 ? 'border-r border-white' : '']">
                <span class="text-gray-300">{{ formatHour(hour.time) }}</span>
                <img loading="lazy" :src="hour.condition.icon">
                <span class="text-4xl">{{ Math.round(isCelsius ? hour.temp_c : hour.temp_f) }}&deg;</span>
                <div class="group flex items-center relative">
                    <DropComp class="w-5 h-5" />
                    <span>{{ hour.chance_of_rain }}%</span>
                    <span class="group-hover:scale-100 absolute -top-2 left-20 scale-0 p-2 min-w-max z-30 bg-yellow-500 rounded-lg transition-all duration-100 origin-left">Chance of rain</span>
                </div>
            </div>
        </div>
    </div>

This is the div
I’m having trouble trying to make my web app responsive. When I make the screen size smaller in the dev tools this div doesn’t shrink and also keeps the parent div with it’s children from shrinking.

I thought maybe the parent is causing this to happen so I gave this div a way smaller width size than the parent div and the parent div and all of it’s children were shrinking and growing with the screen until they became the same size as this div and at that point they stopped shrinking.

I also tried this div on it’s own in an empty HTML file and it was shrinking and growing as expected but for some reason it doesn’t do the same in my Vue project.

Other than these I literally have no idea on what to try.

Passing an object to a route with vue-router

Based on this from vue-routers site it seems as though you can pass an object as a prop. However, everytime I try to do this it seems to it fail saying invalid param

My route is defined as follows:

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      component: () => import('../layouts/DashboardLayout.vue'),
      meta: {
        requiresAuth: true,
      },
      children: [
        {
          path: '/upload',
          name: 'Upload Review',
          component: () => import('../pages/CertificationUploadPage.vue'),
          props: { mode: 'manual'}
        },
      ],
    },
    // default redirect to home page
    { 
      path: '/:pathMatch(.*)*', 
      redirect: '/error',
      meta: {
      requiresAuth: true,
      }
    },
    { path: '/:pathMatch(.*)*', 
      redirect: '/login',
      meta: {
        requiresAuth: false,
     }
    }
  ]
})

I programmatically push a new page using this:

router.push({ name: 'Upload Review', params : {mode: 'email'} })

I am curious if I can also go one step further and pass a nested object with some additional data I want to get to the next page/component or would I have to use pinia for that?

Show custom HTML in Firefox add-on popup/dialog

I’m learning how to make an extension (for Firefox).

This add-on reads the youtube main page (https://www.youtube.com/) and get the visible videos on it. From those videos, I’m able to extract the video ID, title, duration of the video, channel name and channel ID.

With this data, I want to show a pop-up dialog with a HTML table that has the obtained info as folows:

Channel No. of videos
NationSquid 1
Numberphile 4
JhnNroses 8
HugoX Chugox 3

[…and so on]


My manifest.json – doesn’t really add much, but, I’ve followed the description of the tag.

{
  "manifest_version": 2,
  "name": "Ejemplo",
  "version": "1.0",

  "description": "Inspeccionar elementos de youtube.com.",

  "icons": {
    "48": "icons/border-48.png"
  },

  "applications": {
    "gecko": {
      "id": "[email protected]"
    }
  },

  // N.B: This is the code extracted from 
  // https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/user_interface/Popups#specifying_a_popup 
  "browser_action": {
     "default_icon": "icons/beasts-32.png",
     "default_title": "Ejemplo",
     "default_popup": "popup/base_html_file.html"
  },

  "content_scripts": [
    {
      "matches": ["https://*.youtube.com/"],
      "js": ["Ejemplo.js", "jquery-1.9.1.min.js"]
    }
  ]
}

My goal is:

I want the add-on shows a pop-up dialog with the HTML I want to specify – in this case, a HTML <table> as shown in the example above.

My current issue is:

I haven’t found a way to pass the JSON object to my base html file1 OR
a way to use the JSON object to build a custom HTML code in the pop-up
dialog.

I’ve read about the user interface and popups in the documentation; however, I haven’t found how the extension can be coded for achieve this requirement.

Can anyone point me to the right path to achive this goal?


1 In the documentation – section “specifying a popup”, the add-on uses a base HTML with a pre-defined HTML, but, I haven’t found if this “base HTML” can be modified with javascript.

Refresh / Reload page on pause youtube iframe api

I have a problem with my code. I want to refresh the page on pause or exit of full screen. The exit on Full screen works. The pause using the youTube iframe API does not “onstatechange”. Any suggestions I could be missing? It appears the onstatechange is not being received. Could there be a Issue with the way I have constructed the “onYouTubeIframeAPIReady()”? I have followed the documentation but this continues to not refresh when the video is paused.

Thanks

<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <style>
        .container {
            width: 80%;
            margin: 0 auto;
        }
        .responsive-video {
            overflow: hidden;
            padding-bottom: 56.25%;
            position: relative;
            height: 0;
        }
        .responsive-video iframe {
            left: 0;
            top: 0;
            height: 100%;
            width: 100%;
            position: absolute;
        }
    </style>
    <script src="https://www.youtube.com/iframe_api"></script>
</head>
<body>
    <div class="container">
        <div class="responsive-video">
            <iframe id="youtubeIframe" width="560" height="315" src="https://www.youtube.com/embed/oJUvTTGVdTMyY" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
        </div>
    </div>

    <script>
        var player;
        var iframe = document.getElementById('youtubeIframe');
        var src = iframe.src;

        function onYouTubeIframeAPIReady() {
            console.log('YouTube IFrame API Ready');
            player = new YT.Player('youtubeIframe', {
                events: {
                    'onReady': onPlayerReady,
                    'onStateChange': onPlayerStateChange
                }
            });
        }

        function onPlayerReady(event) {
            console.log('Player Ready');
        }

        function onPlayerStateChange(event) {
            console.log('Player State Changed:', event.data);
            if (event.data == YT.PlayerState.PAUSED || event.data == YT.PlayerState.ENDED) {
                console.log('Playback stopped or paused, reloading the player');
                setTimeout(reloadPlayer, 100); // Call the reload function after a short delay
            }
        }

        function reloadPlayer() {
            console.log('Reloading player');
            iframe.src = src; // Reset the src attribute to reload the iframe
        }

        function checkFullscreen() {
            if (!document.fullscreenElement && 
                !document.webkitFullscreenElement && 
                !document.mozFullScreenElement && 
                !document.msFullscreenElement) {
                console.log('Exiting fullscreen, reloading the player');
                setTimeout(reloadPlayer, 100); // Call the reload function after a short delay
            }
        }

        // Add event listeners for fullscreen change
        document.addEventListener('fullscreenchange', checkFullscreen);
        document.addEventListener('webkitfullscreenchange', checkFullscreen);
        document.addEventListener('mozfullscreenchange', checkFullscreen);
        document.addEventListener('MSFullscreenChange', checkFullscreen);

        window.onYouTubeIframeAPIReady = onYouTubeIframeAPIReady;
    </script>
</body>
</html>

Hide page count from the go to section of the pdf toolbar when pdf is opened in browser

From java side I am converting tiff images to PDF like below.

        Rectangle pagesize = new Rectangle(maxWidth, maxHeight);
        Document document = new Document(pagesize);
        PdfWriter.getInstance(document, output);
        document.open();

        for (int imageIndex = 0; imageIndex < numPages; imageIndex++) {

            img = images.get(imageIndex);
            img.setAlignment(Image.MIDDLE);
            document.setPageSize(new Rectangle(maxWidth, maxHeight));
            document.add(img);
            document.newPage();
        }

        document.close();

and then from the angular side , I am using window.open to show the PDF file like this

.subscribe(fileUrl => {
        dialogRef.close();
        windowRef = window.open(..${fileUrl}#toolbar=0, '_blank', 'width=800,height=600');
            this.addToAttachmentManager(windowRef, processId);},
() => dialogRef.close());

When the pdf is opened in the browser , I want to hide the Total page count only from the pdf toolbar panel
reference img

How to automatically change the background color on left side of an HTML range slider?

I’m making an HTML music player project and I’m trying to make the left part of the <input type="range" value="0"> slider be black.
The slider is to show how much a song has played and to change from where the song is played. The slider has this CSS:

#progress{
    -webkit-appearance: none;
    width: 100%;
    height: 10px;
    cursor: pointer;
    border-radius: 4px;
    margin: 40px 0;
    background: white;
    border: 4px solid black;
    box-shadow: 0 5px 5px rgba(0, 0, 0, 0.2);
}
#progress::-webkit-slider-thumb{
    -webkit-appearance: none;
    background-color: rgb(245, 245, 245);
    width: 20px;
    height: 20px;
    border-radius: 50%;
    border: 3px solid black;
    box-shadow: 0 5px 5px rgba(0, 0, 0, 0.2);
}

This is the whole HTML

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <link rel="stylesheet" href="style.css">
    <title>
        HTML Music Player
    </title>
    <script defer src="script.js"></script>
</head>
<body>
    <div class="container">
        <div class="music-player">
            <audio id="song"></audio>

            <img id="thumbnail">
            <h1 id="title"></h1>
            <h4 id="artist"></h4>

            <input type="range" value="0" id="progress">
            <div class="controls">
                <div onclick="previousSong()" onmouseover="prevOver()" onmouseout="prevOut()" id="backward">
                    <img src="icons/backward.png" width="40%">
                </div>
                <div onclick="playPause()" onmouseover="playOver()" onmouseout="playOut()" id="play">
                    <img src="icons/play.png" width="40%" id="ctrlIcon">
                </div>
                <div onclick="nextSong()" onmouseover="nextOver()" onmouseout="nextOut()" id="forward">
                    <img src="icons/forward.png" width="40%">
                </div>
            </div>
        </div>
    </div>
</body>
</html>

accent-color: black; won’t work for some reason.
I’m using vanilla JavaScript. This code makes so that the left side’s background color changes only on an input, not automatically while the song is playing.

song.ontimeupdate = function() {
    progress.value = song.currentTime;
}

progress.oninput = function() {
    song.currentTime = progress.value;
}

progress.onchange = function() {
    progress.style.background = `linear-gradient(to right, black 0%, black ${(this.value-this.min)/(this.max-this.min)*100}%, #DEE2E6 ${(this.value-this.min)/(this.max-this.min)*100}%, #DEE2E6 100%)`;
}

I need to change the background of the left side automatically.

Context Load before Client? react-native

i created a context to start up the socket
but before that it validate the token sending a request to the server.
there is an issue that i can’t really figure it out.

if the app is closed and i open it i receive this error
ERROR Error validating token: [TypeError: Cannot read property 'getString' of undefined

if i keep the app open, and i Reload the app i see all the logs and data correctly.

i tried setting up a timeout of 1minute since the app opens and i have no errors.
but this approach is not ok.

so i thought the context loaded before the client actually was actually setted up ? no idea

    useEffect(() => {

        const validateToken = async () => {
            try {
                const { data } = await client.query({
                    query: VALIDATE_TOKEN,
                    fetchPolicy: 'network-only',
                });
                console.log('HEREHEREHERE');
                console.log(data);

                if (data && data.ValidateToken) {
                    setSenderID(data.ValidateToken._id);
                    setSenderUserName(data.ValidateToken.userName);
                    setIsTokenValid(true);
                } else {
                    console.error('Token validation failed');
                    setIsTokenValid(false);
                }
            } catch (error) {
                console.error('Error validating token:', error);
                setIsTokenValid(false);
            }
        };

        validateToken();
    }, []);
import { ApolloClient, HttpLink, ApolloLink } from '@apollo/client';
import { InMemoryCache } from '@apollo/client/cache';
import { storage } from './storage'
import { SERVER } from '@env';

const httpLink = new HttpLink({ uri: `http://${SERVER}:5552/graphql` });
const authLink = new ApolloLink((operation, forward) => {
  const token = storage.getString('UID');
  operation.setContext({
    headers: {
      Authorization: token ? `Bearer ${token}` : '',
    }
  });
  return forward(operation);
});

const client = new ApolloClient({
  //uri: 'http://10.0.2.2:5552/graphql',
  link: authLink.concat(httpLink),
  cache: new InMemoryCache({}),
});

export default client

const Root = () => {
  return (
    <ApolloProvider client={client}>
      <WebSocketProvider>
        <App />
      </WebSocketProvider>
    </ApolloProvider>
  );
};

React & Cypress Component Tests: How to pass an object to an imported library in the Cypress setup?

I’m setting up Cypress to run component tests on a React-based app. The app uses multiple libraries, which I cannot change in any way. Although the app runs perfectly well, I’m unable to get any Cypress tests to run as an object ‘palette’ is not available in one of the libraries, and I get this error message:

(uncaught exception)TypeError: Cannot read properties of undefined (reading 'silver')

This is the code in the library that is failing:

export default ({ palette }: Theme) => ({
  offBackground: palette.colors.silver,
  etc...

I’m using cypress/support/component.js for setting up the configuration, and the component being tested is nested inside a number of context providers:

<I18nContext.Provider value={i18n.english}>
  <ThemeProvider theme={theme}>
    {component}
  </ThemeProvider>
</I18nContext.Provider>

I can import the palette object into the component.js file – is there a way of making it globally available so that it is useable by the library when it is imported?

Vue 3 and Vitest focus input sets document.activeElement to HTMLBodyElement in test in composition API

Given a Vue 3 component

<template>
  <input id="input" type="text" @focus="handleOnFocus($event)" />
</template>
<script setup type="ts">
const handleOnFocus = () => {
  console.log('Component document.activeElement:', document.activeElement)
}
</script>

And test:

import { mount } from '@vue/test-utils'
import { expect } from 'vitest'
import AarghOmg from './AarghOmg.vue'

describe('AarghOmg', () => {
  let wrapper: any

  beforeEach(() => {
    wrapper = mount<typeof AarghOmg>(AarghOmg, {
      attachTo: document.body
    })
  })

  it('outputs activeElement', () => {
    wrapper.find('#input').trigger('focus')

    console.log('Test document.body.innerHTML:', document.body.innerHTML)
    expect(true).toBe(true)
  })
})

console.log

Component document.activeElement: HTMLBodyElement {}
Test document.body.innerHTML: <div data-v-app=""><input id="input" type="text"></div>

I would expect for the document.activeElement to be the input, not the body element. This works correctly in a browser, so is an issue with the wrapper and the test framework.