251216_01_ENH : 프로젝트에 FW User 배정 구현 및 테스트 완료
This commit is contained in:
@@ -5,6 +5,9 @@ import { cn } from "@/lib/utils";
|
||||
import type { KriEditorProps } from "./types";
|
||||
import { useDebouncedChange } from "./hooks/useDebouncedChange";
|
||||
import { sanitizeHtmlForPreview } from "./utils/sanitizeHtml";
|
||||
import {useCallback} from "react";
|
||||
import {toast} from "sonner";
|
||||
import {compressImage} from "@/components/kri-editor/utils/imageCompression";
|
||||
|
||||
type HtmlOnlyProps = Omit<KriEditorProps, "mode"> & {
|
||||
mode: "html";
|
||||
@@ -20,18 +23,26 @@ export function KriEditorHtmlOnly(props: HtmlOnlyProps) {
|
||||
showPreview,
|
||||
previewClassName,
|
||||
rows = 14,
|
||||
debounceMs = 350,
|
||||
|
||||
onImageUpload,
|
||||
onImageUploadError,
|
||||
debounceMs = 350,
|
||||
maxImageBytes = 5 * 1024 * 1024,
|
||||
imageMaxWidth = 1600,
|
||||
imageMaxHeight = 1600,
|
||||
imageQuality = 0.82,
|
||||
imageMimeType = "image/webp",
|
||||
} = props;
|
||||
|
||||
const [html, setHtml] = React.useState<string>(value || "");
|
||||
const textareaRef = React.useRef<HTMLTextAreaElement | null>(null);
|
||||
const fileInputRef = React.useRef<HTMLInputElement | null>(null);
|
||||
const fileRef = React.useRef<HTMLInputElement | null>(null);
|
||||
const latestHtmlRef = React.useRef(html);
|
||||
latestHtmlRef.current = html;
|
||||
|
||||
const flushChange = useDebouncedChange(onChange, debounceMs);
|
||||
const canImageUpload = Boolean(onImageUpload);
|
||||
|
||||
const { scheduleChange, flushChange } = useDebouncedChange(onChange, debounceMs);
|
||||
|
||||
// 외부 value 변경 시 동기화
|
||||
React.useEffect(() => {
|
||||
@@ -45,65 +56,100 @@ export function KriEditorHtmlOnly(props: HtmlOnlyProps) {
|
||||
const next = e.target.value;
|
||||
setHtml(next);
|
||||
latestHtmlRef.current = next;
|
||||
flushChange(next);
|
||||
scheduleChange(next);
|
||||
};
|
||||
|
||||
const handleBlur = () => {
|
||||
flushChange(latestHtmlRef.current);
|
||||
};
|
||||
|
||||
const handleClickImageButton = () => {
|
||||
if (!onImageUpload) return;
|
||||
fileInputRef.current?.click();
|
||||
};
|
||||
const handlePickImage = useCallback(() => {
|
||||
if (!canImageUpload) return;
|
||||
fileRef.current?.click();
|
||||
}, [canImageUpload]);
|
||||
|
||||
const handleFileChange = async (
|
||||
e: React.ChangeEvent<HTMLInputElement>,
|
||||
) => {
|
||||
const file = e.target.files?.[0];
|
||||
if (!file || !onImageUpload) return;
|
||||
const handleFile = useCallback(
|
||||
async (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
try {
|
||||
const file = e.target.files?.[0];
|
||||
e.target.value = "";
|
||||
if (!file) return;
|
||||
|
||||
try {
|
||||
const url = await onImageUpload(file);
|
||||
if (!url) return;
|
||||
if (!canImageUpload || !onImageUpload) return;
|
||||
|
||||
setHtml((prev) => {
|
||||
const current = prev ?? "";
|
||||
const textarea = textareaRef.current;
|
||||
const imgTag = `<img src="${url}" alt="" />`;
|
||||
if (!file.type.startsWith("image/")) {
|
||||
toast.error("이미지 파일만 업로드할 수 있습니다.");
|
||||
return;
|
||||
}
|
||||
|
||||
if (!textarea) {
|
||||
const next = current + imgTag;
|
||||
latestHtmlRef.current = next;
|
||||
flushChange(next);
|
||||
return next;
|
||||
const compressed = await compressImage(file, {
|
||||
maxBytes: maxImageBytes,
|
||||
maxWidth: imageMaxWidth,
|
||||
maxHeight: imageMaxHeight,
|
||||
mimeType: imageMimeType,
|
||||
quality: imageQuality,
|
||||
});
|
||||
|
||||
if (compressed.size > maxImageBytes) {
|
||||
toast.error("이미지 용량이 제한을 초과합니다.", {
|
||||
description: `최대 ${(maxImageBytes / (1024 * 1024)).toFixed(0)}MB`,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
const { url } = await onImageUpload(compressed);
|
||||
|
||||
if (!url || typeof url !== "string") {
|
||||
toast.error("이미지 업로드 응답이 올바르지 않습니다.");
|
||||
return;
|
||||
}
|
||||
|
||||
setHtml((prev) => {
|
||||
const current = prev ?? "";
|
||||
const textarea = textareaRef.current;
|
||||
const imgTag = `<img src="${url}" alt="" />`;
|
||||
|
||||
if (!textarea) {
|
||||
const next = current + imgTag;
|
||||
latestHtmlRef.current = next;
|
||||
scheduleChange(next);
|
||||
return next;
|
||||
}
|
||||
|
||||
const { selectionStart, selectionEnd } = textarea;
|
||||
const before = current.slice(0, selectionStart);
|
||||
const after = current.slice(selectionEnd);
|
||||
const next = before + imgTag + after;
|
||||
|
||||
latestHtmlRef.current = next;
|
||||
scheduleChange(next);
|
||||
|
||||
// 커서 위치를 이미지 태그 뒤로 이동
|
||||
window.requestAnimationFrame(() => {
|
||||
const pos = before.length + imgTag.length;
|
||||
textarea.focus();
|
||||
textarea.setSelectionRange(pos, pos);
|
||||
});
|
||||
|
||||
return next;
|
||||
});
|
||||
} catch (err) {
|
||||
toast.error("이미지 업로드에 실패했습니다.");
|
||||
console.error(err);
|
||||
}
|
||||
|
||||
const { selectionStart, selectionEnd } = textarea;
|
||||
const before = current.slice(0, selectionStart);
|
||||
const after = current.slice(selectionEnd);
|
||||
const next = before + imgTag + after;
|
||||
|
||||
latestHtmlRef.current = next;
|
||||
flushChange(next);
|
||||
|
||||
// 커서 위치를 이미지 태그 뒤로 이동
|
||||
window.requestAnimationFrame(() => {
|
||||
const pos = before.length + imgTag.length;
|
||||
textarea.focus();
|
||||
textarea.setSelectionRange(pos, pos);
|
||||
});
|
||||
|
||||
return next;
|
||||
});
|
||||
} catch (error) {
|
||||
onImageUploadError?.(error);
|
||||
} finally {
|
||||
if (fileInputRef.current) {
|
||||
fileInputRef.current.value = "";
|
||||
}
|
||||
}
|
||||
};
|
||||
},
|
||||
[
|
||||
scheduleChange,
|
||||
setHtml,
|
||||
canImageUpload,
|
||||
onImageUpload,
|
||||
maxImageBytes,
|
||||
imageMaxWidth,
|
||||
imageMaxHeight,
|
||||
imageMimeType,
|
||||
imageQuality,
|
||||
]
|
||||
);
|
||||
|
||||
const sanitizedHtml = React.useMemo(
|
||||
() => sanitizeHtmlForPreview(html || ""),
|
||||
@@ -124,7 +170,7 @@ export function KriEditorHtmlOnly(props: HtmlOnlyProps) {
|
||||
{onImageUpload && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={handleClickImageButton}
|
||||
onClick={handlePickImage}
|
||||
className="rounded border px-2 py-1 text-xs hover:bg-gray-50"
|
||||
>
|
||||
이미지 업로드
|
||||
@@ -143,18 +189,17 @@ export function KriEditorHtmlOnly(props: HtmlOnlyProps) {
|
||||
/>
|
||||
|
||||
<input
|
||||
ref={fileInputRef}
|
||||
ref={fileRef}
|
||||
type="file"
|
||||
accept="image/*"
|
||||
className="hidden"
|
||||
onChange={handleFileChange}
|
||||
onChange={handleFile}
|
||||
/>
|
||||
</div>
|
||||
{showPreview ?? (
|
||||
{showPreview && (
|
||||
<div className={cn("border-t p-3", previewClassName)}>
|
||||
<div className="mb-2 text-sm font-semibold">미리보기</div>
|
||||
<div className="rounded-md border bg-gray-50 p-3 text-sm leading-relaxed">
|
||||
{/* eslint-disable-next-line react/no-danger */}
|
||||
<div dangerouslySetInnerHTML={{ __html: sanitizedHtml }} />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -79,6 +79,7 @@ export function KriEditorWysiwyg(props: KriEditorProps) {
|
||||
debounceMs = 350,
|
||||
|
||||
onImageUpload,
|
||||
onImageUploadError,
|
||||
maxImageBytes = 5 * 1024 * 1024,
|
||||
imageMaxWidth = 1600,
|
||||
imageMaxHeight = 1600,
|
||||
@@ -93,6 +94,11 @@ export function KriEditorWysiwyg(props: KriEditorProps) {
|
||||
const isLmsMode = mode === "lms";
|
||||
const showHtmlToggle = mode === "both";
|
||||
|
||||
const LINK_HTML_ATTRS = {
|
||||
rel: "noopener noreferrer",
|
||||
target: "_blank",
|
||||
} as const;
|
||||
|
||||
const { scheduleChange, flushChange, optimisticHtmlRef } = useDebouncedChange(onChange, debounceMs);
|
||||
|
||||
const fileRef = useRef<HTMLInputElement | null>(null);
|
||||
@@ -156,13 +162,12 @@ export function KriEditorWysiwyg(props: KriEditorProps) {
|
||||
Div,
|
||||
|
||||
Link.configure({
|
||||
openOnClick: false,
|
||||
autolink: true,
|
||||
openOnClick: false,
|
||||
linkOnPaste: true,
|
||||
HTMLAttributes: {
|
||||
class: "text-blue-600 underline underline-offset-2",
|
||||
rel: "noopener noreferrer nofollow",
|
||||
target: "_blank",
|
||||
class: "cursor-pointer text-blue-600 underline underline-offset-2",
|
||||
...LINK_HTML_ATTRS,
|
||||
},
|
||||
}),
|
||||
|
||||
@@ -174,6 +179,7 @@ export function KriEditorWysiwyg(props: KriEditorProps) {
|
||||
TableCell,
|
||||
|
||||
TiptapImage.configure({
|
||||
inline: true,
|
||||
allowBase64,
|
||||
HTMLAttributes: {
|
||||
class: "max-w-full h-auto",
|
||||
@@ -206,6 +212,52 @@ export function KriEditorWysiwyg(props: KriEditorProps) {
|
||||
"[&_td]:border [&_td]:p-2 [&_td]:align-top [&_td]:min-w-[90px]"
|
||||
),
|
||||
},
|
||||
handleDOMEvents: {
|
||||
click: (view, event) => {
|
||||
const e = event as MouseEvent;
|
||||
|
||||
// Alt + 좌클릭만
|
||||
if (!e.altKey || e.button !== 0) return false;
|
||||
|
||||
// 이미지(또는 리사이즈 컨테이너) 클릭일 때만
|
||||
const target = e.target as HTMLElement | null;
|
||||
const isImageClick = !!target?.closest?.("img, [data-resize-container]");
|
||||
if (!isImageClick) return false;
|
||||
|
||||
// 1) 문서 상태에서 link mark의 href 찾기 (NodeView/리사이즈 DOM에서도 안전)
|
||||
const pos = view.posAtCoords({ left: e.clientX, top: e.clientY });
|
||||
const linkType = view.state.schema.marks.link;
|
||||
|
||||
let href: string | undefined;
|
||||
|
||||
if (pos && linkType) {
|
||||
const $pos = view.state.doc.resolve(pos.pos);
|
||||
|
||||
const pickHref = (marks: readonly any[] | null | undefined) =>
|
||||
marks?.find(m => m.type === linkType)?.attrs?.href as string | undefined;
|
||||
|
||||
href =
|
||||
pickHref($pos.marks()) ||
|
||||
pickHref($pos.nodeAfter?.marks) ||
|
||||
pickHref($pos.nodeBefore?.marks);
|
||||
}
|
||||
|
||||
// 2) DOM fallback (실제 <a>가 있는 경우)
|
||||
if (!href) {
|
||||
const a = target?.closest?.("a") as HTMLAnchorElement | null;
|
||||
if (a?.href) href = a.href;
|
||||
}
|
||||
|
||||
if (!href) return false;
|
||||
|
||||
// 링크 열기 + 에디터 클릭 처리(커서 이동 등) 막기
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
console.log(LINK_HTML_ATTRS.rel.replaceAll(" ",","))
|
||||
window.open(href, LINK_HTML_ATTRS.target, LINK_HTML_ATTRS.rel.replaceAll(" ",","));
|
||||
return true;
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
@@ -318,12 +370,14 @@ const normalizeLinkUrl = (raw: string): string => {
|
||||
if (!editor) return;
|
||||
restoreSelection();
|
||||
|
||||
const prev = (editor.getAttributes("link").href as string | undefined) ?? "";
|
||||
if (editor.isActive("link")) {
|
||||
editor.chain().focus().unsetLink().run();
|
||||
return;
|
||||
if(confirm(`링크를 해제 하시겠습니까?\r\nLink: ${prev}`)){
|
||||
editor.chain().focus().unsetLink().run();
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
const prev = (editor.getAttributes("link").href as string | undefined) ?? "";
|
||||
const url = window.prompt("링크 URL을 입력하세요", prev);
|
||||
if (url === null) return;
|
||||
|
||||
@@ -412,8 +466,12 @@ const normalizeLinkUrl = (raw: string): string => {
|
||||
restoreSelection();
|
||||
editor.chain().focus().setImage({ src: url }).run();
|
||||
} catch (err) {
|
||||
toast.error("이미지 업로드에 실패했습니다.");
|
||||
console.error(err);
|
||||
if(onImageUploadError){
|
||||
onImageUploadError(err);
|
||||
}else{
|
||||
toast.error("이미지 업로드에 실패했습니다.");
|
||||
console.error(err);
|
||||
}
|
||||
}
|
||||
},
|
||||
[
|
||||
|
||||
Reference in New Issue
Block a user