Object key exist outside of the function call but not inside the function scope

I am working with fabric.js and at one point I use this code:

canvas.on("object:modified", (opt) => {
  console.log(opt.action); //="scale"
  handleScaled(opt);
});

But in the handleScaled function opt.action is undefined:

function handleScaled(opt) {
  console.log(opt.action) //=undefined
  console.log(opt) //displays the whole opt object but there is no "action" in it
  //further handleScaled code
}

console.log(opt.action) before the function call would display “scale” correctly but then when I call the same in handleScaled, opt.action is undefined.

Why doesn’t opt.action seem to exist in the scope of the called function but happens to exist before the call?

Correct working code that only calls handleScale when the action was “scale”:

canvas.on("object:modified", (opt) => {
  if (opt.action === "scale") {
    handleScaled(opt);
  }
});

how to completley hide div (including column headings) in php report (if all div input value are null or 0. )

I am displaying php report in div. If div have no data to display or 0 value then I want that whole div should be hide from the report.Here is my php report code in two div

                        <div class = "abc">
                      echo '<table class="styled-table">';
                            echo "<thead>";
                                echo "<tr>";                                  
                                   
                echo "<th>Name</th>";
                echo "<th>Phone</th>";
                echo "<th>Age</th>";        
                                   
                                    echo "<th>Action</th>";
                                echo "</tr>";
                            echo "</thead>";
                            echo "<tbody>";
                            while($row = mysqli_fetch_array($result)){
                                echo "<tr>";                                       
                                    echo "<td>" . $row['pname'] . "</td>";
                echo "<td>" . $row['phone1'] . "</td>";
                echo "<td>" . $row['age'] . "</td>";                
                                 
                                    echo "<td>";  </div>

Is there a way to set position for specific layer instead of all layers on the map?

One specific layer requires the following block to be positioned properly in relation to map.

const mapSize = map.getSize();
const globalPos = L.DomUtil.getPosition(map.getPane("mapPane"));
const topLeft = globalPos.multiplyBy(-1);
const bottomRight = topLeft.add(mapSize);
L.DomUtil.setPosition(map.getPane(this.options.pane), topLeft);

This block is getting called on every map view update.

The problem is: when I try to add another layer (GeoJSON/JSON), which doesn’t require such adjustment, it’s also being affected by DomUtil position and is placed improperly on the map.
Is there a way to set position for specific layer only, or perhaps to offset the position of GeoJSON layer somehow to compensate for the changes to position set through DomUtil?

`console.log` and `alert` not working in Vite Laravel 10 app

I’m currently working on a Vite Laravel 10 app and I’m facing an issue where both console.log and alert statements are not working.

I have the following code in my `resources/js/app.js

alert("hi");
console.log("hi");
import "./bootstrap";

I expect to see the alert dialog and the message “hi” logged to the browser’s console. However, neither of them are displaying any output.

Environment Details:

  • Operating System: WSL Ubuntu
  • PHP Version: 8.1.2
  • Laravel Framework Version: 10.15.0
  • Vite Version: 4.4.3

Troubleshooting Steps Taken:

  • Checked that the code is correctly placed in the resources/js/app.js file.
  • Verified that the bootstrap module is imported correctly.
  • Tried using both console.log and alert statements in different parts of my code.
  • Changed browsers to see if the issue persists.
  • Ensured that there are no filters applied in the Chrome console.
  • Checked all levels of output (verbose, info, warnings, errors) in the Chrome console.
  • Executed the npm run dev command to start the development server.

Despite these attempts, I’m still unable to see the alert dialog or the message “hi” logged to the browser’s console.

I would appreciate any insights or suggestions on how to resolve this issue. Thank you!

: First uploading doesn’t work

Problem

I’m on working with React on Chrome, and to upload a file I use <input type="file" />. However, the first upload never works, but the subsequent uploads have absolutely no problems.

Edit: When I talk about the upload, I’m referring to pictureFile. I’m really sorry about my bad use of words…

Trials

To tell you the truth, I really don’t know where to begin to deal with this problem…

I first tried to delete the onClick, which is used to deal with the upload of the same file. But it has no effects. And I also tried some solutions found in an old Stack Overflow post but there are still no results.

Code

Below it’s my code:

import { useState } from "react";

function Settings() {
  let [pictureFile, setPictureFile] = useState(false);

  const updateAvatar = (event) => {
    if (event.target.files && event.target.files.length > 0) {
      setPictureFile(event.target.files[0]);
    }
    console.log(pictureFile);
  };

  return (
    <div id="settingsContainer">
      <input
        type="file"
        accept=".png, .jpeg, .jpg, .gif"
        name="user_pictureURL"
        id="user_pictureURL"
        onChange={updateAvatar}
        onClick={event => event.target.value = null}
      />
    </div>
  );
}

export default Settings;

I thank in advance anyone who will take the time to help me :D.

How to use field mapping for nested object in ts

I have two objects below,

let response = {
                offer: {
                    custom_fields: {
                        job_title: 'engineer'
                    },
                    starts_at: 'test',
                    job_post: 'test'
                }
            }

let defaultFieldMapping = {
                "$.engagementData.title": {
                    default: "Software Engineer",
                    path: "$.offer.custom_fields.job_title",
                    fieldName: 'Title'
                },
                "$.engagementData.startDateUTC": {
                    default: null,
                    path: "$.offer.starts_at",
                },
            }

Need to form new object and expected result like below

let expectedResult = [
                {
                    externalFieldId: '$.offer.custom_fields.job_title',
                    integrationFieldId: '$.engagementData.title'
                },
                {
                    externalFieldId: '$.offer.starts_at',
                    integrationFieldId: '$.engagementData.startDateUTC'
                },
                {
                    externalFieldId: '$.offer.job_post',
                    integrationFieldId: ''
                },
            ]

integrationFieldId is empty string because that’s not exists in the defaultFieldMapping path column.

Reading a file from the clipboard with the Clipboard API

I am trying to read a file from the clipboard using the Clipboard API according to the manual , but my browser throws the error.

I am trying to read a file from the clipboard using the Clipboard API in this way:

const clipboard = await window.navigator.clipboard.read();
console.debug(clipboard);

The browser throws an error when executing this code:

Uncaught (in promise) DOMException: No valid data on clipboard.

Can you tell me how to make sure that this error does not occur and it is possible to receive files from the clipboard?

PWA application – display a badge on the app icon works windows but not work on android

I am struggling with PWA and badging. I added
if (navigator.setAppBadge) { navigator.setAppBadge(6); }
to the push notification method(service-worker.js) and it works fine on windows(chrome browser) but it doesn’t work on android(also chrome browser). Consent to notifications granted. Are you able to advise what is wrong or what I miss or maybe android requires additional permissions?

Thanks in advance.

I tried set badge without number but it also don’t work. I also check if I can add additional permission for PWA app on the Android device.

Can I run Nuxt 3 without using ?

Is it possible to migrate a Nuxt 2 application to Nuxt 3 and keep the JavaScript I execute in the pages between pure <script> tags, instead of updating them to the <script setup> tag?

If not, what are the changes I should make to my code? Basically: what are the main differences between these two?

How can I restrict the value type of FormGroup in ts?

I have a const like this:

const defaultInfo: FormGroup = this.fb.group({
  id: 1,
  name: qian,
  amount: 123,
})

and I want to restrict the type inside the FormGroup, so I write like this:

interface InfoInterface {
  id: number,
  name: string,
  amount: number,
}


interface InfoFormGroup extends FormGroup {
  value: InfoInterface
}

const defaultInfo: InfoFormGroup = this.fb.group({
  id: 1,
  name: qian,
  amount: 123,
})

obviously it doesn’t work, because whatever I change the properties of Info Interface to, there is no error, why? how can I restrict the value type of FormGroup in ts

restrict the value type of FormGroup in ts

Does EsLint have a rule to make sure key and value of object in the same line?

Looking for a rule (can’t seem to find anything, might’ve just missed it) in EsLint to basically prefer something like this:

const example = {
    a: 
    5
};

vs something like this:

const example = {
    a: 5
};

I hope the rule can check if the key and value not in the same line.

I tried to add a rule named “object-curly-newline” and my setting looks like:

{
    "rules": {
        "object-curly-newline": [
            "error",
            {
                "ObjectExpression": "always",
                "ObjectPattern": {
                    "multiline": true
                },
                "ImportDeclaration": "never",
                "ExportDeclaration": {
                    "multiline": true,
                    "minProperties": 3
                }
            }
        ]
    }
}

but it doesn’t work in my case.

How to avoid querySnapshot.docChanges() to listen all the eixsting documents as “added”

We are implementing firestore in a chat. At first render we send a request to fetch 10 documents from the chat. At the same time to listen the realtime changes in these documents. querySnapshot.docChanges() is applied till the last fetched message. When user scroll onEndReached function is triggered and request is sent to get documents at the previous fetched last message time. Again to listen the changes in realtime to all the fetched documents. Again querySnapshot.docChanges() is applied to the last message time fetched with loadMore function.

It works fine as of functionality. But the issue came when at first we get 10 documents querySnapshot.docChanges() listen to the existing 10 documents as “added”. Now when loadMore is called now again it listen to the existing all documents as “added”. So If we fetched 200 documents it first listen to the 200 documents as added and if there is any change in any of that document. It listen as “modified”.

So we fetched 10 then 15 then 15 then again 15 and soo on. These are shown to user. But the issue is on each loadMore querySnapshot.docChanges() listen to the documents like 0 to 10 then 0 to 25 then 0 to 40. So the time came. We fetched 200 messages and its listened again and again. 0 to 185 and then 0 to 200.

First fetch code

useEffect(() => {
    if (!chatId) {
      cloudFunction('createDirectChat', {recipient: uid}).then(res => {
        console.log(res.data.chatId);
        setChatId(res.data.chatId);
      });
    } else {
      firestore()
        .collection('chats/' + chatId + '/messages')
        .orderBy('sentAt', 'desc')
        .limit(10)
        .get()
        .then(querySnapshot => {
          const documents = [];
          querySnapshot.forEach(documentSnapshot => {
            let obj = {
              id: documentSnapshot.id,
              ...documentSnapshot.data(),
            };
            documents.push(obj);
          });

          /////
          if (documents && documents.length > 2) {
            firstBatchLastMessageTime.current = documents[1].sentAt;
          } else if (documents && documents.length == 1) {
            firstBatchLastMessageTime.current = documents[0].sentAt;
          }

          //// checking time to add snapshot listener till that last fetched message time.
          if (documents && documents.length > 0) {
            firstBatchLastMessageTime.current =
              documents[documents.length - 1].sentAt;
            setLastMessageFetchedTime(documents[documents.length - 1].sentAt);
          } else {
            /*
             as there is no chat
             so we have to listen every change in chat collection
             instead of fixing for few documents.
             Its used below to avoiding endAt filter.
             */
            setIsNewChat(true);

            let d = new Date();
            seconds = d.getTime() / 1000;
            firstBatchLastMessageTime.current = {seconds};
            setLastMessageFetchedTime({seconds});
          }

          setMessages([...documents]);
          setLoading(false);
        });
    }
  }, [chatId, setChatId, setLoading, setMessages, uid]);

loadMore Code

  async function loadMore() {
    let startAfterTime;
    if (messages.length > 5) {
      startAfterTime = messages[messages.length - 1].sentAt;

      let docs = await getMoreMessages(chatId, startAfterTime);

      if (docs && docs.length > 0) {
        setLastMessageFetchedTime(docs[docs.length - 1].sentAt);
      }

      setMessages([...messages, ...docs]);
    }
  }

That causes a big freeze and lagg in UI. It’s of no use. Because if new document is created we want to listen that and if any other document is changed/removed we want to listen that only. Listening to already existing documents in useless. It’s not a bug but is marked in firebase documentation that it listen to all the previous documents as added.

I avoided to process the documents that were already available by checking the time of the last message I get in the first fetched. As there is not going to be any document created before the message I already fetched. But till that condition it render the loop. That causes a big lagg/freeze in UI.

any alternate or change in this scenario will be much appreciated.
This is the code to listen to the changes.:

 useEffect(() => {
    if (
      chatId &&
      chatId !== '' &&
      chatId.length >= 1 &&
      lastFetchedMessageTime
    ) {
      let firebaseQuery = firestore()
        .collection('chats/' + chatId + '/messages')
        .orderBy('sentAt', 'desc');

      /* if its new chat so it should not apply this filter
       becuase there is no data already on firestore
      so it will not listen to the changes we are going to make now.
      Like if we are going to send a new message */

      if (!isNewChat) {
        firebaseQuery = firebaseQuery.endAt(lastFetchedMessageTime);
      }

      firebaseQuery.onSnapshot(snapshot => {
        snapshot.docChanges().forEach(change => {
          const message = change.doc.data();
          message.id = change.doc.id; 
          // It will not process any change of type 'added'. if the message is sent before the last time of the first batch.

          if (
            change.type == 'added' &&
            message.sentAt.seconds < firstBatchLastMessageTime.current.seconds
          ) {
            return;
          } 
          // Handle the specific change made to the message (e.g., update UI, apply changes, etc.)
          switch (change.type) {
            case 'added':
              // Handle newly added message
              handleNewDocumentCallback(message);
              break;
            case 'modified':
              // Handle modified message
              handleChangeDocumentCallback(message);
              break;
            case 'removed':
              // Handle removed message
              handleDeleteDocumentCallback(message);
              break;
          }
        });
      });
    }
  }, [chatId, isNewChat, lastFetchedMessageTime]);

How can i scroll to each section inside a overflow container with click of a button?

I have a container that has some sections inside, and it scrolls using the user’s scroll value. I want to scroll to each section with the click of a button.

I tried to use the scrollIntoView() function, but that didn’t work for me because I am using gsap for trigger position and I also have some other animation linked with it, so if I use scrollIntoView(), my other animation won’t work. So, I would need to scroll the window to make the animations work. I tried a lot of things like overighting the progress of scrollTrigger, using offsetTop value of the container and adding the height of the section but couldn’t figure out something that worked. If someone can help, I would appreciate it.

Here’s a little demo of what i’ve been trying:

const container = document.querySelector(".container");
const content = document.querySelector(".content");
const buttons = document.querySelectorAll(".button");
const slides = document.querySelectorAll(".texts");
const wrappper = document.querySelector(".wrapper");

const scrollToElement = (index) => {
  let totalOffset = wrappper.offsetTop;

  for (let i = 0; i < index; i++) {
    totalOffset += slides[i].offsetHeight / 3;
    console.log(i);
  }

  const scrollOff = totalOffset;
  console.log(scrollOff);

  window.scrollTo({
    top: scrollOff,
    behavior: "smooth"
  });
};

buttons.forEach((button, index) => {
  button.addEventListener("click", () => {
    scrollToElement(index);
  });
});

ScrollTrigger.create({
  trigger: container,
  start: "top top",
  end: "bottom top",
  pin: true,
  scrub: 0.1,
  markers: true,
  onUpdate: (self) => {
    const progress = self.progress;

    animationProgress = progress;

    const scrollPosition =
      progress * (content.scrollHeight - container.offsetHeight);
    content.scrollTop = scrollPosition;
  }
});