@zhenryx/react-editor 0.1.0 → 0.1.2

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 CHANGED
@@ -76,7 +76,26 @@ function inlineToMd(node) {
76
76
  }
77
77
  case "IMG": {
78
78
  const src = el.getAttribute("src") || "";
79
- return src ? `![${el.getAttribute("alt") || ""}](${src})` : "";
79
+ if (!src) return "";
80
+ const alt = el.getAttribute("alt") || "";
81
+ const width = Number(el.getAttribute("data-kb-w") || "");
82
+ const height = Number(el.getAttribute("data-kb-h") || "");
83
+ const align = el.getAttribute("data-kb-align") || "";
84
+ const caption = (el.getAttribute("data-kb-caption") || el.closest("figure")?.querySelector("figcaption")?.textContent || "").trim();
85
+ const tokens = [];
86
+ if (Number.isInteger(width) && width >= 20 && width <= 4e3) tokens.push(`kbw=${width}`);
87
+ if (Number.isInteger(height) && height > 0) tokens.push(`kbh=${height}`);
88
+ if (/^(left|center|right)$/.test(align)) tokens.push(`kba=${align}`);
89
+ if (caption) tokens.push(`kbc=${encodeURIComponent(caption)}`);
90
+ return `![${alt}](${src}${tokens.length ? ` "${tokens.join(" ")}"` : ""})`;
91
+ }
92
+ case "FIGURE": {
93
+ const img = el.querySelector("img");
94
+ return img ? `
95
+
96
+ ${inlineToMd(img)}
97
+
98
+ ` : "";
80
99
  }
81
100
  case "UL":
82
101
  case "OL": return `\n\n${listToMd(el)}`;
@@ -146,7 +165,7 @@ function blockToMd(el) {
146
165
  }
147
166
  case "P":
148
167
  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("");
168
+ if (Array.from(el.children).some((child) => /^(P|DIV|H[1-6]|UL|OL|LI|BLOCKQUOTE|PRE|TABLE|HR|FIGURE)$/.test(child.tagName))) return Array.from(el.childNodes).map(nodeToMd).join("");
150
169
  const content = inlineToMd(el).trim();
151
170
  const align = (el.style.textAlign || "").toLowerCase();
152
171
  if (/^(left|center|right|justify)$/.test(align) && content) return `\n\n<span style="display: block; text-align: ${align}">${content}</span>\n\n`;
@@ -171,9 +190,10 @@ function nodeToMd(node) {
171
190
  }
172
191
  if (el.classList.contains("kb-code")) {
173
192
  const pre = el.querySelector("pre");
174
- if (pre) return preToMd(pre, el.querySelector(".kb-code-lang")?.textContent?.trim() || "");
193
+ const extra = Array.from(el.children).filter((child) => child.tagName !== "PRE" && !child.classList.contains("kb-code-lang")).map((child) => nodeToMd(child)).join("");
194
+ return (pre ? preToMd(pre, el.querySelector(".kb-code-lang")?.textContent?.trim() || "") : "") + extra;
175
195
  }
176
- if (/^(P|DIV|H[1-6]|UL|OL|BLOCKQUOTE|PRE|TABLE|HR)$/.test(el.tagName)) return blockToMd(el);
196
+ if (/^(P|DIV|H[1-6]|UL|OL|BLOCKQUOTE|PRE|TABLE|HR|FIGURE)$/.test(el.tagName)) return blockToMd(el);
177
197
  return inlineToMd(el);
178
198
  }
179
199
  /** contentEditable 的 innerHTML → Markdown */
