How do I write a function in node js which is waiting for a completion of an asynchronous call to return the result?

asyncFunc1 is the function I am waiting to complete.

const asyncFunc1 = async (data) => {

  let money = data.money
  let res = {}

  if(data.flag === 1) {
    let calRes = await funcToCalTax(data)
    res.calRes = calRes
  } else {
    let calRes = await funcToCalBonus(data)
    res.calRes = calRes
  }
  return res
}

const mainFunc = (data) => {
  let totAmt = []
  let empList = ['abc', 'def', 'ghi']
  empList.forEach(element => {
    totAmt.push(bonus(element))
  });

  if(data.tempFlag > 0) {
    totAmt.push(asyncFunc1(data))

    if(data.check === true) {
      totAmt.push(func2(data))
    }
  }

  return totAmt
}

Since asyncFunc1 returns a promise mainFunc needs to changed accordingly. I am getting stuck while converting it to accept that promise. This is what I have written for mainFunc:

const mainFunc = (data) => {
  let totAmt = []
  let empList = ['abc', 'def', 'ghi']
  empList.forEach(element => {
    totAmt.push(bonus(element))
  });

  if(data.tempFlag > 0) {

    asyncFunc1(data).then(res => {
      totAmt.push(res)

      if(data.check === true) {
        totAmt.push(func2(data))
      }
    })

    // return totAmt
  }
  return totAmt
}

Where am I going wrong? Return is not waiting for the if part to be completed. How do I change it to return only after the if completes?

Getting a 2D array or Json strip from a page to a controller asp.net core mvc

I need to complete the following task:
There is a table with buttons on the page. Each button is an element of a two-dimensional array. The user selects a radio button and then clicks on the buttons from the table. The button changes its color and gets the corresponding value (0 – red, 1 – green, 2 – orange). I need to transfer these values later to the controller and save them to the database. But I can’t get those values.

model:

    public const int ROW_Free_time = 30;
    
    public const int COL_Free_time = 7;

    

    [NotMapped]
    [JsonIgnore] 
    public int[,] Free_time { get; set; } = new int[COL_Free_time, ROW_Free_time];

    [JsonProperty(nameof(Free_time))] 
    public string Free_timeJson
    {
        get => JsonConvert.SerializeObject(Free_time);
        set => Free_time = JsonConvert.DeserializeObject<int[,]>(value);
    }

page:

<div>
         <p>Indicate available hours:</p>
         <div>
             <div>
                 <p>
                     <span style="color:red"><input type="radio" name="radioValue" value="0" onclick="changeRadioButtonColor(this)" />Busy</span><br />
                     <span style="color:green"><input type="radio" name="radioValue" value="1" onclick="changeRadioButtonColor(this)" />Free time for individual lessons</span><br />
                     <span style="color: orange"><input type="radio" name="radioValue" value="2" onclick="changeRadioButtonColor(this)" />Free time for group classes</span><br />
                 </p>
             </div>

             <p>Class time:</p>
             <table border="1" style="padding:2px;">
                 <thead>
                     <tr>
                         <th></th>
                         <th>Monday</th>
                         <th>Tuesday</th>
                         <th>Wednesday</th>
                         <th>Thursday</th>
                         <th>Friday</th>
                         <th>Saturday</th>
                         <th>Sunday</th>
                     </tr>
                 </thead>
                 <tbody>
                     @for (int i = 0; i < Model.Free_time.GetLength(1); i++)
                     {
                         <tr>
                             <th>@(Math.Floor(8 + (i * 0.5)).ToString("0")):@((i % 2 == 0) ? "00" : "30")</th>

                             @for (int j = 0; j < Model.Free_time.GetLength(0); j++)
                             {
                                 int value = Model.Free_time[j, i];
                                 string color = "";
                                 switch (value)
                                 {
                                     case 0:
                                         color = "red";
                                         break
                                     case 1:
                                         color = "green";
                                         break
                                     case 2:
                                         color = "orange";
                                         break
                                 }

                                 <td>
                                     <input type="hidden" name="FreeTime[@j,@i]" value="@value" />
                                     <input type="button" name="buttonValue" onclick="changeColor(this, @j, @i, @value)" class="centered-button" style="background-color: @color" />

                                 </td>
                             }
                         </tr>
                     }
                 </tbody>
             </table>
         </div>
     </div>

javascript:

function changeRadioButtonColor(radioButton) {
        var selectedColor = radioButton.parentElement.style.color;
        var selectedButton = document.querySelector('input[name="buttonValue"]:checked');
        if (selectedButton) {
            var row = selectedButton.getAttribute('data-row');
            var col = selectedButton.getAttribute('data-col');
            var value = radioButton.value;
            selectedButton.style.backgroundColor = selectedColor;
            
        }
    }


    function changeColor(button, row, col, value) {
var radioButton = document.querySelector('input[name="radioValue"]:checked');
if (radioButton) {
    var selectedColor = radioButton.parentElement.style.color;
    button.style.backgroundColor = selectedColor;

    var input = document.getElementsByName("FreeTime[" + row + "," + col + "]")[0];
    input.setAttribute("value", radioButton.value);

    
}

}

