import { escapeHtml } from './utils';
const WIKI_LINK_PATTERN = /\[\[([^|\]]+)(?:\|([^\]]+))?\]\]/g;
const PROTOCOL_PATTERN = /^[\w-]+:/i;
export interface ProcessedLink {
href: string;
text: string;
isExternal: boolean;
className: string;
}
export function processWikiLink(target: string, displayText?: string): ProcessedLink {
const isExternal = PROTOCOL_PATTERN.test(target);
const href = isExternal ? target : `/t/${target}`;
const text = displayText || target;
return {
href,
text,
isExternal,
className: 'bogam-link',
};
}
export function processWikiLinks(text: string): string {
return text.replace(WIKI_LINK_PATTERN, (_, target, displayText) => {
const link = processWikiLink(target, displayText);
const attrs = [`class="${link.className}"`];
attrs.push(`href="${escapeHtml(link.href)}"`);
if (link.isExternal) {
attrs.push('target="_blank"');
attrs.push('rel="noopener noreferrer"');
}
return `${link.text}`;
});
}
export { WIKI_LINK_PATTERN, PROTOCOL_PATTERN };