@@ -868,6 +888,9 @@ function RichTextEditor({ markdown, onChange, onUploadImage, onSwitchToMarkdown,
868
888
  const [busy, setBusy] = useState(false);
869
889
  const [error, setError] = useState("");
870
890
  const [popover, setPopover] = useState(null);
891
+ const selectedImageRef = useRef(null);
892
+ const [imageSel, setImageSel] = useState(null);
893
+ const [imageDialog, setImageDialog] = useState(null);
871
894
  const [videoUrl, setVideoUrl] = useState("");
872
895
  const [formulaText, setFormulaText] = useState("");
873
896
  const [wide, setWide] = useState(false);
@@ -882,6 +905,9 @@ function RichTextEditor({ markdown, onChange, onUploadImage, onSwitchToMarkdown,
882
905
  if (lastMd.current === markdown) return;
883
906
  el.innerHTML = renderMarkdown(markdown);
884
907
  lastMd.current = markdown;
908
+ selectedImageRef.current = null;
909
+ setImageSel(null);
910
+ setImageDialog(null);
885
911
  refreshHeadings();
886
912
  }, [markdown]);
887
913
  useEffect(() => {
@@ -902,6 +928,28 @@ function RichTextEditor({ markdown, onChange, onUploadImage, onSwitchToMarkdown,
902
928
  document.addEventListener("mousedown", onDown);
903
929
  return () => document.removeEventListener("mousedown", onDown);
904
930
  }, [popover]);
931
+ useEffect(() => {
932
+ if (!imageSel) return;
933
+ const onScroll = () => updateImageRect();
934
+ const onResize = () => updateImageRect();
935
+ window.addEventListener("scroll", onScroll, true);
936
+ window.addEventListener("resize", onResize);
937
+ return () => {
938
+ window.removeEventListener("scroll", onScroll, true);
939
+ window.removeEventListener("resize", onResize);
940
+ };
941
+ }, [imageSel]);
942
+ useEffect(() => {
943
+ if (!imageSel) return;
944
+ const onDown = (event) => {
945
+ const target = event.target;
946
+ if (target?.closest(".rre-img-tool") || target?.closest(".rre-img-dialog")) return;
947
+ if (target?.closest("img")) return;
948
+ clearImageSelection();
949
+ };
950
+ document.addEventListener("mousedown", onDown);
951
+ return () => document.removeEventListener("mousedown", onDown);
952
+ }, [imageSel]);
905
953
  useEffect(() => {
906
954
  if (!markdown.trim()) return;
907
955
  const timer = window.setTimeout(() => {
@@ -1175,7 +1223,9 @@ function RichTextEditor({ markdown, onChange, onUploadImage, onSwitchToMarkdown,
1175
1223
  try {
1176
1224
  const src = safeRichHref(await onUploadImage(file));
1177
1225
  if (!src) throw new Error("图片地址不合法");
1178
- insertHtml(`<img src="${src}" alt="${escapeHtml(file.name.replace(/\.[^.]+$/, ""))}">`);
1226
+ const contentWidth = editorRef.current?.clientWidth || 860;
1227
+ const defaultWidth = Math.max(120, Math.round(contentWidth * .75));
1228
+ insertHtml(`<img src="${src}" alt="${escapeHtml(file.name.replace(/\.[^.]+$/, ""))}" data-kb-w="${defaultWidth}" style="--kbw:${defaultWidth}px">`);
1179
1229
  } catch (err) {
1180
1230
  setError(err instanceof Error ? err.message : "图片上传失败");
1181
1231
  } finally {
@@ -1186,6 +1236,118 @@ function RichTextEditor({ markdown, onChange, onUploadImage, onSwitchToMarkdown,
1186
1236
  const row = "<tr><td>内容</td><td>内容</td><td>内容</td></tr>";
1187
1237
  insertHtml(`<table><thead><tr><th>列 1</th><th>列 2</th><th>列 3</th></tr></thead><tbody>${row}${row}</tbody></table><p><br></p>`);
1188
1238
  }
1239
+ function clearImageSelection() {
1240
+ selectedImageRef.current = null;
1241
+ setImageSel(null);
1242
+ }
1243
+ function updateImageRect() {
1244
+ const img = selectedImageRef.current;
1245
+ if (!img) return;
1246
+ const rect = img.getBoundingClientRect();
1247
+ setImageSel({
1248
+ left: Math.round(rect.left),
1249
+ top: Math.round(rect.top),
1250
+ width: Math.round(rect.width),
1251
+ height: Math.round(rect.height)
1252
+ });
1253
+ }
1254
+ function selectImage(img) {
1255
+ selectedImageRef.current = img;
1256
+ updateImageRect();
1257
+ }
1258
+ function calcImageHeight(widthPx) {
1259
+ const img = selectedImageRef.current;
1260
+ if (!img || !img.naturalWidth) return 0;
1261
+ return Math.max(1, Math.round(img.naturalHeight / img.naturalWidth * widthPx));
1262
+ }
1263
+ function startImageResize(event) {
1264
+ const img = selectedImageRef.current;
1265
+ const container = editorRef.current;
1266
+ if (!img || !container) return;
1267
+ event.preventDefault();
1268
+ event.stopPropagation();
1269
+ const startX = event.clientX;
1270
+ const startWidth = img.getBoundingClientRect().width;
1271
+ const containerWidth = container.clientWidth || 1;
1272
+ const onMove = (moveEvent) => {
1273
+ const next = Math.max(40, Math.min(containerWidth, Math.round(startWidth + moveEvent.clientX - startX)));
1274
+ img.setAttribute("data-kb-w", String(next));
1275
+ img.style.setProperty("--kbw", `${next}px`);
1276
+ updateImageRect();
1277
+ };
1278
+ const onUp = () => {
1279
+ document.removeEventListener("pointermove", onMove);
1280
+ document.removeEventListener("pointerup", onUp);
1281
+ sync();
1282
+ };
1283
+ document.addEventListener("pointermove", onMove);
1284
+ document.addEventListener("pointerup", onUp);
1285
+ }
1286
+ function openImageDialog() {
1287
+ const img = selectedImageRef.current;
1288
+ if (!img) return;
1289
+ const widthAttr = Number(img.getAttribute("data-kb-w") || "");
1290
+ const width = Number.isInteger(widthAttr) && widthAttr >= 20 ? widthAttr : Math.max(40, Math.round(img.getBoundingClientRect().width));
1291
+ const heightAttr = Number(img.getAttribute("data-kb-h") || "");
1292
+ const alignRaw = img.getAttribute("data-kb-align") || "";
1293
+ const align = /^(left|center|right)$/.test(alignRaw) ? alignRaw : "none";
1294
+ const caption = (img.getAttribute("data-kb-caption") || "").trim();
1295
+ setImageDialog({
1296
+ url: img.getAttribute("src") || "",
1297
+ alt: img.getAttribute("alt") || "",
1298
+ width,
1299
+ height: Number.isInteger(heightAttr) && heightAttr > 0 ? heightAttr : calcImageHeight(width),
1300
+ lock: !(Number.isInteger(heightAttr) && heightAttr > 0),
1301
+ align,
1302
+ caption: Boolean(caption),
1303
+ captionText: caption
1304
+ });
1305
+ }
1306
+ function applyImageDialog() {
1307
+ const img = selectedImageRef.current;
1308
+ if (!img || !imageDialog) return;
1309
+ const src = safeRichHref(imageDialog.url.trim());
1310
+ if (!src) {
1311
+ setError("图片地址不合法");
1312
+ return;
1313
+ }
1314
+ img.setAttribute("src", src);
1315
+ 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) {
1319
+ img.removeAttribute("data-kb-h");
1320
+ img.style.removeProperty("--kbh");
1321
+ } else {
1322
+ img.setAttribute("data-kb-h", String(imageDialog.height));
1323
+ img.style.setProperty("--kbh", `${imageDialog.height}px`);
1324
+ }
1325
+ if (imageDialog.align === "none") img.removeAttribute("data-kb-align");
1326
+ else img.setAttribute("data-kb-align", imageDialog.align);
1327
+ if (imageDialog.caption && imageDialog.captionText.trim()) img.setAttribute("data-kb-caption", imageDialog.captionText.trim());
1328
+ else img.removeAttribute("data-kb-caption");
1329
+ setImageDialog(null);
1330
+ clearImageSelection();
1331
+ sync();
1332
+ const el = editorRef.current;
1333
+ if (el) {
1334
+ const md = htmlToMarkdown(el.innerHTML);
1335
+ el.innerHTML = renderMarkdown(md);
1336
+ lastMd.current = md;
1337
+ }
1338
+ }
1339
+ function resetImageSize() {
1340
+ const img = selectedImageRef.current;
1341
+ const containerWidth = editorRef.current?.clientWidth || 1;
1342
+ if (!img) return;
1343
+ const naturalWidth = Math.max(40, Math.min(containerWidth, img.naturalWidth || 640));
1344
+ setImageDialog((prev) => prev ? {
1345
+ ...prev,
1346
+ width: naturalWidth,
1347
+ height: calcImageHeight(naturalWidth),
1348
+ lock: true
1349
+ } : prev);
1350
+ }
1189
1351
  function toolButton(label, icon, onClick, opts = {}) {
1190
1352
  return /* @__PURE__ */ jsxs("button", {
1191
1353
  type: "button",
@@ -1212,7 +1374,10 @@ function RichTextEditor({ markdown, onChange, onUploadImage, onSwitchToMarkdown,
1212
1374
  event.preventDefault();
1213
1375
  saveRange();
1214
1376
  },
1215
- onClick: (event) => openPopover(kind, event.currentTarget),
1377
+ onClick: (event) => {
1378
+ if (popover?.kind === kind) setPopover(null);
1379
+ else openPopover(kind, event.currentTarget);
1380
+ },
1216
1381
  children: [icon, /* @__PURE__ */ jsxs("span", {
1217
1382
  className: withCaret ? "rre-popover-label" : void 0,
1218
1383
  children: [label, withCaret ? /* @__PURE__ */ jsx("svg", {
@@ -1537,12 +1702,228 @@ function RichTextEditor({ markdown, onChange, onUploadImage, onSwitchToMarkdown,
1537
1702
  "data-placeholder": placeholder,
1538
1703
  onInput: sync,
1539
1704
  onBlur: sync,
1540
- onPaste
1705
+ onPaste,
1706
+ onClick: (event) => {
1707
+ const img = event.target?.closest("img");
1708
+ if (img && editorRef.current?.contains(img)) {
1709
+ event.preventDefault();
1710
+ selectImage(img);
1711
+ }
1712
+ }
1541
1713
  })
1542
1714
  })
1543
1715
  })
1544
1716
  ]
1545
1717
  }),
1718
+ imageSel && selectedImageRef.current && !imageDialog ? /* @__PURE__ */ jsxs("div", {
1719
+ className: "rre-img-tool",
1720
+ style: {
1721
+ left: imageSel.left,
1722
+ top: imageSel.top,
1723
+ width: imageSel.width,
1724
+ height: imageSel.height
1725
+ },
1726
+ children: [/* @__PURE__ */ jsx("button", {
1727
+ type: "button",
1728
+ className: "rre-img-edit",
1729
+ onMouseDown: (event) => event.preventDefault(),
1730
+ onClick: openImageDialog,
1731
+ children: "编辑"
1732
+ }), /* @__PURE__ */ jsx("span", {
1733
+ className: "rre-img-handle",
1734
+ title: "点击并拖拽以改变尺寸",
1735
+ onPointerDown: startImageResize
1736
+ })]
1737
+ }) : null,
1738
+ imageDialog ? /* @__PURE__ */ jsx("div", {
1739
+ className: "rre-img-dialog-mask",
1740
+ onMouseDown: (event) => {
1741
+ if (event.target === event.currentTarget) setImageDialog(null);
1742
+ },
1743
+ children: /* @__PURE__ */ jsxs("div", {
1744
+ className: "rre-img-dialog",
1745
+ role: "dialog",
1746
+ "aria-modal": "true",
1747
+ "aria-label": "图像属性",
1748
+ children: [
1749
+ /* @__PURE__ */ jsxs("div", {
1750
+ className: "rre-img-dialog-head",
1751
+ children: [/* @__PURE__ */ jsx("b", { children: "图像属性" }), /* @__PURE__ */ jsx("button", {
1752
+ type: "button",
1753
+ onClick: () => setImageDialog(null),
1754
+ "aria-label": "关闭",
1755
+ title: "关闭",
1756
+ children: /* @__PURE__ */ jsx("svg", {
1757
+ width: "14",
1758
+ height: "14",
1759
+ viewBox: "0 0 24 24",
1760
+ fill: "none",
1761
+ stroke: "currentColor",
1762
+ strokeWidth: "2",
1763
+ strokeLinecap: "round",
1764
+ "aria-hidden": "true",
1765
+ children: /* @__PURE__ */ jsx("path", { d: "m6 6 12 12M18 6 6 18" })
1766
+ })
1767
+ })]
1768
+ }),
1769
+ /* @__PURE__ */ jsxs("label", {
1770
+ className: "rre-img-field",
1771
+ children: [/* @__PURE__ */ jsx("span", { children: "图片 URL" }), /* @__PURE__ */ jsx("input", {
1772
+ value: imageDialog.url,
1773
+ onChange: (event) => setImageDialog({
1774
+ ...imageDialog,
1775
+ url: event.target.value
1776
+ })
1777
+ })]
1778
+ }),
1779
+ /* @__PURE__ */ jsxs("label", {
1780
+ className: "rre-img-field",
1781
+ children: [/* @__PURE__ */ jsx("span", { children: "替换文本" }), /* @__PURE__ */ jsx("input", {
1782
+ value: imageDialog.alt,
1783
+ onChange: (event) => setImageDialog({
1784
+ ...imageDialog,
1785
+ alt: event.target.value
1786
+ })
1787
+ })]
1788
+ }),
1789
+ /* @__PURE__ */ jsxs("div", {
1790
+ className: "rre-img-size",
1791
+ children: [
1792
+ /* @__PURE__ */ jsxs("label", {
1793
+ className: "rre-img-field",
1794
+ children: [/* @__PURE__ */ jsx("span", { children: "宽度(px)" }), /* @__PURE__ */ jsx("input", {
1795
+ type: "number",
1796
+ min: 20,
1797
+ max: 4e3,
1798
+ value: imageDialog.width,
1799
+ onChange: (event) => {
1800
+ const width = Math.max(20, Math.min(4e3, Number(event.target.value) || 20));
1801
+ setImageDialog({
1802
+ ...imageDialog,
1803
+ width,
1804
+ height: imageDialog.lock ? calcImageHeight(width) : imageDialog.height
1805
+ });
1806
+ }
1807
+ })]
1808
+ }),
1809
+ /* @__PURE__ */ jsxs("label", {
1810
+ className: "rre-img-field",
1811
+ children: [/* @__PURE__ */ jsx("span", { children: "高度(px)" }), /* @__PURE__ */ jsx("input", {
1812
+ type: "number",
1813
+ min: 1,
1814
+ value: imageDialog.height || "",
1815
+ readOnly: imageDialog.lock,
1816
+ onChange: (event) => setImageDialog({
1817
+ ...imageDialog,
1818
+ height: Math.max(1, Number(event.target.value) || 1)
1819
+ })
1820
+ })]
1821
+ }),
1822
+ /* @__PURE__ */ jsxs("div", {
1823
+ className: "rre-img-size-tools",
1824
+ children: [/* @__PURE__ */ jsx("button", {
1825
+ type: "button",
1826
+ className: imageDialog.lock ? "is-on" : "",
1827
+ title: imageDialog.lock ? "解锁比例" : "锁定比例",
1828
+ onClick: () => setImageDialog({
1829
+ ...imageDialog,
1830
+ lock: !imageDialog.lock,
1831
+ height: !imageDialog.lock ? calcImageHeight(imageDialog.width) : imageDialog.height
1832
+ }),
1833
+ children: /* @__PURE__ */ jsxs("svg", {
1834
+ width: "15",
1835
+ height: "15",
1836
+ viewBox: "0 0 24 24",
1837
+ fill: "none",
1838
+ stroke: "currentColor",
1839
+ strokeWidth: "1.8",
1840
+ strokeLinecap: "round",
1841
+ strokeLinejoin: "round",
1842
+ "aria-hidden": "true",
1843
+ children: [/* @__PURE__ */ jsx("rect", {
1844
+ x: "5",
1845
+ y: "10",
1846
+ width: "14",
1847
+ height: "10",
1848
+ rx: "2"
1849
+ }), /* @__PURE__ */ jsx("path", { d: "M8.5 10V7.5a3.5 3.5 0 0 1 7 0V10" })]
1850
+ })
1851
+ }), /* @__PURE__ */ jsx("button", {
1852
+ type: "button",
1853
+ title: "恢复原始尺寸",
1854
+ onClick: resetImageSize,
1855
+ children: /* @__PURE__ */ jsxs("svg", {
1856
+ width: "15",
1857
+ height: "15",
1858
+ viewBox: "0 0 24 24",
1859
+ fill: "none",
1860
+ stroke: "currentColor",
1861
+ strokeWidth: "1.8",
1862
+ strokeLinecap: "round",
1863
+ strokeLinejoin: "round",
1864
+ "aria-hidden": "true",
1865
+ children: [/* @__PURE__ */ jsx("path", { d: "M20 12a8 8 0 1 1-2.3-5.7" }), /* @__PURE__ */ jsx("path", { d: "M20 4v5h-5" })]
1866
+ })
1867
+ })]
1868
+ })
1869
+ ]
1870
+ }),
1871
+ /* @__PURE__ */ jsxs("div", {
1872
+ className: "rre-img-align",
1873
+ children: [/* @__PURE__ */ jsx("span", { children: "对齐方式" }), [
1874
+ ["none", "无"],
1875
+ ["left", "左对齐"],
1876
+ ["center", "居中"],
1877
+ ["right", "右对齐"]
1878
+ ].map(([value, label]) => /* @__PURE__ */ jsxs("label", { children: [/* @__PURE__ */ jsx("input", {
1879
+ type: "radio",
1880
+ name: "rre-img-align",
1881
+ checked: imageDialog.align === value,
1882
+ onChange: () => setImageDialog({
1883
+ ...imageDialog,
1884
+ align: value
1885
+ })
1886
+ }), label] }, value))]
1887
+ }),
1888
+ /* @__PURE__ */ jsxs("label", {
1889
+ className: "rre-img-caption-toggle",
1890
+ children: [/* @__PURE__ */ jsx("input", {
1891
+ type: "checkbox",
1892
+ checked: imageDialog.caption,
1893
+ onChange: (event) => setImageDialog({
1894
+ ...imageDialog,
1895
+ caption: event.target.checked
1896
+ })
1897
+ }), "带标题图像"]
1898
+ }),
1899
+ imageDialog.caption ? /* @__PURE__ */ jsxs("label", {
1900
+ className: "rre-img-field",
1901
+ children: [/* @__PURE__ */ jsx("span", { children: "图注" }), /* @__PURE__ */ jsx("input", {
1902
+ value: imageDialog.captionText,
1903
+ onChange: (event) => setImageDialog({
1904
+ ...imageDialog,
1905
+ captionText: event.target.value
1906
+ }),
1907
+ placeholder: "图片下方的说明文字"
1908
+ })]
1909
+ }) : null,
1910
+ /* @__PURE__ */ jsxs("div", {
1911
+ className: "rre-img-dialog-foot",
1912
+ children: [/* @__PURE__ */ jsx("button", {
1913
+ type: "button",
1914
+ className: "rre-btn",
1915
+ onClick: () => setImageDialog(null),
1916
+ children: "取消"
1917
+ }), /* @__PURE__ */ jsx("button", {
1918
+ type: "button",
1919
+ className: "rre-btn rre-btn-primary",
1920
+ onClick: applyImageDialog,
1921
+ children: "确定"
1922
+ })]
1923
+ })
1924
+ ]
1925
+ })
1926
+ }) : null,
1546
1927
  /* @__PURE__ */ jsx("input", {
1547
1928
  ref: imageRef,
1548
1929
  type: "file",
@@ -2254,7 +2635,7 @@ function MarkdownEditor({ markdown, onChange, onUploadImage, renderMarkdown = de
2254
2635
  setError("");
2255
2636
  try {
2256
2637
  const url = await onUploadImage(file);
2257
- insertAtCursor(`![${file.name.replace(/\.[^.]+$/, "")}](${url})`, "", file.name);
2638
+ insertAtCursor(`![${file.name.replace(/\.[^.]+$/, "")}](${url} "kbw=640")`, "", file.name);
2258
2639
  } catch (err) {
2259
2640
  setError(err instanceof Error ? err.message : "图片上传失败");
2260
2641
  } finally {