import { Data } from '../constants/data';
import { Setting } from '../interface';
export function convertTextLink(t: string, setting: Setting): string {
const text = t;
const regexLink =
/(https?:\/\/(?:www\.|(?!www))[a-zA-Z0-9][a-zA-Z0-9-]+[a-zA-Z0-9]\.[^\s]{2,}|www\.[a-zA-Z0-9][a-zA-Z0-9-]+[a-zA-Z0-9]\.[^\s]{2,}|https?:\/\/(?:www\.|(?!www))[a-zA-Z0-9]+\.[^\s]{2,}|www\.[a-zA-Z0-9]+\.[^\s]{2,})/g;
const regexAtsign = /([@])\w+/g;
const regexHashTag = /([#])\w+/g;
let replacedText = text;
// Find all links within the text and replace them with their titles
let match;
while ((match = regexLink.exec(text)) !== null) {
const link = match[0];
try {
let url = new URL(link);
let hostName = url.hostname.split('.').slice(-2).join('.');
let displayHostName = url.hostname.replace('www.', '');
let icon = Data[hostName] ? Data[hostName].svg : Data['defualt'].svg;
let displayLink = `${displayHostName}${
url.pathname.length > setting.link.pathnameLengthLimit
? url.pathname.substring(0, setting.link.pathnameLengthLimit) + '...'
: url.pathname
}`;
let replaceText = `
${
setting.link?.showIcon ?? setting.showIcon
? `
` +
icon +
`
`
: ``
}
${displayLink}
`;
replacedText = replacedText.replace(link, replaceText);
} catch (error) {
console.error(`Error fetching link title: ${error}`);
}
}
if (setting.hashTag && setting.hashTag.enable) {
while ((match = regexHashTag.exec(text)) !== null) {
const hashTag = match[0];
try {
let hashTagText = hashTag.replace('#', '');
let icon = Data['hashTag'].svg;
let displayHashTag = `${
setting.hashTag?.removeHashTagChar ? hashTagText : hashTag
}`;
let replaceText = `
${
setting.hashTag?.showIcon ?? setting.showIcon
? `
` +
icon +
`
`
: ``
}
${displayHashTag}
`;
replacedText = replacedText.replace(hashTag, replaceText);
} catch (error) {
console.error(`Error fetching link title: ${error}`);
}
}
}
if (setting.atsign && setting.atsign.enable) {
while ((match = regexAtsign.exec(text)) !== null) {
const atsign = match[0];
try {
let atsignText = atsign.replace('@', '');
let icon = Data['atsign'].svg;
let displayAtsign = `${
setting.atsign?.removeAtsignChar ? atsignText : atsign
}`;
let replaceText = `
${
setting.atsign?.showIcon ?? setting.showIcon
? `
` +
icon +
`
`
: ``
}
${displayAtsign}
`;
replacedText = replacedText.replace(atsign, replaceText);
} catch (error) {
console.error(`Error fetching link title: ${error}`);
}
}
}
return replacedText;
}