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