261117_02_ENH: kri-editor 이미지맵 미리보기 오버레이·smsFrameClassName 추가, React Compiler lint 및 SonarQube 지적 사항 수정
This commit is contained in:
@@ -65,7 +65,6 @@ export function KriEditorHtmlOnly({
|
||||
React.useEffect(() => {
|
||||
applyExternalValue(value || '')
|
||||
// 최초 마운트 시 1회만 실행 — 이후 value 변경은 아래 effect가 처리한다.
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [])
|
||||
|
||||
React.useEffect(() => {
|
||||
|
||||
@@ -8,10 +8,25 @@ import { useTextareaInsert } from './hooks/useTextareaInsert'
|
||||
|
||||
type SmsEditorProps = Omit<KriEditorProps, 'mode'> & { mode: 'sms' }
|
||||
|
||||
type SmsMessageType = 'SMS' | 'LMS' | 'MMS'
|
||||
|
||||
function calculateBytes(value: string): number {
|
||||
return new TextEncoder().encode(value).byteLength
|
||||
}
|
||||
|
||||
// 첨부파일이 있으면 MMS, 제목이 있거나 smsMaxBytes 이상이면 LMS, 나머지는 SMS로 미리보기 판정한다.
|
||||
function getSmsMessageType(hasAttachment: boolean, byteSize: number, smsMaxBytes: number, title: string): SmsMessageType {
|
||||
if (hasAttachment) return 'MMS'
|
||||
if (byteSize >= smsMaxBytes || Boolean(title)) return 'LMS'
|
||||
return 'SMS'
|
||||
}
|
||||
|
||||
function getTextareaMinHeight(hasImages: boolean, hasTitle: boolean): string {
|
||||
if (hasImages) return '160px'
|
||||
if (hasTitle) return '320px'
|
||||
return '360px'
|
||||
}
|
||||
|
||||
export function KriEditorSms({
|
||||
label,
|
||||
value,
|
||||
@@ -29,16 +44,17 @@ export function KriEditorSms({
|
||||
smsPreviewSuffix = '',
|
||||
smsHasAttachment = false,
|
||||
smsImages = [],
|
||||
smsFrameClassName,
|
||||
}: SmsEditorProps) {
|
||||
const [text, setText] = React.useState(value || '')
|
||||
const textareaRef = React.useRef<HTMLTextAreaElement | null>(null)
|
||||
const latestTextRef = React.useRef(text)
|
||||
const lastTypeRef = React.useRef<'SMS' | 'LMS' | 'MMS' | null>(null)
|
||||
const lastTypeRef = React.useRef<SmsMessageType | null>(null)
|
||||
const { scheduleChange, flushChange } = useDebouncedChange(onChange, debounceMs)
|
||||
const textareaInsert = useTextareaInsert(textareaRef)
|
||||
const previewText = smsPreviewSuffix ? `${text}\n${smsPreviewSuffix}` : text
|
||||
const byteSize = React.useMemo(() => calculateBytes(previewText), [previewText])
|
||||
const messageType: 'SMS' | 'LMS' | 'MMS' = smsHasAttachment ? 'MMS' : byteSize >= smsMaxBytes || Boolean(smsTitle) ? 'LMS' : 'SMS'
|
||||
const messageType = getSmsMessageType(smsHasAttachment, byteSize, smsMaxBytes, smsTitle)
|
||||
const maxBytes = messageType === 'SMS' ? smsMaxBytes : lmsMaxBytes
|
||||
|
||||
function getBadgeColor(): string {
|
||||
@@ -95,7 +111,7 @@ export function KriEditorSms({
|
||||
return (
|
||||
<div className={cn('mx-auto w-full max-w-[320px]', className)}>
|
||||
{label ? <div className="mb-2 text-sm font-semibold">{label}</div> : null}
|
||||
<div className="relative h-[600px] w-full overflow-hidden rounded-[40px] border-8 border-gray-800 bg-white shadow-2xl">
|
||||
<div className={cn('relative h-[600px] w-full overflow-hidden rounded-[40px] border-8 border-gray-800 bg-white shadow-2xl', smsFrameClassName)}>
|
||||
<div className="absolute top-0 left-1/2 z-10 h-6 w-32 -translate-x-1/2 rounded-b-2xl bg-gray-800" />
|
||||
<div className="flex h-full flex-col bg-gray-50 px-4 pt-8 pb-4">
|
||||
<div className="mb-3 flex items-center justify-between px-2">
|
||||
@@ -126,7 +142,7 @@ export function KriEditorSms({
|
||||
onBlur={() => flushChange(latestTextRef.current)}
|
||||
placeholder={placeholder}
|
||||
readOnly={isSmsReadOnly}
|
||||
style={{ minHeight: smsImages.length > 0 ? '160px' : smsTitle ? '320px' : '360px' }}
|
||||
style={{ minHeight: getTextareaMinHeight(smsImages.length > 0, Boolean(smsTitle)) }}
|
||||
{...textareaInsert.bindSelectionHandlers}
|
||||
/>
|
||||
{smsPreviewSuffix ? (
|
||||
|
||||
@@ -35,9 +35,62 @@ 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";
|
||||
|
||||
type ToolbarEndSlotProps = Pick<KriEditorProps, "renderToolbarEnd"> & {
|
||||
editor: Editor;
|
||||
command: KriEditorCommand;
|
||||
view: ViewMode;
|
||||
};
|
||||
|
||||
// command는 ref를 사용하는 함수 묶음이라, 렌더 중 외부 함수에 직접 넘기면 React Compiler가
|
||||
// ref 접근으로 판단한다. 별도 컴포넌트의 props로 전달해 렌더 범위를 분리한다(동작 동일).
|
||||
function ToolbarEndSlot({ renderToolbarEnd, editor, command, view }: Readonly<ToolbarEndSlotProps>) {
|
||||
return <>{renderToolbarEnd?.({ editor, command, view })}</>;
|
||||
}
|
||||
|
||||
// 주입된 정제 함수가 우선이고, 없으면 sanitizeHtml 옵션에 따라 기본 정제기를 사용한다.
|
||||
function sanitizeEditorHtml(
|
||||
html: string,
|
||||
htmlSanitizer: KriEditorProps["htmlSanitizer"],
|
||||
sanitizeEnabled: boolean,
|
||||
allowedCustomHtml: KriEditorProps["allowedCustomHtml"],
|
||||
): string {
|
||||
if (htmlSanitizer) return htmlSanitizer(html);
|
||||
if (sanitizeEnabled) return sanitizeHtml(html, allowedCustomHtml);
|
||||
return html;
|
||||
}
|
||||
|
||||
function writeHtmlDraft(
|
||||
draftRef: { current: string },
|
||||
textareaRef: { current: HTMLTextAreaElement | null },
|
||||
html: string,
|
||||
): void {
|
||||
draftRef.current = html;
|
||||
if (textareaRef.current) textareaRef.current.value = html;
|
||||
}
|
||||
|
||||
// 외부에서 본문이 변경된 경우에만 기존 editor 문서를 갱신한다.
|
||||
function syncEditorContent(editor: Editor, value: string, optimisticHtml: string): void {
|
||||
// 빈 문자열("")은 ProseMirror 스키마상 유효한 문서가 아니라 setContent가 조용히 실패해
|
||||
// 이전 템플릿 본문이 그대로 남는 문제가 있었음 -> 빈 값은 빈 문단으로 정규화해서 비교/설정.
|
||||
const normalizedValue = value || "<p></p>";
|
||||
if (normalizedValue === editor.getHTML() || normalizedValue === optimisticHtml) return;
|
||||
|
||||
editor.commands.setContent(normalizedValue, {
|
||||
emitUpdate: false,
|
||||
parseOptions: { preserveWhitespace: "full" },
|
||||
});
|
||||
|
||||
// resize가 활성화된 TipTap 이미지 NodeView는 노드의 src 변경을 기존 DOM에 반영하지 않는다.
|
||||
// editor 전체 대신 NodeView만 다시 생성해 이미지를 갱신하고 편집 포커스는 유지한다.
|
||||
if (normalizedValue.includes("<img")) {
|
||||
editor.createNodeViews();
|
||||
}
|
||||
}
|
||||
|
||||
function getToolbarState(editor: Editor): ToolbarState {
|
||||
const ts = editor.getAttributes("textStyle") as { fontSize?: string | null; fontFamily?: string | null; color?: string | null };
|
||||
const hl = editor.getAttributes("highlight") as { color?: string | null };
|
||||
@@ -69,7 +122,7 @@ function getToolbarState(editor: Editor): ToolbarState {
|
||||
};
|
||||
}
|
||||
|
||||
export function KriEditorWysiwyg(props: KriEditorProps) {
|
||||
export function KriEditorWysiwyg(props: Readonly<KriEditorProps>) {
|
||||
const {
|
||||
|
||||
label,
|
||||
@@ -114,6 +167,7 @@ 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;
|
||||
@@ -132,6 +186,9 @@ export function KriEditorWysiwyg(props: KriEditorProps) {
|
||||
}, [view]);
|
||||
|
||||
const htmlDraftRef = useRef<string>(value ?? "");
|
||||
// HTML textarea는 비제어 컴포넌트다. 렌더 중 ref를 읽지 않도록, HTML 보기로 전환하는 시점의
|
||||
// 초안을 state로 보관해 textarea가 마운트될 때의 초기값(defaultValue)으로만 사용한다.
|
||||
const [htmlTextareaSeed, setHtmlTextareaSeed] = useState<string>(value ?? "");
|
||||
const canImageUpload = Boolean(onImageUpload);
|
||||
|
||||
const selectionRef = useRef<{ from: number; to: number } | null>(null);
|
||||
@@ -469,6 +526,7 @@ export function KriEditorWysiwyg(props: KriEditorProps) {
|
||||
if (viewRef.current === "wysiwyg") {
|
||||
const raw = editor.getHTML();
|
||||
htmlDraftRef.current = raw;
|
||||
setHtmlTextareaSeed(raw);
|
||||
setView("html");
|
||||
|
||||
// WYSIWYG에서 막 넘어온, 사용자가 직접 타이핑하지 않은 HTML이므로
|
||||
@@ -490,14 +548,12 @@ export function KriEditorWysiwyg(props: KriEditorProps) {
|
||||
toast.message(compatibility.reason ?? "현재 HTML은 WYSIWYG로 전환할 수 없습니다.");
|
||||
return;
|
||||
}
|
||||
const safe = htmlSanitizer
|
||||
? htmlSanitizer(raw)
|
||||
: sanitizeHtmlOpt ? sanitizeHtml(raw, allowedCustomHtml) : raw;
|
||||
const safe = sanitizeEditorHtml(raw, htmlSanitizer, sanitizeHtmlOpt, allowedCustomHtml);
|
||||
|
||||
editor.commands.setContent(safe, { emitUpdate: false, parseOptions: { preserveWhitespace: "full" } });
|
||||
flushChange(preserveEmptyParagraphs(editor.getHTML()));
|
||||
setView("wysiwyg");
|
||||
}, [allowedCustomHtml, editor, flushChange, getCompatibility, htmlSanitizer, sanitizeHtmlOpt]);
|
||||
}, [allowedCustomHtml, editor, flushChange, getCompatibility, htmlSanitizer, sanitizeHtmlOpt, setView, setPreviewSource, setHtmlTextareaSeed]);
|
||||
|
||||
const formatHtmlView = useCallback(async () => {
|
||||
try {
|
||||
@@ -510,7 +566,7 @@ export function KriEditorWysiwyg(props: KriEditorProps) {
|
||||
toast.error("HTML 정렬에 실패했습니다.");
|
||||
console.error(err);
|
||||
}
|
||||
}, [scheduleChange]);
|
||||
}, [scheduleChange, setPreviewSource]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!editor) return;
|
||||
@@ -542,46 +598,28 @@ export function KriEditorWysiwyg(props: KriEditorProps) {
|
||||
|
||||
useEffect(() => {
|
||||
setPreviewSource(value ?? "");
|
||||
if (!editor) return;
|
||||
if (value == null) return;
|
||||
if (!editor || value == null) return;
|
||||
|
||||
const compatibility = getCompatibility(value);
|
||||
if (showHtmlToggle && !compatibility.compatible) {
|
||||
htmlDraftRef.current = value;
|
||||
if (htmlTextareaRef.current) htmlTextareaRef.current.value = value;
|
||||
// WYSIWYG로 손실 없이 편집할 수 없는 값은 HTML 보기로 전환해 원문을 유지한다.
|
||||
if (showHtmlToggle && !getCompatibility(value).compatible) {
|
||||
writeHtmlDraft(htmlDraftRef, htmlTextareaRef, value);
|
||||
if (viewRef.current !== "html") {
|
||||
viewRef.current = "html";
|
||||
setHtmlTextareaSeed(value);
|
||||
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;
|
||||
const isExternalChange = value !== optimisticHtmlRef.current && value !== htmlDraftRef.current;
|
||||
if (getWysiwygCompatibility && isExternalChange) {
|
||||
writeHtmlDraft(htmlDraftRef, htmlTextareaRef, value);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// 빈 문자열("")은 ProseMirror 스키마상 유효한 문서가 아니라 setContent가 조용히 실패해
|
||||
// 이전 템플릿 본문이 그대로 남는 문제가 있었음 -> 빈 값은 빈 문단으로 정규화해서 비교/설정.
|
||||
const normalizedValue = value || "<p></p>";
|
||||
const current = editor.getHTML();
|
||||
|
||||
if (normalizedValue !== current && normalizedValue !== optimisticHtmlRef.current) {
|
||||
// 외부에서 본문이 변경된 경우에만 기존 editor 문서를 갱신한다.
|
||||
editor.commands.setContent(normalizedValue, {
|
||||
emitUpdate: false,
|
||||
parseOptions: {preserveWhitespace: "full"},
|
||||
});
|
||||
|
||||
// resize가 활성화된 TipTap 이미지 NodeView는 노드의 src 변경을 기존 DOM에 반영하지 않는다.
|
||||
// editor 전체 대신 NodeView만 다시 생성해 이미지를 갱신하고 편집 포커스는 유지한다.
|
||||
if (normalizedValue.includes("<img")) {
|
||||
editor.createNodeViews();
|
||||
}
|
||||
}
|
||||
syncEditorContent(editor, value, optimisticHtmlRef.current);
|
||||
}, [value, editor, view, getCompatibility, getWysiwygCompatibility, showHtmlToggle]);
|
||||
|
||||
useEffect(() => {
|
||||
@@ -646,13 +684,14 @@ export function KriEditorWysiwyg(props: KriEditorProps) {
|
||||
|
||||
const previewHtml = useMemo(() => {
|
||||
const preserved = preserveEmptyParagraphs(previewSource);
|
||||
const sanitized = htmlSanitizer
|
||||
? htmlSanitizer(preserved)
|
||||
: sanitizeHtmlOpt ? sanitizeHtml(preserved, allowedCustomHtml) : preserved;
|
||||
const sanitized = sanitizeEditorHtml(preserved, htmlSanitizer, sanitizeHtmlOpt, allowedCustomHtml);
|
||||
const withLinkStyle = applyLinkPreviewClass(sanitized);
|
||||
return transformPreviewHtml ? transformPreviewHtml(withLinkStyle) : withLinkStyle;
|
||||
}, [allowedCustomHtml, htmlSanitizer, previewSource, sanitizeHtmlOpt, transformPreviewHtml]);
|
||||
|
||||
// 이미지맵을 사용할 때만 미리보기에 <area> 영역을 표시한다.
|
||||
const imageMapOverlayBoxes = useImageMapOverlay(previewContainerRef, previewHtml, enableImageMap && showPreview);
|
||||
|
||||
const wysiwygCompatibility = useMemo(
|
||||
() => getCompatibility(view === "html" ? previewSource : (editor?.getHTML() ?? previewSource)),
|
||||
[editor, getCompatibility, previewSource, view],
|
||||
@@ -700,7 +739,11 @@ export function KriEditorWysiwyg(props: KriEditorProps) {
|
||||
onAddRow={addRow}
|
||||
onAddColumn={addColumn}
|
||||
onDeleteTable={deleteTable}
|
||||
customContent={props.renderToolbarEnd?.({ editor, command, view })}
|
||||
customContent={
|
||||
props.renderToolbarEnd ? (
|
||||
<ToolbarEndSlot renderToolbarEnd={props.renderToolbarEnd} editor={editor} command={command} view={view} />
|
||||
) : undefined
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
) : null}
|
||||
@@ -714,7 +757,7 @@ export function KriEditorWysiwyg(props: KriEditorProps) {
|
||||
<textarea
|
||||
ref={htmlTextareaRef}
|
||||
className="h-[220px] w-full resize-y rounded-md border bg-background p-3 font-mono text-sm outline-none"
|
||||
defaultValue={htmlDraftRef.current}
|
||||
defaultValue={htmlTextareaSeed}
|
||||
onMouseDown={(e) => e.stopPropagation()}
|
||||
onChange={(e) => {
|
||||
htmlDraftRef.current = e.target.value;
|
||||
@@ -726,9 +769,9 @@ export function KriEditorWysiwyg(props: KriEditorProps) {
|
||||
{...htmlTi.bindSelectionHandlers}
|
||||
/>
|
||||
{!wysiwygCompatibility.compatible ? (
|
||||
<p className="mt-2 text-xs text-amber-700" role="status">
|
||||
<output className="mt-2 block text-xs text-amber-700">
|
||||
{wysiwygCompatibility.reason ?? "현재 HTML은 WYSIWYG에서 손실 없이 편집할 수 없습니다."}
|
||||
</p>
|
||||
</output>
|
||||
) : null}
|
||||
</div>
|
||||
)}
|
||||
@@ -736,8 +779,19 @@ export function KriEditorWysiwyg(props: KriEditorProps) {
|
||||
{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>
|
||||
)}
|
||||
|
||||
48
registry/components/kri-editor/hooks/useImageMapOverlay.ts
Normal file
48
registry/components/kri-editor/hooks/useImageMapOverlay.ts
Normal file
@@ -0,0 +1,48 @@
|
||||
import { useLayoutEffect, useRef, useState } from "react"
|
||||
import { computeImageMapOverlayBoxes, type ImageMapOverlayBox } from "../utils/imageMapOverlay"
|
||||
|
||||
// previewHtml이 바뀔 때마다(이미지 로드/리사이즈 포함) <map>/<area> 오버레이 위치를 다시 계산한다.
|
||||
// enabled가 false이면 계산·관찰하지 않는다.
|
||||
export function useImageMapOverlay(
|
||||
containerRef: React.RefObject<HTMLElement | null>,
|
||||
previewHtml: string,
|
||||
enabled = true,
|
||||
): ImageMapOverlayBox[] {
|
||||
const [boxes, setBoxes] = useState<ImageMapOverlayBox[]>([])
|
||||
const frameRef = useRef<number | null>(null)
|
||||
|
||||
useLayoutEffect(() => {
|
||||
const container = containerRef.current
|
||||
if (!enabled || !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, enabled])
|
||||
|
||||
return boxes
|
||||
}
|
||||
@@ -90,6 +90,8 @@ export type KriEditorProps = {
|
||||
smsHasAttachment?: boolean
|
||||
/** 문자 미리보기의 제목과 본문 사이에 표시할 첨부 이미지 */
|
||||
smsImages?: KriEditorSmsImage[]
|
||||
/** 휴대폰 프레임 class (기본 높이 h-[600px] 조정 등) */
|
||||
smsFrameClassName?: string
|
||||
/** 알림톡 미리보기의 강조 제목. 없으면 표시하지 않는다. */
|
||||
kkoTitle?: string
|
||||
/** 알림톡 미리보기의 채널명·발신 프로필 이름. 없으면 표시하지 않는다. */
|
||||
|
||||
112
registry/components/kri-editor/utils/imageMapOverlay.ts
Normal file
112
registry/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
|
||||
}
|
||||
Reference in New Issue
Block a user