Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 | 141x 2x 141x 3x 3x 3x 3x 3x 2x 1x 141x 98x 15x 15x 15x 15x 15x 15x 9x 3x 9x 9x 15x 9x 15x 141x 63x 141x 102x 102x 102x 102x 102x 102x 4x 4x 4x 4x 4x 102x 98x 98x 104x 102x 141x 3x 3x 141x 4x 4x 4x 4x 20x 20x 20x 12x 12x 20x 4x 141x 1047x 1047x 141x 19x 19x 19x 141x 3x 3x 3x 141x 827x 827x 825x 789x 141x 2x 2x 2x 2x 2x 141x 102x 102x 102x | import { convertPdfToImage } from "@shared/FileUpload/utils";
import { ConversationCounterVariant, MessagesChatTypes, User } from "./types";
import { CustomPalette } from "@theme/v2/palette.interface";
// Helper function to check if two messages are from the same user
const isSameUser = (a: MessagesChatTypes, b: MessagesChatTypes) =>
a.authorAccID === b.authorAccID && a.fullName === b.fullName;
/**
* Determines whether to show the profile image for a message
* @param currentMessage - The current message being rendered
* @param messagesArray - Array of all messages in the group
* @param currentIndex - Index of the current message
* @returns boolean indicating whether to show profile image
*
* * WHY:
* This logic ensures:
* - Only one profile image is shown per consecutive message group.
* - Profile images don't appear redundantly.
* - Attached files maintain visual association with the sender.
*/
export const determineProfileImageVisibility = (
currentMessage: MessagesChatTypes,
messagesArray: MessagesChatTypes[],
currentIndex: number,
): {
showProfileImageNextToFile: boolean;
showProfileImageNextToMessage: boolean;
} => {
const hasFiles = !!currentMessage?.files?.length;
const prevMessage = messagesArray?.[currentIndex - 1];
/* The list is sorted from latest message to the oldest, so we need to check if current message's previous message is from the same user,
to determine whether we should show the profile image next to the file or the message
*/
const isPreviousMessageFromTheSameUser = prevMessage
? isSameUser(currentMessage, prevMessage)
: false;
// If merchant has files, show profile image next to file only if next message is from a different user
Iif (hasFiles) {
return {
showProfileImageNextToFile: !isPreviousMessageFromTheSameUser,
showProfileImageNextToMessage: false,
};
}
// If merchant has no files, show profile image next to current message only if next message is from a different user
if (!isPreviousMessageFromTheSameUser || !prevMessage) {
return {
showProfileImageNextToMessage: true,
showProfileImageNextToFile: false,
};
}
return {
showProfileImageNextToMessage: false,
showProfileImageNextToFile: false,
};
};
export const highlightText = (text: string, search: string) => {
if (!search) return [{ text, isSearchMatch: false }];
// Normalize and escape
const normalizedText = text.replace(/[’‘]/g, "'");
const cleanSearch = search
.replace(/[’‘]/g, "'")
.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
const regex = new RegExp(`(${cleanSearch})`, "gi");
const segments: { text: string; isSearchMatch: boolean }[] = [];
let lastIndex = 0;
let match;
while ((match = regex.exec(normalizedText)) !== null) {
if (match.index > lastIndex) {
segments.push({
text: normalizedText.slice(lastIndex, match.index),
isSearchMatch: false,
});
}
segments.push({
text: normalizedText.slice(match.index, regex.lastIndex), // preserve case from original
isSearchMatch: true,
});
lastIndex = regex.lastIndex;
}
if (lastIndex < normalizedText.length) {
segments.push({
text: normalizedText.slice(lastIndex),
isSearchMatch: false,
});
}
return segments;
};
export const isStringEmptyWithHtmlTags = (message: string) =>
!!message?.replace(/<[^>]*>/g, "").trim();
export const parseMentionsAndSearch = (text = "", searchWord = "") => {
const mentionRegex = /@\[__(.*?)__]\(user:__.*?\)/g;
// Normalize input
const normalizedText = text.replace(/[’‘]/g, "'");
const normalizedSearch = searchWord.replace(/[’‘]/g, "'");
const segments: {
text: string;
isMention?: boolean;
isSearchMatch?: boolean;
}[] = [];
let lastIndex = 0;
let match;
while ((match = mentionRegex.exec(normalizedText)) !== null) {
Iif (match.index > lastIndex) {
const nonMention = normalizedText.slice(lastIndex, match.index);
highlightText(nonMention, normalizedSearch).forEach((seg) =>
segments.push({ ...seg }),
);
}
const mentionText = `@${match[1]}`;
const isSearchMatch =
normalizedSearch !== "" &&
mentionText.toLowerCase().includes(normalizedSearch.toLowerCase());
segments.push({ text: mentionText, isMention: true, isSearchMatch });
lastIndex = mentionRegex.lastIndex;
}
if (lastIndex < normalizedText.length) {
const rest = normalizedText.slice(lastIndex);
highlightText(rest, normalizedSearch).forEach((seg) =>
segments.push({ ...seg }),
);
}
return segments;
};
export const convertPdfFileToImagePreview = async (
file: File,
): Promise<string> => {
const objectUrl = URL.createObjectURL(file);
const img = await convertPdfToImage(objectUrl);
URL.revokeObjectURL(objectUrl); // Clean up after usage
return img;
};
export const countMatchingMessages = (
messages: { message: string; id: number }[],
searchKeyword: string,
): { numberOfMatches: number; matchingMessageIds: string[] } => {
Iif (!searchKeyword || !messages?.length)
return { numberOfMatches: 0, matchingMessageIds: [] };
// Convert search keyword to lowercase for case-insensitive search
const keyword = searchKeyword.toLowerCase();
const matchingMessageIds = [] as string[];
// Count total occurrences across all messages
const numberOfMatches = messages?.reduce((count, item) => {
// Convert message to lowercase for case-insensitive search
const message = item?.message?.toLowerCase();
// Count occurrences in current message
const occurrences = (message?.match(new RegExp(keyword, "g")) || []).length;
// We save id for each of an item's match, because we might have multiple matches in the same message
if (occurrences) {
for (let i = 0; i < occurrences; i++) {
matchingMessageIds?.push(item.id.toString());
}
}
return count + occurrences;
}, 0);
return { numberOfMatches, matchingMessageIds };
};
export const getConversationColors = (
palette: CustomPalette,
variant: ConversationCounterVariant,
) => {
const ConverationCounterColorMap = {
unread: palette.surface?.overlay,
tagged: palette.primitive?.warning[50],
reply: palette.primitive?.error[50],
};
return ConverationCounterColorMap[variant || "unread"];
};
export function extractUserIds(text: string): number[] {
const regex = /\(user:__([0-9]+)__\)/g;
const ids: number[] = [];
let match;
while ((match = regex.exec(text)) !== null) {
match[1] && ids.push(Number(match[1]));
}
return ids;
}
export const getStartOfDay = (timestamp: number) => {
const date = new Date(timestamp * 1000);
date.setHours(0, 0, 0, 0);
return Math.floor(date.getTime() / 1000);
};
export const transformMessage = ({
item,
idx,
arr,
nthFromLast,
loggedInUserAccountId,
}: {
item: any;
idx: number;
arr: any[];
nthFromLast: number;
loggedInUserAccountId?: number | null;
}) => {
const isNthFromLast = idx === arr.length - nthFromLast;
const files = (item?.attachments || [])
?.filter((item: any) => item?.isUploaded)
?.map((item: any) => {
const url = item?.fileURL;
return {
...item,
fileURL: url,
thumbFileUrl: url,
};
});
return {
...item,
message: item?.body,
id: item?.id,
time: Number(item?.createdAt || 0),
profileImage: item?.authorAvatarImageURL
? `${item.authorAvatarImageURL}/thumb`
: "",
isLoggedInUser: loggedInUserAccountId === item?.authorAccID,
isRead: !isNthFromLast,
fullName: `${item?.authorFirstName || ""} ${item?.authorLastName || ""}`,
files,
...determineProfileImageVisibility({ ...item, files }, arr, idx),
};
};
export const getCounterVariant = ({
isMentioned,
didMerchantReply,
unreadMessagesCount,
}: {
isMentioned: boolean;
didMerchantReply: boolean;
unreadMessagesCount?: number;
}): ConversationCounterVariant => {
Iif (didMerchantReply) return "reply";
if (isMentioned) return "tagged";
if (unreadMessagesCount && unreadMessagesCount > 0) return "unread";
return null;
};
export const parseContentToString = (container: HTMLElement): string => {
let output = "";
container.childNodes.forEach((node) => {
if (node.nodeType === Node.TEXT_NODE) {
output += node.textContent;
} else Eif (node.nodeType === Node.ELEMENT_NODE) {
const el = node as HTMLElement;
// Mentions
if (el.getAttribute("data-type") === "mention") {
const display = el.getAttribute("data-display");
const id = el.getAttribute("data-id");
output += `@[__${display}__](user:__${id}__)`;
return;
}
const tag = el.tagName.toLowerCase();
// Supported tags: br, b, i, u, strong, em
if (["br"].includes(tag)) {
output += "<br />";
} else if (["b", "i", "u", "strong", "em"].includes(tag)) {
output += `<${tag}>${parseContentToString(el)}</${tag}>`;
} else {
// Recursively process unsupported elements
output += parseContentToString(el);
}
}
});
return output.trim();
};
export const getFallbackString = (user: User) => {
const { firstName, lastName, email } = user;
const fallbackString =
firstName || lastName
? `${firstName?.[0] || ""}${lastName?.[0] || ""}`.trim()
: email?.slice(0, 2);
return fallbackString?.toUpperCase();
};
|