controller:
(I do not know)

    public async Task<IActionResult> AccountEditTutor(Tutor Tutor)
or
public async Task<IActionResult> AccountEditTutor(Tutor Tutor, int[,] FreeTime)

Mouse dragging nodes in D3.js not working after adding boundary restrictions

D3.js mouse dragging event is not working

First question here, so I would be happy if you guys could let me know if I asked the correct way or not.

I am trying to replicate Obsidian‘s (a note taking app) graph view , where you can drag the nodes and also nodes grow bigger when you hover over the mouse button. I am doing this for for another usage case. However, although my first propotype is working completely fine, improved versions stopped working.

Here is the first script’s mouse events, which is working completely fine:

import * as d3 from 'd3';
import * as lil from 'lil-gui';

const parameters = {
  repelForce: -100,
  linkForce: 0.5,
  centerForce: 0.1,
  linkDistance: 30,
  dragConnectedRooms: false,
  display: {
    nodes: true,
    links: true,
    labels: true,
  },
};

const boundaryDimensions = {
  width: 400,
  height: 100,
};

let simulation = null;
const width = 1280;
const height = 720;

let svg = null;

function updateSimulation() {
  if (simulation) {
    simulation
      .force('link', d3.forceLink().id(d => d.id).distance(parameters.linkDistance))
      .force('charge', d3.forceManyBody().strength(parameters.repelForce))
      .force('center', d3.forceCenter(width / 2, height / 2).strength(parameters.centerForce))
      .alpha(1)
      .restart();
  }
}

function drag(simulation) {
  function dragStarted(event) {
    if (!event.active) simulation.alphaTarget(0.3).restart();
    event.subject.fx = event.subject.x;
    event.subject.fy = event.subject.y;
  }

  function dragged(event) {
    event.subject.fx = event.x;
    event.subject.fy = event.y;
  }

  function dragEnded(event) {
    if (!event.active) simulation.alphaTarget(0);
    event.subject.fx = null;
    event.subject.fy = null;
  }

  return d3.drag()
    .on('start', dragStarted)
    .on('drag', dragged)
    .on('end', dragEnded);
}

function updateBoundary() {
  svg.select('.boundary')
    .attr('width', boundaryDimensions.width)
    .attr('height', boundaryDimensions.height)
    .attr('x', (width - boundaryDimensions.width) / 2)
    .attr('y', (height - boundaryDimensions.height) / 2);
}

d3.json('room-data.json').then(data => {
  simulation = d3.forceSimulation(data.nodes)
    .force('link', d3.forceLink(data.links).id(d => d.id).distance(parameters.linkDistance))
    .force('charge', d3.forceManyBody().strength(parameters.repelForce))
    .force('center', d3.forceCenter(width / 2, height / 2).strength(parameters.centerForce));

  svg = d3.create('svg')
    .attr('width', width)
    .attr('height', height)
    .call(d3.zoom().scaleExtent([0.1, 10]).on('zoom', function (event) {
      svg.attr('transform', event.transform);
    }));

  const linkGroup = svg.append('g').attr('class', 'links');
  const nodeGroup = svg.append('g').attr('class', 'nodes');
  const labelGroup = svg.append('g').attr('class', 'labels');

  const boundary = svg.append('rect')
    .attr('class', 'boundary')
    .attr('width', boundaryDimensions.width)
    .attr('height', boundaryDimensions.height)
    .attr('x', (width - boundaryDimensions.width) / 2)
    .attr('y', (height - boundaryDimensions.height) / 2)
    .style('fill', 'none')
    .style('stroke', 'white')
    .style('stroke-width', 1);

  const link = linkGroup
    .selectAll('line')
    .data(data.links)
    .join('line')
    .style('stroke', 'white');

  const node = nodeGroup
    .selectAll('circle')
    .data(data.nodes)
    .join('circle')
    .attr('r', d => Math.sqrt(d.area))
    .style('fill', 'white')
    .call(drag(simulation))
    .on('mouseover', function (event, d) {
      d3.select(this).transition()
        .duration(500)
        .attr('r', Math.sqrt(d.area) * 1.5)
        .style('fill', '#ffd92c');
      label.filter(l => l.id === d.id)
        .transition()
        .duration(500)
        .style('font-weight', 'bold')
        .attr('dy', '2em');
    })
    .on('mouseout', function (event, d) {
      d3.select(this).transition()
        .duration(500)
        .attr('r', Math.sqrt(d.area))
        .style('fill', 'white');
      label.filter(l => l.id === d.id)
        .transition()
        .duration(500)
        .style('font-weight', 'normal')
        .attr('dy', '1.3em');
    });

  const label = labelGroup
    .selectAll('text')
    .data(data.nodes)
    .enter()
    .append('text')
    .text(d => d.name)
    .style('font-family', 'Lato')
    .style('fill', 'white')
    .attr('text-anchor', 'middle')
    .attr('dy', '1.3em');

  simulation.on('tick', () => {
    link
      .attr('x1', d => d.source.x)
      .attr('y1', d => d.source.y)
      .attr('x2', d => d.target.x)
      .attr('y2', d => d.target.y);

    node
      .attr('cx', d => d.x)
      .attr('cy', d => d.y);

    label
      .attr('x', d => d.x)
      .attr('y', d => d.y);
  });

  document.body.appendChild(svg.node());

  const gui = new lil.GUI({ width: 300 });
  gui.add(parameters, 'repelForce', -500, 500).onChange(updateSimulation).name('Repel Force');
  gui.add(parameters, 'linkForce', 0, 2).onChange(updateSimulation).name('Link Force');
  gui.add(parameters, 'centerForce', 0, 1).onChange(updateSimulation).name('Center Force');
  gui.add(parameters, 'linkDistance', 0, 100).onChange(updateSimulation).name('Link Distance');
  gui.add(parameters, 'dragConnectedRooms');
  gui.add(boundaryDimensions, 'width', 100, 400).step(12.5).onChange(updateBoundary).name('Boundary Width (m)');
  gui.add(boundaryDimensions, 'height', 100, 400).step(12.5).onChange(updateBoundary).name('Boundary Height (m)');


  const displayFolder = gui.addFolder('Display Options');
  displayFolder.add(parameters.display, 'nodes').name('Show Nodes').onChange(value => {
    nodeGroup.style('display', value ? 'block' : 'none');
  });
  displayFolder.add(parameters.display, 'links').name('Show Links').onChange(value => {
    linkGroup.style('display', value ? 'block' : 'none');
  });
  displayFolder.add(parameters.display, 'labels').name('Show Labels').onChange(value => {
    labelGroup.style('display', value ? 'block' : 'none');
  });
});

