Forestry + Gatsby Image – reference image from JSON files

I’m looking into using Forestry with Gatsby (and use gatsby-plugin-image to optimize the images), but I’m stuck on how to get it working and not sure if it’s even possible.

  1. The first approach I tried (not working with Gatsby Image) is:

The image path is set in JSON files (to make all page content editable) and the images are uploaded to the static/uploads folder because Forestry requires an absolute path for the images:

content/pages/home.json:

{
  "title": "Home",
  "hero_image": "../../uploads/hero_image.png",
  "hero_image_alt": "An image",
  ...
}

–> This approach will not make it queryable in GraphQL by Gatsby so I can only use it in a normal img tag:

pages/index.js:

import { useStaticQuery, graphql } from "gatsby"
...
const { allPagesJson } = useStaticQuery(
    graphql`
      {
        allPagesJson {
          nodes {
            hero_image_alt
            hero_image
          }
        }
      }
    `

const data = allPagesJson.nodes[0]
<img src={data.hero_image} alt={data.hero_image_alt} />
  1. Second approach I tried (queryable but still not working) is:

The images are uploaded to content/images and then a relative path is added in the JSON files:

content/pages/home.json:

{
  "title": "Home",
  "hero_image": "../images/hero_image.png",
  "hero_image_alt": "A picture"
}

–> This approach makes it queryable, so I’d think I can use it in the GatsbyImage component, but it always returns a 404 error:

pages/index.js:

import { useStaticQuery, graphql } from "gatsby"
import { GatsbyImage, getImage } from "gatsby-plugin-image"
...
const { allPagesJson } = useStaticQuery(
    graphql`
      {
        allPagesJson{
          nodes {
            hero_image_alt
            hero_image {
              childImageSharp {
                gatsbyImageData
              }
            }
          }
        }
      }
    `
  )
...
const data = allPagesJson.nodes[0]
const hero_image = getImage(data.hero_image)
...
<GatsbyImage image={hero_image} alt={data.hero_image_alt} />

This returns the error:
GET http://localhost:8000/static/130e6fa61e2ebe523785c187e562a5f8/61d51/hero_image.webp 404 (Not Found)

I’ve been struggling with this all afternoon and not sure what else I can try to get it working with Forestry.

My basic requirements are that I need to be able to make all page content editable (text/images) for users instead of only being able to create posts + optimize the images with GatsbyImage so if there’s a better way in general to make that happen I’m also all ears.

Type error: Subsequent variable declarations must have the same type. Variable ‘e’ must be of type ‘any’, but here has type ‘Event’

I am trying to build the project and would like to deploy it to vercel but getting some type errors.

The site runs fine in development (using yarn dev).

These are the two functions am using to close a modal without event propagation.

    //Closes the modal
    const exitModal = (e) => {
    closeModal(false)

    //this part stops the click from propagating
    if (!e) var e = window.event
    e.cancelBubble = true
    if (e.stopPropagation) e.stopPropagation()
   }

  const exitAndRefresh = (e) => {
    exitModal(e)
    window.location.reload()
  }

The JSX below with the onClick function:

              <button
                className="absolute z-10 top-0 right-0 mt-1 mr-2 p-2 rounded-lg text-white bg-red-500 hover:bg-red-700"
                onClick={exitModal}
              >
                Cancel
              </button>

Build Error: (using yarn build)

Type error: Subsequent variable declarations must have the same type.  Variable 'e' must be of type 'any', but here has type 'Event'.

  91 |
  92 |     //this part stops the click from propagating
> 93 |     if (!e) var e = window.event
     |                 ^
  94 |     e.cancelBubble = true
  95 |     if (e.stopPropagation) e.stopPropagation()
  96 |   }

I tried doing this –

//Closes the modal
  const exitModal = (e: Event) => {
    closeModal(false)

    //this part stops the click from propagating
    if (!e) var e = window.event
    e.cancelBubble = true
    if (e.stopPropagation) e.stopPropagation()
  }

  const exitAndRefresh = (e: Event) => {
    exitModal(e)
    window.location.reload()
  }

But got this error instead:

