@zhenryx/react-editor 0.1.3 → 0.1.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -150,8 +150,23 @@ function preToMd(pre, langOverride = "") {
150
150
  const code = pre.querySelector("code");
151
151
  const text = (code || pre).textContent || "";
152
152
  const lang = langOverride || code?.className.match(/language-([\w-]+)/)?.[1] || "";
153
+ const display = pre.getAttribute("data-kb-display") || "";
154
+ const refId = pre.getAttribute("data-kb-ref") || "";
155
+ if (refId) return `\n\n[[kbcode:${refId}${display === "file" ? ":file" : ""}]]\n\n`;
156
+ const info = [lang];
157
+ if (display === "block" || display === "file") info.push(`kbdisplay=${display}`);
158
+ const rawName = pre.getAttribute("data-kb-name") || "";
159
+ if (rawName) info.push(`kbname=${encodeURIComponent(rawName)}`);
153
160
  const fence = text.includes("```") ? "~~~" : "```";
154
- return `\n\n${fence}${lang}\n${text.replace(/\n$/, "")}\n${fence}\n\n`;
161
+ return `\n\n${fence}${info.filter(Boolean).join(" ")}\n${text.replace(/\n$/, "")}\n${fence}\n\n`;
162
+ }
163
+ function codeFileToMd(card) {
164
+ const codeEl = card.querySelector("code");
165
+ const code = codeEl?.textContent || "";
166
+ const lang = card.getAttribute("data-kb-lang") || codeEl?.className.match(/language-([\w-]+)/)?.[1] || "text";
167
+ const name = card.querySelector(".kb-code-file-meta b")?.textContent?.trim() || "";
168
+ const fence = code.includes("```") ? "~~~" : "```";
169
+ return `\n\n${fence}${lang} kbdisplay=file${name ? ` kbname=${encodeURIComponent(name)}` : ""}\n${code.replace(/\n$/, "")}\n${fence}\n\n`;
155
170
  }
