260803_01_ENH: 에디터에 QR 코드 삽입 추가 #17

Merged
gitadmin merged 1 commits from develop into master 2026-08-03 15:16:19 +09:00
18 changed files with 665 additions and 38 deletions

View File

@@ -5,6 +5,7 @@ ENV=local
CONTACT_SERVER=http://localhost:4001
API_CONTACT_SERVER=http://localhost:4001/api/v1
API_NOTIHUB_SERVER=https://noti-hub.kric.com/api/v1
#API_NOTIHUB_SERVER=http://localhost:4011/api/v1
API_INTRANET_SERVER=https://intranet-ext.kric.com/api/v1
API_KART_SERVER=https://rapi.kric.com/api/v1
KART_API_KEY=4B726963-436F6E74616374-46726F6E74-402531213230

BIN
public/qr_example.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 851 KiB

View File

@@ -304,7 +304,11 @@ const ListManagePage = () => {
{isInternal && (
<>
<ListResetDialog filterSummary={filterSummary} onConfirm={handleResetConfirm} />
<ListResetDialog
selectedSids={selectedSidSet}
filterSummary={filterSummary}
onConfirm={handleResetConfirm}
/>
<ListUploadDialog
onUpload={handleUploadConfirm}
onDownloadTemplate={handleDownloadTemplate}
@@ -321,7 +325,12 @@ const ListManagePage = () => {
{canManageList && (
<>
<ListDownloadDialog mode={downloadMode} filterSummary={filterSummary} onDownload={handleDownloadConfirm} />
<ListDownloadDialog
mode={downloadMode}
selectedSids={selectedSidSet}
filterSummary={filterSummary}
onDownload={handleDownloadConfirm}
/>
<MessageSendDialog
mode={messageSendMode}
listHeaders={headerManageRows}

View File

@@ -163,14 +163,25 @@
cursor: pointer;
}
/* 미리보기(.kri-editor-preview)는 실제 발송 HTML을 그대로 dangerouslySetInnerHTML로 그린다.
Tailwind preflight가 img를 display:block + vertical-align:middle로 리셋하는데,
실제 메일 클라이언트에는 이 리셋 CSS가 없어 img가 브라우저 기본값(inline, vertical-align:baseline)으로
렌더링된다. 미리보기가 실제 발송 결과와 같아 보이도록 두 속성 다 기본값으로 되돌린다. */
.kri-editor-preview img {
display: inline;
vertical-align: baseline;
}
.ProseMirror .ProseMirror-selectednode img {
outline: 5px solid #0ea5e9;
outline-offset: -5px;
}
/* 리사이즈 컨테이너 기본 배치 */
/* Tiptap ResizableNodeView가 style.display = "flex"를 인라인으로 강제 지정하므로,
inline 이미지 노드처럼 줄바꿈 없이 배치하려면 !important로 덮어써야 한다. */
.ProseMirror [data-resize-container] {
position: relative;
display: inline-block;
display: inline-block !important;
}
/* 리사이즈 핸들 공통 스타일 */
@@ -221,4 +232,4 @@
/* 리사이즈 중인 상태를 잡고 싶으면 */
.ProseMirror [data-resize-container][data-resize-state="resizing"] {
outline: 1px dashed #0ea5e9;
}
}

View File

@@ -53,6 +53,7 @@ export type ListBatchEditDialogProps = {
headerOptions: BatchEditOption[]
resultCodes: ResultCode[]
surveys: ProjectSurvey[]
selectedSids: string[]
filterSummary?: string[]
initialRows?: BatchEditRow[]
initialResultCodes?: BatchEditResultCodes
@@ -80,6 +81,7 @@ const ListBatchEditDialog = ({
headerOptions,
resultCodes,
surveys,
selectedSids,
filterSummary,
initialRows = [],
initialResultCodes = {},
@@ -169,7 +171,7 @@ const ListBatchEditDialog = ({
const handleConfirm = async () => {
setInvalidRowId(null)
if (!validateApplyFilterTarget(target, filterSummary)) return
if (!validateApplyFilterTarget(target, { selectedCount: selectedSids.length, filterSummary })) return
const normalized = rows.filter((row) => row.headerId > 0 && row.value.trim().length > 0)
const surveyResultCodes = Object.entries(surveyResultSelections).map(([prjctSurveyIdx, resultCd]) => ({
@@ -229,7 +231,13 @@ const ListBatchEditDialog = ({
>
<div className="rounded-md border p-4 space-y-4">
<p className="text-lg font-semibold">적용 대상</p>
<ApplyFilterOption value={target} onValueChange={setTarget} idPrefix="batch-edit-target" filterSummary={filterSummary} />
<ApplyFilterOption
value={target}
onValueChange={setTarget}
idPrefix="batch-edit-target"
selectedSids={selectedSids}
filterSummary={filterSummary}
/>
</div>
<div className="rounded-md border p-4 space-y-3">

View File

@@ -7,20 +7,29 @@ import type { ListFilterTarget } from "@/types/list";
export type ApplyFilterOptionValue = ListFilterTarget
type ApplyFilterTargetValidation = {
selectedCount: number
filterSummary?: string[]
}
/**
* "필터 적용 대상만"을 선택했는데 실제로 적용된 필터가 없는 경우를 검사한다.
* 선택 항목과 필터 적용 대상의 유효성을 각각 실제 상태값으로 검사한다.
* alert 후 진행을 막아야 하는 호출부에서 공통으로 사용한다.
*/
export const validateApplyFilterTarget = (value: ApplyFilterOptionValue, filterSummary?: string[]): boolean => {
if (["selected", "filtered"].includes(value) && (filterSummary?.length ?? 0) === 0) {
const alertText: string =
value === "selected" ?
"선택된 항목이 없습니다. 항목을 선택해 주세요"
: "적용된 필터가 없습니다. 필터를 적용해 주세요."
alert(alertText)
export const validateApplyFilterTarget = (
value: ApplyFilterOptionValue,
{ selectedCount, filterSummary }: ApplyFilterTargetValidation,
): boolean => {
if (value === "selected" && selectedCount === 0) {
alert("선택된 항목이 없습니다. 항목을 선택해 주세요")
return false
}
if (value === "filtered" && (filterSummary?.length ?? 0) === 0) {
alert("적용된 필터가 없습니다. 필터를 적용해 주세요.")
return false
}
return true
}
@@ -28,11 +37,13 @@ type ApplyFilterGroupProps = {
value: ApplyFilterOptionValue
onValueChange: (value: ApplyFilterOptionValue) => void
idPrefix: string
/** 현재 선택된 리스트의 SID 목록 */
selectedSids?: string[]
/** '필터 적용 대상만' 선택 시 보여줄, 사람이 읽을 수 있는 현재 필터 조건 목록 */
filterSummary?: string[]
}
const ApplyFilterOption = ({ value, onValueChange, idPrefix, filterSummary }: ApplyFilterGroupProps) => {
const ApplyFilterOption = ({ value, onValueChange, idPrefix, selectedSids, filterSummary }: ApplyFilterGroupProps) => {
return (
<div className="space-y-3">
<RadioGroup
@@ -54,6 +65,19 @@ const ApplyFilterOption = ({ value, onValueChange, idPrefix, filterSummary }: Ap
</div>
</RadioGroup>
{value === 'selected' && selectedSids !== undefined && (
<div className="rounded-md border px-4 py-3 text-sm">
<p className="font-semibold mb-1">선택된 SID ({selectedSids.length}개)</p>
{selectedSids.length > 0 ? (
<p className="text-muted-foreground max-h-40 overflow-y-auto break-words">
{selectedSids.join(', ')}
</p>
) : (
<p className="text-muted-foreground">선택된 항목이 없습니다.</p>
)}
</div>
)}
{value === 'filtered' && filterSummary !== undefined && (
<div className="rounded-md border px-4 py-3 text-sm">
<p className="font-semibold mb-1">적용된 필터</p>

View File

@@ -17,6 +17,7 @@ export type ListDownloadDialogProps = {
open?: boolean
onOpenChange?: (open: boolean) => void
mode: ListDownloadMode
selectedSids: string[]
filterSummary?: string[]
onDownload: (payload: ListDownloadPayload) => void | Promise<void>
}
@@ -33,6 +34,7 @@ const ListDownloadDialog = ({
open,
onOpenChange,
mode,
selectedSids,
filterSummary,
onDownload,
}: ListDownloadDialogProps) => {
@@ -55,7 +57,7 @@ const ListDownloadDialog = ({
}
const handleDownload = async () => {
if (!validateApplyFilterTarget(target, filterSummary)) return
if (!validateApplyFilterTarget(target, { selectedCount: selectedSids.length, filterSummary })) return
if (mode === 'contact-history') {
const hasFrom = contactHistoryDateFrom.length > 0
@@ -120,7 +122,13 @@ const ListDownloadDialog = ({
) : null}
<div className="rounded-md border p-4 space-y-4">
<p className="text-lg font-semibold">다운로드 범위</p>
<ApplyFilterOption value={target} onValueChange={setTarget} idPrefix="download-scope-target" filterSummary={filterSummary} />
<ApplyFilterOption
value={target}
onValueChange={setTarget}
idPrefix="download-scope-target"
selectedSids={selectedSids}
filterSummary={filterSummary}
/>
</div>
{mode === 'contact-history' ? (
<div className="rounded-md border p-4 space-y-4">

View File

@@ -14,6 +14,7 @@ export type ListResetDialogProps = {
dialogId?: DialogId
open?: boolean
onOpenChange?: (open: boolean) => void
selectedSids: string[]
filterSummary?: string[]
onConfirm: (payload: { target: ListFilterTarget; scope: ListResetScope }) => void | Promise<void>
}
@@ -22,6 +23,7 @@ const ListResetDialog = ({
dialogId = 'listResetDialog',
open,
onOpenChange,
selectedSids,
filterSummary,
onConfirm,
}: ListResetDialogProps) => {
@@ -42,7 +44,7 @@ const ListResetDialog = ({
}
const handleConfirm = async () => {
if (!validateApplyFilterTarget(target, filterSummary)) return
if (!validateApplyFilterTarget(target, { selectedCount: selectedSids.length, filterSummary })) return
if (target === 'all' && !confirm('전체 리스트가 초기화 됩니다. 진행하시겠습니까?')) return
setSubmitting(true)
@@ -78,6 +80,7 @@ const ListResetDialog = ({
value={target}
onValueChange={(v) => setTarget(v)}
idPrefix="list-reset-target"
selectedSids={selectedSids}
filterSummary={filterSummary}
/>
</div>

View File

@@ -25,6 +25,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 { applyLinkPreviewClass } from '@/components/kri-editor/utils/linkPreview'
export type MessageSendMode = 'email' | 'sms'
@@ -80,6 +82,10 @@ const MessageSendDialog = ({
const selectedTemplate = templateDetailQuery.data ?? null
const mainTemplateQuery = useMainTemplateIdxQuery(prjctIdx, chnnlTy, enabled)
const mainTemplateIdx = mainTemplateQuery.data ?? null
const selectedSids = useMemo(
() => selectedRows.map((row) => String(row.sid ?? '')).filter((sid) => sid.length > 0),
[selectedRows],
)
const templateSenderName = selectedTemplate?.sendNm
const templateSenderEmail = selectedTemplate && 'sendEml' in selectedTemplate ? selectedTemplate.sendEml : undefined
@@ -151,7 +157,7 @@ const MessageSendDialog = ({
}
const handleConfirm = async () => {
if (!validateApplyFilterTarget(target, filterSummary)) return
if (!validateApplyFilterTarget(target, { selectedCount: selectedSids.length, filterSummary })) return
if (!selectedTemplate || !templateIdx) {
alert('템플릿을 선택해 주세요.')
return
@@ -301,7 +307,13 @@ const MessageSendDialog = ({
<div className="space-y-2 rounded-md border p-4">
<Label className="text-base">수신 대상</Label>
<ApplyFilterOption value={target} onValueChange={setTarget} idPrefix="message-send-target" filterSummary={filterSummary} />
<ApplyFilterOption
value={target}
onValueChange={setTarget}
idPrefix="message-send-target"
selectedSids={selectedSids}
filterSummary={filterSummary}
/>
</div>
</div>
@@ -328,8 +340,17 @@ const MessageSendDialog = ({
</div>
) : (
<div
className={cn('rounded-md border bg-muted/30 p-3')}
dangerouslySetInnerHTML={{ __html: sanitizeHtmlForPreview(selectedTemplate.tmplatBody || '(내용 없음)') }}
className={cn('kri-editor-preview rounded-md border bg-muted/30 p-3')}
dangerouslySetInnerHTML={{
__html: renderQrCodePreviewHtml(
applyLinkPreviewClass(
sanitizeHtmlForPreview(
normalizeQrCodeForEditor(selectedTemplate.tmplatBody) || '(내용 없음)',
QR_CODE_ALLOWED_HTML,
),
),
),
}}
/>
)}
</>

View File

@@ -26,6 +26,7 @@ import { FontSize } from "./extensions/font-size";
import { Div } from "./extensions/div";
import { compressImage } from "./utils/imageCompression";
import { sanitizeHtml } from "./utils/sanitizeHtml";
import { applyLinkPreviewClass, KRI_EDITOR_LINK_CLASS } from "./utils/linkPreview";
import { Toolbar } from "./toolbar/Toolbar";
import { useDebouncedChange } from "./hooks/useDebouncedChange";
import { useTextareaInsert } from "./hooks/useTextareaInsert";
@@ -87,6 +88,9 @@ export function KriEditorWysiwyg(props: KriEditorProps) {
allowBase64 = false,
sanitizeHtml: sanitizeHtmlOpt = true,
toolbar = {},
editorExtensions = [],
allowedCustomHtml,
transformPreviewHtml,
} = props;
const showHtmlToggle = mode === "both";
@@ -154,7 +158,7 @@ export function KriEditorWysiwyg(props: KriEditorProps) {
openOnClick: false,
linkOnPaste: true,
HTMLAttributes: {
class: "cursor-pointer text-blue-600 underline underline-offset-2",
class: KRI_EDITOR_LINK_CLASS,
...LINK_HTML_ATTRS,
},
}),
@@ -179,6 +183,7 @@ export function KriEditorWysiwyg(props: KriEditorProps) {
},
}),
Placeholder.configure({ placeholder }),
...editorExtensions,
],
content: value || "<p></p>",
@@ -436,12 +441,12 @@ export function KriEditorWysiwyg(props: KriEditorProps) {
}
const raw = htmlDraftRef.current;
const safe = sanitizeHtmlOpt ? sanitizeHtml(raw) : raw;
const safe = sanitizeHtmlOpt ? sanitizeHtml(raw, allowedCustomHtml) : raw;
editor.commands.setContent(safe, { emitUpdate: false, parseOptions: { preserveWhitespace: "full" } });
flushChange(editor.getHTML());
setView("wysiwyg");
}, [editor, flushChange, sanitizeHtmlOpt]);
}, [allowedCustomHtml, editor, flushChange, sanitizeHtmlOpt]);
useEffect(() => {
if (!editor) return;
@@ -558,8 +563,10 @@ export function KriEditorWysiwyg(props: KriEditorProps) {
}, [command, editor, props.onCommandReady]);
const previewHtml = useMemo(() => {
return sanitizeHtmlOpt ? sanitizeHtml(previewSource) : previewSource;
}, [previewSource, sanitizeHtmlOpt]);
const sanitized = sanitizeHtmlOpt ? sanitizeHtml(previewSource, allowedCustomHtml) : previewSource;
const withLinkStyle = applyLinkPreviewClass(sanitized);
return transformPreviewHtml ? transformPreviewHtml(withLinkStyle) : withLinkStyle;
}, [allowedCustomHtml, previewSource, sanitizeHtmlOpt, transformPreviewHtml]);
if (!editor) {
return (
@@ -630,7 +637,7 @@ export function KriEditorWysiwyg(props: KriEditorProps) {
<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 dangerouslySetInnerHTML={{ __html: previewHtml }} />
<div className="kri-editor-preview" dangerouslySetInnerHTML={{ __html: previewHtml }} />
</div>
</div>
)}

View File

@@ -4,6 +4,7 @@ export { KriEditorSms } from './KriEditorSms'
export { KriEditorWysiwyg } from './KriEditorWysiwyg'
export { ToolbarButton as KriEditorToolbarButton } from './toolbar/ToolbarButton'
export type {
KriEditorAllowedHtml,
KriEditorCommand,
KriEditorMode,
KriEditorProps,

View File

@@ -1,3 +1,4 @@
import type { Extensions } from '@tiptap/core'
import type { Editor } from '@tiptap/react'
import type { ReactNode } from 'react'
@@ -33,6 +34,11 @@ export type KriEditorToolbarContext = {
view: 'wysiwyg' | 'html'
}
export type KriEditorAllowedHtml = {
tags?: string[]
attributes?: string[]
}
export type KriEditorProps = {
onEditorReady?: (editor: Editor | HTMLTextAreaElement | null) => void
onCommandReady?: (command: KriEditorCommand | null) => void
@@ -64,6 +70,10 @@ export type KriEditorProps = {
lmsMaxBytes?: number
toolbar?: KriEditorToolbarConfig | false
renderToolbarEnd?: (context: KriEditorToolbarContext) => ReactNode
editorExtensions?: Extensions
allowedCustomHtml?: KriEditorAllowedHtml
/** 미리보기 패널에 표시할 HTML을 sanitize 이후 추가로 가공하고 싶을 때 사용 (예: 커스텀 태그를 대체 이미지로 치환) */
transformPreviewHtml?: (html: string) => string
}
export type ToolbarState = {

View File

@@ -0,0 +1,29 @@
export const KRI_EDITOR_LINK_CLASS = "cursor-pointer text-blue-600 underline underline-offset-2";
const CLASS_ATTR_PATTERN = /class\s*=\s*"([^"]*)"|class\s*=\s*'([^']*)'/i;
/**
* 미리보기(dangerouslySetInnerHTML)에 쓰이는 원본 HTML은 예전 템플릿이거나
* HTML 모드에서 직접 작성된 경우 에디터의 링크 스타일 클래스가 없을 수 있다.
* <a> 태그에 KRI_EDITOR_LINK_CLASS를 보정해 항상 동일하게 보이도록 한다.
*/
export function applyLinkPreviewClass(html: string): string {
if (!html) return html;
return html.replace(/<a\b([^>]*)>/gi, (match, attrs: string) => {
const classMatch = attrs.match(CLASS_ATTR_PATTERN);
if (!classMatch) {
return `<a${attrs} class="${KRI_EDITOR_LINK_CLASS}">`;
}
const existingClasses = (classMatch[1] ?? classMatch[2] ?? "").split(/\s+/).filter(Boolean);
const missingClasses = KRI_EDITOR_LINK_CLASS.split(" ").filter((c) => !existingClasses.includes(c));
if (missingClasses.length === 0) return match;
const mergedClass = [...existingClasses, ...missingClasses].join(" ");
const newAttrs = attrs.replace(CLASS_ATTR_PATTERN, `class="${mergedClass}"`);
return `<a${newAttrs}>`;
});
}

View File

@@ -2,27 +2,41 @@
import DOMPurify from "dompurify";
const HTML_PROFILE = {
USE_PROFILES: {
html: true,
},
} as const;
export type SanitizeHtmlOptions = {
tags?: string[];
attributes?: string[];
};
export function sanitizeHtml(
input: string,
options?: SanitizeHtmlOptions,
): string {
if (!input) {
return "";
}
// DOMPurify는 window/document가 있어야 동작한다. Next.js는 "use client" 컴포넌트도
// 최초 HTML을 만들 때 서버에서 한 번 실행하므로, SSR 단계에서는 sanitize를 건너뛴다.
// (이 값은 하이드레이션 후 클라이언트에서 다시 렌더링되며 정상적으로 sanitize된다.)
if (typeof window === "undefined") {
return input;
}
return DOMPurify.sanitize(
input,
HTML_PROFILE,
{
USE_PROFILES: {
html: true,
},
ADD_TAGS: options?.tags ?? [],
ADD_ATTR: options?.attributes ?? [],
},
);
}
export function sanitizeHtmlForPreview(
input: string,
options?: SanitizeHtmlOptions,
): string {
return sanitizeHtml(input);
return sanitizeHtml(input, options);
}

View File

@@ -185,6 +185,10 @@ export function ListSearchTable({
const [batchResultCodes, setBatchResultCodes] = useState<BatchEditResultCodes>({})
const [batchSurveyResultCodes, setBatchSurveyResultCodes] = useState<BatchEditSurveyResultCodes>({})
const [selectedRows, setSelectedRows] = useState<ListTableRow[]>([])
const selectedSids = useMemo(
() => selectedRows.map((row) => String(row.sid ?? '')).filter((sid) => sid.length > 0),
[selectedRows],
)
const updateListMutation = useUpdateListMutation(prjctIdx)
@@ -654,6 +658,7 @@ export function ListSearchTable({
headerOptions={headerOptions}
resultCodes={resultCodes}
surveys={surveys}
selectedSids={selectedSids}
filterSummary={filterSummaryLines}
initialRows={batchRows}
initialResultCodes={batchResultCodes}

View File

@@ -36,12 +36,22 @@ import {listHeader} from "@/types/list";
import {useListHeaderQuery} from "@/query/list";
import {useProjectInfoQuery} from "@/query/project";
import {MessageVariableList} from "@/components/message-template/MessageVariableList";
import {QrCodeToolbar} from "@/components/message-template/QrCodeToolbar";
import {
normalizeQrCodeForEditor,
normalizeQrCodeForStorage,
QR_CODE_ALLOWED_HTML,
QrCode,
renderQrCodePreviewHtml,
} from "@/components/message-template/qrcode";
interface MessageTemplateProps {
pageTitle: string;
defaultTemplate: Template;
}
const MESSAGE_EDITOR_EXTENSIONS = [QrCode];
const MessageTemplate = ({ pageTitle, defaultTemplate }: MessageTemplateProps) => {
const { selectedProject } = useSelectedProject();
@@ -252,9 +262,16 @@ const MessageTemplate = ({ pageTitle, defaultTemplate }: MessageTemplateProps) =
}
try {
const templateToSave = isSmsTemplate(selectedTemplate)
? selectedTemplate
: {
...selectedTemplate,
tmplatBody: normalizeQrCodeForStorage(selectedTemplate.tmplatBody),
};
const res = await saveTemplateMutation.mutateAsync({
method,
template: selectedTemplate,
template: templateToSave,
});
setSelectedTemplate(res);
@@ -418,7 +435,7 @@ const MessageTemplate = ({ pageTitle, defaultTemplate }: MessageTemplateProps) =
//mode="both"
mode="wysiwyg"
showPreview={true}
value={selectedTemplate.tmplatBody ?? "<p></p>"}
value={normalizeQrCodeForEditor(selectedTemplate.tmplatBody) || "<p></p>"}
onChange={(html: string) => setTemplateBody(html)}
placeholder="이메일 내용을 입력해 주세요"
className="w-full"
@@ -427,6 +444,13 @@ const MessageTemplate = ({ pageTitle, defaultTemplate }: MessageTemplateProps) =
editorCmdRef.current = cmd;
}}
onImageUpload={async (file) => await handleImageUpload(file)}
toolbar={{ strike: false, table: false, bulletList: false, orderedList: false }}
editorExtensions={MESSAGE_EDITOR_EXTENSIONS}
allowedCustomHtml={QR_CODE_ALLOWED_HTML}
transformPreviewHtml={renderQrCodePreviewHtml}
renderToolbarEnd={({editor}) => (
<QrCodeToolbar editor={editor} surveys={surveys} />
)}
/>
)}
</div>

View File

@@ -0,0 +1,228 @@
'use client'
import { useEffect, useId, useMemo, useState } from 'react'
import type { Editor } from '@tiptap/react'
import { QrCode as QrCodeIcon, Trash2 } from 'lucide-react'
import { KriEditorToolbarButton } from '@/components/kri-editor'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover'
import type { ProjectSurvey } from '@/types/project'
import {
DEFAULT_QR_CODE_ATTRIBUTES,
parseQrCodeInput,
QR_CODE_NODE_NAME,
toPositiveDimension,
type QrCodeAttributes,
} from './qrcode'
type QrCodeToolbarProps = {
editor: Editor
surveys: ProjectSurvey[]
}
type SurveyOption = {
id: string
label: string
value: string
}
export const QrCodeToolbar = ({ editor, surveys }: QrCodeToolbarProps) => {
const fieldId = useId()
const [open, setOpen] = useState(false)
const [editing, setEditing] = useState(false)
const [surveyId, setSurveyId] = useState('')
const [attributes, setAttributes] = useState<QrCodeAttributes>(DEFAULT_QR_CODE_ATTRIBUTES)
const surveyOptions = useMemo<SurveyOption[]>(
() =>
surveys
.map((survey, index) => {
const value =
survey.surveyUrl?.trim() ||
survey.surveyShortUrl?.trim() ||
survey.surveyFullUrl?.trim() ||
''
return {
id: String(survey.prjctSurveyIdx ?? `${survey.surveyOrder}-${index}`),
label: survey.surveyName,
value,
}
})
.filter((survey) => survey.value.length > 0),
[surveys],
)
const [isActive, setIsActive] = useState(() => editor.isActive(QR_CODE_NODE_NAME))
const canApply = attributes.src.trim().length > 0
useEffect(() => {
const syncActive = () => setIsActive(editor.isActive(QR_CODE_NODE_NAME))
syncActive()
editor.on('transaction', syncActive)
editor.on('selectionUpdate', syncActive)
return () => {
editor.off('transaction', syncActive)
editor.off('selectionUpdate', syncActive)
}
}, [editor])
useEffect(() => {
if (!open) return
const active = editor.isActive(QR_CODE_NODE_NAME)
setEditing(active)
setSurveyId('')
if (active) {
const current = editor.getAttributes(QR_CODE_NODE_NAME)
setAttributes({
src: String(current.src ?? ''),
width: String(current.width ?? DEFAULT_QR_CODE_ATTRIBUTES.width),
height: String(current.height ?? DEFAULT_QR_CODE_ATTRIBUTES.height),
alt: String(current.alt ?? DEFAULT_QR_CODE_ATTRIBUTES.alt),
})
return
}
setAttributes(DEFAULT_QR_CODE_ATTRIBUTES)
}, [editor, open])
const updateAttribute = (key: keyof QrCodeAttributes, value: string) => {
setAttributes((current) => ({ ...current, [key]: value }))
}
const handleSurveyChange = (nextSurveyId: string) => {
setSurveyId(nextSurveyId)
const survey = surveyOptions.find((option) => option.id === nextSurveyId)
if (!survey) return
setAttributes(parseQrCodeInput(survey.value))
}
const handleApply = () => {
const nextAttributes: QrCodeAttributes = {
src: attributes.src.trim(),
width: toPositiveDimension(attributes.width, DEFAULT_QR_CODE_ATTRIBUTES.width),
height: toPositiveDimension(attributes.height, DEFAULT_QR_CODE_ATTRIBUTES.height),
alt: attributes.alt.trim() || DEFAULT_QR_CODE_ATTRIBUTES.alt,
}
if (!nextAttributes.src) return
if (editing) {
editor.chain().focus().updateAttributes(QR_CODE_NODE_NAME, nextAttributes).run()
} else {
editor.chain().focus().insertContent({
type: QR_CODE_NODE_NAME,
attrs: nextAttributes,
}).run()
}
setOpen(false)
}
const handleDelete = () => {
editor.chain().focus().deleteNode(QR_CODE_NODE_NAME).run()
setOpen(false)
}
return (
<Popover open={open} onOpenChange={setOpen}>
<PopoverTrigger asChild>
<span>
<KriEditorToolbarButton active={isActive} title={isActive ? 'QR 코드 수정' : 'QR 코드 삽입'}>
<QrCodeIcon className="size-4" />
</KriEditorToolbarButton>
</span>
</PopoverTrigger>
<PopoverContent className="w-96 space-y-4" align="end">
<div>
<p className="font-semibold">{editing ? 'QR 코드 수정' : 'QR 코드 삽입'}</p>
<p className="text-muted-foreground mt-1 text-xs">설문을 선택하거나 URL을 직접 입력하세요.</p>
</div>
<div className="space-y-1.5">
<Label htmlFor={`${fieldId}-survey`}>설문 선택</Label>
<select
id={`${fieldId}-survey`}
value={surveyId}
onChange={(event) => handleSurveyChange(event.target.value)}
className="border-input bg-background h-9 w-full rounded-md border px-3 text-sm"
>
<option value="">직접 입력</option>
{surveyOptions.map((survey) => (
<option key={survey.id} value={survey.id}>
{survey.label}
</option>
))}
</select>
</div>
<div className="space-y-1.5">
<Label htmlFor={`${fieldId}-src`}>URL</Label>
<Input
id={`${fieldId}-src`}
value={attributes.src}
onChange={(event) => updateAttribute('src', event.target.value)}
placeholder="https://example.com?sid=[$SID]"
/>
</div>
<div className="grid grid-cols-2 gap-3">
<div className="space-y-1.5">
<Label htmlFor={`${fieldId}-width`}>너비(px)</Label>
<Input
id={`${fieldId}-width`}
type="number"
min={1}
value={attributes.width}
onChange={(event) => updateAttribute('width', event.target.value)}
/>
</div>
<div className="space-y-1.5">
<Label htmlFor={`${fieldId}-height`}>높이(px)</Label>
<Input
id={`${fieldId}-height`}
type="number"
min={1}
value={attributes.height}
onChange={(event) => updateAttribute('height', event.target.value)}
/>
</div>
</div>
<div className="space-y-1.5">
<Label htmlFor={`${fieldId}-alt`}>대체 텍스트</Label>
<Input
id={`${fieldId}-alt`}
value={attributes.alt}
onChange={(event) => updateAttribute('alt', event.target.value)}
placeholder={DEFAULT_QR_CODE_ATTRIBUTES.alt}
/>
</div>
<div className="flex items-center justify-between gap-2">
<div>
{editing ? (
<Button type="button" variant="destructive" size="sm" className="gap-1.5" onClick={handleDelete}>
<Trash2 className="size-4" />
삭제
</Button>
) : null}
</div>
<div className="flex gap-2">
<Button type="button" variant="outline" size="sm" onClick={() => setOpen(false)}>
취소
</Button>
<Button type="button" size="sm" disabled={!canApply} onClick={handleApply}>
{editing ? '수정' : '삽입'}
</Button>
</div>
</div>
</PopoverContent>
</Popover>
)
}

View File

@@ -0,0 +1,224 @@
import { mergeAttributes, Node } from '@tiptap/core'
import { NodeSelection } from '@tiptap/pm/state'
export const QR_CODE_NODE_NAME = 'qrCode'
export const QR_CODE_PREVIEW_IMAGE_SRC = '/qr_example.png'
/** <qrcode> 커스텀 태그를 다루는 모든 화면(에디터, 발송 미리보기 등)이 공유하는 sanitize 허용 목록 */
export const QR_CODE_ALLOWED_HTML: { tags: string[]; attributes: string[] } = {
tags: ['qrcode'],
attributes: ['src', 'width', 'height', 'alt'],
}
export type QrCodeAttributes = {
src: string
width: string
height: string
alt: string
}
export const DEFAULT_QR_CODE_ATTRIBUTES: QrCodeAttributes = {
src: '',
width: '100',
height: '100',
alt: 'QR 코드',
}
export const toPositiveDimension = (value: string, fallback: string): string => {
const parsed = Number.parseInt(value, 10)
return Number.isFinite(parsed) && parsed > 0 ? String(parsed) : fallback
}
const decodeHtmlEntities = (value: string): string => {
if (typeof document === 'undefined') return value
const textarea = document.createElement('textarea')
textarea.innerHTML = value
return textarea.value
}
const ATTRIBUTE_PATTERN = /([:\w-]+)\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'=<>`]+))/g
const extractAttributes = (raw: string): Map<string, string> => {
const attributes = new Map<string, string>()
for (const match of raw.matchAll(ATTRIBUTE_PATTERN)) {
attributes.set(match[1].toLowerCase(), match[2] ?? match[3] ?? match[4] ?? '')
}
return attributes
}
export const parseQrCodeInput = (value: string): QrCodeAttributes => {
const decoded = decodeHtmlEntities(value.trim())
const tagMatch = decoded.match(/<qrcode\b([^>]*)\/?>/i)
if (!tagMatch) {
return {
...DEFAULT_QR_CODE_ATTRIBUTES,
src: decoded,
}
}
const attributes = extractAttributes(tagMatch[1])
return {
src: attributes.get('src') ?? '',
width: attributes.get('width') ?? DEFAULT_QR_CODE_ATTRIBUTES.width,
height: attributes.get('height') ?? DEFAULT_QR_CODE_ATTRIBUTES.height,
alt: attributes.get('alt') ?? DEFAULT_QR_CODE_ATTRIBUTES.alt,
}
}
/**
* HTML 파서는 사용자 정의 태그의 self-closing 문법을 보장하지 않으므로
* TipTap에 전달하기 전 명시적인 여닫는 태그로 정규화한다.
*/
export const normalizeQrCodeForEditor = (html?: string | null): string => {
if (!html) return ''
const decodedPairedTags = html.replace(
/&lt;qrcode\b([\s\S]*?)&gt;\s*&lt;\/qrcode\s*&gt;/gi,
'<qrcode$1></qrcode>',
)
const decodedSelfClosingTags = decodedPairedTags.replace(
/&lt;qrcode\b([\s\S]*?)\/\s*&gt;/gi,
'<qrcode$1/>',
)
return decodedSelfClosingTags.replace(
/<qrcode\b([^>]*)\/\s*>/gi,
(_match, attributes: string) => `<qrcode${attributes.trimEnd()}></qrcode>`,
)
}
/**
* TipTap의 사용자 정의 노드 직렬화 결과를 메시지 서버 규격인 self-closing 태그로 변환한다.
*/
export const normalizeQrCodeForStorage = (html?: string | null): string => {
if (!html) return ''
return html.replace(
/<qrcode\b([^>]*)>\s*<\/qrcode\s*>/gi,
(_match, attributes: string) => `<qrcode${attributes.trimEnd()}/>`,
)
}
const escapeHtmlAttribute = (value: string): string =>
value.replace(/&/g, '&amp;').replace(/"/g, '&quot;').replace(/</g, '&lt;').replace(/>/g, '&gt;')
/**
* 미리보기 전용 변환. <qrcode> 커스텀 태그는 실제 QR을 생성하지 않으므로
* public/qr_example.png 예시 이미지를 속성에 지정된 크기로 대신 보여준다.
*/
export const renderQrCodePreviewHtml = (html: string): string => {
if (!html) return html
return html.replace(
/<qrcode\b([^>]*?)\/>|<qrcode\b([^>]*?)>\s*<\/qrcode\s*>/gi,
(_match, selfClosingAttrs?: string, pairedAttrs?: string) => {
const attributes = extractAttributes(selfClosingAttrs ?? pairedAttrs ?? '')
const width = toPositiveDimension(attributes.get('width') ?? '', DEFAULT_QR_CODE_ATTRIBUTES.width)
const height = toPositiveDimension(attributes.get('height') ?? '', DEFAULT_QR_CODE_ATTRIBUTES.height)
const alt = attributes.get('alt') ?? DEFAULT_QR_CODE_ATTRIBUTES.alt
return `<img src="${QR_CODE_PREVIEW_IMAGE_SRC}" width="${width}" height="${height}" alt="${escapeHtmlAttribute(alt)}" data-qr-preview="true" style="display:inline-block;vertical-align:middle;object-fit:contain;" />`
},
)
}
export const QrCode = Node.create({
name: QR_CODE_NODE_NAME,
group: 'inline',
inline: true,
atom: true,
selectable: true,
addAttributes() {
return {
src: {
default: DEFAULT_QR_CODE_ATTRIBUTES.src,
},
width: {
default: DEFAULT_QR_CODE_ATTRIBUTES.width,
},
height: {
default: DEFAULT_QR_CODE_ATTRIBUTES.height,
},
alt: {
default: DEFAULT_QR_CODE_ATTRIBUTES.alt,
},
}
},
parseHTML() {
return [{ tag: 'qrcode' }]
},
renderHTML({ HTMLAttributes }) {
return ['qrcode', mergeAttributes(HTMLAttributes)]
},
addNodeView() {
return ({ node, editor, getPos }) => {
const dom = document.createElement('span')
const BASE_CLASS =
'mx-0.5 inline-flex max-w-full cursor-pointer items-center rounded-md border border-blue-300 bg-blue-50 px-2 py-1 align-middle text-xs text-blue-800 transition-colors'
const SELECTED_CLASS = ['border-blue-500', 'bg-blue-100', 'ring-2', 'ring-blue-400', 'ring-offset-1']
let selected = false
const applyClassName = () => {
dom.className = BASE_CLASS
if (selected) dom.classList.add(...SELECTED_CLASS)
}
const render = (attributes: Record<string, unknown>) => {
const src = String(attributes.src ?? '')
const width = String(attributes.width ?? '')
const height = String(attributes.height ?? '')
const alt = String(attributes.alt ?? '')
dom.contentEditable = 'false'
applyClassName()
dom.dataset.qrCode = 'true'
dom.textContent = `QR 코드 · ${src}`
dom.title = `${alt} (${width}×${height}px)\n${src}`
}
render(node.attrs)
// 인라인 atom 노드는 클릭 시 NodeSelection이 잡히지 않는 경우가 있어
// 직접 선택을 잡아줘야 툴바 활성 표시(selectNode)가 안정적으로 동작한다.
dom.addEventListener('click', (event) => {
event.preventDefault()
if (typeof getPos !== 'function') return
const pos = getPos()
if (pos == null) return
const { state, dispatch } = editor.view
dispatch(state.tr.setSelection(NodeSelection.create(state.doc, pos)))
editor.view.focus()
})
return {
dom,
selectNode: () => {
selected = true
applyClassName()
},
deselectNode: () => {
selected = false
applyClassName()
},
update: (updatedNode) => {
if (updatedNode.type.name !== QR_CODE_NODE_NAME) return false
render(updatedNode.attrs)
return true
},
}
}
},
})