How can I implement changing of a task, when the user clicks the button Save?

When the user clicks the ‘Edit’ button, the input field opens, allowing the user to type their new task. However, I’m unable to implement saving these changes when the user clicks the ‘Save’ button. Currently, when the user clicks ‘Save,’ the previous task is saved, but the new task disappears.

import { ADD_TASK, REMOVE_TASK, UPDATE_TASK } from "../actionsTypes";
import { v4 as uuidv4 } from "uuid";

export const initialState = {
  tasklist: [], //tasklist
};

export function taskReducer(state = initialState, action) {
  switch (action.type) {
    case ADD_TASK:
      return {
        ...state,
        tasklist: [
          ...state.tasklist,
          {
            id: uuidv4(),
            title: action.payload,
            isCompleted: false,
            isEditing: false,
            status: "To do",
            number: state.tasklist.length + 1,
          },
        ],
      };

    case REMOVE_TASK:
      return {
        ...state,
        tasklist: state.tasklist.filter((todo) => action.payload !== todo.id),
      };

    case UPDATE_TASK:
      return {
        ...state,
        tasklist: state.tasklist.map((prevTask) =>
          prevTask.id === action.payload.id
            ? { ...prevTask, title: action.payload.newTitle }
            : prevTask
        ),
      };

    default:
      return state;
  }
}
import React, { useState } from "react";
import "./Task.css";
import Button from "@mui/material/Button";
import DeleteIcon from "@mui/icons-material/Delete";
import EditIcon from "@mui/icons-material/Edit";
import { useDispatch } from "react-redux";
import { updateTask } from "../../store/actions";

const Task = ({ task, onDelete }) => {
  const [isEditing, setIsEditing] = useState(false);
  const [inputValue, setInputValue] = useState(task.title);
  const dispatch = useDispatch();

  const onEdit = () => {
    setIsEditing(!isEditing);
  };

  const onSaveClicked = (title) => {
    dispatch(updateTask(title.id, inputValue));
    setIsEditing(!isEditing);
  };

  return (
    <li>
      {isEditing ? (
        <input
          id="edittask"
          type="text"
          value={inputValue}
          onChange={(e) => {
            // const newName = e.target.value; // setInputValue
            // dispatch(updateTask(task.id, newName));
            setInputValue(e.target.value);
          }}
        />
      ) : (
        <>
          {task.number}
          <p>{task.title}</p>
          {task.isCompleted}
          {task.status}
        </>
      )}
      {!isEditing ? (
        <Button onClick={onEdit} variant="outlined" endIcon={<EditIcon />}>
          Edit
        </Button>
      ) : (
        <Button onClick={onSaveClicked} variant="outlined">
          Save
        </Button>
      )}
      <Button onClick={onDelete} variant="outlined" endIcon={<DeleteIcon />}>
        Remove
      </Button>
    </li>
  );
};

export default Task;
import { ADD_TASK, REMOVE_TASK, UPDATE_TASK } from "./actionsTypes";

export const addTask = (title) => ({
  type: ADD_TASK,
  payload: title, //title
});

export const removeTask = (id) => ({
  type: REMOVE_TASK,
  payload: id,
});

export const updateTask = (id, title) => ({
  type: UPDATE_TASK,
  payload: { id, newName: title },
});
import React from "react";
import InputTask from "../InputTask/InputTask";
import HeaderOfTaskList from "../HeaderOfTaskList/HeaderOfTaskList";
import Task from "../Task/Task";
import { useDispatch, useSelector } from "react-redux";
import { removeTask, addTask } from "../../../redux/store/actions";
import "./TaskList.css";

export const TaskList = () => {
  const dispatch = useDispatch();
  const task = useSelector((state) => state.tasklist);

  const handleDelete = (id) => {
    dispatch(removeTask(id));
  };

  const handleAddTask = (tasklist) => {
    dispatch(addTask(tasklist));
  };

  return (
    <div>
      <InputTask addTask={handleAddTask} />
      <HeaderOfTaskList />
      <ul>
        {task.map((task) => (
          <Task
            task={task}
            key={task.id}
            onDelete={() => handleDelete(task.id)}
          />
        ))}
      </ul>
    </div>
  );
};

