Async await function result in js

Please tell me why in this code:

function print() {
   console.log("1");
 }
   console.log("2");

 async function foo() {
   console.log("3");
   await print();
   console.log("4");
 }

 foo();

 console.log(5);

Output is: 2 3 1 5 4
But not: 2 3 1 4 5

What’s reason?

see above

I expected that result : But not: 2 3 1 4 5
But Output is: 2 3 1 5 4

Is there a way to lint event listener types in JS/TS?

I use eslint and tslint to help me avoid silly mistakes.

However, today, I made a mistake when declaring an event listener to catch uncaught promise rejections:

   window.addEventListener('unhandledRejection', debugError)

The correct type is unhandledrejection, not unhandledRejection. I wasted a lot of time debugging this before I realized I had made a typo. Given the prevelance of camelCase in JS, I fear I will make the same mistake again.

Is there some way to lint this against known event types? I don’t use any custom events in my app.

Check array of dates to see if increasing

I want to check an array of dates to see if they are increasing. For example, [’12/12/2023′,’13/12/2023′] would return true. However, [’12/12/2023′,’11/12/2023′] would return false.
I have been playing around with a function suggested by users for checking integer values. I thought I could do the same but use dates instead.

Here is the function:

function isIncreasing(dates) {
    for (var i = 1; i < dates.length; i++) {
        let convertedToDate = new Date(dates[i]);
        //console.log(currentDate);
        if (convertedToDate[i] !== convertedToDate[i - 1] && convertedToDate[i] != convertedToDate[i - 1] + 1) {
            return false;
        }
    }
    return true;
}
console.log(isIncreasing(['12/12/2023','11/12/2023','10/12/2023']))

The function does not work as the above returns true. Any help is appreciated.

Multiple different named images don’t working in jquery magic 360 plugin

I have multiple images and they’re named in different names and extension. I’m using magic 360 javascript plugin version 4.6.13. In frontend the page is show only tree.jpg. and magic360 dont working when I drag skin. in console there’s nothing errors. I made by doc

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>jQuery Integrated 360 Magic Spin Viewer</title>
    <link rel="stylesheet" href="assets/css/magic360.css">
    <script src="assets/js/magic360.js"></script>
</head>
<body>

    <style type="text/css">
        #gallery {
            width: 500px; /* Adjust the width as needed */
            height: 400px; /* Adjust the height as needed */
            margin: 0 auto;
        }

        .magic360 {
            width: 100%;
            height: 100%;
        }
    </style>

    <div id="gallery">
        <a class="Magic360" data-options="images: images/nature/tree.jpg images/car_slides/mountain.webp">
            <img src="images/nature/tree.jpg">
        </a>
    </div>

<!-- Your HTML content here -->
<script>
    var Magic360Options = {
        columns: 6
    };
</script>
</body>
</html>

send file to whatsapp cloud api using the media endpoints

Im using the whatsapp api to generate a file and send it to whatsapp api. I first test all parameters by postman and everything was great, postman generated this code:

const myHeaders = new Headers();
myHeaders.append("Authorization", "Bearer token");
myHeaders.append("Cookie", "ps_l=0; ps_n=0");

const formdata = new FormData();
formdata.append("file", fileInput.files[0], "/C:/Users/Sub2/Documents/Hoja de trabajo.docx");
formdata.append("type", "document");
formdata.append("messaging_product", "whatsapp");

const requestOptions = {
  method: "POST",
  headers: myHeaders,
  body: formdata,
  redirect: "follow"
};

fetch("https://graph.facebook.com/v19.0/{{media_id}}/media", requestOptions)
  .then((response) => response.text())
  .then((result) => console.log(result))
  .catch((error) => console.error(error));

If you use this code it will upload the file to the whatsapp api.
The problem is that in node js its giving an error: {"error":{"message":"(#100) The parameter messaging_product is required.","type":"OAuthException","code":100,"fbtrace_id":"AAql5W804gIHMiKVCxX7InY"}}

