kyle-editor 1.0.1 → 1.0.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.
@@ -199,6 +199,43 @@ const CSS$1 = `
199
199
  .ke-size-cell:hover { border-color: var(--ke-primary); color: var(--ke-primary); background: var(--ke-primary-weak); }
200
200
  .ke-size-cell.ke-is-active { border-color: var(--ke-primary); background: var(--ke-primary); color: #fff; }
201
201
 
202
+ /* -------- 自定义下拉按钮 -------- */
203
+ .ke-btn-custom .ke-btn-text { max-width: 96px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
204
+ .ke-btn-custom.ke-has-value { color: var(--ke-primary); }
205
+ .ke-panel-icon { margin-left: auto; width: 22px; height: 22px; padding: 0; border: 1px solid var(--ke-line); border-radius: 50%; background: #fff; color: #6b7280; cursor: pointer; display: inline-flex; align-items: center; justify-content: center; }
206
+ .ke-panel-icon:hover { border-color: var(--ke-primary); color: var(--ke-primary); }
207
+ .ke-panel-icon .ke-ico { width: 13px; height: 13px; }
208
+ .ke-panel-icon + .ke-panel-note { margin-left: 8px; }
209
+
210
+ .ke-panel-select .ke-sel-search { margin-bottom: 8px; }
211
+ .ke-sel-body { max-height: 268px; overflow-y: auto; overscroll-behavior: contain; margin: 0 -4px; padding: 0 4px; }
212
+ .ke-sel-row {
213
+ display: flex; align-items: center; gap: 8px; width: 100%;
214
+ padding: 7px 9px; margin-bottom: 3px; border: 1px solid transparent; border-radius: 8px;
215
+ background: #fff; cursor: pointer; text-align: left; transition: background .14s, border-color .14s;
216
+ }
217
+ .ke-sel-row:last-child { margin-bottom: 0; }
218
+ .ke-sel-row:hover:not(:disabled) { background: #f7f8fa; }
219
+ .ke-sel-row:disabled { cursor: not-allowed; opacity: .45; }
220
+ .ke-sel-row.ke-is-active { border-color: var(--ke-primary); background: var(--ke-primary-weak); }
221
+ .ke-sel-main { display: flex; flex-direction: column; gap: 1px; min-width: 0; flex: 1; }
222
+ .ke-sel-label { color: #1f2329; font-size: 13.5px; line-height: 1.4; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
223
+ .ke-sel-row.ke-is-active .ke-sel-label { color: var(--ke-primary); font-weight: 600; }
224
+ .ke-sel-desc { color: #a2a8b3; font-size: 11.5px; line-height: 1.45; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
225
+ .ke-sel-link { display: inline-flex; align-items: center; gap: 3px; color: #2f6fed; font-size: 11px; }
226
+ .ke-sel-link .ke-ico { width: 11px; height: 11px; flex: none; }
227
+ .ke-sel-link i { font-style: normal; opacity: .8; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; max-width: 150px; }
228
+ .ke-sel-check { flex: none; width: 16px; height: 16px; color: var(--ke-primary); }
229
+ .ke-sel-check .ke-ico { width: 16px; height: 16px; }
230
+
231
+ .ke-sel-loading { display: flex; align-items: center; gap: 8px; padding: 4px 2px 10px; color: #6b7280; font-size: 12.5px; }
232
+ .ke-sel-loading .ke-spinner { width: 14px; height: 14px; }
233
+ .ke-sel-skel { height: 34px; margin-bottom: 6px; border-radius: 8px; background: linear-gradient(90deg, #f2f3f5 25%, #e9ebef 37%, #f2f3f5 63%); background-size: 400% 100%; animation: ke-skel 1.3s ease infinite; }
234
+ @keyframes ke-skel { from { background-position: 100% 50%; } to { background-position: 0 50%; } }
235
+ .ke-sel-tip { display: flex; flex-direction: column; align-items: center; gap: 10px; padding: 22px 12px; text-align: center; }
236
+ .ke-sel-tip-text { color: #a2a8b3; font-size: 12.5px; line-height: 1.6; word-break: break-all; }
237
+ .ke-sel-tip .ke-btn-primary { align-self: center; }
238
+
202
239
  .ke-tabs { display: flex; gap: 4px; margin: -12px -14px 12px; padding: 0 14px; background: #f8f9fb; border-bottom: 1px solid var(--ke-line-weak); }
203
240
  .ke-tab { height: 34px; padding: 0 4px; margin-right: 10px; border: 0; border-bottom: 2px solid transparent; background: transparent; color: #6b7280; font-size: 13px; cursor: pointer; }
204
241
  .ke-tab:hover { color: #1f2329; }
@@ -642,8 +679,8 @@ class Popover {
642
679
  this.el.classList.remove("ke-pop-in");
643
680
  void this.el.offsetWidth;
644
681
  this.el.classList.add("ke-pop-in");
645
- const first = [...this.el.querySelectorAll("[data-k-autofocus]")].find((node) => node.offsetParent !== null);
646
- (_a = first == null ? void 0 : first.focus) == null ? void 0 : _a.call(first);
682
+ const first2 = [...this.el.querySelectorAll("[data-k-autofocus]")].find((node) => node.offsetParent !== null);
683
+ (_a = first2 == null ? void 0 : first2.focus) == null ? void 0 : _a.call(first2);
647
684
  }
648
685
  close() {
649
686
  if (this.el.hidden) return;
@@ -989,6 +1026,121 @@ function linkPanel({ url = "", text = "", target = false, onSubmit, onCancel, on
989
1026
  wrap.appendChild(body);
990
1027
  return wrap;
991
1028
  }
1029
+ function hostOf(url) {
1030
+ try {
1031
+ return new URL(url, window.location.href).host;
1032
+ } catch {
1033
+ return String(url).slice(0, 40);
1034
+ }
1035
+ }
1036
+ function selectPanel({ title, note, searchable, width, remote, value, load, reload, linkOf, onPick, emptyText }) {
1037
+ const wrap = panel(title);
1038
+ wrap.classList.add("ke-panel-wide", "ke-panel-select");
1039
+ if (width) wrap.style.width = `${Math.min(420, Math.max(200, Number(width)))}px`;
1040
+ const head = wrap.querySelector(".ke-panel-head");
1041
+ const countEl = h("span.ke-panel-note", { text: note || "" });
1042
+ if (remote) {
1043
+ head.appendChild(h("button.ke-panel-icon", {
1044
+ type: "button",
1045
+ title: "重新加载数据",
1046
+ html: icon("retry"),
1047
+ onclick: () => run(reload || load, true)
1048
+ }));
1049
+ }
1050
+ head.appendChild(countEl);
1051
+ const body = h("div.ke-sel-body");
1052
+ wrap.appendChild(body);
1053
+ let items = [];
1054
+ let keyword = "";
1055
+ let generation = 0;
1056
+ if (searchable) {
1057
+ const search = h("input.ke-input.ke-sel-search", {
1058
+ type: "search",
1059
+ placeholder: "搜索…",
1060
+ "data-k-autofocus": ""
1061
+ });
1062
+ search.addEventListener("input", () => {
1063
+ keyword = search.value.trim().toLowerCase();
1064
+ renderRows();
1065
+ });
1066
+ wrap.insertBefore(search, body);
1067
+ }
1068
+ function setState(kind, message) {
1069
+ body.textContent = "";
1070
+ body.dataset.state = kind;
1071
+ if (kind === "loading") {
1072
+ for (let i = 0; i < 3; i += 1) body.appendChild(h("div.ke-sel-skel"));
1073
+ body.insertBefore(h("div.ke-sel-loading", {}, [h("span.ke-spinner"), "数据加载中…"]), body.firstChild);
1074
+ } else if (kind === "error") {
1075
+ body.appendChild(
1076
+ h("div.ke-sel-tip", {}, [
1077
+ h("span.ke-sel-tip-text", { text: message || "数据加载失败" }),
1078
+ h("button.ke-btn-primary", { type: "button", text: "重试", onclick: () => run(reload || load, true) })
1079
+ ])
1080
+ );
1081
+ } else {
1082
+ body.appendChild(h("div.ke-sel-tip", {}, [h("span.ke-sel-tip-text", { text: message || emptyText || "暂无数据" })]));
1083
+ }
1084
+ }
1085
+ function renderRows() {
1086
+ const list = keyword ? items.filter((item) => `${item.label} ${item.desc} ${item.value} ${item.group}`.toLowerCase().includes(keyword)) : items;
1087
+ countEl.textContent = note || (keyword ? `${list.length} / ${items.length} 项` : `${items.length} 项`);
1088
+ body.textContent = "";
1089
+ delete body.dataset.state;
1090
+ if (!list.length) {
1091
+ setState("empty", keyword ? `没有匹配「${keyword}」的选项` : emptyText || "暂无数据");
1092
+ return;
1093
+ }
1094
+ let group = null;
1095
+ list.forEach((item) => {
1096
+ if (item.group && item.group !== group) {
1097
+ group = item.group;
1098
+ body.appendChild(h("div.ke-panel-sect", { text: group }));
1099
+ }
1100
+ body.appendChild(row(item));
1101
+ });
1102
+ }
1103
+ function row(item) {
1104
+ const link = linkOf ? linkOf(item) : null;
1105
+ const el = h("button.ke-sel-row", {
1106
+ type: "button",
1107
+ disabled: item.disabled || void 0,
1108
+ dataset: { kValue: item.value },
1109
+ title: item.disabled ? "该项不可用" : link && link.mode === "open" ? `打开 ${link.url}` : link ? `插入链接:${link.url}` : item.title || "",
1110
+ onclick: () => {
1111
+ if (item.disabled) return;
1112
+ onPick(item);
1113
+ }
1114
+ });
1115
+ el.appendChild(h("span.ke-sel-main", {}, [
1116
+ h("span.ke-sel-label", { text: item.label }),
1117
+ item.desc ? h("span.ke-sel-desc", { text: item.desc }) : null,
1118
+ link ? h("span.ke-sel-link", { html: `${icon("link")}<i>${hostOf(link.url)}</i>` }) : null
1119
+ ]));
1120
+ if (value && String(value) === String(item.value)) {
1121
+ el.classList.add("ke-is-active");
1122
+ el.appendChild(h("span.ke-sel-check", { html: icon("check") }));
1123
+ }
1124
+ if (link) el.classList.add("ke-has-link");
1125
+ return el;
1126
+ }
1127
+ function run(task, force) {
1128
+ generation += 1;
1129
+ const mine = generation;
1130
+ setState("loading");
1131
+ Promise.resolve().then(() => task({ force })).then((result) => {
1132
+ if (mine !== generation || !wrap.isConnected) return;
1133
+ items = Array.isArray(result) ? result : [];
1134
+ if (!items.length) setState("empty");
1135
+ else renderRows();
1136
+ }).catch((error) => {
1137
+ if (mine !== generation || !wrap.isConnected) return;
1138
+ setState("error", error && error.message ? error.message : "数据加载失败");
1139
+ });
1140
+ }
1141
+ run(load);
1142
+ return wrap;
1143
+ }
992
1144
  function normalizeUrl(url) {
993
1145
  const value = String(url || "").trim();
994
1146
  if (!value) return "";
@@ -1466,6 +1618,453 @@ function currentWidthPercent(img, figureWidth) {
1466
1618
  if (match) return parseFloat(match[1]);
1467
1619
  return img.getBoundingClientRect().width / figureWidth * 100;
1468
1620
  }
1621
+ const ALLOWED_TAGS = /* @__PURE__ */ new Set([
1622
+ "a",
1623
+ "abbr",
1624
+ "b",
1625
+ "blockquote",
1626
+ "br",
1627
+ "code",
1628
+ "col",
1629
+ "colgroup",
1630
+ "dd",
1631
+ "del",
1632
+ "div",
1633
+ "dl",
1634
+ "dt",
1635
+ "em",
1636
+ "figcaption",
1637
+ "figure",
1638
+ "font",
1639
+ "h1",
1640
+ "h2",
1641
+ "h3",
1642
+ "h4",
1643
+ "h5",
1644
+ "h6",
1645
+ "hr",
1646
+ "i",
1647
+ "img",
1648
+ "ins",
1649
+ "kbd",
1650
+ "li",
1651
+ "mark",
1652
+ "ol",
1653
+ "p",
1654
+ "pre",
1655
+ "s",
1656
+ "samp",
1657
+ "section",
1658
+ "small",
1659
+ "span",
1660
+ "strong",
1661
+ "sub",
1662
+ "sup",
1663
+ "table",
1664
+ "tbody",
1665
+ "td",
1666
+ "tfoot",
1667
+ "th",
1668
+ "thead",
1669
+ "tr",
1670
+ "u",
1671
+ "ul",
1672
+ "video",
1673
+ "source"
1674
+ ]);
1675
+ const GLOBAL_ATTRS = /* @__PURE__ */ new Set(["style", "class"]);
1676
+ const TAG_ATTRS = {
1677
+ A: ["href", "title", "target", "rel"],
1678
+ IMG: ["src", "alt", "title", "width", "height"],
1679
+ VIDEO: ["src", "poster", "controls", "loop", "muted", "playsinline", "preload", "width", "height"],
1680
+ SOURCE: ["src", "type"],
1681
+ FONT: ["size", "color"],
1682
+ TD: ["colspan", "rowspan"],
1683
+ TH: ["colspan", "rowspan"],
1684
+ OL: ["start"],
1685
+ LI: ["value"]
1686
+ };
1687
+ const DATA_PREFIX = ["data-k-", "data-keditor-"];
1688
+ const SAFE_URL_RE = /^(?:https?:|mailto:|tel:|blob:|\/|#|\.{1,2}\/|[^:]*$)/i;
1689
+ const SAFE_DATA_RE = /^data:image\/(?:png|jpe?g|gif|webp|svg\+xml);/i;
1690
+ function isSafeUrl(url) {
1691
+ if (!url) return false;
1692
+ const value = String(url).trim().replace(/\s+/g, "");
1693
+ if (/^(javascript|vbscript|file|about):/i.test(value)) return false;
1694
+ if (value.startsWith("data:")) return SAFE_DATA_RE.test(value);
1695
+ return SAFE_URL_RE.test(value);
1696
+ }
1697
+ function sanitizeStyle(value) {
1698
+ const out = [];
1699
+ for (const decl of String(value).split(";")) {
1700
+ const idx = decl.indexOf(":");
1701
+ if (idx < 0) continue;
1702
+ const prop = decl.slice(0, idx).trim().toLowerCase();
1703
+ const val = decl.slice(idx + 1).trim();
1704
+ if (!prop || !val) continue;
1705
+ if (!/^[a-z-]+$/.test(prop)) continue;
1706
+ if (prop.startsWith("mso-") || prop.startsWith("-mso-")) continue;
1707
+ if (/expression|javascript:|behavior:|url\(\s*['"]?\s*(javascript|data):/i.test(val)) continue;
1708
+ out.push(`${prop}:${val}`);
1709
+ }
1710
+ return out.join(";");
1711
+ }
1712
+ function sanitizeClass(value) {
1713
+ return String(value).split(/\s+/).filter((name) => /^[\w-]+$/.test(name) && !/^(script|javascript)/i.test(name)).join(" ");
1714
+ }
1715
+ function keepAttribute(tagName, attrName, attrValue) {
1716
+ const name = attrName.toLowerCase();
1717
+ if (name.startsWith("on")) return false;
1718
+ if (GLOBAL_ATTRS.has(name)) return true;
1719
+ if (DATA_PREFIX.some((prefix) => name.startsWith(prefix))) return true;
1720
+ const list = TAG_ATTRS[tagName] || [];
1721
+ return list.includes(name);
1722
+ }
1723
+ function sanitizeHtml(html, { allowEmpty = false } = {}) {
1724
+ if (!html) return allowEmpty ? "" : "<p><br></p>";
1725
+ const doc = new DOMParser().parseFromString(`<div>${html}</div>`, "text/html");
1726
+ const root = doc.body.firstChild;
1727
+ walk(root);
1728
+ const result = root.innerHTML.trim();
1729
+ if (!result && !allowEmpty) return "<p><br></p>";
1730
+ return result;
1731
+ }
1732
+ function walk(node) {
1733
+ const children = Array.from(node.childNodes);
1734
+ for (const child of children) {
1735
+ if (child.nodeType === 8) {
1736
+ child.remove();
1737
+ continue;
1738
+ }
1739
+ if (child.nodeType === 3) continue;
1740
+ if (child.nodeType !== 1) {
1741
+ child.remove();
1742
+ continue;
1743
+ }
1744
+ const tagName = child.tagName;
1745
+ if (!ALLOWED_TAGS.has(tagName.toLowerCase())) {
1746
+ if (tagName === "SCRIPT" || tagName === "STYLE" || tagName === "IFRAME" || tagName === "OBJECT" || tagName === "EMBED" || tagName === "FORM" || tagName === "LINK" || tagName === "META") {
1747
+ child.remove();
1748
+ continue;
1749
+ }
1750
+ const parent = child.parentNode;
1751
+ while (child.firstChild) parent.insertBefore(child.firstChild, child);
1752
+ parent.removeChild(child);
1753
+ continue;
1754
+ }
1755
+ for (const attr of Array.from(child.attributes)) {
1756
+ if (!keepAttribute(tagName, attr.name, attr.value)) {
1757
+ child.removeAttribute(attr.name);
1758
+ continue;
1759
+ }
1760
+ const lower = attr.name.toLowerCase();
1761
+ if (lower === "style") child.setAttribute("style", sanitizeStyle(attr.value));
1762
+ else if (lower === "class") {
1763
+ const cls = sanitizeClass(attr.value);
1764
+ if (cls) child.setAttribute("class", cls);
1765
+ else child.removeAttribute("class");
1766
+ } else if (lower === "href" || lower === "src" || lower === "poster") {
1767
+ if (!isSafeUrl(attr.value)) child.removeAttribute(attr.name);
1768
+ }
1769
+ }
1770
+ if (tagName === "A" && child.getAttribute("target") === "_blank") child.setAttribute("rel", "noopener noreferrer");
1771
+ if (child.getAttribute("href") === "" || !child.getAttribute("href")) {
1772
+ if (tagName === "A") child.removeAttribute("href");
1773
+ }
1774
+ walk(child);
1775
+ }
1776
+ }
1777
+ const WORD_FONT_SIZES = { 1: 10, 2: 13, 3: 16, 4: 18, 5: 24, 6: 32, 7: 48 };
1778
+ function isWordHtml(html) {
1779
+ return /urn:schemas-microsoft-com|class=["']?Mso|ProgID|w:val=/i.test(html);
1780
+ }
1781
+ function cleanWordHtml(html) {
1782
+ const doc = new DOMParser().parseFromString(`<div>${html}</div>`, "text/html");
1783
+ const root = doc.body.firstChild;
1784
+ root.querySelectorAll("*").forEach((node) => {
1785
+ const tag = node.tagName.toLowerCase();
1786
+ if (tag.startsWith("o:") || tag.startsWith("w:") || tag === "style" || tag === "script" || tag === "link" || tag === "meta") {
1787
+ node.remove();
1788
+ return;
1789
+ }
1790
+ if (tag === "img") {
1791
+ const width = Number(node.getAttribute("width") || 0);
1792
+ const height = Number(node.getAttribute("height") || 0);
1793
+ if (width && width <= 3 || height && height <= 3) node.remove();
1794
+ return;
1795
+ }
1796
+ if (tag === "font") {
1797
+ const size = WORD_FONT_SIZES[Number(node.getAttribute("size"))];
1798
+ const span = doc.createElement("span");
1799
+ const styles = [];
1800
+ if (size) styles.push(`font-size:${size}px`);
1801
+ if (node.color) styles.push(`color:${node.color}`);
1802
+ if (styles.length) span.setAttribute("style", styles.join(";"));
1803
+ while (node.firstChild) span.appendChild(node.firstChild);
1804
+ node.replaceWith(span);
1805
+ return;
1806
+ }
1807
+ for (const attr of Array.from(node.attributes)) {
1808
+ const name = attr.name.toLowerCase();
1809
+ if (name.startsWith("mso-") || name === "class" || name.startsWith("_") || name.startsWith("w:") || name.startsWith("o:") || name === "lang" || name === "dir") {
1810
+ node.removeAttribute(attr.name);
1811
+ }
1812
+ }
1813
+ });
1814
+ return root.innerHTML;
1815
+ }
1816
+ function escapeHtml(text) {
1817
+ return String(text).replace(/[&<>"']/g, (ch) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" })[ch]);
1818
+ }
1819
+ function toPlainText(html) {
1820
+ const doc = new DOMParser().parseFromString(`<div>${html}</div>`, "text/html");
1821
+ doc.body.querySelectorAll("style,script").forEach((n) => n.remove());
1822
+ doc.body.innerHTML = doc.body.innerHTML.replace(/<\/(p|div|h[1-6]|li|blockquote|pre|tr)>/gi, "\n");
1823
+ return doc.body.textContent.replace(/\u00a0/g, " ").replace(/\n{3,}/g, "\n\n").trim();
1824
+ }
1825
+ const DEFAULT_TIMEOUT = 1e4;
1826
+ function pickArray(raw) {
1827
+ if (Array.isArray(raw)) return raw;
1828
+ if (!raw || typeof raw !== "object") return [];
1829
+ for (const key of ["items", "list", "data", "rows", "records", "result"]) {
1830
+ const value = raw[key];
1831
+ if (Array.isArray(value)) return value;
1832
+ if (value && typeof value === "object") {
1833
+ const nested = pickArray(value);
1834
+ if (nested.length) return nested;
1835
+ }
1836
+ }
1837
+ return [];
1838
+ }
1839
+ function first(entry, keys) {
1840
+ for (const key of keys) {
1841
+ const value = entry[key];
1842
+ if (value !== void 0 && value !== null) return value;
1843
+ }
1844
+ return void 0;
1845
+ }
1846
+ function normalizeItem(entry, index) {
1847
+ if (entry === void 0 || entry === null) return null;
1848
+ if (typeof entry === "string" || typeof entry === "number") {
1849
+ const text = String(entry);
1850
+ return { value: text, label: text, desc: "", url: "", group: "", html: "", disabled: false, raw: entry };
1851
+ }
1852
+ if (typeof entry !== "object") return null;
1853
+ const value = first(entry, ["value", "id", "key", "val", "code"]);
1854
+ const label = first(entry, ["label", "text", "name", "title"]);
1855
+ return {
1856
+ value: value === void 0 ? String(index) : String(value),
1857
+ label: label === void 0 || label === "" ? value === void 0 ? String(index) : String(value) : String(label),
1858
+ desc: String(first(entry, ["desc", "description", "sub", "subtitle", "tip"]) ?? ""),
1859
+ url: String(first(entry, ["url", "href", "link", "jumpUrl", "jump"]) ?? ""),
1860
+ group: String(entry.group ?? ""),
1861
+ html: String(entry.html ?? ""),
1862
+ disabled: !!entry.disabled,
1863
+ raw: entry
1864
+ };
1865
+ }
1866
+ function normalizeItems(raw) {
1867
+ return pickArray(raw).map(normalizeItem).filter(Boolean);
1868
+ }
1869
+ function normalizeCustomButton(spec) {
1870
+ if (!spec || typeof spec !== "object") return null;
1871
+ const name = String(spec.name || "").trim();
1872
+ if (!name) return null;
1873
+ return {
1874
+ name,
1875
+ type: spec.type === "button" ? "button" : "select",
1876
+ title: spec.title || spec.text || name,
1877
+ text: spec.text || "",
1878
+ placeholder: spec.placeholder || spec.text || "请选择",
1879
+ icon: spec.icon || "",
1880
+ width: Number(spec.width) > 0 ? Number(spec.width) : 0,
1881
+ searchable: !!spec.searchable,
1882
+ note: spec.note ? String(spec.note) : "",
1883
+ emptyText: spec.emptyText ? String(spec.emptyText) : "",
1884
+ cache: spec.cache !== false,
1885
+ keepValue: spec.keepValue !== false,
1886
+ multiple: false,
1887
+ options: spec.options ?? null,
1888
+ load: typeof spec.load === "function" ? spec.load : null,
1889
+ url: spec.url ? String(spec.url) : "",
1890
+ fetchOptions: spec.fetchOptions && typeof spec.fetchOptions === "object" ? spec.fetchOptions : {},
1891
+ pick: typeof spec.pick === "function" ? spec.pick : null,
1892
+ link: spec.link ?? null,
1893
+ insert: spec.insert === void 0 ? "auto" : spec.insert,
1894
+ onSelect: typeof spec.onSelect === "function" ? spec.onSelect : null,
1895
+ onClick: typeof spec.onClick === "function" ? spec.onClick : null,
1896
+ active: typeof spec.active === "function" ? spec.active : null,
1897
+ enabled: typeof spec.enabled === "function" ? spec.enabled : null
1898
+ };
1899
+ }
1900
+ function normalizeCustomButtons(list) {
1901
+ if (!Array.isArray(list)) return [];
1902
+ return list.map(normalizeCustomButton).filter(Boolean);
1903
+ }
1904
+ function createButtonRuntime() {
1905
+ return { items: null, loaded: false, loading: null, value: null, controller: null, error: "", gen: 0, external: false };
1906
+ }
1907
+ async function fetchItems(spec, editor, rt) {
1908
+ if (spec.load) return normalizeItems(await spec.load(editor));
1909
+ if (spec.url) return normalizeItems(await httpFetch(spec, editor, rt));
1910
+ return normalizeItems(spec.options);
1911
+ }
1912
+ async function httpFetch(spec, editor, rt) {
1913
+ var _a;
1914
+ const cfg = spec.fetchOptions;
1915
+ const impl = cfg.fetch || (typeof fetch === "function" ? fetch.bind(globalThis) : null);
1916
+ if (!impl) throw new Error("当前环境无 fetch,请改用 load 函数提供数据");
1917
+ (_a = rt.controller) == null ? void 0 : _a.abort();
1918
+ const controller = typeof AbortController === "function" ? new AbortController() : null;
1919
+ rt.controller = controller;
1920
+ const timeout = Number(cfg.timeout) > 0 ? Number(cfg.timeout) : DEFAULT_TIMEOUT;
1921
+ const timer = setTimeout(() => controller == null ? void 0 : controller.abort(), timeout);
1922
+ try {
1923
+ const res = await impl(spec.url, {
1924
+ method: cfg.method || "GET",
1925
+ headers: cfg.headers,
1926
+ body: cfg.body,
1927
+ credentials: cfg.credentials,
1928
+ signal: controller ? controller.signal : void 0
1929
+ });
1930
+ if (!res || res.ok === false) throw new Error(`接口返回 ${res && res.status ? res.status : "异常"}`);
1931
+ const payload = cfg.parser ? await cfg.parser(res) : await res.json();
1932
+ return spec.pick ? spec.pick(payload, editor) : payload;
1933
+ } catch (error) {
1934
+ if (error && error.name === "AbortError") throw new Error(`请求超时(${timeout}ms)或被取消`);
1935
+ throw error;
1936
+ } finally {
1937
+ clearTimeout(timer);
1938
+ if (rt.controller === controller) rt.controller = null;
1939
+ }
1940
+ }
1941
+ function loadItems(spec, editor, rt, { force = false } = {}) {
1942
+ if (!force && rt.external && rt.items) return Promise.resolve(rt.items);
1943
+ if (!force && spec.cache && rt.items) return Promise.resolve(rt.items);
1944
+ if (!force && rt.loading) return rt.loading;
1945
+ const gen = rt.gen;
1946
+ const task = fetchItems(spec, editor, rt).then((items) => {
1947
+ if (gen !== rt.gen) return rt.items;
1948
+ rt.items = items;
1949
+ rt.loaded = true;
1950
+ rt.error = "";
1951
+ return items;
1952
+ }).catch((error) => {
1953
+ if (gen !== rt.gen) return rt.items;
1954
+ rt.error = error && error.message ? error.message : String(error);
1955
+ throw error;
1956
+ }).finally(() => {
1957
+ if (rt.loading === task) rt.loading = null;
1958
+ });
1959
+ rt.loading = task;
1960
+ return task;
1961
+ }
1962
+ function setRuntimeItems(rt, raw) {
1963
+ rt.gen += 1;
1964
+ rt.items = normalizeItems(raw);
1965
+ rt.loaded = true;
1966
+ rt.error = "";
1967
+ rt.external = true;
1968
+ abortRuntime(rt);
1969
+ rt.loading = null;
1970
+ return rt.items;
1971
+ }
1972
+ function abortRuntime(rt) {
1973
+ var _a;
1974
+ (_a = rt.controller) == null ? void 0 : _a.abort();
1975
+ rt.controller = null;
1976
+ }
1977
+ function fill(template, item) {
1978
+ return String(template).replace(/\{(\w+)\}/g, (match, key) => {
1979
+ if (item[key] !== void 0 && item[key] !== null) return String(item[key]);
1980
+ const fromRaw = item.raw && item.raw[key];
1981
+ return fromRaw === void 0 || fromRaw === null ? match : String(fromRaw);
1982
+ });
1983
+ }
1984
+ function pick$1(raw, item, editor) {
1985
+ return typeof raw === "function" ? raw(item, editor) : raw;
1986
+ }
1987
+ function resolveLink(spec, item, editor) {
1988
+ const conf = spec.link;
1989
+ let raw = null;
1990
+ if (typeof conf === "function") raw = conf(item, editor);
1991
+ else if (typeof conf === "string") raw = { url: conf };
1992
+ else if (conf && typeof conf === "object") raw = conf;
1993
+ else if (conf === true || item.url) raw = { url: item.url };
1994
+ if (!raw) return null;
1995
+ if (typeof raw === "string") raw = { url: raw };
1996
+ const url = normalizeUrl(fill(String(pick$1(raw.url, item, editor) ?? ""), item));
1997
+ if (!url || !isSafeUrl(url)) return null;
1998
+ const text = pick$1(raw.text, item, editor);
1999
+ const title = pick$1(raw.title, item, editor);
2000
+ const mode = raw.mode === "open" ? "open" : "insert";
2001
+ const target = raw.target === "_self" || raw.target === false ? "_self" : "_blank";
2002
+ return {
2003
+ mode,
2004
+ url,
2005
+ text: text === void 0 || text === null || text === "" ? item.label : fill(String(text), item),
2006
+ target,
2007
+ title: title ? fill(String(title), item) : ""
2008
+ };
2009
+ }
2010
+ function insertText(editor, text) {
2011
+ editor.commands.insertHTML(escapeHtml(text));
2012
+ }
2013
+ async function applySelection(editor, spec, rt, item) {
2014
+ editor.restoreSelection();
2015
+ const link = resolveLink(spec, item, editor);
2016
+ const ctx = {
2017
+ editor,
2018
+ item,
2019
+ link,
2020
+ insertLink: (override) => insertLink(editor, { ...link, ...override }),
2021
+ insertHtml: (html) => editor.commands.insertHTML(String(html)),
2022
+ insertText: (text) => insertText(editor, text),
2023
+ open: (url, target) => openUrl(url || link && link.url, target || link && link.target)
2024
+ };
2025
+ let action = "none";
2026
+ let handled = false;
2027
+ if (spec.onSelect) {
2028
+ handled = await spec.onSelect(item, ctx) === false;
2029
+ }
2030
+ if (!handled) action = doDefaultInsert(editor, spec, item, link);
2031
+ if (spec.keepValue) rt.value = item;
2032
+ const payload = { name: spec.name, item, link, action, editor };
2033
+ editor.emit("customselect", payload);
2034
+ return payload;
2035
+ }
2036
+ function doDefaultInsert(editor, spec, item, link) {
2037
+ const mode = spec.insert;
2038
+ if (mode === false || mode === "none") return "none";
2039
+ if (link && link.mode === "open") {
2040
+ openUrl(link.url, link.target);
2041
+ return "open";
2042
+ }
2043
+ if (mode === "link" || mode === "auto" && link) {
2044
+ if (!link) return "none";
2045
+ insertLink(editor, link);
2046
+ return "link";
2047
+ }
2048
+ if (mode === "html" || mode === "auto" && item.html) {
2049
+ if (!item.html) return "none";
2050
+ editor.commands.insertHTML(item.html);
2051
+ return "html";
2052
+ }
2053
+ insertText(editor, item.label);
2054
+ return "text";
2055
+ }
2056
+ function insertLink(editor, link) {
2057
+ editor.commands.createLink({
2058
+ url: link.url,
2059
+ text: link.text,
2060
+ target: link.target !== "_self"
2061
+ });
2062
+ }
2063
+ function openUrl(url, target = "_blank") {
2064
+ if (!url || !isSafeUrl(url)) return;
2065
+ if (target === "_self") window.location.href = url;
2066
+ else window.open(url, "_blank", "noopener,noreferrer");
2067
+ }
1469
2068
  const CARET = '<svg class="ke-caret" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round"><path d="m6 9 6 6 6-6"/></svg>';
1470
2069
  const SCROLL_HINT_KEY = "keditor.toolbarScrollHint";
1471
2070
  const SCROLL_HINT_ICON = '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.1" stroke-linecap="round" stroke-linejoin="round"><path d="M8 7 4 12l4 5"/><path d="M16 7l4 5-4 5"/><path d="M4 12h16"/></svg>';
@@ -1540,28 +2139,37 @@ const ITEMS = {
1540
2139
  backColor: { pop: "back", title: "背景高亮色", toggles: true, swatch: "back" }
1541
2140
  };
1542
2141
  class Toolbar {
1543
- constructor(editor, items = DEFAULT_TOOLBAR) {
2142
+ constructor(editor, items = DEFAULT_TOOLBAR, customButtons = []) {
1544
2143
  this.editor = editor;
1545
2144
  this.buttons = /* @__PURE__ */ new Map();
2145
+ this.custom = /* @__PURE__ */ new Map();
1546
2146
  this.colorState = { foreColor: "#3f3f3f", backColor: "#f6c344" };
1547
2147
  this.recent = { foreColor: [], backColor: [] };
1548
2148
  this.el = editor.tbEl;
2149
+ for (const spec of customButtons) this.registerCustom(spec);
1549
2150
  this.build(items);
1550
2151
  this.setupScrollHints();
1551
2152
  }
1552
2153
  build(items) {
1553
2154
  const group = h("div.ke-tb-group");
1554
2155
  this.el.appendChild(group);
1555
- let tail = null;
1556
- const target = () => tail || group;
2156
+ this.groupEl = group;
2157
+ this.tailEl = null;
2158
+ const target = () => this.tailEl || group;
1557
2159
  for (const key of items) {
1558
2160
  if (key === "|") {
1559
- group.appendChild(h("span.ke-tb-sep"));
2161
+ target().appendChild(h("span.ke-tb-sep"));
1560
2162
  continue;
1561
2163
  }
1562
2164
  if (key === ":tail") {
1563
- tail = h("div.ke-tb-tail");
1564
- this.el.appendChild(tail);
2165
+ this.tailEl = h("div.ke-tb-tail");
2166
+ this.el.appendChild(this.tailEl);
2167
+ continue;
2168
+ }
2169
+ if (this.custom.has(key)) {
2170
+ const entry = this.custom.get(key);
2171
+ entry.button = this.buildCustomButton(entry);
2172
+ target().appendChild(entry.button);
1565
2173
  continue;
1566
2174
  }
1567
2175
  if (key === "heading") {
@@ -1576,6 +2184,13 @@ class Toolbar {
1576
2184
  if (!spec) continue;
1577
2185
  target().appendChild(this.buildButton(key, spec));
1578
2186
  }
2187
+ for (const [name, entry] of this.custom) {
2188
+ if (!entry.button) {
2189
+ entry.button = this.buildCustomButton(entry);
2190
+ target().appendChild(entry.button);
2191
+ }
2192
+ entry.button.dataset.kCustom = name;
2193
+ }
1579
2194
  }
1580
2195
  buildButton(name, spec) {
1581
2196
  const button = h("button.ke-btn", {
@@ -1686,6 +2301,172 @@ class Toolbar {
1686
2301
  this.buttons.set("fontsize", button);
1687
2302
  return button;
1688
2303
  }
2304
+ /* ---------------- 自定义按钮 ---------------- */
2305
+ /** 登记一个自定义按钮规格;统一在此规范化,保证配置与 addButton 两条路径行为一致 */
2306
+ registerCustom(raw) {
2307
+ const spec = normalizeCustomButton(raw);
2308
+ if (!spec) return null;
2309
+ const prev = this.custom.get(spec.name);
2310
+ const entry = { spec, rt: prev ? prev.rt : createButtonRuntime(), button: prev ? prev.button : null };
2311
+ this.custom.set(spec.name, entry);
2312
+ return entry;
2313
+ }
2314
+ buildCustomButton(entry) {
2315
+ const { spec } = entry;
2316
+ const isSelect = spec.type === "select";
2317
+ const button = h("button.ke-btn", {
2318
+ type: "button",
2319
+ class: isSelect ? "ke-btn-label ke-btn-custom" : "ke-btn-custom",
2320
+ title: spec.title,
2321
+ "data-k-item": spec.name,
2322
+ dataset: { kPop: spec.name },
2323
+ onclick: (event) => {
2324
+ event.preventDefault();
2325
+ if (isSelect) this.openCustom(spec.name);
2326
+ else this.runCustomButton(spec);
2327
+ }
2328
+ });
2329
+ if (spec.icon) button.innerHTML = /</.test(spec.icon) ? spec.icon : icon(spec.icon);
2330
+ if (isSelect) {
2331
+ button.appendChild(h("span.ke-btn-text", { text: spec.text || spec.placeholder }));
2332
+ button.insertAdjacentHTML("beforeend", CARET);
2333
+ } else if (spec.text) {
2334
+ button.appendChild(h("span.ke-btn-text", { text: spec.text }));
2335
+ }
2336
+ this.syncCustomLabel(spec.name, button);
2337
+ return button;
2338
+ }
2339
+ /** 按钮文案跟随当前选中项(与段落样式 / 字号按钮一致) */
2340
+ syncCustomLabel(name, node) {
2341
+ const entry = this.custom.get(name);
2342
+ const button = node || (entry == null ? void 0 : entry.button);
2343
+ if (!entry || !button) return;
2344
+ const { spec, rt } = entry;
2345
+ if (spec.type !== "select") return;
2346
+ const label = button.querySelector(".ke-btn-text");
2347
+ if (!label) return;
2348
+ const picked = rt.value;
2349
+ label.textContent = picked ? picked.label : spec.text || spec.placeholder;
2350
+ button.title = picked ? `${spec.title}:${picked.label}` : spec.title;
2351
+ button.classList.toggle("ke-has-value", !!picked);
2352
+ }
2353
+ /** 打开下拉面板:数据异步加载,带缓存 / 重试 / 搜索 */
2354
+ openCustom(name) {
2355
+ const entry = this.custom.get(name);
2356
+ if (!entry) return;
2357
+ this.revealButton(entry.button);
2358
+ const { spec, rt } = entry;
2359
+ const remote = !!(spec.load || spec.url);
2360
+ const fetcher = ({ force } = {}) => loadItems(spec, this.editor, rt, { force });
2361
+ this.togglePop(name, entry.button, () => selectPanel({
2362
+ title: spec.title,
2363
+ note: spec.note || "",
2364
+ searchable: spec.searchable,
2365
+ width: spec.width,
2366
+ remote,
2367
+ value: rt.value ? rt.value.value : "",
2368
+ emptyText: spec.emptyText,
2369
+ load: fetcher,
2370
+ reload: fetcher,
2371
+ linkOf: (item) => resolveLink(spec, item, this.editor),
2372
+ onPick: (item) => this.pickCustom(name, item)
2373
+ }));
2374
+ }
2375
+ async pickCustom(name, item) {
2376
+ const entry = this.custom.get(name);
2377
+ if (!entry) return;
2378
+ this.editor.popover.close();
2379
+ try {
2380
+ await applySelection(this.editor, entry.spec, entry.rt, item);
2381
+ } catch (error) {
2382
+ this.editor.reportError("custombutton", error);
2383
+ }
2384
+ this.syncCustomLabel(name);
2385
+ this.editor.refresh();
2386
+ }
2387
+ /** type:'button' 的简单自定义按钮 */
2388
+ async runCustomButton(spec) {
2389
+ this.editor.popover.close();
2390
+ try {
2391
+ if (spec.onClick) await spec.onClick({ editor: this.editor, name: spec.name });
2392
+ this.editor.emit("customclick", { name: spec.name, editor: this.editor });
2393
+ } catch (error) {
2394
+ this.editor.reportError("custombutton", error);
2395
+ }
2396
+ this.editor.refresh();
2397
+ }
2398
+ /** 运行时新增自定义按钮;at 为 toolbar 内插入位置(默认追加到主分组末尾) */
2399
+ addButton(spec, { at } = {}) {
2400
+ var _a;
2401
+ const entry = this.registerCustom(spec);
2402
+ if (!entry) return null;
2403
+ if (entry.button) entry.button.remove();
2404
+ entry.button = this.buildCustomButton(entry);
2405
+ const host = this.tailEl || this.groupEl;
2406
+ if (!host) return entry.button;
2407
+ if (typeof at === "number" && at >= 0) {
2408
+ const ref = host.children[Math.min(at, host.children.length)];
2409
+ host.insertBefore(entry.button, ref || null);
2410
+ } else {
2411
+ const sep2 = h("span.ke-tb-sep");
2412
+ host.appendChild(sep2);
2413
+ host.appendChild(entry.button);
2414
+ }
2415
+ this.revealButton(entry.button);
2416
+ (_a = this.syncScrollHints) == null ? void 0 : _a.call(this);
2417
+ return entry.button;
2418
+ }
2419
+ /** 工具栏溢出时把按钮滚进可视区(避开 sticky 尾栏的遮挡) */
2420
+ revealButton(button) {
2421
+ const tb = this.el;
2422
+ if (!tb || !button || !button.isConnected) return;
2423
+ const max = tb.scrollWidth - tb.clientWidth;
2424
+ if (max <= 1) return;
2425
+ const tailW = this.tailEl ? this.tailEl.offsetWidth : 0;
2426
+ const left = button.offsetLeft;
2427
+ const right = left + button.offsetWidth;
2428
+ const viewR = tb.scrollLeft + tb.clientWidth - tailW;
2429
+ if (right > viewR - 4) tb.scrollLeft = Math.min(max, right - tb.clientWidth + tailW + 10);
2430
+ else if (left < tb.scrollLeft + 4) tb.scrollLeft = Math.max(0, left - 10);
2431
+ }
2432
+ /** 移除自定义按钮并中断其未完成的请求 */
2433
+ removeButton(name) {
2434
+ var _a, _b;
2435
+ const entry = this.custom.get(name);
2436
+ if (!entry) return false;
2437
+ abortRuntime(entry.rt);
2438
+ if (this.editor.popover.anchor === entry.button) this.editor.popover.close();
2439
+ (_a = entry.button) == null ? void 0 : _a.remove();
2440
+ this.buttons.delete(name);
2441
+ this.custom.delete(name);
2442
+ (_b = this.syncScrollHints) == null ? void 0 : _b.call(this);
2443
+ return true;
2444
+ }
2445
+ /** 外部灌入下拉数据(接口在编辑器之外请求时用),并刷新已打开的面板 */
2446
+ setButtonOptions(name, items) {
2447
+ const entry = this.custom.get(name);
2448
+ if (!entry) return null;
2449
+ const list = setRuntimeItems(entry.rt, items);
2450
+ if (this.editor.popover.isOpen && this.editor.popover.anchor === entry.button) {
2451
+ this.editor.popover.close();
2452
+ this.openCustom(name);
2453
+ }
2454
+ return list;
2455
+ }
2456
+ /** 读取按钮当前选中项 */
2457
+ getButtonValue(name) {
2458
+ const entry = this.custom.get(name);
2459
+ return entry ? entry.rt.value : null;
2460
+ }
2461
+ setButtonValue(name, value) {
2462
+ const entry = this.custom.get(name);
2463
+ if (!entry) return null;
2464
+ const items = entry.rt.items || [];
2465
+ const match = items.find((item) => String(item.value) === String(value)) || null;
2466
+ entry.rt.value = match;
2467
+ this.syncCustomLabel(name);
2468
+ return match;
2469
+ }
1689
2470
  toggleColor(name, button) {
1690
2471
  const kind = name === "foreColor" ? "fore" : "back";
1691
2472
  this.togglePop(
@@ -1774,6 +2555,13 @@ class Toolbar {
1774
2555
  if (button.dataset.kPop || !spec.pop) button.classList.toggle("ke-is-active", active);
1775
2556
  if (spec.enabled) button.disabled = !spec.enabled(state);
1776
2557
  }
2558
+ for (const [name, entry] of this.custom) {
2559
+ const { spec, button } = entry;
2560
+ if (!button) continue;
2561
+ if (spec.active) button.classList.toggle("ke-is-active", !!spec.active(state, this.editor));
2562
+ if (spec.enabled) button.disabled = !spec.enabled(state, this.editor);
2563
+ if (spec.type === "select") this.syncCustomLabel(name);
2564
+ }
1777
2565
  if (this.headingEl) {
1778
2566
  const match = HEADINGS.find((x) => x.value === state.block);
1779
2567
  const label = this.headingEl.querySelector(".ke-btn-text");
@@ -1923,6 +2711,8 @@ class Toolbar {
1923
2711
  }
1924
2712
  if (this.onTbScroll) tb.removeEventListener("scroll", this.onTbScroll);
1925
2713
  if (this.onTbPointerDown) tb.removeEventListener("pointerdown", this.onTbPointerDown);
2714
+ for (const entry of this.custom.values()) abortRuntime(entry.rt);
2715
+ this.custom.clear();
1926
2716
  (_a = this.scrollFades) == null ? void 0 : _a.remove();
1927
2717
  (_b = this.hintEl) == null ? void 0 : _b.remove();
1928
2718
  this.scrollFades = null;
@@ -2038,210 +2828,6 @@ function closestBlock(node, root) {
2038
2828
  }
2039
2829
  return null;
2040
2830
  }
2041
- const ALLOWED_TAGS = /* @__PURE__ */ new Set([
2042
- "a",
2043
- "abbr",
2044
- "b",
2045
- "blockquote",
2046
- "br",
2047
- "code",
2048
- "col",
2049
- "colgroup",
2050
- "dd",
2051
- "del",
2052
- "div",
2053
- "dl",
2054
- "dt",
2055
- "em",
2056
- "figcaption",
2057
- "figure",
2058
- "font",
2059
- "h1",
2060
- "h2",
2061
- "h3",
2062
- "h4",
2063
- "h5",
2064
- "h6",
2065
- "hr",
2066
- "i",
2067
- "img",
2068
- "ins",
2069
- "kbd",
2070
- "li",
2071
- "mark",
2072
- "ol",
2073
- "p",
2074
- "pre",
2075
- "s",
2076
- "samp",
2077
- "section",
2078
- "small",
2079
- "span",
2080
- "strong",
2081
- "sub",
2082
- "sup",
2083
- "table",
2084
- "tbody",
2085
- "td",
2086
- "tfoot",
2087
- "th",
2088
- "thead",
2089
- "tr",
2090
- "u",
2091
- "ul",
2092
- "video",
2093
- "source"
2094
- ]);
2095
- const GLOBAL_ATTRS = /* @__PURE__ */ new Set(["style", "class"]);
2096
- const TAG_ATTRS = {
2097
- A: ["href", "title", "target", "rel"],
2098
- IMG: ["src", "alt", "title", "width", "height"],
2099
- VIDEO: ["src", "poster", "controls", "loop", "muted", "playsinline", "preload", "width", "height"],
2100
- SOURCE: ["src", "type"],
2101
- FONT: ["size", "color"],
2102
- TD: ["colspan", "rowspan"],
2103
- TH: ["colspan", "rowspan"],
2104
- OL: ["start"],
2105
- LI: ["value"]
2106
- };
2107
- const DATA_PREFIX = ["data-k-", "data-keditor-"];
2108
- const SAFE_URL_RE = /^(?:https?:|mailto:|tel:|blob:|\/|#|\.{1,2}\/|[^:]*$)/i;
2109
- const SAFE_DATA_RE = /^data:image\/(?:png|jpe?g|gif|webp|svg\+xml);/i;
2110
- function isSafeUrl(url) {
2111
- if (!url) return false;
2112
- const value = String(url).trim().replace(/\s+/g, "");
2113
- if (/^(javascript|vbscript|file|about):/i.test(value)) return false;
2114
- if (value.startsWith("data:")) return SAFE_DATA_RE.test(value);
2115
- return SAFE_URL_RE.test(value);
2116
- }
2117
- function sanitizeStyle(value) {
2118
- const out = [];
2119
- for (const decl of String(value).split(";")) {
2120
- const idx = decl.indexOf(":");
2121
- if (idx < 0) continue;
2122
- const prop = decl.slice(0, idx).trim().toLowerCase();
2123
- const val = decl.slice(idx + 1).trim();
2124
- if (!prop || !val) continue;
2125
- if (!/^[a-z-]+$/.test(prop)) continue;
2126
- if (prop.startsWith("mso-") || prop.startsWith("-mso-")) continue;
2127
- if (/expression|javascript:|behavior:|url\(\s*['"]?\s*(javascript|data):/i.test(val)) continue;
2128
- out.push(`${prop}:${val}`);
2129
- }
2130
- return out.join(";");
2131
- }
2132
- function sanitizeClass(value) {
2133
- return String(value).split(/\s+/).filter((name) => /^[\w-]+$/.test(name) && !/^(script|javascript)/i.test(name)).join(" ");
2134
- }
2135
- function keepAttribute(tagName, attrName, attrValue) {
2136
- const name = attrName.toLowerCase();
2137
- if (name.startsWith("on")) return false;
2138
- if (GLOBAL_ATTRS.has(name)) return true;
2139
- if (DATA_PREFIX.some((prefix) => name.startsWith(prefix))) return true;
2140
- const list = TAG_ATTRS[tagName] || [];
2141
- return list.includes(name);
2142
- }
2143
- function sanitizeHtml(html, { allowEmpty = false } = {}) {
2144
- if (!html) return allowEmpty ? "" : "<p><br></p>";
2145
- const doc = new DOMParser().parseFromString(`<div>${html}</div>`, "text/html");
2146
- const root = doc.body.firstChild;
2147
- walk(root);
2148
- const result = root.innerHTML.trim();
2149
- if (!result && !allowEmpty) return "<p><br></p>";
2150
- return result;
2151
- }
2152
- function walk(node) {
2153
- const children = Array.from(node.childNodes);
2154
- for (const child of children) {
2155
- if (child.nodeType === 8) {
2156
- child.remove();
2157
- continue;
2158
- }
2159
- if (child.nodeType === 3) continue;
2160
- if (child.nodeType !== 1) {
2161
- child.remove();
2162
- continue;
2163
- }
2164
- const tagName = child.tagName;
2165
- if (!ALLOWED_TAGS.has(tagName.toLowerCase())) {
2166
- if (tagName === "SCRIPT" || tagName === "STYLE" || tagName === "IFRAME" || tagName === "OBJECT" || tagName === "EMBED" || tagName === "FORM" || tagName === "LINK" || tagName === "META") {
2167
- child.remove();
2168
- continue;
2169
- }
2170
- const parent = child.parentNode;
2171
- while (child.firstChild) parent.insertBefore(child.firstChild, child);
2172
- parent.removeChild(child);
2173
- continue;
2174
- }
2175
- for (const attr of Array.from(child.attributes)) {
2176
- if (!keepAttribute(tagName, attr.name, attr.value)) {
2177
- child.removeAttribute(attr.name);
2178
- continue;
2179
- }
2180
- const lower = attr.name.toLowerCase();
2181
- if (lower === "style") child.setAttribute("style", sanitizeStyle(attr.value));
2182
- else if (lower === "class") {
2183
- const cls = sanitizeClass(attr.value);
2184
- if (cls) child.setAttribute("class", cls);
2185
- else child.removeAttribute("class");
2186
- } else if (lower === "href" || lower === "src" || lower === "poster") {
2187
- if (!isSafeUrl(attr.value)) child.removeAttribute(attr.name);
2188
- }
2189
- }
2190
- if (tagName === "A" && child.getAttribute("target") === "_blank") child.setAttribute("rel", "noopener noreferrer");
2191
- if (child.getAttribute("href") === "" || !child.getAttribute("href")) {
2192
- if (tagName === "A") child.removeAttribute("href");
2193
- }
2194
- walk(child);
2195
- }
2196
- }
2197
- const WORD_FONT_SIZES = { 1: 10, 2: 13, 3: 16, 4: 18, 5: 24, 6: 32, 7: 48 };
2198
- function isWordHtml(html) {
2199
- return /urn:schemas-microsoft-com|class=["']?Mso|ProgID|w:val=/i.test(html);
2200
- }
2201
- function cleanWordHtml(html) {
2202
- const doc = new DOMParser().parseFromString(`<div>${html}</div>`, "text/html");
2203
- const root = doc.body.firstChild;
2204
- root.querySelectorAll("*").forEach((node) => {
2205
- const tag = node.tagName.toLowerCase();
2206
- if (tag.startsWith("o:") || tag.startsWith("w:") || tag === "style" || tag === "script" || tag === "link" || tag === "meta") {
2207
- node.remove();
2208
- return;
2209
- }
2210
- if (tag === "img") {
2211
- const width = Number(node.getAttribute("width") || 0);
2212
- const height = Number(node.getAttribute("height") || 0);
2213
- if (width && width <= 3 || height && height <= 3) node.remove();
2214
- return;
2215
- }
2216
- if (tag === "font") {
2217
- const size = WORD_FONT_SIZES[Number(node.getAttribute("size"))];
2218
- const span = doc.createElement("span");
2219
- const styles = [];
2220
- if (size) styles.push(`font-size:${size}px`);
2221
- if (node.color) styles.push(`color:${node.color}`);
2222
- if (styles.length) span.setAttribute("style", styles.join(";"));
2223
- while (node.firstChild) span.appendChild(node.firstChild);
2224
- node.replaceWith(span);
2225
- return;
2226
- }
2227
- for (const attr of Array.from(node.attributes)) {
2228
- const name = attr.name.toLowerCase();
2229
- if (name.startsWith("mso-") || name === "class" || name.startsWith("_") || name.startsWith("w:") || name.startsWith("o:") || name === "lang" || name === "dir") {
2230
- node.removeAttribute(attr.name);
2231
- }
2232
- }
2233
- });
2234
- return root.innerHTML;
2235
- }
2236
- function escapeHtml(text) {
2237
- return String(text).replace(/[&<>"']/g, (ch) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" })[ch]);
2238
- }
2239
- function toPlainText(html) {
2240
- const doc = new DOMParser().parseFromString(`<div>${html}</div>`, "text/html");
2241
- doc.body.querySelectorAll("style,script").forEach((n) => n.remove());
2242
- doc.body.innerHTML = doc.body.innerHTML.replace(/<\/(p|div|h[1-6]|li|blockquote|pre|tr)>/gi, "\n");
2243
- return doc.body.textContent.replace(/\u00a0/g, " ").replace(/\n{3,}/g, "\n\n").trim();
2244
- }
2245
2831
  class Commands {
2246
2832
  constructor(editor) {
2247
2833
  this.editor = editor;
@@ -3396,6 +3982,8 @@ const defaults = {
3396
3982
  primaryColor: "#07c160",
3397
3983
  paperWidth: 677,
3398
3984
  toolbar: DEFAULT_TOOLBAR,
3985
+ /** 自定义工具栏按钮(下拉选择,数据可静态配置或从接口读取) */
3986
+ customButtons: [],
3399
3987
  hideToolbar: false,
3400
3988
  hideStatusbar: false,
3401
3989
  readOnly: false,
@@ -3430,6 +4018,7 @@ class KEditor {
3430
4018
  this.options = mergeOptions(options);
3431
4019
  this.id = `ke-${instanceSeq += 1}`;
3432
4020
  this.el = resolveTarget(target, this.id);
4021
+ this.el.__keditor__ = this;
3433
4022
  const hostHTML = this.el.innerHTML;
3434
4023
  this.emitters = /* @__PURE__ */ new Map();
3435
4024
  this.domListeners = [];
@@ -3445,7 +4034,7 @@ class KEditor {
3445
4034
  this.uploader = createUploader(this.options.uploader, this.options.upload);
3446
4035
  this.media = createMedia(this);
3447
4036
  this.history = new History(this.root, { limit: this.options.historyLimit });
3448
- this.toolbar = new Toolbar(this, this.options.toolbar);
4037
+ this.toolbar = new Toolbar(this, this.options.toolbar, this.options.customButtons);
3449
4038
  this.source = new SourcePanel(this);
3450
4039
  this.previewPanel = new PreviewOverlay(this);
3451
4040
  this.bubble = new MediaBubble(this);
@@ -3753,8 +4342,8 @@ class KEditor {
3753
4342
  const sel = window.getSelection();
3754
4343
  if (!sel || sel.rangeCount === 0 || !this.root.contains(sel.anchorNode)) {
3755
4344
  const range = document.createRange();
3756
- const first = this.root.firstElementChild || this.root;
3757
- range.selectNodeContents(first);
4345
+ const first2 = this.root.firstElementChild || this.root;
4346
+ range.selectNodeContents(first2);
3758
4347
  range.collapse(false);
3759
4348
  sel.removeAllRanges();
3760
4349
  sel.addRange(range);
@@ -3827,6 +4416,36 @@ class KEditor {
3827
4416
  this.media.cancelAll();
3828
4417
  return this;
3829
4418
  }
4419
+ /* ------------------------------ 自定义工具栏按钮 ------------------------------ */
4420
+ /** 运行时新增自定义按钮(下拉选择 / 普通按钮),返回按钮 DOM */
4421
+ addButton(spec, options) {
4422
+ return this.toolbar.addButton(spec, options);
4423
+ }
4424
+ /** 移除自定义按钮,并中断其未完成的接口请求 */
4425
+ removeButton(name) {
4426
+ return this.toolbar.removeButton(name);
4427
+ }
4428
+ /** 外部灌入下拉数据(接口在编辑器之外请求时使用),返回规范化后的列表 */
4429
+ setButtonOptions(name, items) {
4430
+ return this.toolbar.setButtonOptions(name, items);
4431
+ }
4432
+ /** 读取 / 设置下拉按钮当前选中项 */
4433
+ getButtonValue(name) {
4434
+ return this.toolbar.getButtonValue(name);
4435
+ }
4436
+ setButtonValue(name, value) {
4437
+ return this.toolbar.setButtonValue(name, value);
4438
+ }
4439
+ /** 统一错误上报:toast 提示 + emit('error') + options.onError */
4440
+ reportError(type, error) {
4441
+ var _a, _b, _c;
4442
+ const message = error && error.message ? error.message : String(error);
4443
+ const payload = { type, error: error instanceof Error ? error : new Error(message), message };
4444
+ (_a = this.toast) == null ? void 0 : _a.error(message);
4445
+ this.emit("error", payload);
4446
+ (_c = (_b = this.options).onError) == null ? void 0 : _c.call(_b, payload);
4447
+ return this;
4448
+ }
3830
4449
  /* ------------------------------ 面板 ------------------------------ */
3831
4450
  toggleSource() {
3832
4451
  if (this.sourceMode) this.exitSource();
@@ -3932,6 +4551,7 @@ class KEditor {
3932
4551
  this.scrollEl.removeEventListener("scroll", this.scrollHandler);
3933
4552
  window.removeEventListener("resize", this.scrollHandler);
3934
4553
  if (this.fullscreen) document.body.style.overflow = "";
4554
+ if (this.el.__keditor__ === this) this.el.__keditor__ = null;
3935
4555
  this.el.innerHTML = "";
3936
4556
  this.el.classList.remove("ke", "ke-is-fullscreen", "ke-is-readonly");
3937
4557
  this.el.removeAttribute("style");
@@ -3984,12 +4604,21 @@ function mergeOptions(options) {
3984
4604
  out.image = { ...defaults.image, ...options.image || {} };
3985
4605
  out.paste = { ...defaults.paste, ...options.paste || {} };
3986
4606
  out.upload = { ...defaults.upload, ...options.upload || {} };
4607
+ out.customButtons = normalizeCustomButtons(options.customButtons);
3987
4608
  if (Array.isArray(options.toolbar)) out.toolbar = options.toolbar;
3988
4609
  if (options.toolbar === false) out.toolbar = [];
3989
4610
  if (options.toolbar === true) out.toolbar = DEFAULT_TOOLBAR;
4611
+ if (out.customButtons.length && options.toolbar === void 0) {
4612
+ out.toolbar = appendCustomNames(DEFAULT_TOOLBAR, out.customButtons.map((spec) => spec.name));
4613
+ }
3990
4614
  out.height = clamp$1(out.height ?? 460, 0, 4e3);
3991
4615
  return out;
3992
4616
  }
4617
+ function appendCustomNames(items, names) {
4618
+ const at = items.indexOf(":tail");
4619
+ const insert = ["|", ...names];
4620
+ return at < 0 ? [...items, ...insert] : [...items.slice(0, at), ...insert, ...items.slice(at)];
4621
+ }
3993
4622
  function buildStatusbar(editor) {
3994
4623
  const chars = h("b", { text: "0" });
3995
4624
  const words = h("b", { text: "0" });
@@ -4081,7 +4710,7 @@ function previewHtml(html) {
4081
4710
  });
4082
4711
  return root.innerHTML;
4083
4712
  }
4084
- const version = "1.0.0";
4713
+ const version = "1.0.2";
4085
4714
  function create(target, options = {}) {
4086
4715
  return new KEditor(target, options);
4087
4716
  }
@@ -4109,6 +4738,8 @@ export {
4109
4738
  maybeCompress,
4110
4739
  mockAdapter,
4111
4740
  mount,
4741
+ normalizeCustomButtons,
4742
+ normalizeItems,
4112
4743
  replace,
4113
4744
  sanitizeHtml,
4114
4745
  simpleAdapter,