However, as my code became more developed, this function stopped working as I also tried to limit the dragging inside the boundary. Here is the parts related in the developed version:

function drag(simulation) {
  function dragStarted(event) {
    if (!event.active) simulation.alphaTarget(0.3).restart();
    event.subject.fx = event.subject.x;
    event.subject.fy = event.subject.y;
  }

  function dragged(event) {
    const boundaryWidth = parameters.initialInputs.boundaryDimensions.width;
    const boundaryHeight = parameters.initialInputs.boundaryDimensions.height;
    const nodeRadius = Math.sqrt(event.subject.area);

    // Calculate the allowed range within the boundary
    const minX = boundaryX + nodeRadius;
    const minY = boundaryY + nodeRadius;
    const maxX = boundaryX + boundaryWidth - nodeRadius;
    const maxY = boundaryY + boundaryHeight - nodeRadius;

    // Restrict the node's position within the allowed range
    event.subject.fx = Math.max(minX, Math.min(maxX, event.x));
    event.subject.fy = Math.max(minY, Math.min(maxY, event.y));
  }


  function dragEnded(event) {
    if (!event.active) simulation.alphaTarget(0);
    event.subject.fx = null;
    event.subject.fy = null;
  }

  return d3.drag()
    .on('start', dragStarted)
    .on('drag', dragged)
    .on('end', dragEnded);
}
...
  const node = nodeGroup
    .selectAll('circle')
    .data(data.nodes)
    .join('circle')
    .attr('r', d => Math.sqrt(d.area))
    .style('fill', d => colorScale(d.name))
    .call(drag(simulation))
    .on('mouseover', function (event, d) {
      d3.select(this).transition()
        .duration(500)
        .attr('r', Math.sqrt(d.area) * 1.5)
        .style('fill', '#fff');
      label.filter(l => l.id === d.id)
        .transition()
        .duration(500)
        .style('font-weight', 'bold')
        .attr('dy', '2em');
    })
    .on('mouseout', function (event, d) {
      d3.select(this).transition()
        .duration(500)
        .attr('r', Math.sqrt(d.area))
        .style('fill', colorScale(d.name));
      label.filter(l => l.id === d.id)
        .transition()
        .duration(500)
        .style('font-weight', 'normal')
        .attr('dy', '0.3em');
    });

I asked ChatGPT-4 a few times, but it couldn’t identify the issue. I thought it could be related to the forces so I made them 0 but still did not work. Any ideas? Thanks beforehand!

how to resolve the redirection problem into another page in angular

so i am working on a website and i would like to go from the home page to a registration page i am using angular framework, the problem is i can’t even use the href tag in the templates(HTML) for some reason it dosn’t work here is the template code of the home page :

  <div class="col-lg-4 mt-2">
      <div class="stepBox">
        <h1>Nous Rejoindre</h1>
        <p>text</p>
<!--        <button class="info-button"  ></button>-->
       <a href="/register">Rejoindre</a>
      </div>
    </div>

i have tried to follow a lot of tutorial video and website examples but none of them works.
first i have tried to specify more for the file location :

<a href="src/app/register">Rejoindre</a>

