diff --git a/.env.local b/.env.local index adc3bd4..2657ce9 100644 --- a/.env.local +++ b/.env.local @@ -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 \ No newline at end of file diff --git a/public/qr_example.png b/public/qr_example.png new file mode 100644 index 0000000..4e4f40b Binary files /dev/null and b/public/qr_example.png differ diff --git a/src/app/(pages)/(main)/list/manage/page.tsx b/src/app/(pages)/(main)/list/manage/page.tsx index b293869..7035280 100644 --- a/src/app/(pages)/(main)/list/manage/page.tsx +++ b/src/app/(pages)/(main)/list/manage/page.tsx @@ -304,7 +304,11 @@ const ListManagePage = () => { {isInternal && ( <> - + { {canManageList && ( <> - + { 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 = ({ >

적용 대상

- +
diff --git a/src/components/dialog/ListDialogOption/ApplyFilterOption.tsx b/src/components/dialog/ListDialogOption/ApplyFilterOption.tsx index fd3cfeb..2c1ba77 100644 --- a/src/components/dialog/ListDialogOption/ApplyFilterOption.tsx +++ b/src/components/dialog/ListDialogOption/ApplyFilterOption.tsx @@ -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 (
+ {value === 'selected' && selectedSids !== undefined && ( +
+

선택된 SID ({selectedSids.length}개)

+ {selectedSids.length > 0 ? ( +

+ {selectedSids.join(', ')} +

+ ) : ( +

선택된 항목이 없습니다.

+ )} +
+ )} + {value === 'filtered' && filterSummary !== undefined && (

적용된 필터

diff --git a/src/components/dialog/ListDownloadDialog.tsx b/src/components/dialog/ListDownloadDialog.tsx index 6b090d7..abd4835 100644 --- a/src/components/dialog/ListDownloadDialog.tsx +++ b/src/components/dialog/ListDownloadDialog.tsx @@ -17,6 +17,7 @@ export type ListDownloadDialogProps = { open?: boolean onOpenChange?: (open: boolean) => void mode: ListDownloadMode + selectedSids: string[] filterSummary?: string[] onDownload: (payload: ListDownloadPayload) => void | Promise } @@ -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}

다운로드 범위

- +
{mode === 'contact-history' ? (
diff --git a/src/components/dialog/ListResetDialog.tsx b/src/components/dialog/ListResetDialog.tsx index 3121b13..a8d6691 100644 --- a/src/components/dialog/ListResetDialog.tsx +++ b/src/components/dialog/ListResetDialog.tsx @@ -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 } @@ -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} />
diff --git a/src/components/dialog/MessageSendDialog.tsx b/src/components/dialog/MessageSendDialog.tsx index 07d5ed6..50404fc 100644 --- a/src/components/dialog/MessageSendDialog.tsx +++ b/src/components/dialog/MessageSendDialog.tsx @@ -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 = ({
- +
@@ -328,8 +340,17 @@ const MessageSendDialog = ({
) : (
)} diff --git a/src/components/kri-editor/KriEditorWysiwyg.tsx b/src/components/kri-editor/KriEditorWysiwyg.tsx index 180323d..e2b10f3 100644 --- a/src/components/kri-editor/KriEditorWysiwyg.tsx +++ b/src/components/kri-editor/KriEditorWysiwyg.tsx @@ -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 || "

", @@ -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) {
미리보기
-
+
)} diff --git a/src/components/kri-editor/index.ts b/src/components/kri-editor/index.ts index 86e0a7d..11bfa8f 100644 --- a/src/components/kri-editor/index.ts +++ b/src/components/kri-editor/index.ts @@ -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, diff --git a/src/components/kri-editor/types.ts b/src/components/kri-editor/types.ts index ed055a4..18fb051 100644 --- a/src/components/kri-editor/types.ts +++ b/src/components/kri-editor/types.ts @@ -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 = { diff --git a/src/components/kri-editor/utils/linkPreview.ts b/src/components/kri-editor/utils/linkPreview.ts new file mode 100644 index 0000000..210f746 --- /dev/null +++ b/src/components/kri-editor/utils/linkPreview.ts @@ -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 모드에서 직접 작성된 경우 에디터의 링크 스타일 클래스가 없을 수 있다. + * 태그에 KRI_EDITOR_LINK_CLASS를 보정해 항상 동일하게 보이도록 한다. + */ +export function applyLinkPreviewClass(html: string): string { + if (!html) return html; + + return html.replace(/]*)>/gi, (match, attrs: string) => { + const classMatch = attrs.match(CLASS_ATTR_PATTERN); + + if (!classMatch) { + return ``; + } + + 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 ``; + }); +} diff --git a/src/components/kri-editor/utils/sanitizeHtml.ts b/src/components/kri-editor/utils/sanitizeHtml.ts index 3e52308..a209e7f 100644 --- a/src/components/kri-editor/utils/sanitizeHtml.ts +++ b/src/components/kri-editor/utils/sanitizeHtml.ts @@ -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); } diff --git a/src/components/list/ListSearchTable.tsx b/src/components/list/ListSearchTable.tsx index 3a7f822..ab38e54 100644 --- a/src/components/list/ListSearchTable.tsx +++ b/src/components/list/ListSearchTable.tsx @@ -185,6 +185,10 @@ export function ListSearchTable({ const [batchResultCodes, setBatchResultCodes] = useState({}) const [batchSurveyResultCodes, setBatchSurveyResultCodes] = useState({}) const [selectedRows, setSelectedRows] = useState([]) + 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} diff --git a/src/components/message-template/MessageTemplate.tsx b/src/components/message-template/MessageTemplate.tsx index 68e5092..cf1cc65 100644 --- a/src/components/message-template/MessageTemplate.tsx +++ b/src/components/message-template/MessageTemplate.tsx @@ -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 ?? "

"} + value={normalizeQrCodeForEditor(selectedTemplate.tmplatBody) || "

"} 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}) => ( + + )} /> )}
diff --git a/src/components/message-template/QrCodeToolbar.tsx b/src/components/message-template/QrCodeToolbar.tsx new file mode 100644 index 0000000..2c2de03 --- /dev/null +++ b/src/components/message-template/QrCodeToolbar.tsx @@ -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(DEFAULT_QR_CODE_ATTRIBUTES) + + const surveyOptions = useMemo( + () => + 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 ( + + + + + + + + + +
+

{editing ? 'QR 코드 수정' : 'QR 코드 삽입'}

+

설문을 선택하거나 URL을 직접 입력하세요.

+
+ +
+ + +
+ +
+ + updateAttribute('src', event.target.value)} + placeholder="https://example.com?sid=[$SID]" + /> +
+ +
+
+ + updateAttribute('width', event.target.value)} + /> +
+
+ + updateAttribute('height', event.target.value)} + /> +
+
+ +
+ + updateAttribute('alt', event.target.value)} + placeholder={DEFAULT_QR_CODE_ATTRIBUTES.alt} + /> +
+ +
+
+ {editing ? ( + + ) : null} +
+
+ + +
+
+
+
+ ) +} diff --git a/src/components/message-template/qrcode.ts b/src/components/message-template/qrcode.ts new file mode 100644 index 0000000..1ff633c --- /dev/null +++ b/src/components/message-template/qrcode.ts @@ -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' + +/** 커스텀 태그를 다루는 모든 화면(에디터, 발송 미리보기 등)이 공유하는 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 => { + const attributes = new Map() + + 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(/]*)\/?>/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( + /<qrcode\b([\s\S]*?)>\s*<\/qrcode\s*>/gi, + '', + ) + const decodedSelfClosingTags = decodedPairedTags.replace( + /<qrcode\b([\s\S]*?)\/\s*>/gi, + '', + ) + + return decodedSelfClosingTags.replace( + /]*)\/\s*>/gi, + (_match, attributes: string) => ``, + ) +} + +/** + * TipTap의 사용자 정의 노드 직렬화 결과를 메시지 서버 규격인 self-closing 태그로 변환한다. + */ +export const normalizeQrCodeForStorage = (html?: string | null): string => { + if (!html) return '' + + return html.replace( + /]*)>\s*<\/qrcode\s*>/gi, + (_match, attributes: string) => ``, + ) +} + +const escapeHtmlAttribute = (value: string): string => + value.replace(/&/g, '&').replace(/"/g, '"').replace(//g, '>') + +/** + * 미리보기 전용 변환. 커스텀 태그는 실제 QR을 생성하지 않으므로 + * public/qr_example.png 예시 이미지를 속성에 지정된 크기로 대신 보여준다. + */ +export const renderQrCodePreviewHtml = (html: string): string => { + if (!html) return html + + return html.replace( + /]*?)\/>|]*?)>\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 `${escapeHtmlAttribute(alt)}` + }, + ) +} + +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) => { + 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 + }, + } + } + }, +})