develop #31
@@ -6,7 +6,9 @@ import { Button } from "@/components/ui/button";
|
||||
import { KriHeader } from "@/components/layout/KriHeader";
|
||||
import type { TopMenuItem } from "@/config/menu.types";
|
||||
import type { LoginUser } from "@kri/common";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { useInternalInfoQuery } from "@/query/internal";
|
||||
import { useCtiConnectionStatus } from "@/hooks/useCtiConnectionStatus";
|
||||
|
||||
interface AppHeaderProps {
|
||||
isMain: boolean;
|
||||
@@ -43,6 +45,8 @@ export function AppHeader({
|
||||
}: AppHeaderProps) {
|
||||
const internalInfoQuery = useInternalInfoQuery(!!userInfo);
|
||||
const seatNo = internalInfoQuery.data?.clientId ?? "";
|
||||
const ctiConnectionStatus = useCtiConnectionStatus();
|
||||
const isCtiConnected = ctiConnectionStatus === "open";
|
||||
|
||||
return (
|
||||
<KriHeader
|
||||
@@ -86,9 +90,20 @@ export function AppHeader({
|
||||
<Button variant="ghost" size="icon-lg" onClick={onOpenReserveSearch} title="예약 내역 조회">
|
||||
<CalendarClock className="size-6" />
|
||||
</Button>
|
||||
<span className="hidden text-sm text-gray-600 sm:inline">
|
||||
<span className="hidden items-center gap-1.5 text-sm text-gray-600 sm:inline-flex">
|
||||
{userInfo?.userName || ""}
|
||||
{seatNo ? ` (${seatNo})` : ""}
|
||||
{seatNo ? (
|
||||
<span className="inline-flex items-center gap-1">
|
||||
{`(${seatNo})`}
|
||||
<span
|
||||
className={cn(
|
||||
"inline-block h-2 w-2 rounded-full",
|
||||
isCtiConnected ? "bg-green-500" : "bg-red-500",
|
||||
)}
|
||||
title={isCtiConnected ? "CTI 연결됨" : "CTI 연결 안됨"}
|
||||
/>
|
||||
</span>
|
||||
) : null}
|
||||
</span>
|
||||
<Button variant="ghost" size="sm" className="gap-2" onClick={() => onNavigate("/logout")}>
|
||||
<LogOut className="h-4 w-4" />
|
||||
|
||||
@@ -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,
|
||||
),
|
||||
),
|
||||
),
|
||||
|
||||
@@ -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)])),
|
||||
|
||||
@@ -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";
|
||||
@@ -34,6 +35,7 @@ import { applyLinkPreviewClass, KRI_EDITOR_LINK_CLASS } from "./utils/linkPrevie
|
||||
import { Toolbar } from "./toolbar/Toolbar";
|
||||
import { useDebouncedChange } from "./hooks/useDebouncedChange";
|
||||
import { useTextareaInsert } from "./hooks/useTextareaInsert";
|
||||
import { useImageMapOverlay } from "./hooks/useImageMapOverlay";
|
||||
|
||||
type ViewMode = "wysiwyg" | "html";
|
||||
|
||||
@@ -97,6 +99,9 @@ export function KriEditorWysiwyg(props: KriEditorProps) {
|
||||
fontFamilyOptions = DEFAULT_FONT_FAMILY_OPTIONS,
|
||||
editorExtensions = [],
|
||||
allowedCustomHtml,
|
||||
enableImageMap = false,
|
||||
htmlSanitizer,
|
||||
getWysiwygCompatibility,
|
||||
transformPreviewHtml,
|
||||
} = props;
|
||||
|
||||
@@ -110,13 +115,19 @@ export function KriEditorWysiwyg(props: KriEditorProps) {
|
||||
const { scheduleChange, flushChange, optimisticHtmlRef } = useDebouncedChange(onChange, debounceMs);
|
||||
|
||||
const fileRef = useRef<HTMLInputElement | null>(null);
|
||||
const previewContainerRef = useRef<HTMLDivElement | null>(null);
|
||||
const htmlTextareaRef = useRef<HTMLTextAreaElement | null>(null);
|
||||
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 +190,7 @@ export function KriEditorWysiwyg(props: KriEditorProps) {
|
||||
TableHeader,
|
||||
TableCell,
|
||||
|
||||
TiptapImage.configure({
|
||||
(enableImageMap ? ImageWithMap : TiptapImage).configure({
|
||||
inline: true,
|
||||
allowBase64,
|
||||
HTMLAttributes: {
|
||||
@@ -191,6 +202,7 @@ export function KriEditorWysiwyg(props: KriEditorProps) {
|
||||
alwaysPreserveAspectRatio: true,
|
||||
},
|
||||
}),
|
||||
...(enableImageMap ? [ImageMap] : []),
|
||||
Placeholder.configure({ placeholder }),
|
||||
...editorExtensions,
|
||||
],
|
||||
@@ -475,12 +487,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 +545,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 +584,7 @@ export function KriEditorWysiwyg(props: KriEditorProps) {
|
||||
editor.createNodeViews();
|
||||
}
|
||||
}
|
||||
}, [value, editor, view]);
|
||||
}, [value, editor, view, getCompatibility, getWysiwygCompatibility, showHtmlToggle]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!editor) return;
|
||||
@@ -611,10 +648,19 @@ 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 imageMapOverlayBoxes = useImageMapOverlay(previewContainerRef, previewHtml);
|
||||
|
||||
const wysiwygCompatibility = useMemo(
|
||||
() => getCompatibility(view === "html" ? previewSource : (editor?.getHTML() ?? previewSource)),
|
||||
[editor, getCompatibility, previewSource, view],
|
||||
);
|
||||
|
||||
if (!editor) {
|
||||
return (
|
||||
@@ -640,6 +686,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,14 +729,30 @@ 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>
|
||||
)}
|
||||
|
||||
{showPreview && (
|
||||
<div className={cn("border-t p-3", previewClassName)}>
|
||||
<div className="mb-2 text-sm font-semibold">미리보기</div>
|
||||
<div className="rounded-md border bg-muted/30 p-3">
|
||||
<div ref={previewContainerRef} className="relative rounded-md border bg-muted/30 p-3">
|
||||
<div dangerouslySetInnerHTML={{ __html: previewHtml }} />
|
||||
{imageMapOverlayBoxes.length > 0 && (
|
||||
<div className="pointer-events-none absolute inset-0" aria-hidden="true">
|
||||
{imageMapOverlayBoxes.map((box) => (
|
||||
<div
|
||||
key={box.key}
|
||||
className="absolute border-2 border-sky-500 bg-sky-500/30"
|
||||
style={box.style}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
93
src/components/kri-editor/extensions/image-map.ts
Normal file
93
src/components/kri-editor/extensions/image-map.ts
Normal 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
|
||||
},
|
||||
})
|
||||
46
src/components/kri-editor/hooks/useImageMapOverlay.ts
Normal file
46
src/components/kri-editor/hooks/useImageMapOverlay.ts
Normal file
@@ -0,0 +1,46 @@
|
||||
import { useLayoutEffect, useRef, useState } from "react"
|
||||
import { computeImageMapOverlayBoxes, type ImageMapOverlayBox } from "../utils/imageMapOverlay"
|
||||
|
||||
// previewHtml이 바뀔 때마다(이미지 로드/리사이즈 포함) <map>/<area> 오버레이 위치를 다시 계산한다.
|
||||
export function useImageMapOverlay(
|
||||
containerRef: React.RefObject<HTMLElement | null>,
|
||||
previewHtml: string,
|
||||
): ImageMapOverlayBox[] {
|
||||
const [boxes, setBoxes] = useState<ImageMapOverlayBox[]>([])
|
||||
const frameRef = useRef<number | null>(null)
|
||||
|
||||
useLayoutEffect(() => {
|
||||
const container = containerRef.current
|
||||
if (!container) {
|
||||
setBoxes([])
|
||||
return
|
||||
}
|
||||
|
||||
const recompute = () => setBoxes(computeImageMapOverlayBoxes(container))
|
||||
|
||||
const scheduleRecompute = () => {
|
||||
if (frameRef.current !== null) cancelAnimationFrame(frameRef.current)
|
||||
frameRef.current = requestAnimationFrame(recompute)
|
||||
}
|
||||
|
||||
scheduleRecompute()
|
||||
|
||||
const images = Array.from(container.querySelectorAll<HTMLImageElement>("img[usemap]"))
|
||||
images.forEach((img) => {
|
||||
if (!img.complete) img.addEventListener("load", scheduleRecompute)
|
||||
})
|
||||
|
||||
const resizeObserver = new ResizeObserver(scheduleRecompute)
|
||||
resizeObserver.observe(container)
|
||||
window.addEventListener("resize", scheduleRecompute)
|
||||
|
||||
return () => {
|
||||
if (frameRef.current !== null) cancelAnimationFrame(frameRef.current)
|
||||
images.forEach((img) => img.removeEventListener("load", scheduleRecompute))
|
||||
resizeObserver.disconnect()
|
||||
window.removeEventListener("resize", scheduleRecompute)
|
||||
}
|
||||
}, [containerRef, previewHtml])
|
||||
|
||||
return boxes
|
||||
}
|
||||
@@ -14,6 +14,7 @@ export type {
|
||||
KriEditorToolbarContext,
|
||||
KriEditorToolbarFeature,
|
||||
KriEditorUploadResult,
|
||||
KriEditorWysiwygCompatibility,
|
||||
ToolbarState,
|
||||
} from './types'
|
||||
export type { KriEditorToolbarButtonProps } from './toolbar/ToolbarButton'
|
||||
|
||||
@@ -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}
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
|
||||
112
src/components/kri-editor/utils/imageMapOverlay.ts
Normal file
112
src/components/kri-editor/utils/imageMapOverlay.ts
Normal file
@@ -0,0 +1,112 @@
|
||||
export type ImageMapOverlayBox = {
|
||||
key: string
|
||||
style: {
|
||||
left: number
|
||||
top: number
|
||||
width: number
|
||||
height: number
|
||||
borderRadius?: string
|
||||
clipPath?: string
|
||||
}
|
||||
}
|
||||
|
||||
const parseCoords = (raw: string | null): number[] =>
|
||||
(raw ?? "")
|
||||
.split(",")
|
||||
.map((value) => Number(value.trim()))
|
||||
.filter((value) => Number.isFinite(value))
|
||||
|
||||
// coords는 <img>의 원본(naturalWidth/Height) 기준이라, 미리보기에서 이미지가
|
||||
// 리사이즈되어 렌더링된 크기에 맞춰 스케일 변환한 뒤 컨테이너 기준 좌표로 옮겨야 한다.
|
||||
export function computeImageMapOverlayBoxes(container: HTMLElement): ImageMapOverlayBox[] {
|
||||
const boxes: ImageMapOverlayBox[] = []
|
||||
const containerRect = container.getBoundingClientRect()
|
||||
const images = container.querySelectorAll<HTMLImageElement>("img[usemap]")
|
||||
|
||||
images.forEach((img, imageIndex) => {
|
||||
if (!img.complete || img.naturalWidth === 0 || img.naturalHeight === 0) return
|
||||
|
||||
const mapName = img.getAttribute("usemap")?.replace(/^#/, "")
|
||||
if (!mapName) return
|
||||
|
||||
const map = container.querySelector<HTMLMapElement>(`map[name="${CSS.escape(mapName)}"]`)
|
||||
if (!map) return
|
||||
|
||||
const imgRect = img.getBoundingClientRect()
|
||||
if (imgRect.width === 0 || imgRect.height === 0) return
|
||||
|
||||
const scaleX = imgRect.width / img.naturalWidth
|
||||
const scaleY = imgRect.height / img.naturalHeight
|
||||
const offsetX = imgRect.left - containerRect.left
|
||||
const offsetY = imgRect.top - containerRect.top
|
||||
|
||||
map.querySelectorAll("area").forEach((area, areaIndex) => {
|
||||
const shape = (area.getAttribute("shape") || "rect").toLowerCase()
|
||||
const coords = parseCoords(area.getAttribute("coords"))
|
||||
const key = `${imageIndex}-${areaIndex}`
|
||||
|
||||
if (shape === "rect" && coords.length >= 4) {
|
||||
const [x1, y1, x2, y2] = coords
|
||||
boxes.push({
|
||||
key,
|
||||
style: {
|
||||
left: offsetX + Math.min(x1, x2) * scaleX,
|
||||
top: offsetY + Math.min(y1, y2) * scaleY,
|
||||
width: Math.abs(x2 - x1) * scaleX,
|
||||
height: Math.abs(y2 - y1) * scaleY,
|
||||
},
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
if (shape === "circle" && coords.length >= 3) {
|
||||
const [cx, cy, r] = coords
|
||||
boxes.push({
|
||||
key,
|
||||
style: {
|
||||
left: offsetX + (cx - r) * scaleX,
|
||||
top: offsetY + (cy - r) * scaleY,
|
||||
width: r * 2 * scaleX,
|
||||
height: r * 2 * scaleY,
|
||||
borderRadius: "9999px",
|
||||
},
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
if (shape === "poly" && coords.length >= 6 && coords.length % 2 === 0) {
|
||||
const xs = coords.filter((_, i) => i % 2 === 0)
|
||||
const ys = coords.filter((_, i) => i % 2 === 1)
|
||||
const minX = Math.min(...xs)
|
||||
const maxX = Math.max(...xs)
|
||||
const minY = Math.min(...ys)
|
||||
const maxY = Math.max(...ys)
|
||||
const width = maxX - minX
|
||||
const height = maxY - minY
|
||||
if (width <= 0 || height <= 0) return
|
||||
|
||||
const points: string[] = []
|
||||
for (let i = 0; i < coords.length; i += 2) {
|
||||
const px = ((coords[i] - minX) / width) * 100
|
||||
const py = ((coords[i + 1] - minY) / height) * 100
|
||||
points.push(`${px}% ${py}%`)
|
||||
}
|
||||
|
||||
boxes.push({
|
||||
key,
|
||||
style: {
|
||||
left: offsetX + minX * scaleX,
|
||||
top: offsetY + minY * scaleY,
|
||||
width: width * scaleX,
|
||||
height: height * scaleY,
|
||||
clipPath: `polygon(${points.join(", ")})`,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
// shape="default"(이미지 전체)는 별도 오버레이 없이 그대로 둔다.
|
||||
})
|
||||
})
|
||||
|
||||
return boxes
|
||||
}
|
||||
@@ -57,6 +57,12 @@ import {
|
||||
QrCode,
|
||||
renderQrCodePreviewHtml,
|
||||
} from "@/components/message-template/qrcode";
|
||||
import {
|
||||
getEmailHtmlPolicyIssues,
|
||||
getEmailWysiwygCompatibility,
|
||||
hasImageMapMarkup,
|
||||
sanitizeEmailHtml,
|
||||
} from "@/components/message-template/emailHtmlPolicy";
|
||||
|
||||
interface MessageTemplateProps {
|
||||
pageTitle: string;
|
||||
@@ -368,13 +374,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 +599,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}) => (
|
||||
@@ -589,6 +610,12 @@ const MessageTemplate = ({ pageTitle, defaultTemplate }: MessageTemplateProps) =
|
||||
/>
|
||||
)}
|
||||
|
||||
{!isSms && hasImageMapMarkup(selectedTemplate.tmplatBody) && (
|
||||
<p className="text-sm text-muted-foreground">
|
||||
※ <map>, <area> 가 사용된 경우 해당 영역이 반투명하게 보여집니다.
|
||||
</p>
|
||||
)}
|
||||
|
||||
{!isSms && (
|
||||
<div className="space-y-2">
|
||||
<div className="flex items-center justify-between">
|
||||
|
||||
225
src/components/message-template/emailHtmlPolicy.ts
Normal file
225
src/components/message-template/emailHtmlPolicy.ts
Normal file
@@ -0,0 +1,225 @@
|
||||
"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 hasImageMapMarkup(html: string): boolean {
|
||||
if (!html) return false;
|
||||
const template = parseHtml(html);
|
||||
if (!template) return /<\s*(map|area)\b/i.test(html);
|
||||
return template.content.querySelector("map, area") !== null;
|
||||
}
|
||||
|
||||
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();
|
||||
}
|
||||
Reference in New Issue
Block a user