Skip to content

Instantly share code, notes, and snippets.

@goforbg
Created January 14, 2024 13:12
Show Gist options
  • Save goforbg/69364c86d2b1ada2d8020f3dae23770c to your computer and use it in GitHub Desktop.
Save goforbg/69364c86d2b1ada2d8020f3dae23770c to your computer and use it in GitHub Desktop.
Inboxpirates Helper Functions
const htmlToFormattedText = require("html-to-formatted-text");
export const stringToBoolean = (string) => {
if (!string) {
return false;
}
switch (`${string}`?.toLowerCase().trim()) {
case "true":
case "yes":
case "1":
return true;
case "false":
case "no":
case "0":
case null:
return false;
default:
return Boolean(string);
}
}
//https://stackoverflow.com/questions/14679113/getting-all-url-parameters-using-regex
//https://stackoverflow.com/questions/31944749/how-to-return-part-of-javascript-string-that-matches-regex
export const getQueryParamsAlone = ({url = ""}) => {
const match = url?.match(/(\?|\&)([^=]+)\=([^&]+)/gm) ?? ""
if (!match) {
return ""
}
if ((match ?? "").toString().length < 1) {
return ""
}
return match?.join("")
}
//https://stackoverflow.com/a/17062041/9490453 modified on my own :cowboy: 🤠 //
//https://regex101.com/r/YDIEB2/1 //
export const remove_multiple_brs = ({text = ""}) => {
const TAG = "remove_multiple_brs"
let result;
result = text?.replace(/(<br \/>\s*){2,}/gi, '<br />');
if (result?.trim()?.indexOf('<br />') === 0) {
console.debug(`[INFO] ${TAG} :: Removing first br`)
result = result?.slice(result?.indexOf('<br />') + 6, result?.length);
} else {
console.debug(`[INFO] ${TAG} :: No first br`)
}
return result?.trim()
}
//https://stackoverflow.com/a/10154462/9490453
export function nl2br(str, is_xhtml) {
var breakTag = (is_xhtml || typeof is_xhtml === 'undefined') ? '<br />' : '<br>';
return (str + '').replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1' + breakTag + '$2');
}
export function sanitizeToPlainText(email_body_text) {
try {
console.debug(`bg :: before ${email_body_text}`)
const stripped_html = stripeNonTextTags(stripScripts(email_body_text))
console.debug(`inboxpirates :: santizeToPlainText :: after remove style tags :: ${stripped_html}`)
const email_body_text_nlbred = nl2br(htmlToFormattedText(stripped_html))
console.debug(`bg :: after nl2br ${email_body_text_nlbred}`)
//Replace all soft hyphens which is not allowing multiple brs to be detected! - https://stackoverflow.com/a/10391971/9490453
const email_after_removing_multi_brs = String(remove_multiple_brs({text: email_body_text_nlbred?.replace(/(\r\n|\n|\r)/gm, "")?.replace(/[\u00AD\u002D\u2011]+/g, '')}))
console.debug(`bg :: after removing brs ${email_after_removing_multi_brs}`)
return String("" + `${email_after_removing_multi_brs}` + "").replace(/(\r\n|\n|\r)/gm, "");
} catch (e) {
console.debug(`bg :: unable to convert`)
console.error(e)
return email_body_text
}
}
//Remove script tags from element when copying innerhtml for content
//https://javascript.tutorialink.com/removing-all-script-tags-from-html-with-js-regular-expression/
export function stripScripts(s = "") {
const div = document.createElement('div');
div.innerHTML = s;
const scripts = div?.getElementsByTagName('script');
let i = scripts?.length;
while (i--) {
scripts[i].parentNode.removeChild(scripts[i]);
}
return div?.innerHTML;
}
function stripeNonTextTags(s = "") {
const div = document.createElement("div")
div.innerHTML = s;
const styles = div?.getElementsByTagName('style');
let i = styles?.length;
while (i--) {
styles[i].parentNode.removeChild(styles[i])
}
const titles = div?.getElementsByTagName('title');
let j = titles?.length;
while (j--) {
titles[j].parentNode.removeChild(titles[j])
}
const metas = div?.getElementsByTagName('meta');
let k = metas?.length;
while (k--) {
metas[k].parentNode.removeChild(metas[k])
}
return div?.innerHTML
}
//We need to add new line for non formatting html (non formatting html tags are like <p> <b> <u>)
//If it has real html like table, div iframe, we won't add <br/> for every new line.
export const stringHasNonFormattingHTML = (str) => {
if (document === undefined) {
return false;
} else {
const div = document.createElement('div');
div.innerHTML = str;
const divs = div?.getElementsByTagName('div')?.length ?? 0;
const tables = div?.getElementsByTagName('table')?.length ?? 0;
const iframe = div?.getElementsByTagName('iframe')?.length ?? 0;
const embed = div?.getElementsByTagName('embed')?.length ?? 0;
return (divs > 0 || tables > 0 || iframe > 0 || embed > 0)
}
}
//There is no easy official way to do it, it is still in discussion among contributors.
//
// That said, there is a way. Next-auth does refresh session if you click on another tab, then on the one of your app. It happens, it is a javascript event we can reproduce.
//
// So just define a method to do it :
//https://stackoverflow.com/a/70405437
export const reloadSession = () => {
try {
const event = new Event("visibilitychange");
document.dispatchEvent(event);
} catch (e) {
console.error(e)
}
};
export const getTimeZone = () => {
try {
return Intl?.DateTimeFormat()?.resolvedOptions()?.timeZone ?? "no timezone"
} catch (e) {
return "no timezone"
}
}
export async function isExtensionInstalled(extensionId="angdoeeofmfhhecbfnnclelbiodppmlf") {
const TAG = "isExtensionInstalled"
try {
return await loadImageAndResolveTrueIfExists("chrome-extension://" + extensionId + "/icon16.png")
} catch (e) {
console.error(`${TAG} :: Unexpected error Happened!`)
console.error(e)
return false;
}
}
function loadImageAndResolveTrueIfExists(url) {
return new Promise((resolve, reject) => {
try {
const img = new Image();
img.src = url;
img.addEventListener('load', () => resolve(true));
img.addEventListener('error', () => {
resolve(false)
});
} catch (e) {
resolve(false)
}
});
}
export function getDateInGmailFormat(date = new Date()) {
return date.toLocaleDateString('en-GB', {
day: 'numeric', month: 'short'
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment