After updating PhpStorm to 2024.1 it’s no longer possible to go to the declaration of a JavaScript function by Ctrl+click left
Cannot find declaration to go to
Category: javascript
Category Added in a WPeMatico Campaign
toDataUrl() freezes when trying to save blob on iPhone
I am trying to save a div locally with the HTML2Canvas dependency. Everything seems to be working perfect on desktop and Android phones, but on an iPhone there is am facing the following problem:
When trying to save the generated canvas with the following code, the browser freezes:
html2canvas(document.getElementById("theID"), {
scale: 5,
allowTaint: true,
imageTimeout: 15000,
logging: true,
useCORS: true,
}).then(function (canvas) {
if (saveLocally) {
console.log("Start saving locally: ");
console.log(canvas);
canvas.toBlob(function (blob) {
console.log(blob);
var imgsrc = canvas.toDataURL("image/png");
});
console.log("finished creating screenshot");
window.location.href = "https://example.com/cart";
}
});
The following output is written in the console:
DEBUG#1 0ms Starting document clone with size 414x720 scrolled to 0,-170
WARNING#1 1054ms Unable to restore scroll position for cloned document
DEBUG#1 1057ms Document cloned, element located at 76.15625,81.34375 with size 1066.4046630859375x1508.0211181640625 using computed rendering
DEBUG#1 1057ms Starting DOM parsing
DEBUG#1 1088ms Added image data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink' fill-rule='evenodd' viewBox='0 0 88 23'%3E%3Cdefs%3E%3Cpath id='logo' d='M11.5 2.25c5.105 0 9.25 4.145 9.25 9.25s-4.145 9.25-9.25 9.25-9.2
DEBUG#1 1088ms Starting renderer for element at 76.15625,81.34375 with size 1067x1509
DEBUG#1 1089ms Canvas renderer initialized (1067x1509) with scale 5
DEBUG#1 1130ms Finished rendering
LOGStart saving locally:
LOG[object HTMLCanvasElement]
I have found some information on the internet that the maximum size of a canvas on Ios is quite small, so maybe that could be the issue. But what is the solution on this? Is it possible to manually increase the maximum size for example?
I want my images to have the best quality (most of them are around 12MB).
Also trying to save the blob with saveAs(blob, 'customImage.png'); from the FileSaver library does freeze the window.
single header and footer frame page or multi main pages and include header and footer
is it better to load header and footer on multiple pages or load main div Granular between header and footer in a single page
wich is better?
1.fixed header and footer and load body of pages
$(function(){
$("#bodySection").load("/pages/Main/main.html");
});
2.fixed multi pages and load footer and header
$(function(){
$("#header").load("header.html");
$("#footer").load("footer.html");
});
Applicazione web per picking e gestire un Magazzino [closed]
Buongiorno,
Vorrei sapere come si può sviluppare o avere qualche esempio per fare un applicazione web per picking, e gestire gli ordini entro un magazzino.vi allego un screenshot come esempio.
Vorrei sapere come si può sviluppare o avere qualche esempio per fare un applicazione web per picking, e gestire gli ordini entro un magazzino.vi allego un screenshot come esempio.
jest mock “TypeError: Cannot assign to read only property”
I am using jest 29.7.0
I have a module named message.js with
export async function send() {...}
Then in my test I want to mock the send function.
I tried with
import { jest } from '@jest/globals'
import * as message from "../../message.js"
it("Test", function(){
jest.spyOn(message, 'send').mockImplementationOnce(() => Promise.resolve());
})
But the spyOn is throwing TypeError: Cannot assign to read only property 'send' of object '[object Module]'
I also tried with
message.send = jest.fn();
But I have the same issue
I also tried adding
jest.mock('../../message.js', () => ({
__esModule: true,
send: jest.fn(),
}));
after, before the import, in the test, in an before
But in each cases I have the same issue calling message .send.mockReturnValue(Promise.resolve) TypeError: message.send.mockReturnValue is not a function
I also tried with
Object.defineProperty(message, "send", {
value: jest.fn(),
configurable: true,
writable: true
});
Before calling jest.spyOn but it throws TypeError: Cannot redefine property: send
Hi. I am new to programming and I am trying to create a search bar in html which store search input as string
<i id="show"></i>//Out put will show here//
<input id="search" type="text" placeholder="Search...">//Search Bar//
<button value="submit" onclick="return test()" type="submit">Search</button>
<script>//Main function//
function test(){
var a = document.getElementById('search').value;
var b = "Apple, Banana";
for (var c = 0; c <= 1; c++) {
if (a.innerHTML().match(b[c])){
document.getElementById('show').innerHTML = "You search " + "'" + b[c] + "'";
}
else
document.getElementById('show').innerHTML = "ERROR.";
}
}
</script>
I am trying to create a search bar in html with 3 main functions. Store a search input as string(a), see if the string(a) and data(b) match or not, if mach then show data and if not, show error. But I not getting any output. I don’t know where I am wrong or maybe my whole code is wrong. Sorry for bad english.
Looping through folder of files & extracting exported JS Object from each?
I am working in nodejs / nextjs, where I have access to the file system. I have multiple React files in a folder:
content
- blog-post-1.jsx
- blog-post-2.jsx
- blog-post-3.jsx
I now want to go through the files in this folder and extract the frontmatter of each file. I was thinking of exporting a javascript object from each file, e.g.:
// e.g.: blog-post-1.jsx
export const frontmatter = {
title: "My Title",
published: "02/12/2024"
}
But I am stuck here: How could I map through the folder and automatically grab the frontmatter object from each file, without knowing the exact number of files in the content folder?
I have built an extension, I want to toggle On/Off so that it will turn on/off the extension. How can i do that? [duplicate]
document.addEventListener('DOMContentLoaded', function() {
const toggleSwitch = document.getElementById('toggleSwitch');
const toggleStatus = document.getElementById('toggleStatus');
// Set initial state of toggle switch
chrome.storage.sync.get('enabled', function(data) {
const isEnabled = data.enabled;
toggleSwitch.checked = isEnabled;
toggleStatus.textContent = isEnabled ? 'Extension is currently ON' : 'Extension is currently OFF';
});
// Toggle extension state when switch is clicked
toggleSwitch.addEventListener('change', function() {
const enabled = toggleSwitch.checked;
chrome.storage.sync.set({ 'enabled': enabled }, function() {
toggleStatus.textContent = enabled ? 'Extension is currently ON' : 'Extension is currently OFF';
updateExtensionState(enabled);
});
if (!enabled) {
chrome.management.setEnabled('jgljfcgfldbadoohflpjbheloooggmdm', false);
}
});
// Update extension state based on toggle switch
function updateExtensionState(enabled) {
chrome.runtime.sendMessage({ command: "toggleExtension", enabled: enabled });
}
});
Here I got this error
Uncaught TypeError: chrome.management.setEnabled is not a function
can anyone help me to build on/off button for my extension?
solution code for on/off toggle button that turns on/off my extension in google chrome
Add space between functions
I give this code to Prettier
function firstFunction(){console.log('1 func')}; function secondFunction() {console.log('2 func')}
The output looks like this:
function firstFunction() {
console.log("1 func");
}
function secondFunction() {
console.log("2 func");
}
The problem is that two functions stick to each other.
I’d like to make code look like this. How do I make it?
function firstFunction() {
console.log("1 func");
}
function secondFunction() {
console.log("2 func");
}
I tried to read Prettier settings but didn’t find any option that would help me.
How can I make the shadow cover a component that has the css property “relative”
Below is a simple code, the essence of which boils down to the following: at the top of the page there is a shadow and if you scroll the page vertically, this shadow will be constantly visible, covering the components (except VideoComponent ) that are located in the div with id=’sub’.
<div id='main' class="flex h-full">
<div class="absolute inset-0 shadow-[inset_0_10px_3px_red] pointer-events-none"></div>
<div id='sub' class="overflow-auto" style="width: 100vw">
<div class="h-[50vh] bg-blue-200">Some text</div>
<div class="h-[50vh] bg-sky-200">Some text</div>
<VideoComponent />
<div class="h-[50vh] bg-teal-200">Some text</div>
<div class="h-[50vh] bg-emerald-200">Some text</div>
</div>
</div>
You may ask why it is necessary to use the “relative” CSS property in VideoComponent…..I’ll explain. Since in VideoComponent I use html tag video and overlay text and photos on the video itself using the CSS property “absolute”. In abbreviated form, this code looks like this:
export function VideoComponent() {
return (
<div className="relative grid">
<video className="aspect-video rounded-lg" ref={videoRef} />
{needText && (
<div className="absolute h-full w-full">
<TextView />
</div>
)}
{needPhoto && (
<div className="absolute h-full w-full">
<PhotoView />
</div>
)}
</div>
);
}
If a shadow passes through a VideoComponent, the shadow is no longer visible, meaning the VideoComponent covers the shadow. This happens because VideoComponent have the “relative” css property.
My question is this: how can I change the VideoComponent so that when scrolled it will be covered by a shadow and not break the current functionality in this component.
Perhaps, somehow you can influence not the VideoComponent, but the shadow (the first part of the code).
I would be grateful for any advice
Uncaught TypeError: Cannot read properties of undefined (reading ‘0’)- half fetching
am trying to fetching data from an API endpoint in a React application and displaying it in a component. Specifically, am fetching questions, answers, and explanations from the API and rendering them in a component called ReviewQuestions. The issue am facing is that while the questions and answers are being fetched and displayed correctly, the explanations are not showing up as expected. Despite fetching the explanations from the API and storing them in the Redux store as a string array, the explanations are not being rendered in the component, and instead, it always shows “No explanation available”.
// ReviewQuestions.js
import React, { useState } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { fetchQuestions } from '../../../store/actions/questionActions';
const ReviewQuestions = () => {
const dispatch = useDispatch();
const questions = useSelector(state => state.questions.queue);
const answers = useSelector(state => state.questions.answers);
const explain = useSelector(state => state.questions.explain);
const [fetching, setFetching] = useState(false);
const getOptionLetter = (index) => {
return String.fromCharCode(65 + index);
};
const handleFetchQuestions = () => {
setFetching(true);
dispatch(fetchQuestions())
.then(() => setFetching(false))
.catch(error => {
console.error('Error fetching questions:', error);
setFetching(false);
});
};
if (fetching) {
return <div>Loading questions...</div>;
}
if (!questions || questions.length === 0) {
return <div>No questions available</div>;
}
return (
<div className='box'>
<h1 className='title text-white text-2xl'>Review Questions</h1>
<div className='overflow-auto' style={{ maxHeight: '80vh' }}>
<div className='grid grid-cols-1 gap-4'>
{questions.map((question, index) => (
<div key={index} className="bg-gray-200 p-4 rounded-lg">
<h2 className="text-xl font-bold mb-2">{index + 1}. {question.question}</h2>
<p className="text-green-600 font-semibold">
Correct Answer: {getOptionLetter(answers[index])} - {question.options[answers[index]]}
</p>
<p className="text-blue-600 font-semibold">
Explanation: {explain && explain[index] ? explain[index] : 'loading error'}
</p>
</div>
))}
</div>
</div>
</div>
);
};
export default ReviewQuestions;
i want to be fixed my db is working perfectly
Cannot find name ‘myFun’ (defined in included file “my-funs.js”)
The function myFun is defined in the included file:
<include src="my-funs.js"><script>
The include file has // @ts-check and a JSDoc comment for the function:
/**
*
* @param {*} type
* @param {*} attrib
* @param {*} inner
* @returns {*}
*/
function myFun(type, attrib, inner) {
// code
}
I am using VS Code and it tells me the error in the title.
I expected JSDoc/TypeScript to find the declaration of myFun, but obviously I was wrong.
What am I missing?
How can i import svelte framework to a script tag in html file?
Here’s the code where i wanna import svelte in. Fyi im using replit cuz i can’t use laptop for immobilities. I tried using that link which y’all need to scroll down to see but not working. Another ways i tried. Not working at all, though tried to do it on app.svelte tag and it’s not even showing on the WebView. Now these problems making me kinda wanna quit. Pls help on how can i do that
Code
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>replit</title>
<link href="style.css" rel="stylesheet" type="text/css" />
</head>
<body>
<script></script>
<svelte:head>
<script async src="https://www.example.com/my.js"></script>
</svelte:head>
</body>
</html>
</script>
How can I integrate HTML pages from a design company into Storybook for Angular?
I’ve received HTML pages from a design company to integrate into my Angular application.
These pages are structured with assets located in an app_files directory. I need to showcase them in Storybook. Typically, Storybook looks for *.stories.ts files, but my files are pure HTML.
I prefer not to modify these HTML files directly to maintain compatibility with updates from the design company. How can I serve these HTML pages in Storybook?
Do I need to create a separate stories file for each HTML page, or is there a more efficient approach?
(Those pages are NOT components; they are just plain HTML files I want to see in the storybook).
Code and structure:
project-root/
│
├── .storybook/
│ └── main.js
│
├── src/
│ ├── app/
│ │ ├── components/
│ │ │ ├── ...
│ │ │ ├── foo.component.ts
│ │ │ └── ...
│ │ └── ...
│ │
│ └── htmls/
│ ├── ...
│ ├── app_files/
│ │ ├── css/
│ │ │ ├── normalize.min.css
│ │ │ ├── base.css
│ │ │ └── style.css
│ │ ├── svg/
│ │ ├── img/
│ │ ├── fonts/
│ │ └── ...
│ │
│ ├── homepage.html
│ ├── page1.html
│ └── ...
│
└── ...
Sample HTML structure (e.g., homepage.html):
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>APP cheatsheet</title>
<link rel="stylesheet" href="app_files/css/normalize.min.css">
<link rel="stylesheet" href="app_files/css/base.css">
<link rel="stylesheet" href="app_files/css/style.css">
</head>
<body>
<main class="container-bg" style="background-image: none;">
..........
</main>
</body>
</html>
Allow newly added images to be loaded after a build in Next.js
I’ve recently rewritten a React app in Next.js (version 14.1.4). It’s a website that has a page with a list of products, each product consisting of some text and an image. The content is managed by the owner through an admin panel, which is a separate application, so products can be changed, deleted and added at any time.
After building the app on my server, I noticed that newly added images weren’t being loaded by Next.js. This made sense to me as I was using the Image component from next/image. Since my images are already optimized in the backend with the appropriate formats and sizes, I decided to take care of it myself and avoid using the Image component. However, this didn’t work as I still had the problem of new images not loading.
I couldn’t find any information in the official documentation on how to handle this properly, so I created a custom request handler that returns the appropriate image as a response:
// api/images/[itemId]/[imageName]/route.ts
import { type NextRequest } from "next/server";
import path from "path";
import fs from "fs";
export async function GET(
request: NextRequest,
{ params }: { params: { itemId: string; imageName: string; } }
) {
const searchParams = request.nextUrl.searchParams;
const size = searchParams.get("size");
const type = searchParams.get("type");
const productType = searchParams.get("productType");
const { itemId, imageName } = params;
const imagePath = path.join(
process.cwd(), "public", "uploads", `${productType}`, itemId, `${imageName}_${size}.${type}`
);
if (!fs.existsSync(imagePath)) {
return new Response("Image not found", { status: 404 });
}
let contentType: string;
switch (type) {
case "jpg":
contentType = "image/jpeg";
break;
case "webp":
contentType = "image/webp";
break;
default:
contentType = "image/jpeg";
}
const headers = {
"Content-Type": contentType
};
// Create a read stream from the image file and return it as the response
const stream = fs.createReadStream(imagePath);
// @ts-ignore
return new Response(stream, { headers });
}
I also created a custom Image component for this:
import clsx from "clsx";
type Props = React.ComponentPropsWithoutRef<"img"> & {
src: string;
alt: string;
productType: "products" | "gallery";
className?: string;
};
export default function CustomImage({
src,
alt,
productType,
className,
...rest
}: Props) {
return !src ? <p>No image</p> : (
<picture>
<source
type="image/webp"
srcSet={`${src}?size=sm&type=webp&productType=${productType} 450w, ${src}?size=md&type=webp&productType=${productType} 900w, ${src}?size=lg&type=webp&productType=${productType} 1350w`}
sizes="(min-width: 61.25em) 500px, 100vw" // 980px
/>
<img
loading="lazy"
src={`${src}?size=sm&type=jpg&productType=${productType}`}
alt={alt ?? ""}
width="400"
height="300"
className={clsx("product-image", className)}
{...rest}
/>
</picture>
);
}
This seemed to be working fine, but I noticed that the images were not always loading on my mobile device. When visiting the /products web page, the images are displayed without any problems. However, when I navigate from the product detail page /products/slug back to /products using the link provided in the breadcrumbs (it’s basically just a Link component), I’m back on the same page but without the images loading. Again, this behavior somehow only occurs on my mobile device, in all major browsers. Also worth noting is that I have the same Link component in my main navigation and everything works fine when I click on the /products link, very strange.
I find this kind of bug hard to track down, because I don’t know what’s really going on and what Next.js is doing under the hood that could be causing this error.
So, despite my attempts to gain control over the images, it seems that Next.js is still messing with my images, and I don’t want that.
Which brings me to my question: Am I on the right track with my approach to handling the images myself, or am I completely missing something and there is a much easier way to handle this?