I have the above snippets of code

Need to click button using accessibility service

I attempted to use the accessibility service to click a button on the node below. The node is clickable, and it clicks only first time, even when I manually write text in the textfield, but not when I enter text using code. I can’t find the issue; please provide a solution.

Node :
[androidx.core.view.accessibility.AccessibilityNodeInfoCompat@81f3a; boundsInParent: Rect(0, 0 – 87, 62); boundsInScreen: Rect(585, 953 – 672, 1015); packageName: com.example.android; className: android.widget.TextView; text: Send; contentDescription: null; viewId: null; checkable: false; checked: false; focusable: true; focused: false; selected: false; clickable: true; longClickable: false; enabled: true; password: false; scrollable: false; [ACTION_FOCUS, ACTION_SELECT, ACTION_CLEAR_SELECTION, ACTION_CLICK, ACTION_ACCESSIBILITY_FOCUS, ACTION_NEXT_AT_MOVEMENT_GRANULARITY, ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY, ACTION_SET_SELECTION, ACTION_SHOW_ON_SCREEN]]

Refer code :

       if (getRootInActiveWindow() == null) {
           return;
       }
       AccessibilityNodeInfoCompat rootInActiveWindow = AccessibilityNodeInfoCompat.wrap(getRootInActiveWindow());

       new Handler().postDelayed(() -> {
           List<AccessibilityNodeInfoCompat> replyNode = rootInActiveWindow.findAccessibilityNodeInfosByViewId("com.example.android:id/comments");
           if (!replyNode.isEmpty() && !isreply1) {
               System.out.println("Found nodes:" + replyNode);
               System.out.println("Number of nodes:" + replyNode.size());
                   AccessibilityNodeInfoCompat replybtnNode = replyNode.get(0);
                   replybtnNode.performAction(AccessibilityNodeInfo.ACTION_CLICK);
               isreply1 = true;
           } else {
               System.out.println("No nodes found");
           }
       }, 6000);


       new Handler().postDelayed(() -> {
               AccessibilityNodeInfoCompat replyNode2 = rootInActiveWindow.findAccessibilityNodeInfosByViewId("com.example.android:id/comments_input").get(0);
               if (!isreply2) {
                   System.out.println("Input field");
                   replyNode2.performAction(AccessibilityNodeInfo.ACTION_FOCUS);
                   replyNode2.performAction(AccessibilityNodeInfo.ACTION_CLICK);
                   String commentText = "Nice";
                   Bundle arguments = new Bundle();
                   arguments.putCharSequence(
                           AccessibilityNodeInfoCompat.ACTION_ARGUMENT_SET_TEXT_CHARSEQUENCE,
                           commentText
                   );
                   replyNode2.performAction(AccessibilityNodeInfoCompat.ACTION_SET_TEXT, arguments);
                   isreply2 = true;
               }
       }, 9000);


     new Handler().postDelayed(() -> {
         List<AccessibilityNodeInfoCompat> replyNode3 = rootInActiveWindow.findAccessibilityNodeInfosByText("Send");
         if (!replyNode3.isEmpty()) {
             System.out.println("Found reply nodes:" + replyNode3);
             System.out.println("Number of reply nodes:" + replyNode3.size());
             AccessibilityNodeInfoCompat replybtnNode2 = replyNode3.get(0);
             replybtnNode2.performAction(AccessibilityNodeInfo.ACTION_CLICK);
         } else {
             System.out.println("No reply nodes found");
         }
   }, 12000);
}```

Thanks in advance !!!

how to detect whether website is running in “android Custom Tabs” or “Safari View Controller”

This is question talks about those mentioned techniques:
Android equivalent of iOS’ SFSafariViewController

There is browser windows that open within the app:

  1. IOS: SFSafariViewController
  2. Android: Chrome Custom Tabs

My website unfortunately only functions in a fully opened browser app. A lot of my users enter my app through either of the two above mentioned in-app-browser-windows. If they did, I want to notify my users of that, since they would be experiencing a broken website, that they should switch to the actual safari/chrome app.

I am actually using the Ionic Framework in my website, but I don’t think the Platform.is() includes any method to detect this.

How do I detect this? Maybe through user agent or something similar?

DOM not update properly on removing items from top or middle angular FormArray reactive forms – angular17

I’ve tried to implement a reactive form with formArray in angular17. I encountered this issue when you removed one item from the formArray from the top or from the middle.
here’s the stackbiz for the issue reproduction.

reproduction path:

  1. put some values in the film fields.
  2. click the add film button to add another film to the form.
  3. put some other values in the newly added film fields.
  4. click on the remove film button under the first film fields.
  5. observe the values in the film fields, the removed film field values are still showing on the dom. but in the below json where I display the form values are updated correctly.

I try to use ApplicationRef.tick(), ChangeDetectorRef.detectChanges(), and updateValueAndValidity() as other similar issues suggested, but no luck. try to use trackBy, but it doesn’t do the trick also. Can someone tell me what I’m doing wrong here?

import { CommonModule } from '@angular/common';
import { ApplicationRef, ChangeDetectorRef, Component } from '@angular/core';
import {
  FormArray,
  FormBuilder,
  FormControl,
  FormGroup,
  ReactiveFormsModule,
} from '@angular/forms';

@Component({
  selector: 'app-add-vehicle',
  standalone: true,
  imports: [CommonModule, ReactiveFormsModule],
  templateUrl: './add-vehicle.component.html',
  styleUrl: './add-vehicle.component.scss',
})
export class AddVehicleComponent {
  constructor(
    private fb: FormBuilder,
    private appRef: ApplicationRef,
    private cdr: ChangeDetectorRef
  ) {}

  addVehicleForm = this.fb.group({
    make: [''],
    model: [''],
    year: [''],
    films: this.fb.array([this.createFilmFormGroup()]),
  });

  createFilmFormGroup(): FormGroup {
    return this.fb.group({
      title: [''],
      releaseDate: [''],
      url: [''],
    });
  }

  get films(): FormArray {
    return this.addVehicleForm.get('films') as FormArray;
  }

  addFilm() {
    this.films.push(this.createFilmFormGroup());
  }

  removeFilm(index: number) {
    this.films.removeAt(index);

    this.addVehicleForm.reset(this.addVehicleForm.value);

    // not working
    // this.addVehicleForm.updateValueAndValidity();

    // not working
    // this.appRef.tick();

    //not woorking
    // this.cdr.detectChanges();
  }
}
<div>
  <h1>Add Vehicle</h1>
  <form [formGroup]="addVehicleForm">
    <div class="form-group">
      <label for="make">Vehicle Make</label>
      <input
        type="text"
        class="form-control"
        id="make"
        formControlName="make"
      />
    </div>
    <div class="form-group">
      <label for="model">Vehicle Model</label>
      <input
        type="text"
        class="form-control"
        id="model"
        formControlName="model"
      />
    </div>
    <div class="form-group">
      <label for="ManufactureYear">Manufacture year</label>
      <input
        type="text"
        class="form-control"
        id="ManufactureYear"
        formControlName="year"
      />
    </div>

    <div style="border: 1px solid black; border-radius: 10px; padding: 10px">
      <div formArrayName="films">
        @for (film of films.controls; track $index) {
        <div
          [formGroupName]="$index"
          style="
          border-bottom: 1px solid #222;
          padding: 10px;
          margin-bottom: 10px;
        "
        >
          <input type="hidden" name="id" formControlName="id" />
          <div class="form-group">
            <label [for]="'title' + $index">Title</label>
            <input
              type="text"
              class="form-control"
              [id]="'title' + $index"
              formControlName="title"
            />
          </div>
          <div class="form-group">
            <label [for]="'releaseDate' + $index">Release Date</label>
            <input
              type="text"
              class="form-control"
              [id]="'releaseDate' + $index"
              formControlName="releaseDate"
            />
          </div>
          <div class="form-group">
            <label [for]="'url' + $index">URL</label>
            <input
              type="text"
              class="form-control"
              [id]="'url' + $index"
              formControlName="url"
            />
          </div>
          <button type="button" (click)="removeFilm($index)">
            Remove Film
          </button>
        </div>
        }
      </div>
      <button type="button" (click)="addFilm()">Add Film</button>
    </div>
  </form>

  <pre>
  {{ addVehicleForm.value | json }}
</pre
  >
</div>

Why does an if block work but a && statement doesn’t work for executing a try catch block?

Basically wanted the issue && block to work the same as if(issue) block in my nextjs component for an edit form which basically detects if there is a prop passed named issues passed on to the component. If it does exist then the issue && statement would be executed. However it isn’t working and chatgpt recommends that I use the if block instead. The error that it shows is –

Parsing error: ':' expected.eslint
(property) try: {
    setIsSubmitting(: any): any;
    await: Promise<AxiosResponse<any, any>>;
    router: AppRouterInstance;
    "": any;
}
issue && {
      try {
        setIsSubmitting(true);
        await axios.post("/api/issues", data);
        router.push("/issues");
      } catch (error) {
        setIsSubmitting(false);
        setError("An unexpected error occurred");
      }
    }
    
if (issue) {
    try {
        setIsSubmitting(true);
        await axios.post("/api/issues", data);
        router.push("/issues");
      } catch (error) {
        setIsSubmitting(false);
        setError("An unexpected error occurred");
      }
} 
 

HTML, Javascipt : Need Help to make the user open a url new tab after clicking a specific button inside , but can only declare on

please anybody help me thru this case 🙁
I just started learning html css and javascript, and i have a problem. I need to make the visitor to open an extra tab with specific url after clicking some button. This specific url is actually a thankyou page, so that after they finished filling out a form and click ‘Register’, they dont just got redirected to a new page, but also open an extra tab.
the button inside the is declared in this code :

Now, the original script works fine but I dont know how to make the auto open extra tab after clicking the button, plus i cannot edit anything inside the tag since its a template cms, i can only add some script at the footer text or head meta.
i dont know if I should add an extra javascript code or else to make this works, please help

How can I auto-import a certain file of the project by unimport?

I am using the plugin named Unimport which is used for auto-import modules from third-part libs or current project. It was used in nuxt and can be configired in nuxt.config.ts like:

export default defineNuxtConfig({
  imports: {
    // Auto-import pinia stores defined in `~/stores`
    dirs: ['stores']
  }
}

Unimport will generate a declaration file named unimport.d.ts:

export {}
declare global {
  const globalStore: typeof import('/home/stores/globalStore')['globalStore']
}

Modules under stores dir can be auto-imported correctly, but if I already created a entry file of the stores dir and exports other modules in it:

export * from './globalStore'

Expect globalStore can be imported from stores/index.ts file instead of stores/globalStore.ts, so I want to specify the auto-import of a particular file.

Unimport only provide a option named dirs for auto-import all files, how can I auto-import a certain file ?

Code to calculate SumProduct in a payroll system

I am having issues to convert the below formula into a javascript:
=+MAX(SUMPRODUCT((GrossTotal>{350000,400000,500000,600000})*(GrossTotal-{350000,400000,500000,600000}),{0.05,0.05,0.05,0.05}),3000)

I tried using a loop. I tried asking the company who is in charge of salary department. They provide us only with the above formula. And they told that the Malagassy Govt only gave them the formula as it is.

How to implementing conditional execution of JavaScript Code in React.js Project Using useEffect Dependency State

I want to add javascript code in react js project, I need to implement this code according to condition.
I have used one state, according to that state I want to add and remove that script.

This is the javascript that I need to add in react js project.

<!-- start Gist JS code–>
<script>
(function(d,h,w){var gist=w.gist=w.gist||[];gist.methods=[‘trackPageView’,‘identify’,‘track’,‘setAppId’];gist.factory=function(t){return function(){var e=Array.prototype.slice.call(arguments);e.unshift(t);gist.push(e);return gist;}};for(var i=0;i<gist.methods.length;i++){var c=gist.methods[i];gist[c]=gist.factory©}s=d.createElement(‘script’),s.src=“url”,s.async=!0,e=d.getElementsByTagName(h)[0],e.appendChild(s),s.addEventListener(‘load’,function(e){},!1),gist.setAppId(“app
Id”),gist.trackPageView()})(document,‘head’,window);
</script>
<!-- end Gist JS code–>

How to load xml into mxGraph

I am trying to load xml into mxGraph but it doesn’t seem to work. First i grab xml made in editor like this:

 var encoder = new mxCodec();
var node = encoder.encode(graph.getModel());
var xml = mxUtils.getXml(node);

return xml;

After this function, this is a example xml i got:

<mxGraphModel><root><mxCell id="0"><mxCell id="1" parent="0"><mxCell id="2" value="TEST" xss=removed vertex="1" parent="1"><mxGeometry x="30" y="60" width="390" height="210" as="geometry"></mxCell><mxCell id="3" value="test 2" xss=removed vertex="1" parent="1"><mxGeometry x="550" y="110" width="440" height="130" as="geometry"></mxCell><mxCell id="4" edge="1" parent="1" source="2" target="3"><mxGeometry relative="1" as="geometry"></mxCell></root></mxGraphModel>

Then i try to load xml in a diffrent page with this code:


function loadGraphFromXML(xmlString){
  var doc = mxUtils.parseXml(xmlString);
  var codec = new mxCodec(doc);
  codec.decode(doc.documentElement, graph.getModel());
}

This is the error i got.

mxObjectCodec.js:801 Uncaught TypeError: this.decodeChildren is not a function
    at mxObjectCodec.decodeNode (mxObjectCodec.js:801:8)
    at mxObjectCodec.decode (mxObjectCodec.js:780:7)
    at mxCodec.decode (mxCodec.js:440:14)
    at loadGraphFromXML (graph.js?v=1708919730:342:9)
    at Object.success (graph.js?v=1708919730:372:5)
    at i (jquery-3.1.1.min.js:2:27983)
    at Object.fireWith [as resolveWith] (jquery-3.1.1.min.js:2:28749)
    at A (jquery-3.1.1.min.js:4:14203)
    at XMLHttpRequest.<anonymous> (jquery-3.1.1.min.js:4:16491)

Thanks

I tried converting to svg, didn’t work. Tried diffrent xml types almost none of them did work.

After setting networkingMode=mirrored in WSL, vscode cannot launch Node.js projects using launch.json vscode debug

VERSION

WSL version: 2.0.14.0
Kernel version: 5.15.133.1-1
WSLg version: 1.0.59
MSRDC version: 1.2.4677
Direct3D version: 1.611.1-81528511
DXCore version: 10.0.25131.1002-220531-1700.rs-onecore-base2-hyp
Windows version: 10.0.22621.3155

.wslconfig

[wsl2]
autoProxy=true
dnsTunneling=true
firewall=true
networkingMode=mirrored # nat | mirrored
[experimental]
autoMemoryReclaim=gradual  # gradual  | dropcache | disabled

Description of the problem

When using vscode and configuring launch.json to start the program, it takes a long time to execute.When setting networkingMode to nat, this issue doesn’t occur.

enter image description here

How to enable vscode debugging properly while networkingMode is set to mirrored mode.

My code only works with letters and numbers

Im trying to get a input user and set it, that way I can run my following code (PRINT PDFs) but this only work withs letter and numbers like “A2, A3, A1000, etc” The problem is that I have just number “1, 2, 3,4…” in my database.

This is my code:

function promptUserToSelectInvoices(data) {
  // Prompts the user to enter invoice numbers separated by commas
  var selectedInvoices = [];
  var ui = SpreadsheetApp.getUi();
  var response = ui.prompt('Select Invoices to Print', 'Enter the invoice numbers separated by commas:', ui.ButtonSet.OK_CANCEL);
  
  if (response.getSelectedButton() === ui.Button.OK) {
    var input = response.getResponseText().trim();
    Logger.log(input)
    selectedInvoices = input.split(',').map(function(value) {
      return value.trim();
    });

    // Calls the PrintSelectedToPDF() function with the selectedInvoices array
    PrintSelectedToPDF(selectedInvoices);
  }
}

function PrintSelectedToPDF(invoicesToPrint) {
  var spreadsheet = SpreadsheetApp.getActive();
  var databaseSheet = spreadsheet.getSheetByName('Database');
  var invoiceSheet = spreadsheet.getSheetByName('Invoice');
  
  var dataRange = databaseSheet.getRange(3, 12, databaseSheet.getLastRow() -2, 1);
  var data = dataRange.getValues();
  
  for (var i = 0; i < data.length; i++) {
    var valueToPrint = data[i][0];
    Logger.log(valueToPrint);
    
    // Check if invoicesToPrint is empty or includes the current invoice number
    if (invoicesToPrint.length === 0 || invoicesToPrint.includes(valueToPrint)) {
      invoiceSheet.getRange('Q7').setValue(valueToPrint);
      
      var url = 'https://docs.google.com/spreadsheets/d/' + spreadsheet.getId() + '/export?';
      var params = {
        exportFormat: 'pdf',
        format: 'pdf',
        size: 'letter',
        portrait: 'true',
        fitw: 'true',
        sheetnames: 'false',
        printtitle: 'false',
        top_margin: 0,
        bottom_margin: 0,
        left_margin: 0,
        right_margin: 0,
        gid: invoiceSheet.getSheetId()
      };
      
      var ss = SpreadsheetApp.getActiveSpreadsheet();
      var range = ss.getRange("invoice!A1:V41");
      var rangeParam = '&range=' + range.getA1Notation();
      url += getUrlParams(params) + rangeParam;
      
      var backoffTime = 500;
      var maxBackoffTime = 5000;
      var attempts = 0;
      var response;
     

Want to remove style src unsafe inline from application

I’m trying to mitigate XSS attacks by setting the Content-Security-Policy header but Chrome keeps throwing an error:

Refused to execute inline event handler because it violates the following Content Security Policy directive: “script-src ‘self’ ‘nonce-Njg3MGUxNzkyMjViNDZkN2I3YTM3MDAzY2M0MjUxZGEzZmFhNDU0OGZjNDExMWU5OTVmMmMwMTg4NTA3ZmY4OQ=='”. Either the ‘unsafe-inline’ keyword, a hash (‘sha256-…’), or a nonce (‘nonce-…’) is required to enable inline execution.

Here’s my Content-Security-Policy header:

Dont want to include style src unsafe-inline in my application while removing its throwing error

        httpResponse.setHeader(
                "Content-Security-Policy",
                "default-src 'self' 'unsafe-inline' 'unsafe-eval' data:;"
                        + "style-src 'self' fonts.googleapis.com 'sha256-CwE3Bg0VYQOIdNAkbB/Btdkhul49qZuwgNCMPgNY5zw=';" + "base-uri 'self' data:;"
                        + "frame-src 'self' * data:;" + "connect-src 'self' * data:;"
                        + "font-src 'self' fonts.gstatic.com https://cdn.predix-ui.com data:;"
                        + "frame-ancestors 'self' data:");
        chain.doFilter(request, httpResponse);