diff --git a/components/admin/AdminMarkdownEditor.vue b/components/admin/AdminMarkdownEditor.vue index ac5f869..06d7599 100644 --- a/components/admin/AdminMarkdownEditor.vue +++ b/components/admin/AdminMarkdownEditor.vue @@ -2,18 +2,15 @@ import { normalizeMarkdownContent } from '../../lib/markdown-content-normalizer.js' import { resolveActiveBlockContext } from '../../lib/markdown-block-context.js' import { - getImageDefaultAltLabel, isImageUrl, parseImageMarkdownLine, serializeImageMarkdown } from '../../lib/markdown-image.js' import { convertHtmlToMarkdown, - formatInlineColorMarkdown, readEditableTextFromElement } from '../../lib/markdown-inline.js' import { - getMarkdownLineBodyPrefixLength, getSelectionOffsetInElement } from '../../lib/markdown-live-selection.js' import { @@ -42,6 +39,21 @@ import { resolveImageUploadInsertTarget, resolveUploadFetchErrorMessage } from '../../lib/markdown-editor-media.js' +import { + createCalloutOptionsReplacementPlan, + createCodeOptionsReplacementPlan, + createEmbedUrlReplacementPlan, + createGalleryImageMovePlan, + createGalleryImagesAppendPlan, + createLiveInlineColorValue, + createMediaImageRemovePlan, + createMediaImagesReplacementPlan, + createMediaImageUpdatePlan, + createMediaUseAltPatch, + createQuoteBackgroundValue, + createSourceInlineColorValue, + createToggleOptionsReplacementPlan +} from '../../lib/markdown-editor-block-options.js' import { createSlashCommandApplyPlan, createSlashCommandEditorEffectPlan, @@ -61,9 +73,6 @@ import { DEFAULT_SLASH_MENU_WIDTH } from '../../lib/markdown-slash-menu-position.js' import { calculateSlashMenuScrollTop } from '../../lib/markdown-slash-menu-scroll.js' -import { buildCalloutOpenerLine, CALLOUT_BACKGROUND_OPTIONS, QUOTE_BACKGROUND_OPTIONS } from '../../lib/markdown-callout.js' -import { buildCodeFenceOpener } from '../../lib/markdown-code-block.js' -import { buildToggleOpenerLine } from '../../lib/markdown-toggle.js' import { getTextareaCaretCoordinates } from '../../lib/textarea-caret-coordinates.js' import { useAdminMarkdownSlashMenu } from '../../composables/useAdminMarkdownSlashMenu.js' import { useAdminMarkdownHistory } from '../../composables/useAdminMarkdownHistory.js' @@ -1213,6 +1222,21 @@ const replaceLineRange = (startLine, endLine, replacementLines, focusEditor = tr } } +/** + * 줄 범위 교체 계획을 현재 마크다운 본문에 적용한다. + * @param {{ startLine: number, endLine: number, replacementLines: string[] }|null} plan - 교체 계획 + * @param {boolean} focusEditor - 교체 후 textarea에 포커스를 돌릴지 여부 + * @returns {boolean} 적용 여부 + */ +const applyLineReplacementPlan = (plan, focusEditor = false) => { + if (!plan) { + return false + } + + replaceLineRange(plan.startLine, plan.endLine, plan.replacementLines, focusEditor) + return true +} + /** * 현재 문서 기준 fenced 블록의 닫는 줄을 찾는다. * @param {number} startLine - 시작 줄 @@ -1242,32 +1266,10 @@ const resolveCurrentFencedBlockEndLine = (startLine, fallbackEndLine) => { * @returns {void} */ const replaceActiveMediaImages = (images) => { - const block = activeMediaBlock.value - - if (!block) { - return - } - - if (block.kind === 'image') { - if (!images[0]) { - replaceLineRange(block.startLine, block.endLine, [], false) - return - } - - replaceLineRange(block.startLine, block.endLine, [createImageMarkdown(images[0])], false) - return - } - - if (!images.length) { - replaceLineRange(block.startLine, block.endLine, [], false) - return - } - - replaceLineRange(block.startLine, block.endLine, [ - ':::gallery', - ...images.map(createImageMarkdown), - ':::' - ], false) + applyLineReplacementPlan( + createMediaImagesReplacementPlan(activeMediaBlock.value, images), + false + ) } /** @@ -1277,15 +1279,14 @@ const replaceActiveMediaImages = (images) => { * @returns {void} */ const updateActiveMediaImage = (imageIndex, patch) => { - const block = activeMediaBlock.value + const plan = createMediaImageUpdatePlan(activeMediaBlock.value, imageIndex, patch) - if (!block) { + if (!plan) { return } ensureBlockPanelEngaged() - const images = block.images.map((image, index) => index === imageIndex ? { ...image, ...patch } : image) - replaceActiveMediaImages(images) + applyLineReplacementPlan(plan, false) } /** @@ -1296,24 +1297,12 @@ const updateActiveMediaImage = (imageIndex, patch) => { */ const setActiveMediaUseAlt = (imageIndex, enabled) => { const image = activeMediaBlock.value?.images[imageIndex] + const patch = createMediaUseAltPatch(image, enabled) - if (!image) { + if (!patch) { return } - const filename = getImageDefaultAltLabel(image.url) - const patch = { useAlt: enabled } - - if (enabled) { - if (!String(image.caption || '').trim()) { - const legacy = String(image.legacyBracketLabel || '').trim() - - patch.caption = legacy && legacy !== filename ? legacy : filename - } - } else if (String(image.caption || '').trim() === filename) { - patch.caption = '' - } - updateActiveMediaImage(imageIndex, patch) } @@ -2078,22 +2067,13 @@ const onPreviewMergeWithPreviousLine = ({ lineIndex, mergedLine }) => { * @returns {void} */ const moveActiveGalleryImage = (imageIndex, direction) => { - const block = activeMediaBlock.value + const plan = createGalleryImageMovePlan(activeMediaBlock.value, imageIndex, direction) - if (!block || block.kind !== 'gallery') { + if (!plan) { return } - const nextIndex = imageIndex + direction - - if (nextIndex < 0 || nextIndex >= block.images.length) { - return - } - - const images = [...block.images] - const [target] = images.splice(imageIndex, 1) - images.splice(nextIndex, 0, target) - replaceActiveMediaImages(images) + applyLineReplacementPlan(plan, false) } /** @@ -2102,13 +2082,10 @@ const moveActiveGalleryImage = (imageIndex, direction) => { * @returns {void} */ const removeActiveMediaImage = (imageIndex) => { - const block = activeMediaBlock.value - - if (!block) { - return - } - - replaceActiveMediaImages(block.images.filter((_, index) => index !== imageIndex)) + applyLineReplacementPlan( + createMediaImageRemovePlan(activeMediaBlock.value, imageIndex), + false + ) } /** @@ -2117,14 +2094,14 @@ const removeActiveMediaImage = (imageIndex) => { * @returns {void} */ const appendImagesToActiveGallery = (images) => { - const block = activeMediaBlock.value + const plan = createGalleryImagesAppendPlan(activeMediaBlock.value, images) - if (!block || block.kind !== 'gallery') { + if (!plan) { insertGallery(images) return } - replaceActiveMediaImages([...block.images, ...images]) + applyLineReplacementPlan(plan, false) } /** @@ -2133,21 +2110,14 @@ const appendImagesToActiveGallery = (images) => { * @returns {void} */ const updateActiveEmbedUrl = (url) => { - const block = activeBlockContext.value + const plan = createEmbedUrlReplacementPlan(activeBlockContext.value, url) - if (!block || !['link', 'iframe', 'html'].includes(block.kind)) { + if (!plan) { return } ensureBlockPanelEngaged() - const trimmed = String(url || '').trim() - - if (!trimmed) { - replaceLineRange(block.startLine, block.endLine, [], false) - return - } - - replaceLineRange(block.startLine, block.endLine, [`:::${block.kind}`, trimmed, ':::'], false) + applyLineReplacementPlan(plan, false) } /** @@ -2156,30 +2126,18 @@ const updateActiveEmbedUrl = (url) => { * @returns {void} */ const updateActiveQuoteBackground = (background) => { - const block = activeBlockContext.value + const nextValue = createQuoteBackgroundValue({ + value: markdownValue.value, + block: activeBlockContext.value, + background + }) - if (!block || block.kind !== 'quote') { + if (nextValue === null) { return } ensureBlockPanelEngaged() - const value = String(background || '').trim() - - if (!QUOTE_BACKGROUND_OPTIONS.includes(value)) { - return - } - - const optionLine = `> [!bg=${value}]` - const lines = (markdownValue.value || '').split('\n') - const nextLines = [...lines] - - if (block.hasQuoteOptions) { - nextLines.splice(block.startLine, 1, optionLine) - } else { - nextLines.splice(block.startLine, 0, optionLine) - } - - markdownValue.value = nextLines.join('\n') + markdownValue.value = nextValue } /** @@ -2188,27 +2146,14 @@ const updateActiveQuoteBackground = (background) => { * @returns {void} */ const updateActiveCalloutOptions = (patch = {}) => { - const block = activeBlockContext.value + const plan = createCalloutOptionsReplacementPlan(activeBlockContext.value, patch) - if (!block || block.kind !== 'callout') { + if (!plan) { return } ensureBlockPanelEngaged() - const nextBackground = CALLOUT_BACKGROUND_OPTIONS.includes(patch.calloutBackground) - ? patch.calloutBackground - : block.calloutBackground - const nextLine = buildCalloutOpenerLine({ - calloutEmojiEnabled: patch.calloutEmojiEnabled ?? block.calloutEmojiEnabled, - calloutEmoji: patch.calloutEmoji ?? block.calloutEmoji, - calloutBackground: nextBackground, - title: patch.title ?? block.title - }) - const lines = (markdownValue.value || '').split('\n') - const nextLines = [...lines] - - nextLines.splice(block.startLine, 1, nextLine) - markdownValue.value = nextLines.join('\n') + applyLineReplacementPlan(plan, false) } /** @@ -2217,22 +2162,14 @@ const updateActiveCalloutOptions = (patch = {}) => { * @returns {void} */ const updateActiveCodeOptions = (patch = {}) => { - const block = activeBlockContext.value + const plan = createCodeOptionsReplacementPlan(activeBlockContext.value, patch) - if (!block || block.kind !== 'code') { + if (!plan) { return } ensureBlockPanelEngaged() - const nextLine = buildCodeFenceOpener({ - language: patch.language ?? block.language, - showLineNumbers: patch.showLineNumbers ?? block.showLineNumbers - }) - const lines = (markdownValue.value || '').split('\n') - const nextLines = [...lines] - - nextLines.splice(block.startLine, 1, nextLine) - markdownValue.value = nextLines.join('\n') + applyLineReplacementPlan(plan, false) } /** @@ -2241,22 +2178,14 @@ const updateActiveCodeOptions = (patch = {}) => { * @returns {void} */ const updateActiveToggleOptions = (patch = {}) => { - const block = activeBlockContext.value + const plan = createToggleOptionsReplacementPlan(activeBlockContext.value, patch) - if (!block || block.kind !== 'toggle') { + if (!plan) { return } ensureBlockPanelEngaged() - const nextLine = buildToggleOpenerLine({ - title: block.title, - defaultOpen: patch.defaultOpen ?? block.defaultOpen - }) - const lines = (markdownValue.value || '').split('\n') - const nextLines = [...lines] - - nextLines.splice(block.startLine, 1, nextLine) - markdownValue.value = nextLines.join('\n') + applyLineReplacementPlan(plan, false) } /** @@ -2273,51 +2202,44 @@ const updateActiveInlineColor = (color) => { ensureBlockPanelEngaged() - if (context.mode === 'source') { - const value = markdownValue.value || '' - const start = Math.max(0, Math.min(context.start ?? 0, value.length)) - const end = Math.max(start, Math.min(context.end ?? start, value.length)) - const selectedText = value.slice(start, end) - const replacement = formatInlineColorMarkdown(color, selectedText) + const sourceResult = createSourceInlineColorValue({ + value: markdownValue.value, + context, + color + }) - markdownValue.value = `${value.slice(0, start)}${replacement}${value.slice(end)}` + if (sourceResult) { + markdownValue.value = sourceResult.value inlineColorSelectionContext.value = null - setTextareaSelection(start + replacement.length, start + replacement.length, { preserveScroll: true }) + setTextareaSelection(sourceResult.selectionStart, sourceResult.selectionEnd, { preserveScroll: true }) return } - if (context.mode === 'live' && Number.isInteger(context.sourceLine)) { - const lines = (markdownValue.value || '').split('\n') - const line = lines[context.sourceLine] + const liveResult = createLiveInlineColorValue({ + value: markdownValue.value, + context, + color + }) - if (typeof line !== 'string') { - return - } - - const prefixLength = getMarkdownLineBodyPrefixLength(line, context.bodyText || '') - const absoluteStart = prefixLength + Math.max(0, context.startOffset ?? 0) - const absoluteEnd = prefixLength + Math.max(context.startOffset ?? 0, context.endOffset ?? 0) - const selectedText = line.slice(absoluteStart, absoluteEnd) - const replacement = formatInlineColorMarkdown(color, selectedText) - const nextVisibleOffset = (context.startOffset ?? 0) + selectedText.length - - lines.splice(context.sourceLine, 1, `${line.slice(0, absoluteStart)}${replacement}${line.slice(absoluteEnd)}`) - markdownValue.value = lines.join('\n') - inlineColorSelectionContext.value = null - requestPreviewFocus({ - line: context.sourceLine, - offset: nextVisibleOffset - }) - nextTick(() => { - focusPreviewEditableAtLine( - context.sourceLine, - 0, - 'auto', - nextVisibleOffset, - 'nearest' - ) - }) + if (!liveResult) { + return } + + markdownValue.value = liveResult.value + inlineColorSelectionContext.value = null + requestPreviewFocus({ + line: liveResult.focusLine, + offset: liveResult.focusOffset + }) + nextTick(() => { + focusPreviewEditableAtLine( + liveResult.focusLine, + 0, + 'auto', + liveResult.focusOffset, + 'nearest' + ) + }) } /** diff --git a/docs/history.md b/docs/history.md index 4be207d..af3986e 100644 --- a/docs/history.md +++ b/docs/history.md @@ -1,3 +1,7 @@ +## 2026-07-28 v1.11.116 — 블록 옵션 문자열 계산은 에디터 밖에서 만든다 + +관리자 Markdown 에디터의 오른쪽 패널은 이미지 캡션·갤러리 순서·임베드 URL·콜아웃/코드/토글 선언 줄·인라인 색상처럼 서로 다른 마크다운 문자열을 직접 조립하고 있었다. 이 계산이 컴포넌트 안에 남으면 패널 포커스 유지나 DOM 포커스 복원과 실제 저장 문법이 한 파일에서 계속 얽힌다. 따라서 `markdown-editor-block-options` helper가 줄 교체 계획과 새 본문 값을 만들고, 에디터는 계산 결과를 현재 문서에 적용하는 역할만 맡게 한다. + ## 2026-07-28 v1.11.115 — 블록 패널 표시 상태는 편집 본문과 분리한다 관리자 Markdown 에디터의 오른쪽 블록 패널은 textarea 포커스, 라이브 편집 줄 포커스, 패널 자체 포커스, IME 조합 중 직전 컨텍스트 유지, 인라인 색상 선택 우선순위가 함께 결정한다. 이 상태 계산을 본문 변경 함수와 같은 파일에 두면 이미지·콜아웃·코드 옵션을 수정할 때 패널 표시 조건까지 같이 흔들릴 수 있다. 따라서 `useAdminMarkdownBlockPanel`이 표시 상태와 포커스 유지 규칙을 맡고, 에디터는 실제 본문 값을 바꾸는 함수와 선택 컨텍스트 계산만 유지한다. diff --git a/docs/map.md b/docs/map.md index e355dea..ca7f3bc 100644 --- a/docs/map.md +++ b/docs/map.md @@ -66,6 +66,7 @@ | lib/markdown-editor-keyboard.js | 관리자 Markdown-first 에디터 전역 단축키 판별(Cmd/Ctrl 조합, undo/redo, 작성/미리보기 전환, 미디어 선택 닫기) | | lib/markdown-source-selection.js | 관리자 Markdown-first 소스 textarea 선택 상태, 본문 치환, 블록 조각 삽입, 인라인 링크·감싸기, 줄 변환·삭제 계산 | | lib/markdown-editor-media.js | 관리자 Markdown-first 에디터 미디어 선택 모달의 미디어 종류 판별, 대상별 선택 가능 여부, 미리보기 URL, 업로드 MIME 허용, 선택 대상별 제목·accept·API kind·업로드 안내, 라이브러리 빈 상태 문구, 적용 버튼 상태, 목록 조회 query, 선택 순서·토글·항목 해석, 선택 미디어 삽입 계획, 업로드 입력·FormData·응답 파일 정규화, 붙여넣기·드롭 이미지 필터링, 업로드 오류·한도 검증, 페이지 상태·범위·페이지 번호 보정·페이지 번호 계산, fenced 미디어 블록 생성 | +| lib/markdown-editor-block-options.js | 관리자 Markdown-first 에디터 오른쪽 블록 패널의 이미지·갤러리·임베드·인용·콜아웃·코드·토글 옵션 줄 교체 계획과 인라인 색상 본문 변경 계산 | | lib/markdown-block-parser.js | 공개 Markdown 본문 문자열을 제목·문단·이미지·갤러리·fenced 블록·인용·목록·코드·표 렌더링 블록으로 변환 | | lib/markdown-block-context.js | 관리자 Markdown textarea·라이브 편집 포커스 위치 기준 이미지·갤러리·링크·iframe·HTML·인용·콜아웃·코드·토글 블록 설정 패널 대상 판별, 인용 옵션 공통 파서 연결, 코드 fenced 블록 여닫는 펜스 쌍 판별 | | lib/markdown-iframe-embed.js | 게시물 본문 iframe 블록의 코드 판별과 안전 속성 추출, `allowfullscreen`을 `allow=fullscreen` 권한으로 정규화 | @@ -143,6 +144,7 @@ | tests/markdown-editor-keyboard.test.js | 관리자 Markdown 에디터 전역 단축키 판별 단위 회귀 테스트 | | tests/useAdminMarkdownFocusBridge.test.js | 관리자 Markdown 에디터 작성/라이브 모드 전환 포커스 대기 상태와 복원 콜백 단위 테스트 | | tests/markdown-source-selection.test.js | 관리자 Markdown 에디터 소스 textarea 선택·치환·줄 변환 helper 단위 테스트 | +| tests/markdown-editor-block-options.test.js | 관리자 Markdown 에디터 블록 옵션 줄 교체 계획과 인라인 색상 본문 변경 helper 단위 테스트 | | tests/markdown-editor-media.test.js | 관리자 Markdown 에디터 미디어 선택 helper의 종류·선택 가능 여부·미리보기·선택 상태·삽입 계획·업로드 정규화·블록 생성 단위 회귀 테스트 | | tests/markdown-slash-commands.test.js | 관리자 슬래시 명령 파싱·입력값 기준 명령 해석·미디어 action·모달 종류·적용 계획·제외 줄 Set 갱신·하이라이트 인덱스 보정·방향키 순환·키보드 동작 분류·후보 개수 기준 키보드 가로채기·포커스 대상·textarea 선택 위치·원문 줄 교체 삽입 단위 회귀 테스트 | | tests/markdown-slash-menu-scroll.test.js | 관리자 슬래시 메뉴 선택 항목 scrollTop 보정 단위 테스트 | diff --git a/docs/spec.md b/docs/spec.md index b26d61c..36c76da 100644 --- a/docs/spec.md +++ b/docs/spec.md @@ -112,7 +112,7 @@ - Markdown 리스트 마커는 항목이 여러 줄로 줄바꿈되어도 항목 전체 높이 중앙이 아니라 첫 줄 기준으로 정렬한다. - 표준 마크다운 표(`| 헤더 | ... |`, `| --- | ... |`)는 본문에서 가로 스크롤 가능한 HTML table로 렌더링한다. 정렬 구분선(`:---`, `:---:`, `---:`)은 각각 좌/중앙/우 정렬로 반영한다. 표 헤더와 셀 내부의 인라인 링크·굵게·기울임·인라인 코드를 렌더링하고, 셀 내부 `
` 또는 `
`은 줄바꿈으로 표시한다. 링크 텍스트 안의 `**굵게**` 같은 중첩 인라인 문법도 렌더링한다. - 인용문(`>`)은 왼쪽 세로 막대형 기본 스타일로 표시한다. 기본 인용 텍스트는 라이트·다크 모드 모두 사이트 본문 텍스트 색상(`--site-text`)을 따른다. 첫 줄 옵션 `> [!bg=blue]` 또는 `> {bg=blue}`는 인용 막대 색상으로 반영하며, 지원 값은 콜아웃과 같은 `gray`, `blue`, `green`, `yellow`, `red`, `purple`이다. 인용 본문 안의 `::red[**텍스트**]` 같은 색상·굵게·링크 등 인라인 문법은 일반 문단과 같은 규칙으로 렌더링한다. -- 관리자 Markdown-first 글쓰기의 오른쪽 블록 설정 패널은 인용·콜아웃·코드 블록·토글 설정과 선택 텍스트 색상 설정을 지원한다. 단일 이미지는 전체 너비(자동)·갤러리 2장 1칸(356px)·갤러리 3장 1칸(235px)·갤러리 3장 2칸(477px)·직접 입력 셀렉트로 표시 너비를 고를 수 있으며 저장 시 이미지 마크다운 뒤에 `{size=숫자}` 옵션을 붙인다. 공개 본문은 이 값을 최대 너비로 적용하고 원본 비율은 유지한다. 직접 입력은 120~1600px 범위로 저장하되 입력 중에는 범위 보정을 즉시 강제하지 않는다. 콜아웃은 제목·아이콘 표시 ON/OFF 토글·아이콘·배경색, 코드 블록은 언어 셀렉트·줄번호 표시 ON/OFF 토글, 토글은 기본 펼침·닫힘 상태를 선언 줄에 저장한다. 콜아웃 아이콘 입력·프리셋은 아이콘 표시가 꺼진 상태에서 흐린 비활성 영역으로 표시하고, 토글을 켠 뒤에만 조작한다. 코드 블록 줄번호는 기본 숨김이며, 켠 경우에만 선언 줄에 `line-numbers`를 저장한다. 일반 텍스트 범위를 선택하면 텍스트 색상 패널이 열리고 회색·파랑·초록·노랑·빨강·보라 인라인 색상을 적용한다. 콜아웃 아이콘은 라이브·공개 화면 모두 왼쪽 상단에 배치하고, 아이콘·제목 헤더 아래에 본문을 줄바꿈해 표시한다. 아이콘 미사용 시 자리 표시자를 남기지 않는다. 인용·콜아웃·토글 본문은 라이브 모드에서 굵게·링크·색상 같은 인라인 문법과 기본 불릿/번호 목록을 표시한다. 라이브 문단에서는 `>` 입력으로 인용, ``` Enter로 코드 블록, `!!!` Enter로 콜아웃을 만들 수 있고, `/표` 또는 `/table` 슬래시 명령으로 기본 3열 표 마크다운을 삽입한다. `/html`은 `:::html`, `/link`는 `:::link`, `/iframe`은 `:::iframe` fenced 블록을 삽입한다. 소스·라이브 모드 모두 텍스트를 선택한 뒤 `Cmd/Ctrl+K`를 누르면 `[선택 텍스트](https://)` 인라인 링크 마크다운을 삽입하고 URL 부분을 선택한다. 소스 textarea의 선택 치환·인라인 감싸기·링크 삽입·줄 변환 계산은 `markdown-source-selection` helper가 담당하고, 라이브 전환 포커스 대상 보정과 코드 펜스 본문 줄 판별은 `markdown-editor-focus` helper가 담당한다. 슬래시 명령의 미디어 모달·마크다운 줄 삽입 적용 계획과 적용 후 에디터 효과 계획은 `markdown-slash-commands` helper가 계산한다. 미디어 선택 모달의 상태·표시 계산, 서버 목록 조회, 업로드 실행과 업로드 후 선택 상태 갱신은 `useAdminMarkdownMediaPicker`가 관리하고, 선택 미디어 삽입 계획과 업로드 입력·응답 정규화는 `markdown-editor-media` helper가 계산한다. 에디터는 선택·업로드 결과의 본문 반영과 실제 포커스·스크롤 실행만 처리한다. 작성/라이브 모드 전환의 pending 포커스 상태와 복원 순서는 `useAdminMarkdownFocusBridge`가 관리한다. 에디터 되돌리기·다시 실행은 `useAdminMarkdownHistory`에서 본문 값과 선택 위치를 함께 복원해 줄 앞 이동을 줄인다. 라이브 모드에서 위·아래 방향키로 인접 블록을 이동하면 커서가 화면 밖으로 벗어날 때 편집 스크롤 영역도 함께 이동한다. 라이브 코드·인용·콜아웃·토글 블록은 맨 위/맨 아래 방향키로 외부 기본 문단을 만들며 빠져나올 수 있고, 인용 첫 글자 앞 Backspace는 일반 문단으로 되돌린다. 한글 등 IME 조합 입력 중에는 줄바꿈 직후 블록 판별이 일시적으로 비어도 마지막 블록 컨텍스트를 유지해 설정 패널이 닫히지 않게 한다. 인용 편집 중 브라우저 자동 목록 보정으로 `>. ` 접두가 섞이면 커밋 시 정리한다. +- 관리자 Markdown-first 글쓰기의 오른쪽 블록 설정 패널은 인용·콜아웃·코드 블록·토글 설정과 선택 텍스트 색상 설정을 지원한다. 단일 이미지는 전체 너비(자동)·갤러리 2장 1칸(356px)·갤러리 3장 1칸(235px)·갤러리 3장 2칸(477px)·직접 입력 셀렉트로 표시 너비를 고를 수 있으며 저장 시 이미지 마크다운 뒤에 `{size=숫자}` 옵션을 붙인다. 공개 본문은 이 값을 최대 너비로 적용하고 원본 비율은 유지한다. 직접 입력은 120~1600px 범위로 저장하되 입력 중에는 범위 보정을 즉시 강제하지 않는다. 콜아웃은 제목·아이콘 표시 ON/OFF 토글·아이콘·배경색, 코드 블록은 언어 셀렉트·줄번호 표시 ON/OFF 토글, 토글은 기본 펼침·닫힘 상태를 선언 줄에 저장한다. 콜아웃 아이콘 입력·프리셋은 아이콘 표시가 꺼진 상태에서 흐린 비활성 영역으로 표시하고, 토글을 켠 뒤에만 조작한다. 코드 블록 줄번호는 기본 숨김이며, 켠 경우에만 선언 줄에 `line-numbers`를 저장한다. 일반 텍스트 범위를 선택하면 텍스트 색상 패널이 열리고 회색·파랑·초록·노랑·빨강·보라 인라인 색상을 적용한다. 콜아웃 아이콘은 라이브·공개 화면 모두 왼쪽 상단에 배치하고, 아이콘·제목 헤더 아래에 본문을 줄바꿈해 표시한다. 아이콘 미사용 시 자리 표시자를 남기지 않는다. 인용·콜아웃·토글 본문은 라이브 모드에서 굵게·링크·색상 같은 인라인 문법과 기본 불릿/번호 목록을 표시한다. 라이브 문단에서는 `>` 입력으로 인용, ``` Enter로 코드 블록, `!!!` Enter로 콜아웃을 만들 수 있고, `/표` 또는 `/table` 슬래시 명령으로 기본 3열 표 마크다운을 삽입한다. `/html`은 `:::html`, `/link`는 `:::link`, `/iframe`은 `:::iframe` fenced 블록을 삽입한다. 소스·라이브 모드 모두 텍스트를 선택한 뒤 `Cmd/Ctrl+K`를 누르면 `[선택 텍스트](https://)` 인라인 링크 마크다운을 삽입하고 URL 부분을 선택한다. 소스 textarea의 선택 치환·인라인 감싸기·링크 삽입·줄 변환 계산은 `markdown-source-selection` helper가 담당하고, 라이브 전환 포커스 대상 보정과 코드 펜스 본문 줄 판별은 `markdown-editor-focus` helper가 담당한다. 슬래시 명령의 미디어 모달·마크다운 줄 삽입 적용 계획과 적용 후 에디터 효과 계획은 `markdown-slash-commands` helper가 계산한다. 미디어 선택 모달의 상태·표시 계산, 서버 목록 조회, 업로드 실행과 업로드 후 선택 상태 갱신은 `useAdminMarkdownMediaPicker`가 관리하고, 선택 미디어 삽입 계획과 업로드 입력·응답 정규화는 `markdown-editor-media` helper가 계산한다. 오른쪽 블록 패널의 미디어·임베드·인용·콜아웃·코드·토글 옵션 줄 교체와 인라인 색상 본문 변경 계산은 `markdown-editor-block-options` helper가 담당한다. 에디터는 선택·업로드·옵션 변경 결과의 본문 반영과 실제 포커스·스크롤 실행만 처리한다. 작성/라이브 모드 전환의 pending 포커스 상태와 복원 순서는 `useAdminMarkdownFocusBridge`가 관리한다. 에디터 되돌리기·다시 실행은 `useAdminMarkdownHistory`에서 본문 값과 선택 위치를 함께 복원해 줄 앞 이동을 줄인다. 라이브 모드에서 위·아래 방향키로 인접 블록을 이동하면 커서가 화면 밖으로 벗어날 때 편집 스크롤 영역도 함께 이동한다. 라이브 코드·인용·콜아웃·토글 블록은 맨 위/맨 아래 방향키로 외부 기본 문단을 만들며 빠져나올 수 있고, 인용 첫 글자 앞 Backspace는 일반 문단으로 되돌린다. 한글 등 IME 조합 입력 중에는 줄바꿈 직후 블록 판별이 일시적으로 비어도 마지막 블록 컨텍스트를 유지해 설정 패널이 닫히지 않게 한다. 인용 편집 중 브라우저 자동 목록 보정으로 `>. ` 접두가 섞이면 커밋 시 정리한다. - 게시물 상세의 오른쪽 사이드바는 데스크톱에서 블로그 소개·Follow 대신 본문 H1~H3 제목 기반 목차를 최상단에 표시한다. 목차는 별도 최대 높이와 내부 스크롤을 두지 않고 전체 목록이 먼저 펼쳐지며, 왼쪽 기준선과 브랜드 컬러 활성 항목 표시선을 둔다. 목차 항목은 최소 24px 높이와 세로 중앙 정렬을 사용하며, 2줄 이상 제목에서는 항목 높이에 맞춰 활성 표시선도 함께 늘어난다. 활성 표시선은 항목의 가상 요소 배경 막대로 그려 텍스트 시작점이 밀리지 않게 한다. 목차 링크는 본문 제목에 부여된 앵커 ID로 부드럽게 이동하며, 고정 상단 헤더 높이와 여백을 반영해 제목이 화면 밖에 걸리지 않게 한다. 본문 스크롤 중에는 현재 제목에 해당하는 목차 항목을 강조하고, 목차 항목이 많으면 오른쪽 사이드바 스크롤이 활성 항목을 따라간다. 본문 제목이 없으면 목차 없음 문구를 표시한다. 오른쪽 사이드바가 본문 아래로 내려가는 모바일 폭에서는 목차를 숨긴다. 게시물 상세에서는 일반 오른쪽 사이드 광고 대신 게시물 사이드 광고 코드를 목차 아래에 표시하고, 왼쪽 사이드바에는 게시물 광고를 표시하지 않는다. 게시물 상세 목차와 게시물 사이드 광고 슬롯은 하단 구분선을 표시하지 않는다. - 제목 우측 공유 버튼을 누르면 게시물 공유 모달을 연다. - 공개 회원 로그인 세션의 회원 ID가 게시물 `author_id`와 같으면 제목 우측 공유 버튼 옆에 수정 아이콘을 표시하며, 클릭 시 `/admin/posts/:id` 편집 화면을 새 탭으로 연다. 별도 관리자 세션만 있거나 비로그인 상태에서는 표시하지 않는다. diff --git a/docs/todo.md b/docs/todo.md index c9f31c1..7fe1d0e 100644 --- a/docs/todo.md +++ b/docs/todo.md @@ -3,7 +3,7 @@ ## v1.11 내부 개선 - 거대 컴포넌트 책임 분리 진행. - - `components/admin/AdminMarkdownEditor.vue`: 라이브 편집 줄 포커스 실행과 블록별 옵션 수정 함수를 단계적으로 composable 또는 하위 컴포넌트로 분리. + - `components/admin/AdminMarkdownEditor.vue`: 라이브 편집 줄 포커스 실행과 남은 블록 이벤트 연결을 단계적으로 composable 또는 하위 컴포넌트로 분리. - 미디어 카탈로그 전환 코드 수명 정리. - 운영 `MEDIA_CATALOG_MODE=database` 안정화 후 `shadow`/`filesystem` 런타임 분기 축소 가능 여부 검토. - fallback은 운영 안정성에 필요하므로 제거 전 reconcile·로그·테스트 기준을 먼저 정리. diff --git a/docs/update.md b/docs/update.md index f52858f..7b0355b 100644 --- a/docs/update.md +++ b/docs/update.md @@ -1,5 +1,11 @@ # 업데이트 이력 +## v1.11.116 + +- 관리자 Markdown 에디터의 이미지·갤러리·임베드·인용·콜아웃·코드·토글 옵션 변경 계산을 `markdown-editor-block-options` helper로 분리. +- 에디터 컴포넌트는 블록 옵션 변경 결과를 줄 범위 교체 계획으로 적용하고, 실제 문자열 조립 책임을 제거. +- 블록 옵션 helper의 미디어 교체, 캡션 사용, 갤러리 이동·추가, fenced 옵션, 인라인 색상 단위 테스트 추가. + ## v1.11.115 - 관리자 Markdown 에디터의 블록 설정 패널 표시 상태·포커스 유지·IME 조합 중 직전 컨텍스트 유지·인라인 색상 패널 우선순위를 `useAdminMarkdownBlockPanel` composable로 분리. diff --git a/lib/markdown-editor-block-options.js b/lib/markdown-editor-block-options.js new file mode 100644 index 0000000..510ffdc --- /dev/null +++ b/lib/markdown-editor-block-options.js @@ -0,0 +1,322 @@ +import { buildCalloutOpenerLine, CALLOUT_BACKGROUND_OPTIONS, QUOTE_BACKGROUND_OPTIONS } from './markdown-callout.js' +import { buildCodeFenceOpener } from './markdown-code-block.js' +import { buildToggleOpenerLine } from './markdown-toggle.js' +import { formatInlineColorMarkdown } from './markdown-inline.js' +import { getMarkdownLineBodyPrefixLength } from './markdown-live-selection.js' +import { getImageDefaultAltLabel, serializeImageMarkdown } from './markdown-image.js' + +/** + * 블록 줄 범위 교체 계획을 만든다. + * @param {Object} block - 대상 블록 + * @param {string[]} replacementLines - 대체 줄 목록 + * @returns {{ startLine: number, endLine: number, replacementLines: string[] }|null} 교체 계획 + */ +const createLineReplacementPlan = (block, replacementLines) => { + if (!block || !Number.isInteger(block.startLine) || !Number.isInteger(block.endLine)) { + return null + } + + return { + startLine: block.startLine, + endLine: block.endLine, + replacementLines + } +} + +/** + * 이미지 목록 기준 미디어 블록 교체 계획을 만든다. + * @param {Object|null} block - 미디어 블록 + * @param {Array} images - 이미지 목록 + * @returns {{ startLine: number, endLine: number, replacementLines: string[] }|null} 교체 계획 + */ +export const createMediaImagesReplacementPlan = (block, images) => { + if (!block || !['image', 'gallery'].includes(block.kind)) { + return null + } + + const safeImages = Array.isArray(images) ? images : [] + + if (block.kind === 'image') { + return createLineReplacementPlan( + block, + safeImages[0] ? [serializeImageMarkdown(safeImages[0])] : [] + ) + } + + if (!safeImages.length) { + return createLineReplacementPlan(block, []) + } + + return createLineReplacementPlan(block, [ + ':::gallery', + ...safeImages.map(serializeImageMarkdown), + ':::' + ]) +} + +/** + * 미디어 이미지 항목 수정 후 교체 계획을 만든다. + * @param {Object|null} block - 미디어 블록 + * @param {number} imageIndex - 이미지 인덱스 + * @param {Object} patch - 이미지 변경값 + * @returns {{ startLine: number, endLine: number, replacementLines: string[] }|null} 교체 계획 + */ +export const createMediaImageUpdatePlan = (block, imageIndex, patch) => { + if (!block || !Array.isArray(block.images) || !block.images[imageIndex]) { + return null + } + + const images = block.images.map((image, index) => index === imageIndex ? { ...image, ...patch } : image) + return createMediaImagesReplacementPlan(block, images) +} + +/** + * 파일명 캡션 사용 여부 변경 patch를 만든다. + * @param {Object|null} image - 이미지 항목 + * @param {boolean} enabled - 파일명 캡션 사용 여부 + * @returns {Object|null} 이미지 patch + */ +export const createMediaUseAltPatch = (image, enabled) => { + if (!image) { + return null + } + + const filename = getImageDefaultAltLabel(image.url) + const patch = { useAlt: enabled } + + if (enabled) { + if (!String(image.caption || '').trim()) { + const legacy = String(image.legacyBracketLabel || '').trim() + + patch.caption = legacy && legacy !== filename ? legacy : filename + } + } else if (String(image.caption || '').trim() === filename) { + patch.caption = '' + } + + return patch +} + +/** + * 갤러리 이미지 순서 변경 계획을 만든다. + * @param {Object|null} block - 갤러리 블록 + * @param {number} imageIndex - 이동할 이미지 인덱스 + * @param {-1|1} direction - 이동 방향 + * @returns {{ startLine: number, endLine: number, replacementLines: string[] }|null} 교체 계획 + */ +export const createGalleryImageMovePlan = (block, imageIndex, direction) => { + if (!block || block.kind !== 'gallery' || !Array.isArray(block.images)) { + return null + } + + const nextIndex = imageIndex + direction + + if (nextIndex < 0 || nextIndex >= block.images.length) { + return null + } + + const images = [...block.images] + const [target] = images.splice(imageIndex, 1) + images.splice(nextIndex, 0, target) + + return createMediaImagesReplacementPlan(block, images) +} + +/** + * 미디어 이미지 삭제 계획을 만든다. + * @param {Object|null} block - 미디어 블록 + * @param {number} imageIndex - 삭제할 이미지 인덱스 + * @returns {{ startLine: number, endLine: number, replacementLines: string[] }|null} 교체 계획 + */ +export const createMediaImageRemovePlan = (block, imageIndex) => { + if (!block || !Array.isArray(block.images)) { + return null + } + + return createMediaImagesReplacementPlan(block, block.images.filter((_, index) => index !== imageIndex)) +} + +/** + * 현재 갤러리에 이미지 추가 계획을 만든다. + * @param {Object|null} block - 갤러리 블록 + * @param {Array} images - 추가 이미지 목록 + * @returns {{ startLine: number, endLine: number, replacementLines: string[] }|null} 교체 계획 + */ +export const createGalleryImagesAppendPlan = (block, images) => { + if (!block || block.kind !== 'gallery') { + return null + } + + return createMediaImagesReplacementPlan(block, [...block.images, ...images]) +} + +/** + * 링크·iframe·HTML 블록 값 교체 계획을 만든다. + * @param {Object|null} block - 임베드 블록 + * @param {string} url - 새 값 + * @returns {{ startLine: number, endLine: number, replacementLines: string[] }|null} 교체 계획 + */ +export const createEmbedUrlReplacementPlan = (block, url) => { + if (!block || !['link', 'iframe', 'html'].includes(block.kind)) { + return null + } + + const trimmed = String(url || '').trim() + return createLineReplacementPlan(block, trimmed ? [`:::${block.kind}`, trimmed, ':::'] : []) +} + +/** + * 인용 배경색 변경 후 전체 Markdown 값을 만든다. + * @param {Object} options - 변경 옵션 + * @param {string} options.value - Markdown 본문 + * @param {Object|null} options.block - 인용 블록 + * @param {string} options.background - 배경색 + * @returns {string|null} 변경된 Markdown 본문 + */ +export const createQuoteBackgroundValue = ({ value, block, background }) => { + if (!block || block.kind !== 'quote') { + return null + } + + const nextBackground = String(background || '').trim() + + if (!QUOTE_BACKGROUND_OPTIONS.includes(nextBackground)) { + return null + } + + const optionLine = `> [!bg=${nextBackground}]` + const nextLines = String(value || '').split('\n') + + if (block.hasQuoteOptions) { + nextLines.splice(block.startLine, 1, optionLine) + } else { + nextLines.splice(block.startLine, 0, optionLine) + } + + return nextLines.join('\n') +} + +/** + * 콜아웃 옵션 교체 계획을 만든다. + * @param {Object|null} block - 콜아웃 블록 + * @param {Object} patch - 변경 옵션 + * @returns {{ startLine: number, endLine: number, replacementLines: string[] }|null} 교체 계획 + */ +export const createCalloutOptionsReplacementPlan = (block, patch = {}) => { + if (!block || block.kind !== 'callout') { + return null + } + + const nextBackground = CALLOUT_BACKGROUND_OPTIONS.includes(patch.calloutBackground) + ? patch.calloutBackground + : block.calloutBackground + const nextLine = buildCalloutOpenerLine({ + calloutEmojiEnabled: patch.calloutEmojiEnabled ?? block.calloutEmojiEnabled, + calloutEmoji: patch.calloutEmoji ?? block.calloutEmoji, + calloutBackground: nextBackground, + title: patch.title ?? block.title + }) + + return createLineReplacementPlan(block, [nextLine]) +} + +/** + * 코드 옵션 교체 계획을 만든다. + * @param {Object|null} block - 코드 블록 + * @param {Object} patch - 변경 옵션 + * @returns {{ startLine: number, endLine: number, replacementLines: string[] }|null} 교체 계획 + */ +export const createCodeOptionsReplacementPlan = (block, patch = {}) => { + if (!block || block.kind !== 'code') { + return null + } + + return createLineReplacementPlan(block, [ + buildCodeFenceOpener({ + language: patch.language ?? block.language, + showLineNumbers: patch.showLineNumbers ?? block.showLineNumbers + }) + ]) +} + +/** + * 토글 옵션 교체 계획을 만든다. + * @param {Object|null} block - 토글 블록 + * @param {Object} patch - 변경 옵션 + * @returns {{ startLine: number, endLine: number, replacementLines: string[] }|null} 교체 계획 + */ +export const createToggleOptionsReplacementPlan = (block, patch = {}) => { + if (!block || block.kind !== 'toggle') { + return null + } + + return createLineReplacementPlan(block, [ + buildToggleOpenerLine({ + title: block.title, + defaultOpen: patch.defaultOpen ?? block.defaultOpen + }) + ]) +} + +/** + * 소스 모드 인라인 색상 적용 결과를 만든다. + * @param {Object} options - 적용 옵션 + * @param {string} options.value - Markdown 본문 + * @param {Object|null} options.context - 인라인 색상 컨텍스트 + * @param {string} options.color - 색상 이름 + * @returns {{ value: string, selectionStart: number, selectionEnd: number }|null} 적용 결과 + */ +export const createSourceInlineColorValue = ({ value, context, color }) => { + if (!context || context.kind !== 'inline-color' || context.mode !== 'source') { + return null + } + + const source = String(value || '') + const start = Math.max(0, Math.min(context.start ?? 0, source.length)) + const end = Math.max(start, Math.min(context.end ?? start, source.length)) + const selectedText = source.slice(start, end) + const replacement = formatInlineColorMarkdown(color, selectedText) + const nextOffset = start + replacement.length + + return { + value: `${source.slice(0, start)}${replacement}${source.slice(end)}`, + selectionStart: nextOffset, + selectionEnd: nextOffset + } +} + +/** + * 라이브 모드 인라인 색상 적용 결과를 만든다. + * @param {Object} options - 적용 옵션 + * @param {string} options.value - Markdown 본문 + * @param {Object|null} options.context - 인라인 색상 컨텍스트 + * @param {string} options.color - 색상 이름 + * @returns {{ value: string, focusLine: number, focusOffset: number }|null} 적용 결과 + */ +export const createLiveInlineColorValue = ({ value, context, color }) => { + if (!context || context.kind !== 'inline-color' || context.mode !== 'live' || !Number.isInteger(context.sourceLine)) { + return null + } + + const lines = String(value || '').split('\n') + const line = lines[context.sourceLine] + + if (typeof line !== 'string') { + return null + } + + const prefixLength = getMarkdownLineBodyPrefixLength(line, context.bodyText || '') + const absoluteStart = prefixLength + Math.max(0, context.startOffset ?? 0) + const absoluteEnd = prefixLength + Math.max(context.startOffset ?? 0, context.endOffset ?? 0) + const selectedText = line.slice(absoluteStart, absoluteEnd) + const replacement = formatInlineColorMarkdown(color, selectedText) + const focusOffset = (context.startOffset ?? 0) + selectedText.length + + lines.splice(context.sourceLine, 1, `${line.slice(0, absoluteStart)}${replacement}${line.slice(absoluteEnd)}`) + + return { + value: lines.join('\n'), + focusLine: context.sourceLine, + focusOffset + } +} diff --git a/package-lock.json b/package-lock.json index 007f4d8..6aec1a5 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "sori.studio", - "version": "1.11.115", + "version": "1.11.116", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "sori.studio", - "version": "1.11.115", + "version": "1.11.116", "hasInstallScript": true, "dependencies": { "@nuxtjs/tailwindcss": "^6.14.0", diff --git a/package.json b/package.json index e9aeac7..5bc498b 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "sori.studio", - "version": "1.11.115", + "version": "1.11.116", "private": true, "type": "module", "imports": { diff --git a/tests/markdown-editor-block-options.test.js b/tests/markdown-editor-block-options.test.js new file mode 100644 index 0000000..dd2ccdb --- /dev/null +++ b/tests/markdown-editor-block-options.test.js @@ -0,0 +1,230 @@ +import assert from 'node:assert/strict' +import test from 'node:test' +import { + createCalloutOptionsReplacementPlan, + createCodeOptionsReplacementPlan, + createEmbedUrlReplacementPlan, + createGalleryImageMovePlan, + createGalleryImagesAppendPlan, + createLiveInlineColorValue, + createMediaImageRemovePlan, + createMediaImagesReplacementPlan, + createMediaImageUpdatePlan, + createMediaUseAltPatch, + createQuoteBackgroundValue, + createSourceInlineColorValue, + createToggleOptionsReplacementPlan +} from '../lib/markdown-editor-block-options.js' + +const imageBlock = { + kind: 'image', + startLine: 2, + endLine: 2, + images: [{ + url: '/uploads/one.png', + caption: '', + useAlt: false, + width: 'regular', + pixelWidth: null + }] +} + +const galleryBlock = { + kind: 'gallery', + startLine: 1, + endLine: 4, + images: [ + { url: '/uploads/one.png', caption: '', useAlt: false, width: 'regular', pixelWidth: null }, + { url: '/uploads/two.png', caption: '둘', useAlt: true, width: 'regular', pixelWidth: 235 } + ] +} + +test('단일 이미지와 갤러리 이미지 목록 교체 계획을 만든다', () => { + assert.deepEqual(createMediaImagesReplacementPlan(imageBlock, []), { + startLine: 2, + endLine: 2, + replacementLines: [] + }) + + assert.deepEqual(createMediaImagesReplacementPlan(galleryBlock, galleryBlock.images), { + startLine: 1, + endLine: 4, + replacementLines: [ + ':::gallery', + '![](/uploads/one.png)', + '![](/uploads/two.png "둘"){size=235}', + ':::' + ] + }) +}) + +test('미디어 이미지 수정과 삭제 계획을 만든다', () => { + assert.deepEqual(createMediaImageUpdatePlan(imageBlock, 0, { caption: '캡션', useAlt: true }), { + startLine: 2, + endLine: 2, + replacementLines: ['![](/uploads/one.png "캡션")'] + }) + + assert.deepEqual(createMediaImageRemovePlan(galleryBlock, 1), { + startLine: 1, + endLine: 4, + replacementLines: [ + ':::gallery', + '![](/uploads/one.png)', + ':::' + ] + }) +}) + +test('파일명 캡션 사용 patch를 만든다', () => { + assert.deepEqual(createMediaUseAltPatch({ + url: '/uploads/posts/2026/07/sample-car.png', + caption: '', + legacyBracketLabel: '' + }, true), { + useAlt: true, + caption: 'sample-car.png' + }) + + assert.deepEqual(createMediaUseAltPatch({ + url: '/uploads/posts/2026/07/sample-car.png', + caption: 'sample-car.png', + legacyBracketLabel: '' + }, false), { + useAlt: false, + caption: '' + }) +}) + +test('갤러리 이미지 이동과 추가 계획을 만든다', () => { + assert.equal(createGalleryImageMovePlan(galleryBlock, 0, -1), null) + assert.deepEqual(createGalleryImageMovePlan(galleryBlock, 0, 1), { + startLine: 1, + endLine: 4, + replacementLines: [ + ':::gallery', + '![](/uploads/two.png "둘"){size=235}', + '![](/uploads/one.png)', + ':::' + ] + }) + + assert.deepEqual(createGalleryImagesAppendPlan(galleryBlock, [{ url: '/uploads/three.png' }]), { + startLine: 1, + endLine: 4, + replacementLines: [ + ':::gallery', + '![](/uploads/one.png)', + '![](/uploads/two.png "둘"){size=235}', + '![](/uploads/three.png)', + ':::' + ] + }) +}) + +test('임베드 블록 값 교체 계획을 만든다', () => { + const block = { kind: 'iframe', startLine: 3, endLine: 5 } + + assert.deepEqual(createEmbedUrlReplacementPlan(block, ' https://example.com '), { + startLine: 3, + endLine: 5, + replacementLines: [':::iframe', 'https://example.com', ':::'] + }) + + assert.deepEqual(createEmbedUrlReplacementPlan(block, ' '), { + startLine: 3, + endLine: 5, + replacementLines: [] + }) +}) + +test('인용 배경색은 옵션 줄을 삽입하거나 교체한다', () => { + assert.equal(createQuoteBackgroundValue({ + value: '> 인용', + block: { kind: 'quote', startLine: 0, endLine: 0, hasQuoteOptions: false }, + background: 'blue' + }), '> [!bg=blue]\n> 인용') + + assert.equal(createQuoteBackgroundValue({ + value: '> [!bg=gray]\n> 인용', + block: { kind: 'quote', startLine: 0, endLine: 1, hasQuoteOptions: true }, + background: 'purple' + }), '> [!bg=purple]\n> 인용') +}) + +test('콜아웃·코드·토글 선언 줄 교체 계획을 만든다', () => { + assert.deepEqual(createCalloutOptionsReplacementPlan({ + kind: 'callout', + startLine: 1, + endLine: 3, + calloutEmojiEnabled: false, + calloutEmoji: '💡', + calloutBackground: 'gray', + title: '기존' + }, { + calloutEmojiEnabled: true, + calloutBackground: 'blue', + title: '주의' + }), { + startLine: 1, + endLine: 3, + replacementLines: [':::callout emoji=💡 bg=blue title=주의'] + }) + + assert.deepEqual(createCodeOptionsReplacementPlan({ + kind: 'code', + startLine: 5, + endLine: 7, + language: 'javascript', + showLineNumbers: false + }, { + showLineNumbers: true + }), { + startLine: 5, + endLine: 7, + replacementLines: ['```javascript line-numbers'] + }) + + assert.deepEqual(createToggleOptionsReplacementPlan({ + kind: 'toggle', + startLine: 9, + endLine: 11, + title: '더 보기', + defaultOpen: false + }, { + defaultOpen: true + }), { + startLine: 9, + endLine: 11, + replacementLines: [':::toggle open 더 보기'] + }) +}) + +test('소스와 라이브 인라인 색상 적용 결과를 만든다', () => { + assert.deepEqual(createSourceInlineColorValue({ + value: 'hello world', + context: { kind: 'inline-color', mode: 'source', start: 6, end: 11 }, + color: 'red' + }), { + value: 'hello ::red[world]', + selectionStart: 18, + selectionEnd: 18 + }) + + assert.deepEqual(createLiveInlineColorValue({ + value: '- 안녕하세요', + context: { + kind: 'inline-color', + mode: 'live', + sourceLine: 0, + bodyText: '안녕하세요', + startOffset: 0, + endOffset: 2 + }, + color: 'blue' + }), { + value: '- ::blue[안녕]하세요', + focusLine: 0, + focusOffset: 2 + }) +})