and then i tried the routerLink function that comes with angular
this is the app.modules.ts (code):

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import { UserService } from './users.service';
import { HttpClientModule } from '@angular/common/http';
import { FormsModule } from '@angular/forms';
import { HeaderComponent } from './header/header.component';
import {FooterComponent} from "./footer/footer.component";
import {RouterLink, RouterModule, RouterOutlet, Routes} from "@angular/router";
import {HomeComponent} from "./home/home.component";
import {RegisterComponent} from "./register/register.component";
import {AuthentificationComponent} from "./authentification/authentification.component";

const routes: Routes = [
  {
    path:'',component: HomeComponent
  },
  {
    path:'header',component: HeaderComponent
  }
];

@NgModule({
  declarations: [
    AppComponent,
    HeaderComponent,
    FooterComponent,
    HomeComponent,
    RegisterComponent,
    AuthentificationComponent
  ],
  imports: [
    BrowserModule,
    RouterModule.forRoot(routes),
    FormsModule, HttpClientModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

so why even a simple href dosn’t want to work?

Video.currentTIme javascript video curent time set function not work in laravel view.blade.php

This is the code


<!doctype html>
<html lang='en'>
<head>
<meta charset='utf-8'>
<meta name='viewport' content='width=device-width, initial-scale=1'>
<title></title>
<!-- <link rel='stylesheet' href='style.css'> -->
<link href='https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css' rel='stylesheet' integrity='sha384-GLhlTQ8iRABdZLl6O3oVMWSktQOp6b7In1Zl3/Jr59b6EGGoI1aFkw7cmDA6j6gD' crossorigin='anonymous'>
</head>
<body>
   <div class="col-6 right-head gif-head text-center">
      <button onclick="abc()">abc</button>
      <video id="v0" controls preload>
        <source type="video/mp4" src="{{asset('assets/img/mobile.mp4')}}">
      </video>
    </div>
    
    <script>
      function abc() {
        alert('clicked');
        let video = document.getElementById('v0');
    
          video.currentTime = 26;
      }
    </script>
    
</body>
</html>

I stuck to this “video.currentTime = 26” function. This same code I have run in HTML and PHP extension files and it runs properly but in blade.php it’s not working. In other click button it alerts clicked and then set the current time of my video to 26 seconds but in laravel blade it alerts clicked and then nothing happens

How can I create a pop-up in React for individual task checklists?

So I’m creating task-specific checklists that can be unique for each task. I managed to create the popup and inside the popup I can add checklists that can be checked but the tasks don’t retain that checklist, and when I manage to make them retain it it retains it for all tasks not for the specific task I have clicked here is my code, I hope someone can help me figure out what is the problem here:

import React, { useState, useEffect } from 'react';
import {
    Paper,
    Typography,
    IconButton,
    TextField,
    Menu,
    MenuItem,
    Card,
    Dialog,
    DialogTitle,
    DialogContent,
    DialogActions,
    Button,
    FormControlLabel,
    List,
    ListItem,
    ListItemText,
    Grid,
} from '@mui/material';
import useMediaQuery from '@mui/material/useMediaQuery'
import { useTheme } from '@mui/material/styles';
import MoreHorizIcon from '@mui/icons-material/MoreHoriz';
import ExpandMoreIcon from '@mui/icons-material/ExpandMore';
import EmojiEventsIcon from '@mui/icons-material/EmojiEvents';
import Leaderboard from './Leaderboard';
import TodoPopup from './TodoPopup';
import "./TodoList.css";
import CloseIcon from "@mui/icons-material/Close";
import CheckBoxIcon from "@mui/icons-material/CheckBox";
import CheckBoxOutlineBlankIcon from "@mui/icons-material/CheckBoxOutlineBlank";

function TodoList() {
    const defaultTasks = [
        { name: "Learn Angular", category: "inProgress", color: "white", checklist: []},
        { name: "Learn React", category: "inProgress", color: "white", checklist: []},
        { name: "Learn Vue", category: "complete", color: "white", checklist: []},
        { name: "Learn Bootstrap", category: "todo", color: "white", checklist: []}
    ];
    const [tasks, setTasks] = useState(() => {
        const savedTasks = JSON.parse(localStorage.getItem('tasks'));
        return savedTasks || defaultTasks;
    });
    const [anchorEl, setAnchorEl] = useState(null);
    const [newTaskName, setNewTaskName] = useState("");
    const [selectedCategory, setSelectedCategory] = useState("all");
    const [openColorMenu, setOpenColorMenu] = useState(false);
    const [selectedTaskColor, setSelectedTaskColor] = useState([]);
    const [tempSelectedTask, setTempSelectedTask] = useState(selectedTask);
    const [selectedColor, setSelectedColor] = useState("white");
    const [name, setName] = useState("");
    const [open, setOpen] = useState(false);
    const [leaderboardData, setLeaderboardData] = useState([]);
    const [showLeaderboard, setShowLeaderboard] = useState(false);
    //TodoPopup
    const [checklistItem, setChecklistItem] = useState('');
    const [checklist, setChecklist] = useState([]);
    const [checkedItems, setCheckedItems] = useState([]);
    const [selectedTask, setSelectedTask] = useState(null);

    const handleColorSelect = (color,) => {
        setSelectedColor(color);
        const updatedTasks = tasks.map((t) => {
            if (t === selectedTask) {
                return {...t, color: color};
            }
            return t
        })
        setTasks(updatedTasks);
    };
    const handleMenuOpen = (event, t) => {
        setAnchorEl(event.currentTarget);
        setSelectedTask(t);
        setTempSelectedTask(t);
        setSelectedTaskColor(t.color);
    }

    const handleMenuClose = () => {
        setAnchorEl(null);
        setSelectedTask(null);
    }
    const handleMoveTask = (newCategory) => {
        const updatedTasks = tasks.map(task => {
            if (task.name === selectedTask.name) {
                return {...task, category: newCategory, color: selectedColor};
            }
            return task;
        })
        setTasks(updatedTasks);
        handleMenuClose();
    }
    const onDragStart = (ev, id, col) => {
        ev.dataTransfer.setData("id", id);
    }
    const onDragOver = ev => {
        ev.preventDefault();
    }
    const onDrop = (ev, cat) => {
        let id = ev.dataTransfer.getData("id");
        let updateTasks = tasks.map(task => {
            if (task.name === id) {
                return {...task, category: cat, color: task.color};
            }
            return task;
        })
        setTasks(updateTasks);
    }
    useEffect(() => {
        localStorage.setItem('tasks', JSON.stringify(tasks));
    }, [tasks]);

    useEffect(() => {
        const savedTasks = JSON.parse(localStorage.getItem('tasks'));
        if(savedTasks) {
            setTasks(savedTasks);
        }
    }, []);

    const deleteTask = () => {
        setTasks(tasks.filter((task) => task.name !== selectedTask.name));
        handleMenuClose();
    };
    const handleAddTodo = (event) => {
        event.preventDefault();
        const newTodo = {
            id: `task-${tasks.length + 1}`,
            name: newTaskName,
            category: "todo"
        }
        setTasks([...tasks, newTodo]);
        setNewTaskName("");

        if(selectedCategory === "inProgress") {
            setTasks((prevTasks) =>
                prevTasks.map((task) =>
                    task.id === newTodo.id?{...task, category: "inProgress"} : task
                )
            )
        } else if (selectedTask === "complete") {
            setTasks((prevTasks) =>
                prevTasks.map((task) =>
                    task.id === newTodo.id?{...task, category: "complete"} : task
                )
            )
        }
    }

    useEffect(() => {
        const data = JSON.parse(localStorage.getItem("leaderboardData"));
        if(data) {
            setLeaderboardData(data)
        }
    }, []);

    const handleAddToLeaderboard = (name) => {
        const newScore = tasks1.complete.length;
        const newLeaderboardData = JSON.parse(localStorage.getItem("leaderboardData")) || [];
        const limitedName = name.substring(0, 20).trim() || "Anonymous";
        newLeaderboardData.push({ name: limitedName, score: newScore });
        localStorage.setItem("leaderboardData", JSON.stringify(newLeaderboardData));
        setLeaderboardData(newLeaderboardData);
    };
// This is where I get the tasks on click
    const handleTaskClick = (task) => {
        setSelectedTask(task.key);
        setChecklist(task.checklist || []);
    }
    const handlePopupClose = () => {
        setSelectedTask(null);
    }
    //Popup
    const handleAddChecklistItem = () => {
        if (checklistItem.trim() !== '') {
            const newItem = { id: checklist.length, value: checklistItem, checked: false };
            setChecklist((prevChecklist) => [...prevChecklist, newItem]);
            setChecklistItem('');
            setCheckedItems((prevCheckedItems) => [...prevCheckedItems, false]);
        }
    }
    const handleChecklistItemClick = (itemId) => {
        setCheckedItems((prevCheckedItems) =>
            prevCheckedItems.map((checked, index) => (index === itemId ? !checked : checked))
        );
    };

    //
    const theme = useTheme();
    const isMobile = useMediaQuery(theme.breakpoints.down('md'));

    const tasks1 = {
        todo: [],
        inProgress: [],
        complete: []
    };

    const countTasks = () => {
        return (
            <div className="count-tasks-container" onClick={() => setOpen(true)}>
                Completed Tasks
                <Typography variant="div" className="countComplete__tasks">
                    {tasks1.complete.length}
                </Typography>
                <Typography className="count-tasks-tooltip">
                    Join the Leaderboard
                </Typography>
            </div>
        )
    }
    leaderboardData.sort((a, b) => b.score - a.score);
    tasks.forEach((t) => {
        tasks1[t.category].push(
            <div onDragStart={e => onDragStart(e, t.name,)} draggable key={t.name} style={{ marginBottom: "10px"}} >
                <Card key={t.name} style={{ display: "flex", justifyContent: "space-between", backgroundColor: t.color}} >
                    <Typography sx={{ padding: "5px", color: selectedColor !== 'white' ? 'black' : 'inherit', fontWeight: 600 }} >{t.name}</Typography>
                    <IconButton aria-controls="simple-menu" aria-haspopup="true"
                                onClick={(e) => handleMenuOpen(e, t)}
                    >
                        <MoreHorizIcon />
                    </IconButton>
                    <Menu id="simple-menu"
                          anchorEl={anchorEl}
                          open={Boolean(anchorEl && selectedTask === t)}
                          onClose={handleMenuClose}
                    >
                        <MenuItem onClick={() => handleMoveTask("todo")}>Move to Todo</MenuItem>
                        <MenuItem onClick={() => handleMoveTask("inProgress")}>Move in Progress</MenuItem>
                        <MenuItem onClick={() => handleMoveTask("complete")}>Move to Complete</MenuItem>
                        <MenuItem sx={{ display: "flex", justifyContent: "space-between"}} onClick={() => setOpenColorMenu(true)}>
                            <Typography>
                                Color
                            </Typography>
                            <ExpandMoreIcon />
                        </MenuItem>
                        {openColorMenu && (
                            <div style={{ display: "flex", justifyContent: "center", alignItems: "center" }}>
                                {[ "red", "blue", "green", "yellow", "purple", ].map((color) => (
                                    <Typography
                                        variant="div"
                                        key={color}
                                        style={{
                                            backgroundColor: color,
                                            width: 20,
                                            height: 20,
                                            borderRadius: "50%",
                                            margin: "0 10px",
                                            cursor: "pointer",
                                            border: selectedColor === color ? "2px solid white" : "none",
                                        }}
                                        onClick={() => handleColorSelect(color)}
                                    />
                                ))}
                            </div>
                        )}
                        <MenuItem sx={{ color: "red"}} onClick={deleteTask}>Delete</MenuItem>
                    </Menu>
                </Card>
            </div>
        )
    })
    return (
        <div style={{ display: "flex", justifyContent: 'center', height: '100%',  marginTop: isMobile ? '4vh' : '2vh', flexWrap: isMobile ? 'wrap' : 'no-wrap' }}>
            {isMobile && (
                <IconButton onClick={() => setShowLeaderboard(!showLeaderboard)} sx={{position: "absolute", top: "4vh", right: "2vh", backgroundColor: "white" }}>
                    <EmojiEventsIcon sx={{ fontSize: "3rem",}} />
                </IconButton>
            )}
            {showLeaderboard && isMobile && (
                <Leaderboard leaderboardData={leaderboardData} showLeaderboard={showLeaderboard} setShowLeaderboard={setShowLeaderboard} closeLeaderboard={() => setShowLeaderboard(false)} />
            )}
            <Paper
                sx={{ width: isMobile ? '100%' : '400px', height: '600px', mr: isMobile ? '0' : '3vh', mb: isMobile ? '3vh' : '0', display: 'flex', flexDirection: 'column' }}
                onDragOver={e => onDragOver(e)}
                onDrop={e => onDrop(e, "todo")}
            >
                <div className="todo-header">
                    <Typography variant="h4" sx={{ textAlign: 'center', fontWeight: '500'}} >
                        Todo
                        <Typography variant="div" className="todoCount_tasks">
                            {tasks1.todo.length}
                        </Typography>
                    </Typography>
                </div>
                <Typography variant="div" sx={{ fontSize: '20px', overflowY: 'auto', height: '600px'}} >
                    {tasks1.todo.map((task, index) => (
                        <div key={index} onClick={() => handleTaskClick(task)} >
                            {task}
                        </div>
                    ))}
                </Typography>
                <form onSubmit={handleAddTodo} style={{  position: "sticky", bottom: 0, display: "flex", flexDirection: "column", paddingLeft: "5px", paddingRight: "5px" }} >
                    <TextField sx={{ width: '100%', marginBottom: '1vh', height: '100%', background: "white"}} label="New Todo" value={newTaskName} onChange={(e) => setNewTaskName(e.target.value)} />
                </form>
            </Paper>
            <Paper sx={{ width: isMobile ? '100%' : '400px', height: '600px', mr: isMobile ? '0' : '3vh', mb: isMobile ? '3vh' : '0', display: 'flex', flexDirection: 'column'}}
                   onDragOver={e => onDragOver(e)} onDrop={e => onDrop(e, "inProgress")} >
                <div className="todo-header">
                    <Typography variant="h4" sx={{ textAlign: 'center', fontWeight: '500'}} >
                        In Progress
                        <Typography variant="div" className="todoCount_tasks">
                            {tasks1.inProgress.length}
                        </Typography>
                    </Typography>
                </div>
                <Typography variant="div" sx={{ fontSize: '20px', overflowY: 'auto', height: '600px',  }}>
                    {tasks1.inProgress}
                </Typography>
            </Paper>
            <Paper sx={{ width: isMobile ? '100%' : '400px', height: '600px', mr: isMobile ? '0' : '3vh', mb: isMobile ? '3vh' : '0', display: 'flex', flexDirection: 'column' }} onDragOver={e => onDragOver(e)} onDrop={e => onDrop(e, "complete")}>
                <Typography variant="h4" sx={{ textAlign: 'center', fontWeight: '500', }} >
                    {countTasks()}
                </Typography>
                <Typography  variant="div" sx={{ fontSize: '20px', }} >{tasks1.complete}</Typography>
            </Paper>
            {!isMobile && (
                <Paper sx={{ width: '300px', height: '400px', position: 'relative', justifyContent: "flex-end"}}>
                    <div style={{ display: "flex", alignItems: 'center', position: "absolute", top: '10px', left: '10px',}}>
                        <EmojiEventsIcon />
                        <Typography variant="h5" sx={{ display: "inline", textAlign: 'center', ml: "25px"}}>
                            Leaderboard
                        </Typography>
                    </div>
                    <div style={{ alignItems: 'center', textAlign: 'center', marginTop: '50px'}}>
                        {leaderboardData.map((data, index) => (
                            <div key={index} style={{ display: "flex", justifyContent: "space-between" }}  >
                                <Typography variant="h6" sx={{ display: "flex", width: '100%'}} >
                                    { index < 10 ? `${index + 1}. ${data.name}` : ''}
                                </Typography>
                                { index < 10 && (
                                    <Typography variant="subtitle1">{data.score}</Typography>
                                )}
                            </div>
                        ))}
                    </div>
                </Paper>
            )}
            <Dialog open={!!selectedTask} onClose={handlePopupClose} maxWidth="sm" fullWidth >
                <DialogTitle style={{ display: 'flex', alignItems: 'center' }}>
                    <Typography style={{ fontSize: '30px', flex: '1'}} >{selectedTask}</Typography>
                    <IconButton onClick={() => setSelectedTask(null)}>
                        <CloseIcon />
                    </IconButton>
                </DialogTitle>
                <DialogContent>
                    <TextField
                        value={checklistItem}
                        onChange={(e) => setChecklistItem(e.target.value)}
                        label="Add checklist item"
                        fullWidth
                        variant="outlined"
                        margin="normal"
                    />
                    {checklist.map((item, index) => (
                        <div key={index} onClick={() => handleChecklistItemClick(item.id)} style={{ cursor: 'pointer', display: 'flex', alignItems: 'center' }} >
                            {checkedItems[item.id] ? (
                                <CheckBoxIcon fontSize="medium" />
                            ) : (
                                <CheckBoxOutlineBlankIcon fontSize="medium" />
                            )}
                            <Typography variant="body1" component="span" style={{ marginLeft: 5, fontSize: '20px' }}>
                                {item.value}
                            </Typography>
                        </div>
                    ))}
                </DialogContent>
                <DialogActions>
                    <Button onClick={handleAddChecklistItem}>Add</Button>
                </DialogActions>
            </Dialog>
        </div>
    )
}

export default TodoList;

I’m trying to trying to make a popup that can add checklists for each task individually.

HTML user input for snake game

HTML Input Help for Snake Game

  <h3>Snake</h3>
        <div class="setting">
          <label for="snakeColor">Body Color</label>
          <input 
            type="color" 
            name="snakeColor" 
            id="snakeColor"
            onchange="updateSnakeColor(this.value)"
            value="#008000"
          >
        </div>
        <div class="setting">
          <label for="snakeHeadColor">Head Color</label>
          <input type="color" name="snakeHeadColor" id="snakeHeadColor"
          onchange="updateSnakeHeadColor(this.value)"
          value="#006400">

        </div>

I am currently using this code to have the user change the color of the snakes body and head on my snake game website. I am looking for a way to make the color of the head a darker shade of whatever body color the user chooses instead of giving them 2 separate options.

Any ideas on how I would do such a thing?

Inconsistent behavior of innerHTML for HTMLStyleElement

In most cases the value of an HTMLStyleElement is the source CSS string. For example, for an element <style>body > #myid</style> the innerHTML property is body > #myid, which equals to the textContent property.

However, it seems that sometimes the innerHTML property returns an HTML-escaped string instead, i.e. body &gt; #myid in the above case. An instance I have encountered is a page in reddit.com. For example, the <style class="" data-href="chunkCSS/CommentsPage.c74e9c3aba90ae40d351_.css">...</style> in page https://www.reddit.com/r/DataHoarder/ (login required, tested on Firefox 113.0.2 and Google Chrome 113.0.5672.127).

The inconsistency breaks the code in various cases. I’d like to know why it happens, when will it happen, and whether there is a way to fix it?

Sveltekit is not intercepting fetch call in handleFetch hook

I recently discovered the handleFetch hook in Sveltekit. Now I’m trying to use it to intercept calls to my backend (written in Go) but doesn’t seem to work (unless I’m missing something).

The documentation reads:

This function allows you to modify (or replace) a fetch request that happens inside a load or action function that runs on the server (or during pre-rendering).

I’ve got srchooks.server.js:

/** @type {import('@sveltejs/kit').HandleFetch} */
export async function handleFetch({ request, fetch }) {
    console.log("HERE IN --------> HANDLE FETCH HOOK")

    return fetch(request);
}

As you can see I’m just trying to make sure the hooks is called by printing a message on the terminal.

I’ve got a load function in srcroutesrecords+page.server.js:

export async function load() {
    console.log("HERE IN LOAD")
    // const records = await getAllRecords(1, 10);
    const response = await fetch(`http://127.0.0.1:8080/api/v1/records?page=1&per_page=2`);
    const records = await response.json();
    console.log(await records);
    return records;
}

Although I see the HERE IN LOAD message and the response being printed I never see the message that indicates that the hook was hit.

What am I missing?

Thanks

Vue2 prerender-spa-plugin – all generated index.html files have the same root content after build

I have a working Vue 2 project. I wanted to add the prerender feature to that project. I, therefore, installed the prerender-spa-plugin and did some necessary configurations in the vue.config.js file. I added a couple of routes (eg: home and about) for prerendering. When I build the project a separate folder for about is getting created, but unfortunately, the index.html file inside the about folder has the same content as the root index.html.

Sharing the related references of my project:

// vue.config.js
const path = require('path')
const PrerenderSpaPlugin = require('prerender-spa-plugin')

const productionPlugins = [
  new PrerenderSpaPlugin({
    staticDir: path.join(__dirname, 'dist'),
    routes: ['/', '/about']
  })
]

module.exports = {
  transpileDependencies: [
    'vuetify'
  ],
  configureWebpack: (config) => {
    if (process.env.NODE_ENV === 'production') {
      config.plugins.push(...productionPlugins)
    }
  },
  chainWebpack: config => {
    config.module
      .rule('pdf-loader')
      .test(/.pdf$/)
      .use('file-loader')
      .loader('file-loader')
      .end()
  }
}
// routes.js
export default [
  {
    path: '',
    component: resolve => require(['@/views/PublicSite/Home/Index.vue'], resolve),
    meta: { title: '' }
  },
  {
    path: '/about',
    name: 'about',
    component: resolve => require(['@/views/PublicSite/About.vue'], resolve),
    meta: { title: 'About' }
  }
}
// App.vue
<template>
  <v-app>
    <v-main class="primary darken-4">
      <router-view></router-view>
    </v-main>
  </v-app>
</template>
// About.vue
<template>
  <div>
    This is the About page.
  </div>
</template>
// index.html
<html lang="en" style="overflow: hidden">
  <head>
    ...
  </head>
  <body>
    <div id="app"></div>
    <!-- built files will be auto-injected -->
  </body>
</html>
// package.json
...
  "devDependencies": {
    "@mdi/font": "^5.9.55",
    "@vue/cli-plugin-eslint": "~4.5.0",
    "@vue/cli-plugin-pwa": "~4.5.0",
    "@vue/cli-plugin-router": "~4.5.0",
    "@vue/cli-plugin-vuex": "~4.5.0",
    "@vue/cli-service": "~4.5.0",
    "@vue/eslint-config-standard": "^5.1.2",
    "node-sass": "^4.12.0",
    "prerender-spa-plugin": "^3.4.0",
    "sass": "~1.32.6",
    "sass-loader": "^10.0.0",
    "vue-cli-plugin-vuetify": "~2.4.0",
    "vue-template-compiler": "^2.6.11",
    "vuetify-loader": "^1.7.0"
  }
...

I need a suggestion on what wrong I am doing in the configuration.

PS: I had done some hands-on on a new Vue 2 project with webpack-simple.

need your assistance to run the redux app

Please help me to solve the error what I am facing when it’s running the code ..

Unable to solve this problem.. tried out my best..

I’ve also added import to import the required elements. I’m just learning on the other platform.. just got stuck after getting some errors even tried out.

I’ve just mentioned as same as I have got it from StackBlitz.. Why I’m facing this error..



<!DOCTYPE html>

<html>

    <head>

        <title>Page Title</title>

          <script src="https://unpkg.com/react@16/umd/react.development.js" crossorigin></script>

        <script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js" crossorigin>

        </script>

        <script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script> 

    </head>

    <body>

      <div id="root"></div>

      <script type="text/babel">

      import React from 'react';

      import {Provider} from 'react-redux';

      import {createStore} from 'redux';

      import {connect} from 'react-redux';

      

          function incrementCounter(num) {

              return {

                  type: 'INCREMENT',

                  num: num

              }

            }

          const initialState  = {

              count: 0

          };

          

          function reducer(state= initialState, action) {

              switch(action.type) {

                case 'INCREMENT': 

                  return { count: state.count + action.num  }

                default:

                  return state

           }

          

          }

          

          let counter = (props) => {

              function handleClick() {

                  props.incrementCounter(1);

              }

              

              return 

                  <div>

                    <p>{props.count}</p>

                    <button onClick={handleClick}>Increment</button>

                  </div>;

          }

          

          function mapStateToProps(state) {

              return {

                  count: state.count

              };

          }

          

          const mapDispatchToProps = {

              incrementCounter 

          }

          

           let store = createStore(reducer);

          

           Counter = connect(mapStateToProps, mapDispatchToProps)(Counter);

          

          ReactDOM.render(

             <Provider store={store}>

              <Counter/>

             </Provider>,

            document.getElementById("root")

          );

      </script>

    </body>

</htmerror showing.. similar to the image..l>