The parameter messaging_product is required, but this code: formdata.append("messaging_product", "whatsapp"); add that parameter, i dont know what’s the problem. The only code part that is different in my node code is this formdata.append("file", fileStream); im using the exceljs to generate a file, Thank you for any suggestions.

How to optimistically update the database when a form value changes?

I have this callback function that is called from a child component that updates the form (I’m using react-hook-form) of the parent component

  const goalSetter = useMemo(() => {
    return (value: string[]) => {
      const goals: Goals[] = value
        .map((goal) => stringToEnumValue(goal, Goals))
        .filter((v) => !!v) as Goals[];

      form.setValue('goals', [...goals]);
      await updateUserData('goals');
    };
  }, []);

Problem is the updateUserData function takes a long time to execute and slows down the app. So, it takes about a second to see the visual feedback in the UI.

updateUserData:

  const updateUserData = async (field: ProfileField) => {
    await form.trigger(field);
    if (form.formState.isValid) {
      await updateUser(userDataSchema.cast(form.getValues()));
    } else {
      form.setError(field, {
        type: 'validation-error',
        message: 'Please enter a valid input',
      });
      console.log('form is not valid');
    }
  };

I have tried memoizing the functions but that barely makes a difference. How can I refactor this to do the update part in the background and increase the responsiveness ?

Any help is welcome. Thanks

Can i store and run website versions from a container with no software required

We are developing a website using Blazor.

The bosses would like something set up so each day we can create a build, and store that build on one of our shared drives for company wide viewing.

The purpose is so they can have a record of daily changes forever.

The issue is, they want anyone to be able to click on one button or file name. From this is will launch the entire website in a browser. They require no predownloaded software – this is the big issue!

Originally i was going to create a Docker container each day which i can share. But the company insists that there must be no predownloaded programs required at all.

I think im very stuck. The closest i think i can get is a html file they open to display a single page. But i have no idea how i can locally host and share a website. Without a program such as docker, VS code or other software.

The build files in Blazor are far more complicated than my normal React build files. There are so mnay dependencies required.

Im looking for a way to build or convert a file so i can store it as a zipped folder, then when one of the items inside is clicked on, the whole webpage runs.

I have tried creating a docker image and finding a way to run docker images without downloading the software.

Catching screen keyboard entries in javascript on Android webview

In my (old but needed) webapp, I registered a keydown event on document (using jquery) to get which keys were pressed:

