260907_01_ENH: 에디터 이미지맵 보존 및 SMS 미리보기 문구 지원

This commit is contained in:
2026-09-07 14:28:31 +09:00
parent b36893610f
commit b6ed23fa88
9 changed files with 416 additions and 17 deletions

View File

@@ -16,7 +16,6 @@ import {
useTemplateQuery,
} from '@/query/message'
import { ChannelType, TemplateSms } from '@kri/common/noti-hub'
import { sanitizeHtmlForPreview } from '@/components/kri-editor/utils/sanitizeHtml'
import { cn } from '@/lib/utils'
import { getNearestFutureDateTime } from '@/lib/datetime'
import type { DialogId } from '@/store/jotai/dialog'
@@ -25,7 +24,8 @@ import { ListHeaderConst } from '@/const/listConst'
import type { ListTableRow } from '@/components/table-column/ListTableColumn'
import ApplyFilterOption, { validateApplyFilterTarget } from './ListDialogOption/ApplyFilterOption'
import { KriEditor } from '@/components/kri-editor'
import { normalizeQrCodeForEditor, QR_CODE_ALLOWED_HTML, renderQrCodePreviewHtml } from '@/components/message-template/qrcode'
import { normalizeQrCodeForEditor, renderQrCodePreviewHtml } from '@/components/message-template/qrcode'
import { sanitizeEmailHtml } from '@/components/message-template/emailHtmlPolicy'
import { applyLinkPreviewClass } from '@/components/kri-editor/utils/linkPreview'
import TemplateAttachmentList from '@/components/message-template/TemplateAttachmentList'
import type { TemplateEmailWithAttachments, TemplateSummaryWithPurpose } from '@/types/message'
@@ -351,9 +351,8 @@ const MessageSendDialog = ({
dangerouslySetInnerHTML={{
__html: renderQrCodePreviewHtml(
applyLinkPreviewClass(
sanitizeHtmlForPreview(
sanitizeEmailHtml(
normalizeQrCodeForEditor(selectedTemplate.tmplatBody) || '(내용 없음)',
QR_CODE_ALLOWED_HTML,
),
),
),

View File

@@ -15,8 +15,8 @@ import {
useTemplateQuery,
} from '@/query/message'
import { ChannelType, type TemplateSms, type TemplateSummary } from '@kri/common/noti-hub'
import { sanitizeHtmlForPreview } from '@/components/kri-editor/utils/sanitizeHtml'
import { KriEditor } from '@/components/kri-editor'
import { sanitizeEmailHtml } from '@/components/message-template/emailHtmlPolicy'
import { getNearestFutureDateTime } from '@/lib/datetime'
import { escapeHtml, substituteVariables } from '@/lib/variableSubstitution'
import type { DialogId } from '@/store/jotai/dialog'
@@ -255,7 +255,7 @@ const SingleMessageSendDialog = ({
<div
className="rounded-md border bg-muted/30 p-3 text-sm"
dangerouslySetInnerHTML={{
__html: sanitizeHtmlForPreview(
__html: sanitizeEmailHtml(
substituteVariables(
selectedTemplate.tmplatBody || '(내용 없음)',
Object.fromEntries(Object.entries(previewValues).map(([key, val]) => [key, escapeHtml(val)])),

View File

@@ -25,6 +25,7 @@ import type { KriEditorCommand, KriEditorProps, ToolbarState } from "./types";
import { resolveUploadUrl } from "./types";
import { FontSize } from "./extensions/font-size";
import { Div } from "./extensions/div";
import { ImageMap, ImageWithMap } from "./extensions/image-map";
import { compressImage } from "./utils/imageCompression";
import { sanitizeHtml } from "./utils/sanitizeHtml";
import { preserveEmptyParagraphs } from "./utils/emptyParagraph";
@@ -97,6 +98,9 @@ export function KriEditorWysiwyg(props: KriEditorProps) {
fontFamilyOptions = DEFAULT_FONT_FAMILY_OPTIONS,
editorExtensions = [],
allowedCustomHtml,
enableImageMap = false,
htmlSanitizer,
getWysiwygCompatibility,
transformPreviewHtml,
} = props;
@@ -114,9 +118,14 @@ export function KriEditorWysiwyg(props: KriEditorProps) {
const htmlTi = useTextareaInsert(htmlTextareaRef);
const { insertText: insertTextareaText } = htmlTi;
const [view, setView] = useState<ViewMode>("wysiwyg");
const getCompatibility = useCallback(
(html: string) => getWysiwygCompatibility?.(html) ?? { compatible: true },
[getWysiwygCompatibility],
);
const initialView: ViewMode = showHtmlToggle && !getCompatibility(value ?? "").compatible ? "html" : "wysiwyg";
const [view, setView] = useState<ViewMode>(initialView);
const [previewSource, setPreviewSource] = useState(value ?? "");
const viewRef = useRef<ViewMode>("wysiwyg");
const viewRef = useRef<ViewMode>(initialView);
useEffect(() => {
viewRef.current = view;
@@ -179,7 +188,7 @@ export function KriEditorWysiwyg(props: KriEditorProps) {
TableHeader,
TableCell,
TiptapImage.configure({
(enableImageMap ? ImageWithMap : TiptapImage).configure({
inline: true,
allowBase64,
HTMLAttributes: {
@@ -191,6 +200,7 @@ export function KriEditorWysiwyg(props: KriEditorProps) {
alwaysPreserveAspectRatio: true,
},
}),
...(enableImageMap ? [ImageMap] : []),
Placeholder.configure({ placeholder }),
...editorExtensions,
],
@@ -475,12 +485,19 @@ export function KriEditorWysiwyg(props: KriEditorProps) {
}
const raw = htmlDraftRef.current;
const safe = sanitizeHtmlOpt ? sanitizeHtml(raw, allowedCustomHtml) : raw;
const compatibility = getCompatibility(raw);
if (!compatibility.compatible) {
toast.message(compatibility.reason ?? "현재 HTML은 WYSIWYG로 전환할 수 없습니다.");
return;
}
const safe = htmlSanitizer
? htmlSanitizer(raw)
: sanitizeHtmlOpt ? sanitizeHtml(raw, allowedCustomHtml) : raw;
editor.commands.setContent(safe, { emitUpdate: false, parseOptions: { preserveWhitespace: "full" } });
flushChange(preserveEmptyParagraphs(editor.getHTML()));
setView("wysiwyg");
}, [allowedCustomHtml, editor, flushChange, sanitizeHtmlOpt]);
}, [allowedCustomHtml, editor, flushChange, getCompatibility, htmlSanitizer, sanitizeHtmlOpt]);
const formatHtmlView = useCallback(async () => {
try {
@@ -526,9 +543,27 @@ export function KriEditorWysiwyg(props: KriEditorProps) {
useEffect(() => {
setPreviewSource(value ?? "");
if (!editor) return;
if (viewRef.current === "html") return;
if (value == null) return;
const compatibility = getCompatibility(value);
if (showHtmlToggle && !compatibility.compatible) {
htmlDraftRef.current = value;
if (htmlTextareaRef.current) htmlTextareaRef.current.value = value;
if (viewRef.current !== "html") {
viewRef.current = "html";
setView("html");
}
return;
}
if (viewRef.current === "html") {
if (getWysiwygCompatibility && value !== optimisticHtmlRef.current && value !== htmlDraftRef.current) {
htmlDraftRef.current = value;
if (htmlTextareaRef.current) htmlTextareaRef.current.value = value;
}
return;
}
// 빈 문자열("")은 ProseMirror 스키마상 유효한 문서가 아니라 setContent가 조용히 실패해
// 이전 템플릿 본문이 그대로 남는 문제가 있었음 -> 빈 값은 빈 문단으로 정규화해서 비교/설정.
const normalizedValue = value || "<p></p>";
@@ -547,7 +582,7 @@ export function KriEditorWysiwyg(props: KriEditorProps) {
editor.createNodeViews();
}
}
}, [value, editor, view]);
}, [value, editor, view, getCompatibility, getWysiwygCompatibility, showHtmlToggle]);
useEffect(() => {
if (!editor) return;
@@ -611,10 +646,17 @@ export function KriEditorWysiwyg(props: KriEditorProps) {
const previewHtml = useMemo(() => {
const preserved = preserveEmptyParagraphs(previewSource);
const sanitized = sanitizeHtmlOpt ? sanitizeHtml(preserved, allowedCustomHtml) : preserved;
const sanitized = htmlSanitizer
? htmlSanitizer(preserved)
: sanitizeHtmlOpt ? sanitizeHtml(preserved, allowedCustomHtml) : preserved;
const withLinkStyle = applyLinkPreviewClass(sanitized);
return transformPreviewHtml ? transformPreviewHtml(withLinkStyle) : withLinkStyle;
}, [allowedCustomHtml, previewSource, sanitizeHtmlOpt, transformPreviewHtml]);
}, [allowedCustomHtml, htmlSanitizer, previewSource, sanitizeHtmlOpt, transformPreviewHtml]);
const wysiwygCompatibility = useMemo(
() => getCompatibility(view === "html" ? previewSource : (editor?.getHTML() ?? previewSource)),
[editor, getCompatibility, previewSource, view],
);
if (!editor) {
return (
@@ -640,6 +682,8 @@ export function KriEditorWysiwyg(props: KriEditorProps) {
onPickImage={handlePickImage}
showHtmlToggle={showHtmlToggle}
isHtmlView={view === "html"}
htmlToWysiwygDisabled={!wysiwygCompatibility.compatible}
htmlToWysiwygDisabledReason={wysiwygCompatibility.reason}
onToggleHtmlView={onToggleHtmlView}
onFormatHtml={formatHtmlView}
fontFamilyOptions={fontFamilyOptions}
@@ -681,6 +725,11 @@ export function KriEditorWysiwyg(props: KriEditorProps) {
placeholder={placeholder}
{...htmlTi.bindSelectionHandlers}
/>
{!wysiwygCompatibility.compatible ? (
<p className="mt-2 text-xs text-amber-700" role="status">
{wysiwygCompatibility.reason ?? "현재 HTML은 WYSIWYG에서 손실 없이 편집할 수 없습니다."}
</p>
) : null}
</div>
)}

View File

@@ -0,0 +1,93 @@
import { Node, mergeAttributes } from '@tiptap/core'
import TiptapImage from '@tiptap/extension-image'
import type { DOMOutputSpec } from '@tiptap/pm/model'
export type ImageMapAreaAttributes = {
shape?: string
coords?: string
href?: string
alt?: string
title?: string
target?: string
}
const readAttribute = (element: Element, name: string): string | undefined =>
element.getAttribute(name) ?? undefined
export const ImageWithMap = TiptapImage.extend({
addAttributes() {
return {
...this.parent?.(),
usemap: {
default: null,
parseHTML: (element) => element.getAttribute('usemap'),
renderHTML: (attributes) => attributes.usemap ? { usemap: attributes.usemap } : {},
},
align: {
default: null,
parseHTML: (element) => element.getAttribute('align'),
renderHTML: (attributes) => attributes.align ? { align: attributes.align } : {},
},
style: {
default: null,
parseHTML: (element) => element.getAttribute('style'),
renderHTML: (attributes) => attributes.style ? { style: attributes.style } : {},
},
loading: {
default: null,
parseHTML: (element) => element.getAttribute('loading'),
renderHTML: (attributes) => attributes.loading ? { loading: attributes.loading } : {},
},
}
},
})
export const ImageMap = Node.create({
name: 'imageMap',
group: 'block',
atom: true,
addAttributes() {
return {
name: {
default: null,
parseHTML: (element) => element.getAttribute('name'),
renderHTML: (attributes) => attributes.name ? { name: attributes.name } : {},
},
id: {
default: null,
parseHTML: (element) => element.getAttribute('id'),
renderHTML: (attributes) => attributes.id ? { id: attributes.id } : {},
},
areas: {
default: [],
parseHTML: (element) => Array.from(element.children)
.filter((child) => child.tagName.toLowerCase() === 'area')
.map((area): ImageMapAreaAttributes => ({
shape: readAttribute(area, 'shape'),
coords: readAttribute(area, 'coords'),
href: readAttribute(area, 'href'),
alt: readAttribute(area, 'alt'),
title: readAttribute(area, 'title'),
target: readAttribute(area, 'target'),
})),
renderHTML: () => ({}),
},
}
},
parseHTML() {
return [{ tag: 'map' }]
},
renderHTML({ node, HTMLAttributes }) {
const mapAttributes = { ...HTMLAttributes }
delete mapAttributes.areas
const areas = (node.attrs.areas as ImageMapAreaAttributes[]).map((area): DOMOutputSpec => [
'area',
Object.fromEntries(Object.entries(area).filter(([, value]) => Boolean(value))),
])
return ['map', mergeAttributes(mapAttributes), ...areas] as DOMOutputSpec
},
})

View File

@@ -14,6 +14,7 @@ export type {
KriEditorToolbarContext,
KriEditorToolbarFeature,
KriEditorUploadResult,
KriEditorWysiwygCompatibility,
ToolbarState,
} from './types'
export type { KriEditorToolbarButtonProps } from './toolbar/ToolbarButton'

View File

@@ -38,6 +38,8 @@ interface ToolbarProps {
onPickImage: () => void
showHtmlToggle: boolean
isHtmlView: boolean
htmlToWysiwygDisabled?: boolean
htmlToWysiwygDisabledReason?: string
onToggleHtmlView: () => void
onFormatHtml: () => void
fontFamilyOptions: KriEditorFontFamilyOption[]
@@ -77,6 +79,8 @@ export function Toolbar({
onPickImage,
showHtmlToggle,
isHtmlView,
htmlToWysiwygDisabled = false,
htmlToWysiwygDisabledReason,
onToggleHtmlView,
onFormatHtml,
fontFamilyOptions,
@@ -298,7 +302,14 @@ export function Toolbar({
{showHtmlToggle && enabled('html') ? (
<>
<Separator orientation="vertical" className="mx-1 h-6" />
<ToolbarButton active={isHtmlView} title={isHtmlView ? 'WYSIWYG로 전환' : 'HTML 편집'} onClick={onToggleHtmlView}><Code2 className="size-4" /></ToolbarButton>
<ToolbarButton
active={isHtmlView}
disabled={isHtmlView && htmlToWysiwygDisabled}
title={isHtmlView && htmlToWysiwygDisabled ? (htmlToWysiwygDisabledReason ?? 'WYSIWYG로 전환할 수 없습니다.') : (isHtmlView ? 'WYSIWYG로 전환' : 'HTML 편집')}
onClick={onToggleHtmlView}
>
<Code2 className="size-4" />
</ToolbarButton>
{isHtmlView ? (
<ToolbarButton title="HTML 정렬" onClick={onFormatHtml}><IndentIncrease className="size-4" /></ToolbarButton>
) : null}

View File

@@ -40,6 +40,11 @@ export type KriEditorAllowedHtml = {
attributes?: string[]
}
export type KriEditorWysiwygCompatibility = {
compatible: boolean
reason?: string
}
export type KriEditorFontFamilyOption = {
label: string
value: string
@@ -80,6 +85,9 @@ export type KriEditorProps = {
renderToolbarEnd?: (context: KriEditorToolbarContext) => ReactNode
editorExtensions?: Extensions
allowedCustomHtml?: KriEditorAllowedHtml
enableImageMap?: boolean
htmlSanitizer?: (html: string) => string
getWysiwygCompatibility?: (html: string) => KriEditorWysiwygCompatibility
transformPreviewHtml?: (html: string) => string
}

View File

@@ -57,6 +57,11 @@ import {
QrCode,
renderQrCodePreviewHtml,
} from "@/components/message-template/qrcode";
import {
getEmailHtmlPolicyIssues,
getEmailWysiwygCompatibility,
sanitizeEmailHtml,
} from "@/components/message-template/emailHtmlPolicy";
interface MessageTemplateProps {
pageTitle: string;
@@ -368,13 +373,25 @@ const MessageTemplate = ({ pageTitle, defaultTemplate }: MessageTemplateProps) =
return;
}
if (!isSmsTemplate(selectedTemplate)) {
const policyIssues = getEmailHtmlPolicyIssues(selectedTemplate.tmplatBody);
if (policyIssues.length > 0) {
const issueSummary = policyIssues.slice(0, 5).join("\n- ");
const remaining = policyIssues.length > 5 ? `\n외 ${policyIssues.length - 5}개` : "";
const shouldContinue = window.confirm(
`백엔드 허용 목록에 없는 항목은 제거되어 저장됩니다.\n\n- ${issueSummary}${remaining}\n\n계속 저장하시겠습니까?`,
);
if (!shouldContinue) return;
}
}
try {
const templateToSave = isSmsTemplate(selectedTemplate)
? { ...selectedTemplate, tmplatPurpose: selectedTemplate.tmplatPurpose ?? TEMPLATE_PURPOSE.NORMAL }
: {
...selectedTemplate,
tmplatPurpose: TEMPLATE_PURPOSE.NORMAL,
tmplatBody: normalizeQrCodeForStorage(selectedTemplate.tmplatBody),
tmplatBody: normalizeQrCodeForStorage(sanitizeEmailHtml(selectedTemplate.tmplatBody)),
};
const res = await saveTemplateMutation.mutateAsync({
@@ -581,6 +598,9 @@ const MessageTemplate = ({ pageTitle, defaultTemplate }: MessageTemplateProps) =
toolbar={{ strike: false, table: false, bulletList: false, orderedList: false }}
editorExtensions={MESSAGE_EDITOR_EXTENSIONS}
allowedCustomHtml={QR_CODE_ALLOWED_HTML}
enableImageMap
htmlSanitizer={sanitizeEmailHtml}
getWysiwygCompatibility={getEmailWysiwygCompatibility}
previewClassName="kri-editor-preview"
transformPreviewHtml={renderQrCodePreviewHtml}
renderToolbarEnd={({editor}) => (

View File

@@ -0,0 +1,218 @@
"use client";
import DOMPurify, { type DOMPurify as DOMPurifyInstance } from "dompurify";
import type { KriEditorWysiwygCompatibility } from "@/components/kri-editor";
const EMAIL_ALLOWED_ATTRIBUTES = {
a: ["href", "title", "style", "target", "rel"],
area: ["shape", "coords", "href", "alt", "title", "target"],
b: ["style"],
blockquote: ["cite"],
col: ["span", "width"],
colgroup: ["span", "width"],
div: ["style", "align"],
img: ["src", "width", "height", "alt", "title", "align", "style", "loading", "usemap"],
map: ["name", "id"],
mark: ["style", "data-color"],
ol: ["start", "type"],
p: ["style"],
q: ["cite"],
qrcode: ["src", "width", "height", "alt"],
span: ["style"],
table: ["summary", "width", "height", "style", "cellpadding", "cellspacing", "border", "align", "bgcolor", "role"],
tbody: ["style", "align", "valign"],
td: ["abbr", "axis", "colspan", "rowspan", "width", "height", "style", "align", "valign", "bgcolor"],
th: ["abbr", "axis", "colspan", "rowspan", "scope", "width", "height", "style", "align", "valign", "bgcolor"],
tr: ["style", "align", "valign", "bgcolor", "height"],
ul: ["type"],
} as const;
export const EMAIL_ALLOWED_TAGS = [
"a", "area", "b", "blockquote", "br", "caption", "cite", "code", "col", "colgroup", "dd", "div", "dl", "dt",
"em", "h1", "h2", "h3", "h4", "h5", "h6", "i", "img", "li", "map", "mark", "ol", "p", "pre", "q", "qrcode",
"small", "span", "strike", "strong", "sub", "sup", "table", "tbody", "td", "tfoot", "th", "thead", "tr", "u", "ul",
] as const;
const TAGS_WITHOUT_ATTRIBUTES = new Set(
EMAIL_ALLOWED_TAGS.filter((tag) => !(tag in EMAIL_ALLOWED_ATTRIBUTES)),
);
const ALLOWED_TAG_SET = new Set<string>(EMAIL_ALLOWED_TAGS);
const ALLOWED_ATTRIBUTE_SET = new Set<string>(Object.values(EMAIL_ALLOWED_ATTRIBUTES).flat());
const ALLOWED_PROTOCOLS: Record<string, ReadonlySet<string>> = {
"a.href": new Set(["http", "https", "mailto", "tel", "ftp"]),
"area.href": new Set(["http", "https", "mailto", "tel"]),
"img.src": new Set(["http", "https"]),
"blockquote.cite": new Set(["http", "https"]),
"q.cite": new Set(["http", "https"]),
};
const WYSIWYG_ATTRIBUTES: Record<string, ReadonlySet<string>> = {
a: new Set(["href", "target", "rel", "class"]),
area: new Set(EMAIL_ALLOWED_ATTRIBUTES.area),
div: new Set(["style", "class"]),
img: new Set([...EMAIL_ALLOWED_ATTRIBUTES.img, "class", "data-kri-image"]),
map: new Set(EMAIL_ALLOWED_ATTRIBUTES.map),
mark: new Set(EMAIL_ALLOWED_ATTRIBUTES.mark),
ol: new Set(["start"]),
p: new Set(["style"]),
qrcode: new Set(EMAIL_ALLOWED_ATTRIBUTES.qrcode),
span: new Set(["style"]),
td: new Set(["colspan", "rowspan"]),
th: new Set(["colspan", "rowspan"]),
};
const WYSIWYG_TAGS = new Set([
"a", "area", "b", "br", "div", "em", "i", "img", "li", "map", "mark", "ol", "p", "qrcode", "span", "strong",
"table", "tbody", "td", "th", "tr", "u", "ul",
]);
const WYSIWYG_SPAN_STYLE_PROPERTIES = new Set(["color", "font-family", "font-size"]);
const WYSIWYG_PARAGRAPH_STYLE_PROPERTIES = new Set(["text-align"]);
function resolvePurifier(): DOMPurifyInstance | null {
if (typeof window === "undefined") return null;
if (typeof DOMPurify.sanitize === "function") return DOMPurify;
return DOMPurify(window);
}
function parseHtml(html: string): HTMLTemplateElement | null {
if (typeof document === "undefined") return null;
const template = document.createElement("template");
template.innerHTML = html;
return template;
}
function allowedAttributesFor(tagName: string): ReadonlySet<string> {
if (TAGS_WITHOUT_ATTRIBUTES.has(tagName as typeof EMAIL_ALLOWED_TAGS[number])) return new Set();
return new Set((EMAIL_ALLOWED_ATTRIBUTES as Record<string, readonly string[]>)[tagName] ?? []);
}
function hasAllowedProtocol(tagName: string, attributeName: string, value: string): boolean {
const protocols = ALLOWED_PROTOCOLS[`${tagName}.${attributeName}`];
if (!protocols) return true;
const match = /^([a-z][a-z\d+.-]*):/i.exec(value.trim());
return Boolean(match && protocols.has(match[1].toLowerCase()));
}
function styleProperties(value: string): Set<string> {
return new Set(
value.split(";")
.map((declaration) => declaration.split(":", 1)[0]?.trim().toLowerCase())
.filter((property): property is string => Boolean(property)),
);
}
function isWysiwygStyleCompatible(tagName: string, value: string): boolean {
if (tagName === "div" || tagName === "img" || tagName === "mark") return true;
const supported = tagName === "span"
? WYSIWYG_SPAN_STYLE_PROPERTIES
: tagName === "p" ? WYSIWYG_PARAGRAPH_STYLE_PROPERTIES : null;
return Boolean(supported && [...styleProperties(value)].every((property) => supported.has(property)));
}
function summarizeIssues(issues: readonly string[]): string {
const unique = [...new Set(issues)];
const visible = unique.slice(0, 3).join(", ");
const suffix = unique.length > 3 ? ` 외 ${unique.length - 3}개` : "";
return `${visible}${suffix} 항목은 WYSIWYG에서 손실될 수 있어 HTML 모드로 유지됩니다.`;
}
export function getEmailWysiwygCompatibility(html: string): KriEditorWysiwygCompatibility {
const template = parseHtml(html);
const issues: string[] = [];
if (!template) {
const tags = [...html.matchAll(/<\/?\s*([a-z][\w-]*)\b/gi)].map((match) => match[1].toLowerCase());
for (const tagName of tags) {
if (!WYSIWYG_TAGS.has(tagName)) issues.push(`<${tagName}>`);
}
} else {
for (const element of Array.from(template.content.querySelectorAll("*"))) {
const tagName = element.tagName.toLowerCase();
if (!WYSIWYG_TAGS.has(tagName)) {
issues.push(`<${tagName}>`);
continue;
}
const supportedAttributes = WYSIWYG_ATTRIBUTES[tagName] ?? new Set<string>();
for (const attribute of Array.from(element.attributes)) {
const attributeName = attribute.name.toLowerCase();
if (!supportedAttributes.has(attributeName)) {
issues.push(`<${tagName}>의 ${attributeName}`);
} else if (attributeName === "style" && !isWysiwygStyleCompatible(tagName, attribute.value)) {
issues.push(`<${tagName}>의 일부 style`);
}
}
if (tagName === "area" && element.parentElement?.tagName.toLowerCase() !== "map") {
issues.push("<map> 밖의 <area>");
}
}
}
return issues.length > 0
? { compatible: false, reason: summarizeIssues(issues) }
: { compatible: true };
}
function isEditorDecoration(tagName: string, attributeName: string, value: string): boolean {
if (tagName === "a" && attributeName === "class" && value === "kri-editor-link") return true;
if (tagName !== "img") return false;
return (attributeName === "class" && value === "max-w-full h-auto")
|| (attributeName === "data-kri-image" && value === "true");
}
export function getEmailHtmlPolicyIssues(html: string): string[] {
const template = parseHtml(html);
if (!template) return [];
const issues: string[] = [];
for (const element of Array.from(template.content.querySelectorAll("*"))) {
const tagName = element.tagName.toLowerCase();
if (!ALLOWED_TAG_SET.has(tagName)) {
issues.push(`<${tagName}> 태그`);
continue;
}
const allowedAttributes = allowedAttributesFor(tagName);
for (const attribute of Array.from(element.attributes)) {
const attributeName = attribute.name.toLowerCase();
if (isEditorDecoration(tagName, attributeName, attribute.value)) continue;
if (!allowedAttributes.has(attributeName)) {
issues.push(`<${tagName}>의 ${attributeName} 속성`);
} else if (!hasAllowedProtocol(tagName, attributeName, attribute.value)) {
issues.push(`<${tagName}>의 ${attributeName} URL`);
}
}
}
return [...new Set(issues)];
}
export function sanitizeEmailHtml(html: string): string {
if (!html) return "";
const purifier = resolvePurifier();
if (!purifier) return html.replace(/<[^>]*>/g, "");
const sanitized = purifier.sanitize(html, {
ALLOWED_TAGS: [...EMAIL_ALLOWED_TAGS],
ALLOWED_ATTR: [...ALLOWED_ATTRIBUTE_SET],
ALLOW_DATA_ATTR: false,
});
const template = parseHtml(sanitized);
if (!template) return "";
for (const element of Array.from(template.content.querySelectorAll("*"))) {
const tagName = element.tagName.toLowerCase();
const allowedAttributes = allowedAttributesFor(tagName);
for (const attribute of Array.from(element.attributes)) {
const attributeName = attribute.name.toLowerCase();
if (!allowedAttributes.has(attributeName) || !hasAllowedProtocol(tagName, attributeName, attribute.value)) {
element.removeAttribute(attribute.name);
}
}
}
return template.innerHTML.replace(/[\u0000-\u0008\u000B\u000C\u000E-\u001F\u007F]/g, "").trim();
}