Type error: Type '(e: Event) => void' is not assignable to type 'MouseEventHandler<HTMLButtonElement>'.
  Types of parameters 'e' and 'event' are incompatible.
    Type 'MouseEvent<HTMLButtonElement, MouseEvent>' is missing the following properties from type 'Event': cancelBubble, composed, returnValue, srcElement, and 7 more.

  158 |               <button
  159 |                 className="absolute z-10 top-0 right-0 mt-1 mr-2 p-2 rounded-lg text-white bg-red-500 hover:bg-red-700"
> 160 |                 onClick={exitModal}
      |                 ^
  161 |               >
  162 |                 Cancel
  163 |               </button>
error Command failed with exit code 1.

Webcam Access for Custom Filters:vTypeError: URL.createObjectURL: Argument 1 is not valid for any of the 1-argument overloads

I am currently trying to improve my JS skills by going through WesBos’s 30 Days of JavaScript. (It is really fun if!) I’m currently on Day 19, which is about using JS to access the WebCam, and then add affects using CSS.

I was successfully able to set up a local server, and here is my code so far:

 function getVideo() {
        navigator.mediaDevices.getUserMedia({video: true, audio: false})
        .then(localMediaStream => {
            console.log(localMediaStream);
            video.src = window.URL.createObjectURL(localMediaStream);
            video.play();
        })
        .catch(err => {
            console.error(`Web camera access is not enabled. To resolve, reload the page and allow 
    access.`, err);
        });
    }
    
    getVideo();

However, I am getting this error:

    TypeError: URL.createObjectURL: Argument 1 is not valid for any of the 1-argument overloads.
    getVideo http://localhost/19-webcam-fun/scripts.js:12
    promise callback*getVideo http://localhost/19-webcam-fun/scripts.js:10
    <anonymous> http://localhost/19-webcam-fun/scripts.js:27

Idk if this helps, but the console.log(localMediaStream) results in the following:


    MediaStream { id: "{97c3d27e-404e-4d14-b1d2-2a9ebbf09137}", active: true, onaddtrack: null, 
    onremovetrack: null }
    ​
    active: true
    ​
    id: "{97c3d27e-404e-4d14-b1d2-2a9ebbf09137}"
    ​
    onaddtrack: null
    ​
    onremovetrack: null
    ​
    <prototype>: MediaStreamPrototype { getAudioTracks: getAudioTracks(), getVideoTracks: 
    getVideoTracks(), getTracks: getTracks(), … }

I would really appreciate it if someone could help me understand this a little better! Thanks!

Why I get this error when trying to simplify an 3D model using SimplifyModifier of Three.js?

I’m trying to simplify an 3D Model (.STL file) that is loaded using STLLoader and the Three.js function SimplifyModifier to reduce vertices and simplify the model.

I have a function called loadMesh that loads the file and return an Three.js mesh that renders on a Scene:

     /**
     * Method to load the mesh model from .stl or .3mf file and return Mesh ThreeJS object
     * @param {*} part Part or model of a part, on form of a .stl or .3mf file
     * @param {*} color Color of the mesh material. Default = #0096d6
     * @returns Mesh from ThreeJS
     */
    static loadMesh(part, color = '#0096d6') {
        if (!FileUtil.existsPath(part.path)) return null;

        const loader = (Loader, encoding) => new Loader().parse(FileUtil.readFile(part.path, encoding));

        let mesh = null;
        const material = new THREE.MeshStandardMaterial({ color, flatShading: true });

        const ext = FileUtil.getExtName(part.path, true).toLowerCase();
        if (ext == 'stl') {
            const geometry = loader(STLLoader, 'binary');

            // Make an instance of SimplifyModifier
            const modifier = new SimplifyModifier();

            // Create Mesh wit geometry and material already defined
            mesh = new THREE.Mesh(geometry, material);

            // Number of vertices to remove from part
            const count = Math.floor( mesh.geometry.attributes.position.count * 0.1 );

            console.log(count);

            // Now modify the geometry of our mesh to optimize number of polygons
            mesh.geometry = modifier.modify( mesh.geometry, count );


        } else if (ext == '3mf') {
            mesh = loader(ThreeMFLoader, 'buffer');

            for (const [index, buildItem] of Object.entries(mesh.children)) {
                (function updateMaterial(children) {
                    for (const child of children) {
                        if (child.children?.length > 0) {
                            updateMaterial(child.children);
                        } else {
                            child.index = String(index);
                            child.material = material.clone();
                        }
                    }
                })(buildItem.children);
            }

            if (part.buildItemIndex != 'all') {
                mesh = mesh.children[+part.buildItemIndex];
                mesh.position.set(0, 0, 0);
            }
        }

        mesh.part = part;
        MeshUtil.resetOrigin(mesh);

        return mesh;
    }

