30 lines
1.2 KiB
TypeScript
30 lines
1.2 KiB
TypeScript
export const KRI_EDITOR_LINK_CLASS = "cursor-pointer text-blue-600 underline underline-offset-2";
|
|
|
|
const CLASS_ATTR_PATTERN = /class\s*=\s*"([^"]*)"|class\s*=\s*'([^']*)'/i;
|
|
|
|
/**
|
|
* 미리보기(dangerouslySetInnerHTML)에 쓰이는 원본 HTML은 예전 템플릿이거나
|
|
* HTML 모드에서 직접 작성된 경우 에디터의 링크 스타일 클래스가 없을 수 있다.
|
|
* <a> 태그에 KRI_EDITOR_LINK_CLASS를 보정해 항상 동일하게 보이도록 한다.
|
|
*/
|
|
export function applyLinkPreviewClass(html: string): string {
|
|
if (!html) return html;
|
|
|
|
return html.replace(/<a\b([^>]*)>/gi, (match, attrs: string) => {
|
|
const classMatch = attrs.match(CLASS_ATTR_PATTERN);
|
|
|
|
if (!classMatch) {
|
|
return `<a${attrs} class="${KRI_EDITOR_LINK_CLASS}">`;
|
|
}
|
|
|
|
const existingClasses = (classMatch[1] ?? classMatch[2] ?? "").split(/\s+/).filter(Boolean);
|
|
const missingClasses = KRI_EDITOR_LINK_CLASS.split(" ").filter((c) => !existingClasses.includes(c));
|
|
|
|
if (missingClasses.length === 0) return match;
|
|
|
|
const mergedClass = [...existingClasses, ...missingClasses].join(" ");
|
|
const newAttrs = attrs.replace(CLASS_ATTR_PATTERN, `class="${mergedClass}"`);
|
|
return `<a${newAttrs}>`;
|
|
});
|
|
}
|