260714_01_ENH: 테스트 서버에서 기동 후 중간 테스트를 위한 커밋
This commit is contained in:
@@ -1,244 +1,158 @@
|
||||
"use client";
|
||||
'use client'
|
||||
|
||||
import * as React from "react";
|
||||
import { toast } from "sonner";
|
||||
import { cn } from "@kri/common/ui";
|
||||
import * as React from 'react'
|
||||
import { toast } from 'sonner'
|
||||
import { cn } from '@/lib/utils'
|
||||
import type { KriEditorProps } from './types'
|
||||
import { resolveUploadUrl } from './types'
|
||||
import { compressImage } from './utils/imageCompression'
|
||||
import { useDebouncedChange } from './hooks/useDebouncedChange'
|
||||
import { sanitizeHtmlForPreview } from './utils/sanitizeHtml'
|
||||
import { useTextareaInsert } from './hooks/useTextareaInsert'
|
||||
|
||||
import type { KriEditorProps } from "./types";
|
||||
import { compressImage } from "./utils/imageCompression";
|
||||
import { useDebouncedChange } from "./hooks/useDebouncedChange";
|
||||
import { sanitizeHtmlForPreview } from "./utils/sanitizeHtml";
|
||||
import {useCallback} from "react";
|
||||
import { useTextareaInsert } from "./hooks/useTextareaInsert";
|
||||
type HtmlOnlyProps = Omit<KriEditorProps, 'mode'> & { mode: 'html' }
|
||||
|
||||
type HtmlOnlyProps = Omit<KriEditorProps, "mode"> & {
|
||||
mode: "html";
|
||||
};
|
||||
export function KriEditorHtmlOnly({
|
||||
label,
|
||||
value,
|
||||
onChange,
|
||||
placeholder = 'HTML을 입력하세요...',
|
||||
className,
|
||||
showPreview,
|
||||
previewClassName,
|
||||
rows = 14,
|
||||
debounceMs = 350,
|
||||
onImageUpload,
|
||||
onImageUploadError,
|
||||
maxImageBytes = 5 * 1024 * 1024,
|
||||
imageMaxWidth = 1600,
|
||||
imageMaxHeight = 1600,
|
||||
imageQuality = 0.82,
|
||||
imageMimeType = 'image/webp',
|
||||
onEditorReady,
|
||||
onCommandReady,
|
||||
}: HtmlOnlyProps) {
|
||||
const [html, setHtml] = React.useState(value || '')
|
||||
const textareaRef = React.useRef<HTMLTextAreaElement | null>(null)
|
||||
const fileRef = React.useRef<HTMLInputElement | null>(null)
|
||||
const latestHtmlRef = React.useRef(html)
|
||||
const { scheduleChange, flushChange } = useDebouncedChange(onChange, debounceMs)
|
||||
const textareaInsert = useTextareaInsert(textareaRef)
|
||||
|
||||
export function KriEditorHtmlOnly(props: HtmlOnlyProps) {
|
||||
const {
|
||||
label,
|
||||
value,
|
||||
onChange,
|
||||
placeholder = "HTML을 입력하세요...",
|
||||
className,
|
||||
showPreview,
|
||||
previewClassName,
|
||||
rows = 14,
|
||||
debounceMs = 350,
|
||||
const commitHtml = React.useCallback((next: string, immediate = false) => {
|
||||
setHtml(next)
|
||||
latestHtmlRef.current = next
|
||||
if (immediate) flushChange(next)
|
||||
else scheduleChange(next)
|
||||
}, [flushChange, scheduleChange])
|
||||
|
||||
onImageUpload,
|
||||
onImageUploadError,
|
||||
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 fileRef = React.useRef<HTMLInputElement | null>(null);
|
||||
const latestHtmlRef = React.useRef(html);
|
||||
|
||||
const canImageUpload = Boolean(onImageUpload);
|
||||
|
||||
const { scheduleChange, flushChange } = useDebouncedChange(onChange, debounceMs);
|
||||
const ti = useTextareaInsert(textareaRef);
|
||||
|
||||
const handleTextChange = (e: React.ChangeEvent<HTMLTextAreaElement>) => {
|
||||
const next = e.target.value;
|
||||
setHtml(next);
|
||||
latestHtmlRef.current = next;
|
||||
scheduleChange(next);
|
||||
};
|
||||
|
||||
const handleBlur = () => {
|
||||
flushChange(latestHtmlRef.current);
|
||||
};
|
||||
|
||||
const handlePickImage = useCallback(() => {
|
||||
if (!canImageUpload) return;
|
||||
fileRef.current?.click();
|
||||
}, [canImageUpload]);
|
||||
|
||||
const handleFile = useCallback(
|
||||
async (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
try {
|
||||
const file = e.target.files?.[0];
|
||||
e.target.value = "";
|
||||
if (!file) return;
|
||||
|
||||
if (!canImageUpload || !onImageUpload) return;
|
||||
|
||||
if (!file.type.startsWith("image/")) {
|
||||
toast.error("이미지 파일만 업로드할 수 있습니다.");
|
||||
return;
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
},
|
||||
[
|
||||
scheduleChange,
|
||||
setHtml,
|
||||
canImageUpload,
|
||||
onImageUpload,
|
||||
maxImageBytes,
|
||||
imageMaxWidth,
|
||||
imageMaxHeight,
|
||||
imageMimeType,
|
||||
imageQuality,
|
||||
]
|
||||
);
|
||||
|
||||
const sanitizedHtml = React.useMemo(
|
||||
() => sanitizeHtmlForPreview(html || ""),
|
||||
[html],
|
||||
);
|
||||
|
||||
// 외부 value 변경 시 동기화
|
||||
React.useEffect(() => {
|
||||
if ((value || "") !== latestHtmlRef.current) {
|
||||
setHtml(value || "");
|
||||
latestHtmlRef.current = value || "";
|
||||
if ((value || '') !== latestHtmlRef.current) {
|
||||
setHtml(value || '')
|
||||
latestHtmlRef.current = value || ''
|
||||
}
|
||||
}, [value]);
|
||||
}, [value])
|
||||
|
||||
React.useEffect(() => {
|
||||
if (textareaRef.current && props.onEditorReady) {
|
||||
props.onEditorReady(textareaRef.current);
|
||||
}
|
||||
},[props.onEditorReady])
|
||||
onEditorReady?.(textareaRef.current)
|
||||
}, [onEditorReady])
|
||||
|
||||
React.useEffect(() => {
|
||||
if (!props.onCommandReady) return;
|
||||
|
||||
props.onCommandReady({
|
||||
if (!onCommandReady) return
|
||||
onCommandReady({
|
||||
focus: () => textareaRef.current?.focus(),
|
||||
insertText: (placeholder: string) => {
|
||||
const current = latestHtmlRef.current ?? "";
|
||||
|
||||
ti.insertText(
|
||||
placeholder,
|
||||
current,
|
||||
(next) => {
|
||||
setHtml(next);
|
||||
latestHtmlRef.current = next;
|
||||
},
|
||||
(next) => {
|
||||
// html 모드도 debounce 쓰면 flush 권장
|
||||
flushChange(next);
|
||||
},
|
||||
);
|
||||
insertText: (text) => {
|
||||
textareaInsert.insertText(
|
||||
text,
|
||||
latestHtmlRef.current,
|
||||
(next) => commitHtml(next),
|
||||
(next) => commitHtml(next, true),
|
||||
)
|
||||
},
|
||||
});
|
||||
})
|
||||
return () => onCommandReady(null)
|
||||
}, [commitHtml, onCommandReady, textareaInsert])
|
||||
|
||||
return () => props.onCommandReady?.(null);
|
||||
}, [props.onCommandReady, ti, flushChange]);
|
||||
const handleFile = async (event: React.ChangeEvent<HTMLInputElement>) => {
|
||||
try {
|
||||
const file = event.target.files?.[0]
|
||||
event.target.value = ''
|
||||
if (!file || !onImageUpload) return
|
||||
if (!file.type.startsWith('image/')) {
|
||||
toast.error('이미지 파일만 업로드할 수 있습니다.')
|
||||
return
|
||||
}
|
||||
|
||||
const compressed = await compressImage(file, {
|
||||
maxBytes: maxImageBytes,
|
||||
maxWidth: imageMaxWidth,
|
||||
maxHeight: imageMaxHeight,
|
||||
mimeType: imageMimeType,
|
||||
quality: imageQuality,
|
||||
})
|
||||
|
||||
if (compressed.size > maxImageBytes) {
|
||||
toast.error('이미지 용량이 제한을 초과합니다.')
|
||||
return
|
||||
}
|
||||
|
||||
const url = resolveUploadUrl(await onImageUpload(compressed))
|
||||
if (!url) {
|
||||
toast.error('이미지 업로드 응답이 올바르지 않습니다.')
|
||||
return
|
||||
}
|
||||
|
||||
const current = latestHtmlRef.current
|
||||
const textarea = textareaRef.current
|
||||
const imageTag = `<img src="${url}" alt="" />`
|
||||
const start = textarea?.selectionStart ?? current.length
|
||||
const end = textarea?.selectionEnd ?? current.length
|
||||
const next = `${current.slice(0, start)}${imageTag}${current.slice(end)}`
|
||||
commitHtml(next)
|
||||
|
||||
requestAnimationFrame(() => {
|
||||
const position = start + imageTag.length
|
||||
textarea?.focus()
|
||||
textarea?.setSelectionRange(position, position)
|
||||
})
|
||||
} catch (error) {
|
||||
if (onImageUploadError) onImageUploadError(error)
|
||||
else toast.error('이미지 업로드에 실패했습니다.')
|
||||
}
|
||||
}
|
||||
|
||||
const previewHtml = React.useMemo(() => sanitizeHtmlForPreview(html), [html])
|
||||
|
||||
return (
|
||||
<div className={cn("rounded-md border bg-white", className)}>
|
||||
{label && (
|
||||
<div className="border-b px-3 py-2 text-sm font-semibold">
|
||||
{label}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className={cn('rounded-md border bg-background', className)}>
|
||||
{label ? <div className="border-b px-3 py-2 text-sm font-semibold">{label}</div> : null}
|
||||
<div className="flex flex-col gap-2 px-3 py-2">
|
||||
<div className="flex items-center justify-between text-xs text-gray-500">
|
||||
<div className="text-muted-foreground flex items-center justify-between text-xs">
|
||||
<span>HTML 모드</span>
|
||||
{onImageUpload && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={handlePickImage}
|
||||
className="rounded border px-2 py-1 text-xs hover:bg-gray-50"
|
||||
>
|
||||
{onImageUpload ? (
|
||||
<button type="button" onClick={() => fileRef.current?.click()} className="rounded border px-2 py-1 hover:bg-muted">
|
||||
이미지 업로드
|
||||
</button>
|
||||
)}
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
<textarea
|
||||
ref={textareaRef}
|
||||
className="min-h-[200px] w-full resize-y border bg-white p-2 text-sm font-mono outline-none"
|
||||
className="min-h-[200px] w-full resize-y rounded-md border bg-background p-2 font-mono text-sm outline-none"
|
||||
value={html}
|
||||
onChange={handleTextChange}
|
||||
onBlur={handleBlur}
|
||||
onChange={(event) => commitHtml(event.target.value)}
|
||||
onBlur={() => flushChange(latestHtmlRef.current)}
|
||||
placeholder={placeholder}
|
||||
rows={rows}
|
||||
{...ti.bindSelectionHandlers}
|
||||
/>
|
||||
|
||||
<input
|
||||
ref={fileRef}
|
||||
type="file"
|
||||
accept="image/*"
|
||||
className="hidden"
|
||||
onChange={handleFile}
|
||||
{...textareaInsert.bindSelectionHandlers}
|
||||
/>
|
||||
<input ref={fileRef} type="file" accept="image/*" className="hidden" onChange={handleFile} />
|
||||
</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-gray-50 p-3 text-sm leading-relaxed">
|
||||
<div dangerouslySetInnerHTML={{ __html: sanitizedHtml }} />
|
||||
</div>
|
||||
</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 text-sm leading-relaxed" dangerouslySetInnerHTML={{ __html: previewHtml }} />
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user