Currently the app supports two 3d files extensions: .STL and .3MF, that’s why you can use that the function checks the extension and its executes based on that. But for the moment im trying to simplify an STL model, so the important thing here is happening inside the STL if condition:

            const geometry = loader(STLLoader, 'binary');

            // Make an instance of SimplifyModifier
            const modifier = new SimplifyModifier();

            // Create Mesh wit geometry and material already defined
            mesh = new THREE.Mesh(geometry, material);

            // Number of vertices to remove from part
            const count = Math.floor( mesh.geometry.attributes.position.count * 0.1 );
//
            console.log(count);

            // Now modify the geometry of our mesh to optimize number of polygons
            mesh.geometry = modifier.modify( mesh.geometry, count );

When I try to render the model on another component using

// mesh is the returned mesh from the above function
scene.add(mesh);

I get the next error on console:

Error of undefined on console

Notes

Already tried to change count of vertices to remove and there is no difference.

For better reference, there are the properties of the geometry object that im trying to simplify:
geomtry object properties

The purpose of this is because in some cases the app can receive large files and it crashes when trying to render on Scene.

Also, don’t know if there is any problem that is BufferGeometry, and if its the case, how can I solved that?

3 buttons have different inputs but showing the same output as the first button

I have 3 modal buttons. All three buttons have different inputs. But when I press the first button, everything is showing completely fine but when I press the 2nd and 3rd button, it shows the same results as the first button. Please have a look, I am attaching my code below.

Extra: It would be very helpful for me if you can suggest me, how I can put multiple photos stacked in the modal body without losing the shape of the modal. It will show a single photo in the modal body but if someone swap over the picture then the next picture will arrive. Thank you so much.

// Modal
// Get DOM Elements
const modal = document.querySelector('#my-modal');
const modalBtn = document.querySelectorAll('.button');
const closeBtn = document.querySelector('.close');

// Events
modalBtn.forEach(btn => btn.addEventListener('click', openModal));
closeBtn.addEventListener('click', closeModal);
window.addEventListener('click', outsideClick);

// Open
function openModal() {
  modal.style.display = 'block';
}

// Close
function closeModal() {
  modal.style.display = 'none';
}

// Close If Outside Click
function outsideClick(e) {
  if (e.target == modal) {
    modal.style.display = 'none';
  }
}
/* Modal section styling */

:root {
    --modal-duration: 1s;
    --modal-color: crimson;
  }
  
  .button {
    font-family: 'poppins', sans-serif;
    display: inline-block;
    background: crimson;
    color: #fff;
    font-size: 18px;
    font-weight: 500;
    padding: 8px 16px;
    margin-top: 20px;
    border-radius: 6px;
    border: 2px solid crimson;
    transition: all 0.3s ease;
  }
  
  .button:hover {
    color: crimson;
    background: none;
  }
  
  .modal {
    display: none;
    position: fixed;
    z-index: 99999;
    left: 0;
    top: 0;
    height: 100%;
    width: 100%;
    overflow: auto;
    background-color: rgba(0, 0, 0, 0.5);
  }
  
  .modal-content {
    margin: 50px auto;
    width: 60%;
    box-shadow: 0 5px 8px 0 rgba(0, 0, 0, 0.2), 0 7px 20px 0 rgba(0, 0, 0, 0.17);
    animation-name: modalopen;
    animation-duration: var(--modal-duration);
  }
  
  .modal-header h2,
  .modal-footer h3 {
    margin: 0;
  }
  
  .modal-header {
    background: var(--modal-color);
    text-align: center;
    padding: 10px;
    color: #fff;
    border-top-left-radius: 5px;
    border-top-right-radius: 5px;
  }
  
  .modal-body {
    padding: 10px 5px 1px 5px;
    background: #fff;
  }
  
  .modal-footer {
    background: var(--modal-color);
    padding: 10px;
    font-size: 15px;
    font-weight: lighter;
    color: #fff;
    text-align: center;
    border-bottom-left-radius: 5px;
    border-bottom-right-radius: 5px;
  }
  
  .close {
    color: #ccc;
    float: right;
    font-size: 30px;
    color: #fff;
  }
  
  .close:hover,
  .close:focus {
    color: #000;
    text-decoration: none;
    cursor: pointer;
  }
  .responsive {
    width: 100%;
    height: auto;
  }
  @keyframes modalopen {
    from {
      opacity: 0;
    }
    to {
      opacity: 1;
    }
  }
