How do I WhatsApp and other app input box Identify links, numbers and text and even preview the page attached to a link. And style them separately from other text.
I am working on a project and am hoping of putting such functionality in it.
Blancer.com Tutorials and projects
Freelance Projects, Design and Programming Tutorials
Category Added in a WPeMatico Campaign
How do I WhatsApp and other app input box Identify links, numbers and text and even preview the page attached to a link. And style them separately from other text.
I am working on a project and am hoping of putting such functionality in it.
How can I Calculate the distance between two pin codes, with Estimated time duration and Cost of logistics?
I am making an app and need the above, Hope you can help.
setTimeout is a macrotask right? And event loop executes only 1 macrotask in 1 “tick”, as far as I understand. So, why does it look like these functions were executed in one “tick” of event loop. I mean, just in one 1000ms delay, not in chain of three 1000ms delays after each other.
setTimeout(() => console.log("First"), 1000)
setTimeout(() => console.log("Second"), 1000)
setTimeout(() => console.log("Third"), 1000)
I am using Mantine as a UI library and I have a send icon button that opens a Menu. This menu then contains a TagsInput component where I can select multiple email addresses.
The problem I have now is that when I select an email in the list (eg [email protected]), the entire menu closes down and I have to click the ‘Send via email’ button again if I want to select more items.
How can I keep the menu open when I click an option in the TagsInput?
The component that handles this action:
import {
ActionIcon,
Button,
Flex,
FloatingPosition,
Menu,
Stack,
TagsInput,
Title,
Tooltip,
} from '@mantine/core';
import { IconSend } from '@tabler/icons-react';
import { useState } from 'react';
function EmailActionButton({ withText = true, position = 'bottom-end' }: EmailActionButtonProps) {
const [emails, setEmails] = useState<string[]>([]);
const options = ['[email protected]', '[email protected]', '[email protected]'];
return (
<Menu width={'min(350px, 100%)'} position={position}>
<Menu.Target>
{withText ? (
<Button
leftSection={<IconSend size="1rem" />}
size="sm"
variant="light"
>
Send via email
</Button>
) : (
<Tooltip label="Send via email" withArrow>
<ActionIcon color="gray" variant="light">
<IconSend size="1rem" />
</ActionIcon>
</Tooltip>
)}
</Menu.Target>
<Menu.Dropdown>
<Stack style={{ position: 'relative' }} p="md" gap="sm">
<Flex justify="space-between" align="center">
<Title order={5}>Send via email</Title>
</Flex>
<TagsInput placeholder="Select emails" data={options} value={emails} onChange={setEmails} />
<Button leftSection={<IconSend size="1rem" />} fullWidth>
Send
</Button>
</Stack>
</Menu.Dropdown>
</Menu>
);
}
interface EmailActionButtonProps {
withText?: boolean;
position?: FloatingPosition;
}
export default EmailActionButton;
I’m encountering an issue with Firebase Notifications specifically in Chrome on Windows OS. When I attempt to focus on an already open tab using the notification, the tab goes blank. This issue doesn’t seem to occur on other browsers or operating systems.
self.addEventListener('notificationclick', function (event) {
var redirectURL = event.notification.data;
event.waitUntil(
clients
.matchAll({
includeUncontrolled: true,
type: 'window',
})
.then((clientsArr) => {
console.log(clientsArr);
let isFocused = false;
for (var client of clientsArr) {
var redirectPath = new URL(redirectURL);
var clientPath = new URL(client.url);
if (clientPath.origin === redirectPath.origin) {
const clientConversationId =
clientPath.pathname.split('/')[
clientPath.pathname.split('/').length - 1
];
const redirectConversationId =
redirectPath.pathname.split('/')[
redirectPath.pathname.split('/').length - 1
];
if (clientConversationId === redirectConversationId) {
//same conversation
isFocused = true;
client.focus();
break;
}
}
}
if (!isFocused || !clientsArr.length) {
console.log('Opening new window');
return clients.openWindow(redirectURL);
}
}),
);
event.notification.close();});
Problem:
When the notification click event is triggered and the code attempts to focus on an already open tab, the tab goes blank.
Expected behavior:
The tab should retain its content when focused, as expected.
Environment:
Operating System: Windows
Browser: Chrome
Additional notes:
This issue seems to be specific to Chrome on Windows OS. I’ve tested it on other browsers and operating systems, and the problem does not occur.
Insecure CSP value in chrome extension.
{
"manifest_version": 3,
"name": "ASDF",
"version": "1.0",
"description": "ASDF",
"host_permissions": ["<all_urls>"],
"icons": {
"16": "images/slack-logo.png",
"32": "images/slack-logo.png",
"180": "images/slack-logo.png",
"192": "images/slack-logo.png",
"512": "images/slack-logo.png"
},
"offline_enabled": true,
"permissions": ["storage", "activeTab", "contextMenus", "tabs", "scripting"],
"background": {
"service_worker": "background.js"
},
"content_scripts": [
{
"matches": ["<all_urls>"],
"js": ["contentScript.js"],
"all_frames": true
}
],
"action": {
"default_popup": "index.html"
},
"content_security_policy": {
"extension_pages": "script-src 'self' 'wasm-unsafe-eval'; object-src 'self';"
}
}
If i use the above content security policy, the extension build is getting loaded but while opening the extension, I’m getting error as Refused to execute inline script because it violates the following Content Security Policy directive: “script-src ‘self’ ‘wasm-unsafe-eval'”. Either the ‘unsafe-inline’ keyword, a hash (‘sha256-6YAOYbVm9ElCxbsfIJfzPLj4oAb9VijVytz9kOhJ/38=’), or a nonce (‘nonce-…’) is required to enable inline execution.
{
"manifest_version": 3,
"name": "ASDF",
"version": "1.0",
"description": "ASDF",
"host_permissions": ["<all_urls>"],
"icons": {
"16": "images/slack-logo.png",
"32": "images/slack-logo.png",
"180": "images/slack-logo.png",
"192": "images/slack-logo.png",
"512": "images/slack-logo.png"
},
"offline_enabled": true,
"permissions": ["storage", "activeTab", "contextMenus", "tabs", "scripting"],
"background": {
"service_worker": "background.js"
},
"content_scripts": [
{
"matches": ["<all_urls>"],
"js": ["contentScript.js"],
"all_frames": true
}
],
"action": {
"default_popup": "index.html"
},
"content_security_policy": {
"extension_pages": "script-src 'self' sha256-5F95733C4CDFE823HHB647F57E74DE2E726BBC6G2B2F7DF7AD05C5F88778ABC2; object-src 'self';"
}
}
And If i use the above manifest.json , then while loading using load unpacked in chrome dev mode, I’m getting error as Error
‘content_security_policy.extension_pages’: Insecure CSP value “sha256-5F95733C4CDFE823AAB647F57E74DE2E726BBC6A2A2F7DF7AD05C5F88778AED2” in directive ‘script-src’.
Could not load manifest. Which means it’s not getting loaded only
I’ve been trying to get the value under a span and use it as a variable inside tag manager with no luck. I’ve tried a few different scripts inside a custom javascript variable but constantly just get ‘undefined’ returned.
Below is the HTML where I’m trying to get the number of items in the users cart under the count class
<div class="site-main-menu__buttons-col">
<a class="link--icon-count">
<i class="icon--cart"></i>
<span class="is-hidden">Shopping cart</span>
<span class="count">1<span class="is-hidden"> items</span></span>
</a>
</div>
I’ve tried a simple method like the below with no luck, I just get undefined as i mentioned already
function(){return document.getElementsByClassName("count").innerHTML;}
I have a complex use case where I need to get some initial data, then add a Firestore Snapshot Listener. My code below works initially, however, when I update a document that matches the listeners query it returns an empty array. What do I need to change here?
useEffect(() => {
async function getData() {
try {
const [profile, venue, offers, redemptions] = await Promise.all([
getProfile(user.uid),
getVenue(id),
getOffers(id),
getRedemptions(user.uid, id),
]);
const isFavourite = profile?.favourites?.includes(id);
setIsFavourite(isFavourite);
setVenue(venue);
const updatedOffers = matchOffers(offers, redemptions);
setOffers(updatedOffers);
} catch (error) {
console.log(error);
}
}
const listener = firestore()
.collection(`users/${user.uid}/redemptions`)
.where("venue.venue_id", "==", id)
.where("used", "==", true)
.onSnapshot((querySnapshot) => {
const redemptions = querySnapshot.docs.map((doc) => ({
id: doc.id,
...doc.data(),
}));
const matchedOffers = matchOffers(offers, redemptions);
console.log("MATCHED OFFERS:", matchedOffers); // returns []??
setOffers(matchedOffers);
});
getData().then(() => {
setLoading(false);
});
return () => listener();
}, []);
const matchOffers = (offers, redemptions) => {
const updatedOffers = offers.map((offer) => {
const used = redemptions.find((redemption) => redemption.id === offer.id);
if (used) {
return { ...offer, used: true };
} else {
return { ...offer, used: false };
}
});
return updatedOffers;
};
I’m trying to create two resizable panes side by side in HTML, where users can adjust the size of each pane by dragging a resize handle. I’ve added CSS to display a resize cursor when hovering over the handle, and I’ve implemented JavaScript to update the width of the panes as the user drags the handle. However, although the resize cursor appears when I hover over the handle, dragging it doesn’t seem to have any effect on the panes’ sizes.
Here’s the code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Resizable Panes</title>
<style>
body, html {
margin: 0;
padding: 0;
height: 100%;
}
.container {
display: flex;
height: 100%;
}
.pane {
flex: 1;
position: relative;
overflow: hidden;
}
.resize-handle {
position: absolute;
width: 10px;
height: 100%;
cursor: col-resize;
background: #ddd;
top: 0;
right: -5px;
}
</style>
</head>
<body>
<div class="container">
<div id="pane1" class="pane">
<div class="resize-handle"></div>
Pane 1
</div>
<div id="pane2" class="pane">
<div class="resize-handle"></div>
Pane 2
</div>
</div>
<script>
const resizeHandle1 = document.querySelector("#pane1 .resize-handle");
const resizeHandle2 = document.querySelector("#pane2 .resize-handle");
const pane1 = document.getElementById("pane1");
const pane2 = document.getElementById("pane2");
let isResizing = false;
resizeHandle1.addEventListener("mousedown", (e) => {
isResizing = true;
document.addEventListener("mousemove", resizePane1);
document.addEventListener("mouseup", stopResize);
});
resizeHandle2.addEventListener("mousedown", (e) => {
isResizing = true;
document.addEventListener("mousemove", resizePane2);
document.addEventListener("mouseup", stopResize);
});
function resizePane1(e) {
if (isResizing) {
const offsetRight = document.body.offsetWidth - e.clientX;
pane1.style.width = `calc(100% - ${offsetRight}px)`;
}
}
function resizePane2(e) {
if (isResizing) {
const offsetLeft = e.clientX;
pane2.style.width = `calc(${offsetLeft}px - 10px)`;
}
}
function stopResize() {
isResizing = false;
document.removeEventListener("mousemove", resizePane1);
document.removeEventListener("mousemove", resizePane2);
}
</script>
</body>
</html>
i am writing a method deleteFolderOrFiles it takes a configuration={
filePath:’path to the folder’,
fileName:’fileName’
}
in the filename we could pass regex as a string the problem here i am creating this function in s3 where i first gets the keys of the filePath with listObjectV2 Command then i match the file name passed with the regex problem is that i can’t identify whether user passed a regex or not or
eg if user passes abc.txt than what should i do whether should i delete a single file or multiple files
i am looking for a which could identify us that okay it’s regex or user want to delete multiple files without any extra flags
I have a a problem with a IOS webview mobile application. the stack is php and js. When the ‘start’ button is clicked, it redirects to the Rise 360 Articulate course in a new tab in Android and any other browsers except iOS. In iOS, the link opens in the same window because opening a new window is not working.
Here is the open tab code,
if (isIOS) {
wnd = window.location.href = $(this).data("url");
} else if (isWindows || isAndroid || isSafari || isChrome || isFirefox || isEdge || isOpera) {
wnd = window.open($(this).data("url"), 'Captivate Content', 'height=675,width=900,left=100');
} else {
wnd = window.open($(this).data("url"), 'Captivate Content', 'height=675,width=900,left=100');
}
Once inside the Articulate course, for both iOS and Android, there is an ‘exit’ module button. By default, in Rise 360 content, when closing Articulate, we can only add a URL to redirect. It has a default ‘target=”_blank”‘ attribute, which I cannot change from our code.
inside articulate code
<a class="blocks-button__button brand--ui" href="https://www.getsal.com/articulate_close.php" role="button" tabindex="0" target="_blank" style="background-color: rgb(40, 95, 159);">EXIT MODULE</a>
After clicking that, it goes to the PHP page, calls the TPL file, and using JavaScript, it closes the Articulate window.
if (isAndroid ){
window.location.href = 'comprehension.php?activity=' + activityId + '&site=' + site;
}
else if (isIOS){
window.location.href = 'comprehension.php?activity=' + activityId + '&site=' + site;
}
else {
window.close();
}
It works fine in Android, but in iOS, when clicking the ‘exit’ button, nothing works. How can i fix that?
I tried different ways to close the tab in ios but nothing works. In ios that not redirect or open tab to close the articulate.
I am using redux form in my react application. I have a pretty big custom field component with a few files. This function is getting passed to a child table of this field:
console.log(`input:`, input);
// for post select table
const removeEntityFromSelection = record => {
console.log(`input:`, input);
const newValue = input.value
? input.value.filter(r => r[idAs] !== record[idAs])
: [];
if (newValue.length) {
input.onChange(newValue);
setTempValue(null);
resetPostSelectSelection();
} else {
removeSelection();
}
};
....
....
<PostSelectTable
removeEntityFromSelection={removeEntityFromSelection}
...otherProps
/>
inside a functional component. Why is the input in the function out of sync with the input outside of the function. The function’s input value is not getting updated at all. The child component is not using useMemo. The parent is also a functional component. I have tried changing to a useCallback which didn’t work.
I am trying to connect mongoDB with my nextjs (14) project through mongoose. But I am encountering problem with connecting mongoDB with nextjs (14).
It’s a simple nextjs form project to push email and username to my database and then read it to show those info. When I try to submit data to my database it show’s this error …
MongooseError: Operation users.insertOne() buffering timed out after 10000ms
at Timeout. (D:joynextJsweek ninedata-fetchingfetch-datanode_modulesmongooselibdriversnode-mongodb-nativecollection.js:185:23)
at listOnTimeout (node:internal/timers:573:17)
at process.processTimers (node:internal/timers:514:7)
This is my connectMongo function to connect mongoDB with nextjs.
import mongoose from "mongoose";
const MONGO_URI = process.env.MONGO_URI;
const cached = {};
async function connectMongo() {
if (!MONGO_URI) {
throw new Error(
"Please define the MONGO_URI environment variable inside .env.local"
);
}
if (cached.connection) {
return cached.connection;
}
if (!cached.promise) {
const opts = {
bufferCommands: false,
};
cached.promise = mongoose.connect(MONGO_URI, opts);
}
try {
cached.connection = await cached.promise;
} catch (e) {
cached.promise = undefined;
throw e;
}
return cached.connection;
}
export default connectMongo;
This is UserShema model…
import mongoose from "mongoose";
const UserSchema = new mongoose.Schema({
name: {
type: String,
default: "Anonymous",
min: 2,
max: 100,
},
email: {
type: String,
match: [
/^w+([.-]?w+)*@w+([.-]?w+)*(.w{2,3})+$/,
"Please fill a valid email address",
],
min: 2,
max: 100,
},
});
const User = mongoose.models.User || mongoose.model("User", UserSchema);
export default User;
and this is my form component…
import connectMongo from "@/dbConnect/connectMongo";
import User from "@/models/User";
export default function NewUserForm() {
const addUser = async (formData) => {
"use server";
const name = formData.get("name");
const email = formData.get("email");
const userData = {
name,
email,
};
try {
await connectMongo;
await new User(userData).save();
} catch (error) {
console.log(error);
}
};
return (
<form action={addUser}>
<div>
<input type='text' name='name' placeholder='Name' />
</div>
<div>
<input type='email' name='email' placeholder='Email' />
</div>
<div>
<button type='submit'>Submit</button>
</div>
</form>
);
}
** point to be noted: I changed my local DNS to google DNS (8.8.8.8) and in mongoAtlas network access I allowed all user to access.**
I’m using the DocViewer component from @cyntler/react-doc-viewer in my React application to display PDF documents. I’m facing two challenges:
Getting the Current Page Number: I need assistance in retrieving the current page number of the PDF document being displayed. The DocViewer component doesn’t seem to provide a straightforward way to access this information. Can someone provide guidance on how to achieve this?
Modifying Controls: Additionally, I’m interested in customizing or modifying the controls provided by the DocViewer component.
import React, { useState } from 'react';
import { Link } from 'next/link';
import { CircleChevronLeft } from 'lucide-react';
import DocViewer, { DocViewerRenderers } from "@cyntler/react-doc-viewer";
const BookReader: React.FC = () => {
const [loading, setLoading] = useState(true);
const docs = [
{ uri: "https://assets.openstax.org/oscms-prodcms/media/documents/PrinciplesofFinance-WEB.pdf" }
];
return (
<>
<div className='margin-top'>
<Link href="/library">
<CircleChevronLeft className='ml-7'/>
</Link>
<div className='mt-5 margin-bottom margin-display' style={{
justifyContent: 'center',
alignItems: 'center',
backgroundColor: 'white',
overflowY: "auto",
minHeight: '90%',
maxHeight: "calc(100vh - 300px)",
width: "70%",
position: 'relative',
scrollbarWidth: "thin",
scrollbarColor: "transparent transparent"
}}>
{loading ? (
<div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', minHeight: '100vh' }}>
<img src="/kevin.gif" alt="Loading..." style={{ width: '200px', height: '150px' }} />
</div>
) : (
<DocViewer
documents={docs}
pluginRenderers={DocViewerRenderers}
config={{ header: {
disableHeader: true,
disableFileName: true,
}}}
/>
)}
</div>
</div>
</>
);
};
export default BookReader;
I have an app on code.org that uses multiple screens, and for the buttons that I use to navigate them, I find myself writing the same onEvent, only different each time.
The first would go as follows:
onEvent("nextButton1", "click", function(){
setScreen("person1");
});
Then, for a button on the next screen, with the same exact appearance AND purpose, the coding goes as follows:
onEvent("nextButton2", "click", function(){
setScreen("person2");
});
When I noticed this pattern (somewhat a redundancy when you consider just how similar they are), I figured “I should be able to set a variable (i) that is equal to 1, and then when you hit the next Button for a screen, that variable would increase by one. This way, the same variable name could be used, while it created an incrementally larger value after each button was pressed.
So, I created the following code:
var i = 1;
onEvent("button" + i, " click", function(){
setScreen("person" + i);
i++; //If i didn't use this, it would be i = i + 1
});`
This ended up working for just screen one, and I came to discover that that was because “i” is a global variable, so it essentially trumps over the change that occurs at the end of the onEvent. You might think “why can’t you just put it inside the onEvent to make it a local one?” I can’t because if I did that, then the onEvent would no longer have a defined id to be called by. In other words, if i don’t establish i BEFORE the onEvent, the id (“button” + i) is undefined/invalid.
So, my final question is: is there a way to create or use a function that IDENTIFIES which screen that I’m on, so that I can set the variable (i) BASED on that information. I know this is a mouthful but I would really appreciate it.
To make sure that whoever is reading this gets the clarification they might need about what i’m trying to do: my goal is to set up a conditional based on the screen, so that then i can be established. For example:
if(getScreen) == "homeScreen"{
i = 1
}else if(getScreen) == "user1"{
i=2
}else if(getScreen) == "user2"{
i=3.....
and so on and so forth.
your text