156
171
  function blockToMd(el) {
157
172
  switch (el.tagName) {
@@ -189,6 +204,7 @@ function nodeToMd(node) {
189
204
  const annotation = el.querySelector("annotation[encoding=\"application/x-tex\"]")?.textContent?.trim() || "";
190
205
  if (annotation) return `\n\n$$${annotation}$$\n\n`;
191
206
  }
207
+ if (el.classList.contains("kb-code-file")) return codeFileToMd(el);
192
208
  if (el.classList.contains("kb-code")) {
193
209
  const pre = el.querySelector("pre");
194
210
  const extra = Array.from(el.children).filter((child) => child.tagName !== "PRE" && !child.classList.contains("kb-code-lang")).map((child) => nodeToMd(child)).join("");
@@ -211,6 +227,35 @@ function safeRichHref(raw) {
211
227
  if (/^\.\.?\//.test(url)) return escapeAttr(url);
212
228
  return "";
213
229
  }
230
+ // src/code-insert.ts
231
+ function escapeHtml$1(value) {
232
+ return value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
233
+ }
234
+ function languageOf$1(payload) {
235
+ return (payload.language || "text").trim().toLowerCase();
236
+ }
237
+ /** 代码库引用:[[kbcode:12]] / [[kbcode:12:file]] */
238
+ function codeInsertToken(payload) {
239
+ if (!payload.refId) return "";
240
+ return `[[kbcode:${payload.refId}${payload.display === "file" ? ":file" : ""}]]`;
241
+ }
242
+ /** Markdown 编辑器插入内容(前后留空行,避免粘在上一段后面) */
243
+ function codeInsertMarkdown(payload) {
244
+ if (payload.refId) return `\n\n${codeInsertToken(payload)}\n\n`;
245
+ const fence = payload.code.includes("```") ? "~~~" : "```";
246
+ const info = [languageOf$1(payload), `kbdisplay=${payload.display}`];
247
+ if (payload.fileName) info.push(`kbname=${encodeURIComponent(payload.fileName)}`);
248
+ return `\n\n${fence}${info.join(" ")}\n${payload.code.replace(/\n$/, "")}\n${fence}\n\n`;
249
+ }
250
+ /** 普通编辑器插入 HTML;data-* 会由 htmlToMarkdown 还原成上面的 Markdown */
251
+ function codeInsertHtml(payload) {
252
+ const attrs = [];
253
+ if (payload.refId) attrs.push(`data-kb-ref="${payload.refId}"`);
254
+ attrs.push(`data-kb-display="${payload.display}"`);
255
+ if (payload.fileName) attrs.push(`data-kb-name="${escapeHtml$1(payload.fileName)}"`);
256
+ const lang = languageOf$1(payload);
257
+ return `<pre ${attrs.join(" ")}><code class="language-${escapeHtml$1(lang)}">${escapeHtml$1(payload.code)}</code></pre><p><br></p>`;
258
+ }
214
259
  // src/default-render.ts
215
260
  function defaultRenderMarkdown(markdown) {
216
261
  return markdown.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").split(/\n{2,}/).map((block) => `<p>${block.replace(/\n/g, "<br>")}</p>`).join("");
@@ -860,7 +905,7 @@ const TEMPLATES = [
860
905
  markdown: "# 项目复盘\n\n## 目标\n\n## 做对了什么\n\n## 可以改进\n\n## 下一步\n"
861
906
  }
862
907
  ];
863
- function RichTextEditor({ markdown, onChange, onUploadImage, onSwitchToMarkdown, switchLabel = "使用 Markdown 编辑器", renderMarkdown = defaultRenderMarkdown, placeholder = "开始写正文…", className = "", features }) {
908
+ function RichTextEditor({ markdown, onChange, onUploadImage, onSwitchToMarkdown, switchLabel = "使用 Markdown 编辑器", renderMarkdown = defaultRenderMarkdown, placeholder = "开始写正文…", className = "", features, onInsertCodeRequest }) {
864
909
  const feature = (key) => features?.[key] !== false;
865
910
  const rootRef = (0, react.useRef)(null);
866
911
  const [containerWidth, setContainerWidth] = (0, react.useState)(0);
@@ -1057,6 +1102,15 @@ function RichTextEditor({ markdown, onChange, onUploadImage, onSwitchToMarkdown,
1057
1102
  onChange(value);
1058
1103
  setPopover(null);
1059
1104
  }
1105
+ function requestCodeInsert() {
1106
+ const selectedText = window.getSelection()?.toString() || "";
1107
+ saveRange();
1108
+ onInsertCodeRequest?.({
1109
+ mode: "rich",
1110
+ selectedText,
1111
+ insert: (payload) => insertBlockHtml(codeInsertHtml(payload))
1112
+ });
1113
+ }
1060
1114
  function openCodeDialog() {
1061
1115
  const el = editorRef.current;
1062
1116
  const sel = window.getSelection();
@@ -1079,7 +1133,7 @@ function RichTextEditor({ markdown, onChange, onUploadImage, onSwitchToMarkdown,
1079
1133
  setCodeOpen(true);
1080
1134
  }
1081
1135
  function insertCode() {
1082
- insertHtml(`<pre><code class="language-${codeLang === "CSS/SCSS/LESS" ? "css" : codeLang.toLowerCase()}">${escapeHtml(codeText)}</code></pre><p><br></p>`);
1136
+ insertBlockHtml(`<pre><code class="language-${codeLang === "CSS/SCSS/LESS" ? "css" : codeLang.toLowerCase()}">${escapeHtml(codeText)}</code></pre><p><br></p>`);
1083
1137
  setCodeOpen(false);
1084
1138
  }
1085
1139
  function runRichCode() {
@@ -1175,6 +1229,38 @@ function RichTextEditor({ markdown, onChange, onUploadImage, onSwitchToMarkdown,
1175
1229
  saveRange();
1176
1230
  sync();
1177
1231
  }
1232
+ /** 插入块级 HTML(代码块等):放在当前段落之后,避免 execCommand 把首行拆成行内 span */
1233
+ function insertBlockHtml(html) {
1234
+ const el = editorRef.current;
1235
+ if (!el) return;
1236
+ el.focus();
1237
+ restoreRange();
1238
+ const sel = window.getSelection();
1239
+ const range = sel?.rangeCount ? sel.getRangeAt(0) : null;
1240
+ if (range && !range.collapsed) range.deleteContents();
1241
+ let block = null;
1242
+ if (range) {
1243
+ const anchor = range.startContainer;
1244
+ block = (anchor instanceof Element ? anchor : anchor.parentElement)?.closest("p,div,li,h1,h2,h3,h4,h5,h6,blockquote,pre,figure,table") || null;
1245
+ if (block === el || block && !el.contains(block)) block = null;
1246
+ if (block?.tagName === "LI") block = block.closest("ul,ol") || block;
1247
+ }
1248
+ const template = document.createElement("template");
1249
+ template.innerHTML = html;
1250
+ const fragment = template.content;
1251
+ const tail = fragment.lastElementChild;
1252
+ if (block?.parentNode) block.parentNode.insertBefore(fragment, block.nextSibling);
1253
+ else el.appendChild(fragment);
1254
+ if (tail?.tagName === "P") {
1255
+ const next = document.createRange();
1256
+ next.setStart(tail, 0);
1257
+ next.collapse(true);
1258
+ sel?.removeAllRanges();
1259
+ sel?.addRange(next);
1260
+ }
1261
+ saveRange();
1262
+ sync();
1263
+ }
1178
1264
  function onPaste(event) {
1179
1265
  event.preventDefault();
1180
1266
  const text = event.clipboardData.getData("text/plain");
@@ -1439,7 +1525,7 @@ function RichTextEditor({ markdown, onChange, onUploadImage, onSwitchToMarkdown,
1439
1525
  case "orderedList": return toolButton("有序", EditorIcons.ol, () => run("insertOrderedList", void 0, true));
1440
1526
  case "quote": return toolButton("块引用", EditorIcons.quote, () => applyBlock("blockquote"));
1441
1527
  case "hr": return toolButton("水平线", EditorIcons.hr, () => run("insertHorizontalRule"));
1442
- case "code": return popoverTool("代码", EditorIcons.code, "code");
1528
+ case "code": return onInsertCodeRequest ? toolButton("代码", EditorIcons.code, requestCodeInsert) : popoverTool("代码", EditorIcons.code, "code");
1443
1529
  case "table": return toolButton("表格", EditorIcons.table, insertTable);
1444
1530
  case "image": return toolButton(busy ? "上传中" : "图像", EditorIcons.image, () => imageRef.current?.click());
1445
1531
  case "history": return popoverTool("历史", EditorIcons.history, "history");
@@ -2052,9 +2138,9 @@ function RichTextEditor({ markdown, onChange, onUploadImage, onSwitchToMarkdown,
2052
2138
  ]
2053
2139
  }, command))
2054
2140
  }) : null,
2055
- popover.kind === "other" ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
2141
+ popover.kind === "other" ? /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
2056
2142
  className: "rre-popover-list",
2057
- children: [
2143
+ children: [[
2058
2144
  [
2059
2145
  "倾斜",
2060
2146
  "italic",
@@ -2088,7 +2174,17 @@ function RichTextEditor({ markdown, onChange, onUploadImage, onSwitchToMarkdown,
2088
2174
  children: EditorIcons.check
2089
2175
  }) : null
2090
2176
  ]
2091
- }, command))
2177
+ }, command)), onInsertCodeRequest && feature("code") ? /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("button", {
2178
+ type: "button",
2179
+ onClick: () => {
2180
+ setPopover(null);
2181
+ runRichCode();
2182
+ },
2183
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
2184
+ className: "rre-popover-ico",
2185
+ children: EditorIcons.runCode
2186
+ }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", { children: "运行代码" })]
2187
+ }) : null]
2092
2188
  }) : null,
2093
2189
  popover.kind === "code" ? /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
2094
2190
  className: "rre-popover-list",
@@ -2314,11 +2410,15 @@ try { ${richRun.code.replace(/<\/script/gi, "<\\/script")} } catch (e) { send('e
2314
2410
  * 为 Markdown 渲染出的 HTML 代码块增加「源码 / 预览 / 复制 / 全屏 / 刷新」。
2315
2411
  * 只处理 language-html / language-htm,普通代码块完全不动。
2316
2412
  */
2317
- const CSP = "default-src 'none'; style-src 'unsafe-inline'; script-src 'unsafe-inline'; img-src data: https: http:; font-src data: https: http:;";
2413
+ const CSP = "default-src 'none'; style-src 'unsafe-inline'; script-src 'unsafe-inline'; img-src data: https: http:; font-src data: https: http:; form-action 'none'; base-uri 'none';";
2318
2414
  function buildDoc(code) {
2319
- 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>`;
2320
- if (/<html[\s>]/i.test(code)) return code.replace(/<head([^>]*)>/i, `<head$1><meta http-equiv="Content-Security-Policy" content="${CSP}">${style}`);
2321
- return `<!doctype html><html><head><meta charset="utf-8"><meta http-equiv="Content-Security-Policy" content="${CSP}">${style}</head><body>${code}</body></html>`;
2415
+ const meta = "<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">";
2416
+ 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>`;
2417
+ if (/<html[\s>]/i.test(code)) {
2418
+ if (/<head([^>]*)>/i.test(code)) return code.replace(/<head([^>]*)>/i, `<head$1>${meta}<meta http-equiv="Content-Security-Policy" content="${CSP}">${style}`);
2419
+ return code.replace(/<html([^>]*)>/i, `<html$1><head>${meta}<meta http-equiv="Content-Security-Policy" content="${CSP}">${style}</head>`);
2420
+ }
2421
+ return `<!doctype html><html><head><meta charset="utf-8">${meta}<meta http-equiv="Content-Security-Policy" content="${CSP}">${style}</head><body>${code}</body></html>`;
2322
2422
  }
2323
2423
  function makeButton(label, className) {
2324
2424
  const button = document.createElement("button");
@@ -2330,7 +2430,8 @@ function makeButton(label, className) {
2330
2430
  function languageOf(code) {
2331
2431
  return ((code.className || "").match(/language-([\w-]+)/)?.[1] || "").toLowerCase();
2332
2432
  }
2333
- function enhanceHtmlCodeBlocks(container) {
2433
+ function enhanceHtmlCodeBlocks(container, options = {}) {
2434
+ const useSandbox = options.sandbox !== false;
2334
2435
  container.querySelectorAll("pre > code").forEach((code) => {
2335
2436
  const pre = code.closest("pre");
2336
2437
  if (!pre) return;
@@ -2371,7 +2472,7 @@ function enhanceHtmlCodeBlocks(container) {
2371
2472
  if (iframe) return iframe;
2372
2473
  iframe = document.createElement("iframe");
2373
2474
  iframe.className = "kb-html-preview-frame";
2374
- iframe.setAttribute("sandbox", "allow-scripts");
2475
+ if (useSandbox) iframe.setAttribute("sandbox", "allow-scripts");
2375
2476
  iframe.setAttribute("title", "HTML 预览");
2376
2477
  iframe.srcdoc = buildDoc(source);
2377
2478
  preview.appendChild(iframe);
@@ -2414,7 +2515,7 @@ function enhanceHtmlCodeBlocks(container) {
2414
2515
  const close = makeButton("关闭", "kb-html-action-btn");
2415
2516
  bar.append(label, close);
2416
2517
  fullFrame = document.createElement("iframe");
2417
- fullFrame.setAttribute("sandbox", "allow-scripts");
2518
+ if (useSandbox) fullFrame.setAttribute("sandbox", "allow-scripts");
2418
2519
  fullFrame.setAttribute("title", "HTML 全屏预览");
2419
2520
  panel.append(bar, fullFrame);
2420
2521
  fullMask.appendChild(panel);
@@ -2497,7 +2598,7 @@ function markdownHeadings(markdown) {
2497
2598
  };
2498
2599
  });
2499
2600
  }
2500
- function MarkdownEditor({ markdown, onChange, onUploadImage, renderMarkdown = defaultRenderMarkdown, onSwitchToRichEditor, switchLabel = "使用普通编辑器", onSave, fileBaseName = "article", features, initialView = "split", placeholder = "# 从这里开始写 Markdown…", className = "" }) {
2601
+ function MarkdownEditor({ markdown, onChange, onUploadImage, renderMarkdown = defaultRenderMarkdown, onSwitchToRichEditor, switchLabel = "使用普通编辑器", onSave, fileBaseName = "article", features, initialView = "split", placeholder = "# 从这里开始写 Markdown…", className = "", onInsertCodeRequest, htmlPreviewSandbox = true }) {
2501
2602
  const feature = (key) => features?.[key] !== false;
2502
2603
  const [view, setView] = (0, react.useState)(initialView);
2503
2604
  const [uploading, setUploading] = (0, react.useState)(false);
@@ -2537,7 +2638,7 @@ function MarkdownEditor({ markdown, onChange, onUploadImage, renderMarkdown = de
2537
2638
  (0, react.useEffect)(() => {
2538
2639
  const pv = previewRef.current;
2539
2640
  if (!pv) return;
2540
- const run = () => enhanceHtmlCodeBlocks(pv);
2641
+ const run = () => enhanceHtmlCodeBlocks(pv, { sandbox: htmlPreviewSandbox });
2541
2642
  run();
2542
2643
  const observer = new MutationObserver(run);
2543
2644
  observer.observe(pv, {
@@ -2545,7 +2646,7 @@ function MarkdownEditor({ markdown, onChange, onUploadImage, renderMarkdown = de
2545
2646
  subtree: true
2546
2647
  });
2547
2648
  return () => observer.disconnect();
2548
- }, []);
2649
+ }, [htmlPreviewSandbox]);
2549
2650
  (0, react.useEffect)(() => {
2550
2651
  const pv = previewRef.current;
2551
2652
  if (!pv) return;
@@ -2577,6 +2678,27 @@ function MarkdownEditor({ markdown, onChange, onUploadImage, renderMarkdown = de
2577
2678
  window.addEventListener("message", onMessage);
2578
2679
  return () => window.removeEventListener("message", onMessage);
2579
2680
  }, []);
2681
+ function requestCodeInsert() {
2682
+ const el = textareaRef.current;
2683
+ const start = el?.selectionStart ?? markdown.length;
2684
+ const end = el?.selectionEnd ?? markdown.length;
2685
+ const selectedText = markdown.slice(start, end);
2686
+ onInsertCodeRequest?.({
2687
+ mode: "markdown",
2688
+ selectedText,
2689
+ insert: (payload) => {
2690
+ const block = codeInsertMarkdown(payload);
2691
+ onChange(markdown.slice(0, start) + block + markdown.slice(end));
2692
+ window.requestAnimationFrame(() => {
2693
+ const next = textareaRef.current;
2694
+ if (!next) return;
2695
+ next.focus();
2696
+ const caret = start + block.length;
2697
+ next.setSelectionRange(caret, caret);
2698
+ });
2699
+ }
2700
+ });
2701
+ }
2580
2702
  function insertAtCursor(before, after = "", fallback = "文本") {
2581
2703
  const el = textareaRef.current;
2582
2704
  const start = el?.selectionStart ?? markdown.length;
@@ -2873,7 +2995,7 @@ try { ${codeRun.code.replace(/<\/script/gi, "<\\/script")} } catch (e) { send('e
2873
2995
  feature("strike") ? mdTool("删除线", EditorIcons.strike, () => insertAtCursor("~~", "~~", "删除线")) : null,
2874
2996
  /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", { className: "rre-md-sep" }),
2875
2997
  feature("list") ? menuButton("list", "列表", EditorIcons.ul) : null,
2876
- feature("code") ? menuButton("code", "代码块", EditorIcons.code) : null,
2998
+ feature("code") ? onInsertCodeRequest ? mdTool("代码", EditorIcons.code, requestCodeInsert) : menuButton("code", "代码块", EditorIcons.code) : null,
2877
2999
  feature("quote") ? menuButton("more-format", "更多格式") : null,
2878
3000
  /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", { className: "rre-md-sep" }),
2879
3001
  feature("image") ? mdTool(uploading ? "上传中" : "图片", EditorIcons.image, () => imageRef.current?.click()) : null,
@@ -3260,7 +3382,7 @@ try { ${codeRun.code.replace(/<\/script/gi, "<\\/script")} } catch (e) { send('e
3260
3382
  }
3261
3383
  // src/MarkdownRichEditor.tsx
3262
3384
  /** 普通编辑器 + Markdown 编辑器,一个组件内切换 */
3263
- function MarkdownRichEditor({ mode, defaultMode = "rich", onModeChange, markdownView, markdownSwitchLabel = "使用普通编辑器", renderRichMarkdown, onSave, fileBaseName, richSwitchLabel = "使用 Markdown 编辑器", className = "", markdownClassName = "", richClassName = "", ...props }) {
3385
+ function MarkdownRichEditor({ mode, defaultMode = "rich", onModeChange, markdownView, markdownSwitchLabel = "使用普通编辑器", renderRichMarkdown, onSave, fileBaseName, richSwitchLabel = "使用 Markdown 编辑器", htmlPreviewSandbox, className = "", markdownClassName = "", richClassName = "", ...props }) {
3264
3386
  const [innerMode, setInnerMode] = (0, react.useState)(defaultMode);
3265
3387
  const current = mode ?? innerMode;
3266
3388
  function changeMode(next) {
@@ -3269,6 +3391,7 @@ function MarkdownRichEditor({ mode, defaultMode = "rich", onModeChange, markdown
3269
3391
  }
3270
3392
  if (current === "markdown") return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(MarkdownEditor, {
3271
3393
  ...props,
3394
+ htmlPreviewSandbox,
3272
3395
  className: markdownClassName,
3273
3396
  initialView: markdownView,
3274
3397
  switchLabel: markdownSwitchLabel,