What is the best way to passing authentication information to an iFrame

I have the case where I need to embed an iFrame into my page. The iFrame loads another page from the same domain and makes REST calls that require authentication.

The login procedure is handled in the main page and results in an access token. I need to pass the access token to the page loaded inside the iFrame. I thought of the following solutions:

  1. Store in a cookie: Would work since the domain is the same but storing access tokens in cookies is bad practice.
  2. Pass as URL param to the page in the iFrame: This feels insecure. URLs might be logged and are just too easily accessible that way.
  3. Pass via message API: I can’t find any flaws here but have not read a lot about this solution.

I try to keep the procedure between the two webpages.

Is any of these solutions viable or is an additional authentication authorization the only “right” way?

Blazor WASM client and loading of javascript files

I am debugging my WASM client and using a few javascript files. Not all of them get loaded into the browser every time, and there is a pattern to this:

The first time I use a certain browser, like Chrome, it loads the javascript files it finds. And it updates them when I update them. But if add another javascript file, it doesn’t seem to pick up on it automatically. I have do a ctrl-F5 to get this latest file. And I have to do it every single time.

But if I use a different browser, that has never had this app loaded in, it finds all of the files and updates them as expected. But if I add another file, then same problem. If it wasn’t in the wwwroot when I first used the browser, it never seems to get included automatically.

To avoid null/undefined references: when to use a Safe Navigation Operator (?.) and when to use a Logical AND (&&) operator?

Consider that I have an array of objects property (say arrThatCouldBeNullOrUndefined: SomeType[]) in my angular component.

I want to perform some array operation (say filter() operation) on it and store the value in some other property (say filteredArr: SameType[]) as shown below

this.filteredArr = this.arrThatCouldBeNullOrUndefined.data.filter(item => this.someFilterCondition(item));

To avoid any TypeErrors (i.e., any undefined or null references) I could choose either of the below approches to write the code.

Approach 1: Use a Safe operator (?.)

this.filteredArr = this.arrThatCouldBeNullOrUndefined?.data?.filter(item => this.someFilterCondition(item));

or

Approach 2: Use logical and operator (&&)

if(this.arrThatCouldBeNullOrUndefined && this.arrThatCouldBeNullOrUndefined.data) {
    this.filteredArr = this.arrThatCouldBeNullOrUndefined.data.filter(item => this.someFilterCondition(item))
}

My Queries:

  1. When should we use the either of the approaches?
  2. Which approach is the best to follow (or avoid) by default?

Failed to minify file main 1.js: ENOENT: no such file or directory

I received an error because of this code. Can I ask for some help how to fix this? Thank you.

for (const file of data_to_minify) {
  try {
    
      const [error, minifiedContent] = await tryToCatch(minify, file.file.filename, options);

      if (error) {
          console.error(`Failed to minify file ${file.file.filename}: ${error.message}`);
          continue;
      }

      fs.writeFileSync(file.file.filename);

      minifiedFiles.push({
          filename: file.file.filename,
          content: minifiedContent,
          type: file.type
      });
  } catch (error) {
      console.error(`Failed to process file ${file.file.filename}: ${error}`);
  }
}

image of error

Apexcharts curve smooth causes “time warp” (type datetime)

I use Apexcharts to generate this chart. The x axis is of type datetime. The data points are correct, however, when I set the stroke curve: "smooth", the chart gets this weird time warp where it goes “back in time” with the line even though my data is in chronological order. Why is that?

enter image description here

I use next.js and react-apexcharts:

let state = {
    options: {
        chart: {
            height: 250,
            toolbar: {
                show: true,
                offsetX: 0,
                offsetY: 0,
                tools: {
                    download: true,
                    selection: false,
                    zoom: false,
                    zoomin: false,
                    zoomout: false,
                    pan: false,
                    reset: false,
                    customIcons: [],
                },
            },
        },
        xaxis: {
            type: 'datetime',
            min: moment(moment(startDate).format("YYYY-MM-DD") + " " + settings.wake_up_time).unix() * 1000,
            max: moment(moment(endDate).format("YYYY-MM-DD") + " " + settings.bed_time).unix() * 1000,
            labels: {
                datetimeFormatter: {
                    year: 'YYYY',
                    month: 'MMM 'yy',
                    day: 'ddd',
                    hour: 'HH:mm'
                },
                style: {
                    colors: 'hsl(var(--muted-foreground))',
                },
                datetimeUTC: false, // Do not convert to UTC
            },
        },
        yaxis: {
            labels: {
                formatter: function (val) {
                    return val.toFixed(0);
                },
                style: {
                    colors: 'hsl(var(--muted-foreground))',
                },

            },
            tickAmount: 5, // only 6 labels
            min: 0,
            max: 10
        },
        noData: {
            text: "No data yet...",
        },
        dataLabels: {
            enabled: false,
        },
        stroke: {
            curve: 'smooth',
        },
        colors: ['hsl(var(--accent))'],
        tooltip: {
            theme: settings.theme === 0 ? "dark" : "light",
            x: {
                show: true,
                format: 'dd.MM.yy HH:mm',
            },
            y: {
                formatter: function (val) {
                    return val.toFixed(1)
                },
            },
            z: {
                title: "Activities:",
            }
        },
        grid: {
            borderColor: 'hsl(var(--border))',
        }
    },
    series: [{
        name: 'Energylevel',
        data: data,
    }],
    type: "area",
}

