260803_01_ENH: 에디터에 QR 코드 삽입 추가
This commit is contained in:
@@ -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>
|
||||
|
||||
228
src/components/message-template/QrCodeToolbar.tsx
Normal file
228
src/components/message-template/QrCodeToolbar.tsx
Normal 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>
|
||||
)
|
||||
}
|
||||
224
src/components/message-template/qrcode.ts
Normal file
224
src/components/message-template/qrcode.ts
Normal 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(
|
||||
/<qrcode\b([\s\S]*?)>\s*<\/qrcode\s*>/gi,
|
||||
'<qrcode$1></qrcode>',
|
||||
)
|
||||
const decodedSelfClosingTags = decodedPairedTags.replace(
|
||||
/<qrcode\b([\s\S]*?)\/\s*>/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, '&').replace(/"/g, '"').replace(/</g, '<').replace(/>/g, '>')
|
||||
|
||||
/**
|
||||
* 미리보기 전용 변환. <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
|
||||
},
|
||||
}
|
||||
}
|
||||
},
|
||||
})
|
||||
Reference in New Issue
Block a user