260810_03_ENH: 이메일 템플릿 수정에 폰트 추가

This commit is contained in:
2026-08-10 11:54:41 +09:00
parent aad991b16b
commit ef748142f8
10 changed files with 149 additions and 14 deletions

View File

@@ -122,7 +122,10 @@ export function KriEditorHtmlOnly({
}
}
const previewHtml = React.useMemo(() => sanitizeHtmlForPreview(preserveEmptyParagraphs(html)), [html])
const previewHtml = React.useMemo(
() => sanitizeHtmlForPreview(preserveEmptyParagraphs(html)),
[html],
)
return (
<div className={cn('rounded-md border bg-background', className)}>

View File

@@ -5,6 +5,7 @@ import { EditorContent, useEditor, type Editor } from "@tiptap/react";
import StarterKit from "@tiptap/starter-kit";
import Underline from "@tiptap/extension-underline";
import { TextStyle } from "@tiptap/extension-text-style";
import FontFamily from "@tiptap/extension-font-family";
import Color from "@tiptap/extension-color";
import Highlight from "@tiptap/extension-highlight";
import TiptapImage from "@tiptap/extension-image";
@@ -27,6 +28,7 @@ import { Div } from "./extensions/div";
import { compressImage } from "./utils/imageCompression";
import { sanitizeHtml } from "./utils/sanitizeHtml";
import { preserveEmptyParagraphs } from "./utils/emptyParagraph";
import { DEFAULT_FONT_FAMILY_OPTIONS } from "./utils/fontFamilyOptions";
import { applyLinkPreviewClass, KRI_EDITOR_LINK_CLASS } from "./utils/linkPreview";
import { Toolbar } from "./toolbar/Toolbar";
import { useDebouncedChange } from "./hooks/useDebouncedChange";
@@ -35,9 +37,10 @@ import { useTextareaInsert } from "./hooks/useTextareaInsert";
type ViewMode = "wysiwyg" | "html";
function getToolbarState(editor: Editor): ToolbarState {
const ts = editor.getAttributes("textStyle") as { fontSize?: string | null; color?: string | null };
const ts = editor.getAttributes("textStyle") as { fontSize?: string | null; fontFamily?: string | null; color?: string | null };
const hl = editor.getAttributes("highlight") as { color?: string | null };
const fontFamily = (ts?.fontFamily ?? null) as string | null;
const fontSize = (ts?.fontSize ?? "16px") as string;
const textColor = (ts?.color ?? null) as string | null;
const highlightColor = (hl?.color ?? null) as string | null;
@@ -48,6 +51,7 @@ function getToolbarState(editor: Editor): ToolbarState {
"left";
return {
fontFamily,
fontSize,
textColor,
highlightColor,
@@ -89,6 +93,7 @@ export function KriEditorWysiwyg(props: KriEditorProps) {
allowBase64 = false,
sanitizeHtml: sanitizeHtmlOpt = true,
toolbar = {},
fontFamilyOptions = DEFAULT_FONT_FAMILY_OPTIONS,
editorExtensions = [],
allowedCustomHtml,
transformPreviewHtml,
@@ -122,6 +127,7 @@ export function KriEditorWysiwyg(props: KriEditorProps) {
const selectionRef = useRef<{ from: number; to: number } | null>(null);
const [tb, setTb] = useState<ToolbarState>({
fontFamily: null,
fontSize: "16px",
textColor: null,
highlightColor: null,
@@ -150,6 +156,7 @@ export function KriEditorWysiwyg(props: KriEditorProps) {
Underline,
TextStyle,
FontSize,
FontFamily,
Color,
Highlight.configure({ multicolor: true }),
Div,
@@ -276,6 +283,19 @@ export function KriEditorWysiwyg(props: KriEditorProps) {
[editor, restoreSelection]
);
const setFontFamily = useCallback(
(value: string) => {
if (!editor) return;
restoreSelection();
if (!value) {
editor.chain().focus().unsetFontFamily().run();
return;
}
editor.chain().focus().setFontFamily(value).run();
},
[editor, restoreSelection]
);
const setTextColor = useCallback(
(hex: string) => {
if (!editor) return;
@@ -595,6 +615,8 @@ export function KriEditorWysiwyg(props: KriEditorProps) {
showHtmlToggle={showHtmlToggle}
isHtmlView={view === "html"}
onToggleHtmlView={onToggleHtmlView}
fontFamilyOptions={fontFamilyOptions}
onSetFontFamily={setFontFamily}
onSetFontSize={setFontSize}
onSetTextColor={setTextColor}
onUnsetTextColor={unsetTextColor}

View File

@@ -3,9 +3,11 @@ export { KriEditorHtmlOnly } from './KriEditorHtmlOnly'
export { KriEditorSms } from './KriEditorSms'
export { KriEditorWysiwyg } from './KriEditorWysiwyg'
export { ToolbarButton as KriEditorToolbarButton } from './toolbar/ToolbarButton'
export { DEFAULT_FONT_FAMILY_OPTIONS } from './utils/fontFamilyOptions'
export type {
KriEditorAllowedHtml,
KriEditorCommand,
KriEditorFontFamilyOption,
KriEditorMode,
KriEditorProps,
KriEditorToolbarConfig,

View File

@@ -25,7 +25,7 @@ import { Input } from '@/components/ui/input'
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover'
import { Separator } from '@/components/ui/separator'
import { cn } from '@/lib/utils'
import type { KriEditorToolbarConfig, KriEditorToolbarFeature, ToolbarState } from '../types'
import type { KriEditorFontFamilyOption, KriEditorToolbarConfig, KriEditorToolbarFeature, ToolbarState } from '../types'
import { ToolbarButton } from './ToolbarButton'
interface ToolbarProps {
@@ -38,6 +38,8 @@ interface ToolbarProps {
showHtmlToggle: boolean
isHtmlView: boolean
onToggleHtmlView: () => void
fontFamilyOptions: KriEditorFontFamilyOption[]
onSetFontFamily: (value: string) => void
onSetFontSize: (value: string) => void
onSetTextColor: (value: string) => void
onUnsetTextColor: () => void
@@ -74,6 +76,8 @@ export function Toolbar({
showHtmlToggle,
isHtmlView,
onToggleHtmlView,
fontFamilyOptions,
onSetFontFamily,
onSetFontSize,
onSetTextColor,
onUnsetTextColor,
@@ -89,6 +93,7 @@ export function Toolbar({
customContent,
}: ToolbarProps) {
const enabled = (feature: KriEditorToolbarFeature) => config?.[feature] !== false
const showFontControls = enabled('fontFamily') || enabled('fontSize')
const showTextStyle = enabled('bold') || enabled('italic') || enabled('underline') || enabled('strike')
const showColors = enabled('textColor') || enabled('highlight')
const showLists = enabled('bulletList') || enabled('orderedList')
@@ -108,6 +113,19 @@ export function Toolbar({
return (
<div className={cn('flex items-center gap-1 overflow-x-auto whitespace-nowrap px-2 py-1', className)}>
{enabled('fontFamily') ? (
<select
className="h-8 w-[132px] rounded-md border bg-background px-2 text-sm"
value={state.fontFamily ?? ''}
onChange={(event) => onSetFontFamily(event.target.value)}
title="글꼴"
>
{fontFamilyOptions.map((option) => (
<option key={option.value} value={option.value}>{option.label}</option>
))}
</select>
) : null}
{enabled('fontSize') ? (
<select
className="h-8 w-[72px] rounded-md border bg-background px-2 text-sm"
@@ -121,7 +139,7 @@ export function Toolbar({
</select>
) : null}
{enabled('fontSize') && showTextStyle ? <Separator orientation="vertical" className="mx-1 h-6" /> : null}
{showFontControls && showTextStyle ? <Separator orientation="vertical" className="mx-1 h-6" /> : null}
{enabled('bold') ? (
<ToolbarButton active={state.isBold} disabled={!editor.can().chain().focus().toggleBold().run()} onClick={() => editor.chain().focus().toggleBold().run()} title="굵게">

View File

@@ -6,6 +6,7 @@ export type KriEditorMode = 'wysiwyg' | 'both' | 'html' | 'sms'
export type KriEditorUploadResult = string | { url: string }
export type KriEditorToolbarFeature =
| 'fontFamily'
| 'fontSize'
| 'bold'
| 'italic'
@@ -39,6 +40,11 @@ export type KriEditorAllowedHtml = {
attributes?: string[]
}
export type KriEditorFontFamilyOption = {
label: string
value: string
}
export type KriEditorProps = {
onEditorReady?: (editor: Editor | HTMLTextAreaElement | null) => void
onCommandReady?: (command: KriEditorCommand | null) => void
@@ -69,14 +75,15 @@ export type KriEditorProps = {
smsMaxBytes?: number
lmsMaxBytes?: number
toolbar?: KriEditorToolbarConfig | false
fontFamilyOptions?: KriEditorFontFamilyOption[]
renderToolbarEnd?: (context: KriEditorToolbarContext) => ReactNode
editorExtensions?: Extensions
allowedCustomHtml?: KriEditorAllowedHtml
/** 미리보기 패널에 표시할 HTML을 sanitize 이후 추가로 가공하고 싶을 때 사용 (예: 커스텀 태그를 대체 이미지로 치환) */
transformPreviewHtml?: (html: string) => string
}
export type ToolbarState = {
fontFamily: string | null
fontSize: string
textColor: string | null
highlightColor: string | null

View File

@@ -1,8 +1,8 @@
const EMPTY_PARAGRAPH_PATTERN = /<p((?:\s+[^>]*)?)>\s*<\/p>/gi;
/**
* 내용이 전혀 없는 <p></p>는 CSS margin이 collapse되어 이메일 클라이언트 등
* 우리 앱 밖에서는 높이 0으로 붙어버린다. &nbsp;를 채워 실제 콘텐츠로 줄 높이를 보장한다.
* TipTap이 빈 줄을 <p></p>로 직렬화하면 이메일 클라이언트에서 margin collapse로 사라진다.
* 눈에 보이지 않는 콘텐츠(&nbsp;)를 채워 실제 발송 HTML에서도 빈 줄이 유지되게 한다.
*/
export function preserveEmptyParagraphs(html: string): string {
return html.replace(EMPTY_PARAGRAPH_PATTERN, (_match, attrs: string) => `<p${attrs}>&nbsp;</p>`);

View File

@@ -0,0 +1,29 @@
import type { KriEditorFontFamilyOption } from "../types";
/**
* OS/이메일 클라이언트에 기본 설치돼 있어 별도 @font-face 로딩 없이 바로 렌더링되는 웹 세이프 폰트 목록.
* "기본값"은 fontFamily 속성을 제거(unset)해 상위 스타일을 상속한다.
*/
export const DEFAULT_FONT_FAMILY_OPTIONS: KriEditorFontFamilyOption[] = [
{ label: "없음", value: "" },
{ label: "맑은 고딕", value: "'Malgun Gothic', sans-serif" },
{ label: "돋움", value: "Dotum, sans-serif" },
{ label: "굴림", value: "Gulim, sans-serif" },
{ label: "바탕", value: "Batang, serif" },
{ label: "궁서", value: "Gungsuh, serif" },
{ label: "Apple SD 고딕", value: "'Apple SD Gothic Neo', sans-serif" },
{ label: "Arial", value: "Arial, Helvetica, sans-serif" },
{ label: "Helvetica", value: "Helvetica, Arial, sans-serif" },
{ label: "Verdana", value: "Verdana, Geneva, sans-serif" },
{ label: "Tahoma", value: "Tahoma, Geneva, sans-serif" },
{ label: "Trebuchet MS", value: "'Trebuchet MS', Helvetica, sans-serif" },
{ label: "Century Gothic", value: "'Century Gothic', sans-serif" },
{ label: "Georgia", value: "Georgia, 'Times New Roman', serif" },
{ label: "Times New Roman", value: "'Times New Roman', Times, serif" },
{ label: "Palatino Linotype", value: "'Palatino Linotype', 'Book Antiqua', Palatino, serif" },
{ label: "Garamond", value: "Garamond, serif" },
{ label: "Courier New", value: "'Courier New', Courier, monospace" },
{ label: "Lucida Console", value: "'Lucida Console', Monaco, monospace" },
{ label: "Comic Sans MS", value: "'Comic Sans MS', cursive" },
{ label: "Impact", value: "Impact, Charcoal, sans-serif" },
];

View File

@@ -1,12 +1,21 @@
"use client";
import DOMPurify from "dompurify";
import DOMPurify, { type DOMPurify as DOMPurifyInstance } from "dompurify";
export type SanitizeHtmlOptions = {
tags?: string[];
attributes?: string[];
};
// Next.js SSR(Node) 환경에서는 dompurify가 window에 바인딩된 인스턴스가 아니라
// (window: Window) => DOMPurify 형태의 factory만 노출한다. window가 없으면
// factory를 호출할 방법이 없으므로, 여기서 안전하게 null로 폴백한다.
function resolvePurifier(): DOMPurifyInstance | null {
if (typeof window === "undefined") return null;
if (typeof DOMPurify.sanitize === "function") return DOMPurify;
return DOMPurify(window);
}
export function sanitizeHtml(
input: string,
options?: SanitizeHtmlOptions,
@@ -15,14 +24,16 @@ export function sanitizeHtml(
return "";
}
// DOMPurify는 window/document가 있어야 동작한다. Next.js는 "use client" 컴포넌트도
// 최초 HTML을 만들 때 서버에서 한 번 실행하므로, SSR 단계에서는 sanitize를 건너뛴다.
// (이 값은 하이드레이션 후 클라이언트에서 다시 렌더링되며 정상적으로 sanitize된다.)
if (typeof window === "undefined") {
return input;
const purifier = resolvePurifier();
if (!purifier) {
// DOM이 없어 실제 sanitize를 수행할 수 없는 환경(SSR 등)에서는
// 검증되지 않은 HTML을 그대로 노출하지 않도록 태그를 모두 제거한 텍스트만 반환한다.
// 브라우저에서 하이드레이션된 이후 재계산될 때 실제 sanitize 결과로 대체된다.
return input.replace(/<[^>]*>/g, "");
}
return DOMPurify.sanitize(
return purifier.sanitize(
input,
{
USE_PROFILES: {