I want to catch any errors in my node.js code and reply with a html file. I’ve heard about stuff like fastify.setErrorHandle() but can’t find any docs.
:>
Blancer.com Tutorials and projects
Freelance Projects, Design and Programming Tutorials
Category Added in a WPeMatico Campaign
I want to catch any errors in my node.js code and reply with a html file. I’ve heard about stuff like fastify.setErrorHandle() but can’t find any docs.
:>
I’m creating a restaurant homepage linked here https://github.com/AIessi/restaurant-homepage. I’m using webpack to bundle my code. I created a template for the HTML to follow called template.html in my src folder which outputs to my index.html in my dist folder. I created various JS modules for the different pages for the website, as well as a module to load the different JS modules. When I run my index.html file, all that runs is the template. I’m not sure why this is. Any help would be greatly appreciated.
I am building a simple stock tracker which includes a volume graph. The volume is in the ranges of 1k +- 100, while the prices are in the range 1440 +- 5. Because of this if I add in the volume directly in the same graph it zooms out. So I scaled the volume accordingly. Now although they are in the same range, I want to see the actual value when I hover over it.
This is the code for plotting the volume
const barTrace = {
x: {{vol_x | safe}},
y: {{vol_y | safe}},
type: 'scatter',
mode: 'lines',
name: 'Volume',
marker: {
color: 'rgba(255, 0, 0, 0.3)' // Bar color
}
};
data.push(barTrace);
This is my current code for updating the value based on a reference id.
document.getElementById('graph').on('plotly_hover', function(data){
data.points.forEach(function(hoverData){
const traceName = hoverData.data.name; // Assuming curveNumber corresponds to the trace's index
const value = hoverData.y;
// Check if the hovered point belongs to the specific line
if (traceName === 'Volume') {
const reference = {{ vol_reference | safe }};
const displayedValue = reference[value];
console.log(displayedValue)
}})
});
This logs the real value displayedValue to console. However I am stumped on how to replace the indicator next to volume. That is, the 1443.2 should be replaced with displayedValue.
P.S. I am using flask so for those who are unaware {{value}} is replace with the real value which is either an array or json data
async function gatherFilesInfo(postId, fileInputs) {
const postRef = doc(db, 'posts', postId);
const postSnapshot = await getDoc(postRef);
if (!postSnapshot.exists()) {
console.error('Document does not exist!');
return [];
}
const postData = postSnapshot.data();
let existingFiles = postData.files || [];
let newFilesData = existingFiles.map(file => ({ ...file }));
for (let i = 0; i < fileInputs.length; i++) {
const fileInput = fileInputs[i];
if (fileInput && fileInput.files && fileInput.files.length > 0) {
const file = fileInput.files[0];
const storageRef = ref(storage, `posts/${postId}/files/${file.name}`);
const uploadResult = await uploadBytes(storageRef, file);
const newUrl = await getDownloadURL(uploadResult.ref);
newFilesData[i] = { name: file.name, url: newUrl, isEmpty: false };
} else {
if (!existingFiles[i] || existingFiles[i].isEmpty) {
newFilesData[i] = { name: 'nofile', url: '', isEmpty: true };
}
}
}
}
<div class="fileup">
<label for="file1">ยท paper </label>
<input type="file" id="file1" class="file-input"/>
<span id="file-name1" style="color: blue;">nofilenow</span>
<span id="refile-name1" style="display: none; color: red;"></span>
<label for="file1" class="file-label">upload</label>
</div> //it has 0~17 number
It’s a function to edit what you write,
Number 1 from 0 to 17 has a file
If you have added numbers 2 and 3, you will update files 2 and 3.
If number 1 is not selected, number 1 is left without updating it. It seems that even if I select a file in the input, it doesn’t detect it at all
I’m encountering a “Unexpected token, expected ‘,’ (53:12)” error in my React JSX code. The error occurs in a section utilizing a ternary operator for conditional rendering based on a state variable.
Relevant Code (main.jsx):
{isOnline ? (
<RouterProvider router={router} />
) : (
<OfflinePage />
)}
I tried identifying the missing comma causing the “Unexpected token, expected ‘,'” error in the provided React JSX code (main.jsx). I expected the error message to disappear and the code to render correctly after fixing the missing comma. However, I haven’t been able to locate a missing comma within the provided code snippet. There’s a possibility the issue might lie elsewhere in the code or be related to a different part of your setup.
I need to fetch products from the firestore database which title and code fields match a substring (key insensitive)
I’ve tried in the following way:
export const fetchProductsByTitleOrCodeSubstring = createAsyncThunk('fetchProductsByTitleOrCodeSubstring', async substring => {
const [titleQuerySnapshot, codeQuerySnapshot] = await Promise.all([
getDocs(query(productsCollectionRef, where('title', '>=', substring), where('title', '<=', substring + 'uf8ff'), limit(10))),
getDocs(query(productsCollectionRef, where('code', '>=', substring), where('code', '<=', substring + 'uf8ff'), limit(10))),
])
const titleData = [...titleQuerySnapshot.docs].map(doc => {
return { ...doc.data(), id: doc.id }
})
const codeData = [...codeQuerySnapshot.docs].map(doc => {
return { ...doc.data(), id: doc.id }
})
const data = [...titleData, ...codeData]
const meta = { method: STORE_METHOD.REPLACE }
return { data, meta }
})
but it works only if the code or title only starts with received substring and is key sensitive. Is there a way to achieve that?
Thanks in advance!
I’m working on a project involving collaborative text editing with Editor.js and could use some help with a couple of issues:
I’m trying to integrate Editor.js with libraries like Yjs or ShareDB for conflict resolution using CRDT or OT.
Whenever I update a block in Editor.js, it flashes and rerenders, causing the user to lose focus on the text field.
this is my current code:
import React, { createContext, useEffect, useRef } from 'react';
import EditorJS from '@editorjs/editorjs';
import Header from '@editorjs/header';
import Checklist from '@editorjs/checklist'
import RawTool from '@editorjs/raw';
import './css.css';
import 'bootstrap/dist/css/bootstrap.min.css';
import './toolBarcss.css';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faStrikethrough, faBold, faItalic, faUnderline } from '@fortawesome/free-solid-svg-icons';
import SketchExample from './SketchExample';
import Underline from '@editorjs/underline';
import Strikethrough from 'editorjs-strikethrough';
import { SimpleImage } from './simpleimage';
import Video from '@weekwood/editorjs-video';
export const EditorContext = createContext()
let blockid = null;
let blockElement = null;
let data = null;
let selectedText = null;
let startPosition = null;
let endPosition = null;
function Editor(props) {
const editorInstanceRef = useRef(null)
const initEditor = () => {
const editor = new EditorJS({
readOnly: false,
holder: "editorjs",
placeholder: "Let's take a note!",
tools: {
image: {
class: SimpleImage,
config: {
endpoints: {
byFile: 'http://localhost:8008/uploadFile', // Your backend file uploader endpoint
byUrl: 'http://localhost:8008/fetchUrl', // Your endpoint that provides uploading by Url
}
},
actions: [
{
name: 'new_button',
icon: '<svg>...</svg>',
title: 'New Button',
toggle: true,
action: (name) => {
alert(`${name} button clicked`);
}
}
]
}, video: {
class: Video,
config: {
endpoints: {
}
}
},
strikethrough: {
class: Strikethrough,
shortcut: 'CMD+SHIFT+X',
},
underline: Underline,
header: {
class: Header,
config: {
placeholder: 'Enter a header',
levels: [1, 2, 3, 4],
defaultLevel: 1,
shortcut: 'CMD+SHIFT+H',
}
},
raw: {
class: RawTool,
inlineToolbar: false,
},
checklist: {
class: Checklist,
inlineToolbar: false,
}
},
onChange: async () => {
data = await editor.save();
}
})
editorInstanceRef.current = editor
const editorContainer = document.getElementById('editorjs');
editorContainer.addEventListener('click', handleBlockClick);
editorContainer.addEventListener('mouseup', selectionevent);
}
/**
* Handles the user selection event within an editor block.
* This function determines the closest block element based on the event target,
* retrieves the selected text and its start and end positions within the block,
* and gets the index of the current block in the editor.
*
* @param {Event} event - The event object triggered by the user action.
*/
const selectionevent = async (event) => {
const closestBlock = event.target.closest('.ce-block');
let blockElement, blockId;
if (closestBlock) {
blockElement = closestBlock;
blockId = blockElement.getAttribute('data-id');
} else {
blockElement = null;
blockId = null;
}
const selection = window.getSelection();
selectedText = selection.toString();
const range = selection.getRangeAt(0);
const preSelectionRange = range.cloneRange();
preSelectionRange.selectNodeContents(blockElement);
preSelectionRange.setEnd(range.startContainer, range.startOffset);
startPosition = preSelectionRange.toString().length;
// Adjust endPosition by excluding the length of the selectedText itself
endPosition = startPosition + selectedText.length;
index = editorInstanceRef.current.blocks.getCurrentBlockIndex();
};
////// add bold italic underline or color to selected text ////////
/**
* Changes the color of a font element in the HTML content.
* This function takes a color value as input and generates opening and closing tags
* for a font element with the specified color style. It then calls the changeStyle function
* to apply the color change to the HTML content.
*
* @param {string} data - The color value to apply (e.g., "red", "#00ff00", "rgb(255, 0, 0)").
*/
const changeColor = (data) => {
const word = "font"
const open = `<font style="color: ${data};">`
const close = '</font>'
changeStyle(word, open, close);
};
/**
* Removes empty HTML tags from the given text content.
* This function parses the HTML text using DOMParser, removes all empty tags,
* and returns the cleaned HTML text without empty tags.
*
* @param {string} text - The HTML text content to clean.
* @returns {string} - The cleaned HTML text without empty tags.
*/
const cleanHTMLTags = (text) => {
const parser = new DOMParser();
const doc = parser.parseFromString(text, 'text/html');
const emptyTags = doc.querySelectorAll(':empty');
emptyTags.forEach((tag) => tag.parentNode.removeChild(tag));
const cleanedText = doc.body.innerHTML;
return cleanedText;
};
/**
* Adds style tags (bold italic underline and strike) around the selected text in the block content
* using the changestyle function.
*/
const addstyle = (word) => {
const startTime = performance.now();
const open = `<${word}>`;
const close = `</${word}>`;
changeStyle(word, open, close);
const endTime = performance.now();
const elapsedTime = endTime - startTime;
}
/**
* This function is responsible for modifying the styling of the selected text in the block content.
* It take in consideration multiple cases lets take bold for exemple
* it will start by Spliting the text and Iterate through the full html text to determine left, middle, and right portions
* after that it perform checks on the right left and midle to determine wich case are we in
* i have 5 cases for exemple when i press the bold button :
* if i have a text "123456789" and i select "2345678" we are in the last case wich is simple adding
* if i have a text "1<b>2345678<b>9" and i select "2345678" we are in case 3 wich is removing the <b></b>
* if i have a text "1<b>2345678<b>9" and i select "45678" we are in case 3 wich is changing the </b> position
* if i have a text "1<b>2345678<b>9" and i select "23456" we are in case 4 wich is changing the <b> position
* if i have a text "1<b>2345678<b>9" and i select "45" we are in case 4 wich is adding the </b> before "45" and adding <b> after
*
* those are the common cases but sometimes i got other cases like case 1 and 2
* note all cases except the adding are not applyed for the font tag
*
*/
const changeStyle = async (word, open, close) => {
let left = '';
let midle = '';
let right = '';
let leftResult;
let midleResult;
let rightResult;
// Start and end positions for text modification
let a = startPosition;
let b = endPosition;
// Ensure a <= b because when i select a text from right to left they switch
if (a > b) {
a = startPosition;
b = startPosition;
}
// Check if blockid is provided and fetch updated data
if (blockid) {
const updatedData = data;
const currentBlock = updatedData.blocks.find((block) => block.id === blockid);
// If the current block is found
if (currentBlock) {
let currentText = currentBlock.data.text;
/** Split the full html text with the tags into an array for processing
* exemple text:"123456789" html text: "123<b>456</b>789"
*/
const textArray = currentText.split('');
let skipMode = false;
// Iterate through the full html text to determine left, middle, and right portions
for (let i = 0; i < textArray.length && i < b; i++) {
if (i === b) {
break;
}
if (textArray[i] === '<') {
skipMode = true;
}
if (skipMode && i <= a) {
a++;
b++;
}
if (skipMode && i > a) {
b++;
}
if (textArray[i] === '>') {
skipMode = false;
}
}
// Extract left, middle, and right portions of the text
left = currentText.substring(0, a)
midle = currentText.substring(a, b)
right = currentText.substring(b)
// Perform checks and modifications based on the left, middle, and right portions
leftResult = checkLeft(left, word)
midleResult = countAndSubtractTags(midle, word)
rightResult = checkright(right, word)
// Construct modifiedText based on the checks and results
if (leftResult.check && rightResult.check && word !== "font") {
console.log("case 1")
const modifiedText = [
leftResult.text,
midleResult.text,
rightResult.text
].join('');
currentBlock.data.text = cleanHTMLTags(modifiedText);
} else if (leftResult.check && !rightResult.check && word !== "font") {
console.log("case 2")
const modifiedText = [
leftResult.text,
midleResult.text,
rightResult.storedOpenTags,
rightResult.text
].join('');
currentBlock.data.text = cleanHTMLTags(modifiedText);
} else if (!leftResult.check && rightResult.check && word !== "font") {
console.log("case 3")
const modifiedText = [
leftResult.text,
rightResult.CloseTag,
midleResult.text,
rightResult.text
].join('');
currentBlock.data.text = cleanHTMLTags(modifiedText);
} else if (!leftResult.check && !rightResult.check && leftResult.CloseTag && rightResult.storedOpenTags && word !== "font") {
console.log("case 4")
if (word === "font") {
midleResult.text = open + midleResult.text + close;
}
const modifiedText = [
leftResult.text,
leftResult.CloseTag,
midleResult.text,
rightResult.storedOpenTags,
rightResult.text
].join('');
currentBlock.data.text = cleanHTMLTags(modifiedText);
} else {
console.log("case adding")
const modifiedText = [
currentText.substring(0, a),
midleResult.storedCloseTags,
open,
midleResult.text,
close,
midleResult.storedOpenTags,
currentText.substring(b)
].join('');
currentBlock.data.text = cleanHTMLTags(modifiedText);
}
}
// Render the updated data in the editor
editorInstanceRef.current.render(updatedData);
}
}
/**
* Analyzes the left part of a text string in HTML content for a specified word.
* This function looks for the last occurrence of the opening tag and the corresponding
* closing tag related to the specified word in the text. It handles tags and modifies
* the text accordingly, providing information about found tags and any modifications made.
*
* @param {string} text - The input text string to be analyzed.
* @param {string} word - The specified word that the function focuses on in the text.
* @returns {Object} An object containing storedOpenTags, CloseTag, modified text, and check flag.
* - storedOpenTags: Any opening tags related to the specified word found in the text.
* - CloseTag: The closing tag related to the specified word.
* - text: The modified text after tag processing.
* - check: A flag indicating whether modifications were made to the text (true/false).
*/
function checkLeft(text, word) {
let storedOpenTags = '';
let CloseTag = '';
let check = false;
// Check if the input text is not empty
if (text !== '') {
let startIndex = text.length - 1;
let endIndex = text.length;
// Iterate backwards through the text to find the last occurrence of the opening tag of the word
while ((startIndex = text.lastIndexOf('<' + word[0], startIndex)) !== -1) {
// Find the corresponding closing tag for the word
endIndex = text.indexOf(word[word.length - 1] + '>', startIndex);
// If no closing tag is found, break the loop
if (endIndex === -1) {
break;
}
// Extract the tag from startIndex to endIndex
const tag = text.substring(startIndex, endIndex + 1);
// Check if the tag is a closing tag for the word
if (tag.startsWith('</' + word)) {
// If it's a closing tag, break the loop
break;
} else if (tag.startsWith('<' + word)) {
// If it's an opening tag, store it as the storedOpenTags
storedOpenTags = text.substring(startIndex, endIndex + 1);
// Check if the opening tag is at the end of the text
if (endIndex + 1 === text.length) {
// If yes, remove the tag from the text and set check to true
text = text.substring(0, startIndex);
check = true;
break;
} else {
// If not, set the CloseTag and break the loop
CloseTag = '</' + word + '>';
break;
}
}
// Move to the previous character in the text
startIndex--;
}
}
// Return an object containing the storedOpenTags, CloseTag, modified text, and check flag
return { storedOpenTags, CloseTag, text, check };
}
/**
* Analyzes the right part of a text string in HTML content for a specified word.
* This function looks for opening and closing tags related to the specified word
* in the right part of the text. It handles tags and modifies the text accordingly,
* providing information about found tags and any modifications made.
*
* @param {string} text - The input text string to be analyzed.
* @param {string} word - The specified word that the function focuses on in the text.
* @returns {Object} An object containing storedOpenTags, CloseTag, modified text, and check flag.
* - storedOpenTags: Any opening tags related to the specified word found in the text.
* - CloseTag: The closing tag related to the specified word.
* - text: The modified text after tag processing.
* - check: A flag indicating whether modifications were made to the text (true/false).
*/
function checkright(text, word) {
// Initialize variables to store open tags, closing tags, and a check flag
let storedOpenTags = '';
let CloseTag = '';
let startIndex = 0;
let endIndex = 0;
let check = false;
// Iterate through the text to find opening and closing tags related to the specified word
while ((startIndex = text.indexOf('<', endIndex)) !== -1 && endIndex != text.length) {
// Find the index of the closing '>' character
endIndex = text.indexOf('>', startIndex);
// If no closing tag is found, break the loop
if (endIndex === -1) {
break;
}
// Extract the tag from startIndex to endIndex
const tag = text.substring(startIndex, endIndex + 1);
// Check if the tag is a closing tag for the specified word
if (tag.startsWith('</' + word)) {
// If it's a closing tag, check if it's at the begining of the text
if (tag.length === endIndex + 1) {
// If yes, remove the tag from the text and set CloseTag and check flags
text = text.substring(endIndex + 1, text.length);
CloseTag = tag;
check = true;
} else {
// If it's not the entire tag, set CloseTag and storedOpenTags accordingly
CloseTag = tag;
storedOpenTags = '<' + word + '>';
}
// Break the loop after processing the closing tag
break;
} else if (tag.startsWith('<' + word)) {
// If it's an opening tag, break the loop
break;
}
endIndex++; // Move to the next '>' character
}
// Return an object containing the stored open tags, CloseTag, modified text, and check flag
return { storedOpenTags, CloseTag, text, check };
}
/**
* Counts and subtracts opening and closing tags related to a specified word in the text.
* This function iterates through the text to find and process tags (opening and closing)
* related to the specified word. It counts the occurrences of opening and closing tags,
* subtracts them based on certain conditions, and handles tag removal and storage.
*
* @param {string} text - The input text string to be analyzed for tags.
* @param {string} word - The specified word that the function focuses on in the text.
* @returns {Object} An object containing storedOpenTags, storedCloseTags, and modified text.
* - storedOpenTags: Any opening tags related to the specified word found in the text.
* - storedCloseTags: Any closing tags related to the specified word found in the text.
* - text: The modified text after tag processing.
*/
function countAndSubtractTags(text, word) {
// Initialize variables to store open tags, closing tags, and flags
let storedOpenTags = '';
let storedCloseTags = '';
let closedtag = false;
let startIndex = 0;
let endIndex = 0;
let startopen = false;
let countWord1 = (text.match(new RegExp('<' + word, 'g')) || []).length;
let countWord2 = (text.match(new RegExp('</' + word + '>', 'g')) || []).length;
// Iterate through the text to find and process tags related to the specified word
while ((startIndex = text.indexOf('<', endIndex)) !== -1) {
endIndex = text.indexOf('>', startIndex);
if (endIndex === -1) {
break; // Break the loop if no closing '>' character is found
}
const tag = text.substring(startIndex, endIndex + 1);
if (tag.startsWith('</' + word)) {
// Handle closing tags
if (!startopen) {
// If it's the first closing tag encountered, store it in storedCloseTags
closedtag = true;
storedCloseTags += text.substring(startIndex, endIndex + 1);
}
// Remove the tag from the text and update counters
text = text.slice(0, startIndex) + text.slice(endIndex + 1);
startIndex = 0;
endIndex = 0;
countWord2--;
} else if (tag.startsWith('<' + word)) {
// Handle opening tags
startopen = true;
if (countWord2 > 0) {
// If closing tags are still present, decrement the opening tag counter
countWord1--;
} else if (countWord1 > 0 && countWord2 <= 0) {
// If no closing tags are left but opening tags are present, store in storedOpenTags
storedOpenTags += text.substring(startIndex, endIndex + 1);
closedtag = false;
}
// Remove the tag from the text and reset indices
text = text.slice(0, startIndex) + text.slice(endIndex + 1);
startIndex = 0;
endIndex = 0;
}
}
// Return an object containing the stored open tags, stored close tags, and modified text
return { storedOpenTags, storedCloseTags, text };
}
////// end of add bold italic underline or color to selected text ////////
////// when block is clicked ////////
const handleBlockClick = async (event) => {
const closestBlock = event.target.closest('.ce-block');
if (closestBlock) {
blockElement = closestBlock;
blockid = blockElement.getAttribute('data-id');
} else {
blockElement = null;
blockid = null;
}
};
////// end of when block is clicked ////////
return (
<>
<div className="container">
<div className="btn-group" role="group" aria-label="Basic example">
<button onClick={() => addstyle('b')} type="button" className="btn btn-light btn-sm">
<FontAwesomeIcon icon={faBold} />
</button>
<button onClick={() => addstyle('i')} type="button" className="btn btn-light btn-sm">
<FontAwesomeIcon icon={faItalic} />
</button>
<button onClick={() => addstyle('u')} type="button" className="btn btn-light btn-sm">
<FontAwesomeIcon icon={faUnderline} />
</button>
<button onClick={() => addstyle('strike')} type="button" className="btn btn-light btn-sm">
<FontAwesomeIcon icon={faStrikethrough} />
</button>
<SketchExample onData={changeColor} />
</div>
</div>
<EditorContext.Provider value={{ initEditor, editorInstanceRef }}>
{props.children}
</EditorContext.Provider>
</>
)
}
export default Editor;
import React from "react";
import axios from "axios";
interface UsersType {
id: string;
firstName: string;
lastName: string;
email: string;
}
interface dataProps {
allUsers: UsersType[];
}
async function getData() {
try {
const { data } = await axios.get<dataProps>(
`${process.env.NEXT_PUBLIC_WAITINGLIST_URL}/waitinglist/`
);
// console.log(data);
return data;
} catch (error) {
console.log(error);
}
}
export default async function Page() {
const data = await getData();
// console.log(data?.allUsers);
return (
<div className="text-white w-100">
<table className="w-full table ">
<thead>
<tr className=" [&>th]:text-center [&>th]:py-3 [&>th]:px-2 ">
<th>First Name</th>
<th>Last Name</th>
<th>Email</th>
</tr>
</thead>
<tbody>
{data?.allUsers?.map((item: UsersType) => {
return (
<tr
key={item?.id}
className=" [&>td]:text-center [&>td]:py-3 [&>td]:px-2 "
>
<td>{item?.firstName}</td>
<td>{item?.lastName}</td>
<td>{item?.email}</td>
</tr>
);
})}
</tbody>
</table>
</div>
);
}
Build Time Error on Console
[Error]: connect ECONNREFUSED ::1:3000
at I.from (E:usman datamaincorenextjs.nextserverappdashboardadminpage.js:11:10985)
at y. (E:usman datamaincorenextjs.nextserverappdashboardadminpage.js:13:21276) {
port: 3000,
address: ‘::1’,
syscall: ‘connect’,
code: ‘ECONNREFUSED’,
errno: -4078,
method: ‘get’,
url: ‘http://localhost:3000/api/waitinglist/’,
data: undefined
},
.env file
NEXT_PUBLIC_WAITINGLIST_URL="http://localhost:3000/api"
versions
** Node ** : * 18.18.1 *
** Nextjs ** : * 14.2.1 *
I convert a decimal number into binary. My number is 66. I convert it like:
let bin1;
bin1 = Number(66).toString(2);
The result I get is bin1=1000010. So I get only 7 bits of the byte. I want to get all 8 bits of byte. So, I should get 01000010. What should I do to get so?
I’m trying to build a bot that will capture the incoming video and audio streams from google meetings.
I was using chatgpt to help me with this and I managed to get to the point where I can download the video recordings but no matter what I try, I can’t seem to find how/where audio is streamed.
Here is the snipped I used to download incoming video streams:
// Object to store active recorders by stream ID
const recorders = {};
// Override setRemoteDescription method to intercept incoming tracks
const originalSetRemoteDescription = RTCPeerConnection.prototype.setRemoteDescription;
RTCPeerConnection.prototype.setRemoteDescription = async function(desc) {
const result = await originalSetRemoteDescription.call(this, desc).catch(console.error);
// Handle incoming tracks
this.ontrack = (event) => {
console.log('ontrack event:', event);
const streamId = event.streams[0].id; // Unique ID for each stream
if (!recorders[streamId]) {
// If recorder for this stream does not exist, create a new one
const recorder = createRecorder(event.streams[0], streamId);
recorders[streamId] = recorder;
}
};
return result;
};
// Function to create a MediaRecorder and handle recording logic
function createRecorder(stream, id) {
const recorder = new MediaRecorder(stream);
const chunks = [];
recorder.ondataavailable = event => {
if (event.data.size > 0) {
chunks.push(event.data);
}
};
recorder.onstop = () => {
const blob = new Blob(chunks, { type: 'video/webm' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.style.display = 'none';
a.href = url;
a.download = `${id}__${new Date().toISOString()}.webm`;
document.body.appendChild(a);
a.click();
setTimeout(() => {
document.body.removeChild(a);
window.URL.revokeObjectURL(url);
}, 100);
};
recorder.start();
return recorder;
}
// To stop all recordings:
function stopAllRecordings() {
Object.values(recorders).forEach(recorder => {
recorder.stop();
delete recorders[recorder.streamId];
});
}
Any help in this would be amazing, additionally if anyone could point me in a direction where I could learn more about this stuff would also be nice.
import React from "react"
import { Link } from "gatsby"
import { Swiper, SwiperSlide } from "swiper/react"
import SwiperCore, { Autoplay, Navigation, EffectFade } from "swiper"
import { Col, Container, Row } from "react-bootstrap"
import "swiper/css"
import "swiper/css/effect-fade"
import "swiper/css/navigation"
import "swiper/css/pagination"
import { Button } from "@mui/material"
import { SliderData, Sports } from "./data"
import Spline from "@splinetool/react-spline"
SwiperCore.use([Autoplay, Navigation, EffectFade])
const DesktopSlider = () => {
const mainSlideOptions = {
slidesPerView: 1,
direction: "horizontal",
loop: true,
effect: "fade",
navigation: {
nextEl: "#main-slider-next",
prevEl: "#main-slider-prev",
},
autoplay: {
delay: 3000,
disableOnInteraction: false,
},
}
const formatSportsList = () => {
if (Sports?.length === 0) return ""
let formattedList = Sports.join(", ").replace(/, ([^,]*)$/, " and $1")
const lastCommaIndex = formattedList.lastIndexOf(", ")
if (lastCommaIndex !== -1) {
formattedList =
formattedList.substring(0, lastCommaIndex) +
" and" +
formattedList.substring(lastCommaIndex + 1)
}
return formattedList.split(" ").map(item => <span>{item}</span>)
}
return (
<section className="main-slider overflow-hidden">
<Container>`your text`
<Swiper {...mainSlideOptions}>
{SliderData.map(
({ bannerImage, subTitle, title, buttons, text }, index) => (
<SwiperSlide key={index}>
<div
className="image-layer"
style={{ backgroundImage: `url(${bannerImage})` }}
></div>
<div className="banner-slider">
<Row>
<Col className="text-center">
<h1 className="main-slider__title">{title}</h1>
<p className="main-slider__subtext">{subTitle}</p>
<div className="sports-list">{formatSportsList()}</div>
<div className="button-block">
{buttons.map((item) => (
<Link to="#contact-sec" key={item.label}>
<Button > {item.label} </Button>
</Link>
))}
</div>
<div className="banner-slider-bottom-text">
<p className="text-center">{text}</p>
</div>
</Col>
</Row>
</div>
</SwiperSlide>
)
)}
</Swiper>
</Container>
</section>
)
}
export default DesktopSlider
I did import Autoplay and called it with Swipercore.use, it didnt work.
I have added disableOnInteraction to find if anything is wrong with it.
I tried many ways to make it work but failed miserably, my swiper version is 11.1.1
can anyone help me with this!
It was working with 8.2.3, but when I upgraded swiper it stopped working
thanks in advance
I am using Swiper.js to make a carousel that makes use of the renderBullet function provided by Swiper. My current script works great for one instance, the issue I have is that if I want to have multiple instances of this swiper my current code will get confused with the forEach array I am using to pass through the data attributes in order to display the correct pagination hyperlinks.
import Swiper from "swiper";
import { Navigation, Pagination, EffectFade } from "swiper/modules";
import "swiper/css";
import "swiper/css/navigation";
import "swiper/css/pagination";
import "swiper/css/effect-fade";
const titles = document.querySelectorAll(".pag-swiper .swiper-slide");
const title = [];
titles.forEach((element) => {
title.push(element.dataset.title);
});
const swiper = new Swiper(".pag-swiper .js-swiper", {
modules: [Navigation, Pagination, EffectFade],
effect: "fade",
fadeEffect: {
crossFade: true,
},
pagination: {
el: ".pag-nav",
clickable: true,
renderBullet: function (index, className) {
return '<button class="link ' + className + '">' + title[index] + "</button>";
},
},
navigation: {
nextEl: ".swiper-button-next",
prevEl: ".swiper-button-prev",
},
});
Where the HTML markup is:
<div class="pag-swiper">
<div class="swiper js-swiper">
<div class="swiper-wrapper">
<div class="swiper-slide" data-title="Pagination link one">
Slide 1
</div>
<div class="swiper-slide" data-title="Pagination link two">
Slide 2
</div>
</div>
</div>
</div>
I need to almost use the forEach to build this entire swiper based upon .pag-swiper .js-swiper but I can’t work out the syntax for it. At the moment the whole thing just breaks unable to render any pagination bullets at all.
I’m currently working on optimizing the performance of a React.js application and I’m seeking insights into advanced techniques or best practices. Despite implementing basic optimizations like memoization and component shouldComponentUpdate(), I still notice some bottlenecks in rendering speed and excessive component re-renders. I’m interested in learning about more advanced strategies to further improve performance.
I’ve already tried implementing memoization for expensive computations and using shouldComponentUpdate() to prevent unnecessary re-renders. However, I expected these optimizations to fully address performance issues, but I still encounter occasional lag and inefficiencies in rendering. I’m looking for additional techniques or optimizations that I may have overlooked or that are more advanced in nature.
I have a medusajs ecommerce project and trying to send a simple customer-inputted string from my frontend to my backend where it can be displayed on my admin dashboard for every order I receive. A way to do that they said was to add a property to the metadata object, which every entity has. The other way was to extend an entity/validator/use migration files etc but this was the simplest only other way.
Some old comments describe that I can pass metadata to the cart entity when a customer is making an order. I can’t for the life of me figure it out and obviously not that experienced with web dev
export default CustomString
"use client"
import { Heading, Text, clx } from "@medusajs/ui"
import React, { useState, useEffect, useMemo } from "react"
import { useSearchParams } from "next/navigation"
import { Cart } from "@medusajs/medusa"
import Input from "@modules/common/components/input"
const CustomString = ({
cart,
}: {
cart: Omit<Cart, "refundable_amount" | "refunded_total">
}) => {
const [formData, setFormData] = useState({
//I have tried rewriting this in a couple different ways
"cart.metadata": {"customString" : cart?.metadata || ""},
})
const searchParams = useSearchParams()
const isOpen = searchParams.get("step") === "review"
const previousStepsCompleted =
cart.shipping_address &&
cart.shipping_methods.length > 0 &&
cart.payment_session
useEffect(() => {
setFormData({
"cart.metadata": {"customString" : cart?.metadata || ""},
})
}, [cart?.metadata])
const handleChange = (
e: React.ChangeEvent<
HTMLInputElement | HTMLInputElement | HTMLSelectElement
>
) => {
setFormData({
...formData,
[e.target.name]: e.target.value,
})
}
return (
<div>
{isOpen && previousStepsCompleted && (
<>
<div className="flex items-start gap-x-1 w-full mb-6">
<Input
label="Custom String"
name="cart.metadata"
maxLength={11}
value= { cart?.metadata} //I get errors here
onChange={handleChange}
/>
</div>
</>
)}
</div>
)
}
export default CustomString
This is my custom element where a user is supposed to enter a string. One of the errors I get is “Type ‘Record<string, unknown>’ is not assignable to type ‘string | number | readonly string[] | undefined. Type ‘Record<string, unknown>’ is missing the following properties from type ‘readonly string[]’: length, concat, join, slice, and 26 more.ts(2322)”.
How exactly can I accomplish this task? Any pointers are appreciated
how can I iterate through the divs inside one div, and if they all have the same ‘display’ value(‘none’), display a message?
I’m just learning and I need to use it one hundred percent
jQuery
<div class="test1">
<div class="test2" style="display:none">
</div>
<div class="test2" style="display:none">
</div>
<div class="test2" style="display:none">
</div>
<div class="test2" style="display:none">
</div>
</div>
I tried it using jQuery.each
jQuery('.test1 > .test2').each(function(){
if(jQuery(this).css('display') == 'none'){
jQuery('.test_message').text('nothing');
}
})