@zhenryx/react-editor 0.1.3 → 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/README.md +32 -1
- package/dist/index.cjs +133 -12
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +30 -3
- package/dist/index.d.mts +30 -3
- package/dist/index.mjs +133 -12
- package/dist/index.mjs.map +1 -1
- package/dist/style.css +3 -2
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -63,6 +63,7 @@ export default function Editor() {
|
|
|
63
63
|
| `placeholder` | `string` | 否 | 正文占位文案,默认「开始写正文…」 |
|
|
64
64
|
| `className` | `string` | 否 | 追加到根节点 `.rre-root` |
|
|
65
65
|
| `features` | `RichTextEditorFeatures` | 否 | 按按钮控制功能开关,不传 = 全部开启 |
|
|
66
|
+
| `onInsertCodeRequest` | `(request: CodeInsertRequest) => void` | 否 | 自定义「代码」入口:提供后工具栏代码按钮不再弹内置面板,直接把选区交给宿主弹窗 |
|
|
66
67
|
|
|
67
68
|
### features 字段
|
|
68
69
|
|
|
@@ -131,6 +132,36 @@ import { MarkdownRichEditor } from '@zhenryx/react-editor'
|
|
|
131
132
|
- 右侧栏:收起 / 目录 / 语法(不含 AI、营销组件)
|
|
132
133
|
- 按要求不实现模板与资源绑定
|
|
133
134
|
|
|
135
|
+
### 统一插入代码(0.1.4)
|
|
136
|
+
|
|
137
|
+
`RichTextEditor` / `MarkdownEditor` 都支持 `onInsertCodeRequest`:提供后工具栏的「代码」按钮把当前选区交出去,由宿主弹窗决定内容与呈现方式,再调用 `request.insert(payload)` 写回编辑器。
|
|
138
|
+
|
|
139
|
+
```tsx
|
|
140
|
+
import type { CodeInsertRequest } from '@zhenryx/react-editor'
|
|
141
|
+
|
|
142
|
+
let pending: CodeInsertRequest | null = null
|
|
143
|
+
|
|
144
|
+
<RichTextEditor
|
|
145
|
+
markdown={markdown}
|
|
146
|
+
onChange={setMarkdown}
|
|
147
|
+
onUploadImage={upload}
|
|
148
|
+
onInsertCodeRequest={(request) => { pending = request; setCodeDialogOpen(true) }}
|
|
149
|
+
/>
|
|
150
|
+
|
|
151
|
+
// 弹窗点确定:
|
|
152
|
+
pending?.insert({
|
|
153
|
+
refId: 12, // 代码库片段 id;有值时写 [[kbcode:12]] 引用
|
|
154
|
+
code: '...',
|
|
155
|
+
language: 'html',
|
|
156
|
+
display: 'file', // block / file
|
|
157
|
+
fileName: 'index.html',
|
|
158
|
+
})
|
|
159
|
+
```
|
|
160
|
+
|
|
161
|
+
- `request.mode`:`rich`(富文本)或 `markdown`,决定写回 HTML 还是围栏代码。
|
|
162
|
+
- `selectedText`:触发时的选中文本,可用于预填。
|
|
163
|
+
- `CodeInsertPayload.display = 'file'` 在 Markdown 里输出 `kbdisplay=file kbname=...` 围栏;`refId` 输出 `[[kbcode:id]]` / `[[kbcode:id:file]]`。
|
|
164
|
+
|
|
134
165
|
富文本的颜色 / 背景 / 对齐 / 下划线 / 视频会以受限内联 HTML 写入 Markdown;渲染器需放行 `<u>`、`<span style="color/background-color/text-align/display">` 和 `<video src controls>`。
|
|
135
166
|
|
|
136
167
|
## 样式
|
|
@@ -166,4 +197,4 @@ npm run build
|
|
|
166
197
|
npm publish --access public
|
|
167
198
|
```
|
|
168
199
|
|
|
169
|
-
发布后把宿主项目的依赖从本地 `file:` 改成 `^0.1.
|
|
200
|
+
发布后把宿主项目的依赖从本地 `file:` 改成 `^0.1.4` 即可。
|
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}${
|
|
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, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """);
|
|
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, "&").replace(/</g, "<").replace(/>/g, ">").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
|
-
|
|
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.
|
|
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",
|
|
@@ -2316,9 +2412,13 @@ try { ${richRun.code.replace(/<\/script/gi, "<\\/script")} } catch (e) { send('e
|
|
|
2316
2412
|
*/
|
|
2317
2413
|
const CSP = "default-src 'none'; style-src 'unsafe-inline'; script-src 'unsafe-inline'; img-src data: https: http:; font-src data: https: http:;";
|
|
2318
2414
|
function buildDoc(code) {
|
|
2319
|
-
const
|
|
2320
|
-
|
|
2321
|
-
|
|
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");
|
|
@@ -2497,7 +2597,7 @@ function markdownHeadings(markdown) {
|
|
|
2497
2597
|
};
|
|
2498
2598
|
});
|
|
2499
2599
|
}
|
|
2500
|
-
function MarkdownEditor({ markdown, onChange, onUploadImage, renderMarkdown = defaultRenderMarkdown, onSwitchToRichEditor, switchLabel = "使用普通编辑器", onSave, fileBaseName = "article", features, initialView = "split", placeholder = "# 从这里开始写 Markdown…", className = "" }) {
|
|
2600
|
+
function MarkdownEditor({ markdown, onChange, onUploadImage, renderMarkdown = defaultRenderMarkdown, onSwitchToRichEditor, switchLabel = "使用普通编辑器", onSave, fileBaseName = "article", features, initialView = "split", placeholder = "# 从这里开始写 Markdown…", className = "", onInsertCodeRequest }) {
|
|
2501
2601
|
const feature = (key) => features?.[key] !== false;
|
|
2502
2602
|
const [view, setView] = (0, react.useState)(initialView);
|
|
2503
2603
|
const [uploading, setUploading] = (0, react.useState)(false);
|
|
@@ -2577,6 +2677,27 @@ function MarkdownEditor({ markdown, onChange, onUploadImage, renderMarkdown = de
|
|
|
2577
2677
|
window.addEventListener("message", onMessage);
|
|
2578
2678
|
return () => window.removeEventListener("message", onMessage);
|
|
2579
2679
|
}, []);
|
|
2680
|
+
function requestCodeInsert() {
|
|
2681
|
+
const el = textareaRef.current;
|
|
2682
|
+
const start = el?.selectionStart ?? markdown.length;
|
|
2683
|
+
const end = el?.selectionEnd ?? markdown.length;
|
|
2684
|
+
const selectedText = markdown.slice(start, end);
|
|
2685
|
+
onInsertCodeRequest?.({
|
|
2686
|
+
mode: "markdown",
|
|
2687
|
+
selectedText,
|
|
2688
|
+
insert: (payload) => {
|
|
2689
|
+
const block = codeInsertMarkdown(payload);
|
|
2690
|
+
onChange(markdown.slice(0, start) + block + markdown.slice(end));
|
|
2691
|
+
window.requestAnimationFrame(() => {
|
|
2692
|
+
const next = textareaRef.current;
|
|
2693
|
+
if (!next) return;
|
|
2694
|
+
next.focus();
|
|
2695
|
+
const caret = start + block.length;
|
|
2696
|
+
next.setSelectionRange(caret, caret);
|
|
2697
|
+
});
|
|
2698
|
+
}
|
|
2699
|
+
});
|
|
2700
|
+
}
|
|
2580
2701
|
function insertAtCursor(before, after = "", fallback = "文本") {
|
|
2581
2702
|
const el = textareaRef.current;
|
|
2582
2703
|
const start = el?.selectionStart ?? markdown.length;
|
|
@@ -2873,7 +2994,7 @@ try { ${codeRun.code.replace(/<\/script/gi, "<\\/script")} } catch (e) { send('e
|
|
|
2873
2994
|
feature("strike") ? mdTool("删除线", EditorIcons.strike, () => insertAtCursor("~~", "~~", "删除线")) : null,
|
|
2874
2995
|
/* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", { className: "rre-md-sep" }),
|
|
2875
2996
|
feature("list") ? menuButton("list", "列表", EditorIcons.ul) : null,
|
|
2876
|
-
feature("code") ? menuButton("code", "代码块", EditorIcons.code) : null,
|
|
2997
|
+
feature("code") ? onInsertCodeRequest ? mdTool("代码", EditorIcons.code, requestCodeInsert) : menuButton("code", "代码块", EditorIcons.code) : null,
|
|
2877
2998
|
feature("quote") ? menuButton("more-format", "更多格式") : null,
|
|
2878
2999
|
/* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", { className: "rre-md-sep" }),
|
|
2879
3000
|
feature("image") ? mdTool(uploading ? "上传中" : "图片", EditorIcons.image, () => imageRef.current?.click()) : null,
|