return (
    <Chart options={state.options} series={state.series} type={state.type} height={320} width="100%" />
)

data:

[
    {
        "x": "2024-01-05 08:15",
        "y": 8,
        "z": ""
    },
    {
        "x": "2024-01-05 09:00",
        "y": 5,
        "z": ""
    },
    {
        "x": "2024-01-05 09:30",
        "y": 7.5,
        "z": ""
    },
    {
        "x": "2024-01-05 10:00",
        "y": 6.5,
        "z": ""
    },
    {
        "x": "2024-01-05 10:30",
        "y": 7,
        "z": ""
    },
    {
        "x": "2024-01-05 12:00",
        "y": 4.5,
        "z": ""
    }
]

How to obtain only important timezones and their UTC offset from moment-timezone rather than all 596 timezones?

I am using the moment-timezone to obtain the zones and their respective UTC offset within the Nuxt 3 application. Everything is working as expected but the library returns me with 596 timezones which I feel is too much to use within the application as I am using these timezones to populate the Select dropdown field.

Is there a way I can get only important timezones rather than all the timezones? Because I see that there are few duplication of the timezone offset so I tried to remove the duplications but this makes some of the timezone names to miss out:

Following is the approach I am using:

import moment from "moment-timezone";
const timezones = ref([]);

const getTimezonesWithOffset = () => {
  const zones = moment.tz.names();
  let offsetTmz = [];

  for (let i in zones) {
    const offset = `(GMT${moment.tz(zones[i]).format("Z")})`;
    const offsetObj = { text: zones[i], value: offset };
    offsetTmz.push(offsetObj);
  }

  timezones.value = offsetTmz.sort();
};

onMounted(async () => {
  await getTimezonesWithOffset();
  console.log(timezones.value.length);
  console.log(JSON.stringify(timezones.value, null, 4));
});

I tried to filter for unique offset:

if (!uniqueOffsets.has(offset)) {
        uniqueOffsets.add(offset);
        formattedTimezones.push(`${zone} - ${offset}`);
      }

But using this approach will miss out on some of the zone names but able to get unique UTC offset. I would like to know if there is a way to obtain only the most used or important timezones rather than all the zones using the moment-timezone library or is there any better library which i can use for getting only important zones.

NEXT JS: .env variable undefiend

I just migrated my app from React JS to NEXT JS but for some reason my environment variables are undefined, tho they worked fine in React. Can anyone assist me please?

_app.js

    const [apikey, setApikey] = useState(process.env.REACT_APP_API_KEY)
    useEffect(() => {
    console.log(apikey)
    }, [])

.env

    REACT_APP_API_KEY=myapikey

How to set selection of whole row in silevis/reactgrid from context menu?

I need to select whole row (or multiple rows) from the right click context menu.
Is there a possibility to do that in @silevis/reactgrid ?

There is option to select whole row
enableRowSelection
by clicking the first cell from the row but it is not what I need.
I want exactly the same function to run from right click context menu.

If there is available function to set selection range – it will be also helpful because I can pass there row index and first and last column of the row.

Any ideas ??


Rafal

Cursor moves Component from distance

Problem IMAGE

var isGameStarted = false; // Variable pour suivre si le jeu a démarré
var isMouseDown = false;

var container, startPoint;

function initializeGame() {
    container = document.getElementById("first_div"); 
    startPoint = document.getElementById("start");
    document.getElementById("start").addEventListener("click", startGame);
    

    startPoint.addEventListener("mousedown", function (event) {
        isMouseDown = true;

        // Store the initial mouse coordinates relative to the container
        initialMouseX = event.clientX - container.offsetLeft;
        initialMouseY = event.clientY - container.offsetTop;

        // Store the initial position of the start element relative to the container
        initialStartX = startPoint.offsetLeft;
        initialStartY = startPoint.offsetTop;

        // Prevent default to avoid unwanted text selection
        event.preventDefault();
    });
}


