import { useEffect } from "react";
import { getAllSearches } from "../content-script/api/search";
import { SearchMinimal } from "../types/search";
import { setStorage } from "./useStorage";
function splitAndConvert(value: string): string[] {
return value.split(",").map((item) => item.trim());
}
function escapeRegExp(text: string): string {
return text.replace(/[.*+?^{}()|[\]\\]/g, "\\&");
}
function isHeadingSection(node: Node): boolean {
const parentElement = node.parentNode as HTMLElement;
return (
parentElement instanceof HTMLElement &&
((parentElement.classList.contains("text-body-medium") &&
parentElement.classList.contains("break-words")) ||
["artdeco-entity-lockup__subtitle", "ember-view", "truncate"].every(
(className) => parentElement.classList.contains(className),
)) &&
!parentElement.classList.contains("extension-heading-clone")
);
}
async function highlightSearchItems(
node: Node | null,
keyword: string,
): Promise {
if (
node?.nodeType === Node.TEXT_NODE &&
!(node.parentNode as HTMLElement).classList.contains(
"extension-highlight-text",
)
) {
const formattedKeyword = keyword.toLowerCase();
let regExp = new RegExp(
"\b(?:|)" + escapeRegExp(formattedKeyword) + "(?:es|s|,|;|)?\b",
"ig",
);
if (formattedKeyword == "c#" || formattedKeyword == ".net") {
regExp = new RegExp(keyword, "ig");
}
if (formattedKeyword == "c++") {
regExp = new RegExp("C\\+\\+", "ig");
}
const text = node.textContent || "";
const matches = text.match(regExp);
if (matches) {
if (node.parentNode instanceof HTMLElement && isHeadingSection(node)) {
const divCopy = node.parentNode.cloneNode(true) as HTMLElement;
divCopy.classList.add("extension-heading-clone");
const copyText = divCopy.textContent || "";
const highlightedCopyText = copyText.replace(
regExp,
(match) =>
`<span class="extension-highlight-text" style="background:#D0E9FF; padding: 0.15em 0.25em; border-radius: 0.25em;">${match}</span>`,
);
divCopy.innerHTML = highlightedCopyText;
if (node.parentNode.parentNode) {
node.parentNode.parentNode.insertBefore(
divCopy,
node.parentNode.nextSibling,
);
}
(node.parentNode as HTMLElement).style.display = "none";
} else {
const highlightedText = text.replace(
regExp,
(match) =>
`<span class="extension-highlight-text" style="background:#D0E9FF; padding: 0.15em 0.25em; border-radius: 0.25em;">${match}</span>`,
);
const tempSpan = document.createElement("span");
tempSpan.classList.add("extension-highlight-text");
tempSpan.innerHTML = highlightedText;
if (node.parentNode) {
node.parentNode.insertBefore(tempSpan, node);
node.parentNode.removeChild(node);
}
}
}
} else if (node?.nodeType === Node.ELEMENT_NODE) {
for (const childNode of node.childNodes) {
highlightSearchItems(childNode, keyword);
}
}
}
async function removeSpans(node: Node | null): Promise {
if (node?.nodeType === Node.ELEMENT_NODE) {
const childNodes = Array.from(node.childNodes);
for (const childNode of childNodes) {
if (
childNode.nodeType === Node.ELEMENT_NODE &&
childNode instanceof Element &&
childNode.classList.contains("extension-highlight-text")
) {
const parent = childNode.parentNode;
if (parent) {
while (childNode.firstChild) {
parent.insertBefore(childNode.firstChild, childNode);
}
parent.removeChild(childNode);
}
}
}
const updatedChildNodes = Array.from(node.childNodes);
for (const updatedChildNode of updatedChildNodes) {
removeSpans(updatedChildNode);
}
}
// Just a check if all of the spans are done
// const elements = document.querySelectorAll(".extension-highlight-text");
// if (elements.length > 0) {
// const rootNode = document.getElementById("profile-content");
// removeSpans(rootNode);
// }
}
async function removeExtraDiv(): Promise {
const elements = document.querySelectorAll(".extension-heading-clone");
elements.forEach(function (element) {
element.remove();
});
}
async function displayHeadingDiv(): Promise {
const profileHeadings = document.querySelectorAll(
"div.text-body-medium.break-words",
);
profileHeadings.forEach((element) => {
element.style.display = "block";
});
const navHeadings = document.querySelectorAll(
"div.artdeco-entity-lockup__subtitle.ember-view.truncate",
);
navHeadings.forEach((element) => {
element.style.display = "block";
});
}
async function removeHighlighting(): Promise {
const rootNode = document.getElementById("profile-content");
await removeSpans(rootNode);
await removeExtraDiv();
// To reset
await displayHeadingDiv();
}
async function highlightCurrentSearchItem(
result: SearchMinimal | undefined,
): Promise {
let keywords: string[] = [];
if (result) {
const niceToHaveTerms = Object.keys(result.niceToHaveTerms).map((key) => ({
key,
value: result.niceToHaveTerms[key].term,
}));
const requiredTerms = Object.keys(result.requiredTerms).map((key) => ({
key,
value: result.requiredTerms[key].term,
}));
keywords = niceToHaveTerms
.concat(requiredTerms)
.map((item) => splitAndConvert(item.value))
.flat();
const element = document.getElementById("profile-content");
for (const keyword of keywords) {
await highlightSearchItems(element, keyword);
}
}
}
export function useHighlightCurrentSearch(
currentSearch: SearchMinimal | undefined,
currentURL: string,
) {
useEffect(() => {
async function highlightItems() {
setStorage("currentSearch", currentSearch);
console.log("Removing....");
await removeHighlighting();
console.log("Highlighting....");
await highlightCurrentSearchItem(currentSearch);
}
highlightItems();
}, [currentSearch, currentURL]);
}
export async function fetchAndHighlightSearchItems() {
const searchResults: SearchMinimal[] = await getAllSearches();
const result: SearchMinimal = searchResults[0];
highlightCurrentSearchItem(result);
}