<!-- Modal Button 1 start -->
<button id="modal-btn" class="button">Parkit</button>
<div id="my-modal" class="modal">
  <div class="modal-content">
    <div class="modal-header">
      <span class="close">&times;</span>
      <h3>Vehicle Parking Application</h3>
    </div>
    <div class="modal-body">
      <img src="https://thefinancialexpress.com.bd/uploads/1575560371.jpg" alt="Vehicle Parking Application" class="responsive">
    </div>
    <div class="modal-footer">
      <p>
      Footer
      </p>
    </div>
  </div>
</div>
<!-- Modal Button 1 end -->

<!-- Modal Button 2 start -->
<button id="modal-btn2" class="button">IPDC IMS</button>
<div id="my-modal2" class="modal">
  <div class="modal-content">
    <div class="modal-header">
      <span class="close">&times;</span>
      <h3>Asset Management System</h3>
    </div>
    <div class="modal-body">
      <img src="#" alt="Asset Management System" class="responsive">
    </div>
    <div class="modal-footer">
      ...
    </div>
  </div>
</div>
<!-- Modal Button 2 end -->

<!-- Modal Button 3 start -->
<button id="modal-btn3" class="button">Gaming Website</button>
<div id="my-modal3" class="modal">
  <div class="modal-content">
    <div class="modal-header">
      <span class="close">&times;</span>
      <h3>Gaming Website</h3>
    </div>
    <div class="modal-body">
      ...
    </div>
    <div class="modal-footer">

    </div>
  </div>
</div>
<!-- Modal Button 3 end -->

ARjs: Camera Video not centered / wrong image ratio

This problem arises using aframe v1.2.0 and ARjs master branch

Hey everyone:

Is there a way to center the camera image in ARjs?
I am currently using the version from the master branch, but the video is shifted, when using aframe version 1.2.0.
I know that the newest version of aframe is 1.3.0 but there are known incompatibilities with ARjs master branch. When using the dev branch the errors are resolved, but the video is still not centered.

Image from Android Studio:
Video not centered – Android Studio

The desired video should look like this:
Video centered – Android Studio

Script imports:

src=”https://aframe.io/releases/1.3.0/aframe.min.js”

src=”https://unpkg.com/[email protected]/dist/aframe-look-at-component.min.js”

src=”https://raw.githack.com/AR-js-org/AR.js/dev/aframe/build/aframe-ar-nft.js”

Kind regards

Angular swiper is not working Nothing is displayed

I have such a file with markup
HTML

    <div class="reviews__inner">
      <swiper [pagination]="{ type: 'fraction'}" [navigation]="true" class="mySwiper">
        <div class="slider__one">
          <div class="wrapper__one">
            <ng-template swiperSlide>
              <div *ngFor="let slide of slides" class="slide__one">
                <div class="slide__wrap">
                  <img src="{{ slide.image }}" alt="stars" class="stars">
                  <div class="slide__title_size_s">{{ slide.title }}</div>
                  <div class="slide__subtitle_size_s">{{ slide.subtitle }}</div>
                </div>
              </div>
            </ng-template>
          </div>
        </div>
      </swiper>
    </div>

.TS