function startGame() {
    isGameStarted = true;

    // Ajoutez un écouteur d'événements pour suivre le mouvement de la souris sur l'ensemble du document
    document.addEventListener("mousemove", moveStartPoint);

    // Changez la couleur des éléments avec la classe "walls" en vert
    var wallElements = document.getElementsByClassName("walls");
    for (var i = 0; i < wallElements.length; i++) {
        wallElements[i].style.backgroundColor = "green";
    }

    // Changez le texte de l'élément avec l'id "description"
    var descriptionElement = document.getElementById("description");
    descriptionElement.innerHTML = "<b>Trouver la sortie</b>";
}
function moveStartPoint(event) {
    if (isGameStarted && isMouseDown) {
        var mouseX = event.clientX - container.offsetLeft;
        var mouseY = event.clientY - container.offsetTop;

        // Calculate the new position of the start element directly under the cursor
        var newStartX = mouseX - initialMouseX + initialStartX;
        var newStartY = mouseY - initialMouseY + initialStartY;

        // Check boundaries to keep the start element within the walls
        var minX = 0;
        var minY = 0;
        var maxX = container.offsetWidth - startPoint.offsetWidth;
        var maxY = container.offsetHeight - startPoint.offsetHeight;

        newStartX = Math.max(minX, Math.min(newStartX, maxX));
        newStartY = Math.max(minY, Math.min(newStartY, maxY));

        // Update the position of the start element
        startPoint.style.left = newStartX + "px";
        startPoint.style.top = newStartY + "px";

        checkCollisions();
    }
}


document.getElementById("start").addEventListener("mousedown", function () {
    isMouseDown = true;
});

document.addEventListener("mouseup", function () {
    isMouseDown = false;
});

       
    

function checkCollision(element1, element2) {
    var rect1 = element1.getBoundingClientRect();
    var rect2 = element2.getBoundingClientRect();

    return (
        rect1.left < rect2.right &&
        rect1.right > rect2.left &&
        rect1.top < rect2.bottom &&
        rect1.bottom > rect2.top
    );
}

function checkCollisions() {
    var startPoint = document.getElementById("start");
    var wallElements = document.getElementsByClassName("walls");

    for (var i = 0; i < wallElements.length; i++) {
        if (checkCollision(startPoint, wallElements[i])) {
            // Collision détectée, changer la couleur en rouge et le texte
            wallElements[i].style.backgroundColor = "red";
            var descriptionElement = document.getElementById("description");
            descriptionElement.innerHTML = "<b>Désolé, vous avez perdu</b>";
            isGameStarted = false; // Arrêter le jeu en cas de collision
            document.removeEventListener("mousemove", moveStartPoint); // Supprimer l'écouteur d'événements de la souris
            break; // Sortir de la boucle, car la collision a été détectée
        }
    }
}



// Appelez la fonction d'initialisation lors du chargement de la page
window.onload = initializeGame;

Hi guys, appreciate the help. I’m expecting to move the component S (start) with my cursor and to both move n the same direction at the same time. But when I click on the component, it deplaces under the cursor !! I don’t know how to fix it. Please help. the img shows exactly what the problem is.

javascript onchange not placing a correct value when form is submitted

I have a default input form having ID = Form_state, this javascript code is placing a select element on top of it. Its doing what its supposed to do but when I submit the form, the value is not submitted to Input #Form_St

It is showing the value on select, but when you inspect element the #Form_State no value is placed.

// Sample data for options
var stateOptions = [{
"AL":"Alabama",
"AK":"Alaska",
"AZ":"Arizona",
"AR":"Arkansas",
"CA":"California",
"CO":"Colorado",
"CT":"Connecticut",
"DC":"District of Columbia",
"DE":"Delaware",
"FL":"Florida",
"GA":"Georgia",
"HI":"Hawaii",
"ID":"Idaho",
"IL":"Illinois",
"IN":"Indiana",
"IA":"Iowa",
"KS":"Kansas",
"KY":"Kentucky",
"LA":"Louisiana",
"ME":"Maine",
"MD":"Maryland",
"MA":"Massachusetts",
"MI":"Michigan",
"MN":"Minnesota",
"MS":"Mississippi",
"MO":"Missouri",
"MT":"Montana",
"NE":"Nebraska",
"NV":"Nevada",
"NH":"New Hampshire",
"NJ":"New Jersey",
"NM":"New Mexico",
"NY":"New York",
"NC":"North Carolina",
"ND":"North Dakota",
"OH":"Ohio",
"OK":"Oklahoma",
"OR":"Oregon",
"PA":"Pennsylvania",
"RI":"Rhode Island",
"SC":"South Carolina",
"SD":"South Dakota",
"TN":"Tennessee",
"TX":"Texas",
"UT":"Utah",
"VT":"Vermont",
"VA":"Virginia",
"WA":"Washington",
"WV":"West Virginia",
"WI":"Wisconsin",
"WY":"Wyoming"
}];