$(window).on('keydown', function(e) {
     console.log('e.key: ' + e.key);
     console.log('e.keyCode: ' + e.keyCode)
}

I need to bind it to the window because the mobile devices I use have a barcode scanner that emulate key presses. I want the barcode to be catched no matter where the cursor currently is. If the user needed to focus a special field before performing a barcode scan, usability would be ruined. This is why I cannot use the “input” event. “Keydown” worked for years.

Suddenly the scanners stopped working. Here I found why:

The W3C decided that virtual keyboards for whatever reason should fire keydown events, but should no longer submit the e.key or e.keyCode variables. By standard they should now send
keycode 229 and key “Unidentified”.

I haven’t found any way how to get my old usage case done. Any ideas how to catch a virtual keyboard press and get the code of the key pressed?

React project deployment on Vercel

I’m trying to deploy my React project on Vercel, these are the errors I’m getting. I’ve tried installing the same versions and it’s still not working.

npm ERR! code ERESOLVE
npm ERR! ERESOLVE could not resolve
npm ERR! 
npm ERR! While resolving: @material-ui/[email protected]
npm ERR! Found: [email protected]
npm ERR! node_modules/react
npm ERR!   react@"^18.2.0" from the root project
npm ERR!   peer react@"^18.0.0" from @testing-library/[email protected]
npm ERR!   node_modules/@testing-library/react
npm ERR!     @testing-library/react@"^13.4.0" from the root project
npm ERR!   10 more (framer-motion, mdb-react-ui-kit, react-dom, react-icons, ...)
npm ERR! 
npm ERR! Could not resolve dependency:
npm ERR! peer react@"^16.8.0 || ^17.0.0" from @material-ui/[email protected]
npm ERR! node_modules/@material-ui/core
npm ERR!   @material-ui/core@"^4.12.4" from the root project
npm ERR! 
npm ERR! Conflicting peer dependency: [email protected]
npm ERR! node_modules/react
npm ERR!   peer react@"^16.8.0 || ^17.0.0" from @material-ui/[email protected]
npm ERR!   node_modules/@material-ui/core
npm ERR!     @material-ui/core@"^4.12.4" from the root project
npm ERR! 
npm ERR! Fix the upstream dependency conflict, or retry
npm ERR! this command with --force or --legacy-peer-deps
npm ERR! to accept an incorrect (and potentially broken) dependency resolution.
npm ERR! 
npm ERR! 
npm ERR! For a full report see:
npm ERR! /vercel/.npm/_logs/2024-03-26T06_42_43_667Z-eresolve-report.txt
npm ERR! A complete log of this run can be found in: /vercel/.npm/_logs/2024-03-26T06_42_43_667Z-debug-0.log
Error: Command "npm install" exited with 1

I’ve tried installing the same versions. I’ve also uninstalled Node and reinstalled it.

Javascript can’t connect to python secure websockets

I have a python websockets since a year or two, i usually have two clients connecting, one using C# and one using python.

I recently started working on a web client and try to use JS Websocket and it’s throwing an error :
Firefox can’t establish a connection to the server at wss://*url removed for privacy*/.
Same with Chrome :
WebSocket connection to 'wss://*url removed for privacy*/' failed

This is what i have server side :

ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
ssl_cert = "*path to cert*"
ssl_key = "*path to key*"

ssl_context.load_cert_chain(ssl_cert, keyfile=ssl_key)
async def main():
    async with websockets.serve(echo, "0.0.0.0", 465, ssl=ssl_context):
        print(f'Listening on port 465')
        await asyncio.Future()

I can share the echo function if needed

This is my python code for connecting :

async with websockets.connect("wss://*URL removed for privacy*") as websocket:
            await websocket.send('*data sent*')
            response = await websocket.recv()

Working fine

On my C# client :

wsc = new WebsocketClient('wss://*URL Removed for privacy*');
wsc.ReconnectTimeout = TimeSpan.FromSeconds(15);
wsc.ReconnectionHappened.Subscribe(info => Console.WriteLine($"Reconnection happened, type: {info.Type}"));
await wsc.Start();

Working fine

And JS client :

const socket = new WebSocket("wss://*URL Removed for privacy*");
socket.addEventListener("open", (event) => {
    socket.send("*data sent*");
});

Throwing an error

I don’t even know why it doesn’t connect as there’s no details on what’s going on with the connexion try.

Thanks for your help

How to deactivate a function when a focusOut event happens?

Goal

I want to have two search bars, and each of them can:

  • Display suggestions as typing
  • Use arrow keys to select item
  • Each item can be customized

Because of the last bullet I don’t want to use <datalist> tag as it’s limited in style. I also use Deno Fresh, which is based on Preact, which is based on React. At the time I wasn’t aware of guides on navigate through list by arrow keys in React, but in vanilla JS, and I think using the vanilla version will be simpler, so currently I’m using it.

Problem

When a list is navigated by keyboard, the other is also triggered. My idea is to have the script targets different lists, and when users unfocus an input field it will be deactivated. I try having this on the script:

if (list === 'deactivate') return

And on each handler I have:

onBlur={(e) => script('deactivate')}

But it still doesn’t work. Do you have any suggestion?

Code

search.jsx:

export default function SearchBar() {
  const [keyword1, setKeyword1] = useState("");
  const [keyword2, setKeyword2] = useState("");
  
  const list1 = [ 'rabbits', 'raccoons', 'reindeer', 'red pandas', 'rhinoceroses', 'river otters', 'rattlesnakes', 'roosters' ] 
  const list2 = [ 'jacaranda', 'jacarta', 'jack-o-lantern orange', 'jackpot', 'jade', 'jade green', 'jade rosin', 'jaffa' ]

  return (
    <div className="search-bar-container">
      <input
        type="text"
        placeholder={'Search list 1'}
        value={keyword1}
        onInput={(e) => {
          setKeyword1(e.target.value);
          script('1');
        }}
        onBlur={(e) => script('deactivate')}
        />
      <br />
      <ul id={'Suggested list 1'}>
        {keyword1 !== '' ? list1.filter(keyword => keyword.includes(keyword1)).map(
          (item) => <li>{item}</li>,
        ) : ''}
      </ul>
      <div>
        Your selected item is :<span id="Item 1"></span>
      </div>
      <div className="search-bar-container">
        <input
          type="text"
          placeholder={'Search list 2'}
          value={keyword2}
          onInput={(e) => {
            setKeyword2(e.target.value);
            script('2');
          }}
          onBlur={(e) => script('deactivate') }
        />
        <br />
        <ul id={'Suggested list 2'}>
          {keyword2 !== '' ? list2.filter(keyword => keyword.includes(keyword2)).map(
            (item) => <li>{item}</li>,
          ): ''}
        </ul>
        <div>
          Your selected item is :<span id="Item 2"></span>
        </div>
      </div>
    </div>
  );
}

script.ts:

export function script(list: "1" | "2" | 'deactivate') {
  if (list === 'deactivate') return
  if (window !== undefined) {
      const ul = document.getElementById(`Suggested list ${list}`);
      const result = document.getElementById(`Item ${list}`);
//the rest of the script

Full code. Somehow CodeSandbox keeps having twind error even when I don’t. This does run in my machine.

Screenshot (GIF)

Unable to get updated values in form textfields using innerHTML in angular

I’m binding for using innerHTML

    this.html = this.sanitizer.bypassSecurityTrustHtml(
          '<iframe width="100%" height="800" src="assets/template_forms/registration_form.html"></iframe>',
        );

<div [innerHtml]="html"></div>

the form is rendered like this

enter image description here

if i entered some test in input fiekd thennot getting updated value in form input value when accessed html variable.

Any solution Thanks

contentEditable – how to force to write after tag, not inside

I have div with contentEditable and when I add an element into it via JS, like: <span>text</span> I am not able to move cursor after – so when user input something it is going into the span. Is there any way how to prevent that?

<p class="line">Some text <span>text</span>[write_here]</p>

I want to force it to write into [write_here] position.

Here is an example, when you just add element and write it is going into the span – red. You are not able to write out of it after.

const input = document.querySelector('div.content');
const result = document.querySelector('div.result');
const addBtn = document.querySelector('button.addbtn');

input.addEventListener('input', () => {
  result.innerText = input.outerHTML;
});

const createElement = (content) => {
  const element = document.createElement('span');

  element.classList.add('mention');
  element.innerText = `@${content}`;

  return element;
};


addBtn.addEventListener('mousedown', () => {
  const element = createElement('test');
  
  const selection = window.getSelection();
  const selectedRange = selection.getRangeAt(0);
  
  selectedRange.deleteContents();
  selectedRange.insertNode(element);
  
  selectedRange.setStart(element, element.length);
  selectedRange.collapse(true);

  selection.removeAllRanges();
  selection.addRange(selectedRange);
  
  // How to properly move cursor after the `span` to write outside of the span. Even solve when user writes something and delete text right next to the end of the span. 
});
.content {
  width: 350px;
  height: 20px;
  background: lightblue;
}

span.mention {
  background: red;
}
<div class="content" contentEditable="true"><br/></div>
<button class="addbtn">Add element</button>
HTML:
<div class="result"></div>