...
SwiperCore.use([Navigation, Pagination]);
...

I connected the swiper module and nothing is displayed when the page loads, and there are no errors in the console. I did everything according to the official documentation

How to push a container from one HTML page to another one using Vue.js?

To make the HTML code shorter, I decided to put some of the elements outside the main file and then load them from there like a template.
I’ve read through all tutorials I could find but I didn’t find any information about how to do this using Vue.js.

So, here is an example of my problem:

Main file:

<body>
   <span>Here is the place where I want to add an element</span>
</body>

New File:

<h3 @click="SomeFunction()">Hello, {{someVariable}}!</h3>

Is it possible to somehow put the code from the New file to the Main one and then render the page?

How to optimize performance in a list with thousands of items?

I’m building a Chat, the case is as follows.
As users send more messages, more items are added to a list that contains the chat messages, it can reach thousands of thousands (100k for example), my question is if I have to use some lazyload library or js code, to that the browser is not overloaded with so many items.

Maybe the browser supports hundreds of thousands of items (more than 100k) without adding anything, or if I really have to use lazyload or some js code, help me please.

My code is simple:

<div class="chat__content" id="chat-content">
   <div class="message">
       <span class="message__user">Bill Gates</span>
       <span class="message__content">Hello World!</span>
   </div>
</div>

And a socket that is responsible for listening to incoming messages (socket.io)

socket.on("chat:message", function (message) {
  var div = document.createElement("div");
  div.classList.add("message");
  div.innerHTML = '<span class="message__user">' + message.user + '</span><span class="message__content">' + message.content + "</span>";

  const chatContent = document.getElementById('chat-content')
  chatContent.appendChild(div)
  chatContent.scrollTop = chatContent.scrollHeight - chatContent.clientHeight
});

Uncaught SyntaxError: Unexpected token y in JSON at position 0? – Leads Tracker Chrome Extension

I’m trying to do a leads tracker chrome extension from a tutorial, and I’m following the code to a T. Here is my Code:

**HTML**
     <html>
      <head>
        <link rel="stylesheet" href="Practice.css" />
      </head>
      <body>
        <input type="text" id="input-el" />
        <button id="input-btn">SAVE INPUT</button>
        <button id="tab-btn">SAVE TAB</button>
        <button id="delete-btn">DELETE ALL</button>
        <ul id="ul-l"></ul>
        <script src="Practice.js"></script>
      </body>
    </html>


**javascript**
    let myLeads = [];
    let oldLeads = [];
    
    const inputEl = document.getElementById("input-el");
    const InputBtn = document.getElementById("input-btn");
    const ulEl = document.getElementById("ul-l");
    const DeleteBtn = document.getElementById("delete-btn");
    const TabBTN = document.getElementById("tab-btn");
    
    let LeadsFromLocalStorage = JSON.parse(localStorage.getItem("myLeads"));
    
    if (LeadsFromLocalStorage) {
      myLeads = LeadsFromLocalStorage;
      Render(myLeads);
    }
    
    function Render(Leads) {
      let ListItems = "";
      for (let i = 0; i < Leads.length; i++) {
        ListItems += `
        <li> 
          <a target = blank href = ${Leads[i]}>
            ${Leads[i]} 
          </a>
        </li>`;
      }
      ulEl.innerHTML = ListItems;
    }
    
    TabBTN.addEventListener("click", function () {
      chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
        myLeads.push(tabs[0].url);
        localStorage.setItem("myLeads", JSON.stringify(myLeads));
        Render(myLeads);
      });
    });
    
    DeleteBtn.addEventListener("dblclick", function () {
      localStorage.clear("myLeads");
      myLeads.length = 0;
      Render(myLeads);
    });
    
    InputBtn.addEventListener("click", function () {
      myLeads.push(inputEl.value);
      inputEl.value = "";
      localStorage.setItem("myLeads", JSON.stringify(myLeads));
      Render(myLeads);
    });


**JSON**
    {
      "manifest_version": 3,
      "version": "1",
      "name": "Leads Tracker",
      "action": {
        "default_popup": "Practice.html",
        "default_icon": "AmongUs.png"
      },
      "permissions": ["tabs"]
    }

