Untitled
unknown
plain_text
3 years ago
2.9 kB
10
Indexable
useEffect(() => {
const fetchUsernameAndTaggedText = async () => {
const usernameSnapshot = await firebase.database().ref(`users/${uid}/username`).once('value');
const usernameData = usernameSnapshot.val();
if (usernameData) {
setUsername(usernameData);
} else {
setUsername(firebase.auth().displayName);
}
const tagRegex = /@([\w\s]+)/g;
const matches = text ? text.match(tagRegex) : null;
if (matches) {
const replacedMatches = await Promise.all(matches.map(async (match) => {
const username = match.trim().substring(1);
const userRef = firebase.database().ref(`users`).orderByChild('username').equalTo(username);
const snapshot = await userRef.once('value');
const user = snapshot.val();
if (user) {
const uid = Object.keys(user)[0];
return uid;
} else {
return null;
}
}));
let currentIndex = 0;
const newTaggedText = text.replace(tagRegex, (match) => {
const uid = replacedMatches[currentIndex++];
if (uid) {
return `<a href="/profile/${uid}" style="color: blue;">${match}</a>`;
} else {
return match;
}
});
const linkRegex = /(?:^|[^"'])(https?:\/\/[^\s"]+)(?=["']|$)/g;
const newLinkedText = newTaggedText.replace(linkRegex, (match) => {
return `<a href="${match}" style="color: blue;" target="_blank">${match}</a>`;
});
setTaggedText(newLinkedText);
// code block to generate video thumbnail
if (fileUrl && fileUrl.endsWith('.mp4')) {
const video = document.createElement('video');
video.preload = 'metadata';
video.src = fileUrl;
video.currentTime = 5;
video.onseeked = () => {
const canvas = document.createElement('canvas');
canvas.width = video.videoWidth;
canvas.height = video.videoHeight;
const ctx = canvas.getContext('2d');
ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
const dataURL = canvas.toDataURL('image/png');
setThumbnail(dataURL);
video.remove();
};
// call createThumbnail function
createThumbnail(fileUrl);
}
} else {
const linkRegex = /(?:^|[^"'])(https?:\/\/[^\s"]+)(?=["']|$)/g;
const newLinkedText = text ? text.replace(linkRegex, (match) => {
return `<a href="${match}" style="color: blue;" target="_blank">${match}</a>`;
}) : null;
if (newLinkedText !== text) {
setTaggedText(newLinkedText);
} else {
setTaggedText(text);
}
}
};
fetchUsernameAndTaggedText();
}, [uid, text, taggedText, fileUrl]); Editor is loading...