@zhenryx/react-editor 0.1.2 → 0.1.4

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.d.cts CHANGED
@@ -1,4 +1,27 @@
1
1
  'use client';
2
+ /**
3
+ * 统一「插入代码」的数据结构与序列化(2026-11-20)
4
+ *
5
+ * 工具栏只负责把当前选区交给外部弹窗;外部确定后回传 payload,
6
+ * 这里按当前编辑器模式生成 Markdown 或 contentEditable HTML。
7
+ */
8
+ type CodeInsertMode = 'block' | 'file';
9
+ interface CodeInsertPayload {
10
+ /** 代码库片段 id;有值时按引用插入,不内联整段代码 */
11
+ refId?: number;
12
+ code: string;
13
+ language: string;
14
+ display: CodeInsertMode;
15
+ /** 新代码的文件名(可选) */
16
+ fileName?: string;
17
+ }
18
+ interface CodeInsertRequest {
19
+ mode: 'rich' | 'markdown';
20
+ /** 触发按钮时选中的文本,用于弹窗预填 */
21
+ selectedText: string;
22
+ /** 在触发按钮时的光标位置插入 */
23
+ insert: (payload: CodeInsertPayload) => void;
24
+ }
2
25
  type RichTextEditorFeature = 'undo' | 'redo' | 'format' | 'bold' | 'italic' | 'strike' | 'list' | 'orderedList' | 'quote' | 'hr' | 'code' | 'table' | 'image' | 'link' | 'toc' | 'history' | 'color' | 'background' | 'underline' | 'align' | 'video' | 'formula' | 'template' | 'wide' | 'todo' | 'codeRun' | 'save' | 'sidebar' | 'outline' | 'syntax' | 'importMd' | 'exportMd' | 'more' | 'other';
3
26
  type RichTextEditorFeatures = Partial<Record<RichTextEditorFeature, boolean>>;
