@zhenryx/react-editor 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs ADDED
@@ -0,0 +1,2890 @@
1
+ 'use client';
2
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
+ let react = require("react");
4
+ let react_jsx_runtime = require("react/jsx-runtime");
5
+ // src/html-to-markdown.ts
6
+ /**
7
+ * contentEditable HTML → Markdown(2026-11-16)
8
+ *
9
+ * 普通编辑器只做 Markdown 能表达的能力(标题 / 加粗 / 斜体 / 删除线 / 列表 /
10
+ * 引用 / 代码块 / 链接 / 图片 / 表格 / 分割线),因此转换是可逆的:
11
+ * 普通编辑器读入时用 renderMarkdown(),保存时用本文件转回 Markdown。
12
+ */
13
+ function escapeAttr(value) {
14
+ return value.replace(/"/g, "&quot;").replace(/</g, "&lt;");
15
+ }
16
+ function safeStyle(raw) {
17
+ const allowed = /* @__PURE__ */ new Set([
18
+ "color",
19
+ "background-color",
20
+ "text-align",
21
+ "display"
22
+ ]);
23
+ const values = [];
24
+ for (const part of String(raw || "").split(";")) {
25
+ const index = part.indexOf(":");
26
+ if (index < 0) continue;
27
+ const prop = part.slice(0, index).trim().toLowerCase();
28
+ const value = part.slice(index + 1).trim();
29
+ if (!allowed.has(prop) || !value) continue;
30
+ if (prop === "text-align" && !/^(left|center|right|justify)$/i.test(value)) continue;
31
+ if (prop === "display" && !/^(inline|block)$/i.test(value)) continue;
32
+ if (prop !== "text-align" && prop !== "display" && !/^(#[0-9a-f]{3,8}|rgba?\([\d\s.,%]+\)|[a-z]{3,24})$/i.test(value)) continue;
33
+ values.push(`${prop}: ${value}`);
34
+ }
35
+ return values.join("; ");
36
+ }
37
+ function safeMediaUrl(raw) {
38
+ const url = raw.trim();
39
+ return /^(https?:\/\/|\/|\.\.?\/)/i.test(url) ? url : "";
40
+ }
41
+ function inlineToMd(node) {
42
+ if (node.nodeType === Node.TEXT_NODE) return node.nodeValue || "";
43
+ if (node.nodeType !== Node.ELEMENT_NODE) return "";
44
+ const el = node;
45
+ const inner = () => Array.from(el.childNodes).map(inlineToMd).join("");
46
+ if (el.classList.contains("katex") || el.classList.contains("katex-display")) {
47
+ const annotation = el.querySelector("annotation[encoding=\"application/x-tex\"]")?.textContent?.trim() || "";
48
+ if (annotation) return el.classList.contains("katex-display") || Boolean(el.closest(".katex-display")) ? `\n\n$$${annotation}$$\n\n` : `$${annotation}$`;
49
+ }
50
+ switch (el.tagName) {
51
+ case "BR": return "\n";
52
+ case "STRONG":
53
+ case "B": return `**${inner()}**`;
54
+ case "EM":
55
+ case "I": return `*${inner()}*`;
56
+ case "DEL":
57
+ case "S":
58
+ case "STRIKE": return `~~${inner()}~~`;
59
+ case "U": return `<u>${inner()}</u>`;
60
+ case "SPAN": {
61
+ const style = safeStyle(el.getAttribute("style") || "");
62
+ return style ? `<span style="${style}">${inner()}</span>` : inner();
63
+ }
64
+ case "FONT": {
65
+ const color = el.getAttribute("color") || "";
66
+ const style = safeStyle(color ? `color: ${color}` : "");
67
+ return style ? `<span style="${style}">${inner()}</span>` : inner();
68
+ }
69
+ case "VIDEO": {
70
+ const src = safeMediaUrl(el.getAttribute("src") || "");
71
+ return src ? `<video src="${escapeAttr(src)}" controls></video>` : "";
72
+ }
73
+ case "CODE": return el.closest("pre") ? inner() : `\`${inner()}\``;
74
+ case "A": {
75
+ const href = el.getAttribute("href") || "";
76
+ return href ? `[${inner()}](${href})` : inner();
77
+ }
78
+ case "IMG": {
79
+ const src = el.getAttribute("src") || "";
80
+ return src ? `![${el.getAttribute("alt") || ""}](${src})` : "";
81
+ }
82
+ case "UL":
83
+ case "OL": return `\n\n${listToMd(el)}`;
84
+ case "P":
85
+ case "DIV": return `\n\n${inner()}\n\n`;
86
+ default: return inner();
87
+ }
88
+ }
89
+ function listToMd(list, depth = 0) {
90
+ const ordered = list.tagName === "OL";
91
+ let index = Number(list.getAttribute("start") || "1") || 1;
92
+ const lines = [];
93
+ for (const li of Array.from(list.children)) {
94
+ if (!(li instanceof HTMLElement) || li.tagName !== "LI") continue;
95
+ const first = li.firstElementChild;
96
+ const task = first instanceof HTMLInputElement && first.type === "checkbox" ? first : null;
97
+ let inline = "";
98
+ const nested = [];
99
+ for (const child of Array.from(li.childNodes)) {
100
+ if (child.nodeType === Node.ELEMENT_NODE) {
101
+ const el = child;
102
+ if (el.tagName === "UL" || el.tagName === "OL") {
103
+ nested.push(listToMd(el, depth + 1));
104
+ continue;
105
+ }
106
+ if (el instanceof HTMLInputElement && el.type === "checkbox") continue;
107
+ }
108
+ inline += inlineToMd(child);
109
+ }
110
+ const marker = ordered ? `${index++}. ` : "- ";
111
+ let content = inline.trim();
112
+ if (task) content = `[${task.checked ? "x" : " "}] ${content}`;
113
+ lines.push(`${" ".repeat(depth)}${marker}${content}`);
114
+ if (nested.length) lines.push(...nested);
115
+ }
116
+ return lines.join("\n");
117
+ }
118
+ function tableToMd(table) {
119
+ const rows = Array.from(table.querySelectorAll("tr")).map((row) => Array.from(row.children).filter((cell) => cell.tagName === "TH" || cell.tagName === "TD").map((cell) => inlineToMd(cell).replace(/\s+/g, " ").trim().replace(/\|/g, "\\|"))).filter((row) => row.length);
120
+ if (!rows.length) return "";
121
+ const width = Math.max(...rows.map((row) => row.length));
122
+ const pad = (row) => [...row, ...Array(width - row.length).fill("")];
123
+ const [head, ...body] = rows.map(pad);
124
+ return [
125
+ `| ${head.join(" | ")} |`,
126
+ `| ${head.map(() => "---").join(" | ")} |`,
127
+ ...body.map((row) => `| ${row.join(" | ")} |`)
128
+ ].join("\n");
129
+ }
130
+ function preToMd(pre, langOverride = "") {
131
+ const code = pre.querySelector("code");
132
+ const text = (code || pre).textContent || "";
133
+ const lang = langOverride || code?.className.match(/language-([\w-]+)/)?.[1] || "";
134
+ const fence = text.includes("```") ? "~~~" : "```";
135
+ return `\n\n${fence}${lang}\n${text.replace(/\n$/, "")}\n${fence}\n\n`;
136
+ }
137
+ function blockToMd(el) {
138
+ switch (el.tagName) {
139
+ case "H1":
140
+ case "H2":
141
+ case "H3":
142
+ case "H4":
143
+ case "H5":
144
+ case "H6": {
145
+ const level = Number(el.tagName.slice(1));
146
+ return `\n\n${"#".repeat(level)} ${inlineToMd(el).trim()}\n\n`;
147
+ }
148
+ case "P":
149
+ case "DIV": {
150
+ if (Array.from(el.children).some((child) => /^(P|DIV|H[1-6]|UL|OL|LI|BLOCKQUOTE|PRE|TABLE|HR)$/.test(child.tagName))) return Array.from(el.childNodes).map(nodeToMd).join("");
151
+ const content = inlineToMd(el).trim();
152
+ const align = (el.style.textAlign || "").toLowerCase();
153
+ if (/^(left|center|right|justify)$/.test(align) && content) return `\n\n<span style="display: block; text-align: ${align}">${content}</span>\n\n`;
154
+ return `\n\n${content}\n\n`;
155
+ }
156
+ case "UL":
157
+ case "OL": return `\n\n${listToMd(el)}\n\n`;
158
+ case "BLOCKQUOTE": return `\n\n${Array.from(el.childNodes).map(nodeToMd).join("").replace(/\n{3,}/g, "\n\n").trim().split("\n").map((line) => line ? `> ${line}` : ">").join("\n")}\n\n`;
159
+ case "PRE": return preToMd(el);
160
+ case "TABLE": return `\n\n${tableToMd(el)}\n\n`;
161
+ case "HR": return "\n\n---\n\n";
162
+ default: return inlineToMd(el);
163
+ }
164
+ }
165
+ function nodeToMd(node) {
166
+ if (node.nodeType === Node.TEXT_NODE) return node.nodeValue || "";
167
+ if (node.nodeType !== Node.ELEMENT_NODE) return "";
168
+ const el = node;
169
+ if (el.classList.contains("katex-display")) {
170
+ const annotation = el.querySelector("annotation[encoding=\"application/x-tex\"]")?.textContent?.trim() || "";
171
+ if (annotation) return `\n\n$$${annotation}$$\n\n`;
172
+ }
173
+ if (el.classList.contains("kb-code")) {
174
+ const pre = el.querySelector("pre");
175
+ if (pre) return preToMd(pre, el.querySelector(".kb-code-lang")?.textContent?.trim() || "");
176
+ }
177
+ if (/^(P|DIV|H[1-6]|UL|OL|BLOCKQUOTE|PRE|TABLE|HR)$/.test(el.tagName)) return blockToMd(el);
178
+ return inlineToMd(el);
179
+ }
180
+ /** contentEditable 的 innerHTML → Markdown */
181
+ function htmlToMarkdown(html) {
182
+ if (!html) return "";
183
+ const root = document.createElement("div");
184
+ root.innerHTML = html;
185
+ return Array.from(root.childNodes).map(nodeToMd).join("").replace(new RegExp(String.fromCharCode(160), "g"), " ").replace(/[ \t]+\n/g, "\n").replace(/\n{3,}/g, "\n\n").trim();
186
+ }
187
+ function safeRichHref(raw) {
188
+ const url = raw.trim();
189
+ if (!url) return "";
190
+ if (/^(https?:\/\/|mailto:|#|\/)/i.test(url)) return escapeAttr(url);
191
+ if (/^\.\.?\//.test(url)) return escapeAttr(url);
192
+ return "";
193
+ }
194
+ // src/default-render.ts
195
+ function defaultRenderMarkdown(markdown) {
196
+ return markdown.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").split(/\n{2,}/).map((block) => `<p>${block.replace(/\n/g, "<br>")}</p>`).join("");
197
+ }
198
+ // src/icons.tsx
199
+ const EditorIcons = {
200
+ undo: /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("svg", {
201
+ width: "16",
202
+ height: "16",
203
+ viewBox: "0 0 24 24",
204
+ fill: "none",
205
+ stroke: "currentColor",
206
+ strokeWidth: "1.8",
207
+ strokeLinecap: "round",
208
+ strokeLinejoin: "round",
209
+ "aria-hidden": "true",
210
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("path", { d: "M9 7 4.5 11.5 9 16" }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("path", { d: "M5 11.5h9a5 5 0 0 1 0 10h-2" })]
211
+ }),
212
+ redo: /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("svg", {
213
+ width: "16",
214
+ height: "16",
215
+ viewBox: "0 0 24 24",
216
+ fill: "none",
217
+ stroke: "currentColor",
218
+ strokeWidth: "1.8",
219
+ strokeLinecap: "round",
220
+ strokeLinejoin: "round",
221
+ "aria-hidden": "true",
222
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("path", { d: "m15 7 4.5 4.5L15 16" }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("path", { d: "M19 11.5h-9a5 5 0 0 0 0 10h2" })]
223
+ }),
224
+ format: /* @__PURE__ */ (0, react_jsx_runtime.jsx)("svg", {
225
+ width: "16",
226
+ height: "16",
227
+ viewBox: "0 0 24 24",
228
+ fill: "none",
229
+ stroke: "currentColor",
230
+ strokeWidth: "1.8",
231
+ strokeLinecap: "round",
232
+ strokeLinejoin: "round",
233
+ "aria-hidden": "true",
234
+ children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)("path", { d: "M5 5v14M15 5v14M5 12h10" })
235
+ }),
236
+ heading: /* @__PURE__ */ (0, react_jsx_runtime.jsx)("svg", {
237
+ width: "16",
238
+ height: "16",
239
+ viewBox: "0 0 24 24",
240
+ fill: "none",
241
+ stroke: "currentColor",
242
+ strokeWidth: "1.9",
243
+ strokeLinecap: "round",
244
+ "aria-hidden": "true",
245
+ children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)("path", { d: "M5 5v14M19 5v14M5 12h14" })
246
+ }),
247
+ doc: /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("svg", {
248
+ width: "16",
249
+ height: "16",
250
+ viewBox: "0 0 24 24",
251
+ fill: "none",
252
+ stroke: "currentColor",
253
+ strokeWidth: "1.7",
254
+ strokeLinecap: "round",
255
+ strokeLinejoin: "round",
256
+ "aria-hidden": "true",
257
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("path", { d: "M6.5 3H14l4.5 4.5V20a1 1 0 0 1-1 1H6.5a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1Z" }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("path", { d: "M14 3v4.5h4.5M8.5 12h7M8.5 16h4.5" })]
258
+ }),
259
+ split: /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("svg", {
260
+ width: "16",
261
+ height: "16",
262
+ viewBox: "0 0 24 24",
263
+ fill: "none",
264
+ stroke: "currentColor",
265
+ strokeWidth: "1.7",
266
+ strokeLinecap: "round",
267
+ strokeLinejoin: "round",
268
+ "aria-hidden": "true",
269
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("rect", {
270
+ x: "3",
271
+ y: "4",
272
+ width: "18",
273
+ height: "16",
274
+ rx: "2"
275
+ }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("path", { d: "M12 4v16" })]
276
+ }),
277
+ preview: /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("svg", {
278
+ width: "16",
279
+ height: "16",
280
+ viewBox: "0 0 24 24",
281
+ fill: "none",
282
+ stroke: "currentColor",
283
+ strokeWidth: "1.7",
284
+ strokeLinecap: "round",
285
+ strokeLinejoin: "round",
286
+ "aria-hidden": "true",
287
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("rect", {
288
+ x: "3",
289
+ y: "4",
290
+ width: "18",
291
+ height: "16",
292
+ rx: "2"
293
+ }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("path", { d: "M7 9h10M7 13h7M7 17h5" })]
294
+ }),
295
+ switchEditor: /* @__PURE__ */ (0, react_jsx_runtime.jsx)("svg", {
296
+ width: "16",
297
+ height: "16",
298
+ viewBox: "0 0 24 24",
299
+ fill: "none",
300
+ stroke: "currentColor",
301
+ strokeWidth: "1.7",
302
+ strokeLinecap: "round",
303
+ strokeLinejoin: "round",
304
+ "aria-hidden": "true",
305
+ children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)("path", { d: "M4 7h13M14 4l3 3-3 3M20 17H7M10 14l-3 3 3 3" })
306
+ }),
307
+ save: /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("svg", {
308
+ width: "16",
309
+ height: "16",
310
+ viewBox: "0 0 24 24",
311
+ fill: "none",
312
+ stroke: "currentColor",
313
+ strokeWidth: "1.7",
314
+ strokeLinecap: "round",
315
+ strokeLinejoin: "round",
316
+ "aria-hidden": "true",
317
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("path", { d: "M5 4h11l3 3v13H5z" }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("path", { d: "M8 4v5h7V4M8 20v-6h8v6" })]
318
+ }),
319
+ toc: /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("svg", {
320
+ width: "16",
321
+ height: "16",
322
+ viewBox: "0 0 24 24",
323
+ fill: "none",
324
+ stroke: "currentColor",
325
+ strokeWidth: "1.7",
326
+ strokeLinecap: "round",
327
+ "aria-hidden": "true",
328
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("path", { d: "M5 6h14M5 12h9M5 18h6" }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("path", {
329
+ d: "M18 15v5M15.5 17.5h5",
330
+ opacity: ".55"
331
+ })]
332
+ }),
333
+ more: /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("svg", {
334
+ width: "16",
335
+ height: "16",
336
+ viewBox: "0 0 24 24",
337
+ fill: "none",
338
+ stroke: "currentColor",
339
+ strokeWidth: "1.8",
340
+ strokeLinecap: "round",
341
+ "aria-hidden": "true",
342
+ children: [
343
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("circle", {
344
+ cx: "5",
345
+ cy: "12",
346
+ r: "1.2"
347
+ }),
348
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("circle", {
349
+ cx: "12",
350
+ cy: "12",
351
+ r: "1.2"
352
+ }),
353
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("circle", {
354
+ cx: "19",
355
+ cy: "12",
356
+ r: "1.2"
357
+ })
358
+ ]
359
+ }),
360
+ check: /* @__PURE__ */ (0, react_jsx_runtime.jsx)("svg", {
361
+ width: "13",
362
+ height: "13",
363
+ viewBox: "0 0 24 24",
364
+ fill: "none",
365
+ stroke: "currentColor",
366
+ strokeWidth: "2.2",
367
+ strokeLinecap: "round",
368
+ strokeLinejoin: "round",
369
+ "aria-hidden": "true",
370
+ children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)("path", { d: "m5 12.5 4.5 4.5L19 7.5" })
371
+ }),
372
+ alignLeft: /* @__PURE__ */ (0, react_jsx_runtime.jsx)("svg", {
373
+ width: "16",
374
+ height: "16",
375
+ viewBox: "0 0 24 24",
376
+ fill: "none",
377
+ stroke: "currentColor",
378
+ strokeWidth: "1.8",
379
+ strokeLinecap: "round",
380
+ "aria-hidden": "true",
381
+ children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)("path", { d: "M4 6h16M4 10h10M4 14h16M4 18h8" })
382
+ }),
383
+ alignCenter: /* @__PURE__ */ (0, react_jsx_runtime.jsx)("svg", {
384
+ width: "16",
385
+ height: "16",
386
+ viewBox: "0 0 24 24",
387
+ fill: "none",
388
+ stroke: "currentColor",
389
+ strokeWidth: "1.8",
390
+ strokeLinecap: "round",
391
+ "aria-hidden": "true",
392
+ children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)("path", { d: "M4 6h16M7 10h10M4 14h16M8 18h8" })
393
+ }),
394
+ alignRight: /* @__PURE__ */ (0, react_jsx_runtime.jsx)("svg", {
395
+ width: "16",
396
+ height: "16",
397
+ viewBox: "0 0 24 24",
398
+ fill: "none",
399
+ stroke: "currentColor",
400
+ strokeWidth: "1.8",
401
+ strokeLinecap: "round",
402
+ "aria-hidden": "true",
403
+ children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)("path", { d: "M4 6h16M10 10h10M4 14h16M12 18h8" })
404
+ }),
405
+ alignJustify: /* @__PURE__ */ (0, react_jsx_runtime.jsx)("svg", {
406
+ width: "16",
407
+ height: "16",
408
+ viewBox: "0 0 24 24",
409
+ fill: "none",
410
+ stroke: "currentColor",
411
+ strokeWidth: "1.8",
412
+ strokeLinecap: "round",
413
+ "aria-hidden": "true",
414
+ children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)("path", { d: "M4 6h16M4 10h16M4 14h16M4 18h16" })
415
+ }),
416
+ history: /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("svg", {
417
+ width: "16",
418
+ height: "16",
419
+ viewBox: "0 0 24 24",
420
+ fill: "none",
421
+ stroke: "currentColor",
422
+ strokeWidth: "1.8",
423
+ strokeLinecap: "round",
424
+ strokeLinejoin: "round",
425
+ "aria-hidden": "true",
426
+ children: [
427
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("circle", {
428
+ cx: "12",
429
+ cy: "12",
430
+ r: "8"
431
+ }),
432
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("path", { d: "M12 7.5V12l3 2" }),
433
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("path", { d: "M4.5 5.5V9H8" })
434
+ ]
435
+ }),
436
+ color: /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("svg", {
437
+ width: "16",
438
+ height: "16",
439
+ viewBox: "0 0 24 24",
440
+ fill: "none",
441
+ stroke: "currentColor",
442
+ strokeWidth: "1.8",
443
+ strokeLinecap: "round",
444
+ strokeLinejoin: "round",
445
+ "aria-hidden": "true",
446
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("path", { d: "m6 15 5-9 5 9M7.5 12h7" }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("path", { d: "M4 20h16" })]
447
+ }),
448
+ background: /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("svg", {
449
+ width: "16",
450
+ height: "16",
451
+ viewBox: "0 0 24 24",
452
+ fill: "none",
453
+ stroke: "currentColor",
454
+ strokeWidth: "1.8",
455
+ strokeLinecap: "round",
456
+ strokeLinejoin: "round",
457
+ "aria-hidden": "true",
458
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("path", { d: "m5 13 5-5 6 6-5 5a2 2 0 0 1-2.8 0L5 15.8a2 2 0 0 1 0-2.8Z" }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("path", { d: "m9 9 4-4 6 6-4 4M19 16c0 1.5 1 2.5 1 2.5S21 17.5 21 16a1 1 0 0 0-2 0Z" })]
459
+ }),
460
+ underline: /* @__PURE__ */ (0, react_jsx_runtime.jsx)("svg", {
461
+ width: "16",
462
+ height: "16",
463
+ viewBox: "0 0 24 24",
464
+ fill: "none",
465
+ stroke: "currentColor",
466
+ strokeWidth: "1.9",
467
+ strokeLinecap: "round",
468
+ "aria-hidden": "true",
469
+ children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)("path", { d: "M7 5v6a5 5 0 0 0 10 0V5M5 20h14" })
470
+ }),
471
+ align: /* @__PURE__ */ (0, react_jsx_runtime.jsx)("svg", {
472
+ width: "16",
473
+ height: "16",
474
+ viewBox: "0 0 24 24",
475
+ fill: "none",
476
+ stroke: "currentColor",
477
+ strokeWidth: "1.8",
478
+ strokeLinecap: "round",
479
+ "aria-hidden": "true",
480
+ children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)("path", { d: "M4 6h16M4 10h10M4 14h16M4 18h8" })
481
+ }),
482
+ video: /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("svg", {
483
+ width: "16",
484
+ height: "16",
485
+ viewBox: "0 0 24 24",
486
+ fill: "none",
487
+ stroke: "currentColor",
488
+ strokeWidth: "1.8",
489
+ strokeLinecap: "round",
490
+ strokeLinejoin: "round",
491
+ "aria-hidden": "true",
492
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("rect", {
493
+ x: "3",
494
+ y: "5",
495
+ width: "18",
496
+ height: "14",
497
+ rx: "3"
498
+ }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("path", { d: "m10 9 5 3-5 3z" })]
499
+ }),
500
+ formula: /* @__PURE__ */ (0, react_jsx_runtime.jsx)("svg", {
501
+ width: "16",
502
+ height: "16",
503
+ viewBox: "0 0 24 24",
504
+ fill: "none",
505
+ stroke: "currentColor",
506
+ strokeWidth: "1.8",
507
+ strokeLinecap: "round",
508
+ strokeLinejoin: "round",
509
+ "aria-hidden": "true",
510
+ children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)("path", { d: "M18 5H8l5 7-5 7h10" })
511
+ }),
512
+ template: /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("svg", {
513
+ width: "16",
514
+ height: "16",
515
+ viewBox: "0 0 24 24",
516
+ fill: "none",
517
+ stroke: "currentColor",
518
+ strokeWidth: "1.8",
519
+ strokeLinecap: "round",
520
+ strokeLinejoin: "round",
521
+ "aria-hidden": "true",
522
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("rect", {
523
+ x: "3",
524
+ y: "4",
525
+ width: "18",
526
+ height: "16",
527
+ rx: "2"
528
+ }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("path", { d: "M3 9h18M9 9v11" })]
529
+ }),
530
+ wide: /* @__PURE__ */ (0, react_jsx_runtime.jsx)("svg", {
531
+ width: "16",
532
+ height: "16",
533
+ viewBox: "0 0 24 24",
534
+ fill: "none",
535
+ stroke: "currentColor",
536
+ strokeWidth: "1.8",
537
+ strokeLinecap: "round",
538
+ strokeLinejoin: "round",
539
+ "aria-hidden": "true",
540
+ children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)("path", { d: "M4 12h16M7 8l-4 4 4 4M17 8l4 4-4 4" })
541
+ }),
542
+ bold: /* @__PURE__ */ (0, react_jsx_runtime.jsx)("svg", {
543
+ width: "16",
544
+ height: "16",
545
+ viewBox: "0 0 24 24",
546
+ fill: "none",
547
+ stroke: "currentColor",
548
+ strokeWidth: "1.9",
549
+ strokeLinecap: "round",
550
+ strokeLinejoin: "round",
551
+ "aria-hidden": "true",
552
+ children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)("path", { d: "M7 4h6.5a4 4 0 0 1 0 8H7zM7 12h7.5a4 4 0 0 1 0 8H7z" })
553
+ }),
554
+ italic: /* @__PURE__ */ (0, react_jsx_runtime.jsx)("svg", {
555
+ width: "16",
556
+ height: "16",
557
+ viewBox: "0 0 24 24",
558
+ fill: "none",
559
+ stroke: "currentColor",
560
+ strokeWidth: "1.9",
561
+ strokeLinecap: "round",
562
+ "aria-hidden": "true",
563
+ children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)("path", { d: "M10 4h8M6 20h8M14 4 10 20" })
564
+ }),
565
+ strike: /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("svg", {
566
+ width: "16",
567
+ height: "16",
568
+ viewBox: "0 0 24 24",
569
+ fill: "none",
570
+ stroke: "currentColor",
571
+ strokeWidth: "1.8",
572
+ strokeLinecap: "round",
573
+ strokeLinejoin: "round",
574
+ "aria-hidden": "true",
575
+ children: [
576
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("path", { d: "M5 12h14" }),
577
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("path", { d: "M16.5 7.5C15.5 6 14 5.2 12 5.2c-2.4 0-4 1.2-4 2.9 0 1.5 1 2.3 4 3" }),
578
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("path", { d: "M7.5 16.5C8.5 18 10 18.8 12 18.8c2.4 0 4-1.2 4-2.9 0-1.4-1-2.2-3.5-2.7" })
579
+ ]
580
+ }),
581
+ ul: /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("svg", {
582
+ width: "16",
583
+ height: "16",
584
+ viewBox: "0 0 24 24",
585
+ fill: "none",
586
+ stroke: "currentColor",
587
+ strokeWidth: "1.8",
588
+ strokeLinecap: "round",
589
+ "aria-hidden": "true",
590
+ children: [
591
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("path", { d: "M8 6h12M8 12h12M8 18h12" }),
592
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("circle", {
593
+ cx: "4.2",
594
+ cy: "6",
595
+ r: "1"
596
+ }),
597
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("circle", {
598
+ cx: "4.2",
599
+ cy: "12",
600
+ r: "1"
601
+ }),
602
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("circle", {
603
+ cx: "4.2",
604
+ cy: "18",
605
+ r: "1"
606
+ })
607
+ ]
608
+ }),
609
+ ol: /* @__PURE__ */ (0, react_jsx_runtime.jsx)("svg", {
610
+ width: "16",
611
+ height: "16",
612
+ viewBox: "0 0 24 24",
613
+ fill: "none",
614
+ stroke: "currentColor",
615
+ strokeWidth: "1.8",
616
+ strokeLinecap: "round",
617
+ strokeLinejoin: "round",
618
+ "aria-hidden": "true",
619
+ children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)("path", { d: "M10 6h10M10 12h10M10 18h10M4 5h1v4M4 9h2M4 15h2l-2 3h2" })
620
+ }),
621
+ quote: /* @__PURE__ */ (0, react_jsx_runtime.jsx)("svg", {
622
+ width: "16",
623
+ height: "16",
624
+ viewBox: "0 0 24 24",
625
+ fill: "none",
626
+ stroke: "currentColor",
627
+ strokeWidth: "1.8",
628
+ strokeLinecap: "round",
629
+ strokeLinejoin: "round",
630
+ "aria-hidden": "true",
631
+ children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)("path", { d: "M5 6v12M9 6h9M9 12h7M9 18h5" })
632
+ }),
633
+ runCode: /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("svg", {
634
+ width: "16",
635
+ height: "16",
636
+ viewBox: "0 0 24 24",
637
+ fill: "none",
638
+ stroke: "currentColor",
639
+ strokeWidth: "1.8",
640
+ strokeLinecap: "round",
641
+ strokeLinejoin: "round",
642
+ "aria-hidden": "true",
643
+ children: [
644
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("rect", {
645
+ x: "3",
646
+ y: "4",
647
+ width: "18",
648
+ height: "16",
649
+ rx: "2"
650
+ }),
651
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("path", { d: "m7 9 3 3-3 3" }),
652
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("path", { d: "M13 15h4" })
653
+ ]
654
+ }),
655
+ code: /* @__PURE__ */ (0, react_jsx_runtime.jsx)("svg", {
656
+ width: "16",
657
+ height: "16",
658
+ viewBox: "0 0 24 24",
659
+ fill: "none",
660
+ stroke: "currentColor",
661
+ strokeWidth: "1.8",
662
+ strokeLinecap: "round",
663
+ strokeLinejoin: "round",
664
+ "aria-hidden": "true",
665
+ children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)("path", { d: "m8.5 8-4 4 4 4M15.5 8l4 4-4 4" })
666
+ }),
667
+ hr: /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("svg", {
668
+ width: "16",
669
+ height: "16",
670
+ viewBox: "0 0 24 24",
671
+ fill: "none",
672
+ stroke: "currentColor",
673
+ strokeWidth: "1.8",
674
+ strokeLinecap: "round",
675
+ "aria-hidden": "true",
676
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("path", { d: "M4 12h16" }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("path", {
677
+ d: "M5 6h14M5 18h14",
678
+ opacity: ".35"
679
+ })]
680
+ }),
681
+ table: /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("svg", {
682
+ width: "16",
683
+ height: "16",
684
+ viewBox: "0 0 24 24",
685
+ fill: "none",
686
+ stroke: "currentColor",
687
+ strokeWidth: "1.8",
688
+ strokeLinecap: "round",
689
+ strokeLinejoin: "round",
690
+ "aria-hidden": "true",
691
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("rect", {
692
+ x: "3",
693
+ y: "4",
694
+ width: "18",
695
+ height: "16",
696
+ rx: "2"
697
+ }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("path", { d: "M3 9h18M9 9v11M15 9v11" })]
698
+ }),
699
+ image: /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("svg", {
700
+ width: "16",
701
+ height: "16",
702
+ viewBox: "0 0 24 24",
703
+ fill: "none",
704
+ stroke: "currentColor",
705
+ strokeWidth: "1.8",
706
+ strokeLinecap: "round",
707
+ strokeLinejoin: "round",
708
+ "aria-hidden": "true",
709
+ children: [
710
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("rect", {
711
+ x: "3",
712
+ y: "4",
713
+ width: "18",
714
+ height: "16",
715
+ rx: "3"
716
+ }),
717
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("circle", {
718
+ cx: "8.5",
719
+ cy: "9.5",
720
+ r: "1.5"
721
+ }),
722
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("path", { d: "m5 18 4.5-4.5a2 2 0 0 1 2.8 0L17 18" })
723
+ ]
724
+ }),
725
+ link: /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("svg", {
726
+ width: "16",
727
+ height: "16",
728
+ viewBox: "0 0 24 24",
729
+ fill: "none",
730
+ stroke: "currentColor",
731
+ strokeWidth: "1.8",
732
+ strokeLinecap: "round",
733
+ strokeLinejoin: "round",
734
+ "aria-hidden": "true",
735
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("path", { d: "M10 13a4 4 0 0 0 5.6 0l2.4-2.4a4 4 0 0 0-5.6-5.6L11 6.4" }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("path", { d: "M14 11a4 4 0 0 0-5.6 0L6 13.4a4 4 0 0 0 5.6 5.6l1.4-1.4" })]
736
+ })
737
+ };
738
+ /** 普通编辑器:contentEditable + 工具栏,内容以 Markdown 与父组件同步 */
739
+ // src/RichTextEditor.tsx
740
+ function escapeHtml(value) {
741
+ return value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
742
+ }
743
+ const COLOR_ROWS = [
744
+ [
745
+ "",
746
+ "#000000",
747
+ "#f5222d",
748
+ "#fa8c16",
749
+ "#fadb14",
750
+ "#52c41a",
751
+ "#13c2c2",
752
+ "#1890ff",
753
+ "#722ed1"
754
+ ],
755
+ [
756
+ "#f5f5f5",
757
+ "#d9d9d9",
758
+ "#fff1f0",
759
+ "#fff2e8",
760
+ "#feffe6",
761
+ "#f6ffed",
762
+ "#e6fffb",
763
+ "#e6f7ff",
764
+ "#f9f0ff"
765
+ ],
766
+ [
767
+ "#bfbfbf",
768
+ "#8c8c8c",
769
+ "#ffccc7",
770
+ "#ffd8bf",
771
+ "#fff1b8",
772
+ "#d9f7be",
773
+ "#b5f5ec",
774
+ "#bae7ff",
775
+ "#efdbff"
776
+ ],
777
+ [
778
+ "#595959",
779
+ "#434343",
780
+ "#ff7875",
781
+ "#ff9c6e",
782
+ "#ffd666",
783
+ "#95de64",
784
+ "#5cdbd3",
785
+ "#69c0ff",
786
+ "#b37feb"
787
+ ],
788
+ [
789
+ "#9254de",
790
+ "#000000",
791
+ "#cf1322",
792
+ "#d46b08",
793
+ "#ad8b00",
794
+ "#237804",
795
+ "#006d75",
796
+ "#003a8c",
797
+ "#531dab"
798
+ ]
799
+ ];
800
+ const TEXT_COLORS = COLOR_ROWS;
801
+ const BG_COLORS = COLOR_ROWS.map((row, rowIndex) => row.map((color, columnIndex) => rowIndex === 0 && columnIndex === 0 ? "transparent" : color));
802
+ const CODE_LANGUAGES = [
803
+ "HTML",
804
+ "Bash",
805
+ "C++",
806
+ "C#",
807
+ "CSS/SCSS/LESS",
808
+ "Dart",
809
+ "Delphi",
810
+ "diff",
811
+ "VB.NET",
812
+ "Go",
813
+ "Java",
814
+ "JavaScript",
815
+ "Kotlin",
816
+ "Objective-C",
817
+ "Perl",
818
+ "PHP",
819
+ "Python",
820
+ "Ruby",
821
+ "Rust",
822
+ "SQL",
823
+ "Swift",
824
+ "TypeScript",
825
+ "YAML",
826
+ "JSON",
827
+ "Markdown"
828
+ ];
829
+ const TEMPLATES = [
830
+ {
831
+ label: "技术笔记",
832
+ markdown: "# 主题\n\n## 背景\n\n## 结论\n\n## 参考\n"
833
+ },
834
+ {
835
+ label: "问题排查",
836
+ markdown: "# 问题现象\n\n## 复现步骤\n\n## 原因\n\n## 解决方案\n"
837
+ },
838
+ {
839
+ label: "项目复盘",
840
+ markdown: "# 项目复盘\n\n## 目标\n\n## 做对了什么\n\n## 可以改进\n\n## 下一步\n"
841
+ }
842
+ ];
843
+ function RichTextEditor({ markdown, onChange, onUploadImage, onSwitchToMarkdown, switchLabel = "使用 Markdown 编辑器", renderMarkdown = defaultRenderMarkdown, placeholder = "开始写正文…", className = "", features }) {
844
+ const feature = (key) => features?.[key] !== false;
845
+ const rootRef = (0, react.useRef)(null);
846
+ const [containerWidth, setContainerWidth] = (0, react.useState)(0);
847
+ const editorRef = (0, react.useRef)(null);
848
+ const imageRef = (0, react.useRef)(null);
849
+ const savedRange = (0, react.useRef)(null);
850
+ const lastMd = (0, react.useRef)(null);
851
+ const formatRef = (0, react.useRef)(null);
852
+ const formatBtnRef = (0, react.useRef)(null);
853
+ const popoverAnchorRef = (0, react.useRef)(null);
854
+ const linkBtnRef = (0, react.useRef)(null);
855
+ const [linkOpen, setLinkOpen] = (0, react.useState)(false);
856
+ const [linkPos, setLinkPos] = (0, react.useState)({
857
+ left: 0,
858
+ top: 0
859
+ });
860
+ const [linkUrl, setLinkUrl] = (0, react.useState)("");
861
+ const [linkError, setLinkError] = (0, react.useState)("");
862
+ const [formatOpen, setFormatOpen] = (0, react.useState)(false);
863
+ const [formatPos, setFormatPos] = (0, react.useState)({
864
+ left: 0,
865
+ top: 0
866
+ });
867
+ const [tocOpen, setTocOpen] = (0, react.useState)(true);
868
+ const [headings, setHeadings] = (0, react.useState)([]);
869
+ const [busy, setBusy] = (0, react.useState)(false);
870
+ const [error, setError] = (0, react.useState)("");
871
+ const [popover, setPopover] = (0, react.useState)(null);
872
+ const [videoUrl, setVideoUrl] = (0, react.useState)("");
873
+ const [formulaText, setFormulaText] = (0, react.useState)("");
874
+ const [wide, setWide] = (0, react.useState)(false);
875
+ const [history, setHistory] = (0, react.useState)([]);
876
+ const [richRun, setRichRun] = (0, react.useState)(null);
877
+ const [codeOpen, setCodeOpen] = (0, react.useState)(false);
878
+ const [codeText, setCodeText] = (0, react.useState)("");
879
+ const [codeLang, setCodeLang] = (0, react.useState)("html");
880
+ (0, react.useEffect)(() => {
881
+ const el = editorRef.current;
882
+ if (!el) return;
883
+ if (lastMd.current === markdown) return;
884
+ el.innerHTML = renderMarkdown(markdown);
885
+ lastMd.current = markdown;
886
+ refreshHeadings();
887
+ }, [markdown]);
888
+ (0, react.useEffect)(() => {
889
+ if (!formatOpen) return;
890
+ const onDown = (event) => {
891
+ if (!formatRef.current?.contains(event.target)) setFormatOpen(false);
892
+ };
893
+ document.addEventListener("mousedown", onDown);
894
+ return () => document.removeEventListener("mousedown", onDown);
895
+ }, [formatOpen]);
896
+ (0, react.useEffect)(() => {
897
+ if (!popover) return;
898
+ const onDown = (event) => {
899
+ const target = event.target;
900
+ if (target?.closest(".rre-popover") || target?.closest(".rre-tool")) return;
901
+ setPopover(null);
902
+ };
903
+ document.addEventListener("mousedown", onDown);
904
+ return () => document.removeEventListener("mousedown", onDown);
905
+ }, [popover]);
906
+ (0, react.useEffect)(() => {
907
+ if (!markdown.trim()) return;
908
+ const timer = window.setTimeout(() => {
909
+ setHistory((prev) => {
910
+ if (prev[prev.length - 1]?.value === markdown) return prev;
911
+ return [...prev, {
912
+ at: Date.now(),
913
+ value: markdown
914
+ }].slice(-20);
915
+ });
916
+ }, 1500);
917
+ return () => window.clearTimeout(timer);
918
+ }, [markdown]);
919
+ (0, react.useEffect)(() => {
920
+ const el = rootRef.current;
921
+ if (!el) return;
922
+ const observer = new ResizeObserver((entries) => {
923
+ setContainerWidth(entries[0]?.contentRect.width ?? 0);
924
+ });
925
+ observer.observe(el);
926
+ return () => observer.disconnect();
927
+ }, []);
928
+ (0, react.useEffect)(() => {
929
+ function onMessage(event) {
930
+ const data = event.data;
931
+ if (!data || data.source !== "rre-code-run") return;
932
+ setRichRun((prev) => prev ? {
933
+ ...prev,
934
+ output: [...prev.output, String(data.text)]
935
+ } : prev);
936
+ }
937
+ window.addEventListener("message", onMessage);
938
+ return () => window.removeEventListener("message", onMessage);
939
+ }, []);
940
+ function refreshHeadings() {
941
+ if (!feature("toc")) return;
942
+ const el = editorRef.current;
943
+ if (!el) return;
944
+ const list = Array.from(el.querySelectorAll("h1,h2,h3,h4"));
945
+ list.forEach((heading, index) => {
946
+ heading.id = `rre-h-${index}`;
947
+ });
948
+ setHeadings(list.map((heading, index) => ({
949
+ id: `rre-h-${index}`,
950
+ text: heading.textContent?.trim() || "未命名标题",
951
+ level: Number(heading.tagName.slice(1))
952
+ })));
953
+ }
954
+ function scrollToHeading(id) {
955
+ (editorRef.current?.querySelector("#" + id))?.scrollIntoView({
956
+ behavior: "smooth",
957
+ block: "start"
958
+ });
959
+ }
960
+ function openPopover(kind, el) {
961
+ const rect = el.getBoundingClientRect();
962
+ popoverAnchorRef.current = el;
963
+ setPopover({
964
+ kind,
965
+ left: rect.left,
966
+ top: rect.bottom + 6
967
+ });
968
+ }
969
+ function commandActive(command) {
970
+ try {
971
+ return document.queryCommandState(command);
972
+ } catch {
973
+ return false;
974
+ }
975
+ }
976
+ function applyColor(color, background = false) {
977
+ if (!color) run(background ? "hiliteColor" : "foreColor", background ? "transparent" : "#111827");
978
+ else run(background ? "hiliteColor" : "foreColor", color);
979
+ setPopover(null);
980
+ }
981
+ function insertVideo() {
982
+ const url = videoUrl.trim();
983
+ if (!/^(https?:\/\/|\/|\.\.?\/)/i.test(url)) {
984
+ setError("请输入 http(s) 或站内视频地址");
985
+ return;
986
+ }
987
+ insertHtml(`<video src="${escapeHtml(url)}" controls></video><p><br></p>`);
988
+ setVideoUrl("");
989
+ setPopover(null);
990
+ setError("");
991
+ }
992
+ function insertFormula() {
993
+ const value = formulaText.trim();
994
+ if (!value) return;
995
+ insertHtml(escapeHtml(value.startsWith("$") ? value : `$${value}$`));
996
+ setFormulaText("");
997
+ setPopover(null);
998
+ }
999
+ function insertTemplate(markdownText) {
1000
+ insertHtml(renderMarkdown(markdownText));
1001
+ setPopover(null);
1002
+ }
1003
+ function restoreHistory(value) {
1004
+ const el = editorRef.current;
1005
+ if (!el) return;
1006
+ el.innerHTML = renderMarkdown(value);
1007
+ lastMd.current = value;
1008
+ refreshHeadings();
1009
+ onChange(value);
1010
+ setPopover(null);
1011
+ }
1012
+ function openCodeDialog() {
1013
+ const el = editorRef.current;
1014
+ const sel = window.getSelection();
1015
+ let pre = null;
1016
+ if (sel?.anchorNode) pre = (sel.anchorNode instanceof Element ? sel.anchorNode : sel.anchorNode.parentElement)?.closest("pre");
1017
+ if (pre && el?.contains(pre)) {
1018
+ const code = pre.querySelector("code");
1019
+ setCodeText(code?.textContent || pre.textContent || "");
1020
+ setCodeLang((code?.className.match(/language-([\w-]+)/)?.[1] || "html").toLowerCase());
1021
+ const range = document.createRange();
1022
+ range.selectNode(pre);
1023
+ sel?.removeAllRanges();
1024
+ sel?.addRange(range);
1025
+ savedRange.current = range.cloneRange();
1026
+ } else {
1027
+ setCodeText(sel?.toString() || "");
1028
+ setCodeLang("html");
1029
+ }
1030
+ setPopover(null);
1031
+ setCodeOpen(true);
1032
+ }
1033
+ function insertCode() {
1034
+ insertHtml(`<pre><code class="language-${codeLang === "CSS/SCSS/LESS" ? "css" : codeLang.toLowerCase()}">${escapeHtml(codeText)}</code></pre><p><br></p>`);
1035
+ setCodeOpen(false);
1036
+ }
1037
+ function runRichCode() {
1038
+ const selected = window.getSelection()?.toString().trim() || "";
1039
+ const pre = editorRef.current?.querySelector("pre code")?.textContent || "";
1040
+ const code = selected || pre;
1041
+ if (!code.trim()) {
1042
+ setError("请先选中代码,或在正文中加入代码块");
1043
+ return;
1044
+ }
1045
+ setError("");
1046
+ setPopover(null);
1047
+ setRichRun({
1048
+ code,
1049
+ output: [],
1050
+ key: Date.now()
1051
+ });
1052
+ }
1053
+ function focusEnd() {
1054
+ const el = editorRef.current;
1055
+ if (!el) return;
1056
+ const range = document.createRange();
1057
+ range.selectNodeContents(el);
1058
+ range.collapse(false);
1059
+ const sel = window.getSelection();
1060
+ sel?.removeAllRanges();
1061
+ sel?.addRange(range);
1062
+ }
1063
+ function saveRange() {
1064
+ const el = editorRef.current;
1065
+ const sel = window.getSelection();
1066
+ if (!el || !sel || !sel.rangeCount) return;
1067
+ const range = sel.getRangeAt(0);
1068
+ if (el.contains(range.commonAncestorContainer)) savedRange.current = range.cloneRange();
1069
+ }
1070
+ function restoreRange() {
1071
+ const el = editorRef.current;
1072
+ if (!el) return;
1073
+ el.focus();
1074
+ const range = savedRange.current;
1075
+ if (!range || !el.contains(range.commonAncestorContainer)) {
1076
+ focusEnd();
1077
+ return;
1078
+ }
1079
+ const sel = window.getSelection();
1080
+ sel?.removeAllRanges();
1081
+ sel?.addRange(range);
1082
+ }
1083
+ function sync() {
1084
+ const el = editorRef.current;
1085
+ if (!el) return;
1086
+ if (!el.textContent?.trim() && !el.querySelector("img,table,hr,pre")) {
1087
+ if (el.innerHTML) el.innerHTML = "";
1088
+ }
1089
+ const md = htmlToMarkdown(el.innerHTML);
1090
+ lastMd.current = md;
1091
+ refreshHeadings();
1092
+ onChange(md);
1093
+ }
1094
+ /** Chromium 在 insertUnorderedList / insertOrderedList 后会把光标放到行首,这里挪回块尾 */
1095
+ function caretToEndOfBlock() {
1096
+ const sel = window.getSelection();
1097
+ if (!sel || !sel.rangeCount) return;
1098
+ const anchor = sel.anchorNode;
1099
+ const block = (anchor instanceof Element ? anchor : anchor?.parentElement)?.closest("li,p,h1,h2,h3,h4,h5,h6,blockquote,div");
1100
+ if (!block) return;
1101
+ const range = document.createRange();
1102
+ range.selectNodeContents(block);
1103
+ range.collapse(false);
1104
+ sel.removeAllRanges();
1105
+ sel.addRange(range);
1106
+ savedRange.current = range.cloneRange();
1107
+ }
1108
+ function run(command, value, caretEnd = false) {
1109
+ const el = editorRef.current;
1110
+ if (!el) return;
1111
+ el.focus();
1112
+ restoreRange();
1113
+ document.execCommand(command, false, value);
1114
+ if (caretEnd) caretToEndOfBlock();
1115
+ saveRange();
1116
+ sync();
1117
+ }
1118
+ function applyBlock(tag) {
1119
+ run("formatBlock", tag);
1120
+ }
1121
+ function insertHtml(html) {
1122
+ const el = editorRef.current;
1123
+ if (!el) return;
1124
+ el.focus();
1125
+ restoreRange();
1126
+ document.execCommand("insertHTML", false, html);
1127
+ saveRange();
1128
+ sync();
1129
+ }
1130
+ function onPaste(event) {
1131
+ event.preventDefault();
1132
+ const text = event.clipboardData.getData("text/plain");
1133
+ document.execCommand("insertText", false, text);
1134
+ sync();
1135
+ }
1136
+ function openLink() {
1137
+ saveRange();
1138
+ const rect = linkBtnRef.current?.getBoundingClientRect();
1139
+ if (rect) setLinkPos({
1140
+ left: rect.left,
1141
+ top: rect.bottom + 8
1142
+ });
1143
+ setLinkError("");
1144
+ setLinkUrl("");
1145
+ setLinkOpen(true);
1146
+ }
1147
+ function applyLink() {
1148
+ const href = safeRichHref(linkUrl);
1149
+ if (!href) {
1150
+ setLinkError("请输入 http(s) / mailto / 站内地址");
1151
+ return;
1152
+ }
1153
+ const el = editorRef.current;
1154
+ if (!el) return;
1155
+ el.focus();
1156
+ restoreRange();
1157
+ const sel = window.getSelection();
1158
+ if (sel && !sel.isCollapsed) {
1159
+ document.execCommand("createLink", false, href);
1160
+ saveRange();
1161
+ sync();
1162
+ } else {
1163
+ document.execCommand("insertHTML", false, `<a href="${href}">${escapeHtml(linkUrl.trim() || href)}</a>`);
1164
+ saveRange();
1165
+ sync();
1166
+ }
1167
+ setLinkOpen(false);
1168
+ setLinkUrl("");
1169
+ }
1170
+ async function onImageFile(event) {
1171
+ const file = event.target.files?.[0];
1172
+ event.target.value = "";
1173
+ if (!file) return;
1174
+ setBusy(true);
1175
+ setError("");
1176
+ try {
1177
+ const src = safeRichHref(await onUploadImage(file));
1178
+ if (!src) throw new Error("图片地址不合法");
1179
+ insertHtml(`<img src="${src}" alt="${escapeHtml(file.name.replace(/\.[^.]+$/, ""))}">`);
1180
+ } catch (err) {
1181
+ setError(err instanceof Error ? err.message : "图片上传失败");
1182
+ } finally {
1183
+ setBusy(false);
1184
+ }
1185
+ }
1186
+ function insertTable() {
1187
+ const row = "<tr><td>内容</td><td>内容</td><td>内容</td></tr>";
1188
+ insertHtml(`<table><thead><tr><th>列 1</th><th>列 2</th><th>列 3</th></tr></thead><tbody>${row}${row}</tbody></table><p><br></p>`);
1189
+ }
1190
+ function toolButton(label, icon, onClick, opts = {}) {
1191
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("button", {
1192
+ type: "button",
1193
+ className: `rre-tool${opts.strong ? " is-strong" : ""}${opts.active ? " is-on" : ""}`,
1194
+ title: label,
1195
+ "aria-label": label,
1196
+ onMouseDown: (event) => {
1197
+ event.preventDefault();
1198
+ saveRange();
1199
+ },
1200
+ onClick,
1201
+ children: [icon, /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", { children: label })]
1202
+ });
1203
+ }
1204
+ function popoverTool(label, icon, kind) {
1205
+ const withCaret = !["video", "formula"].includes(kind);
1206
+ const active = popover?.kind === kind;
1207
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("button", {
1208
+ type: "button",
1209
+ className: `rre-tool${active ? " is-on" : ""}`,
1210
+ title: label,
1211
+ "aria-label": label,
1212
+ onMouseDown: (event) => {
1213
+ event.preventDefault();
1214
+ saveRange();
1215
+ },
1216
+ onClick: (event) => openPopover(kind, event.currentTarget),
1217
+ children: [icon, /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("span", {
1218
+ className: withCaret ? "rre-popover-label" : void 0,
1219
+ children: [label, withCaret ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)("svg", {
1220
+ className: "rre-caret",
1221
+ width: "10",
1222
+ height: "10",
1223
+ viewBox: "0 0 24 24",
1224
+ fill: "none",
1225
+ stroke: "currentColor",
1226
+ strokeWidth: "2.4",
1227
+ strokeLinecap: "round",
1228
+ strokeLinejoin: "round",
1229
+ "aria-hidden": "true",
1230
+ children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)("path", { d: "m6 9 6 6 6-6" })
1231
+ }) : null]
1232
+ })]
1233
+ });
1234
+ }
1235
+ const visibleGroups = [
1236
+ [
1237
+ "undo",
1238
+ "redo",
1239
+ "history"
1240
+ ],
1241
+ [
1242
+ "format",
1243
+ "bold",
1244
+ "color",
1245
+ "background",
1246
+ "other"
1247
+ ],
1248
+ [
1249
+ "list",
1250
+ "align",
1251
+ "hr",
1252
+ "quote"
1253
+ ],
1254
+ ["code", "table"],
1255
+ [
1256
+ "image",
1257
+ "video",
1258
+ "formula",
1259
+ "link",
1260
+ "template"
1261
+ ],
1262
+ ["wide"]
1263
+ ].map((group) => group.filter((key) => feature(key))).filter((group) => group.length > 0);
1264
+ function renderFeature(key) {
1265
+ switch (key) {
1266
+ case "undo": return toolButton("撤销", EditorIcons.undo, () => run("undo"));
1267
+ case "redo": return toolButton("重做", EditorIcons.redo, () => run("redo"));
1268
+ case "bold": return toolButton("加粗", EditorIcons.bold, () => run("bold"), { strong: true });
1269
+ case "italic": return toolButton("斜体", EditorIcons.italic, () => run("italic"));
1270
+ case "strike": return toolButton("删除线", EditorIcons.strike, () => run("strikeThrough"));
1271
+ case "list": return popoverTool("列表", EditorIcons.ul, "list");
1272
+ case "orderedList": return toolButton("有序", EditorIcons.ol, () => run("insertOrderedList", void 0, true));
1273
+ case "quote": return toolButton("块引用", EditorIcons.quote, () => applyBlock("blockquote"));
1274
+ case "hr": return toolButton("水平线", EditorIcons.hr, () => run("insertHorizontalRule"));
1275
+ case "code": return popoverTool("代码", EditorIcons.code, "code");
1276
+ case "table": return toolButton("表格", EditorIcons.table, insertTable);
1277
+ case "image": return toolButton(busy ? "上传中" : "图像", EditorIcons.image, () => imageRef.current?.click());
1278
+ case "history": return popoverTool("历史", EditorIcons.history, "history");
1279
+ case "color": return popoverTool("颜色", EditorIcons.color, "color");
1280
+ case "background": return popoverTool("背景", EditorIcons.background, "background");
1281
+ case "underline": return toolButton("下划线", EditorIcons.underline, () => run("underline"));
1282
+ case "align": return popoverTool("对齐", EditorIcons.align, "align");
1283
+ case "other": return popoverTool("其他", EditorIcons.more, "other");
1284
+ case "video": return popoverTool("视频", EditorIcons.video, "video");
1285
+ case "formula": return popoverTool("公式", EditorIcons.formula, "formula");
1286
+ case "template": return popoverTool("模版", EditorIcons.template, "template");
1287
+ case "wide": return toolButton("宽屏", EditorIcons.wide, () => setWide((value) => !value), { active: wide });
1288
+ case "format": return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
1289
+ className: "rre-format-wrap",
1290
+ ref: formatRef,
1291
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("button", {
1292
+ type: "button",
1293
+ ref: formatBtnRef,
1294
+ className: `rre-tool${formatOpen ? " is-on" : ""}`,
1295
+ title: "格式",
1296
+ "aria-label": "格式",
1297
+ onMouseDown: (event) => {
1298
+ event.preventDefault();
1299
+ saveRange();
1300
+ },
1301
+ onClick: () => {
1302
+ if (formatOpen) {
1303
+ setFormatOpen(false);
1304
+ return;
1305
+ }
1306
+ const rect = formatBtnRef.current?.getBoundingClientRect();
1307
+ if (rect) setFormatPos({
1308
+ left: rect.left,
1309
+ top: rect.bottom + 4
1310
+ });
1311
+ setFormatOpen(true);
1312
+ },
1313
+ children: [EditorIcons.format, /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("span", {
1314
+ className: "rre-format-label",
1315
+ children: ["格式", /* @__PURE__ */ (0, react_jsx_runtime.jsx)("svg", {
1316
+ className: "rre-caret",
1317
+ width: "11",
1318
+ height: "11",
1319
+ viewBox: "0 0 24 24",
1320
+ fill: "none",
1321
+ stroke: "currentColor",
1322
+ strokeWidth: "2.4",
1323
+ strokeLinecap: "round",
1324
+ strokeLinejoin: "round",
1325
+ "aria-hidden": "true",
1326
+ children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)("path", { d: "m6 9 6 6 6-6" })
1327
+ })]
1328
+ })]
1329
+ }), formatOpen ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
1330
+ className: "rre-format-menu",
1331
+ role: "menu",
1332
+ "aria-label": "段落格式",
1333
+ style: {
1334
+ left: formatPos.left,
1335
+ top: formatPos.top
1336
+ },
1337
+ children: [
1338
+ ["P", "正文"],
1339
+ ["H1", "标题一"],
1340
+ ["H2", "标题二"],
1341
+ ["H3", "标题三"],
1342
+ ["H4", "标题四"],
1343
+ ["H5", "标题五"],
1344
+ ["H6", "标题六"]
1345
+ ].map(([tag, label]) => /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
1346
+ type: "button",
1347
+ role: "menuitem",
1348
+ onClick: () => {
1349
+ setFormatOpen(false);
1350
+ applyBlock(tag);
1351
+ },
1352
+ children: label
1353
+ }, tag))
1354
+ }) : null]
1355
+ }, "format");
1356
+ case "link": return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("span", {
1357
+ className: "rre-link-anchor",
1358
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("button", {
1359
+ ref: linkBtnRef,
1360
+ type: "button",
1361
+ className: `rre-tool${linkOpen ? " is-on" : ""}`,
1362
+ title: "链接",
1363
+ "aria-label": "链接",
1364
+ onMouseDown: (event) => {
1365
+ event.preventDefault();
1366
+ saveRange();
1367
+ },
1368
+ onClick: openLink,
1369
+ children: [EditorIcons.link, /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", { children: "链接" })]
1370
+ }), linkOpen ? /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
1371
+ className: "rre-link-pop",
1372
+ role: "dialog",
1373
+ "aria-label": "插入链接",
1374
+ style: {
1375
+ left: linkPos.left,
1376
+ top: linkPos.top
1377
+ },
1378
+ children: [
1379
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("input", {
1380
+ className: "rre-input-field",
1381
+ value: linkUrl,
1382
+ onChange: (event) => {
1383
+ setLinkUrl(event.target.value);
1384
+ setLinkError("");
1385
+ },
1386
+ onKeyDown: (event) => {
1387
+ if (event.key === "Enter") {
1388
+ event.preventDefault();
1389
+ applyLink();
1390
+ }
1391
+ if (event.key === "Escape") {
1392
+ setLinkOpen(false);
1393
+ setLinkUrl("");
1394
+ }
1395
+ },
1396
+ placeholder: "https://example.com",
1397
+ "aria-label": "链接地址",
1398
+ autoFocus: true
1399
+ }),
1400
+ linkError ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)("em", { children: linkError }) : null,
1401
+ /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
1402
+ className: "rre-link-actions",
1403
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
1404
+ type: "button",
1405
+ className: "rre-btn",
1406
+ onClick: () => {
1407
+ setLinkOpen(false);
1408
+ setLinkUrl("");
1409
+ },
1410
+ children: "取消"
1411
+ }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
1412
+ type: "button",
1413
+ className: "rre-btn rre-btn-primary",
1414
+ onClick: applyLink,
1415
+ children: "确定"
1416
+ })]
1417
+ })
1418
+ ]
1419
+ }) : null]
1420
+ }, "link");
1421
+ default: return null;
1422
+ }
1423
+ }
1424
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
1425
+ ref: rootRef,
1426
+ className: `rre-root${className ? " " + className : ""}${wide ? " is-wide-mode" : ""}${containerWidth >= 1400 ? " is-wide" : containerWidth > 0 && containerWidth <= 900 ? " is-narrow" : ""}`,
1427
+ children: [
1428
+ visibleGroups.length || onSwitchToMarkdown ? /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
1429
+ className: "rre-toolbar",
1430
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
1431
+ className: "rre-tools-scroll",
1432
+ onScroll: () => {
1433
+ setFormatOpen(false);
1434
+ setLinkOpen(false);
1435
+ },
1436
+ children: /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
1437
+ className: "rre-tools",
1438
+ children: [
1439
+ visibleGroups.map((group, index) => /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(react.Fragment, { children: [index > 0 ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", { className: "rre-sep" }) : null, group.map((key) => /* @__PURE__ */ (0, react_jsx_runtime.jsx)(react.Fragment, { children: renderFeature(key) }, key))] }, group.join("-"))),
1440
+ busy ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
1441
+ className: "rre-hint",
1442
+ children: "图片上传中…"
1443
+ }) : null,
1444
+ error ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
1445
+ className: "rre-hint is-error",
1446
+ children: error
1447
+ }) : null
1448
+ ]
1449
+ })
1450
+ }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
1451
+ className: "rre-right",
1452
+ children: onSwitchToMarkdown ? /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("button", {
1453
+ type: "button",
1454
+ className: "rre-switch",
1455
+ onClick: onSwitchToMarkdown,
1456
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
1457
+ className: "rre-switch-icon",
1458
+ children: EditorIcons.switchEditor
1459
+ }), switchLabel]
1460
+ }) : null
1461
+ })]
1462
+ }) : null,
1463
+ /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
1464
+ className: "rre-layout",
1465
+ children: [
1466
+ feature("toc") && !tocOpen ? /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(react_jsx_runtime.Fragment, { children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
1467
+ className: "rre-toc-spacer",
1468
+ "aria-hidden": "true"
1469
+ }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
1470
+ type: "button",
1471
+ className: "rre-toc-open",
1472
+ onClick: () => setTocOpen(true),
1473
+ "aria-label": "展开目录",
1474
+ title: "展开目录",
1475
+ children: /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("svg", {
1476
+ width: "22",
1477
+ height: "22",
1478
+ viewBox: "0 0 24 24",
1479
+ fill: "none",
1480
+ stroke: "currentColor",
1481
+ strokeWidth: "1.9",
1482
+ strokeLinecap: "round",
1483
+ strokeLinejoin: "round",
1484
+ "aria-hidden": "true",
1485
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("path", { d: "m8 6 6 6-6 6" }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("path", { d: "M18 6v12" })]
1486
+ })
1487
+ })] }) : null,
1488
+ feature("toc") && tocOpen ? /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("aside", {
1489
+ className: "rre-toc",
1490
+ "aria-label": "文章目录",
1491
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
1492
+ className: "rre-toc-head",
1493
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("b", { children: "目录" }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
1494
+ type: "button",
1495
+ onClick: () => setTocOpen(false),
1496
+ "aria-label": "收起目录",
1497
+ title: "收起目录",
1498
+ children: /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("svg", {
1499
+ width: "14",
1500
+ height: "14",
1501
+ viewBox: "0 0 24 24",
1502
+ fill: "none",
1503
+ stroke: "currentColor",
1504
+ strokeWidth: "1.9",
1505
+ strokeLinecap: "round",
1506
+ strokeLinejoin: "round",
1507
+ "aria-hidden": "true",
1508
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("path", { d: "m14 6-6 6 6 6" }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("path", { d: "M19 6v12" })]
1509
+ })
1510
+ })]
1511
+ }), headings.length ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)("nav", {
1512
+ className: "rre-toc-list",
1513
+ children: headings.map((heading) => /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
1514
+ type: "button",
1515
+ className: "rre-toc-item",
1516
+ style: { paddingLeft: 8 + (heading.level - 1) * 11 },
1517
+ onClick: () => scrollToHeading(heading.id),
1518
+ title: heading.text,
1519
+ children: heading.text
1520
+ }, heading.id))
1521
+ }) : /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", {
1522
+ className: "rre-toc-empty",
1523
+ children: "为文内增加标题,这里将生成目录"
1524
+ })]
1525
+ }) : null,
1526
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
1527
+ className: "rre-body",
1528
+ children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
1529
+ className: "rre-page",
1530
+ children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
1531
+ ref: editorRef,
1532
+ className: "rre-input",
1533
+ contentEditable: true,
1534
+ suppressContentEditableWarning: true,
1535
+ role: "textbox",
1536
+ "aria-multiline": "true",
1537
+ "aria-label": "普通编辑器正文",
1538
+ "data-placeholder": placeholder,
1539
+ onInput: sync,
1540
+ onBlur: sync,
1541
+ onPaste
1542
+ })
1543
+ })
1544
+ })
1545
+ ]
1546
+ }),
1547
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("input", {
1548
+ ref: imageRef,
1549
+ type: "file",
1550
+ accept: "image/png,image/jpeg,image/gif,image/webp",
1551
+ hidden: true,
1552
+ onChange: (event) => void onImageFile(event)
1553
+ }),
1554
+ popover ? /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
1555
+ className: "rre-popover",
1556
+ style: {
1557
+ left: popover.left,
1558
+ top: popover.top
1559
+ },
1560
+ children: [
1561
+ popover.kind === "color" || popover.kind === "background" ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
1562
+ className: "rre-palette",
1563
+ role: "menu",
1564
+ "aria-label": popover.kind === "color" ? "文字颜色" : "背景颜色",
1565
+ children: (popover.kind === "color" ? TEXT_COLORS : BG_COLORS).map((row, rowIndex) => /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
1566
+ className: "rre-palette-row",
1567
+ children: row.map((color, columnIndex) => /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
1568
+ type: "button",
1569
+ className: !color || color === "transparent" ? "is-transparent" : "",
1570
+ style: { background: !color || color === "transparent" ? "#fff" : color },
1571
+ title: !color || color === "transparent" ? "无颜色" : color,
1572
+ "aria-label": !color || color === "transparent" ? "无颜色" : color,
1573
+ onClick: () => applyColor(color, popover.kind === "background")
1574
+ }, `${rowIndex}-${columnIndex}`))
1575
+ }, rowIndex))
1576
+ }) : null,
1577
+ popover.kind === "align" ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
1578
+ className: "rre-popover-list",
1579
+ children: [
1580
+ [
1581
+ "左对齐",
1582
+ "justifyLeft",
1583
+ EditorIcons.alignLeft
1584
+ ],
1585
+ [
1586
+ "居中对齐",
1587
+ "justifyCenter",
1588
+ EditorIcons.alignCenter
1589
+ ],
1590
+ [
1591
+ "右对齐",
1592
+ "justifyRight",
1593
+ EditorIcons.alignRight
1594
+ ],
1595
+ [
1596
+ "两端对齐",
1597
+ "justifyFull",
1598
+ EditorIcons.alignJustify
1599
+ ]
1600
+ ].map(([label, command, icon]) => /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("button", {
1601
+ type: "button",
1602
+ className: commandActive(command) ? "is-active" : "",
1603
+ onClick: () => {
1604
+ run(command);
1605
+ setPopover(null);
1606
+ },
1607
+ children: [
1608
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
1609
+ className: "rre-popover-ico",
1610
+ children: icon
1611
+ }),
1612
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", { children: label }),
1613
+ commandActive(command) ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
1614
+ className: "rre-popover-check",
1615
+ children: EditorIcons.check
1616
+ }) : null
1617
+ ]
1618
+ }, command))
1619
+ }) : null,
1620
+ popover.kind === "list" ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
1621
+ className: "rre-popover-list",
1622
+ children: [[
1623
+ "有序列表",
1624
+ "insertOrderedList",
1625
+ EditorIcons.ol
1626
+ ], [
1627
+ "无序列表",
1628
+ "insertUnorderedList",
1629
+ EditorIcons.ul
1630
+ ]].map(([label, command, icon]) => /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("button", {
1631
+ type: "button",
1632
+ className: commandActive(command) ? "is-active" : "",
1633
+ onClick: () => {
1634
+ run(command, void 0, true);
1635
+ setPopover(null);
1636
+ },
1637
+ children: [
1638
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
1639
+ className: "rre-popover-ico",
1640
+ children: icon
1641
+ }),
1642
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", { children: label }),
1643
+ commandActive(command) ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
1644
+ className: "rre-popover-check",
1645
+ children: EditorIcons.check
1646
+ }) : null
1647
+ ]
1648
+ }, command))
1649
+ }) : null,
1650
+ popover.kind === "other" ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
1651
+ className: "rre-popover-list",
1652
+ children: [
1653
+ [
1654
+ "倾斜",
1655
+ "italic",
1656
+ EditorIcons.italic
1657
+ ],
1658
+ [
1659
+ "下划线",
1660
+ "underline",
1661
+ EditorIcons.underline
1662
+ ],
1663
+ [
1664
+ "删除线",
1665
+ "strikeThrough",
1666
+ EditorIcons.strike
1667
+ ]
1668
+ ].map(([label, command, icon]) => /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("button", {
1669
+ type: "button",
1670
+ className: commandActive(command) ? "is-active" : "",
1671
+ onClick: () => {
1672
+ run(command);
1673
+ setPopover(null);
1674
+ },
1675
+ children: [
1676
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
1677
+ className: "rre-popover-ico",
1678
+ children: icon
1679
+ }),
1680
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", { children: label }),
1681
+ commandActive(command) ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
1682
+ className: "rre-popover-check",
1683
+ children: EditorIcons.check
1684
+ }) : null
1685
+ ]
1686
+ }, command))
1687
+ }) : null,
1688
+ popover.kind === "code" ? /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
1689
+ className: "rre-popover-list",
1690
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("button", {
1691
+ type: "button",
1692
+ onClick: openCodeDialog,
1693
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
1694
+ className: "rre-popover-ico",
1695
+ children: EditorIcons.code
1696
+ }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", { children: "代码" })]
1697
+ }), /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("button", {
1698
+ type: "button",
1699
+ onClick: runRichCode,
1700
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
1701
+ className: "rre-popover-ico",
1702
+ children: EditorIcons.runCode
1703
+ }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", { children: "运行代码" })]
1704
+ })]
1705
+ }) : null,
1706
+ popover.kind === "template" ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
1707
+ className: "rre-popover-list",
1708
+ children: TEMPLATES.map((item) => /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
1709
+ type: "button",
1710
+ onClick: () => insertTemplate(item.markdown),
1711
+ children: item.label
1712
+ }, item.label))
1713
+ }) : null,
1714
+ popover.kind === "history" ? /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
1715
+ className: "rre-history",
1716
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("b", { children: "本地历史" }), history.length ? history.slice().reverse().map((item) => /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("button", {
1717
+ type: "button",
1718
+ onClick: () => restoreHistory(item.value),
1719
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", { children: new Date(item.at).toLocaleTimeString("zh-CN", { hour12: false }) }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("em", { children: item.value.replace(/\s+/g, " ").slice(0, 30) || "空白" })]
1720
+ }, item.at)) : /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", { children: "还没有历史快照" })]
1721
+ }) : null,
1722
+ popover.kind === "video" ? /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
1723
+ className: "rre-dialog",
1724
+ children: [
1725
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("b", { children: "插入视频" }),
1726
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("input", {
1727
+ className: "rre-input-field",
1728
+ value: videoUrl,
1729
+ onChange: (event) => setVideoUrl(event.target.value),
1730
+ placeholder: "https://…/video.mp4",
1731
+ "aria-label": "视频地址",
1732
+ autoFocus: true
1733
+ }),
1734
+ /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
1735
+ className: "rre-link-actions",
1736
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
1737
+ type: "button",
1738
+ className: "rre-btn",
1739
+ onClick: () => setPopover(null),
1740
+ children: "取消"
1741
+ }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
1742
+ type: "button",
1743
+ className: "rre-btn rre-btn-primary",
1744
+ onClick: insertVideo,
1745
+ children: "插入"
1746
+ })]
1747
+ })
1748
+ ]
1749
+ }) : null,
1750
+ popover.kind === "formula" ? /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
1751
+ className: "rre-dialog",
1752
+ children: [
1753
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("b", { children: "插入公式" }),
1754
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("input", {
1755
+ className: "rre-input-field",
1756
+ value: formulaText,
1757
+ onChange: (event) => setFormulaText(event.target.value),
1758
+ placeholder: "E = mc^2",
1759
+ "aria-label": "LaTeX 公式",
1760
+ autoFocus: true
1761
+ }),
1762
+ /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
1763
+ className: "rre-link-actions",
1764
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
1765
+ type: "button",
1766
+ className: "rre-btn",
1767
+ onClick: () => setPopover(null),
1768
+ children: "取消"
1769
+ }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
1770
+ type: "button",
1771
+ className: "rre-btn rre-btn-primary",
1772
+ onClick: insertFormula,
1773
+ children: "插入"
1774
+ })]
1775
+ })
1776
+ ]
1777
+ }) : null
1778
+ ]
1779
+ }) : null,
1780
+ codeOpen ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
1781
+ className: "rre-code-mask",
1782
+ role: "dialog",
1783
+ "aria-modal": "true",
1784
+ "aria-label": "插入代码",
1785
+ children: /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
1786
+ className: "rre-code-modal",
1787
+ children: [
1788
+ /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
1789
+ className: "rre-code-head",
1790
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("b", { children: "插入代码" }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
1791
+ type: "button",
1792
+ onClick: () => setCodeOpen(false),
1793
+ "aria-label": "关闭",
1794
+ children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)("svg", {
1795
+ width: "15",
1796
+ height: "15",
1797
+ viewBox: "0 0 24 24",
1798
+ fill: "none",
1799
+ stroke: "currentColor",
1800
+ strokeWidth: "2",
1801
+ strokeLinecap: "round",
1802
+ "aria-hidden": "true",
1803
+ children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)("path", { d: "m6 6 12 12M18 6 6 18" })
1804
+ })
1805
+ })]
1806
+ }),
1807
+ /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
1808
+ className: "rre-code-body",
1809
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("textarea", {
1810
+ className: "rre-code-input",
1811
+ value: codeText,
1812
+ onChange: (event) => setCodeText(event.target.value),
1813
+ spellCheck: false,
1814
+ placeholder: "在这里粘贴或输入代码…",
1815
+ autoFocus: true
1816
+ }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
1817
+ className: "rre-code-langs",
1818
+ children: CODE_LANGUAGES.map((language) => /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
1819
+ type: "button",
1820
+ className: codeLang === language.toLowerCase() || language === "CSS/SCSS/LESS" && codeLang === "css" ? "is-on" : "",
1821
+ onClick: () => setCodeLang(language === "CSS/SCSS/LESS" ? "css" : language.toLowerCase()),
1822
+ children: language
1823
+ }, language))
1824
+ })]
1825
+ }),
1826
+ /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
1827
+ className: "rre-code-foot",
1828
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
1829
+ type: "button",
1830
+ className: "rre-btn rre-btn-primary",
1831
+ onClick: insertCode,
1832
+ children: "确定"
1833
+ }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
1834
+ type: "button",
1835
+ className: "rre-btn",
1836
+ onClick: () => setCodeOpen(false),
1837
+ children: "取消"
1838
+ })]
1839
+ })
1840
+ ]
1841
+ })
1842
+ }) : null,
1843
+ richRun ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
1844
+ className: "rre-run-mask",
1845
+ role: "dialog",
1846
+ "aria-modal": "true",
1847
+ "aria-label": "运行代码",
1848
+ children: /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
1849
+ className: "rre-run-modal",
1850
+ children: [
1851
+ /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
1852
+ className: "rre-run-head",
1853
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("b", { children: "运行代码(JavaScript)" }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
1854
+ type: "button",
1855
+ onClick: () => setRichRun(null),
1856
+ "aria-label": "关闭",
1857
+ children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)("svg", {
1858
+ width: "14",
1859
+ height: "14",
1860
+ viewBox: "0 0 24 24",
1861
+ fill: "none",
1862
+ stroke: "currentColor",
1863
+ strokeWidth: "2",
1864
+ strokeLinecap: "round",
1865
+ "aria-hidden": "true",
1866
+ children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)("path", { d: "m6 6 12 12M18 6 6 18" })
1867
+ })
1868
+ })]
1869
+ }),
1870
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("pre", {
1871
+ className: "rre-run-code",
1872
+ children: richRun.code
1873
+ }),
1874
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("iframe", {
1875
+ title: "代码运行结果",
1876
+ sandbox: "allow-scripts",
1877
+ className: "rre-run-frame",
1878
+ srcDoc: `<!doctype html><meta charset="utf-8"><script>
1879
+ const send=(type,args)=>parent.postMessage({source:'rre-code-run',text:(type==='log'?'':type+': ')+args.map(a=>{try{return typeof a==='object'?JSON.stringify(a):String(a)}catch(e){return String(a)}}).join(' ')},'*');
1880
+ ['log','warn','error'].forEach(k=>{console[k]=(...a)=>send(k,a)});
1881
+ try { ${richRun.code.replace(/<\/script/gi, "<\\/script")} } catch (e) { send('error',[e && e.message ? e.message : e]) }
1882
+ <\/script>`
1883
+ }, richRun.key),
1884
+ /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
1885
+ className: "rre-run-output",
1886
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("b", { children: "输出" }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("pre", { children: richRun.output.join("\n") || "(无输出,console.log 会显示在这里)" })]
1887
+ }),
1888
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
1889
+ className: "rre-run-actions",
1890
+ children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
1891
+ type: "button",
1892
+ className: "rre-btn rre-btn-primary",
1893
+ onClick: () => setRichRun({
1894
+ ...richRun,
1895
+ output: [],
1896
+ key: Date.now()
1897
+ }),
1898
+ children: "重新运行"
1899
+ })
1900
+ })
1901
+ ]
1902
+ })
1903
+ }) : null
1904
+ ]
1905
+ });
1906
+ }
1907
+ // src/html-code-preview.ts
1908
+ /**
1909
+ * 为 Markdown 渲染出的 HTML 代码块增加「源码 / 预览 / 复制 / 全屏 / 刷新」。
1910
+ * 只处理 language-html / language-htm,普通代码块完全不动。
1911
+ */
1912
+ const CSP = "default-src 'none'; style-src 'unsafe-inline'; script-src 'unsafe-inline'; img-src data: https: http:; font-src data: https: http:;";
1913
+ function buildDoc(code) {
1914
+ const style = `<style>html,body{margin:0;padding:16px;background:#fff;color:#111827;font:14px/1.7 -apple-system,BlinkMacSystemFont,'Segoe UI','PingFang SC','Microsoft YaHei',sans-serif}img{max-width:100%}a{color:#2563eb}</style>`;
1915
+ if (/<html[\s>]/i.test(code)) return code.replace(/<head([^>]*)>/i, `<head$1><meta http-equiv="Content-Security-Policy" content="${CSP}">${style}`);
1916
+ return `<!doctype html><html><head><meta charset="utf-8"><meta http-equiv="Content-Security-Policy" content="${CSP}">${style}</head><body>${code}</body></html>`;
1917
+ }
1918
+ function makeButton(label, className) {
1919
+ const button = document.createElement("button");
1920
+ button.type = "button";
1921
+ button.className = className;
1922
+ button.textContent = label;
1923
+ return button;
1924
+ }
1925
+ function languageOf(code) {
1926
+ return ((code.className || "").match(/language-([\w-]+)/)?.[1] || "").toLowerCase();
1927
+ }
1928
+ function enhanceHtmlCodeBlocks(container) {
1929
+ container.querySelectorAll("pre > code").forEach((code) => {
1930
+ const pre = code.closest("pre");
1931
+ if (!pre) return;
1932
+ const preEl = pre;
1933
+ const wrapper = preEl.closest(".kb-code, .code-block-wrapper") || pre;
1934
+ const lang = (wrapper.querySelector(".kb-code-lang, .code-block-lang")?.textContent || "").trim().toLowerCase() || languageOf(code);
1935
+ if (lang !== "html" && lang !== "htm") return;
1936
+ if (wrapper.dataset.htmlPreviewEnhanced === "1") return;
1937
+ wrapper.dataset.htmlPreviewEnhanced = "1";
1938
+ wrapper.classList.add("kb-html-code");
1939
+ const actions = document.createElement("div");
1940
+ actions.className = "kb-html-actions";
1941
+ const mode = document.createElement("span");
1942
+ mode.className = "kb-html-mode";
1943
+ const sourceBtn = makeButton("源码", "kb-html-mode-btn is-on");
1944
+ const previewBtn = makeButton("预览", "kb-html-mode-btn");
1945
+ mode.appendChild(sourceBtn);
1946
+ mode.appendChild(previewBtn);
1947
+ const copyBtn = Boolean(wrapper.querySelector(".code-block-copy")) ? null : makeButton("复制", "kb-html-action-btn");
1948
+ const fullBtn = makeButton("全屏", "kb-html-action-btn");
1949
+ const refreshBtn = makeButton("刷新", "kb-html-action-btn");
1950
+ refreshBtn.hidden = true;
1951
+ actions.append(mode);
1952
+ if (copyBtn) actions.appendChild(copyBtn);
1953
+ actions.append(fullBtn, refreshBtn);
1954
+ const header = wrapper.querySelector(".code-block-header");
1955
+ if (header) header.appendChild(actions);
1956
+ else wrapper.appendChild(actions);
1957
+ const preview = document.createElement("div");
1958
+ preview.className = "kb-html-preview";
1959
+ preview.hidden = true;
1960
+ wrapper.appendChild(preview);
1961
+ let iframe = null;
1962
+ let fullMask = null;
1963
+ let fullFrame = null;
1964
+ const source = code.textContent || "";
1965
+ function ensureFrame() {
1966
+ if (iframe) return iframe;
1967
+ iframe = document.createElement("iframe");
1968
+ iframe.className = "kb-html-preview-frame";
1969
+ iframe.setAttribute("sandbox", "allow-scripts");
1970
+ iframe.setAttribute("title", "HTML 预览");
1971
+ iframe.srcdoc = buildDoc(source);
1972
+ preview.appendChild(iframe);
1973
+ return iframe;
1974
+ }
1975
+ function setMode(isPreview) {
1976
+ preEl.hidden = isPreview;
1977
+ preview.hidden = !isPreview;
1978
+ sourceBtn.classList.toggle("is-on", !isPreview);
1979
+ previewBtn.classList.toggle("is-on", isPreview);
1980
+ refreshBtn.hidden = !isPreview;
1981
+ if (isPreview) ensureFrame();
1982
+ }
1983
+ sourceBtn.addEventListener("click", () => setMode(false));
1984
+ previewBtn.addEventListener("click", () => setMode(true));
1985
+ copyBtn?.addEventListener("click", async () => {
1986
+ try {
1987
+ await navigator.clipboard.writeText(source);
1988
+ copyBtn.textContent = "已复制";
1989
+ } catch {
1990
+ copyBtn.textContent = "复制失败";
1991
+ }
1992
+ window.setTimeout(() => {
1993
+ copyBtn.textContent = "复制";
1994
+ }, 1800);
1995
+ });
1996
+ refreshBtn.addEventListener("click", () => {
1997
+ if (iframe) iframe.srcdoc = buildDoc(source);
1998
+ });
1999
+ fullBtn.addEventListener("click", () => {
2000
+ if (!fullMask) {
2001
+ fullMask = document.createElement("div");
2002
+ fullMask.className = "kb-html-full-mask";
2003
+ const panel = document.createElement("div");
2004
+ panel.className = "kb-html-full-panel";
2005
+ const bar = document.createElement("div");
2006
+ bar.className = "kb-html-full-bar";
2007
+ const label = document.createElement("b");
2008
+ label.textContent = "HTML 预览";
2009
+ const close = makeButton("关闭", "kb-html-action-btn");
2010
+ bar.append(label, close);
2011
+ fullFrame = document.createElement("iframe");
2012
+ fullFrame.setAttribute("sandbox", "allow-scripts");
2013
+ fullFrame.setAttribute("title", "HTML 全屏预览");
2014
+ panel.append(bar, fullFrame);
2015
+ fullMask.appendChild(panel);
2016
+ document.body.appendChild(fullMask);
2017
+ close.addEventListener("click", () => {
2018
+ fullMask?.remove();
2019
+ fullMask = null;
2020
+ fullFrame = null;
2021
+ });
2022
+ fullMask.addEventListener("mousedown", (event) => {
2023
+ if (event.target === fullMask) {
2024
+ fullMask?.remove();
2025
+ fullMask = null;
2026
+ fullFrame = null;
2027
+ }
2028
+ });
2029
+ }
2030
+ if (fullFrame) fullFrame.srcdoc = buildDoc(source);
2031
+ });
2032
+ });
2033
+ }
2034
+ // src/MarkdownEditor.tsx
2035
+ const LANGUAGES = [
2036
+ "Bash",
2037
+ "C",
2038
+ "C++",
2039
+ "C#",
2040
+ "CSS",
2041
+ "Dart",
2042
+ "Go",
2043
+ "Java",
2044
+ "JavaScript",
2045
+ "JSON",
2046
+ "Kotlin",
2047
+ "Markdown",
2048
+ "PHP",
2049
+ "Python",
2050
+ "Ruby",
2051
+ "Rust",
2052
+ "SQL",
2053
+ "Swift",
2054
+ "TypeScript",
2055
+ "YAML"
2056
+ ];
2057
+ const SYNTAX_TIPS = [
2058
+ ["标题", "# 一级标题 / ## 二级标题"],
2059
+ ["加粗", "**加粗**"],
2060
+ ["斜体", "*斜体*"],
2061
+ ["删除线", "~~删除线~~"],
2062
+ ["下划线", "<u>下划线</u>"],
2063
+ ["列表", "- 无序 / 1. 有序 / - [ ] 待办"],
2064
+ ["引用", "> 引用内容"],
2065
+ ["代码块", "```js 代码 ```"],
2066
+ ["表格", "| 列 1 | 列 2 |"],
2067
+ ["链接", "[文字](https://example.com)"],
2068
+ ["图片", "![说明](https://example.com/a.png)"],
2069
+ ["目录", "@[TOC](目录)"]
2070
+ ];
2071
+ function headingLines(markdown) {
2072
+ const lines = markdown.split("\n");
2073
+ const result = [];
2074
+ let inFence = false;
2075
+ lines.forEach((line, index) => {
2076
+ const trimmed = line.trim();
2077
+ if (/^(```|~~~)/.test(trimmed)) {
2078
+ inFence = !inFence;
2079
+ return;
2080
+ }
2081
+ if (!inFence && /^#{1,6}\s+/.test(trimmed)) result.push(index);
2082
+ });
2083
+ return result;
2084
+ }
2085
+ function markdownHeadings(markdown) {
2086
+ return headingLines(markdown).map((index) => {
2087
+ const line = markdown.split("\n")[index] || "";
2088
+ return {
2089
+ index,
2090
+ level: line.match(/^#+/)?.[0].length || 1,
2091
+ text: line.replace(/^#{1,6}\s+/, "").trim() || "未命名标题"
2092
+ };
2093
+ });
2094
+ }
2095
+ function MarkdownEditor({ markdown, onChange, onUploadImage, renderMarkdown = defaultRenderMarkdown, onSwitchToRichEditor, switchLabel = "使用普通编辑器", onSave, fileBaseName = "article", features, initialView = "split", placeholder = "# 从这里开始写 Markdown…", className = "" }) {
2096
+ const feature = (key) => features?.[key] !== false;
2097
+ const [view, setView] = (0, react.useState)(initialView);
2098
+ const [uploading, setUploading] = (0, react.useState)(false);
2099
+ const [error, setError] = (0, react.useState)("");
2100
+ const [containerWidth, setContainerWidth] = (0, react.useState)(0);
2101
+ const [menu, setMenu] = (0, react.useState)(null);
2102
+ const [sidePanel, setSidePanel] = (0, react.useState)(null);
2103
+ const [railCollapsed, setRailCollapsed] = (0, react.useState)(false);
2104
+ const [videoOpen, setVideoOpen] = (0, react.useState)(false);
2105
+ const [videoUrl, setVideoUrl] = (0, react.useState)("");
2106
+ const [pendingImport, setPendingImport] = (0, react.useState)(null);
2107
+ const [codeRun, setCodeRun] = (0, react.useState)(null);
2108
+ const rootRef = (0, react.useRef)(null);
2109
+ const textareaRef = (0, react.useRef)(null);
2110
+ const previewRef = (0, react.useRef)(null);
2111
+ const imageRef = (0, react.useRef)(null);
2112
+ const importRef = (0, react.useRef)(null);
2113
+ const previewHeadingOffsets = (0, react.useRef)([]);
2114
+ const sourceLockRef = (0, react.useRef)(0);
2115
+ const previewLockRef = (0, react.useRef)(0);
2116
+ const previewHtml = (0, react.useMemo)(() => renderMarkdown(markdown), [markdown, renderMarkdown]);
2117
+ const headings = (0, react.useMemo)(() => markdownHeadings(markdown), [markdown]);
2118
+ const sourceHeadingRatios = (0, react.useMemo)(() => {
2119
+ const lines = markdown.split("\n");
2120
+ const total = Math.max(1, lines.length - 1);
2121
+ return headingLines(markdown).map((line) => Math.min(1, line / total));
2122
+ }, [markdown]);
2123
+ (0, react.useEffect)(() => {
2124
+ const el = rootRef.current;
2125
+ if (!el) return;
2126
+ const observer = new ResizeObserver((entries) => {
2127
+ setContainerWidth(entries[0]?.contentRect.width ?? 0);
2128
+ });
2129
+ observer.observe(el);
2130
+ return () => observer.disconnect();
2131
+ }, []);
2132
+ (0, react.useEffect)(() => {
2133
+ const pv = previewRef.current;
2134
+ if (!pv) return;
2135
+ const run = () => enhanceHtmlCodeBlocks(pv);
2136
+ run();
2137
+ const observer = new MutationObserver(run);
2138
+ observer.observe(pv, {
2139
+ childList: true,
2140
+ subtree: true
2141
+ });
2142
+ return () => observer.disconnect();
2143
+ }, []);
2144
+ (0, react.useEffect)(() => {
2145
+ const pv = previewRef.current;
2146
+ if (!pv) return;
2147
+ const raf = window.requestAnimationFrame(() => {
2148
+ const base = pv.getBoundingClientRect().top - pv.scrollTop;
2149
+ previewHeadingOffsets.current = Array.from(pv.querySelectorAll("h1,h2,h3,h4,h5,h6")).map((el) => el.getBoundingClientRect().top - base);
2150
+ });
2151
+ return () => window.cancelAnimationFrame(raf);
2152
+ }, [markdown, view]);
2153
+ (0, react.useEffect)(() => {
2154
+ if (!menu) return;
2155
+ const onDown = (event) => {
2156
+ const target = event.target;
2157
+ if (target?.closest(".rre-md-menu") || target?.closest(".rre-md-menu-btn")) return;
2158
+ setMenu(null);
2159
+ };
2160
+ document.addEventListener("mousedown", onDown);
2161
+ return () => document.removeEventListener("mousedown", onDown);
2162
+ }, [menu]);
2163
+ (0, react.useEffect)(() => {
2164
+ function onMessage(event) {
2165
+ const data = event.data;
2166
+ if (!data || data.source !== "rre-code-run") return;
2167
+ setCodeRun((prev) => prev ? {
2168
+ ...prev,
2169
+ output: [...prev.output, String(data.text)]
2170
+ } : prev);
2171
+ }
2172
+ window.addEventListener("message", onMessage);
2173
+ return () => window.removeEventListener("message", onMessage);
2174
+ }, []);
2175
+ function insertAtCursor(before, after = "", fallback = "文本") {
2176
+ const el = textareaRef.current;
2177
+ const start = el?.selectionStart ?? markdown.length;
2178
+ const end = el?.selectionEnd ?? markdown.length;
2179
+ const selected = markdown.slice(start, end) || fallback;
2180
+ onChange(markdown.slice(0, start) + before + selected + after + markdown.slice(end));
2181
+ window.requestAnimationFrame(() => {
2182
+ el?.focus();
2183
+ el?.setSelectionRange(start + before.length, start + before.length + selected.length);
2184
+ });
2185
+ setMenu(null);
2186
+ }
2187
+ function onKeyDown(event) {
2188
+ if (event.key !== "Tab") return;
2189
+ event.preventDefault();
2190
+ const el = event.currentTarget;
2191
+ const start = el.selectionStart;
2192
+ const end = el.selectionEnd;
2193
+ onChange(markdown.slice(0, start) + " " + markdown.slice(end));
2194
+ window.requestAnimationFrame(() => {
2195
+ el.selectionStart = start + 2;
2196
+ el.selectionEnd = start + 2;
2197
+ });
2198
+ }
2199
+ function previewOffsetForRatio(ratio, previewMax) {
2200
+ const source = sourceHeadingRatios;
2201
+ const preview = previewHeadingOffsets.current;
2202
+ if (!source.length || source.length !== preview.length) return null;
2203
+ if (ratio <= source[0]) return (source[0] ? ratio / source[0] : 0) * preview[0];
2204
+ for (let i = 1; i < source.length; i += 1) if (ratio <= source[i]) {
2205
+ const span = source[i] - source[i - 1] || 1;
2206
+ const progress = (ratio - source[i - 1]) / span;
2207
+ return preview[i - 1] + progress * (preview[i] - preview[i - 1]);
2208
+ }
2209
+ const last = source[source.length - 1];
2210
+ const lastPreview = preview[preview.length - 1];
2211
+ return lastPreview + (last < 1 ? (ratio - last) / (1 - last) : 1) * (previewMax - lastPreview);
2212
+ }
2213
+ function ratioForPreviewOffset(offset, previewMax) {
2214
+ const source = sourceHeadingRatios;
2215
+ const preview = previewHeadingOffsets.current;
2216
+ if (!source.length || source.length !== preview.length) return null;
2217
+ if (offset <= preview[0]) return preview[0] ? offset / preview[0] * source[0] : 0;
2218
+ for (let i = 1; i < preview.length; i += 1) if (offset <= preview[i]) {
2219
+ const span = preview[i] - preview[i - 1] || 1;
2220
+ const progress = (offset - preview[i - 1]) / span;
2221
+ return source[i - 1] + progress * (source[i] - source[i - 1]);
2222
+ }
2223
+ const lastSource = source[source.length - 1];
2224
+ const lastPreview = preview[preview.length - 1];
2225
+ return lastSource + (lastPreview < previewMax ? (offset - lastPreview) / (previewMax - lastPreview) : 1) * (1 - lastSource);
2226
+ }
2227
+ function onSourceScroll(event) {
2228
+ if (Date.now() < sourceLockRef.current) return;
2229
+ const preview = previewRef.current;
2230
+ if (!preview) return;
2231
+ const sourceMax = event.currentTarget.scrollHeight - event.currentTarget.clientHeight;
2232
+ const previewMax = preview.scrollHeight - preview.clientHeight;
2233
+ if (sourceMax <= 0 || previewMax <= 0) return;
2234
+ previewLockRef.current = Date.now() + 80;
2235
+ const ratio = event.currentTarget.scrollTop / sourceMax;
2236
+ const target = previewOffsetForRatio(ratio, previewMax);
2237
+ preview.scrollTop = target === null ? ratio * previewMax : Math.max(0, Math.min(previewMax, target - 8));
2238
+ }
2239
+ function onPreviewScroll(event) {
2240
+ if (Date.now() < previewLockRef.current) return;
2241
+ const source = textareaRef.current;
2242
+ if (!source) return;
2243
+ const sourceMax = source.scrollHeight - source.clientHeight;
2244
+ const previewMax = event.currentTarget.scrollHeight - event.currentTarget.clientHeight;
2245
+ if (sourceMax <= 0 || previewMax <= 0) return;
2246
+ sourceLockRef.current = Date.now() + 80;
2247
+ const ratio = ratioForPreviewOffset(event.currentTarget.scrollTop, previewMax);
2248
+ source.scrollTop = (ratio === null ? event.currentTarget.scrollTop / previewMax : ratio) * sourceMax;
2249
+ }
2250
+ async function onImageFile(event) {
2251
+ const file = event.target.files?.[0];
2252
+ event.target.value = "";
2253
+ if (!file) return;
2254
+ setUploading(true);
2255
+ setError("");
2256
+ try {
2257
+ const url = await onUploadImage(file);
2258
+ insertAtCursor(`![${file.name.replace(/\.[^.]+$/, "")}](${url})`, "", file.name);
2259
+ } catch (err) {
2260
+ setError(err instanceof Error ? err.message : "图片上传失败");
2261
+ } finally {
2262
+ setUploading(false);
2263
+ }
2264
+ }
2265
+ function openMenu(kind, element) {
2266
+ const rect = element.getBoundingClientRect();
2267
+ setMenu({
2268
+ kind,
2269
+ left: rect.left,
2270
+ top: rect.bottom + 4
2271
+ });
2272
+ }
2273
+ function menuButton(kind, label, icon) {
2274
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("button", {
2275
+ type: "button",
2276
+ className: `rre-md-menu-btn${menu?.kind === kind ? " is-on" : ""}`,
2277
+ title: label,
2278
+ "aria-label": label,
2279
+ onMouseDown: (event) => event.preventDefault(),
2280
+ onClick: (event) => menu?.kind === kind ? setMenu(null) : openMenu(kind, event.currentTarget),
2281
+ children: [
2282
+ icon,
2283
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", { children: label }),
2284
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("svg", {
2285
+ className: "rre-md-caret",
2286
+ width: "10",
2287
+ height: "10",
2288
+ viewBox: "0 0 24 24",
2289
+ fill: "none",
2290
+ stroke: "currentColor",
2291
+ strokeWidth: "2.4",
2292
+ strokeLinecap: "round",
2293
+ strokeLinejoin: "round",
2294
+ "aria-hidden": "true",
2295
+ children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)("path", { d: "m6 9 6 6 6-6" })
2296
+ })
2297
+ ]
2298
+ });
2299
+ }
2300
+ function mdTool(label, icon, onClick, strong = false) {
2301
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
2302
+ type: "button",
2303
+ className: `rre-md-tool${strong ? " is-strong" : ""}`,
2304
+ title: label,
2305
+ "aria-label": label,
2306
+ onMouseDown: (event) => event.preventDefault(),
2307
+ onClick,
2308
+ children: icon
2309
+ });
2310
+ }
2311
+ function insertTable() {
2312
+ insertAtCursor("| 列 1 | 列 2 |\n| --- | --- |\n| 内容 | 内容 |\n", "", "");
2313
+ setMenu(null);
2314
+ }
2315
+ function insertTodo() {
2316
+ insertAtCursor("- [ ] ", "", "待办事项");
2317
+ }
2318
+ function openVideo() {
2319
+ setMenu(null);
2320
+ setVideoUrl("");
2321
+ setVideoOpen(true);
2322
+ }
2323
+ function insertVideo() {
2324
+ const url = videoUrl.trim();
2325
+ if (!/^(https?:\/\/|\/|\.\.?\/)/i.test(url)) {
2326
+ setError("请输入 http(s) 或站内视频地址");
2327
+ return;
2328
+ }
2329
+ insertAtCursor(`<video src="${url}" controls></video>\n`, "", "");
2330
+ setVideoOpen(false);
2331
+ setError("");
2332
+ }
2333
+ function getCodeForRun() {
2334
+ const el = textareaRef.current;
2335
+ if (!el) return null;
2336
+ const selected = markdown.slice(el.selectionStart, el.selectionEnd).trim();
2337
+ if (selected) return {
2338
+ code: selected,
2339
+ language: "js"
2340
+ };
2341
+ const lines = markdown.split("\n");
2342
+ let startLine = -1;
2343
+ let language = "";
2344
+ for (let i = 0; i <= lines.length; i += 1) if (i < lines.length && /^```/.test(lines[i].trim())) {
2345
+ if (startLine < 0) {
2346
+ startLine = i;
2347
+ language = lines[i].trim().replace(/^```/, "").trim();
2348
+ } else return {
2349
+ code: lines.slice(startLine + 1, i).join("\n"),
2350
+ language
2351
+ };
2352
+ }
2353
+ return null;
2354
+ }
2355
+ function runCode() {
2356
+ setMenu(null);
2357
+ const found = getCodeForRun();
2358
+ if (!found) {
2359
+ setError("请先选中代码,或把光标放在 fenced 代码块内");
2360
+ return;
2361
+ }
2362
+ if (!/^(js|javascript)$/i.test(found.language || "js")) {
2363
+ setError("代码运行目前只支持 JavaScript");
2364
+ return;
2365
+ }
2366
+ setError("");
2367
+ setCodeRun({
2368
+ code: found.code,
2369
+ output: [],
2370
+ key: Date.now()
2371
+ });
2372
+ }
2373
+ function onImportFile(event) {
2374
+ const file = event.target.files?.[0];
2375
+ event.target.value = "";
2376
+ if (!file) return;
2377
+ file.text().then((text) => {
2378
+ if (markdown.trim()) {
2379
+ setPendingImport({
2380
+ name: file.name,
2381
+ text
2382
+ });
2383
+ return;
2384
+ }
2385
+ onChange(text);
2386
+ });
2387
+ }
2388
+ function exportMarkdown() {
2389
+ const blob = new Blob([markdown], { type: "text/markdown;charset=utf-8" });
2390
+ const url = URL.createObjectURL(blob);
2391
+ const link = document.createElement("a");
2392
+ link.href = url;
2393
+ link.download = `${fileBaseName || "article"}.md`;
2394
+ document.body.appendChild(link);
2395
+ link.click();
2396
+ link.remove();
2397
+ window.setTimeout(() => URL.revokeObjectURL(url), 1e3);
2398
+ setMenu(null);
2399
+ }
2400
+ function scrollOutline(index) {
2401
+ const el = textareaRef.current;
2402
+ if (!el) return;
2403
+ const lines = markdown.split("\n").length || 1;
2404
+ el.focus();
2405
+ el.scrollTop = Math.max(0, index / lines * el.scrollHeight - 40);
2406
+ const preview = previewRef.current;
2407
+ if (preview) preview.scrollTop = Math.max(0, index / lines * preview.scrollHeight - 40);
2408
+ setSidePanel(null);
2409
+ }
2410
+ const codeDoc = codeRun ? `<!doctype html><meta charset="utf-8"><script>
2411
+ const send=(type,args)=>parent.postMessage({source:'rre-code-run',text:(type==='log'?'':type+': ')+args.map(a=>{try{return typeof a==='object'?JSON.stringify(a):String(a)}catch(e){return String(a)}}).join(' ')},'*');
2412
+ ['log','warn','error'].forEach(k=>{console[k]=(...a)=>send(k,a)});
2413
+ try { ${codeRun.code.replace(/<\/script/gi, "<\\/script")} } catch (e) { send('error',[e && e.message ? e.message : e]) }
2414
+ <\/script>` : "";
2415
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
2416
+ ref: rootRef,
2417
+ className: `rre-md-root${className ? " " + className : ""}${containerWidth > 0 && containerWidth <= 900 ? " is-narrow" : ""}`,
2418
+ children: [
2419
+ /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
2420
+ className: "rre-md-modes",
2421
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
2422
+ className: "rre-md-mode-group",
2423
+ children: [
2424
+ /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("button", {
2425
+ type: "button",
2426
+ className: view === "markdown" ? "is-on" : "",
2427
+ onClick: () => setView("markdown"),
2428
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
2429
+ className: "rre-md-tab-icon",
2430
+ children: EditorIcons.doc
2431
+ }), "Markdown"]
2432
+ }),
2433
+ /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("button", {
2434
+ type: "button",
2435
+ className: view === "split" ? "is-on" : "",
2436
+ onClick: () => setView("split"),
2437
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
2438
+ className: "rre-md-tab-icon",
2439
+ children: EditorIcons.split
2440
+ }), "比对"]
2441
+ }),
2442
+ /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("button", {
2443
+ type: "button",
2444
+ className: view === "preview" ? "is-on" : "",
2445
+ onClick: () => setView("preview"),
2446
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
2447
+ className: "rre-md-tab-icon",
2448
+ children: EditorIcons.preview
2449
+ }), "预览"]
2450
+ })
2451
+ ]
2452
+ }), onSwitchToRichEditor ? /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("button", {
2453
+ type: "button",
2454
+ className: "rre-md-switch",
2455
+ onClick: onSwitchToRichEditor,
2456
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
2457
+ className: "rre-md-tab-icon",
2458
+ children: EditorIcons.switchEditor
2459
+ }), switchLabel]
2460
+ }) : null]
2461
+ }),
2462
+ /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
2463
+ className: "rre-md-toolbar",
2464
+ children: [
2465
+ feature("bold") ? mdTool("加粗 Ctrl+B", EditorIcons.bold, () => insertAtCursor("**", "**", "加粗"), true) : null,
2466
+ feature("italic") ? mdTool("斜体 Ctrl+I", EditorIcons.italic, () => insertAtCursor("*", "*", "斜体")) : null,
2467
+ feature("format") ? mdTool("标题", EditorIcons.heading, () => insertAtCursor("## ", "", "标题")) : null,
2468
+ feature("strike") ? mdTool("删除线", EditorIcons.strike, () => insertAtCursor("~~", "~~", "删除线")) : null,
2469
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", { className: "rre-md-sep" }),
2470
+ feature("list") ? menuButton("list", "列表", EditorIcons.ul) : null,
2471
+ feature("code") ? menuButton("code", "代码块", EditorIcons.code) : null,
2472
+ feature("quote") ? menuButton("more-format", "更多格式") : null,
2473
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", { className: "rre-md-sep" }),
2474
+ feature("image") ? mdTool(uploading ? "上传中" : "图片", EditorIcons.image, () => imageRef.current?.click()) : null,
2475
+ feature("link") ? mdTool("超链接", EditorIcons.link, () => insertAtCursor("[", "](https://)", "链接文字")) : null,
2476
+ feature("video") || feature("table") ? menuButton("more-insert", "更多插入") : null,
2477
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", { className: "rre-md-sep" }),
2478
+ feature("save") && onSave ? mdTool("保存草稿", EditorIcons.save, onSave) : null,
2479
+ feature("history") ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
2480
+ type: "button",
2481
+ className: "rre-md-tool is-disabled",
2482
+ title: "历史版本",
2483
+ "aria-label": "历史版本",
2484
+ disabled: true,
2485
+ children: EditorIcons.history
2486
+ }) : null,
2487
+ feature("more") ? menuButton("more-actions", "更多操作") : null,
2488
+ error ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
2489
+ className: "rre-md-error",
2490
+ children: error
2491
+ }) : null
2492
+ ]
2493
+ }),
2494
+ /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
2495
+ className: "rre-md-main",
2496
+ children: [
2497
+ /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
2498
+ className: `rre-md-split mode-${view}`,
2499
+ children: [
2500
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
2501
+ className: "rre-md-source",
2502
+ children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)("textarea", {
2503
+ ref: textareaRef,
2504
+ className: "rre-md-input",
2505
+ value: markdown,
2506
+ onChange: (event) => onChange(event.target.value),
2507
+ onKeyDown,
2508
+ onScroll: onSourceScroll,
2509
+ placeholder,
2510
+ spellCheck: false,
2511
+ "aria-label": "Markdown 编辑器"
2512
+ })
2513
+ }),
2514
+ /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("span", {
2515
+ className: "rre-md-drag",
2516
+ "aria-hidden": "true",
2517
+ children: [
2518
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("i", {}),
2519
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("i", {}),
2520
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("i", {})
2521
+ ]
2522
+ }),
2523
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
2524
+ ref: previewRef,
2525
+ className: `rre-md-preview${markdown.trim() ? "" : " is-empty"}`,
2526
+ onScroll: onPreviewScroll,
2527
+ children: markdown.trim() ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", { dangerouslySetInnerHTML: { __html: previewHtml } }) : /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(react_jsx_runtime.Fragment, { children: [
2528
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
2529
+ className: "rre-md-empty-ico",
2530
+ children: EditorIcons.doc
2531
+ }),
2532
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("b", { children: "实时预览" }),
2533
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", { children: "在左侧输入 Markdown,这里会同步渲染。" })
2534
+ ] })
2535
+ })
2536
+ ]
2537
+ }),
2538
+ feature("sidebar") ? railCollapsed ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
2539
+ type: "button",
2540
+ className: "rre-md-rail-open",
2541
+ onClick: () => setRailCollapsed(false),
2542
+ "aria-label": "展开侧栏",
2543
+ title: "展开侧栏",
2544
+ children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)("svg", {
2545
+ width: "14",
2546
+ height: "14",
2547
+ viewBox: "0 0 24 24",
2548
+ fill: "none",
2549
+ stroke: "currentColor",
2550
+ strokeWidth: "1.9",
2551
+ strokeLinecap: "round",
2552
+ strokeLinejoin: "round",
2553
+ "aria-hidden": "true",
2554
+ children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)("path", { d: "m15 6-6 6 6 6" })
2555
+ })
2556
+ }) : /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("aside", {
2557
+ className: "rre-md-rail",
2558
+ "aria-label": "编辑器侧栏",
2559
+ children: [
2560
+ /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("button", {
2561
+ type: "button",
2562
+ className: "rre-md-rail-item",
2563
+ onClick: () => setRailCollapsed(true),
2564
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("svg", {
2565
+ width: "18",
2566
+ height: "18",
2567
+ viewBox: "0 0 24 24",
2568
+ fill: "none",
2569
+ stroke: "currentColor",
2570
+ strokeWidth: "1.9",
2571
+ strokeLinecap: "round",
2572
+ strokeLinejoin: "round",
2573
+ "aria-hidden": "true",
2574
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("path", { d: "m9 6 6 6-6 6" }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("path", { d: "M5 6v12" })]
2575
+ }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("em", { children: "收起" })]
2576
+ }),
2577
+ feature("outline") ? /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("button", {
2578
+ type: "button",
2579
+ className: `rre-md-rail-item${sidePanel === "outline" ? " is-on" : ""}`,
2580
+ onClick: () => setSidePanel((prev) => prev === "outline" ? null : "outline"),
2581
+ children: [EditorIcons.toc, /* @__PURE__ */ (0, react_jsx_runtime.jsx)("em", { children: "目录" })]
2582
+ }) : null,
2583
+ feature("syntax") ? /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("button", {
2584
+ type: "button",
2585
+ className: `rre-md-rail-item${sidePanel === "syntax" ? " is-on" : ""}`,
2586
+ onClick: () => setSidePanel((prev) => prev === "syntax" ? null : "syntax"),
2587
+ children: [EditorIcons.code, /* @__PURE__ */ (0, react_jsx_runtime.jsx)("em", { children: "语法" })]
2588
+ }) : null
2589
+ ]
2590
+ }) : null,
2591
+ sidePanel ? /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
2592
+ className: `rre-md-side-panel is-${sidePanel}`,
2593
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
2594
+ className: "rre-md-side-head",
2595
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("b", { children: sidePanel === "outline" ? "目录" : "Markdown 语法" }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
2596
+ type: "button",
2597
+ onClick: () => setSidePanel(null),
2598
+ "aria-label": "关闭",
2599
+ children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)("svg", {
2600
+ width: "14",
2601
+ height: "14",
2602
+ viewBox: "0 0 24 24",
2603
+ fill: "none",
2604
+ stroke: "currentColor",
2605
+ strokeWidth: "2",
2606
+ strokeLinecap: "round",
2607
+ "aria-hidden": "true",
2608
+ children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)("path", { d: "m6 6 12 12M18 6 6 18" })
2609
+ })
2610
+ })]
2611
+ }), sidePanel === "outline" ? headings.length ? headings.map((heading) => /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
2612
+ type: "button",
2613
+ className: "rre-md-outline-item",
2614
+ style: { paddingLeft: 10 + (heading.level - 1) * 12 },
2615
+ onClick: () => scrollOutline(heading.index),
2616
+ children: heading.text
2617
+ }, `${heading.index}-${heading.text}`)) : /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", {
2618
+ className: "rre-md-side-empty",
2619
+ children: "文内增加标题后会生成目录"
2620
+ }) : /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
2621
+ className: "rre-md-syntax-list",
2622
+ children: SYNTAX_TIPS.map(([name, sample]) => /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", { children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("b", { children: name }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("code", { children: sample })] }, name))
2623
+ })]
2624
+ }) : null
2625
+ ]
2626
+ }),
2627
+ menu ? /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
2628
+ className: "rre-md-menu",
2629
+ style: {
2630
+ left: menu.left,
2631
+ top: menu.top
2632
+ },
2633
+ children: [
2634
+ menu.kind === "list" ? /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(react_jsx_runtime.Fragment, { children: [
2635
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
2636
+ type: "button",
2637
+ onClick: () => insertAtCursor("- ", "", "列表项"),
2638
+ children: "无序列表"
2639
+ }),
2640
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
2641
+ type: "button",
2642
+ onClick: () => insertAtCursor("1. ", "", "列表项"),
2643
+ children: "有序列表"
2644
+ }),
2645
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
2646
+ type: "button",
2647
+ onClick: () => {
2648
+ insertTodo();
2649
+ setMenu(null);
2650
+ },
2651
+ children: "待办事项"
2652
+ })
2653
+ ] }) : null,
2654
+ menu.kind === "code" ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
2655
+ className: "rre-md-lang-list",
2656
+ children: LANGUAGES.map((language) => /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
2657
+ type: "button",
2658
+ onClick: () => insertAtCursor(`\`\`\`${language.toLowerCase()}\n`, "\n```", "code"),
2659
+ children: language
2660
+ }, language))
2661
+ }) : null,
2662
+ menu.kind === "more-format" ? /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(react_jsx_runtime.Fragment, { children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
2663
+ type: "button",
2664
+ onClick: () => insertAtCursor("> ", "", "引用"),
2665
+ children: "引用"
2666
+ }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
2667
+ type: "button",
2668
+ onClick: runCode,
2669
+ children: "代码运行"
2670
+ })] }) : null,
2671
+ menu.kind === "more-insert" ? /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(react_jsx_runtime.Fragment, { children: [feature("video") ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
2672
+ type: "button",
2673
+ onClick: openVideo,
2674
+ children: "视频"
2675
+ }) : null, feature("table") ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
2676
+ type: "button",
2677
+ onClick: insertTable,
2678
+ children: "表格"
2679
+ }) : null] }) : null,
2680
+ menu.kind === "more-actions" ? /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(react_jsx_runtime.Fragment, { children: [
2681
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
2682
+ type: "button",
2683
+ onClick: () => {
2684
+ textareaRef.current?.focus();
2685
+ document.execCommand("undo");
2686
+ setMenu(null);
2687
+ },
2688
+ children: "撤销"
2689
+ }),
2690
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
2691
+ type: "button",
2692
+ onClick: () => {
2693
+ textareaRef.current?.focus();
2694
+ document.execCommand("redo");
2695
+ setMenu(null);
2696
+ },
2697
+ children: "重做"
2698
+ }),
2699
+ feature("importMd") ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
2700
+ type: "button",
2701
+ onClick: () => {
2702
+ setMenu(null);
2703
+ importRef.current?.click();
2704
+ },
2705
+ children: "导入 md"
2706
+ }) : null,
2707
+ feature("exportMd") ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
2708
+ type: "button",
2709
+ onClick: exportMarkdown,
2710
+ children: "导出 md"
2711
+ }) : null
2712
+ ] }) : null
2713
+ ]
2714
+ }) : null,
2715
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("input", {
2716
+ ref: imageRef,
2717
+ type: "file",
2718
+ accept: "image/png,image/jpeg,image/gif,image/webp",
2719
+ hidden: true,
2720
+ onChange: (event) => void onImageFile(event)
2721
+ }),
2722
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("input", {
2723
+ ref: importRef,
2724
+ type: "file",
2725
+ accept: ".md,.markdown,text/markdown,text/plain",
2726
+ hidden: true,
2727
+ onChange: onImportFile
2728
+ }),
2729
+ videoOpen ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
2730
+ className: "rre-md-modal-mask",
2731
+ role: "dialog",
2732
+ "aria-modal": "true",
2733
+ "aria-label": "插入视频",
2734
+ children: /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
2735
+ className: "rre-md-modal",
2736
+ children: [
2737
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("b", { children: "插入视频" }),
2738
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("input", {
2739
+ className: "rre-md-field",
2740
+ value: videoUrl,
2741
+ onChange: (event) => setVideoUrl(event.target.value),
2742
+ placeholder: "https://…/video.mp4",
2743
+ autoFocus: true
2744
+ }),
2745
+ /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
2746
+ className: "rre-md-modal-actions",
2747
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
2748
+ type: "button",
2749
+ className: "rre-md-btn",
2750
+ onClick: () => setVideoOpen(false),
2751
+ children: "取消"
2752
+ }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
2753
+ type: "button",
2754
+ className: "rre-md-btn is-primary",
2755
+ onClick: insertVideo,
2756
+ children: "插入"
2757
+ })]
2758
+ })
2759
+ ]
2760
+ })
2761
+ }) : null,
2762
+ pendingImport ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
2763
+ className: "rre-md-modal-mask",
2764
+ role: "dialog",
2765
+ "aria-modal": "true",
2766
+ "aria-label": "导入 Markdown",
2767
+ children: /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
2768
+ className: "rre-md-modal",
2769
+ children: [
2770
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("b", { children: "覆盖当前内容?" }),
2771
+ /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("p", { children: [
2772
+ "导入「",
2773
+ pendingImport.name,
2774
+ "」会覆盖编辑器里当前的内容,原内容无法恢复。"
2775
+ ] }),
2776
+ /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
2777
+ className: "rre-md-modal-actions",
2778
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
2779
+ type: "button",
2780
+ className: "rre-md-btn",
2781
+ onClick: () => setPendingImport(null),
2782
+ children: "取消"
2783
+ }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
2784
+ type: "button",
2785
+ className: "rre-md-btn is-danger",
2786
+ onClick: () => {
2787
+ onChange(pendingImport.text);
2788
+ setPendingImport(null);
2789
+ },
2790
+ children: "覆盖导入"
2791
+ })]
2792
+ })
2793
+ ]
2794
+ })
2795
+ }) : null,
2796
+ codeRun ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
2797
+ className: "rre-md-modal-mask",
2798
+ role: "dialog",
2799
+ "aria-modal": "true",
2800
+ "aria-label": "运行代码",
2801
+ children: /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
2802
+ className: "rre-md-modal rre-md-run",
2803
+ children: [
2804
+ /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
2805
+ className: "rre-md-run-head",
2806
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("b", { children: "代码运行(JavaScript)" }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
2807
+ type: "button",
2808
+ onClick: () => setCodeRun(null),
2809
+ "aria-label": "关闭",
2810
+ children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)("svg", {
2811
+ width: "14",
2812
+ height: "14",
2813
+ viewBox: "0 0 24 24",
2814
+ fill: "none",
2815
+ stroke: "currentColor",
2816
+ strokeWidth: "2",
2817
+ strokeLinecap: "round",
2818
+ "aria-hidden": "true",
2819
+ children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)("path", { d: "m6 6 12 12M18 6 6 18" })
2820
+ })
2821
+ })]
2822
+ }),
2823
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("pre", {
2824
+ className: "rre-md-run-code",
2825
+ children: codeRun.code
2826
+ }),
2827
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("iframe", {
2828
+ className: "rre-md-run-frame",
2829
+ title: "代码运行结果",
2830
+ sandbox: "allow-scripts",
2831
+ srcDoc: codeDoc
2832
+ }, codeRun.key),
2833
+ /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
2834
+ className: "rre-md-run-output",
2835
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("b", { children: "输出" }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("pre", { children: codeRun.output.join("\n") || "(无输出,console.log 会显示在这里)" })]
2836
+ }),
2837
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
2838
+ className: "rre-md-modal-actions",
2839
+ children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
2840
+ type: "button",
2841
+ className: "rre-md-btn is-primary",
2842
+ onClick: () => setCodeRun({
2843
+ ...codeRun,
2844
+ output: [],
2845
+ key: Date.now()
2846
+ }),
2847
+ children: "重新运行"
2848
+ })
2849
+ })
2850
+ ]
2851
+ })
2852
+ }) : null
2853
+ ]
2854
+ });
2855
+ }
2856
+ // src/MarkdownRichEditor.tsx
2857
+ /** 普通编辑器 + Markdown 编辑器,一个组件内切换 */
2858
+ function MarkdownRichEditor({ mode, defaultMode = "rich", onModeChange, markdownView, markdownSwitchLabel = "使用普通编辑器", renderRichMarkdown, onSave, fileBaseName, richSwitchLabel = "使用 Markdown 编辑器", className = "", markdownClassName = "", richClassName = "", ...props }) {
2859
+ const [innerMode, setInnerMode] = (0, react.useState)(defaultMode);
2860
+ const current = mode ?? innerMode;
2861
+ function changeMode(next) {
2862
+ if (mode === void 0) setInnerMode(next);
2863
+ onModeChange?.(next);
2864
+ }
2865
+ if (current === "markdown") return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(MarkdownEditor, {
2866
+ ...props,
2867
+ className: markdownClassName,
2868
+ initialView: markdownView,
2869
+ switchLabel: markdownSwitchLabel,
2870
+ onSave,
2871
+ fileBaseName,
2872
+ onSwitchToRichEditor: () => changeMode("rich")
2873
+ });
2874
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(RichTextEditor, {
2875
+ ...props,
2876
+ renderMarkdown: renderRichMarkdown ?? props.renderMarkdown,
2877
+ className: `${className}${richClassName ? " " + richClassName : ""}`.trim(),
2878
+ switchLabel: richSwitchLabel,
2879
+ onSwitchToMarkdown: () => changeMode("markdown")
2880
+ });
2881
+ }
2882
+ exports.MarkdownEditor = MarkdownEditor;
2883
+ exports.MarkdownRichEditor = MarkdownRichEditor;
2884
+ exports.RichTextEditor = RichTextEditor;
2885
+ exports.defaultRenderMarkdown = defaultRenderMarkdown;
2886
+ exports.enhanceHtmlCodeBlocks = enhanceHtmlCodeBlocks;
2887
+ exports.htmlToMarkdown = htmlToMarkdown;
2888
+ exports.safeRichHref = safeRichHref;
2889
+
2890
+ //# sourceMappingURL=index.cjs.map