@zhenryx/react-editor 0.0.0-stage → 0.1.1

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