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