-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmarkdown-picture.ts
More file actions
222 lines (190 loc) · 8.2 KB
/
Copy pathmarkdown-picture.ts
File metadata and controls
222 lines (190 loc) · 8.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
import type MarkdownIt from "markdown-it";
import type { RenderRule } from "markdown-it/lib/renderer.mjs";
import { existsSync } from "fs";
import { join, dirname } from "path";
/**
* 이미지 경로에서 확장자를 변경합니다
*/
function changeExtension(src: string, newExt: string): string {
const lastDotIndex = src.lastIndexOf(".");
if (lastDotIndex === -1) return src;
return src.substring(0, lastDotIndex) + "." + newExt;
}
/**
* 절대 경로로 변환하여 파일 존재 여부 확인
*/
function fileExists(relativePath: string, markdownFilePath: string): boolean {
try {
// VitePress rewrites로 인해 env.path가 /posts/... 형태로 오지만
// 실제 파일은 /contents/posts/... 에 있음
// markdownFilePath를 실제 파일 시스템 경로로 변환
let actualPath = markdownFilePath;
if (
markdownFilePath.includes("/posts/") &&
!markdownFilePath.includes("/contents/posts/")
) {
actualPath = markdownFilePath.replace("/posts/", "/contents/posts/");
}
if (
markdownFilePath.includes("/projects/") &&
!markdownFilePath.includes("/contents/projects/")
) {
actualPath = markdownFilePath.replace("/projects/", "/contents/projects/");
}
const dir = dirname(actualPath);
const absolutePath = join(dir, relativePath);
return existsSync(absolutePath);
} catch {
return false;
}
}
/**
* img 태그를 picture 태그로 변환하는 헬퍼 함수
*/
function convertImgToPicture(
src: string,
alt: string | null,
markdownPath: string,
additionalAttrs: string = "",
): string {
const safeAlt = alt || "";
let safeAttrs = additionalAttrs && additionalAttrs.trim() ? " " + additionalAttrs.trim() : "";
let pictureStyle = "";
// width 속성 처리: 퍼센트나 단위가 있는 경우 picture의 스타일로 이동하여 중첩 계산 방지
const widthMatch = /width=["']([^"']+)["']/i.exec(safeAttrs);
if (widthMatch) {
const widthVal = widthMatch[1];
if (widthVal.includes("%") || widthVal.includes("px")) {
pictureStyle = `width: ${widthVal}; display: inline-block;`;
// img 태그에서는 원본 width 속성을 제거하고 내부적으로 100%를 가지도록 함
safeAttrs = safeAttrs.replace(/width=["'][^"']*["']/gi, "").trim();
if (safeAttrs.includes("style=\"")) {
safeAttrs = safeAttrs.replace(/style=["']([^"']*)["']/i, (m, s) => {
const baseStyle = s.trim();
const separator = baseStyle && !baseStyle.endsWith(";") ? ";" : "";
return `style="${baseStyle}${separator} width: 100%;"`;
});
} else {
safeAttrs += " style=\"width: 100%;\"";
}
} else {
// 숫자만 있는 경우(HTML5 표준) px 제거 로직 유지
safeAttrs = safeAttrs.replace(/width="(\d+)(px)?"/gi, "width=\"$1\"");
}
}
// 외부 URL이거나 svg, gif는 picture 태그로 변환하지 않음
if (src.startsWith("http") || src.endsWith(".svg") || src.endsWith(".gif")) {
return `<img src="${src}" alt="${safeAlt}"${safeAttrs ? " " + safeAttrs : ""} loading="lazy" />`;
}
// 이미지 포맷별 경로 생성
const srcWebp = changeExtension(src, "webp");
const srcAvif = changeExtension(src, "avif");
const srcJpeg = changeExtension(src, "jpeg");
// 실제로 존재하는 파일만 source로 추가
const sources: string[] = [];
// AVIF (최우선)
if (fileExists(srcAvif, markdownPath)) {
sources.push(`<source srcset="${srcAvif}" type="image/avif" />`);
}
// WebP (차선)
if (fileExists(srcWebp, markdownPath)) {
sources.push(`<source srcset="${srcWebp}" type="image/webp" />`);
}
// JPEG (폴백)
if (fileExists(srcJpeg, markdownPath)) {
sources.push(`<source srcset="${srcJpeg}" type="image/jpeg" />`);
}
// 변환된 이미지가 없으면 원본만 사용
if (sources.length === 0) {
return `<img src="${src}" alt="${safeAlt}"${safeAttrs ? " " + safeAttrs : ""} loading="lazy" />`;
}
// picture 태그 생성 (원본을 최종 fallback으로 사용)
const pictureAttr = pictureStyle ? ` style="${pictureStyle}"` : "";
return `<picture${pictureAttr}>
${sources.join("\n ")}
<img src="${src}" alt="${safeAlt}"${safeAttrs ? " " + safeAttrs : ""} loading="lazy" />
</picture>`;
}
/**
* HTML 문자열에서 img 태그를 찾아서 picture 태그로 변환
*/
function processHtmlImages(html: string, markdownPath: string): string {
// <img> 태그를 찾는 정규식 (src와 alt 속성 추출)
const imgRegex = /<img\s+([^>]*?)\/?>/gi;
return html.replace(imgRegex, (match, attrs) => {
if (!attrs || typeof attrs !== "string") return match;
// src 속성 추출
const srcMatch = /src=["']([^"']+)["']/i.exec(attrs);
if (!srcMatch) return match;
const src = srcMatch[1];
// alt 속성 추출
const altMatch = /alt=["']([^"']*)["']/i.exec(attrs);
const alt = altMatch ? altMatch[1] : "";
// src와 alt를 제외한 나머지 속성들 추출
let remainingAttrs = attrs
.replace(/src=["'][^"']*["']/gi, "")
.replace(/alt=["'][^"']*["']/gi, "")
.replace(/loading=["'][^"']*["']/gi, "") // loading은 우리가 추가할 것이므로 제거
.replace(/\s+/g, " ") // 중복 공백 제거
.trim();
// 속성이 비어있거나 공백만 있으면 빈 문자열로
if (!remainingAttrs || /^\s*$/.test(remainingAttrs)) {
remainingAttrs = "";
}
return convertImgToPicture(src, alt, markdownPath, remainingAttrs);
});
}
/**
* 마크다운의 이미지를 picture 태그로 변환하는 플러그인
*/
export function markdownPicturePlugin(md: MarkdownIt) {
const defaultRender: RenderRule =
md.renderer.rules.image ||
((tokens, idx, options, env, self) => {
return self.renderToken(tokens, idx, options);
});
// 1. markdown 이미지 () 처리
md.renderer.rules.image = (tokens, idx, options, env, self) => {
const token = tokens[idx];
const srcIndex = token.attrIndex("src");
const altIndex = token.attrIndex("alt");
if (srcIndex < 0) {
return defaultRender(tokens, idx, options, env, self);
}
const src = token.attrs![srcIndex][1];
const alt = altIndex >= 0 ? token.attrs![altIndex][1] : token.content || "";
const markdownPath = env.path || "";
// src, alt를 제외한 나머지 속성들 추출 (width, height 등)
const additionalAttrs = token.attrs!
.filter(([name]) => name !== "src" && name !== "alt")
.map(([name, value]) => `${name}="${value}"`)
.join(" ");
return convertImgToPicture(src, alt, markdownPath, additionalAttrs);
};
// 2. HTML inline 이미지 (<img>) 처리
const defaultHtmlInline =
md.renderer.rules.html_inline || md.renderer.renderToken.bind(md.renderer);
md.renderer.rules.html_inline = (tokens, idx, options, env, self) => {
const token = tokens[idx];
const content = token.content;
const markdownPath = env.path || "";
// img 태그가 있는 경우에만 처리
if (content.includes("<img")) {
return processHtmlImages(content, markdownPath);
}
return defaultHtmlInline(tokens, idx, options, env, self);
};
// 3. HTML block 이미지 처리
const defaultHtmlBlock =
md.renderer.rules.html_block || md.renderer.renderToken.bind(md.renderer);
md.renderer.rules.html_block = (tokens, idx, options, env, self) => {
const token = tokens[idx];
const content = token.content;
const markdownPath = env.path || "";
// img 태그가 있는 경우에만 처리
if (content.includes("<img")) {
return processHtmlImages(content, markdownPath);
}
return defaultHtmlBlock(tokens, idx, options, env, self);
};
}