4
27
  interface RichTextEditorProps {
@@ -19,8 +42,10 @@ interface RichTextEditorProps {
19
42
  className?: string;
20
43
  /** 按按钮控制功能开关;不传 = 全部开启 */
21
44
  features?: RichTextEditorFeatures;
45
+ /** 自定义「代码」入口;提供后工具栏代码按钮直接打开外部统一插入弹窗 */
46
+ onInsertCodeRequest?: (request: CodeInsertRequest) => void;
22
47
  }
23
- declare function RichTextEditor({ markdown, onChange, onUploadImage, onSwitchToMarkdown, switchLabel, renderMarkdown, placeholder, className, features }: RichTextEditorProps): import("react").JSX.Element;
48
+ declare function RichTextEditor({ markdown, onChange, onUploadImage, onSwitchToMarkdown, switchLabel, renderMarkdown, placeholder, className, features, onInsertCodeRequest }: RichTextEditorProps): import("react").JSX.Element;
24
49
  type MarkdownEditorView = 'markdown' | 'split' | 'preview';
25
50
  interface MarkdownEditorProps {
26
51
  /** 当前内容(Markdown) */
@@ -46,8 +71,10 @@ interface MarkdownEditorProps {
46
71
  /** 正文为空时的占位 */
47
72
  placeholder?: string;
48
73
  className?: string;
74
+ /** 自定义「代码」入口;提供后工具栏代码按钮直接打开外部统一插入弹窗 */
75
+ onInsertCodeRequest?: (request: CodeInsertRequest) => void;
49
76
  }
50
- declare function MarkdownEditor({ markdown, onChange, onUploadImage, renderMarkdown, onSwitchToRichEditor, switchLabel, onSave, fileBaseName, features, initialView, placeholder, className }: MarkdownEditorProps): import("react").JSX.Element;
77
+ declare function MarkdownEditor({ markdown, onChange, onUploadImage, renderMarkdown, onSwitchToRichEditor, switchLabel, onSave, fileBaseName, features, initialView, placeholder, className, onInsertCodeRequest }: MarkdownEditorProps): import("react").JSX.Element;
51
78
  type MarkdownRichEditorMode = 'rich' | 'markdown';
52
79
  interface MarkdownRichEditorProps extends Omit<RichTextEditorProps, 'onSwitchToMarkdown' | 'className' | 'switchLabel'> {
53
80
  /** 受控模式;不传时使用 defaultMode 内部维护 */
@@ -92,5 +119,5 @@ declare function safeRichHref(raw: string): string;
92
119
  * 只处理 language-html / language-htm,普通代码块完全不动。
93
120
  */
94
121
  declare function enhanceHtmlCodeBlocks(container: HTMLElement): void;
95
- export { MarkdownEditor, type MarkdownEditorProps, type MarkdownEditorView, MarkdownRichEditor, type MarkdownRichEditorMode, type MarkdownRichEditorProps, RichTextEditor, type RichTextEditorFeature, type RichTextEditorFeatures, type RichTextEditorProps, defaultRenderMarkdown, enhanceHtmlCodeBlocks, htmlToMarkdown, safeRichHref };
122
+ export { type CodeInsertMode, type CodeInsertPayload, type CodeInsertRequest, MarkdownEditor, type MarkdownEditorProps, type MarkdownEditorView, MarkdownRichEditor, type MarkdownRichEditorMode, type MarkdownRichEditorProps, RichTextEditor, type RichTextEditorFeature, type RichTextEditorFeatures, type RichTextEditorProps, defaultRenderMarkdown, enhanceHtmlCodeBlocks, htmlToMarkdown, safeRichHref };
96
123
  //# sourceMappingURL=index.d.cts.map
package/dist/index.d.mts CHANGED
@@ -1,4 +1,27 @@
1
1
  'use client';
2
+ /**
3
+ * 统一「插入代码」的数据结构与序列化(2026-11-20)
4
+ *
5
+ * 工具栏只负责把当前选区交给外部弹窗;外部确定后回传 payload,
6
+ * 这里按当前编辑器模式生成 Markdown 或 contentEditable HTML。
7
+ */
8
+ type CodeInsertMode = 'block' | 'file';
9
+ interface CodeInsertPayload {
10
+ /** 代码库片段 id;有值时按引用插入,不内联整段代码 */
11
+ refId?: number;
12
+ code: string;
13
+ language: string;
14
+ display: CodeInsertMode;
15
+ /** 新代码的文件名(可选) */
16
+ fileName?: string;
17
+ }
18
+ interface CodeInsertRequest {
19
+ mode: 'rich' | 'markdown';
20
+ /** 触发按钮时选中的文本,用于弹窗预填 */
21
+ selectedText: string;
22
+ /** 在触发按钮时的光标位置插入 */
23
+ insert: (payload: CodeInsertPayload) => void;
24
+ }
2
25
  type RichTextEditorFeature = 'undo' | 'redo' | 'format' | 'bold' | 'italic' | 'strike' | 'list' | 'orderedList' | 'quote' | 'hr' | 'code' | 'table' | 'image' | 'link' | 'toc' | 'history' | 'color' | 'background' | 'underline' | 'align' | 'video' | 'formula' | 'template' | 'wide' | 'todo' | 'codeRun' | 'save' | 'sidebar' | 'outline' | 'syntax' | 'importMd' | 'exportMd' | 'more' | 'other';
3
26
  type RichTextEditorFeatures = Partial<Record<RichTextEditorFeature, boolean>>;
4
27
  interface RichTextEditorProps {
@@ -19,8 +42,10 @@ interface RichTextEditorProps {
19
42
  className?: string;
20
43
  /** 按按钮控制功能开关;不传 = 全部开启 */
21
44
  features?: RichTextEditorFeatures;
45
+ /** 自定义「代码」入口;提供后工具栏代码按钮直接打开外部统一插入弹窗 */
46
+ onInsertCodeRequest?: (request: CodeInsertRequest) => void;
22
47
  }
23
- declare function RichTextEditor({ markdown, onChange, onUploadImage, onSwitchToMarkdown, switchLabel, renderMarkdown, placeholder, className, features }: RichTextEditorProps): import("react").JSX.Element;
48
+ declare function RichTextEditor({ markdown, onChange, onUploadImage, onSwitchToMarkdown, switchLabel, renderMarkdown, placeholder, className, features, onInsertCodeRequest }: RichTextEditorProps): import("react").JSX.Element;
24
49
  type MarkdownEditorView = 'markdown' | 'split' | 'preview';
25
50
  interface MarkdownEditorProps {
26
51
  /** 当前内容(Markdown) */
@@ -46,8 +71,10 @@ interface MarkdownEditorProps {
46
71
  /** 正文为空时的占位 */
47
72
  placeholder?: string;
48
73
  className?: string;
74
+ /** 自定义「代码」入口;提供后工具栏代码按钮直接打开外部统一插入弹窗 */
75
+ onInsertCodeRequest?: (request: CodeInsertRequest) => void;
49
76
  }
50
- declare function MarkdownEditor({ markdown, onChange, onUploadImage, renderMarkdown, onSwitchToRichEditor, switchLabel, onSave, fileBaseName, features, initialView, placeholder, className }: MarkdownEditorProps): import("react").JSX.Element;
77
+ declare function MarkdownEditor({ markdown, onChange, onUploadImage, renderMarkdown, onSwitchToRichEditor, switchLabel, onSave, fileBaseName, features, initialView, placeholder, className, onInsertCodeRequest }: MarkdownEditorProps): import("react").JSX.Element;
51
78
  type MarkdownRichEditorMode = 'rich' | 'markdown';
52
79
  interface MarkdownRichEditorProps extends Omit<RichTextEditorProps, 'onSwitchToMarkdown' | 'className' | 'switchLabel'> {
53
80
  /** 受控模式;不传时使用 defaultMode 内部维护 */
@@ -92,5 +119,5 @@ declare function safeRichHref(raw: string): string;
92
119
  * 只处理 language-html / language-htm,普通代码块完全不动。
93
120
  */
94
121
  declare function enhanceHtmlCodeBlocks(container: HTMLElement): void;
95
- export { MarkdownEditor, type MarkdownEditorProps, type MarkdownEditorView, MarkdownRichEditor, type MarkdownRichEditorMode, type MarkdownRichEditorProps, RichTextEditor, type RichTextEditorFeature, type RichTextEditorFeatures, type RichTextEditorProps, defaultRenderMarkdown, enhanceHtmlCodeBlocks, htmlToMarkdown, safeRichHref };
122
+ export { type CodeInsertMode, type CodeInsertPayload, type CodeInsertRequest, MarkdownEditor, type MarkdownEditorProps, type MarkdownEditorView, MarkdownRichEditor, type MarkdownRichEditorMode, type MarkdownRichEditorProps, RichTextEditor, type RichTextEditorFeature, type RichTextEditorFeatures, type RichTextEditorProps, defaultRenderMarkdown, enhanceHtmlCodeBlocks, htmlToMarkdown, safeRichHref };
96
123
  //# sourceMappingURL=index.d.mts.map
package/dist/index.mjs CHANGED
@@ -149,8 +149,23 @@ function preToMd(pre, langOverride = "") {
149
149
  const code = pre.querySelector("code");
150
150
  const text = (code || pre).textContent || "";
151
151
  const lang = langOverride || code?.className.match(/language-([\w-]+)/)?.[1] || "";
152
+ const display = pre.getAttribute("data-kb-display") || "";
153
+ const refId = pre.getAttribute("data-kb-ref") || "";
154
+ if (refId) return `\n\n[[kbcode:${refId}${display === "file" ? ":file" : ""}]]\n\n`;
155
+ const info = [lang];
156
+ if (display === "block" || display === "file") info.push(`kbdisplay=${display}`);
157
+ const rawName = pre.getAttribute("data-kb-name") || "";
158
+ if (rawName) info.push(`kbname=${encodeURIComponent(rawName)}`);
152
159
  const fence = text.includes("```") ? "~~~" : "```";
153
- return `\n\n${fence}${lang}\n${text.replace(/\n$/, "")}\n${fence}\n\n`;
160
+ return `\n\n${fence}${info.filter(Boolean).join(" ")}\n${text.replace(/\n$/, "")}\n${fence}\n\n`;
161
+ }
162
+ function codeFileToMd(card) {
163
+ const codeEl = card.querySelector("code");
164
+ const code = codeEl?.textContent || "";
165
+ const lang = card.getAttribute("data-kb-lang") || codeEl?.className.match(/language-([\w-]+)/)?.[1] || "text";
166
+ const name = card.querySelector(".kb-code-file-meta b")?.textContent?.trim() || "";
167
+ const fence = code.includes("```") ? "~~~" : "```";
168
+ return `\n\n${fence}${lang} kbdisplay=file${name ? ` kbname=${encodeURIComponent(name)}` : ""}\n${code.replace(/\n$/, "")}\n${fence}\n\n`;
154
169
  }
155
170
  function blockToMd(el) {
156
171
  switch (el.tagName) {
@@ -188,6 +203,7 @@ function nodeToMd(node) {
188
203
  const annotation = el.querySelector("annotation[encoding=\"application/x-tex\"]")?.textContent?.trim() || "";
189
204
  if (annotation) return `\n\n$$${annotation}$$\n\n`;
190
205
  }
206
+ if (el.classList.contains("kb-code-file")) return codeFileToMd(el);
191
207
  if (el.classList.contains("kb-code")) {
192
208
  const pre = el.querySelector("pre");
193
209
  const extra = Array.from(el.children).filter((child) => child.tagName !== "PRE" && !child.classList.contains("kb-code-lang")).map((child) => nodeToMd(child)).join("");
@@ -210,6 +226,35 @@ function safeRichHref(raw) {
210
226
  if (/^\.\.?\//.test(url)) return escapeAttr(url);
211
227
  return "";
212
228
  }
229
+ // src/code-insert.ts
230
+ function escapeHtml$1(value) {
231
+ return value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
232
+ }
233
+ function languageOf$1(payload) {
234
+ return (payload.language || "text").trim().toLowerCase();
235
+ }
236
+ /** 代码库引用:[[kbcode:12]] / [[kbcode:12:file]] */
237
+ function codeInsertToken(payload) {
238
+ if (!payload.refId) return "";
239
+ return `[[kbcode:${payload.refId}${payload.display === "file" ? ":file" : ""}]]`;
240
+ }
241
+ /** Markdown 编辑器插入内容(前后留空行,避免粘在上一段后面) */
242
+ function codeInsertMarkdown(payload) {
243
+ if (payload.refId) return `\n\n${codeInsertToken(payload)}\n\n`;
244
+ const fence = payload.code.includes("```") ? "~~~" : "```";
245
+ const info = [languageOf$1(payload), `kbdisplay=${payload.display}`];
246
+ if (payload.fileName) info.push(`kbname=${encodeURIComponent(payload.fileName)}`);
247
+ return `\n\n${fence}${info.join(" ")}\n${payload.code.replace(/\n$/, "")}\n${fence}\n\n`;
248
+ }
249
+ /** 普通编辑器插入 HTML;data-* 会由 htmlToMarkdown 还原成上面的 Markdown */
250
+ function codeInsertHtml(payload) {
251
+ const attrs = [];
252
+ if (payload.refId) attrs.push(`data-kb-ref="${payload.refId}"`);
253
+ attrs.push(`data-kb-display="${payload.display}"`);
254
+ if (payload.fileName) attrs.push(`data-kb-name="${escapeHtml$1(payload.fileName)}"`);
255
+ const lang = languageOf$1(payload);
256
+ return `<pre ${attrs.join(" ")}><code class="language-${escapeHtml$1(lang)}">${escapeHtml$1(payload.code)}</code></pre><p><br></p>`;
257
+ }
213
258
  // src/default-render.ts
214
259
  function defaultRenderMarkdown(markdown) {
215
260
  return markdown.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").split(/\n{2,}/).map((block) => `<p>${block.replace(/\n/g, "<br>")}</p>`).join("");
@@ -859,7 +904,7 @@ const TEMPLATES = [
859
904
  markdown: "# 项目复盘\n\n## 目标\n\n## 做对了什么\n\n## 可以改进\n\n## 下一步\n"
860
905
  }
861
906
  ];
862
- function RichTextEditor({ markdown, onChange, onUploadImage, onSwitchToMarkdown, switchLabel = "使用 Markdown 编辑器", renderMarkdown = defaultRenderMarkdown, placeholder = "开始写正文…", className = "", features }) {
907
+ function RichTextEditor({ markdown, onChange, onUploadImage, onSwitchToMarkdown, switchLabel = "使用 Markdown 编辑器", renderMarkdown = defaultRenderMarkdown, placeholder = "开始写正文…", className = "", features, onInsertCodeRequest }) {
863
908
  const feature = (key) => features?.[key] !== false;
864
909
  const rootRef = useRef(null);
865
910
  const [containerWidth, setContainerWidth] = useState(0);
@@ -1056,6 +1101,15 @@ function RichTextEditor({ markdown, onChange, onUploadImage, onSwitchToMarkdown,
1056
1101
  onChange(value);
1057
1102
  setPopover(null);
1058
1103
  }
1104
+ function requestCodeInsert() {
1105
+ const selectedText = window.getSelection()?.toString() || "";
1106
+ saveRange();
1107
+ onInsertCodeRequest?.({
1108
+ mode: "rich",
1109
+ selectedText,
1110
+ insert: (payload) => insertBlockHtml(codeInsertHtml(payload))
1111
+ });
1112
+ }
1059
1113
  function openCodeDialog() {
1060
1114
  const el = editorRef.current;
1061
1115
  const sel = window.getSelection();
@@ -1078,7 +1132,7 @@ function RichTextEditor({ markdown, onChange, onUploadImage, onSwitchToMarkdown,
1078
1132
  setCodeOpen(true);
1079
1133
  }
1080
1134
  function insertCode() {
1081
- insertHtml(`<pre><code class="language-${codeLang === "CSS/SCSS/LESS" ? "css" : codeLang.toLowerCase()}">${escapeHtml(codeText)}</code></pre><p><br></p>`);
1135
+ insertBlockHtml(`<pre><code class="language-${codeLang === "CSS/SCSS/LESS" ? "css" : codeLang.toLowerCase()}">${escapeHtml(codeText)}</code></pre><p><br></p>`);
1082
1136
  setCodeOpen(false);
1083
1137
  }
1084
1138
  function runRichCode() {
@@ -1174,6 +1228,38 @@ function RichTextEditor({ markdown, onChange, onUploadImage, onSwitchToMarkdown,
1174
1228
  saveRange();
1175
1229
  sync();
1176
1230
  }
1231
+ /** 插入块级 HTML(代码块等):放在当前段落之后,避免 execCommand 把首行拆成行内 span */
1232
+ function insertBlockHtml(html) {
1233
+ const el = editorRef.current;
1234
+ if (!el) return;
1235
+ el.focus();
1236
+ restoreRange();
1237
+ const sel = window.getSelection();
1238
+ const range = sel?.rangeCount ? sel.getRangeAt(0) : null;
1239
+ if (range && !range.collapsed) range.deleteContents();
1240
+ let block = null;
1241
+ if (range) {
1242
+ const anchor = range.startContainer;
1243
+ block = (anchor instanceof Element ? anchor : anchor.parentElement)?.closest("p,div,li,h1,h2,h3,h4,h5,h6,blockquote,pre,figure,table") || null;
1244
+ if (block === el || block && !el.contains(block)) block = null;
1245
+ if (block?.tagName === "LI") block = block.closest("ul,ol") || block;
1246
+ }
1247
+ const template = document.createElement("template");
1248
+ template.innerHTML = html;
1249
+ const fragment = template.content;
1250
+ const tail = fragment.lastElementChild;
1251
+ if (block?.parentNode) block.parentNode.insertBefore(fragment, block.nextSibling);
1252
+ else el.appendChild(fragment);
1253
+ if (tail?.tagName === "P") {
1254
+ const next = document.createRange();
1255
+ next.setStart(tail, 0);
1256
+ next.collapse(true);
1257
+ sel?.removeAllRanges();
1258
+ sel?.addRange(next);
1259
+ }
1260
+ saveRange();
1261
+ sync();
1262
+ }
1177
1263
  function onPaste(event) {
1178
1264
  event.preventDefault();
1179
1265
  const text = event.clipboardData.getData("text/plain");
@@ -1311,16 +1397,18 @@ function RichTextEditor({ markdown, onChange, onUploadImage, onSwitchToMarkdown,
1311
1397
  setError("图片地址不合法");
1312
1398
  return;
1313
1399
  }
1400
+ const width = Math.max(20, Math.min(4e3, Number(imageDialog.width) || 20));
1401
+ const height = Math.max(0, Number(imageDialog.height) || 0);
1314
1402
  img.setAttribute("src", src);
1315
1403
  img.setAttribute("alt", imageDialog.alt);
1316
- img.setAttribute("data-kb-w", String(imageDialog.width));
1317
- img.style.setProperty("--kbw", `${imageDialog.width}px`);
1318
- if (imageDialog.lock || !imageDialog.height) {
1404
+ img.setAttribute("data-kb-w", String(width));
1405
+ img.style.setProperty("--kbw", `${width}px`);
1406
+ if (imageDialog.lock || height <= 0) {
1319
1407
  img.removeAttribute("data-kb-h");
1320
1408
  img.style.removeProperty("--kbh");
1321
1409
  } else {
1322
- img.setAttribute("data-kb-h", String(imageDialog.height));
1323
- img.style.setProperty("--kbh", `${imageDialog.height}px`);
1410
+ img.setAttribute("data-kb-h", String(height));
1411
+ img.style.setProperty("--kbh", `${height}px`);
1324
1412
  }
1325
1413
  if (imageDialog.align === "none") img.removeAttribute("data-kb-align");
1326
1414
  else img.setAttribute("data-kb-align", imageDialog.align);
@@ -1436,7 +1524,7 @@ function RichTextEditor({ markdown, onChange, onUploadImage, onSwitchToMarkdown,
1436
1524
  case "orderedList": return toolButton("有序", EditorIcons.ol, () => run("insertOrderedList", void 0, true));
1437
1525
  case "quote": return toolButton("块引用", EditorIcons.quote, () => applyBlock("blockquote"));
1438
1526
  case "hr": return toolButton("水平线", EditorIcons.hr, () => run("insertHorizontalRule"));
1439
- case "code": return popoverTool("代码", EditorIcons.code, "code");
1527
+ case "code": return onInsertCodeRequest ? toolButton("代码", EditorIcons.code, requestCodeInsert) : popoverTool("代码", EditorIcons.code, "code");
1440
1528
  case "table": return toolButton("表格", EditorIcons.table, insertTable);
1441
1529
  case "image": return toolButton(busy ? "上传中" : "图像", EditorIcons.image, () => imageRef.current?.click());
1442
1530
  case "history": return popoverTool("历史", EditorIcons.history, "history");
@@ -1796,13 +1884,25 @@ function RichTextEditor({ markdown, onChange, onUploadImage, onSwitchToMarkdown,
1796
1884
  min: 20,
1797
1885
  max: 4e3,
1798
1886
  value: imageDialog.width,
1887
+ onFocus: (event) => event.currentTarget.select(),
1799
1888
  onChange: (event) => {
1800
- const width = Math.max(20, Math.min(4e3, Number(event.target.value) || 20));
1889
+ const raw = event.target.value;
1890
+ const width = raw === "" ? "" : Math.max(0, Math.min(4e3, Number(raw) || 0));
1801
1891
  setImageDialog({
1802
1892
  ...imageDialog,
1803
1893
  width,
1804
- height: imageDialog.lock ? calcImageHeight(width) : imageDialog.height
1894
+ height: imageDialog.lock ? width === "" || width < 20 ? "" : calcImageHeight(width) : imageDialog.height
1805
1895
  });
1896
+ },
1897
+ onBlur: () => {
1898
+ if (imageDialog.width !== "" && Number(imageDialog.width) < 20) {
1899
+ const width = 20;
1900
+ setImageDialog({
1901
+ ...imageDialog,
1902
+ width,
1903
+ height: imageDialog.lock ? calcImageHeight(width) : imageDialog.height
1904
+ });
1905
+ }
1806
1906
  }
1807
1907
  })]
1808
1908
  }),
@@ -1811,12 +1911,22 @@ function RichTextEditor({ markdown, onChange, onUploadImage, onSwitchToMarkdown,
1811
1911
  children: [/* @__PURE__ */ jsx("span", { children: "高度(px)" }), /* @__PURE__ */ jsx("input", {
1812
1912
  type: "number",
1813
1913
  min: 1,
1814
- value: imageDialog.height || "",
1914
+ value: imageDialog.height,
1815
1915
  readOnly: imageDialog.lock,
1816
- onChange: (event) => setImageDialog({
1817
- ...imageDialog,
1818
- height: Math.max(1, Number(event.target.value) || 1)
1819
- })
1916
+ onFocus: (event) => event.currentTarget.select(),
1917
+ onChange: (event) => {
1918
+ const raw = event.target.value;
1919
+ setImageDialog({
1920
+ ...imageDialog,
1921
+ height: raw === "" ? "" : Math.max(0, Number(raw) || 0)
1922
+ });
1923
+ },
1924
+ onBlur: () => {
1925
+ if (imageDialog.height !== "" && Number(imageDialog.height) < 1) setImageDialog({
1926
+ ...imageDialog,
1927
+ height: 1
1928
+ });
1929
+ }
1820
1930
  })]
1821
1931
  }),
1822
1932
  /* @__PURE__ */ jsxs("div", {
@@ -1828,7 +1938,7 @@ function RichTextEditor({ markdown, onChange, onUploadImage, onSwitchToMarkdown,
1828
1938
  onClick: () => setImageDialog({
1829
1939
  ...imageDialog,
1830
1940
  lock: !imageDialog.lock,
1831
- height: !imageDialog.lock ? calcImageHeight(imageDialog.width) : imageDialog.height
1941
+ height: !imageDialog.lock ? calcImageHeight(Number(imageDialog.width) || 20) : imageDialog.height
1832
1942
  }),
1833
1943
  children: /* @__PURE__ */ jsxs("svg", {
1834
1944
  width: "15",
@@ -2027,9 +2137,9 @@ function RichTextEditor({ markdown, onChange, onUploadImage, onSwitchToMarkdown,
2027
2137
  ]
2028
2138
  }, command))
2029
2139
  }) : null,
2030
- popover.kind === "other" ? /* @__PURE__ */ jsx("div", {
2140
+ popover.kind === "other" ? /* @__PURE__ */ jsxs("div", {
2031
2141
  className: "rre-popover-list",
2032
- children: [
2142
+ children: [[
2033
2143
  [
2034
2144
  "倾斜",
2035
2145
  "italic",
@@ -2063,7 +2173,17 @@ function RichTextEditor({ markdown, onChange, onUploadImage, onSwitchToMarkdown,
2063
2173
  children: EditorIcons.check
2064
2174
  }) : null
2065
2175
  ]
2066
- }, command))
2176
+ }, command)), onInsertCodeRequest && feature("code") ? /* @__PURE__ */ jsxs("button", {
2177
+ type: "button",
2178
+ onClick: () => {
2179
+ setPopover(null);
2180
+ runRichCode();
2181
+ },
2182
+ children: [/* @__PURE__ */ jsx("span", {
2183
+ className: "rre-popover-ico",
2184
+ children: EditorIcons.runCode
2185
+ }), /* @__PURE__ */ jsx("span", { children: "运行代码" })]
2186
+ }) : null]
2067
2187
  }) : null,
2068
2188
  popover.kind === "code" ? /* @__PURE__ */ jsxs("div", {
2069
2189
  className: "rre-popover-list",
@@ -2291,9 +2411,13 @@ try { ${richRun.code.replace(/<\/script/gi, "<\\/script")} } catch (e) { send('e
2291
2411
  */
2292
2412
  const CSP = "default-src 'none'; style-src 'unsafe-inline'; script-src 'unsafe-inline'; img-src data: https: http:; font-src data: https: http:;";
2293
2413
  function buildDoc(code) {
2294
- 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>`;
2295
- if (/<html[\s>]/i.test(code)) return code.replace(/<head([^>]*)>/i, `<head$1><meta http-equiv="Content-Security-Policy" content="${CSP}">${style}`);
2296
- return `<!doctype html><html><head><meta charset="utf-8"><meta http-equiv="Content-Security-Policy" content="${CSP}">${style}</head><body>${code}</body></html>`;
2414
+ const meta = "<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">";
2415
+ const style = `<style>html,body{margin:0;padding:0;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>`;
2416
+ if (/<html[\s>]/i.test(code)) {
2417
+ if (/<head([^>]*)>/i.test(code)) return code.replace(/<head([^>]*)>/i, `<head$1>${meta}<meta http-equiv="Content-Security-Policy" content="${CSP}">${style}`);
2418
+ return code.replace(/<html([^>]*)>/i, `<html$1><head>${meta}<meta http-equiv="Content-Security-Policy" content="${CSP}">${style}</head>`);
2419
+ }
2420
+ return `<!doctype html><html><head><meta charset="utf-8">${meta}<meta http-equiv="Content-Security-Policy" content="${CSP}">${style}</head><body>${code}</body></html>`;
2297
2421
  }
2298
2422
  function makeButton(label, className) {
2299
2423
  const button = document.createElement("button");
@@ -2472,7 +2596,7 @@ function markdownHeadings(markdown) {
2472
2596
  };
2473
2597
  });
2474
2598
  }
2475
- function MarkdownEditor({ markdown, onChange, onUploadImage, renderMarkdown = defaultRenderMarkdown, onSwitchToRichEditor, switchLabel = "使用普通编辑器", onSave, fileBaseName = "article", features, initialView = "split", placeholder = "# 从这里开始写 Markdown…", className = "" }) {
2599
+ function MarkdownEditor({ markdown, onChange, onUploadImage, renderMarkdown = defaultRenderMarkdown, onSwitchToRichEditor, switchLabel = "使用普通编辑器", onSave, fileBaseName = "article", features, initialView = "split", placeholder = "# 从这里开始写 Markdown…", className = "", onInsertCodeRequest }) {
2476
2600
  const feature = (key) => features?.[key] !== false;
2477
2601
  const [view, setView] = useState(initialView);
2478
2602
  const [uploading, setUploading] = useState(false);
@@ -2552,6 +2676,27 @@ function MarkdownEditor({ markdown, onChange, onUploadImage, renderMarkdown = de
2552
2676
  window.addEventListener("message", onMessage);
2553
2677
  return () => window.removeEventListener("message", onMessage);
2554
2678
  }, []);
2679
+ function requestCodeInsert() {
2680
+ const el = textareaRef.current;
2681
+ const start = el?.selectionStart ?? markdown.length;
2682
+ const end = el?.selectionEnd ?? markdown.length;
2683
+ const selectedText = markdown.slice(start, end);
2684
+ onInsertCodeRequest?.({
2685
+ mode: "markdown",
2686
+ selectedText,
2687
+ insert: (payload) => {
2688
+ const block = codeInsertMarkdown(payload);
2689
+ onChange(markdown.slice(0, start) + block + markdown.slice(end));
2690
+ window.requestAnimationFrame(() => {
2691
+ const next = textareaRef.current;
2692
+ if (!next) return;
2693
+ next.focus();
2694
+ const caret = start + block.length;
2695
+ next.setSelectionRange(caret, caret);
2696
+ });
2697
+ }
2698
+ });
2699
+ }
2555
2700
  function insertAtCursor(before, after = "", fallback = "文本") {
2556
2701
  const el = textareaRef.current;
2557
2702
  const start = el?.selectionStart ?? markdown.length;
@@ -2848,7 +2993,7 @@ try { ${codeRun.code.replace(/<\/script/gi, "<\\/script")} } catch (e) { send('e
2848
2993
  feature("strike") ? mdTool("删除线", EditorIcons.strike, () => insertAtCursor("~~", "~~", "删除线")) : null,
2849
2994
  /* @__PURE__ */ jsx("span", { className: "rre-md-sep" }),
2850
2995
  feature("list") ? menuButton("list", "列表", EditorIcons.ul) : null,
2851
- feature("code") ? menuButton("code", "代码块", EditorIcons.code) : null,
2996
+ feature("code") ? onInsertCodeRequest ? mdTool("代码", EditorIcons.code, requestCodeInsert) : menuButton("code", "代码块", EditorIcons.code) : null,
2852
2997
  feature("quote") ? menuButton("more-format", "更多格式") : null,
2853
2998
  /* @__PURE__ */ jsx("span", { className: "rre-md-sep" }),
2854
2999
  feature("image") ? mdTool(uploading ? "上传中" : "图片", EditorIcons.image, () => imageRef.current?.click()) : null,