// Function to create and insert the select element
function createSelectElement(options, insertBeforeId) {
    // Create select element
    var selectElement = document.createElement("select");
    selectElement.style.position = 'absolute';
    selectElement.style.top = '20px';
    selectElement.style.left = '0';
    selectElement.style.width = '100%';
    selectElement.style.height = '25px';
    selectElement.style.lineHeight = '20px';
    selectElement.style.margin = '0';
    selectElement.style.padding = '0';
    selectElement.style.border = '0';
    
    var selectedState = "document.getElementById('form_state').value=this.options[this.selectedIndex].text";

    selectElement.setAttribute("onchange", "document.getElementById('form_state').value=this.options[this.selectedIndex].text; "+selectedState+"; alert("+selectedState+");")

    selectElement.id = "stateSelect";

    // Iterate over options and create option elements
    options.forEach(function (state) {
        for (var key in state) {
            var option = document.createElement("option");
            option.value = key;
            option.text = state[key];
            selectElement.appendChild(option);
        }
    });

    // Find the element to insert before
    var insertBeforeElement = document.getElementById(insertBeforeId);

    // Insert the select element before the specified element
    insertBeforeElement.parentNode.insertBefore(selectElement, insertBeforeElement);
}

// Call the function to create and insert the select element
createSelectElement(stateOptions, "form_state");
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Select Element Example</title>
</head>
<body>

<!-- Your form elements -->
<select id="stateSelect" style="position:absolute;top: 21px;left: 0;width: 100%;height: 25px;line-height:20px;margin:0;padding:0;border: 0;" onchange="updateFormState()">
</select>

<input type="text" id="form_state" placeholder="Selected State">

</body>
</html>

Can Microfrontend using Module Federation Plugin be in different repos?

I am looking at developing a Microfrontend app by having a container/host app and various child apps (all are based on ReactJS, but just divided based on functionaility).
The idea is to get the benefit of independent build/deployments, etc and avoiding code conflicts between different teams working on different modules.

So my question is can Microfrontend implementation using Module Federation Plugin be in different repos ?

The examples I have seen are mostly the child apps are in the same repo, just that they are in a directory/folder of their own (e.g. child1, child2, etc)

Why jquery is not loaded from vite in my blade view?

I made a simple blade view:

<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title> @yield('title') | MY APP</title>
        @vite([
            'resources/css/style.css',
            'node_modules/bootstrap/dist/css/bootstrap.css',
            'node_modules/@fortawesome/fontawesome-free/css/all.css'
           ])
</head>
<body>
<nav id="deltaNavbar">
    <div class="logoContainer "><a href="{{ url('/') }}"><img src="{{ url('/logo.png')  }}"></a>  </div>
</nav>

@section('main')
@show

    @vite([
            'node_modules/jquery/dist/jquery.js',
            'node_modules/bootstrap/dist/js/bootstrap.bundle.js',
            'resources/js/main.js'
           ])
</body>
</html>

That is loaded via this route:

Route::get('/', function () {
    return view('main');
});

And I install jquery, bootstrap and font-awesome via npm:

{
    "private": true,
    "scripts": {
        "dev": "vite",
        "build": "vite build"
    },
    "devDependencies": {
        "axios": "^1.1.2",
        "laravel-vite-plugin": "^0.7.2",
        "vite": "^4.0.0"
    },
    "dependencies": {
        "@fortawesome/fontawesome-free": "^6.5.1",
        "bootstrap": "^5.3.2",
        "dotenv": "^16.3.1",
        "jquery": "^3.7.1",
        "nodejs": "^0.0.0"
    }
}

I did the nessesary installations as well:

npm install

And I used this vite.config.js:

import { defineConfig } from 'vite';
import laravel from 'laravel-vite-plugin';

export default defineConfig({
    plugins: [
        laravel({
            input: [
                'resources/css/style.css',
                'resources/js/main.js',
                'node_modules/jquery/dist/jquery.js',
                'node_modules/bootstrap/dist/js/bootstrap.bundle.js',
                'node_modules/bootstrap/dist/css/bootstrap.css',
                'node_modules/@fortawesome/fontawesome-free/css/all.css'
            ],
            refresh: true,
        }),
    ],
});

But once I run npm build and visit the homepage I get the following error:

Unable to locate file in Vite manifest: node_modules/jquery/dist/jquery.js.

Any idea why that does happen? I have no indication why.