Every time I’m entering a link into the text box it won’t show up on the extension itself. If I open it in a tab by itself it will work just fine. Honestly don’t understand what is wrong.

More error info from chrome

How to reuse props used previously to navigate to url using react router v6

I have this route <Route path="/edit/:id" exact element={<Editar />} /> where i can redirect from <Dashboard>. I dont have any error redirecting to /edit/idClickedOnDashboard but once i redirected to <Editar> i want to reuse this idClickedOnDashboard (to make an url to call API) using props.match.params.id but error says props.match is undefined

Routes:

<BrowserRouter>
        <Routes>
          <Route path="/" exact element={<Login  />} />
          <Route path="/dashboard" exact element={<Dashboard  />} />
          <Route path="/new" exact element={<Nuevo  />} />
          <Route path="/edit/:id" exact element={<Editar />} />
        </Routes>
      </BrowserRouter>

On Dashboard

export const Dashboard = (props) => {
  const [paciente, setPaciente] = useState([]);
  const navigate = useNavigate();
  useEffect(() => {
    let url = `${Apiurl}pacientes?page=1`;
    axios.get(url).then((response) => {
      setPaciente(response.data);
    });
  }, []);

  const handleClick = (id) => {
    navigate(`/edit/${id}`);
  };

  return (
    <>
      <Header />
      <div className="container">
        <table className="table table-dark table-hover">
          <thead>
            <tr>
              <th scope="col">ID</th>
              <th scope="col">DNI</th>
              <th scope="col">NOMBRE</th>
              <th scope="col">TELEFONO</th>
              <th scope="col">CORREO</th>
            </tr>
          </thead>
          <tbody>
            {paciente.map((data, i) => {
              return (
                <tr key={i} onClick={() => handleClick(data.PacienteId)}>
                  <td>{data.PacienteId}</td>
                  <td>{data.DNI}</td>
                  <td>{data.Nombre}</td>
                  <td>{data.Telefono}</td>
                  <td>{data.Correo}</td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>
    </>
  );
};

Finally where i get error Editar.jsx

import React, { useEffect } from "react";
import { useParams } from "react-router-dom";

import { Apiurl } from "../services/api";

export const Editar = (props) => {
  //const { id } = useParams();
  useEffect(() => {
    let pacienteId = props.match.params.id;
    let url =`${Apiurl}pacientes?id=${pacienteId}`;
    console.log(url);
  }, []);





  return <div>Editar</div>;
};

Error
error

What are the aspects of JS binding?

Have the following simpliest component.

class App extends Component {
  constructor(props) {
    super(props);
    console.log(this);
    this.state = {
      name: "John"
    }
  }

  clickHandler() {
    this.setState({
      name: "Mark"
    })
  };

  render() {
    return (
      <div className="App">
        {this.state.name}
        <button onClick={this.clickHandler.bind(this)}></button>
      </div>
    )
  };
}

export default App;

If I write that

<button onClick={this.clickHandler}></button>

it says that this in

this.setState({
      name: "Mark"
    })

is undefined.
That row

<button onClick={console.log(this)}></button>

shows that this is App.
So if this is App why clickHandler does not bind automatically to that object before the dot?

<button onClick={this.clickHandler}></button>

As far as I understand in “context.function” the context should be bound to the function. Or it only works for “context.function()”?

How to add item to array with useState hook in React? [duplicate]

I am new to React and I searched examples for this questions but I could not achieve to do this.

I make 2 separate calls to backend and getting 2 different dto and I want to put them into one table data instead of 2 separate ones.

Here is my code:

const [lensTableData, setLensTableData] = useState<InternalDTO>();
    const [dbsaTableData, setDbsaTableData] = useState<InternalDTO>();
    
useEffect(() => {
        context.services.adapterStatus.getLensAdapterStatus()
            .then((resp) => setLensTableData(resp));

        context.services.adapterStatus.getDbsaAdapterStatus()
            .then((resp) => setDbsaTableData(resp));
    }, [])

It is working but what I want to do is to make just 1 array instead of 2 different and I want to add 2nd one into array after the first one. How can I combine them ?