kyle-editor 0.0.0-stage → 1.0.1
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/LICENSE +21 -0
- package/README.md +137 -2
- package/dist/keditor-vue.cjs +120 -0
- package/dist/keditor-vue.es.js +118 -0
- package/dist/keditor-vue.umd.js +122 -0
- package/dist/keditor.cjs +4117 -0
- package/dist/keditor.es.js +4117 -0
- package/dist/keditor.umd.js +4121 -0
- package/package.json +75 -4
- package/types/index.d.ts +345 -0
- package/types/vue.d.ts +73 -0
|
@@ -0,0 +1,4121 @@
|
|
|
1
|
+
(function(global, factory) {
|
|
2
|
+
typeof exports === "object" && typeof module !== "undefined" ? factory(exports) : typeof define === "function" && define.amd ? define(["exports"], factory) : (global = typeof globalThis !== "undefined" ? globalThis : global || self, factory(global.KEditor = {}));
|
|
3
|
+
})(this, function(exports2) {
|
|
4
|
+
"use strict";
|
|
5
|
+
const CSS$1 = `
|
|
6
|
+
.ke, .ke * { box-sizing: border-box; }
|
|
7
|
+
.ke {
|
|
8
|
+
--ke-primary: #07c160;
|
|
9
|
+
--ke-primary-weak: #eafaf1;
|
|
10
|
+
--ke-text: #3f3f3f;
|
|
11
|
+
--ke-muted: #8a8f99;
|
|
12
|
+
--ke-line: #e6e8eb;
|
|
13
|
+
--ke-line-weak: #f0f1f3;
|
|
14
|
+
--ke-bg: #f6f7f9;
|
|
15
|
+
--ke-radius: 10px;
|
|
16
|
+
--ke-paper: 677px;
|
|
17
|
+
--ke-shadow: 0 1px 2px rgba(16, 24, 40, .04), 0 8px 24px rgba(16, 24, 40, .06);
|
|
18
|
+
font-family: -apple-system, BlinkMacSystemFont, 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', 'Helvetica Neue', Helvetica, Arial, sans-serif;
|
|
19
|
+
color: var(--ke-text);
|
|
20
|
+
background: var(--ke-bg);
|
|
21
|
+
position: relative;
|
|
22
|
+
border: 1px solid var(--ke-line);
|
|
23
|
+
border-radius: var(--ke-radius);
|
|
24
|
+
overflow: hidden;
|
|
25
|
+
display: flex;
|
|
26
|
+
flex-direction: column;
|
|
27
|
+
font-size: 14px;
|
|
28
|
+
-webkit-font-smoothing: antialiased;
|
|
29
|
+
}
|
|
30
|
+
.ke[hidden] { display: none; }
|
|
31
|
+
.ke-is-fullscreen { position: fixed; inset: 0; z-index: 9998; border-radius: 0; }
|
|
32
|
+
|
|
33
|
+
/* ---------------- Toolbar ---------------- */
|
|
34
|
+
.ke-tb {
|
|
35
|
+
position: sticky; top: 0; z-index: 5;
|
|
36
|
+
display: flex; align-items: center; gap: 2px; flex-wrap: nowrap;
|
|
37
|
+
padding: 6px 10px 5px;
|
|
38
|
+
background: #fff;
|
|
39
|
+
border-bottom: 1px solid var(--ke-line);
|
|
40
|
+
overflow-x: auto;
|
|
41
|
+
overflow-y: hidden;
|
|
42
|
+
overscroll-behavior-x: contain;
|
|
43
|
+
-webkit-overflow-scrolling: touch;
|
|
44
|
+
/* 滚动条常显:静止时也能一眼看出「还有更多工具」 */
|
|
45
|
+
scrollbar-width: thin;
|
|
46
|
+
scrollbar-color: rgba(16, 24, 40, .28) rgba(16, 24, 40, .05);
|
|
47
|
+
}
|
|
48
|
+
.ke-tb::-webkit-scrollbar { height: 7px; }
|
|
49
|
+
.ke-tb::-webkit-scrollbar-track { background: rgba(16, 24, 40, .06); border-radius: 4px; }
|
|
50
|
+
.ke-tb::-webkit-scrollbar-thumb { background: rgba(16, 24, 40, .34); border-radius: 4px; }
|
|
51
|
+
.ke-tb:hover::-webkit-scrollbar-thumb { background: rgba(16, 24, 40, .48); }
|
|
52
|
+
.ke-tb::-webkit-scrollbar-thumb:active { background: var(--ke-primary); }
|
|
53
|
+
.ke-tb-group { display: flex; align-items: center; gap: 2px; flex: none; }
|
|
54
|
+
.ke-tb-sep { width: 1px; height: 18px; background: var(--ke-line); margin: 0 6px; flex: none; }
|
|
55
|
+
.ke-tb-tail {
|
|
56
|
+
position: sticky; right: 0; margin-left: auto; display: flex; align-items: center; gap: 4px;
|
|
57
|
+
flex: none; padding: 0 2px 0 12px; background: #fff;
|
|
58
|
+
box-shadow: none; transition: box-shadow .2s;
|
|
59
|
+
}
|
|
60
|
+
/* 仅当右侧仍有被尾部遮住的工具时才显示,让阴影成为「可继续滑动」的信号 */
|
|
61
|
+
.ke.ke-tb-can-r .ke-tb-tail { box-shadow: -16px 0 14px -10px rgba(16, 24, 40, .55); }
|
|
62
|
+
/* 尾部左缘渐隐:明确表达「还有工具滑到这块底下」 */
|
|
63
|
+
.ke-tb-tail::before {
|
|
64
|
+
content: ''; position: absolute; top: 0; bottom: 0; right: 100%; width: 30px;
|
|
65
|
+
background: linear-gradient(to left, rgba(255, 255, 255, .99) 18%, rgba(255, 255, 255, 0));
|
|
66
|
+
opacity: 0; transition: opacity .2s; pointer-events: none;
|
|
67
|
+
}
|
|
68
|
+
.ke.ke-tb-can-r .ke-tb-tail::before { opacity: 1; }
|
|
69
|
+
/* 遮住工具栏右侧 padding 区域,避免滚动内容从尾部后面露出 */
|
|
70
|
+
.ke-tb-tail::after { content: ''; position: absolute; top: 0; bottom: 0; right: -16px; width: 18px; background: #fff; }
|
|
71
|
+
|
|
72
|
+
/* ------- 可滑动提示:左侧渐隐 + 拖拽手势 + 首次引导气泡 ------- */
|
|
73
|
+
/* 高度避开底部 7px 滚动条,否则会把滚动条左端涂白 */
|
|
74
|
+
.ke-tb-fades { position: absolute; left: 0; right: 0; top: 0; height: calc(var(--ke-tb-h, 44px) - 8px); z-index: 6; pointer-events: none; overflow: hidden; }
|
|
75
|
+
.ke-tb-fade { position: absolute; top: 0; bottom: 0; width: 34px; opacity: 0; transition: opacity .2s; }
|
|
76
|
+
.ke-tb-fade-l { left: 0; background: linear-gradient(to right, rgba(255, 255, 255, .99) 26%, rgba(255, 255, 255, 0)); }
|
|
77
|
+
.ke.ke-tb-can-l .ke-tb-fade-l { opacity: 1; }
|
|
78
|
+
@media (hover: hover) and (pointer: fine) {
|
|
79
|
+
.ke.ke-tb-scrollable .ke-tb { cursor: grab; }
|
|
80
|
+
.ke.ke-tb-dragging .ke-tb, .ke.ke-tb-dragging .ke-tb .ke-btn { cursor: grabbing; }
|
|
81
|
+
}
|
|
82
|
+
.ke.ke-tb-dragging { user-select: none; -webkit-user-select: none; }
|
|
83
|
+
.ke-tb-hint {
|
|
84
|
+
position: absolute; left: 50%; top: calc(var(--ke-tb-h, 44px) + 9px); z-index: 7;
|
|
85
|
+
transform: translateX(-50%);
|
|
86
|
+
display: inline-flex; align-items: center; gap: 7px;
|
|
87
|
+
padding: 7px 13px; border-radius: 999px;
|
|
88
|
+
background: rgba(31, 35, 41, .94); color: #fff;
|
|
89
|
+
font-size: 12.5px; line-height: 1; white-space: nowrap; letter-spacing: .2px;
|
|
90
|
+
box-shadow: 0 6px 20px rgba(16, 24, 40, .26);
|
|
91
|
+
pointer-events: none;
|
|
92
|
+
animation: ke-hint-in .3s cubic-bezier(.22, 1, .36, 1) both;
|
|
93
|
+
}
|
|
94
|
+
.ke-tb-hint::before {
|
|
95
|
+
content: ''; position: absolute; top: -5px; left: 50%; margin-left: -5px;
|
|
96
|
+
border: 5px solid transparent; border-top: 0; border-bottom-color: rgba(31, 35, 41, .94);
|
|
97
|
+
}
|
|
98
|
+
.ke-tb-hint-ico { display: flex; color: #7ee2a8; animation: ke-hint-slide 1.15s ease-in-out infinite; }
|
|
99
|
+
.ke-tb-hint-ico svg { width: 15px; height: 15px; display: block; }
|
|
100
|
+
.ke-tb-hint.ke-is-out { animation: ke-hint-out .24s ease-in both; }
|
|
101
|
+
@keyframes ke-hint-in {
|
|
102
|
+
from { opacity: 0; transform: translateX(-50%) translateY(-8px) scale(.96); }
|
|
103
|
+
to { opacity: 1; transform: translateX(-50%) translateY(0) scale(1); }
|
|
104
|
+
}
|
|
105
|
+
@keyframes ke-hint-out {
|
|
106
|
+
to { opacity: 0; transform: translateX(-50%) translateY(-8px) scale(.96); }
|
|
107
|
+
}
|
|
108
|
+
@keyframes ke-hint-slide {
|
|
109
|
+
0%, 100% { transform: translateX(-2.5px); }
|
|
110
|
+
50% { transform: translateX(2.5px); }
|
|
111
|
+
}
|
|
112
|
+
.ke-btn {
|
|
113
|
+
position: relative; flex: none;
|
|
114
|
+
height: 30px; min-width: 30px; padding: 0 6px;
|
|
115
|
+
display: inline-flex; align-items: center; justify-content: center; gap: 4px;
|
|
116
|
+
border: 0; border-radius: 6px; background: transparent; color: #4b5158;
|
|
117
|
+
cursor: pointer; font-size: 13px; line-height: 1; transition: background .15s, color .15s;
|
|
118
|
+
}
|
|
119
|
+
.ke-btn:hover { background: #f2f3f5; color: #1f2329; }
|
|
120
|
+
.ke-btn:active { background: #e9eaec; }
|
|
121
|
+
.ke-btn.ke-is-active { background: var(--ke-primary-weak); color: var(--ke-primary); }
|
|
122
|
+
.ke-btn.ke-is-open { background: #eef0f2; color: #1f2329; }
|
|
123
|
+
.ke-btn-label { padding: 0 6px 0 8px; gap: 2px; min-width: 56px; justify-content: flex-start; }
|
|
124
|
+
.ke-btn-text { font-size: 12.5px; letter-spacing: .2px; }
|
|
125
|
+
.ke-btn:disabled { opacity: .38; cursor: not-allowed; }
|
|
126
|
+
.ke-btn:focus-visible { outline: 2px solid var(--ke-primary); outline-offset: 1px; }
|
|
127
|
+
.ke-ico { width: 17px; height: 17px; display: block; }
|
|
128
|
+
.ke-glyph { font-size: 14px; font-weight: 600; }
|
|
129
|
+
.ke-glyph-i { font-style: italic; font-family: Georgia, 'Times New Roman', serif; }
|
|
130
|
+
.ke-glyph-u { text-decoration: underline; }
|
|
131
|
+
.ke-glyph-s { text-decoration: line-through; }
|
|
132
|
+
.ke-glyph-h { font-weight: 700; font-size: 13px; }
|
|
133
|
+
.ke-dot { position: absolute; left: 4px; right: 4px; bottom: 3px; height: 3px; border-radius: 2px; background: var(--ke-fore, #1f2329); }
|
|
134
|
+
.ke-dot-bg { left: 3px; right: 3px; bottom: 2.5px; height: 4px; border-radius: 2px; background: var(--ke-back, #f6c344); }
|
|
135
|
+
.ke-glyph-a { font-size: 15px; font-weight: 700; letter-spacing: 0; line-height: 1; margin-bottom: 3px; }
|
|
136
|
+
.ke-glyph-hl { position: relative; margin-bottom: 0; padding: 0 3px; }
|
|
137
|
+
.ke-glyph-hl::before { content: ''; position: absolute; left: 0; right: 0; bottom: 0; height: 11px; border-radius: 2px; background: var(--ke-back, #f6c344); }
|
|
138
|
+
.ke-glyph-hl > span { position: relative; z-index: 1; }
|
|
139
|
+
.ke-btn[data-k-pop] .ke-caret { width: 11px; height: 11px; opacity: .5; margin-left: -1px; }
|
|
140
|
+
.ke-select {
|
|
141
|
+
height: 30px; border: 1px solid transparent; border-radius: 6px; background: transparent;
|
|
142
|
+
color: #4b5158; font-size: 13px; padding: 0 4px; cursor: pointer; max-width: 92px;
|
|
143
|
+
}
|
|
144
|
+
.ke-select:hover { background: #f2f3f5; }
|
|
145
|
+
.ke-select:focus { outline: none; border-color: var(--ke-primary); }
|
|
146
|
+
|
|
147
|
+
/* ---------------- Popover ---------------- */
|
|
148
|
+
.ke-pop {
|
|
149
|
+
position: absolute; z-index: 40; min-width: 236px; padding: 0;
|
|
150
|
+
background: #fff; border: 1px solid rgba(31, 35, 41, .07); border-radius: 12px;
|
|
151
|
+
box-shadow: 0 2px 4px rgba(16, 24, 40, .04), 0 12px 32px rgba(16, 24, 40, .14);
|
|
152
|
+
font-size: 13px; color: var(--ke-text); overflow: hidden;
|
|
153
|
+
}
|
|
154
|
+
.ke-pop[hidden] { display: none; }
|
|
155
|
+
.ke-pop-in { animation: ke-pop-in .16s cubic-bezier(.22, 1, .36, 1); }
|
|
156
|
+
@keyframes ke-pop-in { from { opacity: 0; transform: translateY(-6px) scale(.985); } }
|
|
157
|
+
.ke-panel { padding: 12px 14px 14px; }
|
|
158
|
+
.ke-panel-wide { min-width: 268px; }
|
|
159
|
+
.ke-panel-head { display: flex; align-items: center; gap: 8px; margin: -12px -14px 12px; padding: 10px 14px; background: #f8f9fb; border-bottom: 1px solid var(--ke-line-weak); }
|
|
160
|
+
.ke-panel-title { font-size: 13px; font-weight: 600; color: #1f2329; }
|
|
161
|
+
.ke-panel-note { margin-left: auto; font-size: 12px; color: var(--ke-muted); }
|
|
162
|
+
.ke-panel-reset { margin-left: auto; height: 22px; padding: 0 8px; border: 1px solid var(--ke-line); border-radius: 11px; background: #fff; color: #6b7280; font-size: 12px; cursor: pointer; }
|
|
163
|
+
.ke-panel-reset:hover { border-color: var(--ke-primary); color: var(--ke-primary); }
|
|
164
|
+
.ke-panel-sect { margin: 10px 0 6px; font-size: 11px; color: #a2a8b3; letter-spacing: .3px; }
|
|
165
|
+
.ke-panel-sect:first-of-type { margin-top: 0; }
|
|
166
|
+
.ke-panel-divider { height: 1px; background: var(--ke-line-weak); margin: 12px -14px 10px; }
|
|
167
|
+
.ke-panel-hint { font-size: 11.5px; color: #a2a8b3; line-height: 1.5; }
|
|
168
|
+
.ke-panel-foot { display: flex; align-items: center; gap: 8px; margin-top: 10px; }
|
|
169
|
+
|
|
170
|
+
.ke-sw-grid { display: grid; grid-template-columns: repeat(8, 1fr); gap: 6px; }
|
|
171
|
+
.ke-sw {
|
|
172
|
+
position: relative; width: 100%; aspect-ratio: 1 / 1; min-width: 22px; padding: 0;
|
|
173
|
+
border: 1px solid rgba(0, 0, 0, .07); border-radius: 6px; cursor: pointer;
|
|
174
|
+
transition: transform .12s ease, box-shadow .12s ease;
|
|
175
|
+
}
|
|
176
|
+
.ke-sw:hover { transform: translateY(-1px) scale(1.08); box-shadow: 0 2px 6px rgba(16, 24, 40, .18); z-index: 1; }
|
|
177
|
+
.ke-sw.ke-is-active { box-shadow: 0 0 0 2px #fff, 0 0 0 3.5px var(--ke-primary); }
|
|
178
|
+
.ke-sw-check { position: absolute; inset: 0; display: flex; align-items: center; justify-content: center; pointer-events: none; }
|
|
179
|
+
.ke-sw-check .ke-ico { width: 13px; height: 13px; filter: drop-shadow(0 1px 1px rgba(0, 0, 0, .35)); }
|
|
180
|
+
.ke-sw-picker { width: 30px; height: 30px; padding: 0; border: 1px solid var(--ke-line); border-radius: 7px; background: #fff; cursor: pointer; flex: none; }
|
|
181
|
+
.ke-sw-picker::-webkit-color-swatch-wrapper { padding: 3px; }
|
|
182
|
+
.ke-sw-picker::-webkit-color-swatch { border: 0; border-radius: 4px; }
|
|
183
|
+
.ke-sw-hex { flex: 1; font-family: 'SFMono-Regular', Consolas, Menlo, monospace; text-transform: uppercase; }
|
|
184
|
+
|
|
185
|
+
.ke-hd-row {
|
|
186
|
+
display: flex; flex-direction: column; align-items: stretch; gap: 2px; width: 100%;
|
|
187
|
+
padding: 8px 10px; margin-bottom: 4px; border: 1px solid transparent; border-radius: 8px;
|
|
188
|
+
background: #fff; cursor: pointer; text-align: left; transition: background .14s, border-color .14s;
|
|
189
|
+
}
|
|
190
|
+
.ke-hd-row:last-child { margin-bottom: 0; }
|
|
191
|
+
.ke-hd-row:hover { background: #f7f8fa; }
|
|
192
|
+
.ke-hd-row.ke-is-active { border-color: var(--ke-primary); background: var(--ke-primary-weak); }
|
|
193
|
+
.ke-hd-sample { display: block; color: #1f2329; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; line-height: 1.35; }
|
|
194
|
+
.ke-hd-meta { display: flex; align-items: baseline; gap: 6px; font-size: 11.5px; color: #a2a8b3; }
|
|
195
|
+
.ke-hd-label { color: #6b7280; }
|
|
196
|
+
.ke-hd-row .s-body { font-size: 15px; }
|
|
197
|
+
.ke-hd-row .s-h1 { font-size: 21px; font-weight: 700; }
|
|
198
|
+
.ke-hd-row .s-h2 { font-size: 18px; font-weight: 700; }
|
|
199
|
+
.ke-hd-row .s-h3 { font-size: 16px; font-weight: 600; }
|
|
200
|
+
|
|
201
|
+
.ke-size-grid { display: grid; grid-template-columns: repeat(6, 1fr); gap: 6px; }
|
|
202
|
+
.ke-size-cell { height: 32px; border: 1px solid var(--ke-line); border-radius: 7px; background: #fff; color: #4b5158; cursor: pointer; }
|
|
203
|
+
.ke-size-cell:hover { border-color: var(--ke-primary); color: var(--ke-primary); background: var(--ke-primary-weak); }
|
|
204
|
+
.ke-size-cell.ke-is-active { border-color: var(--ke-primary); background: var(--ke-primary); color: #fff; }
|
|
205
|
+
|
|
206
|
+
.ke-tabs { display: flex; gap: 4px; margin: -12px -14px 12px; padding: 0 14px; background: #f8f9fb; border-bottom: 1px solid var(--ke-line-weak); }
|
|
207
|
+
.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
|
+
.ke-tab:hover { color: #1f2329; }
|
|
209
|
+
.ke-tab.ke-is-active { color: var(--ke-primary); border-bottom-color: var(--ke-primary); font-weight: 600; }
|
|
210
|
+
.ke-tab-body[hidden] { display: none; }
|
|
211
|
+
.ke-drop {
|
|
212
|
+
display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 6px;
|
|
213
|
+
padding: 20px 14px; border: 1.5px dashed #d6dade; border-radius: 10px; background: #fbfcfd;
|
|
214
|
+
color: var(--ke-muted); cursor: pointer; text-align: center; transition: border-color .14s, background .14s;
|
|
215
|
+
}
|
|
216
|
+
.ke-drop:hover, .ke-drop.ke-is-over { border-color: var(--ke-primary); background: var(--ke-primary-weak); }
|
|
217
|
+
.ke-drop-ico .ke-ico { width: 24px; height: 24px; color: var(--ke-primary); }
|
|
218
|
+
.ke-drop-title { font-size: 13px; color: #4b5158; }
|
|
219
|
+
.ke-drop-sub { font-size: 11.5px; color: #a2a8b3; }
|
|
220
|
+
.ke-field { display: flex; align-items: center; gap: 8px; margin-bottom: 8px; }
|
|
221
|
+
.ke-field-label { flex: none; width: 34px; font-size: 12px; color: var(--ke-muted); }
|
|
222
|
+
.ke-check { display: flex; align-items: center; gap: 6px; font-size: 12px; color: #4b5158; margin-bottom: 4px; }
|
|
223
|
+
.ke-link-status { min-height: 18px; font-size: 11.5px; color: #a2a8b3; }
|
|
224
|
+
.ke-link-status.ke-is-checking { color: #2f6fed; }
|
|
225
|
+
.ke-link-status.ke-is-ok { color: var(--ke-primary); }
|
|
226
|
+
.ke-link-status.ke-is-bad { color: #ed8936; }
|
|
227
|
+
|
|
228
|
+
.ke-input, .ke-textarea {
|
|
229
|
+
width: 100%; height: 32px; padding: 0 10px; border: 1px solid var(--ke-line); border-radius: 7px;
|
|
230
|
+
font-size: 13px; color: var(--ke-text); background: #fff; transition: border-color .14s, box-shadow .14s;
|
|
231
|
+
}
|
|
232
|
+
.ke-input:focus, .ke-textarea:focus { outline: none; border-color: var(--ke-primary); box-shadow: 0 0 0 3px rgba(7, 193, 96, .12); }
|
|
233
|
+
.ke-input.ke-is-invalid { border-color: #e53e3e; box-shadow: 0 0 0 3px rgba(229, 62, 62, .12); }
|
|
234
|
+
.ke-textarea { height: auto; padding: 8px 10px; resize: vertical; font-family: inherit; line-height: 1.6; }
|
|
235
|
+
.ke-btn-primary { height: 32px; padding: 0 16px; border-radius: 7px; background: var(--ke-primary); color: #fff; font-size: 13px; border: 0; cursor: pointer; flex: none; }
|
|
236
|
+
.ke-btn-primary:hover { background: #06b35a; }
|
|
237
|
+
.ke-btn-primary:disabled { opacity: .45; cursor: progress; }
|
|
238
|
+
.ke-btn-ghost { height: 32px; padding: 0 14px; border-radius: 7px; background: #fff; border: 1px solid var(--ke-line); color: #4b5158; font-size: 13px; cursor: pointer; flex: none; }
|
|
239
|
+
.ke-btn-ghost:hover { border-color: #cfd3d8; color: #1f2329; }
|
|
240
|
+
.ke-table-grid { display: grid; gap: 3px; }
|
|
241
|
+
.ke-table-cell { width: 18px; height: 18px; border: 1px solid #d6dade; border-radius: 3px; transition: background .1s; }
|
|
242
|
+
.ke-table-cell.ke-is-on { background: var(--ke-primary-weak); border-color: var(--ke-primary); }
|
|
243
|
+
|
|
244
|
+
/* ---------------- Paper / Content ---------------- */
|
|
245
|
+
.ke-main { flex: 1; min-height: 0; display: flex; flex-direction: column; position: relative; }
|
|
246
|
+
.ke-scroll { flex: 1; min-height: 0; overflow-y: auto; padding: 22px 18px 28px; background: var(--ke-bg); scrollbar-width: thin; }
|
|
247
|
+
.ke-paper {
|
|
248
|
+
width: min(100%, calc(var(--ke-paper) + 64px)); margin: 0 auto; background: #fff;
|
|
249
|
+
border-radius: 8px; box-shadow: var(--ke-shadow); padding: 32px;
|
|
250
|
+
min-height: var(--ke-min-height, 320px);
|
|
251
|
+
}
|
|
252
|
+
.ke-content { outline: none; font-size: 17px; line-height: 1.75; color: var(--ke-text); word-break: break-word; }
|
|
253
|
+
.ke-content:empty::before,
|
|
254
|
+
.ke-content[data-placeholder].ke-is-empty::before {
|
|
255
|
+
content: attr(data-placeholder); color: #b8bec7; pointer-events: none;
|
|
256
|
+
}
|
|
257
|
+
.ke-content > *:first-child { margin-top: 0; }
|
|
258
|
+
.ke-content p { margin: 0 0 16px; }
|
|
259
|
+
.ke-content h1, .ke-content h2, .ke-content h3, .ke-content h4, .ke-content h5, .ke-content h6 {
|
|
260
|
+
margin: 24px 0 12px; font-weight: 600; line-height: 1.4; color: #1f2329;
|
|
261
|
+
}
|
|
262
|
+
.ke-content h1 { font-size: 22px; } .ke-content h2 { font-size: 20px; } .ke-content h3 { font-size: 18px; }
|
|
263
|
+
.ke-content h4, .ke-content h5, .ke-content h6 { font-size: 17px; }
|
|
264
|
+
.ke-content ul, .ke-content ol { margin: 0 0 16px; padding-left: 26px; }
|
|
265
|
+
.ke-content li { margin: 4px 0; }
|
|
266
|
+
.ke-content blockquote {
|
|
267
|
+
margin: 0 0 16px; padding: 2px 16px; border-left: 3px solid var(--ke-primary);
|
|
268
|
+
background: #f8f9fa; color: #6b7280; border-radius: 0 4px 4px 0;
|
|
269
|
+
}
|
|
270
|
+
.ke-content a { color: #576b95; text-decoration: none; border-bottom: 1px solid rgba(87,107,149,.35); }
|
|
271
|
+
.ke-content hr { border: 0; border-top: 1px solid var(--ke-line); margin: 24px 0; }
|
|
272
|
+
.ke-content code { background: #f2f3f5; border-radius: 4px; padding: 2px 6px; font-size: 14px; font-family: 'SFMono-Regular', Consolas, Menlo, monospace; color: #c7254e; }
|
|
273
|
+
.ke-content pre {
|
|
274
|
+
background: #282c34; color: #e6e6e6; padding: 14px 16px; border-radius: 8px; overflow-x: auto;
|
|
275
|
+
font-size: 13px; line-height: 1.7; margin: 0 0 16px; font-family: 'SFMono-Regular', Consolas, Menlo, monospace;
|
|
276
|
+
}
|
|
277
|
+
.ke-content pre code { background: none; color: inherit; padding: 0; font-size: inherit; }
|
|
278
|
+
.ke-content img, .ke-content video { max-width: 100%; height: auto; display: block; }
|
|
279
|
+
.ke-content figure { margin: 0 0 16px; }
|
|
280
|
+
.ke-content figcaption { font-size: 13px; color: var(--ke-muted); text-align: center; margin-top: 6px; }
|
|
281
|
+
.ke-content table { border-collapse: collapse; width: 100%; margin: 0 0 16px; font-size: 15px; }
|
|
282
|
+
.ke-content th, .ke-content td { border: 1px solid #dfe2e6; padding: 8px 10px; min-width: 40px; }
|
|
283
|
+
.ke-content th { background: #f6f7f9; font-weight: 600; }
|
|
284
|
+
.ke-content section { margin: 0 0 16px; }
|
|
285
|
+
.ke-content .ke-is-selected-media { outline: 2px solid var(--ke-primary); outline-offset: 2px; border-radius: 4px; }
|
|
286
|
+
|
|
287
|
+
/* 上传中的媒体占位 */
|
|
288
|
+
.ke-media-box { position: relative; margin: 0 0 16px; }
|
|
289
|
+
.ke-media-holder {
|
|
290
|
+
border: 1px dashed #cdd3da; border-radius: 8px; background: #fafbfc; color: var(--ke-muted);
|
|
291
|
+
display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 8px;
|
|
292
|
+
min-height: 120px; padding: 16px; font-size: 13px; text-align: center;
|
|
293
|
+
}
|
|
294
|
+
.ke-media-holder img { max-width: 100%; max-height: 260px; border-radius: 6px; opacity: .9; }
|
|
295
|
+
.ke-media-name { max-width: 100%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
|
296
|
+
.ke-progress { width: 100%; height: 6px; border-radius: 3px; background: #eceef1; overflow: hidden; }
|
|
297
|
+
.ke-progress i { display: block; height: 100%; width: 0; background: var(--ke-primary); border-radius: 3px; transition: width .2s ease; }
|
|
298
|
+
.ke-media-meta { display: flex; align-items: center; gap: 10px; width: 100%; }
|
|
299
|
+
.ke-media-pct { color: var(--ke-primary); font-weight: 600; min-width: 40px; text-align: right; }
|
|
300
|
+
.ke-media-error { color: #e53e3e; }
|
|
301
|
+
.ke-media-retry { border: 1px solid var(--ke-line); background: #fff; border-radius: 6px; padding: 4px 12px; cursor: pointer; font-size: 12px; color: #4b5158; }
|
|
302
|
+
.ke-media-retry:hover { border-color: var(--ke-primary); color: var(--ke-primary); }
|
|
303
|
+
.ke-media-cancel { border: 0; background: transparent; color: var(--ke-muted); cursor: pointer; font-size: 12px; }
|
|
304
|
+
.ke-spinner { width: 18px; height: 18px; border: 2px solid #dfe3e8; border-top-color: var(--ke-primary); border-radius: 50%; animation: ke-spin .8s linear infinite; }
|
|
305
|
+
@keyframes ke-spin { to { transform: rotate(360deg); } }
|
|
306
|
+
|
|
307
|
+
/* 视频卡片 */
|
|
308
|
+
.ke-video-card {
|
|
309
|
+
position: relative; border: 1px solid var(--ke-line); border-radius: 10px; background: #0f1115;
|
|
310
|
+
color: #e6e8eb; padding: 12px 14px; margin: 0 0 16px; display: flex; align-items: center; gap: 12px;
|
|
311
|
+
}
|
|
312
|
+
.ke-video-card video { width: 100%; border-radius: 6px; display: block; }
|
|
313
|
+
.ke-video-card .ke-video-body { flex: 1; min-width: 0; }
|
|
314
|
+
.ke-video-head { display: flex; align-items: center; gap: 8px; font-size: 13px; }
|
|
315
|
+
.ke-video-size { color: var(--ke-muted); font-size: 12px; }
|
|
316
|
+
.ke-video-remove { border: 0; background: transparent; color: #9aa2ad; cursor: pointer; padding: 4px; border-radius: 6px; }
|
|
317
|
+
.ke-video-remove:hover { color: #e53e3e; background: rgba(255,255,255,.06); }
|
|
318
|
+
.ke-inline-video video { border-radius: 8px; }
|
|
319
|
+
|
|
320
|
+
/* ---------------- Status bar ---------------- */
|
|
321
|
+
.ke-status {
|
|
322
|
+
display: flex; align-items: center; gap: 12px; padding: 6px 12px;
|
|
323
|
+
background: #fff; border-top: 1px solid var(--ke-line); font-size: 12px; color: var(--ke-muted);
|
|
324
|
+
}
|
|
325
|
+
.ke-status b { color: var(--ke-primary); font-weight: 600; }
|
|
326
|
+
.ke-status-hint { margin-left: 8px; }
|
|
327
|
+
.ke-status-tail { margin-left: auto; display: flex; align-items: center; gap: 4px; }
|
|
328
|
+
.ke-chip { display: inline-flex; align-items: center; gap: 4px; height: 24px; padding: 0 8px; border-radius: 12px; background: #f2f3f5; color: #4b5158; font-size: 12px; }
|
|
329
|
+
.ke-chip[hidden] { display: none; }
|
|
330
|
+
.ke-chip.ke-is-busy { background: var(--ke-primary-weak); color: var(--ke-primary); }
|
|
331
|
+
|
|
332
|
+
/* ---------------- Source mode ---------------- */
|
|
333
|
+
.ke-source { display: flex; flex-direction: column; flex: 1; min-height: 0; background: #1b1f27; }
|
|
334
|
+
.ke-source[hidden] { display: none; }
|
|
335
|
+
.ke-source-bar { display: flex; align-items: center; gap: 8px; padding: 8px 12px; background: #232833; color: #aeb6c2; font-size: 12px; }
|
|
336
|
+
.ke-source-title { font-weight: 600; color: #dfe4ea; }
|
|
337
|
+
.ke-source-bar .ke-btn { color: #aeb6c2; }
|
|
338
|
+
.ke-source-bar .ke-btn:hover { background: rgba(255,255,255,.08); color: #fff; }
|
|
339
|
+
.ke-source-tail { margin-left: auto; display: flex; gap: 8px; align-items: center; }
|
|
340
|
+
.ke-source-code {
|
|
341
|
+
flex: 1; min-height: 240px; margin: 0; padding: 16px 18px; overflow: auto;
|
|
342
|
+
color: #e6edf3; background: #1b1f27; font-size: 12.5px; line-height: 1.7; tab-size: 2;
|
|
343
|
+
font-family: 'SFMono-Regular', Consolas, Menlo, Monaco, monospace; white-space: pre-wrap;
|
|
344
|
+
word-break: break-all; outline: none; caret-color: #4ade80;
|
|
345
|
+
}
|
|
346
|
+
.ke-source-code[data-k-tag] { }
|
|
347
|
+
.ke-source-tip { color: #7d8794; }
|
|
348
|
+
.ke-source-actions button { height: 28px; padding: 0 12px; border-radius: 6px; border: 1px solid #39424f; background: transparent; color: #cfd6de; font-size: 12px; cursor: pointer; }
|
|
349
|
+
.ke-source-actions button:hover { border-color: var(--ke-primary); color: #fff; }
|
|
350
|
+
.ke-source-actions .ke-apply { background: var(--ke-primary); border-color: var(--ke-primary); color: #fff; }
|
|
351
|
+
|
|
352
|
+
/* ---------------- Bubble (图片/视频工具条) ---------------- */
|
|
353
|
+
.ke-bubble {
|
|
354
|
+
position: absolute; z-index: 30; display: flex; align-items: center; gap: 2px; padding: 4px;
|
|
355
|
+
background: rgba(28, 32, 38, .94); border-radius: 8px; box-shadow: 0 6px 20px rgba(0,0,0,.22);
|
|
356
|
+
color: #fff; transform: translate(-50%, -100%); white-space: nowrap;
|
|
357
|
+
}
|
|
358
|
+
.ke-bubble.ke-is-below { transform: translate(-50%, 0); }
|
|
359
|
+
.ke-bubble[hidden] { display: none; }
|
|
360
|
+
.ke-bubble button { height: 28px; min-width: 28px; padding: 0 8px; border: 0; border-radius: 6px; background: transparent; color: #e6e8eb; cursor: pointer; font-size: 12px; display: inline-flex; align-items: center; gap: 4px; }
|
|
361
|
+
.ke-bubble button:hover { background: rgba(255,255,255,.14); }
|
|
362
|
+
.ke-bubble button.ke-is-active { background: var(--ke-primary); color: #fff; }
|
|
363
|
+
.ke-bubble .ke-sep { width: 1px; height: 16px; background: rgba(255,255,255,.18); margin: 0 3px; }
|
|
364
|
+
|
|
365
|
+
/* ---------------- 图片缩放把手(鼠标拖动调大小) ---------------- */
|
|
366
|
+
.ke-img-resize {
|
|
367
|
+
position: absolute; z-index: 31; width: 18px; height: 18px; border-radius: 5px;
|
|
368
|
+
background: #fff; border: 2px solid var(--ke-primary); color: var(--ke-primary);
|
|
369
|
+
cursor: nwse-resize; box-shadow: 0 1px 5px rgba(0,0,0,.25);
|
|
370
|
+
display: flex; align-items: center; justify-content: center;
|
|
371
|
+
touch-action: none; transition: transform .12s ease, background .12s ease, color .12s ease;
|
|
372
|
+
}
|
|
373
|
+
.ke-img-resize svg { width: 10px; height: 10px; display: block; }
|
|
374
|
+
.ke-img-resize:hover { transform: scale(1.12); background: var(--ke-primary); color: #fff; }
|
|
375
|
+
.ke-img-resize[hidden] { display: none; }
|
|
376
|
+
.ke-img-resize-tip {
|
|
377
|
+
position: absolute; z-index: 32; transform: translate(-50%, -100%);
|
|
378
|
+
background: rgba(28,32,38,.9); color: #fff; font-size: 12px; line-height: 1;
|
|
379
|
+
padding: 5px 8px; border-radius: 6px; pointer-events: none; white-space: nowrap;
|
|
380
|
+
}
|
|
381
|
+
.ke-img-resize-tip[hidden] { display: none; }
|
|
382
|
+
|
|
383
|
+
/* ---------------- Drop zone / Toast / Lightbox ---------------- */
|
|
384
|
+
.ke-dropzone {
|
|
385
|
+
position: absolute; inset: 0; z-index: 20; display: none; align-items: center; justify-content: center;
|
|
386
|
+
background: rgba(7, 193, 96, .08); backdrop-filter: blur(1px); border: 2px dashed var(--ke-primary);
|
|
387
|
+
border-radius: var(--ke-radius); color: var(--ke-primary); font-size: 15px; font-weight: 600; pointer-events: none;
|
|
388
|
+
}
|
|
389
|
+
.ke-is-dragover .ke-dropzone { display: flex; }
|
|
390
|
+
.ke-toasts { position: fixed; top: 24px; left: 50%; transform: translateX(-50%); z-index: 10000; display: flex; flex-direction: column; gap: 8px; align-items: center; }
|
|
391
|
+
.ke-toast {
|
|
392
|
+
padding: 8px 16px; border-radius: 8px; background: rgba(28,32,38,.92); color: #fff; font-size: 13px;
|
|
393
|
+
box-shadow: 0 6px 20px rgba(0,0,0,.18); animation: ke-in .18s ease;
|
|
394
|
+
}
|
|
395
|
+
.ke-toast.ke-is-error { background: rgba(229, 62, 62, .95); }
|
|
396
|
+
.ke-toast.ke-is-warn { background: rgba(237, 137, 27, .95); }
|
|
397
|
+
@keyframes ke-in { from { opacity: 0; transform: translateY(-6px); } }
|
|
398
|
+
.ke-lightbox {
|
|
399
|
+
position: fixed; inset: 0; z-index: 10001; background: rgba(0,0,0,.86); display: flex;
|
|
400
|
+
align-items: center; justify-content: center; cursor: zoom-out; animation: ke-in .18s ease;
|
|
401
|
+
}
|
|
402
|
+
.ke-lightbox img { max-width: 92vw; max-height: 92vh; border-radius: 4px; }
|
|
403
|
+
.ke-lightbox-close { position: absolute; top: 18px; right: 22px; color: #fff; background: transparent; border: 0; cursor: pointer; }
|
|
404
|
+
|
|
405
|
+
/* ---------------- Preview overlay ---------------- */
|
|
406
|
+
.ke-preview { position: absolute; inset: 0; z-index: 25; background: #f2f3f5; display: flex; flex-direction: column; }
|
|
407
|
+
.ke-preview[hidden] { display: none; }
|
|
408
|
+
.ke-preview-bar { display: flex; align-items: center; gap: 8px; padding: 8px 12px; background: #fff; border-bottom: 1px solid var(--ke-line); font-size: 12px; color: var(--ke-muted); }
|
|
409
|
+
.ke-preview-body { flex: 1; overflow: auto; padding: 20px; }
|
|
410
|
+
.ke-preview-frame { margin: 0 auto; background: #fff; border-radius: 10px; box-shadow: var(--ke-shadow); padding: 22px 20px; transition: width .2s ease; }
|
|
411
|
+
.ke-preview-frame .ke-content { font-size: 17px; line-height: 1.75; color: var(--ke-text); }
|
|
412
|
+
.ke-preview-frame { min-height: 120px; }
|
|
413
|
+
|
|
414
|
+
/* ---------------- ReadOnly / disabled ---------------- */
|
|
415
|
+
.ke-is-readonly .ke-tb .ke-btn, .ke-is-readonly .ke-tb .ke-select { pointer-events: none; opacity: .45; }
|
|
416
|
+
.ke-is-readonly .ke-content { cursor: default; }
|
|
417
|
+
/* 源码模式下正文类按钮置灰,仅保留源码/预览/全屏 */
|
|
418
|
+
.ke-is-source .ke-tb .ke-btn:not([data-k-item="source"]):not([data-k-item="preview"]):not([data-k-item="fullscreen"]),
|
|
419
|
+
.ke-is-source .ke-tb .ke-btn-label { pointer-events: none; opacity: .35; }
|
|
420
|
+
.ke-is-source .ke-tb .ke-tb-sep { opacity: .4; }
|
|
421
|
+
.ke-btn[data-k-item="source"].ke-is-active { background: var(--ke-primary); color: #fff; }
|
|
422
|
+
.ke-btn[data-k-item="source"].ke-is-active:hover { background: #06b35a; }
|
|
423
|
+
|
|
424
|
+
/* ---------------- Mobile ---------------- */
|
|
425
|
+
@media (max-width: 640px) {
|
|
426
|
+
.ke-tb { padding: 4px 6px; gap: 0; }
|
|
427
|
+
.ke-btn, .ke-select { height: 28px; min-width: 28px; }
|
|
428
|
+
.ke-tb-sep { margin: 0 2px; }
|
|
429
|
+
.ke-scroll { padding: 12px 8px 18px; }
|
|
430
|
+
.ke-paper { padding: 16px 14px; border-radius: 6px; }
|
|
431
|
+
.ke-content { font-size: 16px; }
|
|
432
|
+
.ke-status { padding: 5px 8px; gap: 6px; }
|
|
433
|
+
.ke-status-hint { display: none; }
|
|
434
|
+
}
|
|
435
|
+
@media (prefers-reduced-motion: reduce) {
|
|
436
|
+
.ke * { animation-duration: .01ms !important; transition-duration: .01ms !important; }
|
|
437
|
+
}
|
|
438
|
+
`;
|
|
439
|
+
let injected = false;
|
|
440
|
+
function injectStyle() {
|
|
441
|
+
if (injected || typeof document === "undefined") return;
|
|
442
|
+
const style = document.createElement("style");
|
|
443
|
+
style.setAttribute("data-keditor-style", "");
|
|
444
|
+
style.textContent = CSS$1;
|
|
445
|
+
document.head.appendChild(style);
|
|
446
|
+
injected = true;
|
|
447
|
+
}
|
|
448
|
+
const uid = (prefix = "k") => `${prefix}${Date.now().toString(36)}${Math.random().toString(36).slice(2, 7)}`;
|
|
449
|
+
function debounce(fn, wait = 300) {
|
|
450
|
+
let timer = null;
|
|
451
|
+
const wrapped = (...args) => {
|
|
452
|
+
clearTimeout(timer);
|
|
453
|
+
timer = setTimeout(() => fn(...args), wait);
|
|
454
|
+
};
|
|
455
|
+
wrapped.cancel = () => clearTimeout(timer);
|
|
456
|
+
wrapped.flush = (...args) => {
|
|
457
|
+
clearTimeout(timer);
|
|
458
|
+
fn(...args);
|
|
459
|
+
};
|
|
460
|
+
return wrapped;
|
|
461
|
+
}
|
|
462
|
+
const clamp$1 = (num, min, max) => Math.min(Math.max(num, min), max);
|
|
463
|
+
function formatSize(bytes) {
|
|
464
|
+
if (!bytes && bytes !== 0) return "-";
|
|
465
|
+
const units = ["B", "KB", "MB", "GB"];
|
|
466
|
+
let i = 0;
|
|
467
|
+
let value = bytes;
|
|
468
|
+
while (value >= 1024 && i < units.length - 1) {
|
|
469
|
+
value /= 1024;
|
|
470
|
+
i += 1;
|
|
471
|
+
}
|
|
472
|
+
return `${value.toFixed(value >= 10 || i === 0 ? 0 : 1)}${units[i]}`;
|
|
473
|
+
}
|
|
474
|
+
function h(spec, attrs = {}, children = []) {
|
|
475
|
+
let tag = "div";
|
|
476
|
+
let className = "";
|
|
477
|
+
const parts = String(spec).split(".");
|
|
478
|
+
tag = parts[0] || "div";
|
|
479
|
+
className = parts.slice(1).join(" ");
|
|
480
|
+
const node = document.createElement(tag);
|
|
481
|
+
if (className) node.className = className;
|
|
482
|
+
for (const [key, val] of Object.entries(attrs || {})) {
|
|
483
|
+
if (val === void 0 || val === null || val === false) continue;
|
|
484
|
+
if (key === "class") node.className = `${node.className} ${val}`.trim();
|
|
485
|
+
else if (key === "style" && typeof val === "object") Object.assign(node.style, val);
|
|
486
|
+
else if (key === "html") node.innerHTML = val;
|
|
487
|
+
else if (key === "text") node.textContent = val;
|
|
488
|
+
else if (key === "dataset") Object.assign(node.dataset, val);
|
|
489
|
+
else if (key.startsWith("on") && typeof val === "function") node.addEventListener(key.slice(2).toLowerCase(), val);
|
|
490
|
+
else node.setAttribute(key, val === true ? "" : String(val));
|
|
491
|
+
}
|
|
492
|
+
const list = Array.isArray(children) ? children : [children];
|
|
493
|
+
for (const child of list) {
|
|
494
|
+
if (child === null || child === void 0 || child === false) continue;
|
|
495
|
+
node.appendChild(typeof child === "string" || typeof child === "number" ? document.createTextNode(String(child)) : child);
|
|
496
|
+
}
|
|
497
|
+
return node;
|
|
498
|
+
}
|
|
499
|
+
function getMediaAlign(img) {
|
|
500
|
+
if (!img) return "left";
|
|
501
|
+
const ml = img.style.marginLeft;
|
|
502
|
+
const mr = img.style.marginRight;
|
|
503
|
+
if (ml === "auto" && mr === "auto") return "center";
|
|
504
|
+
if (ml === "auto") return "right";
|
|
505
|
+
return "left";
|
|
506
|
+
}
|
|
507
|
+
function setMediaAlign(img, align) {
|
|
508
|
+
if (!img) return;
|
|
509
|
+
img.style.maxWidth = "100%";
|
|
510
|
+
if (align === "center") {
|
|
511
|
+
img.style.marginLeft = "auto";
|
|
512
|
+
img.style.marginRight = "auto";
|
|
513
|
+
} else if (align === "right") {
|
|
514
|
+
img.style.marginLeft = "auto";
|
|
515
|
+
img.style.marginRight = "0";
|
|
516
|
+
} else {
|
|
517
|
+
img.style.marginLeft = "0";
|
|
518
|
+
img.style.marginRight = "auto";
|
|
519
|
+
}
|
|
520
|
+
}
|
|
521
|
+
const S = (d) => `<svg class="ke-ico" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><path d="${d}"/></svg>`;
|
|
522
|
+
const icons = {
|
|
523
|
+
undo: `<svg class="ke-ico" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><path d="M9 14 4 9l5-5"/><path d="M4 9h10a5 5 0 0 1 0 10h-3"/></svg>`,
|
|
524
|
+
redo: `<svg class="ke-ico" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><path d="m15 14 5-5-5-5"/><path d="M20 9H10a5 5 0 0 0 0 10h3"/></svg>`,
|
|
525
|
+
bold: `<svg class="ke-ico" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M7 5h6.5a3.5 3.5 0 0 1 0 7H7zM7 12h7.5a3.5 3.5 0 0 1 0 7H7z"/></svg>`,
|
|
526
|
+
italic: `<svg class="ke-ico" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round"><path d="M15 5h-5M14 19H9M14.5 5 10 19"/></svg>`,
|
|
527
|
+
underline: `<svg class="ke-ico" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round"><path d="M7 4v8a5 5 0 0 0 10 0V4M5 20h14"/></svg>`,
|
|
528
|
+
strike: `<svg class="ke-ico" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round"><path d="M4 12h16M16.5 7A4.5 4.5 0 0 0 12 5c-2.2 0-3.6 1-4.2 2.4M7.5 17A4.5 4.5 0 0 0 12 19c2.3 0 3.9-1.1 4.4-2.8"/></svg>`,
|
|
529
|
+
foreColor: `<svg class="ke-ico" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><path d="M5 17 9.5 5 14 17M6.8 13h5.9"/><rect x="4" y="19.5" width="11" height="2.2" rx="1" fill="currentColor" stroke="none"/></svg>`,
|
|
530
|
+
backColor: `<svg class="ke-ico" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><path d="M8 20 4 16l7.5-7.5a2 2 0 0 1 2.8 0l3.2 3.2a2 2 0 0 1 0 2.8L13 20z" /><path d="M10 8.5 15.5 14"/></svg>`,
|
|
531
|
+
alignLeft: S("M4 6h16M4 12h10M4 18h13"),
|
|
532
|
+
alignCenter: S("M4 6h16M7 12h10M5.5 18h13"),
|
|
533
|
+
alignRight: S("M4 6h16M10 12h10M7 18h13"),
|
|
534
|
+
alignJustify: S("M4 6h16M4 12h16M4 18h16"),
|
|
535
|
+
ul: `<svg class="ke-ico" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round"><path d="M8 6h12M8 12h12M8 18h12"/><circle cx="4.5" cy="6" r="1.2" fill="currentColor" stroke="none"/><circle cx="4.5" cy="12" r="1.2" fill="currentColor" stroke="none"/><circle cx="4.5" cy="18" r="1.2" fill="currentColor" stroke="none"/></svg>`,
|
|
536
|
+
ol: `<svg class="ke-ico" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round"><path d="M9 6h11M9 12h11M9 18h11"/><text x="1.6" y="8.2" font-size="7" font-family="inherit" fill="currentColor" stroke="none">1</text><text x="1.6" y="14.4" font-size="7" font-family="inherit" fill="currentColor" stroke="none">2</text><text x="1.6" y="20.6" font-size="7" font-family="inherit" fill="currentColor" stroke="none">3</text></svg>`,
|
|
537
|
+
quote: `<svg class="ke-ico" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round"><path d="M5 5v14"/><path d="M10 8h9M10 12h9M10 16h5"/></svg>`,
|
|
538
|
+
link: `<svg class="ke-ico" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"/><path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"/></svg>`,
|
|
539
|
+
unlink: `<svg class="ke-ico" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round"><path d="M9 14 4.5 18.5M14.5 5.5 19 10"/><path d="M10.5 13.5a4 4 0 0 0 5.6 0l2.4-2.4a4 4 0 0 0-5.6-5.6"/><path d="M13.5 10.5a4 4 0 0 0-5.6 0l-2.4 2.4a4 4 0 0 0 5.6 5.6"/><path d="m3 3 18 18"/></svg>`,
|
|
540
|
+
image: `<svg class="ke-ico" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="4.5" width="18" height="15" rx="2.5"/><circle cx="8.5" cy="10" r="1.6"/><path d="m4 18 5-5 3.5 3.5L17 12l3 3"/></svg>`,
|
|
541
|
+
video: `<svg class="ke-ico" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="5" width="18" height="14" rx="2.5"/><path d="m10.5 9 4.5 3-4.5 3z"/></svg>`,
|
|
542
|
+
table: `<svg class="ke-ico" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="5" width="18" height="14" rx="2"/><path d="M3 10h18M3 15h18M9 5v14M15 5v14"/></svg>`,
|
|
543
|
+
code: S("m9 7-5 5 5 5M15 7l5 5-5 5"),
|
|
544
|
+
hr: `<svg class="ke-ico" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round"><path d="M4 12h16" stroke-width="2.4"/><path d="M6 7h12M6 17h12" opacity=".45"/></svg>`,
|
|
545
|
+
clear: `<svg class="ke-ico" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><path d="M8 20 4 16l8-8 4 4-8 8z" /><path d="M12 8 16 4l4 4-4 4M6 20h12"/></svg>`,
|
|
546
|
+
source: S("m8 7-5 5 5 5M16 7l5 5-5 5M13.5 4l-3 16"),
|
|
547
|
+
preview: `<svg class="ke-ico" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><path d="M2.5 12S6 5.5 12 5.5 21.5 12 21.5 12 18 18.5 12 18.5 2.5 12 2.5 12Z"/><circle cx="12" cy="12" r="3"/></svg>`,
|
|
548
|
+
trash: `<svg class="ke-ico" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><path d="M4 7h16M9.5 7V4.5h5V7M6.5 7l1 13h9l1-13"/></svg>`,
|
|
549
|
+
close: S("m6 6 12 12M18 6 6 18"),
|
|
550
|
+
copy: `<svg class="ke-ico" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><rect x="9" y="9" width="11" height="11" rx="2"/><path d="M15 5H6a2 2 0 0 0-2 2v9"/></svg>`,
|
|
551
|
+
format: S("M4 6h10M4 12h16M4 18h7M18 4v6m0 0 2.5-2.5M18 10l-2.5-2.5"),
|
|
552
|
+
check: S("m5 13 4 4L19 7"),
|
|
553
|
+
checkLight: `<svg class="ke-ico" viewBox="0 0 24 24" fill="none" stroke="#fff" stroke-width="2.6" stroke-linecap="round" stroke-linejoin="round"><path d="m5 13 4 4L19 7"/></svg>`,
|
|
554
|
+
plus: S("M12 5v14M5 12h14"),
|
|
555
|
+
minus: S("M5 12h14"),
|
|
556
|
+
upload: `<svg class="ke-ico" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><path d="M12 16V4m0 0-4 4m4-4 4 4"/><path d="M4 15v3a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-3"/></svg>`,
|
|
557
|
+
retry: `<svg class="ke-ico" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><path d="M20 12a8 8 0 1 1-3-6.2"/><path d="M20 4v5h-5"/></svg>`,
|
|
558
|
+
rounded: `<svg class="ke-ico" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><rect x="4" y="4" width="16" height="16" rx="6"/></svg>`,
|
|
559
|
+
expand: `<svg class="ke-ico" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><path d="M4 9V4h5M20 9V4h-5M4 15v5h5M20 15v5h-5"/></svg>`,
|
|
560
|
+
compress: `<svg class="ke-ico" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><path d="M9 4v5H4M15 4v5h5M9 20v-5H4M15 20v-5h5"/></svg>`
|
|
561
|
+
};
|
|
562
|
+
function icon(name) {
|
|
563
|
+
return icons[name] || "";
|
|
564
|
+
}
|
|
565
|
+
const THEME_COLORS = [
|
|
566
|
+
["#07c160", "微信绿"],
|
|
567
|
+
["#2f6fed", "科技蓝"],
|
|
568
|
+
["#7c3aed", "极光紫"],
|
|
569
|
+
["#d53880", "品红"],
|
|
570
|
+
["#e53e3e", "中国红"],
|
|
571
|
+
["#ed8936", "暮橙"],
|
|
572
|
+
["#f6c344", "明黄"],
|
|
573
|
+
["#0f766e", "松石绿"]
|
|
574
|
+
];
|
|
575
|
+
const STANDARD_COLORS = [
|
|
576
|
+
["#1f2329", "墨黑"],
|
|
577
|
+
["#6b7280", "深灰"],
|
|
578
|
+
["#b8bec7", "浅灰"],
|
|
579
|
+
["#f2f3f5", "云灰"],
|
|
580
|
+
["#ffffff", "纯白"],
|
|
581
|
+
["#c00000", "深红"],
|
|
582
|
+
["#ff0000", "正红"],
|
|
583
|
+
["#ffc000", "琥珀"],
|
|
584
|
+
["#ffff00", "柠黄"],
|
|
585
|
+
["#00b050", "草绿"],
|
|
586
|
+
["#00b0f0", "天蓝"],
|
|
587
|
+
["#0070c0", "海蓝"],
|
|
588
|
+
["#7030a0", "葡萄紫"],
|
|
589
|
+
["#ff69b4", "桃花粉"]
|
|
590
|
+
];
|
|
591
|
+
const BG_COLORS = [
|
|
592
|
+
["#fef08a", "柠檬底"],
|
|
593
|
+
["#dcfce7", "薄荷底"],
|
|
594
|
+
["#e0f2fe", "天空底"],
|
|
595
|
+
["#ede9fe", "薰衣底"],
|
|
596
|
+
["#ffe4e6", "樱花底"],
|
|
597
|
+
["#fff4e6", "奶茶底"],
|
|
598
|
+
["#f2f3f5", "纸张灰"],
|
|
599
|
+
["#1f2329", "夜墨"]
|
|
600
|
+
];
|
|
601
|
+
const HEX = /^#([0-9a-f]{3}|[0-9a-f]{6})$/i;
|
|
602
|
+
class Popover {
|
|
603
|
+
constructor(root) {
|
|
604
|
+
this.root = root;
|
|
605
|
+
this.el = h("div.ke-pop", { hidden: true });
|
|
606
|
+
this.anchor = null;
|
|
607
|
+
this.onClose = null;
|
|
608
|
+
root.appendChild(this.el);
|
|
609
|
+
this.el.addEventListener("mousedown", (event) => {
|
|
610
|
+
if (!/^(input|textarea|select)$/i.test(event.target.tagName)) event.preventDefault();
|
|
611
|
+
});
|
|
612
|
+
this.docHandler = (event) => {
|
|
613
|
+
var _a, _b;
|
|
614
|
+
if (this.el.hidden) return;
|
|
615
|
+
if (this.el.contains(event.target)) return;
|
|
616
|
+
if ((_b = (_a = event.target).closest) == null ? void 0 : _b.call(_a, ".ke-btn[data-k-pop]")) return;
|
|
617
|
+
this.close();
|
|
618
|
+
};
|
|
619
|
+
document.addEventListener("mousedown", this.docHandler, true);
|
|
620
|
+
this.keyHandler = (event) => {
|
|
621
|
+
if (event.key === "Escape") this.close();
|
|
622
|
+
};
|
|
623
|
+
document.addEventListener("keydown", this.keyHandler);
|
|
624
|
+
}
|
|
625
|
+
open(anchor, build, { align = "start", onClose } = {}) {
|
|
626
|
+
var _a;
|
|
627
|
+
this.el.textContent = "";
|
|
628
|
+
const content = build((node) => this.el.appendChild(node));
|
|
629
|
+
if (content) this.el.appendChild(content);
|
|
630
|
+
this.el.hidden = false;
|
|
631
|
+
this.anchor = anchor;
|
|
632
|
+
this.onClose = onClose;
|
|
633
|
+
const rootBox = this.root.getBoundingClientRect();
|
|
634
|
+
const box = anchor.getBoundingClientRect();
|
|
635
|
+
const popBox = this.el.getBoundingClientRect();
|
|
636
|
+
let left = box.left - rootBox.left;
|
|
637
|
+
if (align === "center") left = box.left - rootBox.left + box.width / 2 - popBox.width / 2;
|
|
638
|
+
if (align === "end") left = box.right - rootBox.left - popBox.width;
|
|
639
|
+
left = Math.max(8, Math.min(left, rootBox.width - popBox.width - 8));
|
|
640
|
+
let top = box.top - rootBox.top + box.height + 8;
|
|
641
|
+
if (top + popBox.height > rootBox.height - 8 && box.top - rootBox.top - popBox.height - 8 > 0) {
|
|
642
|
+
top = box.top - rootBox.top - popBox.height - 8;
|
|
643
|
+
}
|
|
644
|
+
this.el.style.left = `${left}px`;
|
|
645
|
+
this.el.style.top = `${top}px`;
|
|
646
|
+
this.el.classList.remove("ke-pop-in");
|
|
647
|
+
void this.el.offsetWidth;
|
|
648
|
+
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);
|
|
651
|
+
}
|
|
652
|
+
close() {
|
|
653
|
+
if (this.el.hidden) return;
|
|
654
|
+
this.el.hidden = true;
|
|
655
|
+
this.el.classList.remove("ke-pop-in");
|
|
656
|
+
this.el.textContent = "";
|
|
657
|
+
this.anchor = null;
|
|
658
|
+
const cb = this.onClose;
|
|
659
|
+
this.onClose = null;
|
|
660
|
+
cb == null ? void 0 : cb();
|
|
661
|
+
}
|
|
662
|
+
get isOpen() {
|
|
663
|
+
return !this.el.hidden;
|
|
664
|
+
}
|
|
665
|
+
destroy() {
|
|
666
|
+
document.removeEventListener("mousedown", this.docHandler, true);
|
|
667
|
+
document.removeEventListener("keydown", this.keyHandler);
|
|
668
|
+
this.el.remove();
|
|
669
|
+
}
|
|
670
|
+
}
|
|
671
|
+
function panel(title, right) {
|
|
672
|
+
const head = h("div.ke-panel-head", {}, [h("span.ke-panel-title", { text: title })]);
|
|
673
|
+
if (right) head.appendChild(right);
|
|
674
|
+
const wrap = h("div.ke-panel", {}, [head]);
|
|
675
|
+
return wrap;
|
|
676
|
+
}
|
|
677
|
+
function section(label) {
|
|
678
|
+
return h("div.ke-panel-sect", { text: label });
|
|
679
|
+
}
|
|
680
|
+
function divider() {
|
|
681
|
+
return h("div.ke-panel-divider");
|
|
682
|
+
}
|
|
683
|
+
function colorPanel({ title, kind, colors, value, recents = [], onPick, onClear }) {
|
|
684
|
+
const isBg = kind === "bg";
|
|
685
|
+
const reset = h("button.ke-panel-reset", {
|
|
686
|
+
type: "button",
|
|
687
|
+
title: isBg ? "清除高亮" : "恢复默认文字色",
|
|
688
|
+
text: isBg ? "清除高亮" : "恢复默认",
|
|
689
|
+
onclick: () => onClear ? onClear() : onPick(null)
|
|
690
|
+
});
|
|
691
|
+
const wrap = panel(title, reset);
|
|
692
|
+
if (recents.length) {
|
|
693
|
+
wrap.appendChild(section("最近使用"));
|
|
694
|
+
wrap.appendChild(swatches(recents.slice(0, 8), value, onPick));
|
|
695
|
+
}
|
|
696
|
+
if (!isBg) {
|
|
697
|
+
wrap.appendChild(section("主题颜色"));
|
|
698
|
+
wrap.appendChild(swatches(THEME_COLORS, value, onPick));
|
|
699
|
+
wrap.appendChild(section("标准颜色"));
|
|
700
|
+
wrap.appendChild(swatches(STANDARD_COLORS, value, onPick));
|
|
701
|
+
} else {
|
|
702
|
+
wrap.appendChild(section("推荐底色"));
|
|
703
|
+
wrap.appendChild(swatches(BG_COLORS.map(([c, n]) => [c, n]), value, onPick));
|
|
704
|
+
wrap.appendChild(section("主题颜色"));
|
|
705
|
+
wrap.appendChild(swatches(THEME_COLORS, value, onPick));
|
|
706
|
+
}
|
|
707
|
+
wrap.appendChild(divider());
|
|
708
|
+
wrap.appendChild(customRow(value, onPick));
|
|
709
|
+
return wrap;
|
|
710
|
+
}
|
|
711
|
+
function swatches(list, value, onPick) {
|
|
712
|
+
const grid = h("div.ke-sw-grid");
|
|
713
|
+
list.forEach(([color, name]) => {
|
|
714
|
+
const btn2 = h("button.ke-sw", {
|
|
715
|
+
type: "button",
|
|
716
|
+
title: `${name} ${color}`,
|
|
717
|
+
"aria-label": name,
|
|
718
|
+
style: { background: color }
|
|
719
|
+
});
|
|
720
|
+
if (value && HEX.test(value) && color.toLowerCase() === String(value).toLowerCase()) {
|
|
721
|
+
btn2.classList.add("ke-is-active");
|
|
722
|
+
btn2.appendChild(h("span.ke-sw-check", { html: icon("checkLight") }));
|
|
723
|
+
}
|
|
724
|
+
btn2.addEventListener("click", () => onPick(color));
|
|
725
|
+
grid.appendChild(btn2);
|
|
726
|
+
});
|
|
727
|
+
return grid;
|
|
728
|
+
}
|
|
729
|
+
function customRow(value, onPick) {
|
|
730
|
+
const hex = HEX.test(value || "") ? value : "#07c160";
|
|
731
|
+
const picker = h("input.ke-sw-picker", { type: "color", value: hex, title: "自定义颜色" });
|
|
732
|
+
const input = h("input.ke-input.ke-sw-hex", { type: "text", value: hex, placeholder: "#000000", maxlength: 7 });
|
|
733
|
+
const apply = h("button.ke-btn-primary", { type: "button", text: "应用" });
|
|
734
|
+
const commit = () => {
|
|
735
|
+
const raw = input.value.trim();
|
|
736
|
+
const next = raw.startsWith("#") ? raw : `#${raw}`;
|
|
737
|
+
if (!HEX.test(next)) {
|
|
738
|
+
input.classList.add("ke-is-invalid");
|
|
739
|
+
return;
|
|
740
|
+
}
|
|
741
|
+
input.classList.remove("ke-is-invalid");
|
|
742
|
+
onPick(next);
|
|
743
|
+
};
|
|
744
|
+
picker.addEventListener("input", () => {
|
|
745
|
+
input.value = picker.value;
|
|
746
|
+
});
|
|
747
|
+
picker.addEventListener("change", commit);
|
|
748
|
+
apply.addEventListener("click", commit);
|
|
749
|
+
input.addEventListener("keydown", (event) => {
|
|
750
|
+
if (event.key === "Enter") {
|
|
751
|
+
event.preventDefault();
|
|
752
|
+
commit();
|
|
753
|
+
}
|
|
754
|
+
});
|
|
755
|
+
return h("div.ke-panel-foot", {}, [
|
|
756
|
+
picker,
|
|
757
|
+
input,
|
|
758
|
+
apply
|
|
759
|
+
]);
|
|
760
|
+
}
|
|
761
|
+
function headingPanel(items, { value, onPick }) {
|
|
762
|
+
const wrap = panel("段落样式");
|
|
763
|
+
wrap.classList.add("ke-panel-wide");
|
|
764
|
+
items.forEach((item) => {
|
|
765
|
+
const row = h("button.ke-hd-row", {
|
|
766
|
+
type: "button",
|
|
767
|
+
dataset: { kValue: item.value },
|
|
768
|
+
onclick: () => onPick(item.value)
|
|
769
|
+
}, [
|
|
770
|
+
h("span.ke-hd-sample", { class: item.sampleClass || "", text: item.sample || item.label }),
|
|
771
|
+
h("span.ke-hd-meta", {}, [
|
|
772
|
+
h("span.ke-hd-label", { text: item.label }),
|
|
773
|
+
h("span.ke-hd-desc", { text: item.desc })
|
|
774
|
+
])
|
|
775
|
+
]);
|
|
776
|
+
if (item.value === value) row.classList.add("ke-is-active");
|
|
777
|
+
wrap.appendChild(row);
|
|
778
|
+
});
|
|
779
|
+
return wrap;
|
|
780
|
+
}
|
|
781
|
+
function fontSizePanel(sizes, { value, onPick }) {
|
|
782
|
+
const wrap = panel("字号", h("span.ke-panel-note", { text: value ? `${value}px` : "默认 17px" }));
|
|
783
|
+
wrap.classList.add("ke-panel-wide");
|
|
784
|
+
const grid = h("div.ke-size-grid");
|
|
785
|
+
sizes.forEach((size) => {
|
|
786
|
+
const btn2 = h("button.ke-size-cell", { type: "button", text: String(size), onclick: () => onPick(size) });
|
|
787
|
+
btn2.style.fontSize = `${Math.min(20, 10 + size / 6)}px`;
|
|
788
|
+
if (Number(value) === size) btn2.classList.add("ke-is-active");
|
|
789
|
+
grid.appendChild(btn2);
|
|
790
|
+
});
|
|
791
|
+
wrap.appendChild(grid);
|
|
792
|
+
wrap.appendChild(divider());
|
|
793
|
+
wrap.appendChild(h("div.ke-panel-hint", { text: "仅作用于选中的文字;未选中时对新输入的文字生效" }));
|
|
794
|
+
return wrap;
|
|
795
|
+
}
|
|
796
|
+
({ text: THEME_COLORS.map((x) => x[0]), bg: BG_COLORS.map((x) => x[0]) });
|
|
797
|
+
function tablePanel(onPick, { cols = 10, rows = 8 } = {}) {
|
|
798
|
+
const wrap = panel("插入表格", h("span.ke-panel-note", { text: "最大 10×8" }));
|
|
799
|
+
const grid = h("div.ke-table-grid", { style: { gridTemplateColumns: `repeat(${cols}, 18px)` } });
|
|
800
|
+
const cells = [];
|
|
801
|
+
for (let r = 0; r < rows; r += 1) {
|
|
802
|
+
for (let c = 0; c < cols; c += 1) {
|
|
803
|
+
const cell = h("span.ke-table-cell");
|
|
804
|
+
cell.dataset.r = String(r);
|
|
805
|
+
cell.dataset.c = String(c);
|
|
806
|
+
cells.push(cell);
|
|
807
|
+
grid.appendChild(cell);
|
|
808
|
+
}
|
|
809
|
+
}
|
|
810
|
+
wrap.appendChild(grid);
|
|
811
|
+
const sizeText = h("div.ke-panel-hint", { text: "1 列 × 1 行" });
|
|
812
|
+
wrap.appendChild(sizeText);
|
|
813
|
+
const mark = (maxR, maxC) => {
|
|
814
|
+
cells.forEach((cell) => {
|
|
815
|
+
const on = Number(cell.dataset.r) <= maxR && Number(cell.dataset.c) <= maxC;
|
|
816
|
+
cell.classList.toggle("ke-is-on", on);
|
|
817
|
+
});
|
|
818
|
+
sizeText.textContent = `${maxC + 1} 列 × ${maxR + 1} 行`;
|
|
819
|
+
};
|
|
820
|
+
grid.addEventListener("mousemove", (event) => {
|
|
821
|
+
const cell = event.target.closest(".ke-table-cell");
|
|
822
|
+
if (cell) mark(Number(cell.dataset.r), Number(cell.dataset.c));
|
|
823
|
+
});
|
|
824
|
+
grid.addEventListener("click", (event) => {
|
|
825
|
+
const cell = event.target.closest(".ke-table-cell");
|
|
826
|
+
if (cell) onPick(Number(cell.dataset.c) + 1, Number(cell.dataset.r) + 1);
|
|
827
|
+
});
|
|
828
|
+
grid.addEventListener("mouseenter", () => mark(0, 0));
|
|
829
|
+
mark(0, 0);
|
|
830
|
+
return wrap;
|
|
831
|
+
}
|
|
832
|
+
function mediaPanel(kind, { onFiles, onUrl, multiple, hint, maxText }) {
|
|
833
|
+
const isImage = kind === "image";
|
|
834
|
+
const wrap = panel(isImage ? "插入图片" : "插入视频");
|
|
835
|
+
wrap.classList.add("ke-panel-wide", "ke-panel-media");
|
|
836
|
+
const local = h("div.ke-tab-body");
|
|
837
|
+
const net = h("div.ke-tab-body", { hidden: true });
|
|
838
|
+
const drop = h("div.ke-drop", {}, [
|
|
839
|
+
h("span.ke-drop-ico", { html: icon("upload") }),
|
|
840
|
+
h("div.ke-drop-title", { text: isImage ? "点击选择图片,或拖拽到此处" : "点击选择视频,或拖拽到此处" }),
|
|
841
|
+
h("div.ke-drop-sub", { text: [maxText, hint].filter(Boolean).join(" · ") })
|
|
842
|
+
]);
|
|
843
|
+
const pickBtn = h("button.ke-btn-primary", {
|
|
844
|
+
type: "button",
|
|
845
|
+
text: isImage ? "选择图片" : "选择视频",
|
|
846
|
+
onclick: () => onFiles(null)
|
|
847
|
+
});
|
|
848
|
+
drop.addEventListener("click", () => onFiles(null));
|
|
849
|
+
drop.addEventListener("dragover", (event) => {
|
|
850
|
+
event.preventDefault();
|
|
851
|
+
drop.classList.add("ke-is-over");
|
|
852
|
+
});
|
|
853
|
+
drop.addEventListener("dragleave", () => drop.classList.remove("ke-is-over"));
|
|
854
|
+
drop.addEventListener("drop", (event) => {
|
|
855
|
+
var _a, _b;
|
|
856
|
+
event.preventDefault();
|
|
857
|
+
drop.classList.remove("ke-is-over");
|
|
858
|
+
if ((_b = (_a = event.dataTransfer) == null ? void 0 : _a.files) == null ? void 0 : _b.length) onFiles(event.dataTransfer.files);
|
|
859
|
+
});
|
|
860
|
+
local.append(drop, h("div.ke-panel-foot", {}, [pickBtn, h("span.ke-panel-hint", { text: multiple ? "可一次插入多张" : "单文件大文件将自动分片上传" })]));
|
|
861
|
+
const urlInput = h("input.ke-input", {
|
|
862
|
+
type: "url",
|
|
863
|
+
placeholder: isImage ? "https://example.com/photo.jpg" : "https://example.com/video.mp4",
|
|
864
|
+
"data-k-autofocus": ""
|
|
865
|
+
});
|
|
866
|
+
const nameInput = h("input.ke-input", { type: "text", placeholder: isImage ? "图片描述(可选,作为 alt)" : "视频标题(可选)" });
|
|
867
|
+
const status = h("div.ke-link-status", { text: "粘贴链接后自动校验可访问性" });
|
|
868
|
+
const insertBtn = h("button.ke-btn-primary", { type: "button", text: "插入", disabled: true });
|
|
869
|
+
let timer = null;
|
|
870
|
+
let token = 0;
|
|
871
|
+
const check = () => {
|
|
872
|
+
token += 1;
|
|
873
|
+
const mine = token;
|
|
874
|
+
clearTimeout(timer);
|
|
875
|
+
const url = normalizeUrl(urlInput.value);
|
|
876
|
+
insertBtn.disabled = !url;
|
|
877
|
+
status.className = "ke-link-status";
|
|
878
|
+
if (!url) {
|
|
879
|
+
status.textContent = "请输入 http(s) 开头的链接";
|
|
880
|
+
return;
|
|
881
|
+
}
|
|
882
|
+
status.className = "ke-link-status ke-is-checking";
|
|
883
|
+
status.textContent = "正在校验…";
|
|
884
|
+
timer = setTimeout(() => probe(kind, url, (ok) => {
|
|
885
|
+
if (mine !== token) return;
|
|
886
|
+
if (ok) {
|
|
887
|
+
status.className = "ke-link-status ke-is-ok";
|
|
888
|
+
status.textContent = isImage ? "图片可访问 ✓" : "视频可播放 ✓";
|
|
889
|
+
} else {
|
|
890
|
+
status.className = "ke-link-status ke-is-bad";
|
|
891
|
+
status.textContent = "未能自动加载(可能限制热链),不阻塞插入,发布前请自行确认";
|
|
892
|
+
}
|
|
893
|
+
}), 350);
|
|
894
|
+
};
|
|
895
|
+
urlInput.addEventListener("input", check);
|
|
896
|
+
urlInput.addEventListener("paste", () => setTimeout(check, 0));
|
|
897
|
+
const submit = () => {
|
|
898
|
+
const url = normalizeUrl(urlInput.value);
|
|
899
|
+
if (!url) {
|
|
900
|
+
urlInput.classList.add("ke-is-invalid");
|
|
901
|
+
urlInput.focus();
|
|
902
|
+
return;
|
|
903
|
+
}
|
|
904
|
+
onUrl({ url, name: nameInput.value.trim() });
|
|
905
|
+
};
|
|
906
|
+
insertBtn.addEventListener("click", submit);
|
|
907
|
+
net.addEventListener("keydown", (event) => {
|
|
908
|
+
if (event.key === "Enter") {
|
|
909
|
+
event.preventDefault();
|
|
910
|
+
submit();
|
|
911
|
+
}
|
|
912
|
+
});
|
|
913
|
+
net.append(
|
|
914
|
+
h("div.ke-field", {}, [h("span.ke-field-label", { text: "地址" }), urlInput]),
|
|
915
|
+
h("div.ke-field", {}, [h("span.ke-field-label", { text: isImage ? "描述" : "标题" }), nameInput]),
|
|
916
|
+
status,
|
|
917
|
+
h("div.ke-panel-foot", {}, [insertBtn, h("span.ke-panel-hint", { text: "外链由源站提供,不占用上传配额" })])
|
|
918
|
+
);
|
|
919
|
+
const tabs = h("div.ke-tabs", {}, [
|
|
920
|
+
h("button.ke-tab", { type: "button", text: "本地上传" }),
|
|
921
|
+
h("button.ke-tab", { type: "button", text: "网络链接" })
|
|
922
|
+
]);
|
|
923
|
+
const show = (index) => {
|
|
924
|
+
[...tabs.children].forEach((tab, i) => tab.classList.toggle("ke-is-active", i === index));
|
|
925
|
+
local.hidden = index !== 0;
|
|
926
|
+
net.hidden = index !== 1;
|
|
927
|
+
if (index === 1) urlInput.focus();
|
|
928
|
+
};
|
|
929
|
+
tabs.children[0].addEventListener("click", () => show(0));
|
|
930
|
+
tabs.children[1].addEventListener("click", () => show(1));
|
|
931
|
+
show(0);
|
|
932
|
+
wrap.append(tabs, local, net);
|
|
933
|
+
return wrap;
|
|
934
|
+
}
|
|
935
|
+
function probe(kind, url, done) {
|
|
936
|
+
let settled = false;
|
|
937
|
+
const finish = (ok) => {
|
|
938
|
+
if (settled) return;
|
|
939
|
+
settled = true;
|
|
940
|
+
done(ok);
|
|
941
|
+
};
|
|
942
|
+
try {
|
|
943
|
+
if (kind === "image") {
|
|
944
|
+
const img = new Image();
|
|
945
|
+
img.onload = () => finish(true);
|
|
946
|
+
img.onerror = () => finish(false);
|
|
947
|
+
img.referrerPolicy = "no-referrer";
|
|
948
|
+
img.src = url;
|
|
949
|
+
} else {
|
|
950
|
+
const video = document.createElement("video");
|
|
951
|
+
video.preload = "metadata";
|
|
952
|
+
video.muted = true;
|
|
953
|
+
video.onloadedmetadata = () => finish(video.videoHeight > 0 || video.duration > 0 || Number.isFinite(video.duration));
|
|
954
|
+
video.onerror = () => finish(false);
|
|
955
|
+
video.src = url;
|
|
956
|
+
}
|
|
957
|
+
} catch {
|
|
958
|
+
finish(false);
|
|
959
|
+
}
|
|
960
|
+
}
|
|
961
|
+
function linkPanel({ url = "", text = "", target = false, onSubmit, onCancel, onRemove }) {
|
|
962
|
+
const urlInput = h("input.ke-input", { type: "url", placeholder: "https://mp.weixin.qq.com/...", value: url, "data-k-autofocus": "" });
|
|
963
|
+
const textInput = h("input.ke-input", { type: "text", placeholder: "链接文字(留空使用 URL)", value: text });
|
|
964
|
+
const check = h("input", { type: "checkbox" });
|
|
965
|
+
check.checked = !!target;
|
|
966
|
+
const wrap = panel(url ? "编辑链接" : "插入链接");
|
|
967
|
+
wrap.classList.add("ke-panel-wide");
|
|
968
|
+
const body = h("div", {}, [
|
|
969
|
+
h("div.ke-field", {}, [h("span.ke-field-label", { text: "文字" }), textInput]),
|
|
970
|
+
h("div.ke-field", {}, [h("span.ke-field-label", { text: "地址" }), urlInput]),
|
|
971
|
+
h("label.ke-check", {}, [check, "新窗口打开"]),
|
|
972
|
+
h("div.ke-panel-foot", {}, [
|
|
973
|
+
onRemove ? h("button.ke-btn-ghost", { type: "button", text: "移除链接", style: { marginRight: "auto", color: "#e53e3e" }, onclick: onRemove }) : null,
|
|
974
|
+
h("button.ke-btn-ghost", { type: "button", text: "取消", onclick: onCancel }),
|
|
975
|
+
h("button.ke-btn-primary", { type: "button", text: "确定", onclick: () => submit() })
|
|
976
|
+
])
|
|
977
|
+
]);
|
|
978
|
+
const submit = () => {
|
|
979
|
+
const href = normalizeUrl(urlInput.value);
|
|
980
|
+
if (!href) {
|
|
981
|
+
urlInput.classList.add("ke-is-invalid");
|
|
982
|
+
urlInput.focus();
|
|
983
|
+
return;
|
|
984
|
+
}
|
|
985
|
+
onSubmit({ url: href, text: textInput.value.trim(), target: check.checked });
|
|
986
|
+
};
|
|
987
|
+
body.addEventListener("keydown", (event) => {
|
|
988
|
+
if (event.key === "Enter") {
|
|
989
|
+
event.preventDefault();
|
|
990
|
+
submit();
|
|
991
|
+
}
|
|
992
|
+
});
|
|
993
|
+
wrap.appendChild(body);
|
|
994
|
+
return wrap;
|
|
995
|
+
}
|
|
996
|
+
function normalizeUrl(url) {
|
|
997
|
+
const value = String(url || "").trim();
|
|
998
|
+
if (!value) return "";
|
|
999
|
+
if (/^(https?:|mailto:|tel:|#|\/)/i.test(value)) return value;
|
|
1000
|
+
if (/^[\w-]+(\.[\w-]+)+/.test(value)) return `https://${value}`;
|
|
1001
|
+
return "";
|
|
1002
|
+
}
|
|
1003
|
+
const BLOCK_TAGS = /* @__PURE__ */ new Set(["p", "div", "section", "blockquote", "ul", "ol", "li", "table", "thead", "tbody", "tfoot", "tr", "td", "th", "figure", "figcaption", "pre", "h1", "h2", "h3", "h4", "h5", "h6", "hr", "video"]);
|
|
1004
|
+
function formatHtml(html, { indent = " " } = {}) {
|
|
1005
|
+
if (!html) return "";
|
|
1006
|
+
const doc = new DOMParser().parseFromString(`<div>${html}</div>`, "text/html");
|
|
1007
|
+
const root = doc.body.firstChild;
|
|
1008
|
+
const lines = [];
|
|
1009
|
+
const push = (depth, text) => {
|
|
1010
|
+
const value = text.replace(/\s+/g, " ").trim();
|
|
1011
|
+
if (!value) return;
|
|
1012
|
+
const last = lines[lines.length - 1];
|
|
1013
|
+
if (last && last.depth === depth && last.inlineRun) last.text += ` ${value}`;
|
|
1014
|
+
else lines.push({ depth, text: indent.repeat(depth) + value, inlineRun: true });
|
|
1015
|
+
};
|
|
1016
|
+
const walk2 = (parent, depth) => {
|
|
1017
|
+
const nodes = [...parent.childNodes];
|
|
1018
|
+
nodes.forEach((child) => {
|
|
1019
|
+
if (child.nodeType === 3) {
|
|
1020
|
+
const text = child.textContent.trim();
|
|
1021
|
+
if (text) push(depth, text);
|
|
1022
|
+
return;
|
|
1023
|
+
}
|
|
1024
|
+
if (child.nodeType !== 1) return;
|
|
1025
|
+
const tag = child.tagName.toLowerCase();
|
|
1026
|
+
if (!BLOCK_TAGS.has(tag)) {
|
|
1027
|
+
push(depth, child.outerHTML);
|
|
1028
|
+
return;
|
|
1029
|
+
}
|
|
1030
|
+
const hasBlockChild = [...child.querySelectorAll("*")].some((node) => BLOCK_TAGS.has(node.tagName.toLowerCase()));
|
|
1031
|
+
const keepOneLine = tag === "tr" || tag === "figure" || tag === "video";
|
|
1032
|
+
if (!hasBlockChild || keepOneLine) {
|
|
1033
|
+
lines.push({ depth, text: indent.repeat(depth) + collapse(child.outerHTML), inlineRun: false });
|
|
1034
|
+
return;
|
|
1035
|
+
}
|
|
1036
|
+
lines.push({ depth, text: indent.repeat(depth) + openTag(child), inlineRun: false });
|
|
1037
|
+
walk2(child, depth + 1);
|
|
1038
|
+
lines.push({ depth, text: indent.repeat(depth) + `</${tag}>`, inlineRun: false });
|
|
1039
|
+
});
|
|
1040
|
+
};
|
|
1041
|
+
walk2(root, 0);
|
|
1042
|
+
return lines.map((line) => line.text).join("\n").replace(/\n{3,}/g, "\n\n");
|
|
1043
|
+
}
|
|
1044
|
+
function collapse(markup) {
|
|
1045
|
+
return markup.replace(/\n\s+/g, " ").replace(/\s{2,}/g, " ").trim();
|
|
1046
|
+
}
|
|
1047
|
+
function openTag(element) {
|
|
1048
|
+
const attrs = [...element.attributes].map((attr) => `${attr.name}="${(attr.value || "").replace(/"/g, """)}"`);
|
|
1049
|
+
return `<${element.tagName.toLowerCase()}${attrs.length ? ` ${attrs.join(" ")}` : ""}>`;
|
|
1050
|
+
}
|
|
1051
|
+
class SourcePanel {
|
|
1052
|
+
constructor(editor) {
|
|
1053
|
+
this.editor = editor;
|
|
1054
|
+
this.open = false;
|
|
1055
|
+
this.el = h("div.ke-source", { hidden: true }, [
|
|
1056
|
+
h("div.ke-source-bar", {}, [
|
|
1057
|
+
h("span.ke-source-title", { text: "HTML 源码" }),
|
|
1058
|
+
h("span.ke-source-tip", { text: "可直接编辑,点击「应用」或退出源码模式即生效" }),
|
|
1059
|
+
h("span.ke-source-tail", {}, [
|
|
1060
|
+
h("button.ke-btn", { type: "button", title: "格式化", html: icon("format") + "<span>格式化</span>", onclick: () => this.format() }),
|
|
1061
|
+
h("button.ke-btn", { type: "button", title: "复制全部", html: icon("copy") + "<span>复制</span>", onclick: () => this.copy() }),
|
|
1062
|
+
h("button.ke-btn", { type: "button", title: "应用修改", html: icon("check") + "<span>应用</span>", onclick: () => this.apply() }),
|
|
1063
|
+
h("button.ke-btn", { type: "button", title: "退出源码模式", html: icon("close"), onclick: () => editor.exitSource() })
|
|
1064
|
+
])
|
|
1065
|
+
]),
|
|
1066
|
+
(() => {
|
|
1067
|
+
this.code = h("pre.ke-source-code", { contenteditable: "true", spellcheck: "false", autocapitalize: "off", autocomplete: "off", wrap: "off" });
|
|
1068
|
+
this.code.addEventListener("keydown", (event) => {
|
|
1069
|
+
if (event.key === "Tab") {
|
|
1070
|
+
event.preventDefault();
|
|
1071
|
+
document.execCommand("insertText", false, " ");
|
|
1072
|
+
}
|
|
1073
|
+
if ((event.ctrlKey || event.metaKey) && event.key.toLowerCase() === "s") {
|
|
1074
|
+
event.preventDefault();
|
|
1075
|
+
this.apply();
|
|
1076
|
+
}
|
|
1077
|
+
event.stopPropagation();
|
|
1078
|
+
});
|
|
1079
|
+
return this.code;
|
|
1080
|
+
})()
|
|
1081
|
+
]);
|
|
1082
|
+
}
|
|
1083
|
+
get value() {
|
|
1084
|
+
return this.code.textContent;
|
|
1085
|
+
}
|
|
1086
|
+
set value(text) {
|
|
1087
|
+
this.code.textContent = text;
|
|
1088
|
+
this.code.scrollTop = 0;
|
|
1089
|
+
}
|
|
1090
|
+
show(html) {
|
|
1091
|
+
this.value = formatHtml(html);
|
|
1092
|
+
this.el.hidden = false;
|
|
1093
|
+
this.open = true;
|
|
1094
|
+
this.editor.scrollEl.hidden = true;
|
|
1095
|
+
}
|
|
1096
|
+
hide() {
|
|
1097
|
+
this.el.hidden = true;
|
|
1098
|
+
this.open = false;
|
|
1099
|
+
this.editor.scrollEl.hidden = false;
|
|
1100
|
+
}
|
|
1101
|
+
format() {
|
|
1102
|
+
this.value = formatHtml(this.value);
|
|
1103
|
+
this.editor.toast.show("已格式化");
|
|
1104
|
+
}
|
|
1105
|
+
async copy() {
|
|
1106
|
+
var _a;
|
|
1107
|
+
const text = this.value;
|
|
1108
|
+
try {
|
|
1109
|
+
if ((_a = navigator.clipboard) == null ? void 0 : _a.writeText) await navigator.clipboard.writeText(text);
|
|
1110
|
+
else {
|
|
1111
|
+
this.code.focus();
|
|
1112
|
+
document.execCommand("selectAll");
|
|
1113
|
+
document.execCommand("copy");
|
|
1114
|
+
}
|
|
1115
|
+
this.editor.toast.show("源码已复制到剪贴板");
|
|
1116
|
+
} catch {
|
|
1117
|
+
this.editor.toast.error("复制失败,请手动选择复制");
|
|
1118
|
+
}
|
|
1119
|
+
}
|
|
1120
|
+
/** 应用当前源码到编辑区(做净化) */
|
|
1121
|
+
apply({ silent = false } = {}) {
|
|
1122
|
+
const html = this.value;
|
|
1123
|
+
try {
|
|
1124
|
+
this.editor.setContent(html, { sanitize: true, silent: false });
|
|
1125
|
+
if (!silent) this.editor.toast.show("源码已应用");
|
|
1126
|
+
return true;
|
|
1127
|
+
} catch (error) {
|
|
1128
|
+
this.editor.toast.error(`源码解析失败:${error.message}`);
|
|
1129
|
+
return false;
|
|
1130
|
+
}
|
|
1131
|
+
}
|
|
1132
|
+
destroy() {
|
|
1133
|
+
this.el.remove();
|
|
1134
|
+
}
|
|
1135
|
+
}
|
|
1136
|
+
const DEVICES = [
|
|
1137
|
+
{ key: "mobile", label: "手机", width: 375 },
|
|
1138
|
+
{ key: "pad", label: "平板", width: 540 },
|
|
1139
|
+
{ key: "pc", label: "电脑", width: 677 }
|
|
1140
|
+
];
|
|
1141
|
+
class PreviewOverlay {
|
|
1142
|
+
constructor(editor) {
|
|
1143
|
+
this.editor = editor;
|
|
1144
|
+
this.device = "pc";
|
|
1145
|
+
this.el = h("div.ke-preview", { hidden: true }, [
|
|
1146
|
+
h("div.ke-preview-bar", {}, [
|
|
1147
|
+
h("span", { text: "预览" }),
|
|
1148
|
+
h("span.ke-source-tip", { text: "仅用于查看排版效果,内容不可编辑" }),
|
|
1149
|
+
h("span.ke-status-tail", {}, DEVICES.map(
|
|
1150
|
+
(device) => h("button.ke-btn", {
|
|
1151
|
+
type: "button",
|
|
1152
|
+
"data-k-device": device.key,
|
|
1153
|
+
text: device.label,
|
|
1154
|
+
onclick: () => this.setDevice(device.key)
|
|
1155
|
+
})
|
|
1156
|
+
).concat([h("span.ke-tb-sep"), h("button.ke-btn", { type: "button", title: "关闭预览", html: icon("close"), onclick: () => editor.closePreview() })]))
|
|
1157
|
+
]),
|
|
1158
|
+
(() => {
|
|
1159
|
+
this.body = h("div.ke-preview-body", {}, [h("div.ke-preview-frame", { style: { maxWidth: "677px" } }, [h("div.ke-content.ke-preview-content")])]);
|
|
1160
|
+
this.frame = this.body.firstChild;
|
|
1161
|
+
this.content = this.frame.firstChild;
|
|
1162
|
+
return this.body;
|
|
1163
|
+
})()
|
|
1164
|
+
]);
|
|
1165
|
+
}
|
|
1166
|
+
setDevice(key) {
|
|
1167
|
+
this.device = key;
|
|
1168
|
+
const device = DEVICES.find((d) => d.key === key) || DEVICES[2];
|
|
1169
|
+
this.frame.style.maxWidth = `${device.width}px`;
|
|
1170
|
+
this.frame.style.width = key === "mobile" ? `${device.width}px` : "100%";
|
|
1171
|
+
this.el.querySelectorAll("[data-k-device]").forEach((btn2) => btn2.classList.toggle("ke-is-active", btn2.dataset.kDevice === key));
|
|
1172
|
+
}
|
|
1173
|
+
show(html) {
|
|
1174
|
+
this.content.innerHTML = html;
|
|
1175
|
+
this.el.hidden = false;
|
|
1176
|
+
this.setDevice(this.device);
|
|
1177
|
+
}
|
|
1178
|
+
hide() {
|
|
1179
|
+
this.el.hidden = true;
|
|
1180
|
+
this.content.innerHTML = "";
|
|
1181
|
+
}
|
|
1182
|
+
destroy() {
|
|
1183
|
+
this.el.remove();
|
|
1184
|
+
}
|
|
1185
|
+
}
|
|
1186
|
+
class Toast {
|
|
1187
|
+
constructor(owner = null) {
|
|
1188
|
+
this.owner = owner;
|
|
1189
|
+
this.el = null;
|
|
1190
|
+
}
|
|
1191
|
+
show(message, type = "", duration = 2600) {
|
|
1192
|
+
if (typeof document === "undefined") return;
|
|
1193
|
+
if (!this.el) {
|
|
1194
|
+
this.el = h("div.ke-toasts");
|
|
1195
|
+
document.body.appendChild(this.el);
|
|
1196
|
+
}
|
|
1197
|
+
const item = h(`span.ke-toast${type ? `.ke-is-${type}` : ""}`, { text: message });
|
|
1198
|
+
this.el.appendChild(item);
|
|
1199
|
+
setTimeout(() => {
|
|
1200
|
+
item.style.opacity = "0";
|
|
1201
|
+
item.style.transition = "opacity .2s";
|
|
1202
|
+
setTimeout(() => item.remove(), 220);
|
|
1203
|
+
}, duration);
|
|
1204
|
+
}
|
|
1205
|
+
error(msg) {
|
|
1206
|
+
this.show(msg, "error", 3600);
|
|
1207
|
+
}
|
|
1208
|
+
warn(msg) {
|
|
1209
|
+
this.show(msg, "warn", 3e3);
|
|
1210
|
+
}
|
|
1211
|
+
ok(msg) {
|
|
1212
|
+
this.show(msg, "ok", 2200);
|
|
1213
|
+
}
|
|
1214
|
+
destroy() {
|
|
1215
|
+
if (this.el && !this.el.childElementCount) this.el.remove();
|
|
1216
|
+
this.el = null;
|
|
1217
|
+
}
|
|
1218
|
+
}
|
|
1219
|
+
function lightbox(src, ownerDocument = document) {
|
|
1220
|
+
const box = h("div.ke-lightbox", { tabindex: "-1" }, [h("img", { src, alt: "" })]);
|
|
1221
|
+
const close = () => {
|
|
1222
|
+
box.remove();
|
|
1223
|
+
document.removeEventListener("keydown", onKey);
|
|
1224
|
+
};
|
|
1225
|
+
const onKey = (event) => {
|
|
1226
|
+
if (event.key === "Escape") close();
|
|
1227
|
+
};
|
|
1228
|
+
box.addEventListener("click", close);
|
|
1229
|
+
document.addEventListener("keydown", onKey);
|
|
1230
|
+
ownerDocument.body.appendChild(box);
|
|
1231
|
+
return close;
|
|
1232
|
+
}
|
|
1233
|
+
class MediaBubble {
|
|
1234
|
+
constructor(editor) {
|
|
1235
|
+
this.editor = editor;
|
|
1236
|
+
this.node = null;
|
|
1237
|
+
this.el = h("div.ke-bubble", { hidden: true, contenteditable: "false" });
|
|
1238
|
+
editor.el.appendChild(this.el);
|
|
1239
|
+
this.el.addEventListener("mousedown", (event) => event.preventDefault());
|
|
1240
|
+
this.el.addEventListener("click", (event) => this.onClick(event));
|
|
1241
|
+
this.replaceInput = h("input", { type: "file", style: { display: "none" } });
|
|
1242
|
+
this.replaceInput.addEventListener("change", () => {
|
|
1243
|
+
var _a;
|
|
1244
|
+
const file = (_a = this.replaceInput.files) == null ? void 0 : _a[0];
|
|
1245
|
+
this.replaceInput.value = "";
|
|
1246
|
+
if (file && this.node) this.editor.media.replaceNode(this.node, file);
|
|
1247
|
+
});
|
|
1248
|
+
editor.el.appendChild(this.replaceInput);
|
|
1249
|
+
this.resizeEl = h("div.ke-img-resize", {
|
|
1250
|
+
hidden: true,
|
|
1251
|
+
"aria-label": "拖动缩放图片",
|
|
1252
|
+
title: "拖动缩放图片",
|
|
1253
|
+
html: '<svg viewBox="0 0 10 10"><path d="M7 1 L9 3 M4 4 L6 6 M1 7 L3 9" stroke="currentColor" stroke-width="1.6" stroke-linecap="round"/></svg>'
|
|
1254
|
+
});
|
|
1255
|
+
this.resizeTip = h("div.ke-img-resize-tip", { hidden: true });
|
|
1256
|
+
this.resizeEl.addEventListener("pointerdown", (event) => this.onResizePointerDown(event));
|
|
1257
|
+
editor.el.appendChild(this.resizeEl);
|
|
1258
|
+
editor.el.appendChild(this.resizeTip);
|
|
1259
|
+
}
|
|
1260
|
+
show(node) {
|
|
1261
|
+
this.node = node;
|
|
1262
|
+
const kind = node.dataset.kMedia === "video" ? "video" : "image";
|
|
1263
|
+
this.el.textContent = "";
|
|
1264
|
+
const actions = kind === "image" ? this.imageActions(node) : this.videoActions(node);
|
|
1265
|
+
for (const item of actions) {
|
|
1266
|
+
if (item) this.el.appendChild(item);
|
|
1267
|
+
}
|
|
1268
|
+
this.el.hidden = false;
|
|
1269
|
+
if (kind === "image") this.attachResize();
|
|
1270
|
+
this.position();
|
|
1271
|
+
}
|
|
1272
|
+
hide() {
|
|
1273
|
+
this.el.hidden = true;
|
|
1274
|
+
this.detachResize();
|
|
1275
|
+
this.node = null;
|
|
1276
|
+
}
|
|
1277
|
+
attachResize() {
|
|
1278
|
+
var _a;
|
|
1279
|
+
if (!((_a = this.node) == null ? void 0 : _a.querySelector("img"))) return;
|
|
1280
|
+
this.resizeEl.hidden = false;
|
|
1281
|
+
this.positionHandle();
|
|
1282
|
+
}
|
|
1283
|
+
detachResize() {
|
|
1284
|
+
this.resizeEl.hidden = true;
|
|
1285
|
+
this.resizeTip.hidden = true;
|
|
1286
|
+
}
|
|
1287
|
+
position() {
|
|
1288
|
+
if (!this.node) return;
|
|
1289
|
+
this.positionHandle();
|
|
1290
|
+
if (this.el.hidden) return;
|
|
1291
|
+
const rootBox = this.editor.el.getBoundingClientRect();
|
|
1292
|
+
const box = this.node.getBoundingClientRect();
|
|
1293
|
+
const view = this.editor.scrollEl.getBoundingClientRect();
|
|
1294
|
+
if (!box.height && !box.width) return this.hide();
|
|
1295
|
+
if (box.bottom < view.top || box.top > view.bottom) return this.hide();
|
|
1296
|
+
const popBox = this.el.getBoundingClientRect();
|
|
1297
|
+
const left = box.left - rootBox.left + box.width / 2;
|
|
1298
|
+
const spaceAbove = box.top - rootBox.top;
|
|
1299
|
+
const flip = spaceAbove < popBox.height + 18;
|
|
1300
|
+
const top = flip ? box.bottom - rootBox.top + 10 : box.top - rootBox.top - 10;
|
|
1301
|
+
this.el.classList.toggle("ke-is-below", flip);
|
|
1302
|
+
const halfWidth = popBox.width / 2;
|
|
1303
|
+
this.el.style.left = `${Math.min(Math.max(left, halfWidth + 8), Math.max(halfWidth + 8, rootBox.width - halfWidth - 8))}px`;
|
|
1304
|
+
this.el.style.top = `${Math.max(6, top)}px`;
|
|
1305
|
+
}
|
|
1306
|
+
positionHandle() {
|
|
1307
|
+
const node = this.node;
|
|
1308
|
+
if (!node || this.resizeEl.hidden) return;
|
|
1309
|
+
const img = node.querySelector("img");
|
|
1310
|
+
if (!img) return;
|
|
1311
|
+
const rootBox = this.editor.el.getBoundingClientRect();
|
|
1312
|
+
const box = img.getBoundingClientRect();
|
|
1313
|
+
if (!box.width && !box.height) return;
|
|
1314
|
+
const size = 18;
|
|
1315
|
+
const gap = 6;
|
|
1316
|
+
this.resizeEl.style.left = `${box.right - rootBox.left - size - gap}px`;
|
|
1317
|
+
this.resizeEl.style.top = `${box.bottom - rootBox.top - size - gap}px`;
|
|
1318
|
+
}
|
|
1319
|
+
updateResizeTip(pct) {
|
|
1320
|
+
var _a;
|
|
1321
|
+
if (this.resizeTip.hidden || !this.node) return;
|
|
1322
|
+
this.resizeTip.textContent = `${Math.round(pct)}%`;
|
|
1323
|
+
const rootBox = this.editor.el.getBoundingClientRect();
|
|
1324
|
+
const box = ((_a = this.node.querySelector("img")) == null ? void 0 : _a.getBoundingClientRect()) || this.node.getBoundingClientRect();
|
|
1325
|
+
this.resizeTip.style.left = `${box.left - rootBox.left + box.width / 2}px`;
|
|
1326
|
+
this.resizeTip.style.top = `${box.top - rootBox.top - 10}px`;
|
|
1327
|
+
}
|
|
1328
|
+
onResizePointerDown(event) {
|
|
1329
|
+
var _a;
|
|
1330
|
+
if (event.button != null && event.button !== 0) return;
|
|
1331
|
+
const img = (_a = this.node) == null ? void 0 : _a.querySelector("img");
|
|
1332
|
+
if (!img) return;
|
|
1333
|
+
event.preventDefault();
|
|
1334
|
+
event.stopPropagation();
|
|
1335
|
+
const figure = this.node;
|
|
1336
|
+
const figureWidth = figure.getBoundingClientRect().width;
|
|
1337
|
+
const startPct = clamp(currentWidthPercent(img, figureWidth), 15, 100);
|
|
1338
|
+
const startX = event.clientX;
|
|
1339
|
+
this.el.hidden = true;
|
|
1340
|
+
this.resizeTip.hidden = false;
|
|
1341
|
+
this.updateResizeTip(startPct);
|
|
1342
|
+
try {
|
|
1343
|
+
this.resizeEl.setPointerCapture(event.pointerId);
|
|
1344
|
+
} catch {
|
|
1345
|
+
}
|
|
1346
|
+
const move = (e) => {
|
|
1347
|
+
const dx = e.clientX - startX;
|
|
1348
|
+
const deltaPct = figureWidth ? dx / figureWidth * 100 : 0;
|
|
1349
|
+
const pct = clamp(Math.round(startPct + deltaPct), 15, 100);
|
|
1350
|
+
img.style.width = `${pct}%`;
|
|
1351
|
+
img.style.maxWidth = "100%";
|
|
1352
|
+
this.updateResizeTip(pct);
|
|
1353
|
+
this.positionHandle();
|
|
1354
|
+
};
|
|
1355
|
+
const up = () => {
|
|
1356
|
+
this.resizeEl.removeEventListener("pointermove", move);
|
|
1357
|
+
this.resizeEl.removeEventListener("pointerup", up);
|
|
1358
|
+
this.resizeEl.removeEventListener("pointercancel", up);
|
|
1359
|
+
this.resizeTip.hidden = true;
|
|
1360
|
+
this.editor.commitHistory();
|
|
1361
|
+
this.editor.refreshStatus();
|
|
1362
|
+
this.el.hidden = false;
|
|
1363
|
+
this.position();
|
|
1364
|
+
};
|
|
1365
|
+
this.resizeEl.addEventListener("pointermove", move);
|
|
1366
|
+
this.resizeEl.addEventListener("pointerup", up);
|
|
1367
|
+
this.resizeEl.addEventListener("pointercancel", up);
|
|
1368
|
+
}
|
|
1369
|
+
imageActions(node) {
|
|
1370
|
+
const img = node.querySelector("img");
|
|
1371
|
+
const align = getMediaAlign(img);
|
|
1372
|
+
const radius = img && parseFloat(getComputedStyle(img).borderRadius) > 0;
|
|
1373
|
+
const applyAlign = (a) => {
|
|
1374
|
+
setMediaAlign(img, a);
|
|
1375
|
+
this.editor.commitHistory();
|
|
1376
|
+
this.position();
|
|
1377
|
+
};
|
|
1378
|
+
const applySize = (w) => {
|
|
1379
|
+
img.style.width = w;
|
|
1380
|
+
setMediaAlign(img, getMediaAlign(img));
|
|
1381
|
+
this.editor.commitHistory();
|
|
1382
|
+
this.position();
|
|
1383
|
+
};
|
|
1384
|
+
return [
|
|
1385
|
+
btn("alignLeft", "左对齐", () => applyAlign("left"), align === "left"),
|
|
1386
|
+
btn("alignCenter", "居中", () => applyAlign("center"), align === "center"),
|
|
1387
|
+
btn("alignRight", "右对齐", () => applyAlign("right"), align === "right"),
|
|
1388
|
+
sep(),
|
|
1389
|
+
textBtn("30%", "宽度 30%", () => applySize("30%")),
|
|
1390
|
+
textBtn("60%", "宽度 60%", () => applySize("60%")),
|
|
1391
|
+
textBtn("100%", "宽度 100%", () => applySize("100%")),
|
|
1392
|
+
sep(),
|
|
1393
|
+
btn("rounded", "圆角", () => toggleRadius(img, node), radius),
|
|
1394
|
+
btn("preview", "查看大图", () => previewImage(img)),
|
|
1395
|
+
btn("upload", "替换图片", () => this.pick("image")),
|
|
1396
|
+
sep(),
|
|
1397
|
+
btn("trash", "删除", () => this.remove())
|
|
1398
|
+
];
|
|
1399
|
+
}
|
|
1400
|
+
videoActions() {
|
|
1401
|
+
return [
|
|
1402
|
+
textBtn("小", "窄版", () => this.setVideoWidth("60%")),
|
|
1403
|
+
textBtn("大", "宽版", () => this.setVideoWidth("100%")),
|
|
1404
|
+
sep(),
|
|
1405
|
+
btn("upload", "替换视频", () => this.pick("video")),
|
|
1406
|
+
sep(),
|
|
1407
|
+
btn("trash", "删除", () => this.remove())
|
|
1408
|
+
];
|
|
1409
|
+
}
|
|
1410
|
+
pick(kind) {
|
|
1411
|
+
this.replaceInput.accept = kind === "image" ? this.editor.options.imageAccept : this.editor.options.videoAccept;
|
|
1412
|
+
this.replaceInput.click();
|
|
1413
|
+
}
|
|
1414
|
+
setVideoWidth(width) {
|
|
1415
|
+
if (!this.node) return;
|
|
1416
|
+
this.node.style.width = width;
|
|
1417
|
+
this.editor.commitHistory();
|
|
1418
|
+
this.position();
|
|
1419
|
+
}
|
|
1420
|
+
remove() {
|
|
1421
|
+
if (!this.node) return;
|
|
1422
|
+
const task = this.editor.media.taskFromNode(this.node);
|
|
1423
|
+
if (task) this.editor.media.remove(task);
|
|
1424
|
+
else {
|
|
1425
|
+
const next = this.node.nextElementSibling;
|
|
1426
|
+
this.node.remove();
|
|
1427
|
+
if (next) this.editor.focus();
|
|
1428
|
+
this.editor.commitHistory();
|
|
1429
|
+
}
|
|
1430
|
+
this.hide();
|
|
1431
|
+
this.editor.refreshStatus();
|
|
1432
|
+
}
|
|
1433
|
+
onClick() {
|
|
1434
|
+
}
|
|
1435
|
+
destroy() {
|
|
1436
|
+
this.el.remove();
|
|
1437
|
+
this.replaceInput.remove();
|
|
1438
|
+
this.resizeEl.remove();
|
|
1439
|
+
this.resizeTip.remove();
|
|
1440
|
+
}
|
|
1441
|
+
}
|
|
1442
|
+
function btn(iconName, title, onclick, active = false) {
|
|
1443
|
+
const node = h("button", { type: "button", title, html: icon(iconName) });
|
|
1444
|
+
if (active) node.classList.add("ke-is-active");
|
|
1445
|
+
node.addEventListener("click", onclick);
|
|
1446
|
+
return node;
|
|
1447
|
+
}
|
|
1448
|
+
function textBtn(label, title, onclick) {
|
|
1449
|
+
const node = h("button", { type: "button", title, text: label });
|
|
1450
|
+
node.addEventListener("click", onclick);
|
|
1451
|
+
return node;
|
|
1452
|
+
}
|
|
1453
|
+
const sep = () => h("span.ke-sep");
|
|
1454
|
+
function toggleRadius(img, node) {
|
|
1455
|
+
if (!img) return;
|
|
1456
|
+
const has = parseFloat(getComputedStyle(img).borderRadius) > 0;
|
|
1457
|
+
img.style.borderRadius = has ? "0" : "10px";
|
|
1458
|
+
node.dispatchEvent(new Event("change", { bubbles: true }));
|
|
1459
|
+
}
|
|
1460
|
+
function previewImage(img) {
|
|
1461
|
+
if (img) lightbox(img.src);
|
|
1462
|
+
}
|
|
1463
|
+
function clamp(value, min, max) {
|
|
1464
|
+
return Math.min(max, Math.max(min, value));
|
|
1465
|
+
}
|
|
1466
|
+
function currentWidthPercent(img, figureWidth) {
|
|
1467
|
+
var _a, _b;
|
|
1468
|
+
if (!figureWidth) return 100;
|
|
1469
|
+
const match = (_b = (_a = img == null ? void 0 : img.style) == null ? void 0 : _a.width) == null ? void 0 : _b.match(/^([\d.]+)%$/);
|
|
1470
|
+
if (match) return parseFloat(match[1]);
|
|
1471
|
+
return img.getBoundingClientRect().width / figureWidth * 100;
|
|
1472
|
+
}
|
|
1473
|
+
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
|
+
const SCROLL_HINT_KEY = "keditor.toolbarScrollHint";
|
|
1475
|
+
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>';
|
|
1476
|
+
const HEADINGS = [
|
|
1477
|
+
{ value: "p", label: "正文", desc: "默认段落 · 17px,正文内容都用它", sample: "正文示例文字", sampleClass: "s-body" },
|
|
1478
|
+
{ value: "h1", label: "标题一", desc: "大标题 · 22px 加粗,全文主标题(建议只用一次)", sample: "标题一示例", sampleClass: "s-h1" },
|
|
1479
|
+
{ value: "h2", label: "标题二", desc: "章节标题 · 20px 加粗,划分小节", sample: "标题二示例", sampleClass: "s-h2" },
|
|
1480
|
+
{ value: "h3", label: "标题三", desc: "小标题 · 18px 加粗,章节内的层级", sample: "标题三示例", sampleClass: "s-h3" }
|
|
1481
|
+
];
|
|
1482
|
+
const FONT_SIZES = [12, 14, 15, 16, 17, 18, 20, 22, 24, 28, 32];
|
|
1483
|
+
const DEFAULT_TOOLBAR = [
|
|
1484
|
+
"undo",
|
|
1485
|
+
"redo",
|
|
1486
|
+
"|",
|
|
1487
|
+
"heading",
|
|
1488
|
+
"fontsize",
|
|
1489
|
+
"|",
|
|
1490
|
+
"bold",
|
|
1491
|
+
"italic",
|
|
1492
|
+
"underline",
|
|
1493
|
+
"strike",
|
|
1494
|
+
"|",
|
|
1495
|
+
"foreColor",
|
|
1496
|
+
"backColor",
|
|
1497
|
+
"|",
|
|
1498
|
+
"alignLeft",
|
|
1499
|
+
"alignCenter",
|
|
1500
|
+
"alignRight",
|
|
1501
|
+
"alignJustify",
|
|
1502
|
+
"|",
|
|
1503
|
+
"ul",
|
|
1504
|
+
"ol",
|
|
1505
|
+
"quote",
|
|
1506
|
+
"|",
|
|
1507
|
+
"link",
|
|
1508
|
+
"image",
|
|
1509
|
+
"video",
|
|
1510
|
+
"table",
|
|
1511
|
+
"code",
|
|
1512
|
+
"hr",
|
|
1513
|
+
"clear",
|
|
1514
|
+
":tail",
|
|
1515
|
+
"source",
|
|
1516
|
+
"preview",
|
|
1517
|
+
"fullscreen"
|
|
1518
|
+
];
|
|
1519
|
+
const ITEMS = {
|
|
1520
|
+
undo: { icon: "undo", title: "撤销 (⌘/Ctrl+Z)", run: (e) => e.undo(), active: (s) => !!s.canUndo, enabled: (s) => s.canUndo },
|
|
1521
|
+
redo: { icon: "redo", title: "重做 (⌘/Ctrl+Shift+Z)", run: (e) => e.redo(), active: (s) => !!s.canRedo, enabled: (s) => s.canRedo },
|
|
1522
|
+
bold: { glyph: ["B", "ke-glyph"], title: "加粗 (⌘/Ctrl+B)", cmd: "bold", active: (s) => s.bold },
|
|
1523
|
+
italic: { glyph: ["I", "ke-glyph ke-glyph-i"], title: "斜体 (⌘/Ctrl+I)", cmd: "italic", active: (s) => s.italic },
|
|
1524
|
+
underline: { glyph: ["U", "ke-glyph ke-glyph-u"], title: "下划线 (⌘/Ctrl+U)", cmd: "underline", active: (s) => s.underline },
|
|
1525
|
+
strike: { glyph: ["S", "ke-glyph ke-glyph-s"], title: "删除线", cmd: "strike", active: (s) => s.strikeThrough },
|
|
1526
|
+
alignLeft: { icon: "alignLeft", title: "左对齐", run: (e) => e.commands.setAlign("left"), active: (s) => s.align === "left" },
|
|
1527
|
+
alignCenter: { icon: "alignCenter", title: "居中", run: (e) => e.commands.setAlign("center"), active: (s) => s.align === "center" },
|
|
1528
|
+
alignRight: { icon: "alignRight", title: "右对齐", run: (e) => e.commands.setAlign("right"), active: (s) => s.align === "right" },
|
|
1529
|
+
alignJustify: { icon: "alignJustify", title: "两端对齐", run: (e) => e.commands.setAlign("justify"), active: (s) => s.align === "justify" },
|
|
1530
|
+
ul: { icon: "ul", title: "无序列表", run: (e) => e.commands.toggleList("unordered"), active: (s) => s.ul },
|
|
1531
|
+
ol: { icon: "ol", title: "有序列表", run: (e) => e.commands.toggleList("ordered"), active: (s) => s.ol },
|
|
1532
|
+
quote: { icon: "quote", title: "引用", run: (e) => e.commands.toggleBlockquote(), active: (s) => s.block === "blockquote" },
|
|
1533
|
+
link: { icon: "link", title: "插入链接", run: (e) => e.toolbar.openLink(), active: (s) => s.link, toggles: true },
|
|
1534
|
+
image: { icon: "image", title: "图片(本地上传 / 网络链接)", run: (e) => e.toolbar.openMedia("image"), toggles: true },
|
|
1535
|
+
video: { icon: "video", title: "视频(本地上传 / 网络链接,支持分片上传)", run: (e) => e.toolbar.openMedia("video"), toggles: true },
|
|
1536
|
+
table: { icon: "table", title: "插入表格", run: (e) => e.toolbar.openTable(), toggles: true },
|
|
1537
|
+
code: { icon: "code", title: "代码块", run: (e) => e.commands.insertCodeBlock() },
|
|
1538
|
+
hr: { icon: "hr", title: "分割线", run: (e) => e.commands.insertDivider() },
|
|
1539
|
+
clear: { icon: "clear", title: "清除格式", run: (e) => e.commands.clearFormat() },
|
|
1540
|
+
source: { icon: "source", title: "查看 / 编辑 HTML 源码(⌘/Ctrl+Shift+K)", text: "源码", run: (e) => e.toggleSource(), active: (s) => s.source },
|
|
1541
|
+
preview: { icon: "preview", title: "预览效果(手机 / 平板 / 电脑宽度)", text: "预览", run: (e) => e.togglePreview(), active: (s) => s.preview },
|
|
1542
|
+
fullscreen: { icon: "expand", title: "全屏编辑", text: "全屏", run: (e) => e.toggleFullscreen(), active: (s) => s.fullscreen },
|
|
1543
|
+
foreColor: { pop: "fore", title: "字体颜色", toggles: true, swatch: "fore" },
|
|
1544
|
+
backColor: { pop: "back", title: "背景高亮色", toggles: true, swatch: "back" }
|
|
1545
|
+
};
|
|
1546
|
+
class Toolbar {
|
|
1547
|
+
constructor(editor, items = DEFAULT_TOOLBAR) {
|
|
1548
|
+
this.editor = editor;
|
|
1549
|
+
this.buttons = /* @__PURE__ */ new Map();
|
|
1550
|
+
this.colorState = { foreColor: "#3f3f3f", backColor: "#f6c344" };
|
|
1551
|
+
this.recent = { foreColor: [], backColor: [] };
|
|
1552
|
+
this.el = editor.tbEl;
|
|
1553
|
+
this.build(items);
|
|
1554
|
+
this.setupScrollHints();
|
|
1555
|
+
}
|
|
1556
|
+
build(items) {
|
|
1557
|
+
const group = h("div.ke-tb-group");
|
|
1558
|
+
this.el.appendChild(group);
|
|
1559
|
+
let tail = null;
|
|
1560
|
+
const target = () => tail || group;
|
|
1561
|
+
for (const key of items) {
|
|
1562
|
+
if (key === "|") {
|
|
1563
|
+
group.appendChild(h("span.ke-tb-sep"));
|
|
1564
|
+
continue;
|
|
1565
|
+
}
|
|
1566
|
+
if (key === ":tail") {
|
|
1567
|
+
tail = h("div.ke-tb-tail");
|
|
1568
|
+
this.el.appendChild(tail);
|
|
1569
|
+
continue;
|
|
1570
|
+
}
|
|
1571
|
+
if (key === "heading") {
|
|
1572
|
+
target().appendChild(this.buildHeading());
|
|
1573
|
+
continue;
|
|
1574
|
+
}
|
|
1575
|
+
if (key === "fontsize") {
|
|
1576
|
+
target().appendChild(this.buildFontSize());
|
|
1577
|
+
continue;
|
|
1578
|
+
}
|
|
1579
|
+
const spec = ITEMS[key];
|
|
1580
|
+
if (!spec) continue;
|
|
1581
|
+
target().appendChild(this.buildButton(key, spec));
|
|
1582
|
+
}
|
|
1583
|
+
}
|
|
1584
|
+
buildButton(name, spec) {
|
|
1585
|
+
const button = h("button.ke-btn", {
|
|
1586
|
+
type: "button",
|
|
1587
|
+
title: spec.title,
|
|
1588
|
+
"data-k-item": name,
|
|
1589
|
+
onclick: (event) => {
|
|
1590
|
+
var _a;
|
|
1591
|
+
event.preventDefault();
|
|
1592
|
+
if (spec.pop) this.toggleColor(name, button);
|
|
1593
|
+
else if (spec.cmd) this.editor.commands.toggleMark(spec.cmd);
|
|
1594
|
+
else (_a = spec.run) == null ? void 0 : _a.call(spec, this.editor);
|
|
1595
|
+
if (!spec.toggles) this.editor.popover.close();
|
|
1596
|
+
}
|
|
1597
|
+
});
|
|
1598
|
+
if (spec.icon) button.innerHTML = icon(spec.icon);
|
|
1599
|
+
if (spec.text) button.appendChild(h("span.ke-btn-text", { text: spec.text }));
|
|
1600
|
+
if (spec.glyph) {
|
|
1601
|
+
const [text, cls] = spec.glyph;
|
|
1602
|
+
button.appendChild(h("span", { class: cls, text }));
|
|
1603
|
+
}
|
|
1604
|
+
if (spec.swatch) {
|
|
1605
|
+
const color = spec.swatch === "fore" ? this.colorState.foreColor : this.colorState.backColor;
|
|
1606
|
+
const face = h("span", { class: spec.swatch === "fore" ? "ke-glyph ke-glyph-a" : "ke-glyph ke-glyph-a ke-glyph-hl" });
|
|
1607
|
+
face.appendChild(h("span", { text: "A" }));
|
|
1608
|
+
button.appendChild(face);
|
|
1609
|
+
if (spec.swatch === "fore") button.appendChild(h("span", { class: "ke-dot" }));
|
|
1610
|
+
this.paintButton(button, spec.swatch, color);
|
|
1611
|
+
button.dataset.kPop = spec.swatch === "fore" ? "foreColor" : "backColor";
|
|
1612
|
+
}
|
|
1613
|
+
if (spec.toggles && !spec.swatch) button.dataset.kPop = name;
|
|
1614
|
+
this.buttons.set(name, button);
|
|
1615
|
+
return button;
|
|
1616
|
+
}
|
|
1617
|
+
paintButton(button, kind, color) {
|
|
1618
|
+
if (!button || !color) return;
|
|
1619
|
+
button.style.setProperty(kind === "fore" ? "--ke-fore" : "--ke-back", color);
|
|
1620
|
+
}
|
|
1621
|
+
/* ---------------- 下拉面板 ---------------- */
|
|
1622
|
+
openPop(anchor, builder, options = {}) {
|
|
1623
|
+
this.editor.saveSelection();
|
|
1624
|
+
this.editor.popover.open(anchor, builder, {
|
|
1625
|
+
align: "start",
|
|
1626
|
+
...options,
|
|
1627
|
+
onClose: () => {
|
|
1628
|
+
var _a;
|
|
1629
|
+
anchor.classList.remove("ke-is-open");
|
|
1630
|
+
(_a = options.onClose) == null ? void 0 : _a.call(options);
|
|
1631
|
+
}
|
|
1632
|
+
});
|
|
1633
|
+
anchor.classList.add("ke-is-open");
|
|
1634
|
+
}
|
|
1635
|
+
/** 同一个按钮再次点击 = 关闭;颜色按钮点击直接展开面板 */
|
|
1636
|
+
togglePop(name, button, builder, options = {}) {
|
|
1637
|
+
const pop = this.editor.popover;
|
|
1638
|
+
if (pop.isOpen && pop.anchor === button) {
|
|
1639
|
+
pop.close();
|
|
1640
|
+
return;
|
|
1641
|
+
}
|
|
1642
|
+
this.openPop(button, builder, options);
|
|
1643
|
+
}
|
|
1644
|
+
buildHeading() {
|
|
1645
|
+
const current = HEADINGS[0];
|
|
1646
|
+
const button = h("button.ke-btn.ke-btn-label", {
|
|
1647
|
+
type: "button",
|
|
1648
|
+
title: "段落样式:正文 / 标题一 / 标题二 / 标题三",
|
|
1649
|
+
"data-k-item": "heading",
|
|
1650
|
+
dataset: { kPop: "heading" },
|
|
1651
|
+
onclick: (event) => {
|
|
1652
|
+
event.preventDefault();
|
|
1653
|
+
this.togglePop("heading", button, () => headingPanel(HEADINGS, {
|
|
1654
|
+
value: this.editor.getState().block,
|
|
1655
|
+
onPick: (value) => {
|
|
1656
|
+
this.editor.restoreSelection();
|
|
1657
|
+
this.editor.commands.setHeading(value);
|
|
1658
|
+
this.editor.popover.close();
|
|
1659
|
+
this.editor.refresh();
|
|
1660
|
+
}
|
|
1661
|
+
}));
|
|
1662
|
+
}
|
|
1663
|
+
});
|
|
1664
|
+
button.innerHTML = `<span class="ke-btn-text">${current.label}</span>${CARET}`;
|
|
1665
|
+
this.headingEl = button;
|
|
1666
|
+
this.buttons.set("heading", button);
|
|
1667
|
+
return button;
|
|
1668
|
+
}
|
|
1669
|
+
buildFontSize() {
|
|
1670
|
+
const button = h("button.ke-btn.ke-btn-label", {
|
|
1671
|
+
type: "button",
|
|
1672
|
+
title: "字号",
|
|
1673
|
+
"data-k-item": "fontsize",
|
|
1674
|
+
dataset: { kPop: "fontsize" },
|
|
1675
|
+
onclick: (event) => {
|
|
1676
|
+
event.preventDefault();
|
|
1677
|
+
this.togglePop("fontsize", button, () => fontSizePanel(FONT_SIZES, {
|
|
1678
|
+
value: this.editor.getState().fontSize,
|
|
1679
|
+
onPick: (size) => {
|
|
1680
|
+
this.editor.restoreSelection();
|
|
1681
|
+
this.editor.commands.setFontSize(Number(size));
|
|
1682
|
+
this.editor.popover.close();
|
|
1683
|
+
this.editor.refresh();
|
|
1684
|
+
}
|
|
1685
|
+
}));
|
|
1686
|
+
}
|
|
1687
|
+
});
|
|
1688
|
+
button.innerHTML = `<span class="ke-btn-text">字号</span>${CARET}`;
|
|
1689
|
+
this.fontSizeEl = button;
|
|
1690
|
+
this.buttons.set("fontsize", button);
|
|
1691
|
+
return button;
|
|
1692
|
+
}
|
|
1693
|
+
toggleColor(name, button) {
|
|
1694
|
+
const kind = name === "foreColor" ? "fore" : "back";
|
|
1695
|
+
this.togglePop(
|
|
1696
|
+
name,
|
|
1697
|
+
button,
|
|
1698
|
+
() => colorPanel({
|
|
1699
|
+
title: kind === "fore" ? "字体颜色" : "背景高亮色",
|
|
1700
|
+
kind,
|
|
1701
|
+
value: this.colorState[name],
|
|
1702
|
+
recents: this.recent[name],
|
|
1703
|
+
onPick: (color) => this.applyColor(name, kind, color, button),
|
|
1704
|
+
onClear: () => this.applyColor(name, kind, null, button)
|
|
1705
|
+
}),
|
|
1706
|
+
{
|
|
1707
|
+
onClose: () => button.classList.remove("ke-is-active")
|
|
1708
|
+
}
|
|
1709
|
+
);
|
|
1710
|
+
}
|
|
1711
|
+
applyColor(name, kind, color, button) {
|
|
1712
|
+
this.editor.restoreSelection();
|
|
1713
|
+
if (color) {
|
|
1714
|
+
this.colorState[name] = color;
|
|
1715
|
+
this.recent[name] = [color, ...this.recent[name].filter((x) => x.toLowerCase() !== color.toLowerCase())].slice(0, 8);
|
|
1716
|
+
this.paintButton(button, kind, color);
|
|
1717
|
+
}
|
|
1718
|
+
this.editor.commands.setColor(kind, color);
|
|
1719
|
+
this.editor.popover.close();
|
|
1720
|
+
}
|
|
1721
|
+
openTable() {
|
|
1722
|
+
const button = this.buttons.get("table");
|
|
1723
|
+
this.togglePop("table", button, () => tablePanel((cols, rows) => {
|
|
1724
|
+
this.editor.restoreSelection();
|
|
1725
|
+
this.editor.commands.insertTable(cols, rows);
|
|
1726
|
+
this.editor.popover.close();
|
|
1727
|
+
}));
|
|
1728
|
+
}
|
|
1729
|
+
openLink() {
|
|
1730
|
+
const button = this.buttons.get("link");
|
|
1731
|
+
const state = this.editor.getState();
|
|
1732
|
+
const existing = state.linkUrl;
|
|
1733
|
+
this.togglePop("link", button, () => linkPanel({
|
|
1734
|
+
url: existing || "",
|
|
1735
|
+
text: existing ? "" : state.selectionText || "",
|
|
1736
|
+
target: existing ? state.linkTarget : true,
|
|
1737
|
+
onCancel: () => this.editor.popover.close(),
|
|
1738
|
+
onRemove: existing ? () => {
|
|
1739
|
+
this.editor.restoreSelection();
|
|
1740
|
+
this.editor.commands.removeLink();
|
|
1741
|
+
this.editor.popover.close();
|
|
1742
|
+
} : null,
|
|
1743
|
+
onSubmit: ({ url, text, target }) => {
|
|
1744
|
+
this.editor.restoreSelection();
|
|
1745
|
+
this.editor.commands.createLink({ url: normalizeUrl(url), text, target });
|
|
1746
|
+
this.editor.popover.close();
|
|
1747
|
+
}
|
|
1748
|
+
}));
|
|
1749
|
+
}
|
|
1750
|
+
/** 图片 / 视频:本地上传 + 网络链接输入 */
|
|
1751
|
+
openMedia(kind) {
|
|
1752
|
+
const button = this.buttons.get(kind);
|
|
1753
|
+
const editor = this.editor;
|
|
1754
|
+
const options = editor.options;
|
|
1755
|
+
this.togglePop(kind, button, () => mediaPanel(kind, {
|
|
1756
|
+
multiple: kind === "image",
|
|
1757
|
+
maxText: `${kind === "image" ? "图片" : "视频"}上限 ${formatLimit(kind === "image" ? options.maxImageSize : options.maxVideoSize)}`,
|
|
1758
|
+
hint: kind === "image" ? "支持 PNG / JPG / GIF / WebP / SVG" : "支持 MP4 / MOV / WebM,大文件自动分片",
|
|
1759
|
+
onFiles: (files) => {
|
|
1760
|
+
editor.popover.close();
|
|
1761
|
+
if (files && files.length) editor.media.addFiles([...files]);
|
|
1762
|
+
else editor.media.pickFiles(kind);
|
|
1763
|
+
},
|
|
1764
|
+
onUrl: ({ url, name }) => {
|
|
1765
|
+
editor.popover.close();
|
|
1766
|
+
editor.restoreSelection();
|
|
1767
|
+
editor.media.insertFromUrl(kind, url, name);
|
|
1768
|
+
}
|
|
1769
|
+
}));
|
|
1770
|
+
}
|
|
1771
|
+
/** 根据编辑器状态同步按钮高亮 / 下拉值 / 禁用 */
|
|
1772
|
+
refresh(state) {
|
|
1773
|
+
var _a;
|
|
1774
|
+
for (const [name, button] of this.buttons) {
|
|
1775
|
+
const spec = ITEMS[name];
|
|
1776
|
+
if (!spec) continue;
|
|
1777
|
+
const active = ((_a = spec.active) == null ? void 0 : _a.call(spec, state)) || false;
|
|
1778
|
+
if (button.dataset.kPop || !spec.pop) button.classList.toggle("ke-is-active", active);
|
|
1779
|
+
if (spec.enabled) button.disabled = !spec.enabled(state);
|
|
1780
|
+
}
|
|
1781
|
+
if (this.headingEl) {
|
|
1782
|
+
const match = HEADINGS.find((x) => x.value === state.block);
|
|
1783
|
+
const label = this.headingEl.querySelector(".ke-btn-text");
|
|
1784
|
+
if (label) label.textContent = match ? match.label : "正文";
|
|
1785
|
+
this.headingEl.title = match ? `${match.label}:${match.desc}` : "段落样式";
|
|
1786
|
+
}
|
|
1787
|
+
if (this.fontSizeEl) {
|
|
1788
|
+
const label = this.fontSizeEl.querySelector(".ke-btn-text");
|
|
1789
|
+
if (label) label.textContent = state.fontSize ? `${state.fontSize}px` : "字号";
|
|
1790
|
+
}
|
|
1791
|
+
if (state.linkUrl) {
|
|
1792
|
+
const btn2 = this.buttons.get("link");
|
|
1793
|
+
btn2 == null ? void 0 : btn2.classList.add("ke-is-active");
|
|
1794
|
+
}
|
|
1795
|
+
}
|
|
1796
|
+
/* ---------------- 可滑动提示 ---------------- */
|
|
1797
|
+
/**
|
|
1798
|
+
* 工具栏溢出时给出四重可发现性提示:
|
|
1799
|
+
* 常显滚动条(CSS)、右侧被遮工具的动态阴影、左侧渐隐、鼠标拖拽,
|
|
1800
|
+
* 外加首次加载的引导气泡。
|
|
1801
|
+
*/
|
|
1802
|
+
setupScrollHints() {
|
|
1803
|
+
const tb = this.el;
|
|
1804
|
+
const host = this.editor.el;
|
|
1805
|
+
if (!tb.isConnected) return;
|
|
1806
|
+
this.scrollFades = h("div.ke-tb-fades", { "aria-hidden": "true" }, [h("i.ke-tb-fade ke-tb-fade-l")]);
|
|
1807
|
+
tb.insertAdjacentElement("afterend", this.scrollFades);
|
|
1808
|
+
this.syncScrollHints = () => {
|
|
1809
|
+
if (!tb.isConnected || !host.isConnected) return;
|
|
1810
|
+
const max = tb.scrollWidth - tb.clientWidth;
|
|
1811
|
+
const overflow = max > 1;
|
|
1812
|
+
const left = tb.scrollLeft;
|
|
1813
|
+
host.classList.toggle("ke-tb-scrollable", overflow);
|
|
1814
|
+
host.classList.toggle("ke-tb-can-l", overflow && left > 1);
|
|
1815
|
+
host.classList.toggle("ke-tb-can-r", overflow && left < max - 1);
|
|
1816
|
+
host.style.setProperty("--ke-tb-h", `${tb.offsetHeight}px`);
|
|
1817
|
+
if (overflow && !this.hintSettled) this.showScrollHint();
|
|
1818
|
+
};
|
|
1819
|
+
this.onTbScroll = () => {
|
|
1820
|
+
this.syncScrollHints();
|
|
1821
|
+
this.hideScrollHint();
|
|
1822
|
+
};
|
|
1823
|
+
tb.addEventListener("scroll", this.onTbScroll, { passive: true });
|
|
1824
|
+
if (typeof ResizeObserver !== "undefined") {
|
|
1825
|
+
this.tbRO = new ResizeObserver(() => this.syncScrollHints());
|
|
1826
|
+
this.tbRO.observe(tb);
|
|
1827
|
+
}
|
|
1828
|
+
this.onTbPointerDown = (event) => {
|
|
1829
|
+
this.hideScrollHint();
|
|
1830
|
+
this.startDragScroll(event);
|
|
1831
|
+
};
|
|
1832
|
+
tb.addEventListener("pointerdown", this.onTbPointerDown);
|
|
1833
|
+
requestAnimationFrame(this.syncScrollHints);
|
|
1834
|
+
}
|
|
1835
|
+
/** 鼠标按住拖动平移工具栏(触屏已有原生滑动,不介入) */
|
|
1836
|
+
startDragScroll(event) {
|
|
1837
|
+
const tb = this.el;
|
|
1838
|
+
const host = this.editor.el;
|
|
1839
|
+
if (event.button !== 0 || event.pointerType !== "mouse") return;
|
|
1840
|
+
if (tb.scrollWidth <= tb.clientWidth + 1) return;
|
|
1841
|
+
if (event.target.closest("input, textarea, select")) return;
|
|
1842
|
+
const startX = event.clientX;
|
|
1843
|
+
const startLeft = tb.scrollLeft;
|
|
1844
|
+
let dragging = false;
|
|
1845
|
+
const move = (ev) => {
|
|
1846
|
+
var _a;
|
|
1847
|
+
const dx = ev.clientX - startX;
|
|
1848
|
+
if (!dragging) {
|
|
1849
|
+
if (Math.abs(dx) < 5) return;
|
|
1850
|
+
dragging = true;
|
|
1851
|
+
try {
|
|
1852
|
+
tb.setPointerCapture(event.pointerId);
|
|
1853
|
+
} catch {
|
|
1854
|
+
}
|
|
1855
|
+
host.classList.add("ke-tb-dragging");
|
|
1856
|
+
(_a = this.editor.popover) == null ? void 0 : _a.close();
|
|
1857
|
+
}
|
|
1858
|
+
ev.preventDefault();
|
|
1859
|
+
tb.scrollLeft = startLeft - dx;
|
|
1860
|
+
};
|
|
1861
|
+
const up = () => {
|
|
1862
|
+
tb.removeEventListener("pointermove", move);
|
|
1863
|
+
tb.removeEventListener("pointerup", up);
|
|
1864
|
+
tb.removeEventListener("pointercancel", up);
|
|
1865
|
+
host.classList.remove("ke-tb-dragging");
|
|
1866
|
+
if (!dragging) return;
|
|
1867
|
+
try {
|
|
1868
|
+
tb.releasePointerCapture(event.pointerId);
|
|
1869
|
+
} catch {
|
|
1870
|
+
}
|
|
1871
|
+
const stop = (ev) => {
|
|
1872
|
+
ev.preventDefault();
|
|
1873
|
+
ev.stopPropagation();
|
|
1874
|
+
release();
|
|
1875
|
+
};
|
|
1876
|
+
const release = () => {
|
|
1877
|
+
clearTimeout(fallback);
|
|
1878
|
+
tb.removeEventListener("click", stop, true);
|
|
1879
|
+
};
|
|
1880
|
+
const fallback = setTimeout(release, 400);
|
|
1881
|
+
tb.addEventListener("click", stop, true);
|
|
1882
|
+
};
|
|
1883
|
+
tb.addEventListener("pointermove", move);
|
|
1884
|
+
tb.addEventListener("pointerup", up);
|
|
1885
|
+
tb.addEventListener("pointercancel", up);
|
|
1886
|
+
}
|
|
1887
|
+
showScrollHint() {
|
|
1888
|
+
this.hintSettled = true;
|
|
1889
|
+
let seen = false;
|
|
1890
|
+
try {
|
|
1891
|
+
seen = localStorage.getItem(SCROLL_HINT_KEY) === "1";
|
|
1892
|
+
} catch {
|
|
1893
|
+
}
|
|
1894
|
+
if (seen) return;
|
|
1895
|
+
this.hintEl = h("div.ke-tb-hint", { "aria-hidden": "true" }, [
|
|
1896
|
+
h("span.ke-tb-hint-ico", { html: SCROLL_HINT_ICON }),
|
|
1897
|
+
h("span", { text: "工具栏可左右滑动" })
|
|
1898
|
+
]);
|
|
1899
|
+
this.editor.el.appendChild(this.hintEl);
|
|
1900
|
+
this.hintTimer = setTimeout(() => this.hideScrollHint(), 3800);
|
|
1901
|
+
}
|
|
1902
|
+
hideScrollHint() {
|
|
1903
|
+
if (this.hintTimer) {
|
|
1904
|
+
clearTimeout(this.hintTimer);
|
|
1905
|
+
this.hintTimer = null;
|
|
1906
|
+
}
|
|
1907
|
+
const pill = this.hintEl;
|
|
1908
|
+
if (!pill) return;
|
|
1909
|
+
this.hintEl = null;
|
|
1910
|
+
try {
|
|
1911
|
+
localStorage.setItem(SCROLL_HINT_KEY, "1");
|
|
1912
|
+
} catch {
|
|
1913
|
+
}
|
|
1914
|
+
pill.classList.add("ke-is-out");
|
|
1915
|
+
setTimeout(() => pill.remove(), 260);
|
|
1916
|
+
}
|
|
1917
|
+
destroy() {
|
|
1918
|
+
var _a, _b, _c;
|
|
1919
|
+
const tb = this.el;
|
|
1920
|
+
if (this.tbRO) {
|
|
1921
|
+
this.tbRO.disconnect();
|
|
1922
|
+
this.tbRO = null;
|
|
1923
|
+
}
|
|
1924
|
+
if (this.hintTimer) {
|
|
1925
|
+
clearTimeout(this.hintTimer);
|
|
1926
|
+
this.hintTimer = null;
|
|
1927
|
+
}
|
|
1928
|
+
if (this.onTbScroll) tb.removeEventListener("scroll", this.onTbScroll);
|
|
1929
|
+
if (this.onTbPointerDown) tb.removeEventListener("pointerdown", this.onTbPointerDown);
|
|
1930
|
+
(_a = this.scrollFades) == null ? void 0 : _a.remove();
|
|
1931
|
+
(_b = this.hintEl) == null ? void 0 : _b.remove();
|
|
1932
|
+
this.scrollFades = null;
|
|
1933
|
+
this.hintEl = null;
|
|
1934
|
+
const host = (_c = this.editor) == null ? void 0 : _c.el;
|
|
1935
|
+
if (host) {
|
|
1936
|
+
host.classList.remove("ke-tb-scrollable", "ke-tb-can-l", "ke-tb-can-r", "ke-tb-dragging");
|
|
1937
|
+
host.style.removeProperty("--ke-tb-h");
|
|
1938
|
+
}
|
|
1939
|
+
tb.innerHTML = "";
|
|
1940
|
+
this.buttons.clear();
|
|
1941
|
+
}
|
|
1942
|
+
}
|
|
1943
|
+
function formatLimit(bytes) {
|
|
1944
|
+
if (!bytes) return "不限";
|
|
1945
|
+
const mb = bytes / 1024 / 1024;
|
|
1946
|
+
return mb >= 1 ? `${Math.round(mb)}MB` : `${Math.round(bytes / 1024)}KB`;
|
|
1947
|
+
}
|
|
1948
|
+
function getRange(root) {
|
|
1949
|
+
const sel = window.getSelection();
|
|
1950
|
+
if (!sel || sel.rangeCount === 0) return null;
|
|
1951
|
+
const range = sel.getRangeAt(0);
|
|
1952
|
+
if (!root.contains(range.commonAncestorContainer)) return null;
|
|
1953
|
+
return range;
|
|
1954
|
+
}
|
|
1955
|
+
function caretOffset(root) {
|
|
1956
|
+
const sel = window.getSelection();
|
|
1957
|
+
if (!sel || sel.rangeCount === 0) return null;
|
|
1958
|
+
const range = sel.getRangeAt(0);
|
|
1959
|
+
if (!root.contains(range.startContainer)) return null;
|
|
1960
|
+
let offset = 0;
|
|
1961
|
+
const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT, {
|
|
1962
|
+
acceptNode(node) {
|
|
1963
|
+
if (node === range.startContainer) return NodeFilter.FILTER_ACCEPT;
|
|
1964
|
+
offset += node.textContent.length;
|
|
1965
|
+
return NodeFilter.FILTER_SKIP;
|
|
1966
|
+
}
|
|
1967
|
+
});
|
|
1968
|
+
const found = walker.nextNode();
|
|
1969
|
+
if (!found) return range.startContainer === root ? 0 : null;
|
|
1970
|
+
return offset + range.startOffset;
|
|
1971
|
+
}
|
|
1972
|
+
function setCaretOffset(root, offset) {
|
|
1973
|
+
if (offset === null || offset === void 0) return;
|
|
1974
|
+
const sel = window.getSelection();
|
|
1975
|
+
let remaining = Math.max(0, offset);
|
|
1976
|
+
const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT);
|
|
1977
|
+
let node = walker.nextNode();
|
|
1978
|
+
let last = null;
|
|
1979
|
+
while (node) {
|
|
1980
|
+
const len = node.textContent.length;
|
|
1981
|
+
if (remaining <= len) {
|
|
1982
|
+
try {
|
|
1983
|
+
sel.setBaseAndExtent(node, remaining, node, remaining);
|
|
1984
|
+
} catch {
|
|
1985
|
+
}
|
|
1986
|
+
return;
|
|
1987
|
+
}
|
|
1988
|
+
remaining -= len;
|
|
1989
|
+
last = node;
|
|
1990
|
+
node = walker.nextNode();
|
|
1991
|
+
}
|
|
1992
|
+
if (last) {
|
|
1993
|
+
try {
|
|
1994
|
+
sel.setBaseAndExtent(last, last.textContent.length, last, last.textContent.length);
|
|
1995
|
+
} catch {
|
|
1996
|
+
}
|
|
1997
|
+
}
|
|
1998
|
+
}
|
|
1999
|
+
function insertNode(root, node, { inline = false, selectAfter = true } = {}) {
|
|
2000
|
+
root.focus();
|
|
2001
|
+
const range = getRange(root);
|
|
2002
|
+
if (!range) {
|
|
2003
|
+
root.appendChild(node);
|
|
2004
|
+
ensureEditableTail(root);
|
|
2005
|
+
return node;
|
|
2006
|
+
}
|
|
2007
|
+
if (!range.collapsed) range.deleteContents();
|
|
2008
|
+
if (inline) {
|
|
2009
|
+
range.insertNode(node);
|
|
2010
|
+
} else {
|
|
2011
|
+
const block = closestBlock(range.startContainer, root);
|
|
2012
|
+
if (!block || block === root) root.appendChild(node);
|
|
2013
|
+
else block.after(node);
|
|
2014
|
+
}
|
|
2015
|
+
const after = document.createRange();
|
|
2016
|
+
after.setStartAfter(node);
|
|
2017
|
+
after.collapse(true);
|
|
2018
|
+
const sel = window.getSelection();
|
|
2019
|
+
sel.removeAllRanges();
|
|
2020
|
+
sel.addRange(after);
|
|
2021
|
+
ensureEditableTail(root);
|
|
2022
|
+
if (selectAfter && sel.rangeCount === 0) root.focus();
|
|
2023
|
+
return node;
|
|
2024
|
+
}
|
|
2025
|
+
function ensureEditableTail(root) {
|
|
2026
|
+
const last = root.lastElementChild;
|
|
2027
|
+
if (!last) {
|
|
2028
|
+
root.appendChild(document.createElement("p"));
|
|
2029
|
+
return;
|
|
2030
|
+
}
|
|
2031
|
+
if (/^(IMG|VIDEO|IFRAME)$/.test(last.tagName) || last.dataset.kmedia !== void 0) {
|
|
2032
|
+
const p = document.createElement("p");
|
|
2033
|
+
p.appendChild(document.createElement("br"));
|
|
2034
|
+
root.appendChild(p);
|
|
2035
|
+
}
|
|
2036
|
+
}
|
|
2037
|
+
function closestBlock(node, root) {
|
|
2038
|
+
let current = node;
|
|
2039
|
+
while (current && current !== root) {
|
|
2040
|
+
if (current.nodeType === 1 && /^(P|DIV|H[1-6]|LI|BLOCKQUOTE|PRE|SECTION|TD|TH)$/.test(current.tagName)) return current;
|
|
2041
|
+
current = current.parentNode;
|
|
2042
|
+
}
|
|
2043
|
+
return null;
|
|
2044
|
+
}
|
|
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) => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" })[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
|
+
class Commands {
|
|
2250
|
+
constructor(editor) {
|
|
2251
|
+
this.editor = editor;
|
|
2252
|
+
this.root = editor.root;
|
|
2253
|
+
}
|
|
2254
|
+
/** 统一入口:确保聚焦 + 开启 styleWithCSS(输出 inline style,符合公众号粘贴习惯) */
|
|
2255
|
+
exec(command, value = null) {
|
|
2256
|
+
this.editor.focus();
|
|
2257
|
+
document.execCommand("styleWithCSS", false, true);
|
|
2258
|
+
document.execCommand("defaultParagraphSeparator", false, "p");
|
|
2259
|
+
const ok = document.execCommand(command, false, value);
|
|
2260
|
+
this.editor.afterEdit();
|
|
2261
|
+
return ok;
|
|
2262
|
+
}
|
|
2263
|
+
queryState(command) {
|
|
2264
|
+
try {
|
|
2265
|
+
return document.queryCommandState(command);
|
|
2266
|
+
} catch {
|
|
2267
|
+
return false;
|
|
2268
|
+
}
|
|
2269
|
+
}
|
|
2270
|
+
queryValue(command) {
|
|
2271
|
+
try {
|
|
2272
|
+
return document.queryCommandValue(command);
|
|
2273
|
+
} catch {
|
|
2274
|
+
return "";
|
|
2275
|
+
}
|
|
2276
|
+
}
|
|
2277
|
+
hasSelection() {
|
|
2278
|
+
const range = getRange(this.root);
|
|
2279
|
+
return !!(range && !range.collapsed);
|
|
2280
|
+
}
|
|
2281
|
+
toggleMark(name) {
|
|
2282
|
+
const map = { bold: "bold", italic: "italic", underline: "underline", strike: "strikeThrough" };
|
|
2283
|
+
const cmd = map[name];
|
|
2284
|
+
if (!cmd) return;
|
|
2285
|
+
this.exec(cmd);
|
|
2286
|
+
this.root.querySelectorAll('span[style=""]').forEach((n) => n.replaceWith(...n.childNodes));
|
|
2287
|
+
}
|
|
2288
|
+
/** 字号:用 fontSize=7 作为标记再改写成 font-size:px,避免浏览器字号档位限制 */
|
|
2289
|
+
setFontSize(px) {
|
|
2290
|
+
this.editor.focus();
|
|
2291
|
+
document.execCommand("styleWithCSS", false, false);
|
|
2292
|
+
const marker = `__ke_fs_${uid()}__`;
|
|
2293
|
+
this.root.setAttribute("data-ke-marker", marker);
|
|
2294
|
+
document.execCommand("fontSize", false, "7");
|
|
2295
|
+
this.root.removeAttribute("data-ke-marker");
|
|
2296
|
+
this.root.querySelectorAll('font[size="7"]').forEach((font) => {
|
|
2297
|
+
const span = document.createElement("span");
|
|
2298
|
+
span.style.fontSize = `${px}px`;
|
|
2299
|
+
while (font.firstChild) span.appendChild(font.firstChild);
|
|
2300
|
+
font.replaceWith(span);
|
|
2301
|
+
});
|
|
2302
|
+
this.root.querySelectorAll("span").forEach((span) => {
|
|
2303
|
+
if (/xx-large/i.test(span.style.fontSize)) span.style.fontSize = `${px}px`;
|
|
2304
|
+
});
|
|
2305
|
+
document.execCommand("styleWithCSS", false, true);
|
|
2306
|
+
this.editor.afterEdit();
|
|
2307
|
+
}
|
|
2308
|
+
setColor(mode, color) {
|
|
2309
|
+
this.editor.focus();
|
|
2310
|
+
document.execCommand("styleWithCSS", false, true);
|
|
2311
|
+
if (!color) color = mode === "fore" ? "#3f3f3f" : "transparent";
|
|
2312
|
+
const ok = document.execCommand(mode === "fore" ? "foreColor" : "hiliteColor", false, color);
|
|
2313
|
+
if (!ok) document.execCommand(mode === "fore" ? "foreColor" : "backColor", false, color);
|
|
2314
|
+
if (mode === "back" && color === "transparent") {
|
|
2315
|
+
this.root.querySelectorAll('[style*="background-color"]').forEach((node) => {
|
|
2316
|
+
if (/background-color:\s*transparent|rgba\(0, 0, 0, 0\)/i.test(node.getAttribute("style") || "")) {
|
|
2317
|
+
node.style.backgroundColor = "";
|
|
2318
|
+
if (!node.getAttribute("style").trim()) node.replaceWith(...node.childNodes);
|
|
2319
|
+
}
|
|
2320
|
+
});
|
|
2321
|
+
}
|
|
2322
|
+
this.editor.afterEdit();
|
|
2323
|
+
}
|
|
2324
|
+
setAlign(align) {
|
|
2325
|
+
var _a, _b;
|
|
2326
|
+
const media = (_a = this.editor.bubble) == null ? void 0 : _a.node;
|
|
2327
|
+
if (media && ((_b = media.dataset) == null ? void 0 : _b.kMedia) === "image" && align !== "justify") {
|
|
2328
|
+
const img = media.querySelector("img");
|
|
2329
|
+
if (img) {
|
|
2330
|
+
setMediaAlign(img, align);
|
|
2331
|
+
this.editor.commitHistory();
|
|
2332
|
+
this.editor.bubble.position();
|
|
2333
|
+
return;
|
|
2334
|
+
}
|
|
2335
|
+
}
|
|
2336
|
+
const map = { left: "justifyLeft", center: "justifyCenter", right: "justifyRight", justify: "justifyFull" };
|
|
2337
|
+
const cmd = map[align];
|
|
2338
|
+
if (!cmd) return;
|
|
2339
|
+
this.editor.focus();
|
|
2340
|
+
const range = getRange(this.root);
|
|
2341
|
+
const block = closestBlock((range == null ? void 0 : range.commonAncestorContainer) || this.root, this.root);
|
|
2342
|
+
document.execCommand("styleWithCSS", false, true);
|
|
2343
|
+
document.execCommand(cmd);
|
|
2344
|
+
const node = block || this.root.firstElementChild;
|
|
2345
|
+
if (node && /^(FIGURE|DIV|VIDEO)/.test(node.tagName || "")) node.style.textAlign = align;
|
|
2346
|
+
this.editor.afterEdit();
|
|
2347
|
+
}
|
|
2348
|
+
toggleList(kind) {
|
|
2349
|
+
this.exec(kind === "ordered" ? "insertOrderedList" : "insertUnorderedList");
|
|
2350
|
+
}
|
|
2351
|
+
setHeading(tag) {
|
|
2352
|
+
const value = tag ? `<${tag}>` : "<p>";
|
|
2353
|
+
this.exec("formatBlock", value);
|
|
2354
|
+
}
|
|
2355
|
+
toggleBlockquote() {
|
|
2356
|
+
const range = getRange(this.root);
|
|
2357
|
+
const block = closestBlock((range == null ? void 0 : range.commonAncestorContainer) || this.root, this.root);
|
|
2358
|
+
if (block && block.tagName === "BLOCKQUOTE") this.exec("formatBlock", "<p>");
|
|
2359
|
+
else this.exec("formatBlock", "<blockquote>");
|
|
2360
|
+
}
|
|
2361
|
+
/** 链接:有选区则包裹,无选区则插入完整 a 标签 */
|
|
2362
|
+
createLink({ url, text = "", target = false }) {
|
|
2363
|
+
var _a, _b;
|
|
2364
|
+
this.editor.focus();
|
|
2365
|
+
const range = getRange(this.root);
|
|
2366
|
+
const hasSel = range && !range.collapsed;
|
|
2367
|
+
const label = text || (hasSel ? range.toString() : url);
|
|
2368
|
+
if (hasSel) {
|
|
2369
|
+
document.execCommand("createLink", false, url);
|
|
2370
|
+
(_b = (_a = range.commonAncestorContainer.parentElement) == null ? void 0 : _a.closest) == null ? void 0 : _b.call(_a, "a");
|
|
2371
|
+
this.root.querySelectorAll(`a[href="${cssEscape(url)}"]`).forEach((a) => {
|
|
2372
|
+
if (target) {
|
|
2373
|
+
a.setAttribute("target", "_blank");
|
|
2374
|
+
a.setAttribute("rel", "noopener noreferrer");
|
|
2375
|
+
} else {
|
|
2376
|
+
a.removeAttribute("target");
|
|
2377
|
+
}
|
|
2378
|
+
});
|
|
2379
|
+
} else {
|
|
2380
|
+
const a = h("a", { href: url }, [label]);
|
|
2381
|
+
if (target) {
|
|
2382
|
+
a.setAttribute("target", "_blank");
|
|
2383
|
+
a.setAttribute("rel", "noopener noreferrer");
|
|
2384
|
+
}
|
|
2385
|
+
insertNode(this.root, a, { inline: true });
|
|
2386
|
+
}
|
|
2387
|
+
this.editor.afterEdit();
|
|
2388
|
+
}
|
|
2389
|
+
removeLink() {
|
|
2390
|
+
const range = getRange(this.root);
|
|
2391
|
+
const anchors = closestAnchors(range, this.root);
|
|
2392
|
+
anchors.forEach((node) => node.replaceWith(...node.childNodes));
|
|
2393
|
+
this.editor.afterEdit();
|
|
2394
|
+
}
|
|
2395
|
+
insertTable(cols, rows) {
|
|
2396
|
+
const table = document.createElement("table");
|
|
2397
|
+
const tbody = document.createElement("tbody");
|
|
2398
|
+
for (let r = 0; r < rows; r += 1) {
|
|
2399
|
+
const tr = document.createElement("tr");
|
|
2400
|
+
for (let c = 0; c < cols; c += 1) {
|
|
2401
|
+
const cell = document.createElement(r === 0 ? "th" : "td");
|
|
2402
|
+
cell.innerHTML = "<br>";
|
|
2403
|
+
tr.appendChild(cell);
|
|
2404
|
+
}
|
|
2405
|
+
tbody.appendChild(tr);
|
|
2406
|
+
}
|
|
2407
|
+
table.appendChild(tbody);
|
|
2408
|
+
insertNode(this.root, table);
|
|
2409
|
+
this.exec("insertHTML", "");
|
|
2410
|
+
this.editor.afterEdit();
|
|
2411
|
+
}
|
|
2412
|
+
insertCodeBlock(code = "") {
|
|
2413
|
+
const pre = document.createElement("pre");
|
|
2414
|
+
const codeEl = document.createElement("code");
|
|
2415
|
+
codeEl.textContent = code || "// 在这里输入代码";
|
|
2416
|
+
pre.appendChild(codeEl);
|
|
2417
|
+
insertNode(this.root, pre);
|
|
2418
|
+
this.editor.afterEdit();
|
|
2419
|
+
}
|
|
2420
|
+
insertDivider() {
|
|
2421
|
+
const hr = document.createElement("hr");
|
|
2422
|
+
insertNode(this.root, hr);
|
|
2423
|
+
this.editor.afterEdit();
|
|
2424
|
+
}
|
|
2425
|
+
insertHTML(html, { clean = true } = {}) {
|
|
2426
|
+
const value = clean ? sanitizeHtml(html) : html;
|
|
2427
|
+
this.editor.focus();
|
|
2428
|
+
const range = getRange(this.root);
|
|
2429
|
+
if (range) {
|
|
2430
|
+
range.deleteContents();
|
|
2431
|
+
const tmp = document.createElement("div");
|
|
2432
|
+
tmp.innerHTML = value;
|
|
2433
|
+
const frag = document.createDocumentFragment();
|
|
2434
|
+
while (tmp.firstChild) frag.appendChild(tmp.firstChild);
|
|
2435
|
+
const last = frag.lastChild;
|
|
2436
|
+
range.insertNode(frag);
|
|
2437
|
+
if (last) {
|
|
2438
|
+
const after = document.createRange();
|
|
2439
|
+
after.setStartAfter(last.nodeType === 3 ? last : last.lastChild || last);
|
|
2440
|
+
after.collapse(true);
|
|
2441
|
+
const sel = window.getSelection();
|
|
2442
|
+
sel.removeAllRanges();
|
|
2443
|
+
sel.addRange(after);
|
|
2444
|
+
}
|
|
2445
|
+
} else {
|
|
2446
|
+
this.root.insertAdjacentHTML("beforeend", value);
|
|
2447
|
+
}
|
|
2448
|
+
this.editor.afterEdit();
|
|
2449
|
+
}
|
|
2450
|
+
/** 清除格式:内联样式 + 行内标签 + 段落回归 p */
|
|
2451
|
+
clearFormat() {
|
|
2452
|
+
this.editor.focus();
|
|
2453
|
+
if (this.hasSelection()) {
|
|
2454
|
+
document.execCommand("removeFormat");
|
|
2455
|
+
document.execCommand("unlink");
|
|
2456
|
+
const range = getRange(this.root);
|
|
2457
|
+
const block = closestBlock(range == null ? void 0 : range.commonAncestorContainer, this.root);
|
|
2458
|
+
if (block && /^(H[1-6]|BLOCKQUOTE|PRE)$/.test(block.tagName)) this.exec("formatBlock", "<p>");
|
|
2459
|
+
this.stripInlineStylesInRange(range);
|
|
2460
|
+
} else {
|
|
2461
|
+
const range = getRange(this.root);
|
|
2462
|
+
const block = closestBlock((range == null ? void 0 : range.commonAncestorContainer) || this.root, this.root);
|
|
2463
|
+
if (block) {
|
|
2464
|
+
const html = block.innerHTML;
|
|
2465
|
+
const p = document.createElement("p");
|
|
2466
|
+
p.innerHTML = sanitizeHtml(html, { allowEmpty: true });
|
|
2467
|
+
p.innerHTML = p.innerHTML.replace(/<(?!br|img)[^>]+>/gi, "");
|
|
2468
|
+
block.replaceWith(p);
|
|
2469
|
+
}
|
|
2470
|
+
}
|
|
2471
|
+
this.editor.afterEdit();
|
|
2472
|
+
}
|
|
2473
|
+
stripInlineStylesInRange(range) {
|
|
2474
|
+
if (!range) return;
|
|
2475
|
+
const nodes = [];
|
|
2476
|
+
const walker = document.createTreeWalker(range.commonAncestorContainer, NodeFilter.SHOW_ELEMENT);
|
|
2477
|
+
let node = walker.currentNode;
|
|
2478
|
+
while (node) {
|
|
2479
|
+
if (range.intersectsNode(node) && node.nodeType === 1) nodes.push(node);
|
|
2480
|
+
node = walker.nextNode();
|
|
2481
|
+
}
|
|
2482
|
+
nodes.forEach((el) => {
|
|
2483
|
+
if (el === this.root) return;
|
|
2484
|
+
el.removeAttribute("style");
|
|
2485
|
+
if (/^(SPAN|FONT)$/.test(el.tagName) && !el.attributes.length) el.replaceWith(...el.childNodes);
|
|
2486
|
+
});
|
|
2487
|
+
}
|
|
2488
|
+
/** 标题 / 段落的当前状态(供工具栏高亮) */
|
|
2489
|
+
currentBlock() {
|
|
2490
|
+
var _a;
|
|
2491
|
+
const range = getRange(this.root);
|
|
2492
|
+
const block = closestBlock((range == null ? void 0 : range.commonAncestorContainer) || this.root, this.root);
|
|
2493
|
+
return ((_a = block == null ? void 0 : block.tagName) == null ? void 0 : _a.toLowerCase()) || "p";
|
|
2494
|
+
}
|
|
2495
|
+
currentFontSize() {
|
|
2496
|
+
const range = getRange(this.root);
|
|
2497
|
+
if (!range) return "";
|
|
2498
|
+
let node = range.startContainer;
|
|
2499
|
+
while (node && node !== this.root) {
|
|
2500
|
+
if (node.nodeType === 1 && node.style.fontSize) return node.style.fontSize.replace("px", "");
|
|
2501
|
+
node = node.parentNode;
|
|
2502
|
+
}
|
|
2503
|
+
return "";
|
|
2504
|
+
}
|
|
2505
|
+
}
|
|
2506
|
+
function closestAnchors(range, root) {
|
|
2507
|
+
var _a, _b, _c;
|
|
2508
|
+
if (!range) return [];
|
|
2509
|
+
const out = /* @__PURE__ */ new Set();
|
|
2510
|
+
const start = range.startContainer.nodeType === 1 ? ((_b = (_a = range.startContainer).querySelector) == null ? void 0 : _b.call(_a, "a")) || range.startContainer : range.startContainer;
|
|
2511
|
+
let node = start;
|
|
2512
|
+
while (node && node !== root) {
|
|
2513
|
+
if (node.tagName === "A") out.add(node);
|
|
2514
|
+
node = node.parentNode;
|
|
2515
|
+
}
|
|
2516
|
+
try {
|
|
2517
|
+
(_c = range.querySelectorAll) == null ? void 0 : _c.call(range, "a").forEach((a) => out.add(a));
|
|
2518
|
+
} catch {
|
|
2519
|
+
}
|
|
2520
|
+
const container = range.commonAncestorContainer;
|
|
2521
|
+
if (container.nodeType === 1) container.querySelectorAll("a").forEach((a) => range.intersectsNode(a) ? out.add(a) : null);
|
|
2522
|
+
return [...out];
|
|
2523
|
+
}
|
|
2524
|
+
function cssEscape(value) {
|
|
2525
|
+
var _a;
|
|
2526
|
+
return ((_a = window.CSS) == null ? void 0 : _a.escape) ? CSS.escape(value) : String(value).replace(/["\\]/g, "\\$&");
|
|
2527
|
+
}
|
|
2528
|
+
class History {
|
|
2529
|
+
constructor(root, { limit = 60, delay = 400 } = {}) {
|
|
2530
|
+
this.root = root;
|
|
2531
|
+
this.limit = limit;
|
|
2532
|
+
this.delay = delay;
|
|
2533
|
+
this.stack = [];
|
|
2534
|
+
this.index = -1;
|
|
2535
|
+
this.timer = null;
|
|
2536
|
+
this.locked = false;
|
|
2537
|
+
this.lastHtml = root.innerHTML;
|
|
2538
|
+
}
|
|
2539
|
+
/** 记录当前状态(首个快照不触发 change) */
|
|
2540
|
+
snapshot(immediate = false) {
|
|
2541
|
+
clearTimeout(this.timer);
|
|
2542
|
+
const push = () => {
|
|
2543
|
+
const html = this.root.innerHTML;
|
|
2544
|
+
if (html === this.lastHtml) return;
|
|
2545
|
+
this.lastHtml = html;
|
|
2546
|
+
const point = { html, offset: caretOffset(this.root) };
|
|
2547
|
+
this.stack = this.stack.slice(0, this.index + 1);
|
|
2548
|
+
this.stack.push(point);
|
|
2549
|
+
if (this.stack.length > this.limit) this.stack.shift();
|
|
2550
|
+
this.index = this.stack.length - 1;
|
|
2551
|
+
};
|
|
2552
|
+
if (immediate) push();
|
|
2553
|
+
else this.timer = setTimeout(push, this.delay);
|
|
2554
|
+
}
|
|
2555
|
+
/** 立即落盘挂起的快照 */
|
|
2556
|
+
flush() {
|
|
2557
|
+
clearTimeout(this.timer);
|
|
2558
|
+
this.snapshot(true);
|
|
2559
|
+
}
|
|
2560
|
+
/** 恢复内容但不产生新快照(用于 undo/redo 自身、源码模式应用) */
|
|
2561
|
+
apply(html, offset) {
|
|
2562
|
+
this.locked = true;
|
|
2563
|
+
this.root.innerHTML = html;
|
|
2564
|
+
this.lastHtml = html;
|
|
2565
|
+
if (offset !== void 0 && offset !== null) setCaretOffset(this.root, offset);
|
|
2566
|
+
this.locked = false;
|
|
2567
|
+
}
|
|
2568
|
+
canUndo() {
|
|
2569
|
+
return this.index > 0;
|
|
2570
|
+
}
|
|
2571
|
+
canRedo() {
|
|
2572
|
+
return this.index >= 0 && this.index < this.stack.length - 1;
|
|
2573
|
+
}
|
|
2574
|
+
undo() {
|
|
2575
|
+
if (!this.canUndo()) return false;
|
|
2576
|
+
clearTimeout(this.timer);
|
|
2577
|
+
this.index -= 1;
|
|
2578
|
+
const point = this.stack[this.index];
|
|
2579
|
+
this.apply(point.html, this.currentOffset(point, "undo"));
|
|
2580
|
+
this.lastHtml = point.html;
|
|
2581
|
+
return true;
|
|
2582
|
+
}
|
|
2583
|
+
redo() {
|
|
2584
|
+
if (!this.canRedo()) return false;
|
|
2585
|
+
const point = this.stack[this.index + 1];
|
|
2586
|
+
this.index += 1;
|
|
2587
|
+
this.apply(point.html, this.currentOffset(point, "redo"));
|
|
2588
|
+
this.lastHtml = point.html;
|
|
2589
|
+
return true;
|
|
2590
|
+
}
|
|
2591
|
+
currentOffset(point) {
|
|
2592
|
+
const now = caretOffset(this.root);
|
|
2593
|
+
return now === null ? point.offset : point.offset;
|
|
2594
|
+
}
|
|
2595
|
+
reset(html) {
|
|
2596
|
+
clearTimeout(this.timer);
|
|
2597
|
+
this.stack = [{ html, offset: 0 }];
|
|
2598
|
+
this.index = 0;
|
|
2599
|
+
this.lastHtml = html;
|
|
2600
|
+
}
|
|
2601
|
+
destroy() {
|
|
2602
|
+
clearTimeout(this.timer);
|
|
2603
|
+
this.stack = [];
|
|
2604
|
+
}
|
|
2605
|
+
}
|
|
2606
|
+
const IMAGE_EXT = /\.(jpe?g|png|gif|webp|bmp|svg|avif)$/i;
|
|
2607
|
+
const VIDEO_EXT = /\.(mp4|mov|webm|m4v|ogv|avi|mkv)$/i;
|
|
2608
|
+
class MediaManager {
|
|
2609
|
+
constructor(editor) {
|
|
2610
|
+
this.editor = editor;
|
|
2611
|
+
this.options = editor.options;
|
|
2612
|
+
this.tasks = /* @__PURE__ */ new Map();
|
|
2613
|
+
this.input = null;
|
|
2614
|
+
}
|
|
2615
|
+
kindOf(file) {
|
|
2616
|
+
const type = String(file.type || "");
|
|
2617
|
+
const name = String(file.name || "");
|
|
2618
|
+
if (type.startsWith("image/") || IMAGE_EXT.test(name)) return "image";
|
|
2619
|
+
if (type.startsWith("video/") || VIDEO_EXT.test(name)) return "video";
|
|
2620
|
+
return null;
|
|
2621
|
+
}
|
|
2622
|
+
check(file, kind) {
|
|
2623
|
+
if (!kind) return `不支持的文件类型:${file.name || "剪贴板内容"}`;
|
|
2624
|
+
const limit = kind === "image" ? this.options.maxImageSize : this.options.maxVideoSize;
|
|
2625
|
+
if (limit && file.size > limit) return `${file.name} 超出大小限制(${formatSize(limit)})`;
|
|
2626
|
+
return null;
|
|
2627
|
+
}
|
|
2628
|
+
pickFiles(kind) {
|
|
2629
|
+
if (!this.input) {
|
|
2630
|
+
this.input = h("input", { type: "file", multiple: true, style: { display: "none" } });
|
|
2631
|
+
this.input.addEventListener("change", () => {
|
|
2632
|
+
const files = [...this.input.files || []];
|
|
2633
|
+
this.input.value = "";
|
|
2634
|
+
this.addFiles(files);
|
|
2635
|
+
});
|
|
2636
|
+
document.body.appendChild(this.input);
|
|
2637
|
+
}
|
|
2638
|
+
this.input.accept = kind === "image" ? this.options.imageAccept : this.options.videoAccept;
|
|
2639
|
+
this.input.multiple = kind === "image";
|
|
2640
|
+
this.input.click();
|
|
2641
|
+
}
|
|
2642
|
+
async addFiles(files) {
|
|
2643
|
+
const accepted = [];
|
|
2644
|
+
for (const file of files) {
|
|
2645
|
+
const kind = this.kindOf(file);
|
|
2646
|
+
const error = this.check(file, kind);
|
|
2647
|
+
if (error) this.editor.toast.warn(error);
|
|
2648
|
+
else accepted.push({ file, kind });
|
|
2649
|
+
}
|
|
2650
|
+
for (const item of accepted) await this.upload(item.file, item.kind);
|
|
2651
|
+
return accepted.length;
|
|
2652
|
+
}
|
|
2653
|
+
/** 插入占位并上传,返回结果(失败/取消返回 null) */
|
|
2654
|
+
async upload(file, kind) {
|
|
2655
|
+
const holder = kind === "image" ? this.createImageHolder() : this.createVideoHolder();
|
|
2656
|
+
this.editor.focus();
|
|
2657
|
+
insertNode(this.editor.root, holder);
|
|
2658
|
+
const task = {
|
|
2659
|
+
id: holder.dataset.kId,
|
|
2660
|
+
file,
|
|
2661
|
+
kind,
|
|
2662
|
+
holder,
|
|
2663
|
+
ctrl: new AbortController(),
|
|
2664
|
+
previewUrl: URL.createObjectURL(file)
|
|
2665
|
+
};
|
|
2666
|
+
this.tasks.set(task.id, task);
|
|
2667
|
+
this.decorateHolder(task);
|
|
2668
|
+
const thumb = holder.querySelector("[data-k-preview]");
|
|
2669
|
+
if (thumb) thumb.src = task.previewUrl;
|
|
2670
|
+
return this.runUpload(task);
|
|
2671
|
+
}
|
|
2672
|
+
/** 真正的上传流可重试(复用同一个占位块,保证位置不变) */
|
|
2673
|
+
async runUpload(task) {
|
|
2674
|
+
const editor = this.editor;
|
|
2675
|
+
const { holder, file, kind } = task;
|
|
2676
|
+
editor.emit("uploadstart", { file, kind });
|
|
2677
|
+
editor.refreshStatus();
|
|
2678
|
+
let target = file;
|
|
2679
|
+
try {
|
|
2680
|
+
if (kind === "image") target = await maybeCompress(file, this.options.image);
|
|
2681
|
+
const result = await editor.uploader.upload(target, {
|
|
2682
|
+
signal: task.ctrl.signal,
|
|
2683
|
+
onProgress: (ratio, info) => this.updateProgress(holder, ratio, info, target, task)
|
|
2684
|
+
});
|
|
2685
|
+
const url = typeof result === "string" ? { url: result } : result;
|
|
2686
|
+
if (!(url == null ? void 0 : url.url)) throw new Error("上传结果缺少 url");
|
|
2687
|
+
this.finish(task, { ...url, size: target.size });
|
|
2688
|
+
editor.emit("uploaddone", { file, kind, url: url.url });
|
|
2689
|
+
return url;
|
|
2690
|
+
} catch (error) {
|
|
2691
|
+
if ((error == null ? void 0 : error.name) === "AbortError") {
|
|
2692
|
+
this.remove(task);
|
|
2693
|
+
editor.emit("uploadcancel", { file, kind });
|
|
2694
|
+
return null;
|
|
2695
|
+
}
|
|
2696
|
+
this.fail(task, error);
|
|
2697
|
+
editor.emit("uploaderror", { file, kind, error });
|
|
2698
|
+
editor.toast.error((error == null ? void 0 : error.message) || "上传失败");
|
|
2699
|
+
return null;
|
|
2700
|
+
} finally {
|
|
2701
|
+
ensureEditableTail(editor.root);
|
|
2702
|
+
editor.commitHistory();
|
|
2703
|
+
editor.refreshStatus();
|
|
2704
|
+
}
|
|
2705
|
+
}
|
|
2706
|
+
createImageHolder() {
|
|
2707
|
+
const figure = h("figure", { "data-k-media": "image", "data-k-id": uid("m"), "data-k-state": "uploading", contenteditable: "false" });
|
|
2708
|
+
const holder = h("div.ke-media-holder", {}, [
|
|
2709
|
+
h("img", { "data-k-preview": "", alt: "", style: { display: "none" } }),
|
|
2710
|
+
h("div.ke-media-name", { text: "图片上传中…" }),
|
|
2711
|
+
progressRow()
|
|
2712
|
+
]);
|
|
2713
|
+
holder.appendChild(this.actionRow());
|
|
2714
|
+
figure.appendChild(holder);
|
|
2715
|
+
return figure;
|
|
2716
|
+
}
|
|
2717
|
+
createVideoHolder() {
|
|
2718
|
+
const card = h("div.ke-video-card", { "data-k-media": "video", "data-k-id": uid("m"), "data-k-state": "uploading", contenteditable: "false" });
|
|
2719
|
+
const body = h("div.ke-video-body", {}, [
|
|
2720
|
+
h("div.ke-video-head", {}, [h("span", { text: "视频上传中…" }), h("span.ke-video-size", { text: "" })]),
|
|
2721
|
+
progressRow()
|
|
2722
|
+
]);
|
|
2723
|
+
body.appendChild(this.actionRow());
|
|
2724
|
+
card.appendChild(body);
|
|
2725
|
+
return card;
|
|
2726
|
+
}
|
|
2727
|
+
actionRow() {
|
|
2728
|
+
const self2 = this;
|
|
2729
|
+
return h("div", {
|
|
2730
|
+
"data-k-actions": "",
|
|
2731
|
+
style: { display: "flex", alignItems: "center", gap: "8px", width: "100%", marginTop: "2px" },
|
|
2732
|
+
onclick: (event) => {
|
|
2733
|
+
const holder = event.target.closest("[data-k-id]");
|
|
2734
|
+
const task = holder && self2.tasks.get(holder.dataset.kId);
|
|
2735
|
+
if (!task) return;
|
|
2736
|
+
if (event.target.matches(".ke-media-cancel")) {
|
|
2737
|
+
task.ctrl.abort();
|
|
2738
|
+
self2.remove(task);
|
|
2739
|
+
} else if (event.target.matches(".ke-media-retry")) {
|
|
2740
|
+
task.ctrl = new AbortController();
|
|
2741
|
+
self2.resetHolder(task);
|
|
2742
|
+
self2.runUpload(task);
|
|
2743
|
+
}
|
|
2744
|
+
}
|
|
2745
|
+
}, [h("button.ke-media-cancel", { type: "button", text: "取消" })]);
|
|
2746
|
+
}
|
|
2747
|
+
/** 文件名 / 大小 / 预览图 */
|
|
2748
|
+
decorateHolder(task) {
|
|
2749
|
+
const { holder, file } = task;
|
|
2750
|
+
const name = holder.querySelector(".ke-media-name");
|
|
2751
|
+
if (name) name.textContent = `${file.name || "未命名"}(${formatSize(file.size)})`;
|
|
2752
|
+
const size = holder.querySelector(".ke-video-size");
|
|
2753
|
+
if (size) size.textContent = formatSize(file.size);
|
|
2754
|
+
const head = holder.querySelector(".ke-video-head span");
|
|
2755
|
+
if (head && task.kind === "video") head.textContent = `${file.name || "视频"} 上传中…`;
|
|
2756
|
+
}
|
|
2757
|
+
resetHolder(task) {
|
|
2758
|
+
const holder = task.holder;
|
|
2759
|
+
holder.dataset.kState = "uploading";
|
|
2760
|
+
const bar = holder.querySelector(".ke-progress i");
|
|
2761
|
+
if (bar) {
|
|
2762
|
+
bar.style.width = "0%";
|
|
2763
|
+
bar.style.background = "";
|
|
2764
|
+
}
|
|
2765
|
+
const pct = holder.querySelector(".ke-media-pct");
|
|
2766
|
+
if (pct) pct.textContent = "0%";
|
|
2767
|
+
const actions = holder.querySelector("[data-k-actions]");
|
|
2768
|
+
if (actions) actions.innerHTML = '<button class="ke-media-cancel" type="button">取消</button>';
|
|
2769
|
+
this.decorateHolder(task);
|
|
2770
|
+
}
|
|
2771
|
+
updateProgress(holder, ratio, info, file, task) {
|
|
2772
|
+
const percent = Math.max(0, Math.min(100, Math.round((ratio || 0) * 100)));
|
|
2773
|
+
const bar = holder.querySelector(".ke-progress i");
|
|
2774
|
+
if (bar) bar.style.width = `${percent}%`;
|
|
2775
|
+
const pct = holder.querySelector(".ke-media-pct");
|
|
2776
|
+
if (pct) pct.textContent = `${percent}%`;
|
|
2777
|
+
if (task) this.editor.emit("uploadprogress", { file: task.file, kind: task.kind, percent, info });
|
|
2778
|
+
const meta = holder.querySelector(".ke-media-meta");
|
|
2779
|
+
if (!meta) return;
|
|
2780
|
+
let label = meta.querySelector("[data-k-chunks]");
|
|
2781
|
+
if (!label) {
|
|
2782
|
+
label = h("span", { "data-k-chunks": "", style: { color: "#8a8f99", fontSize: "12px" } });
|
|
2783
|
+
meta.insertBefore(label, meta.firstChild);
|
|
2784
|
+
}
|
|
2785
|
+
if ((info == null ? void 0 : info.chunks) > 1) label.textContent = `${info.chunks} 片 · ${formatSize(info.loaded)}/${formatSize(info.total || file.size)}`;
|
|
2786
|
+
else if (info == null ? void 0 : info.speed) label.textContent = `${formatSize(info.speed)}/s`;
|
|
2787
|
+
}
|
|
2788
|
+
finish(task, result) {
|
|
2789
|
+
const { holder, kind, file } = task;
|
|
2790
|
+
const url = result.url;
|
|
2791
|
+
holder.dataset.kState = "done";
|
|
2792
|
+
holder.dataset.kUrl = url;
|
|
2793
|
+
holder.innerHTML = "";
|
|
2794
|
+
if (kind === "image") {
|
|
2795
|
+
const img = h("img", { src: url, alt: altOf(file), "data-k-name": file.name || "", draggable: "false" });
|
|
2796
|
+
img.addEventListener("dblclick", () => lightbox(img.src));
|
|
2797
|
+
holder.appendChild(img);
|
|
2798
|
+
} else {
|
|
2799
|
+
const video = h("video", { src: url, controls: "", playsinline: "", preload: "metadata", "data-k-name": file.name || "" });
|
|
2800
|
+
const body = h("div.ke-video-body", {}, [
|
|
2801
|
+
h("div.ke-video-head", {}, [h("span", { text: file.name || "视频" }), h("span.ke-video-size", { text: formatSize(result.size || file.size) })]),
|
|
2802
|
+
video
|
|
2803
|
+
]);
|
|
2804
|
+
holder.appendChild(body);
|
|
2805
|
+
}
|
|
2806
|
+
if (task.previewUrl) URL.revokeObjectURL(task.previewUrl);
|
|
2807
|
+
this.tasks.delete(task.id);
|
|
2808
|
+
this.editor.refreshStatus();
|
|
2809
|
+
}
|
|
2810
|
+
fail(task, error) {
|
|
2811
|
+
const holder = task.holder;
|
|
2812
|
+
holder.dataset.kState = "error";
|
|
2813
|
+
const bar = holder.querySelector(".ke-progress i");
|
|
2814
|
+
if (bar) bar.style.background = "#e53e3e";
|
|
2815
|
+
const actions = holder.querySelector("[data-k-actions]");
|
|
2816
|
+
if (actions) {
|
|
2817
|
+
actions.innerHTML = "";
|
|
2818
|
+
actions.appendChild(h("span.ke-media-error", { text: (error == null ? void 0 : error.message) || "上传失败", style: { marginRight: "auto", fontSize: "12px" } }));
|
|
2819
|
+
actions.appendChild(h("button.ke-media-retry", { type: "button", text: "重试" }));
|
|
2820
|
+
actions.appendChild(h("button.ke-media-cancel", { type: "button", text: "移除" }));
|
|
2821
|
+
}
|
|
2822
|
+
}
|
|
2823
|
+
remove(task) {
|
|
2824
|
+
var _a;
|
|
2825
|
+
(_a = task.holder) == null ? void 0 : _a.remove();
|
|
2826
|
+
if (task.previewUrl) URL.revokeObjectURL(task.previewUrl);
|
|
2827
|
+
this.tasks.delete(task.id);
|
|
2828
|
+
ensureEditableTail(this.editor.root);
|
|
2829
|
+
this.editor.refreshStatus();
|
|
2830
|
+
}
|
|
2831
|
+
/** 从 DOM 节点找到对应任务(用于气泡工具条删除) */
|
|
2832
|
+
taskFromNode(node) {
|
|
2833
|
+
var _a;
|
|
2834
|
+
const holder = (_a = node == null ? void 0 : node.closest) == null ? void 0 : _a.call(node, "[data-k-id]");
|
|
2835
|
+
return holder ? this.tasks.get(holder.dataset.kId) : null;
|
|
2836
|
+
}
|
|
2837
|
+
cancelAll() {
|
|
2838
|
+
for (const task of [...this.tasks.values()]) {
|
|
2839
|
+
task.ctrl.abort();
|
|
2840
|
+
this.remove(task);
|
|
2841
|
+
}
|
|
2842
|
+
}
|
|
2843
|
+
/** 从网络链接插入(工具栏「网络链接」入口) */
|
|
2844
|
+
insertFromUrl(kind, url, name = "") {
|
|
2845
|
+
const node = kind === "image" ? this.insertImageUrl(url, name) : this.insertVideoUrl(url, name || "网络视频");
|
|
2846
|
+
this.editor.toast.ok(kind === "image" ? "已插入网络图片" : "已插入网络视频");
|
|
2847
|
+
this.editor.emit("insertmedia", { kind, url, node });
|
|
2848
|
+
return node;
|
|
2849
|
+
}
|
|
2850
|
+
insertImageUrl(url, alt = "") {
|
|
2851
|
+
const img = h("img", { src: url, alt: alt || "", draggable: "false" });
|
|
2852
|
+
img.addEventListener("dblclick", () => lightbox(img.src));
|
|
2853
|
+
const figure = h("figure", { "data-k-media": "image", "data-k-state": "done", "data-k-url": url, contenteditable: "false" }, [img]);
|
|
2854
|
+
insertNode(this.editor.root, figure);
|
|
2855
|
+
this.editor.commitHistory();
|
|
2856
|
+
return figure;
|
|
2857
|
+
}
|
|
2858
|
+
insertVideoUrl(url, label = "视频") {
|
|
2859
|
+
const video = h("video", { src: url, controls: "", playsinline: "", preload: "metadata" });
|
|
2860
|
+
const card = h("div.ke-video-card", { "data-k-media": "video", "data-k-state": "done", "data-k-url": url, contenteditable: "false" }, [
|
|
2861
|
+
h("div.ke-video-body", {}, [h("div.ke-video-head", {}, [h("span", { text: label })]), video])
|
|
2862
|
+
]);
|
|
2863
|
+
insertNode(this.editor.root, card);
|
|
2864
|
+
this.editor.commitHistory();
|
|
2865
|
+
return card;
|
|
2866
|
+
}
|
|
2867
|
+
destroy() {
|
|
2868
|
+
var _a;
|
|
2869
|
+
this.cancelAll();
|
|
2870
|
+
(_a = this.input) == null ? void 0 : _a.remove();
|
|
2871
|
+
this.input = null;
|
|
2872
|
+
}
|
|
2873
|
+
}
|
|
2874
|
+
function altOf(file) {
|
|
2875
|
+
return String(file.name || "").replace(/\.[^.]+$/, "");
|
|
2876
|
+
}
|
|
2877
|
+
function progressRow() {
|
|
2878
|
+
return h("div.ke-media-meta", {}, [h("div.ke-progress", {}, [h("i", { style: { width: "0%" } })]), h("span.ke-media-pct", { text: "0%" })]);
|
|
2879
|
+
}
|
|
2880
|
+
async function maybeCompress(file, options = {}) {
|
|
2881
|
+
var _a, _b;
|
|
2882
|
+
const compress = options == null ? void 0 : options.compress;
|
|
2883
|
+
if (!compress || !/^image\/(jpeg|jpg|png|webp)$/i.test(file.type)) return file;
|
|
2884
|
+
const { maxWidth = 1440, quality = 0.85, minSize = 300 * 1024 } = typeof compress === "object" ? compress : {};
|
|
2885
|
+
if (file.size < minSize) return file;
|
|
2886
|
+
try {
|
|
2887
|
+
const bitmap = await createImageBitmap(file);
|
|
2888
|
+
if (bitmap.width <= maxWidth) {
|
|
2889
|
+
(_a = bitmap.close) == null ? void 0 : _a.call(bitmap);
|
|
2890
|
+
return file;
|
|
2891
|
+
}
|
|
2892
|
+
const canvas = document.createElement("canvas");
|
|
2893
|
+
canvas.width = maxWidth;
|
|
2894
|
+
canvas.height = Math.round(bitmap.height * maxWidth / bitmap.width);
|
|
2895
|
+
canvas.getContext("2d").drawImage(bitmap, 0, 0, canvas.width, canvas.height);
|
|
2896
|
+
(_b = bitmap.close) == null ? void 0 : _b.call(bitmap);
|
|
2897
|
+
const blob = await new Promise((resolve) => canvas.toBlob(resolve, "image/jpeg", quality));
|
|
2898
|
+
if (!blob || blob.size >= file.size) return file;
|
|
2899
|
+
return new File([blob], String(file.name).replace(/\.\w+$/, ".jpg"), { type: "image/jpeg", lastModified: file.lastModified });
|
|
2900
|
+
} catch {
|
|
2901
|
+
return file;
|
|
2902
|
+
}
|
|
2903
|
+
}
|
|
2904
|
+
function fastFingerprint(file) {
|
|
2905
|
+
return `${sizeHex(file.size)}-${stampHex(file.lastModified)}-${safeName(file.name)}`;
|
|
2906
|
+
}
|
|
2907
|
+
async function strongFingerprint(file) {
|
|
2908
|
+
var _a;
|
|
2909
|
+
if (!((_a = globalThis.crypto) == null ? void 0 : _a.subtle)) return fastFingerprint(file);
|
|
2910
|
+
const span = 256 * 1024;
|
|
2911
|
+
const parts = [file.slice(0, span)];
|
|
2912
|
+
if (file.size > span) parts.push(file.slice(file.size - span));
|
|
2913
|
+
const buf = new Uint8Array(parts.reduce((sum, blob) => sum + blob.size, 0));
|
|
2914
|
+
let offset = 0;
|
|
2915
|
+
for (const blob of parts) {
|
|
2916
|
+
const chunk = new Uint8Array(await blob.arrayBuffer());
|
|
2917
|
+
buf.set(chunk, offset);
|
|
2918
|
+
offset += chunk.length;
|
|
2919
|
+
}
|
|
2920
|
+
const digest = await crypto.subtle.digest("SHA-256", buf);
|
|
2921
|
+
const hex = Array.from(new Uint8Array(digest)).map((b) => b.toString(16).padStart(2, "0")).join("");
|
|
2922
|
+
return `${hex.slice(0, 24)}-${sizeHex(file.size)}`;
|
|
2923
|
+
}
|
|
2924
|
+
const sizeHex = (size) => Number(size).toString(16);
|
|
2925
|
+
const stampHex = (ts) => Number(ts || 0).toString(16);
|
|
2926
|
+
const safeName = (name) => String(name).replace(/[^\w.-]/g, "").slice(0, 24);
|
|
2927
|
+
function createFingerprint(mode = "fast") {
|
|
2928
|
+
if (mode === "strong" || mode === "sha256") return strongFingerprint;
|
|
2929
|
+
if (typeof mode === "function") return mode;
|
|
2930
|
+
return async (file) => fastFingerprint(file);
|
|
2931
|
+
}
|
|
2932
|
+
const MB$1 = 1024 * 1024;
|
|
2933
|
+
class ChunkUploader {
|
|
2934
|
+
constructor(adapter, options = {}) {
|
|
2935
|
+
if (!adapter || typeof adapter.put !== "function") {
|
|
2936
|
+
throw new Error("[KEditor] uploader 需要提供 put() 方法,参见 docs/upload-adapter.md");
|
|
2937
|
+
}
|
|
2938
|
+
this.adapter = adapter;
|
|
2939
|
+
this.chunkSize = Math.max(64 * 1024, options.chunkSize || MB$1);
|
|
2940
|
+
this.concurrency = Math.max(1, options.concurrency || 3);
|
|
2941
|
+
this.retries = options.retries === void 0 ? 2 : Math.max(0, options.retries);
|
|
2942
|
+
this.retryDelay = options.retryDelay ?? 600;
|
|
2943
|
+
this.fingerprint = createFingerprint(options.fingerprint || "fast");
|
|
2944
|
+
this.slice = options.slice;
|
|
2945
|
+
}
|
|
2946
|
+
/**
|
|
2947
|
+
* @param {File|Blob} file
|
|
2948
|
+
* @param {{onProgress?,onChunk?,onInfo?,signal?}} handlers
|
|
2949
|
+
* @returns {Promise<{url:string, instant?:boolean, chunks:number, size:number, name:string}>}
|
|
2950
|
+
*/
|
|
2951
|
+
async upload(file, handlers = {}) {
|
|
2952
|
+
var _a, _b, _c, _d, _e, _f;
|
|
2953
|
+
const { onProgress, onChunk, signal } = handlers;
|
|
2954
|
+
if (this.adapter.simple) return this.uploadSimple(file, handlers);
|
|
2955
|
+
const total = Math.max(1, Math.ceil(file.size / this.chunkSize));
|
|
2956
|
+
const meta = {
|
|
2957
|
+
name: file.name || "blob",
|
|
2958
|
+
size: file.size,
|
|
2959
|
+
type: file.type || guessType(file.name),
|
|
2960
|
+
lastModified: file.lastModified || 0,
|
|
2961
|
+
fingerprint: await this.fingerprint(file),
|
|
2962
|
+
chunkSize: this.chunkSize,
|
|
2963
|
+
totalChunks: total
|
|
2964
|
+
};
|
|
2965
|
+
const init = await ((_b = (_a = this.adapter).init) == null ? void 0 : _b.call(_a, meta, { signal })) || {};
|
|
2966
|
+
if (init.url) {
|
|
2967
|
+
onProgress == null ? void 0 : onProgress(1, { percent: 100, loaded: file.size, total: file.size, chunks: total, instant: true });
|
|
2968
|
+
return { url: init.url, instant: true, chunks: 0, size: file.size, name: meta.name, key: init.key };
|
|
2969
|
+
}
|
|
2970
|
+
const uploadId = init.uploadId || meta.fingerprint;
|
|
2971
|
+
const uploaded = new Set((init.uploadedChunks || init.uploaded || []).map(Number));
|
|
2972
|
+
let loadedBytes = 0;
|
|
2973
|
+
for (const index of uploaded) loadedBytes += Math.min(this.chunkSize, file.size - index * this.chunkSize);
|
|
2974
|
+
const queue = [];
|
|
2975
|
+
for (let i = 0; i < total; i += 1) if (!uploaded.has(i)) queue.push(i);
|
|
2976
|
+
const chunkResults = new Array(total);
|
|
2977
|
+
let doneChunks = uploaded.size;
|
|
2978
|
+
const startedAt = Date.now();
|
|
2979
|
+
const report = () => {
|
|
2980
|
+
const elapsed = (Date.now() - startedAt) / 1e3;
|
|
2981
|
+
onProgress == null ? void 0 : onProgress(file.size ? loadedBytes / file.size : 1, {
|
|
2982
|
+
percent: Math.min(100, Math.round(loadedBytes / Math.max(1, file.size) * 100)),
|
|
2983
|
+
loaded: loadedBytes,
|
|
2984
|
+
total: file.size,
|
|
2985
|
+
chunks: total,
|
|
2986
|
+
uploadedChunks: doneChunks,
|
|
2987
|
+
speed: elapsed > 0 ? loadedBytes / elapsed : 0
|
|
2988
|
+
});
|
|
2989
|
+
};
|
|
2990
|
+
report();
|
|
2991
|
+
let cursor = 0;
|
|
2992
|
+
let firstError = null;
|
|
2993
|
+
const worker = async () => {
|
|
2994
|
+
while (cursor < queue.length) {
|
|
2995
|
+
if (signal == null ? void 0 : signal.aborted) throw new DOMException("已取消上传", "AbortError");
|
|
2996
|
+
const index = queue[cursor++];
|
|
2997
|
+
const blob = this.slice ? this.slice(file, index, this.chunkSize) : file.slice(index * this.chunkSize, (index + 1) * this.chunkSize);
|
|
2998
|
+
let attempt = 0;
|
|
2999
|
+
for (; ; ) {
|
|
3000
|
+
try {
|
|
3001
|
+
const res = await this.adapter.put({
|
|
3002
|
+
uploadId,
|
|
3003
|
+
index,
|
|
3004
|
+
total,
|
|
3005
|
+
chunkSize: this.chunkSize,
|
|
3006
|
+
blob,
|
|
3007
|
+
file,
|
|
3008
|
+
meta,
|
|
3009
|
+
signal,
|
|
3010
|
+
size: blob.size
|
|
3011
|
+
});
|
|
3012
|
+
if (res == null ? void 0 : res.url) chunkResults[index] = res;
|
|
3013
|
+
loadedBytes += blob.size;
|
|
3014
|
+
doneChunks += 1;
|
|
3015
|
+
onChunk == null ? void 0 : onChunk({ index, total, size: blob.size });
|
|
3016
|
+
report();
|
|
3017
|
+
break;
|
|
3018
|
+
} catch (error) {
|
|
3019
|
+
if ((error == null ? void 0 : error.name) === "AbortError") throw error;
|
|
3020
|
+
attempt += 1;
|
|
3021
|
+
if (attempt > this.retries) {
|
|
3022
|
+
firstError = error;
|
|
3023
|
+
throw new Error(`分片 ${index + 1}/${total} 上传失败:${(error == null ? void 0 : error.message) || error}`);
|
|
3024
|
+
}
|
|
3025
|
+
await sleep$1(this.retryDelay * attempt, signal);
|
|
3026
|
+
}
|
|
3027
|
+
}
|
|
3028
|
+
}
|
|
3029
|
+
};
|
|
3030
|
+
const workers = Array.from({ length: Math.max(1, Math.min(this.concurrency, queue.length)) }, worker);
|
|
3031
|
+
try {
|
|
3032
|
+
await Promise.all(workers);
|
|
3033
|
+
} catch (error) {
|
|
3034
|
+
await ((_d = (_c = this.adapter).abort) == null ? void 0 : _d.call(_c, { uploadId, meta, error }).catch(() => {
|
|
3035
|
+
}));
|
|
3036
|
+
throw error;
|
|
3037
|
+
}
|
|
3038
|
+
if (firstError) throw firstError;
|
|
3039
|
+
const done = await ((_f = (_e = this.adapter).complete) == null ? void 0 : _f.call(_e, { uploadId, meta, total, uploaded: doneChunks, chunkResults, file })) || {};
|
|
3040
|
+
const url = done.url;
|
|
3041
|
+
if (!url) throw new Error("[KEditor] uploader.complete() 未返回 url");
|
|
3042
|
+
return { url, chunks: total, size: file.size, name: meta.name, key: done.key, poster: done.poster, duration: done.duration, raw: done };
|
|
3043
|
+
}
|
|
3044
|
+
/** 单请求直传(不切片),供对接已有单次上传接口时使用 */
|
|
3045
|
+
async uploadSimple(file, handlers = {}) {
|
|
3046
|
+
const { onProgress, signal } = handlers;
|
|
3047
|
+
const startedAt = Date.now();
|
|
3048
|
+
const result = await this.adapter.upload(file, {
|
|
3049
|
+
signal,
|
|
3050
|
+
onProgress: (loaded, total) => {
|
|
3051
|
+
const ratio = total ? loaded / total : 0;
|
|
3052
|
+
const elapsed = (Date.now() - startedAt) / 1e3;
|
|
3053
|
+
onProgress == null ? void 0 : onProgress(ratio, { percent: Math.round(ratio * 100), loaded, total: total || file.size, chunks: 1, uploadedChunks: ratio >= 1 ? 1 : 0, speed: elapsed > 0 ? loaded / elapsed : 0 });
|
|
3054
|
+
}
|
|
3055
|
+
});
|
|
3056
|
+
const url = typeof result === "string" ? result : result == null ? void 0 : result.url;
|
|
3057
|
+
if (!url) throw new Error("[KEditor] uploader.upload() 未返回 url");
|
|
3058
|
+
return { url, chunks: 1, size: file.size, name: file.name, key: typeof result === "object" ? result.key : void 0, raw: result };
|
|
3059
|
+
}
|
|
3060
|
+
destroy() {
|
|
3061
|
+
var _a, _b;
|
|
3062
|
+
(_b = (_a = this.adapter).destroy) == null ? void 0 : _b.call(_a);
|
|
3063
|
+
}
|
|
3064
|
+
}
|
|
3065
|
+
const sleep$1 = (ms, signal) => new Promise((resolve, reject) => {
|
|
3066
|
+
const timer = setTimeout(() => {
|
|
3067
|
+
signal == null ? void 0 : signal.removeEventListener("abort", onAbort);
|
|
3068
|
+
resolve();
|
|
3069
|
+
}, ms);
|
|
3070
|
+
const onAbort = () => {
|
|
3071
|
+
clearTimeout(timer);
|
|
3072
|
+
reject(new DOMException("已取消上传", "AbortError"));
|
|
3073
|
+
};
|
|
3074
|
+
signal == null ? void 0 : signal.addEventListener("abort", onAbort, { once: true });
|
|
3075
|
+
});
|
|
3076
|
+
function guessType(name = "") {
|
|
3077
|
+
var _a;
|
|
3078
|
+
const ext = (_a = String(name).split(".").pop()) == null ? void 0 : _a.toLowerCase();
|
|
3079
|
+
const map = { jpg: "image/jpeg", jpeg: "image/jpeg", png: "image/png", gif: "image/gif", webp: "image/webp", svg: "image/svg+xml", mp4: "video/mp4", mov: "video/quicktime", webm: "video/webm", m4v: "video/x-m4v" };
|
|
3080
|
+
return map[ext] || "application/octet-stream";
|
|
3081
|
+
}
|
|
3082
|
+
function simpleAdapter(fn) {
|
|
3083
|
+
return {
|
|
3084
|
+
simple: true,
|
|
3085
|
+
async upload(file, ctx = {}) {
|
|
3086
|
+
const res = await fn(toFile(file), ctx);
|
|
3087
|
+
return typeof res === "string" ? { url: res } : res;
|
|
3088
|
+
}
|
|
3089
|
+
};
|
|
3090
|
+
}
|
|
3091
|
+
function toFile(blob, name = "blob", type = blob.type) {
|
|
3092
|
+
if (blob instanceof File) return blob;
|
|
3093
|
+
return new File([blob], name, { type });
|
|
3094
|
+
}
|
|
3095
|
+
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
3096
|
+
const jitter = (base, ratio = 0.4) => base * (1 - ratio + Math.random() * ratio * 2);
|
|
3097
|
+
function mockAdapter(options = {}) {
|
|
3098
|
+
const {
|
|
3099
|
+
latency = 160,
|
|
3100
|
+
// 每个分片的固定网络往返(ms)
|
|
3101
|
+
speed = 12,
|
|
3102
|
+
// 模拟带宽 MB/s
|
|
3103
|
+
onEvent = null,
|
|
3104
|
+
// (type, payload) => void,演示面板可打印日志
|
|
3105
|
+
reuseObjectUrl = true,
|
|
3106
|
+
failFirstChunk = false
|
|
3107
|
+
// 打开后可直观看到自动重试效果
|
|
3108
|
+
} = options;
|
|
3109
|
+
const finished = /* @__PURE__ */ new Map();
|
|
3110
|
+
const sessions = /* @__PURE__ */ new Map();
|
|
3111
|
+
const objectUrls = /* @__PURE__ */ new Map();
|
|
3112
|
+
let failOnce = failFirstChunk;
|
|
3113
|
+
const emit = (type, payload) => onEvent == null ? void 0 : onEvent(type, { ...payload, at: Date.now() });
|
|
3114
|
+
return {
|
|
3115
|
+
name: "mock",
|
|
3116
|
+
async init(meta) {
|
|
3117
|
+
emit("init", meta);
|
|
3118
|
+
await sleep(120);
|
|
3119
|
+
const hit = finished.get(meta.fingerprint);
|
|
3120
|
+
if (hit) {
|
|
3121
|
+
emit("instant", { name: meta.name, url: hit.url });
|
|
3122
|
+
return { url: hit.url, key: meta.fingerprint, instant: true };
|
|
3123
|
+
}
|
|
3124
|
+
const session = sessions.get(meta.fingerprint) || /* @__PURE__ */ new Set();
|
|
3125
|
+
sessions.set(meta.fingerprint, session);
|
|
3126
|
+
return { uploadId: meta.fingerprint, uploadedChunks: [...session] };
|
|
3127
|
+
},
|
|
3128
|
+
async put({ uploadId, index, total, size, blob }) {
|
|
3129
|
+
if (failOnce && index === 0) {
|
|
3130
|
+
failOnce = false;
|
|
3131
|
+
emit("chunk-error", { index, total, message: "mock: 模拟首个分片网络异常" });
|
|
3132
|
+
const error = new Error("mock: 模拟首个分片网络异常");
|
|
3133
|
+
error.retryable = true;
|
|
3134
|
+
throw error;
|
|
3135
|
+
}
|
|
3136
|
+
const cost = Math.max(40, jitter(latency + size / (speed * 1024 / 8) / 8, 0.35));
|
|
3137
|
+
await sleep(cost);
|
|
3138
|
+
const session = sessions.get(uploadId) || /* @__PURE__ */ new Set();
|
|
3139
|
+
session.add(index);
|
|
3140
|
+
sessions.set(uploadId, session);
|
|
3141
|
+
emit("chunk", { index, total, size, blobSize: blob == null ? void 0 : blob.size });
|
|
3142
|
+
return { etag: `${uploadId}-${index}` };
|
|
3143
|
+
},
|
|
3144
|
+
async complete({ uploadId, meta, file }) {
|
|
3145
|
+
await sleep(140);
|
|
3146
|
+
let url = objectUrls.get(meta.fingerprint);
|
|
3147
|
+
if (!url || !reuseObjectUrl) {
|
|
3148
|
+
const blob = file instanceof File ? file : new File([file], meta.name, { type: meta.type });
|
|
3149
|
+
url = URL.createObjectURL(blob);
|
|
3150
|
+
objectUrls.set(meta.fingerprint, url);
|
|
3151
|
+
}
|
|
3152
|
+
finished.set(meta.fingerprint, { url, name: meta.name, size: meta.size, type: meta.type });
|
|
3153
|
+
sessions.delete(uploadId);
|
|
3154
|
+
emit("complete", { name: meta.name, url, chunks: meta.totalChunks, size: meta.size });
|
|
3155
|
+
return { url, key: meta.fingerprint };
|
|
3156
|
+
},
|
|
3157
|
+
async abort({ uploadId }) {
|
|
3158
|
+
emit("abort", { uploadId });
|
|
3159
|
+
},
|
|
3160
|
+
/** 已完成的上传记录(演示用) */
|
|
3161
|
+
list: () => [...finished.entries()].map(([key, value]) => ({ key, ...value })),
|
|
3162
|
+
reset: () => {
|
|
3163
|
+
finished.clear();
|
|
3164
|
+
sessions.clear();
|
|
3165
|
+
}
|
|
3166
|
+
};
|
|
3167
|
+
}
|
|
3168
|
+
function httpAdapter(config = {}) {
|
|
3169
|
+
const {
|
|
3170
|
+
initUrl,
|
|
3171
|
+
chunkUrl,
|
|
3172
|
+
completeUrl,
|
|
3173
|
+
abortUrl,
|
|
3174
|
+
mode = "raw",
|
|
3175
|
+
fieldName = "file",
|
|
3176
|
+
headers = {},
|
|
3177
|
+
withCredentials = false,
|
|
3178
|
+
parse = (json) => (json == null ? void 0 : json.data) || json || {},
|
|
3179
|
+
chunkUrlFor
|
|
3180
|
+
} = config;
|
|
3181
|
+
const headerOf = () => typeof headers === "function" ? headers() || {} : headers || {};
|
|
3182
|
+
const request = async (url, init = {}) => {
|
|
3183
|
+
const res = await fetch(url, { credentials: withCredentials ? "include" : "same-origin", ...init });
|
|
3184
|
+
if (!res.ok) throw new Error(`HTTP ${res.status} ${res.statusText}`);
|
|
3185
|
+
const text = await res.text();
|
|
3186
|
+
if (!text) return {};
|
|
3187
|
+
try {
|
|
3188
|
+
return parse(JSON.parse(text));
|
|
3189
|
+
} catch {
|
|
3190
|
+
throw new Error(`服务端返回非 JSON 数据:${text.slice(0, 80)}`);
|
|
3191
|
+
}
|
|
3192
|
+
};
|
|
3193
|
+
return {
|
|
3194
|
+
name: "http",
|
|
3195
|
+
async init(meta, { signal }) {
|
|
3196
|
+
if (!initUrl) throw new Error("[KEditor] httpAdapter 缺少 initUrl");
|
|
3197
|
+
return request(
|
|
3198
|
+
initUrl,
|
|
3199
|
+
{
|
|
3200
|
+
method: "POST",
|
|
3201
|
+
signal,
|
|
3202
|
+
headers: { "Content-Type": "application/json", ...headerOf() },
|
|
3203
|
+
body: JSON.stringify({
|
|
3204
|
+
fileName: meta.name,
|
|
3205
|
+
fileSize: meta.size,
|
|
3206
|
+
fileType: meta.type,
|
|
3207
|
+
lastModified: meta.lastModified,
|
|
3208
|
+
identifier: meta.fingerprint,
|
|
3209
|
+
chunkSize: meta.chunkSize,
|
|
3210
|
+
totalChunks: meta.totalChunks
|
|
3211
|
+
})
|
|
3212
|
+
}
|
|
3213
|
+
);
|
|
3214
|
+
},
|
|
3215
|
+
async put({ uploadId, index, total, blob, meta, signal }) {
|
|
3216
|
+
if (!chunkUrl) throw new Error("[KEditor] httpAdapter 缺少 chunkUrl");
|
|
3217
|
+
const url = typeof chunkUrlFor === "function" ? chunkUrlFor({ uploadId, index }) : chunkUrl;
|
|
3218
|
+
if (mode === "formdata") {
|
|
3219
|
+
const form = new FormData();
|
|
3220
|
+
form.append(fieldName, blob, `${meta.name}.part${index}`);
|
|
3221
|
+
form.append("uploadId", uploadId);
|
|
3222
|
+
form.append("identifier", meta.fingerprint);
|
|
3223
|
+
form.append("index", String(index));
|
|
3224
|
+
form.append("total", String(total));
|
|
3225
|
+
form.append("filename", meta.name);
|
|
3226
|
+
return request(url, { method: "POST", body: form, signal, headers: headerOf() });
|
|
3227
|
+
}
|
|
3228
|
+
const joiner = url.includes("?") ? "&" : "?";
|
|
3229
|
+
const target = `${url}${joiner}uploadId=${encodeURIComponent(uploadId)}&index=${index}&total=${total}&filename=${encodeURIComponent(meta.name)}`;
|
|
3230
|
+
return request(target, {
|
|
3231
|
+
method: "PUT",
|
|
3232
|
+
body: blob,
|
|
3233
|
+
signal,
|
|
3234
|
+
headers: { "Content-Type": "application/octet-stream", "X-Chunk-Index": String(index), ...headerOf() }
|
|
3235
|
+
});
|
|
3236
|
+
},
|
|
3237
|
+
async complete({ uploadId, meta, total }) {
|
|
3238
|
+
if (!completeUrl) throw new Error("[KEditor] httpAdapter 缺少 completeUrl");
|
|
3239
|
+
return request(
|
|
3240
|
+
completeUrl,
|
|
3241
|
+
{
|
|
3242
|
+
method: "POST",
|
|
3243
|
+
headers: { "Content-Type": "application/json", ...headerOf() },
|
|
3244
|
+
body: JSON.stringify({ uploadId, identifier: meta.fingerprint, fileName: meta.name, fileSize: meta.size, fileType: meta.type, chunkSize: meta.chunkSize, totalChunks: total })
|
|
3245
|
+
}
|
|
3246
|
+
);
|
|
3247
|
+
},
|
|
3248
|
+
async abort({ uploadId }) {
|
|
3249
|
+
if (!abortUrl) return;
|
|
3250
|
+
await request(abortUrl, { method: "POST", headers: { "Content-Type": "application/json", ...headerOf() }, body: JSON.stringify({ uploadId }) }).catch(() => {
|
|
3251
|
+
});
|
|
3252
|
+
}
|
|
3253
|
+
};
|
|
3254
|
+
}
|
|
3255
|
+
function createUploader(option = "mock", config = {}) {
|
|
3256
|
+
if (option instanceof ChunkUploader) return option;
|
|
3257
|
+
if (typeof option === "function" && !option.put) return new ChunkUploader(simpleAdapter(option), config);
|
|
3258
|
+
if (option && typeof option === "object" && !(option instanceof ChunkUploader)) {
|
|
3259
|
+
if (typeof option.put === "function" || typeof option.upload === "function") return new ChunkUploader(option, { ...config, ...pick(option) });
|
|
3260
|
+
if (option.type === "http") return new ChunkUploader(httpAdapter(option), { ...config, ...pick(option) });
|
|
3261
|
+
}
|
|
3262
|
+
return new ChunkUploader(mockAdapter(typeof option === "object" ? option : {}), config);
|
|
3263
|
+
}
|
|
3264
|
+
const pick = (obj) => {
|
|
3265
|
+
const out = {};
|
|
3266
|
+
for (const key of ["chunkSize", "concurrency", "retries", "fingerprint"]) if (obj[key] !== void 0) out[key] = obj[key];
|
|
3267
|
+
return out;
|
|
3268
|
+
};
|
|
3269
|
+
function attachPaste(editor) {
|
|
3270
|
+
editor.root.addEventListener("paste", async (event) => {
|
|
3271
|
+
if (editor.readOnly || !editor.options.paste.enabled) return;
|
|
3272
|
+
const dt = event.clipboardData;
|
|
3273
|
+
if (!dt) return;
|
|
3274
|
+
event.preventDefault();
|
|
3275
|
+
const files = filesFromDataTransfer(dt);
|
|
3276
|
+
if (files.length) {
|
|
3277
|
+
if (editor.options.paste.uploadFiles) {
|
|
3278
|
+
await editor.media.addFiles(files);
|
|
3279
|
+
editor.toast.show(`已上传 ${files.length} 个文件`);
|
|
3280
|
+
} else {
|
|
3281
|
+
editor.toast.warn("当前配置不允许粘贴上传文件");
|
|
3282
|
+
}
|
|
3283
|
+
return;
|
|
3284
|
+
}
|
|
3285
|
+
const html = dt.getData("text/html");
|
|
3286
|
+
const text = dt.getData("text/plain");
|
|
3287
|
+
if (html && editor.options.paste.clean) {
|
|
3288
|
+
let clean = isWordHtml(html) ? cleanWordHtml(html) : html;
|
|
3289
|
+
clean = sanitizeHtml(clean, { allowEmpty: true });
|
|
3290
|
+
if (editor.options.paste.localizeImages) clean = await localizeImages(editor, clean);
|
|
3291
|
+
editor.commands.insertHTML(clean, { clean: false });
|
|
3292
|
+
if (isWordHtml(html)) editor.toast.show("已清理 Word/WPS 格式");
|
|
3293
|
+
} else if (text) {
|
|
3294
|
+
const htmlText = text.split(/\r?\n/).map((line) => `<p>${escapeHtml(line) || "<br>"}</p>`).join("");
|
|
3295
|
+
editor.commands.insertHTML(htmlText, { clean: false });
|
|
3296
|
+
}
|
|
3297
|
+
});
|
|
3298
|
+
}
|
|
3299
|
+
function filesFromDataTransfer(dt) {
|
|
3300
|
+
var _a, _b;
|
|
3301
|
+
const out = [];
|
|
3302
|
+
if ((_a = dt.items) == null ? void 0 : _a.length) {
|
|
3303
|
+
for (const item of dt.items) {
|
|
3304
|
+
if (item.kind === "file") {
|
|
3305
|
+
const file = item.getAsFile();
|
|
3306
|
+
if (file) out.push(normalizePastedFile(file, out.length));
|
|
3307
|
+
}
|
|
3308
|
+
}
|
|
3309
|
+
}
|
|
3310
|
+
if (!out.length && ((_b = dt.files) == null ? void 0 : _b.length)) out.push(...Array.from(dt.files).map((file, i) => normalizePastedFile(file, i)));
|
|
3311
|
+
return out;
|
|
3312
|
+
}
|
|
3313
|
+
function normalizePastedFile(file, index) {
|
|
3314
|
+
if (file.name && file.name !== "image.png") return file;
|
|
3315
|
+
const ext = (file.type.split("/")[1] || "png").replace("jpeg", "jpg").replace("+xml", "");
|
|
3316
|
+
const stamp = (/* @__PURE__ */ new Date()).toISOString().slice(11, 19).replace(/:/g, "");
|
|
3317
|
+
return new File([file], `pasted-${stamp}-${index}.${ext}`, { type: file.type, lastModified: file.lastModified });
|
|
3318
|
+
}
|
|
3319
|
+
function attachDrop(editor) {
|
|
3320
|
+
const zone = editor.root;
|
|
3321
|
+
let depth = 0;
|
|
3322
|
+
const hasFiles = (event) => {
|
|
3323
|
+
var _a;
|
|
3324
|
+
return Array.from(((_a = event.dataTransfer) == null ? void 0 : _a.types) || []).includes("Files");
|
|
3325
|
+
};
|
|
3326
|
+
zone.addEventListener("dragenter", (event) => {
|
|
3327
|
+
if (!hasFiles(event) || editor.readOnly) return;
|
|
3328
|
+
event.preventDefault();
|
|
3329
|
+
depth += 1;
|
|
3330
|
+
editor.el.classList.add("ke-is-dragover");
|
|
3331
|
+
});
|
|
3332
|
+
zone.addEventListener("dragover", (event) => {
|
|
3333
|
+
if (!hasFiles(event) || editor.readOnly) return;
|
|
3334
|
+
event.preventDefault();
|
|
3335
|
+
event.dataTransfer.dropEffect = "copy";
|
|
3336
|
+
});
|
|
3337
|
+
zone.addEventListener("dragleave", (event) => {
|
|
3338
|
+
if (!hasFiles(event)) return;
|
|
3339
|
+
depth = Math.max(0, depth - 1);
|
|
3340
|
+
if (depth === 0) editor.el.classList.remove("ke-is-dragover");
|
|
3341
|
+
});
|
|
3342
|
+
zone.addEventListener("drop", async (event) => {
|
|
3343
|
+
if (!hasFiles(event) || editor.readOnly) return;
|
|
3344
|
+
event.preventDefault();
|
|
3345
|
+
depth = 0;
|
|
3346
|
+
editor.el.classList.remove("ke-is-dragover");
|
|
3347
|
+
placeCaretAtPoint(editor, event);
|
|
3348
|
+
const files = [...event.dataTransfer.files || []];
|
|
3349
|
+
if (!files.length) return;
|
|
3350
|
+
if (editor.options.paste.uploadFiles) {
|
|
3351
|
+
const count = await editor.media.addFiles(files);
|
|
3352
|
+
if (count) editor.toast.show(`已上传 ${count} 个文件`);
|
|
3353
|
+
}
|
|
3354
|
+
});
|
|
3355
|
+
}
|
|
3356
|
+
function placeCaretAtPoint(editor, event) {
|
|
3357
|
+
let range = null;
|
|
3358
|
+
if (document.caretRangeFromPoint) range = document.caretRangeFromPoint(event.clientX, event.clientY);
|
|
3359
|
+
else if (document.caretPositionFromPoint) {
|
|
3360
|
+
const pos = document.caretPositionFromPoint(event.clientX, event.clientY);
|
|
3361
|
+
if (pos) {
|
|
3362
|
+
range = document.createRange();
|
|
3363
|
+
range.setStart(pos.offsetNode, pos.offset);
|
|
3364
|
+
range.collapse(true);
|
|
3365
|
+
}
|
|
3366
|
+
}
|
|
3367
|
+
if (range && editor.root.contains(range.commonAncestorContainer)) {
|
|
3368
|
+
const sel = window.getSelection();
|
|
3369
|
+
sel.removeAllRanges();
|
|
3370
|
+
sel.addRange(range);
|
|
3371
|
+
} else {
|
|
3372
|
+
editor.focus();
|
|
3373
|
+
}
|
|
3374
|
+
}
|
|
3375
|
+
async function localizeImages(editor, html) {
|
|
3376
|
+
const doc = new DOMParser().parseFromString(`<div>${html}</div>`, "text/html");
|
|
3377
|
+
const imgs = [...doc.body.querySelectorAll("img")].filter((img) => /^https?:/i.test(img.getAttribute("src") || ""));
|
|
3378
|
+
for (const img of imgs) {
|
|
3379
|
+
try {
|
|
3380
|
+
const res = await fetch(img.src, { mode: "cors" });
|
|
3381
|
+
if (!res.ok) continue;
|
|
3382
|
+
const blob = await res.blob();
|
|
3383
|
+
const file = new File([blob], img.alt || `remote-${Date.now()}.jpg`, { type: blob.type || "image/jpeg" });
|
|
3384
|
+
const result = await editor.media.upload(file, "image");
|
|
3385
|
+
img.remove();
|
|
3386
|
+
if (result == null ? void 0 : result.url) editor.toast.show("外链图片已本地化");
|
|
3387
|
+
} catch {
|
|
3388
|
+
}
|
|
3389
|
+
}
|
|
3390
|
+
return doc.body.innerHTML.trim();
|
|
3391
|
+
}
|
|
3392
|
+
const KB = 1024;
|
|
3393
|
+
const MB = 1024 * KB;
|
|
3394
|
+
const defaults = {
|
|
3395
|
+
value: "",
|
|
3396
|
+
placeholder: "开始撰写内容,支持拖拽 / 粘贴图片与视频…",
|
|
3397
|
+
height: 460,
|
|
3398
|
+
// 编辑区可视高度(px),0 = 自适应
|
|
3399
|
+
minHeight: 320,
|
|
3400
|
+
primaryColor: "#07c160",
|
|
3401
|
+
paperWidth: 677,
|
|
3402
|
+
toolbar: DEFAULT_TOOLBAR,
|
|
3403
|
+
hideToolbar: false,
|
|
3404
|
+
hideStatusbar: false,
|
|
3405
|
+
readOnly: false,
|
|
3406
|
+
autofocus: false,
|
|
3407
|
+
maxLength: 0,
|
|
3408
|
+
// 0 表示不限制
|
|
3409
|
+
wordCount: true,
|
|
3410
|
+
sanitize: true,
|
|
3411
|
+
historyLimit: 60,
|
|
3412
|
+
uploader: "mock",
|
|
3413
|
+
// 'mock' | {type:'http', ...} | adapter | fn | ChunkUploader
|
|
3414
|
+
upload: { chunkSize: MB, concurrency: 3, retries: 2, fingerprint: "fast" },
|
|
3415
|
+
image: { compress: { maxWidth: 1440, quality: 0.85, minSize: 300 * KB } },
|
|
3416
|
+
maxImageSize: 20 * MB,
|
|
3417
|
+
maxVideoSize: 512 * MB,
|
|
3418
|
+
imageAccept: "image/png,image/jpeg,image/gif,image/webp,image/bmp,image/svg+xml,image/avif",
|
|
3419
|
+
videoAccept: "video/mp4,video/quicktime,video/webm,video/x-m4v,video/ogg",
|
|
3420
|
+
paste: { enabled: true, clean: true, uploadFiles: true, localizeImages: false },
|
|
3421
|
+
onChange: null,
|
|
3422
|
+
onReady: null,
|
|
3423
|
+
onError: null,
|
|
3424
|
+
onUpload: null,
|
|
3425
|
+
// ({stage, file, kind, url, percent, info}) => void
|
|
3426
|
+
beforeUpload: null,
|
|
3427
|
+
// (file, kind) => File | false
|
|
3428
|
+
toolbarFloat: false
|
|
3429
|
+
};
|
|
3430
|
+
let instanceSeq = 0;
|
|
3431
|
+
class KEditor {
|
|
3432
|
+
constructor(target, options = {}) {
|
|
3433
|
+
injectStyle();
|
|
3434
|
+
this.options = mergeOptions(options);
|
|
3435
|
+
this.id = `ke-${instanceSeq += 1}`;
|
|
3436
|
+
this.el = resolveTarget(target, this.id);
|
|
3437
|
+
const hostHTML = this.el.innerHTML;
|
|
3438
|
+
this.emitters = /* @__PURE__ */ new Map();
|
|
3439
|
+
this.domListeners = [];
|
|
3440
|
+
this.destroyed = false;
|
|
3441
|
+
this.sourceMode = false;
|
|
3442
|
+
this.previewMode = false;
|
|
3443
|
+
this.fullscreen = false;
|
|
3444
|
+
this.readOnly = false;
|
|
3445
|
+
this.buildDOM();
|
|
3446
|
+
this.toast = new Toast();
|
|
3447
|
+
this.popover = new Popover(this.el);
|
|
3448
|
+
this.commands = new Commands(this);
|
|
3449
|
+
this.uploader = createUploader(this.options.uploader, this.options.upload);
|
|
3450
|
+
this.media = createMedia(this);
|
|
3451
|
+
this.history = new History(this.root, { limit: this.options.historyLimit });
|
|
3452
|
+
this.toolbar = new Toolbar(this, this.options.toolbar);
|
|
3453
|
+
this.source = new SourcePanel(this);
|
|
3454
|
+
this.previewPanel = new PreviewOverlay(this);
|
|
3455
|
+
this.bubble = new MediaBubble(this);
|
|
3456
|
+
this.mainEl.append(this.source.el, this.previewPanel.el);
|
|
3457
|
+
this.applyTheme();
|
|
3458
|
+
this.setContent(this.options.value || hostHTML, { sanitize: this.options.sanitize, silent: true });
|
|
3459
|
+
this.bindEvents();
|
|
3460
|
+
this.setReadOnly(this.options.readOnly);
|
|
3461
|
+
this.refresh();
|
|
3462
|
+
this.refreshStatus();
|
|
3463
|
+
this.history.reset(this.root.innerHTML);
|
|
3464
|
+
queueMicrotask(() => {
|
|
3465
|
+
var _a, _b;
|
|
3466
|
+
if (this.destroyed) return;
|
|
3467
|
+
this.emit("ready", { editor: this });
|
|
3468
|
+
(_b = (_a = this.options).onReady) == null ? void 0 : _b.call(_a, this);
|
|
3469
|
+
if (this.options.autofocus) this.focus();
|
|
3470
|
+
});
|
|
3471
|
+
}
|
|
3472
|
+
/* ------------------------------ DOM ------------------------------ */
|
|
3473
|
+
buildDOM() {
|
|
3474
|
+
this.el.classList.add("ke");
|
|
3475
|
+
this.el.id = this.el.id || this.id;
|
|
3476
|
+
this.el.innerHTML = "";
|
|
3477
|
+
this.tbEl = h("div.ke-tb", { role: "toolbar", "aria-label": "编辑器工具栏" });
|
|
3478
|
+
this.scrollEl = h("div.ke-scroll");
|
|
3479
|
+
this.paperEl = h("div.ke-paper");
|
|
3480
|
+
this.root = h("div.ke-content", {
|
|
3481
|
+
contenteditable: this.readOnly ? "false" : "true",
|
|
3482
|
+
role: "textbox",
|
|
3483
|
+
"aria-multiline": "true",
|
|
3484
|
+
spellcheck: "false",
|
|
3485
|
+
"data-placeholder": this.options.placeholder,
|
|
3486
|
+
"data-ke-root": ""
|
|
3487
|
+
});
|
|
3488
|
+
this.root.style.minHeight = `${this.options.minHeight}px`;
|
|
3489
|
+
this.paperEl.appendChild(this.root);
|
|
3490
|
+
this.scrollEl.appendChild(this.paperEl);
|
|
3491
|
+
this.mainEl = h("div.ke-main", {}, [this.scrollEl]);
|
|
3492
|
+
this.statusEl = buildStatusbar(this);
|
|
3493
|
+
this.dropzoneEl = h("div.ke-dropzone", {}, [h("span", { text: "松开即可上传(分片传输)" })]);
|
|
3494
|
+
if (!this.options.hideToolbar) this.el.appendChild(this.tbEl);
|
|
3495
|
+
this.el.appendChild(this.mainEl);
|
|
3496
|
+
if (!this.options.hideStatusbar) this.el.appendChild(this.statusEl);
|
|
3497
|
+
this.el.appendChild(this.dropzoneEl);
|
|
3498
|
+
if (this.options.height) {
|
|
3499
|
+
this.scrollEl.style.height = `${this.options.height}px`;
|
|
3500
|
+
this.scrollEl.style.maxHeight = `${this.options.height}px`;
|
|
3501
|
+
}
|
|
3502
|
+
this.paperEl.style.setProperty("--ke-paper", `${this.options.paperWidth}px`);
|
|
3503
|
+
this.paperEl.style.setProperty("--ke-min-height", `${this.options.minHeight}px`);
|
|
3504
|
+
}
|
|
3505
|
+
applyTheme() {
|
|
3506
|
+
if (this.options.primaryColor) this.el.style.setProperty("--ke-primary", this.options.primaryColor);
|
|
3507
|
+
}
|
|
3508
|
+
/* ------------------------------ 事件 ------------------------------ */
|
|
3509
|
+
bindEvents() {
|
|
3510
|
+
const debouncedChange = debounce(() => this.emitChange(), 160);
|
|
3511
|
+
this.bind(this.root, "input", () => {
|
|
3512
|
+
this.history.snapshot();
|
|
3513
|
+
this.refreshStatus();
|
|
3514
|
+
this.togglePlaceholder();
|
|
3515
|
+
debouncedChange();
|
|
3516
|
+
this.enforceMaxLength();
|
|
3517
|
+
});
|
|
3518
|
+
this.bind(this.root, "keydown", (event) => this.handleKeydown(event));
|
|
3519
|
+
this.bind(this.root, "blur", () => {
|
|
3520
|
+
this.history.flush();
|
|
3521
|
+
this.el.classList.remove("ke-is-focus");
|
|
3522
|
+
this.emit("blur");
|
|
3523
|
+
});
|
|
3524
|
+
this.bind(this.root, "focus", () => {
|
|
3525
|
+
this.el.classList.add("ke-is-focus");
|
|
3526
|
+
this.emit("focus");
|
|
3527
|
+
});
|
|
3528
|
+
this.bind(this.root, "click", (event) => this.handleContentClick(event));
|
|
3529
|
+
this.bind(this.root, "dblclick", (event) => {
|
|
3530
|
+
const img = event.target.closest("img");
|
|
3531
|
+
if (img && this.root.contains(img)) lightbox(img.src);
|
|
3532
|
+
});
|
|
3533
|
+
attachPaste(this);
|
|
3534
|
+
attachDrop(this);
|
|
3535
|
+
this.selectionHandler = () => {
|
|
3536
|
+
if (!this.root.contains(document.activeElement) && document.activeElement !== this.root) return;
|
|
3537
|
+
this.refresh();
|
|
3538
|
+
this.syncBubble();
|
|
3539
|
+
};
|
|
3540
|
+
document.addEventListener("selectionchange", this.selectionHandler);
|
|
3541
|
+
this.scrollHandler = () => this.bubble.position();
|
|
3542
|
+
this.bind(this.scrollEl, "scroll", this.scrollHandler);
|
|
3543
|
+
window.addEventListener("resize", this.scrollHandler);
|
|
3544
|
+
}
|
|
3545
|
+
/** 内部 DOM 事件登记,便于 destroy 时统一清理 */
|
|
3546
|
+
bind(node, type, handler) {
|
|
3547
|
+
node.addEventListener(type, handler);
|
|
3548
|
+
this.domListeners.push({ node, type, handler });
|
|
3549
|
+
return handler;
|
|
3550
|
+
}
|
|
3551
|
+
handleKeydown(event) {
|
|
3552
|
+
const meta = event.metaKey || event.ctrlKey;
|
|
3553
|
+
const key = event.key.toLowerCase();
|
|
3554
|
+
if (meta && key === "z") {
|
|
3555
|
+
event.preventDefault();
|
|
3556
|
+
if (event.shiftKey) this.redo();
|
|
3557
|
+
else this.undo();
|
|
3558
|
+
return;
|
|
3559
|
+
}
|
|
3560
|
+
if (meta && key === "y") {
|
|
3561
|
+
event.preventDefault();
|
|
3562
|
+
this.redo();
|
|
3563
|
+
return;
|
|
3564
|
+
}
|
|
3565
|
+
if (meta && ["b", "i", "u"].includes(key)) {
|
|
3566
|
+
event.preventDefault();
|
|
3567
|
+
this.commands.toggleMark({ b: "bold", i: "italic", u: "underline" }[key]);
|
|
3568
|
+
this.refresh();
|
|
3569
|
+
return;
|
|
3570
|
+
}
|
|
3571
|
+
if (meta && event.shiftKey && key === "k") {
|
|
3572
|
+
event.preventDefault();
|
|
3573
|
+
this.toggleSource();
|
|
3574
|
+
return;
|
|
3575
|
+
}
|
|
3576
|
+
if (meta && key === "k") {
|
|
3577
|
+
event.preventDefault();
|
|
3578
|
+
this.toolbar.openLink();
|
|
3579
|
+
return;
|
|
3580
|
+
}
|
|
3581
|
+
if (meta && key === "s") {
|
|
3582
|
+
event.preventDefault();
|
|
3583
|
+
this.emit("save", { html: this.getHTML() });
|
|
3584
|
+
return;
|
|
3585
|
+
}
|
|
3586
|
+
if (event.key === "Escape") {
|
|
3587
|
+
this.popover.close();
|
|
3588
|
+
this.bubble.hide();
|
|
3589
|
+
if (this.previewMode) this.closePreview();
|
|
3590
|
+
return;
|
|
3591
|
+
}
|
|
3592
|
+
if (event.key === "Backspace" || event.key === "Delete") {
|
|
3593
|
+
const selected = this.bubble.node;
|
|
3594
|
+
if (selected) {
|
|
3595
|
+
event.preventDefault();
|
|
3596
|
+
this.bubble.remove();
|
|
3597
|
+
}
|
|
3598
|
+
}
|
|
3599
|
+
}
|
|
3600
|
+
handleContentClick(event) {
|
|
3601
|
+
const media = event.target.closest("[data-k-media]");
|
|
3602
|
+
if (media && this.root.contains(media)) {
|
|
3603
|
+
this.selectMedia(media);
|
|
3604
|
+
return;
|
|
3605
|
+
}
|
|
3606
|
+
this.clearMediaSelection();
|
|
3607
|
+
this.bubble.hide();
|
|
3608
|
+
}
|
|
3609
|
+
selectMedia(node) {
|
|
3610
|
+
this.clearMediaSelection();
|
|
3611
|
+
node.classList.add("ke-is-selected-media");
|
|
3612
|
+
this.bubble.show(node);
|
|
3613
|
+
this.refreshStatus();
|
|
3614
|
+
}
|
|
3615
|
+
clearMediaSelection() {
|
|
3616
|
+
this.root.querySelectorAll(".ke-is-selected-media").forEach((n) => n.classList.remove("ke-is-selected-media"));
|
|
3617
|
+
this.bubble.hide();
|
|
3618
|
+
}
|
|
3619
|
+
syncBubble() {
|
|
3620
|
+
if (!this.bubble.node || !this.root.contains(this.bubble.node)) this.bubble.hide();
|
|
3621
|
+
else this.bubble.position();
|
|
3622
|
+
}
|
|
3623
|
+
/* ------------------------------ 状态 ------------------------------ */
|
|
3624
|
+
getState() {
|
|
3625
|
+
var _a, _b, _c;
|
|
3626
|
+
const range = getRange(this.root);
|
|
3627
|
+
const block = closestBlock((range == null ? void 0 : range.commonAncestorContainer) || this.root, this.root);
|
|
3628
|
+
const anchor = range ? findAnchor(range, this.root) : null;
|
|
3629
|
+
const media = (_a = this.bubble) == null ? void 0 : _a.node;
|
|
3630
|
+
const mediaImg = media && ((_b = media.dataset) == null ? void 0 : _b.kMedia) === "image" ? media.querySelector("img") : null;
|
|
3631
|
+
const align = mediaImg ? getMediaAlign(mediaImg) : currentAlign(range, block);
|
|
3632
|
+
return {
|
|
3633
|
+
bold: this.queryState("bold"),
|
|
3634
|
+
italic: this.queryState("italic"),
|
|
3635
|
+
underline: this.queryState("underline"),
|
|
3636
|
+
strikeThrough: this.queryState("strikeThrough"),
|
|
3637
|
+
ul: this.queryState("insertUnorderedList"),
|
|
3638
|
+
ol: this.queryState("insertOrderedList"),
|
|
3639
|
+
align,
|
|
3640
|
+
block: ((_c = block == null ? void 0 : block.tagName) == null ? void 0 : _c.toLowerCase()) || "p",
|
|
3641
|
+
fontSize: this.commands.currentFontSize(),
|
|
3642
|
+
linkUrl: anchor ? anchor.getAttribute("href") : "",
|
|
3643
|
+
linkTarget: anchor ? anchor.getAttribute("target") === "_blank" : false,
|
|
3644
|
+
selectionText: range ? range.toString() : "",
|
|
3645
|
+
canUndo: this.history.canUndo(),
|
|
3646
|
+
canRedo: this.history.canRedo(),
|
|
3647
|
+
source: this.sourceMode,
|
|
3648
|
+
preview: this.previewMode,
|
|
3649
|
+
fullscreen: this.fullscreen,
|
|
3650
|
+
readOnly: this.readOnly
|
|
3651
|
+
};
|
|
3652
|
+
}
|
|
3653
|
+
queryState(command) {
|
|
3654
|
+
var _a;
|
|
3655
|
+
if (!this.root.contains(((_a = window.getSelection()) == null ? void 0 : _a.anchorNode) || null)) return false;
|
|
3656
|
+
try {
|
|
3657
|
+
return document.queryCommandState(command);
|
|
3658
|
+
} catch {
|
|
3659
|
+
return false;
|
|
3660
|
+
}
|
|
3661
|
+
}
|
|
3662
|
+
refresh() {
|
|
3663
|
+
if (this.destroyed) return;
|
|
3664
|
+
try {
|
|
3665
|
+
this.toolbar.refresh(this.getState());
|
|
3666
|
+
} catch {
|
|
3667
|
+
}
|
|
3668
|
+
}
|
|
3669
|
+
refreshStatus() {
|
|
3670
|
+
const api = this.statusApi;
|
|
3671
|
+
if (api) api.update(this.counts());
|
|
3672
|
+
}
|
|
3673
|
+
counts() {
|
|
3674
|
+
const text = toPlainText(this.root.innerHTML);
|
|
3675
|
+
return {
|
|
3676
|
+
chars: text.replace(/\s/g, "").length,
|
|
3677
|
+
words: countWords(text),
|
|
3678
|
+
images: this.root.querySelectorAll("img").length,
|
|
3679
|
+
videos: this.root.querySelectorAll('[data-k-media="video"] video, video').length,
|
|
3680
|
+
uploading: this.media ? this.media.tasks.size : 0
|
|
3681
|
+
};
|
|
3682
|
+
}
|
|
3683
|
+
togglePlaceholder() {
|
|
3684
|
+
const empty = !this.root.textContent.trim() && !this.root.querySelector("img,video,hr,table,iframe");
|
|
3685
|
+
this.root.classList.toggle("ke-is-empty", empty);
|
|
3686
|
+
}
|
|
3687
|
+
enforceMaxLength() {
|
|
3688
|
+
var _a, _b;
|
|
3689
|
+
const max = this.options.maxLength;
|
|
3690
|
+
if (!max) return;
|
|
3691
|
+
const { chars } = this.counts();
|
|
3692
|
+
if (chars > max) {
|
|
3693
|
+
this.toast.warn(`已超过建议字数 ${max}`);
|
|
3694
|
+
(_a = this.statusEl) == null ? void 0 : _a.classList.add("ke-is-over");
|
|
3695
|
+
} else {
|
|
3696
|
+
(_b = this.statusEl) == null ? void 0 : _b.classList.remove("ke-is-over");
|
|
3697
|
+
}
|
|
3698
|
+
}
|
|
3699
|
+
/* ------------------------------ 内容 API ------------------------------ */
|
|
3700
|
+
getHTML({ clean = true } = {}) {
|
|
3701
|
+
const html = this.root.innerHTML;
|
|
3702
|
+
if (!clean) return html;
|
|
3703
|
+
return exportHtml(html);
|
|
3704
|
+
}
|
|
3705
|
+
getText() {
|
|
3706
|
+
return toPlainText(this.root.innerHTML);
|
|
3707
|
+
}
|
|
3708
|
+
getJSON() {
|
|
3709
|
+
return { html: this.getHTML(), text: this.getText(), counts: this.counts() };
|
|
3710
|
+
}
|
|
3711
|
+
setContent(html, { sanitize = this.options.sanitize, silent = false } = {}) {
|
|
3712
|
+
const value = sanitizeHtml(html || "<p><br></p>", { allowEmpty: true });
|
|
3713
|
+
this.root.innerHTML = value || "<p><br></p>";
|
|
3714
|
+
this.afterEdit({ silent });
|
|
3715
|
+
if (!silent) this.history.snapshot(true);
|
|
3716
|
+
this.togglePlaceholder();
|
|
3717
|
+
return this;
|
|
3718
|
+
}
|
|
3719
|
+
appendHTML(html) {
|
|
3720
|
+
const range = document.createRange();
|
|
3721
|
+
range.selectNodeContents(this.root);
|
|
3722
|
+
range.collapse(false);
|
|
3723
|
+
const sel = window.getSelection();
|
|
3724
|
+
sel.removeAllRanges();
|
|
3725
|
+
sel.addRange(range);
|
|
3726
|
+
this.commands.insertHTML(html);
|
|
3727
|
+
return this;
|
|
3728
|
+
}
|
|
3729
|
+
clear() {
|
|
3730
|
+
this.media.cancelAll();
|
|
3731
|
+
this.setContent("<p><br></p>");
|
|
3732
|
+
this.focus();
|
|
3733
|
+
return this;
|
|
3734
|
+
}
|
|
3735
|
+
afterEdit({ silent = false } = {}) {
|
|
3736
|
+
this.history.snapshot();
|
|
3737
|
+
this.refreshStatus();
|
|
3738
|
+
this.togglePlaceholder();
|
|
3739
|
+
if (!silent) this.emitChange();
|
|
3740
|
+
}
|
|
3741
|
+
commitHistory() {
|
|
3742
|
+
this.history.snapshot(true);
|
|
3743
|
+
this.refreshStatus();
|
|
3744
|
+
this.emitChange();
|
|
3745
|
+
}
|
|
3746
|
+
emitChange() {
|
|
3747
|
+
var _a, _b;
|
|
3748
|
+
this.emit("change", { html: this.getHTML(), text: this.getText() });
|
|
3749
|
+
(_b = (_a = this.options).onChange) == null ? void 0 : _b.call(_a, this.getHTML(), this);
|
|
3750
|
+
}
|
|
3751
|
+
focus() {
|
|
3752
|
+
if (this.readOnly || this.sourceMode) {
|
|
3753
|
+
if (this.sourceMode) this.source.code.focus();
|
|
3754
|
+
return this;
|
|
3755
|
+
}
|
|
3756
|
+
this.root.focus();
|
|
3757
|
+
const sel = window.getSelection();
|
|
3758
|
+
if (!sel || sel.rangeCount === 0 || !this.root.contains(sel.anchorNode)) {
|
|
3759
|
+
const range = document.createRange();
|
|
3760
|
+
const first = this.root.firstElementChild || this.root;
|
|
3761
|
+
range.selectNodeContents(first);
|
|
3762
|
+
range.collapse(false);
|
|
3763
|
+
sel.removeAllRanges();
|
|
3764
|
+
sel.addRange(range);
|
|
3765
|
+
}
|
|
3766
|
+
return this;
|
|
3767
|
+
}
|
|
3768
|
+
blur() {
|
|
3769
|
+
this.root.blur();
|
|
3770
|
+
return this;
|
|
3771
|
+
}
|
|
3772
|
+
/** 打开面板前记录选区(面板内的输入框会抢走焦点) */
|
|
3773
|
+
saveSelection() {
|
|
3774
|
+
const range = getRange(this.root);
|
|
3775
|
+
this.savedRange = range ? range.cloneRange() : null;
|
|
3776
|
+
return this;
|
|
3777
|
+
}
|
|
3778
|
+
/** 执行面板动作前还原选区,无有效选区时退化为 focus() 的兜底 */
|
|
3779
|
+
restoreSelection() {
|
|
3780
|
+
this.root.focus();
|
|
3781
|
+
const sel = window.getSelection();
|
|
3782
|
+
if (this.savedRange && this.root.contains(this.savedRange.startContainer) && this.root.contains(this.savedRange.endContainer)) {
|
|
3783
|
+
sel.removeAllRanges();
|
|
3784
|
+
sel.addRange(this.savedRange);
|
|
3785
|
+
return this;
|
|
3786
|
+
}
|
|
3787
|
+
return this.focus();
|
|
3788
|
+
}
|
|
3789
|
+
setReadOnly(value) {
|
|
3790
|
+
this.readOnly = !!value;
|
|
3791
|
+
this.root.setAttribute("contenteditable", this.readOnly ? "false" : "true");
|
|
3792
|
+
this.el.classList.toggle("ke-is-readonly", this.readOnly);
|
|
3793
|
+
this.refresh();
|
|
3794
|
+
return this;
|
|
3795
|
+
}
|
|
3796
|
+
undo() {
|
|
3797
|
+
this.history.flush();
|
|
3798
|
+
if (!this.history.undo()) {
|
|
3799
|
+
this.toast.show("没有可撤销的操作");
|
|
3800
|
+
return this;
|
|
3801
|
+
}
|
|
3802
|
+
this.afterEdit({ silent: false });
|
|
3803
|
+
this.refresh();
|
|
3804
|
+
return this;
|
|
3805
|
+
}
|
|
3806
|
+
redo() {
|
|
3807
|
+
if (!this.history.redo()) {
|
|
3808
|
+
this.toast.show("没有可重做的操作");
|
|
3809
|
+
return this;
|
|
3810
|
+
}
|
|
3811
|
+
this.afterEdit();
|
|
3812
|
+
this.refresh();
|
|
3813
|
+
return this;
|
|
3814
|
+
}
|
|
3815
|
+
/* ------------------------------ 媒体快捷入口 ------------------------------ */
|
|
3816
|
+
/** 上传任意文件(自动识别图片/视频),等价于点击工具栏上传 */
|
|
3817
|
+
upload(file, kind = this.media.kindOf(file)) {
|
|
3818
|
+
if (!kind) throw new Error("[KEditor] 不支持的文件类型");
|
|
3819
|
+
return this.media.upload(file, kind);
|
|
3820
|
+
}
|
|
3821
|
+
/** 以 URL 插入图片 */
|
|
3822
|
+
insertImage(url, alt = "") {
|
|
3823
|
+
return this.media.insertImageUrl(url, alt);
|
|
3824
|
+
}
|
|
3825
|
+
/** 以 URL 插入视频 */
|
|
3826
|
+
insertVideo(url, label = "视频") {
|
|
3827
|
+
return this.media.insertVideoUrl(url, label);
|
|
3828
|
+
}
|
|
3829
|
+
/** 取消全部进行中的上传 */
|
|
3830
|
+
cancelUploads() {
|
|
3831
|
+
this.media.cancelAll();
|
|
3832
|
+
return this;
|
|
3833
|
+
}
|
|
3834
|
+
/* ------------------------------ 面板 ------------------------------ */
|
|
3835
|
+
toggleSource() {
|
|
3836
|
+
if (this.sourceMode) this.exitSource();
|
|
3837
|
+
else this.enterSource();
|
|
3838
|
+
return this.sourceMode;
|
|
3839
|
+
}
|
|
3840
|
+
enterSource() {
|
|
3841
|
+
if (this.sourceMode) return;
|
|
3842
|
+
this.history.flush();
|
|
3843
|
+
this.sourceMode = true;
|
|
3844
|
+
this.el.classList.add("ke-is-source");
|
|
3845
|
+
this.clearMediaSelection();
|
|
3846
|
+
this.source.show(this.getHTML({ clean: true }));
|
|
3847
|
+
this.previewPanel.hide();
|
|
3848
|
+
this.previewMode = false;
|
|
3849
|
+
this.refresh();
|
|
3850
|
+
this.emit("sourcechange", { mode: "source" });
|
|
3851
|
+
}
|
|
3852
|
+
exitSource() {
|
|
3853
|
+
if (!this.sourceMode) return;
|
|
3854
|
+
this.source.apply({ silent: true });
|
|
3855
|
+
this.sourceMode = false;
|
|
3856
|
+
this.el.classList.remove("ke-is-source");
|
|
3857
|
+
this.source.hide();
|
|
3858
|
+
this.focus();
|
|
3859
|
+
this.refresh();
|
|
3860
|
+
this.emit("sourcechange", { mode: "visual" });
|
|
3861
|
+
}
|
|
3862
|
+
togglePreview() {
|
|
3863
|
+
if (this.previewMode) this.closePreview();
|
|
3864
|
+
else this.openPreview();
|
|
3865
|
+
return this.previewMode;
|
|
3866
|
+
}
|
|
3867
|
+
openPreview() {
|
|
3868
|
+
this.previewMode = true;
|
|
3869
|
+
this.previewPanel.show(previewHtml(this.getHTML()));
|
|
3870
|
+
this.refresh();
|
|
3871
|
+
}
|
|
3872
|
+
closePreview() {
|
|
3873
|
+
this.previewMode = false;
|
|
3874
|
+
this.previewPanel.hide();
|
|
3875
|
+
this.refresh();
|
|
3876
|
+
}
|
|
3877
|
+
toggleFullscreen() {
|
|
3878
|
+
this.fullscreen = !this.fullscreen;
|
|
3879
|
+
this.el.classList.toggle("ke-is-fullscreen", this.fullscreen);
|
|
3880
|
+
document.body.style.overflow = this.fullscreen ? "hidden" : "";
|
|
3881
|
+
this.refresh();
|
|
3882
|
+
return this.fullscreen;
|
|
3883
|
+
}
|
|
3884
|
+
/* ------------------------------ 事件总线 ------------------------------ */
|
|
3885
|
+
/** 订阅编辑器事件:ready / change / focus / blur / save / uploadstart / uploaddone / uploaderror / uploadcancel / sourcechange */
|
|
3886
|
+
on(type, handler) {
|
|
3887
|
+
return this.addListener(type, handler);
|
|
3888
|
+
}
|
|
3889
|
+
off(type, handler) {
|
|
3890
|
+
return this.removeListener(type, handler);
|
|
3891
|
+
}
|
|
3892
|
+
emit(type, payload = {}) {
|
|
3893
|
+
var _a, _b, _c, _d;
|
|
3894
|
+
const list = this.emitters.get(type) || [];
|
|
3895
|
+
for (const handler of list) {
|
|
3896
|
+
try {
|
|
3897
|
+
handler(payload);
|
|
3898
|
+
} catch (error) {
|
|
3899
|
+
(_b = (_a = this.options).onError) == null ? void 0 : _b.call(_a, error);
|
|
3900
|
+
}
|
|
3901
|
+
}
|
|
3902
|
+
if (type.startsWith("upload")) (_d = (_c = this.options).onUpload) == null ? void 0 : _d.call(_c, { stage: type, ...payload });
|
|
3903
|
+
return this;
|
|
3904
|
+
}
|
|
3905
|
+
addListener(type, handler) {
|
|
3906
|
+
if (!this.emitters.has(type)) this.emitters.set(type, []);
|
|
3907
|
+
this.emitters.get(type).push(handler);
|
|
3908
|
+
return () => this.removeListener(type, handler);
|
|
3909
|
+
}
|
|
3910
|
+
removeListener(type, handler) {
|
|
3911
|
+
const list = this.emitters.get(type) || [];
|
|
3912
|
+
const idx = list.indexOf(handler);
|
|
3913
|
+
if (idx >= 0) list.splice(idx, 1);
|
|
3914
|
+
return this;
|
|
3915
|
+
}
|
|
3916
|
+
/* 兼容别名 */
|
|
3917
|
+
get element() {
|
|
3918
|
+
return this.root;
|
|
3919
|
+
}
|
|
3920
|
+
get editorElement() {
|
|
3921
|
+
return this.el;
|
|
3922
|
+
}
|
|
3923
|
+
destroy() {
|
|
3924
|
+
if (this.destroyed) return;
|
|
3925
|
+
this.destroyed = true;
|
|
3926
|
+
this.media.destroy();
|
|
3927
|
+
this.history.destroy();
|
|
3928
|
+
this.popover.destroy();
|
|
3929
|
+
this.source.destroy();
|
|
3930
|
+
this.previewPanel.destroy();
|
|
3931
|
+
this.bubble.destroy();
|
|
3932
|
+
this.toolbar.destroy();
|
|
3933
|
+
this.toast.destroy();
|
|
3934
|
+
for (const { node, type, handler } of this.domListeners) node.removeEventListener(type, handler);
|
|
3935
|
+
document.removeEventListener("selectionchange", this.selectionHandler);
|
|
3936
|
+
this.scrollEl.removeEventListener("scroll", this.scrollHandler);
|
|
3937
|
+
window.removeEventListener("resize", this.scrollHandler);
|
|
3938
|
+
if (this.fullscreen) document.body.style.overflow = "";
|
|
3939
|
+
this.el.innerHTML = "";
|
|
3940
|
+
this.el.classList.remove("ke", "ke-is-fullscreen", "ke-is-readonly");
|
|
3941
|
+
this.el.removeAttribute("style");
|
|
3942
|
+
this.emitters.clear();
|
|
3943
|
+
}
|
|
3944
|
+
/** 便捷静态方法 */
|
|
3945
|
+
static create(target, options) {
|
|
3946
|
+
return new KEditor(target, options);
|
|
3947
|
+
}
|
|
3948
|
+
}
|
|
3949
|
+
function createMedia(editor) {
|
|
3950
|
+
const manager = new MediaManager(editor);
|
|
3951
|
+
const originalUpload = manager.upload.bind(manager);
|
|
3952
|
+
manager.upload = async (file, kind) => {
|
|
3953
|
+
const hook = editor.options.beforeUpload;
|
|
3954
|
+
let target = file;
|
|
3955
|
+
if (hook) {
|
|
3956
|
+
target = await hook(file, kind);
|
|
3957
|
+
if (target === false) return null;
|
|
3958
|
+
}
|
|
3959
|
+
return originalUpload(target, kind);
|
|
3960
|
+
};
|
|
3961
|
+
manager.replaceNode = async (node, file) => {
|
|
3962
|
+
const kind = node.dataset.kMedia === "video" ? "video" : "image";
|
|
3963
|
+
const range = document.createRange();
|
|
3964
|
+
range.setStartBefore(node);
|
|
3965
|
+
range.collapse(true);
|
|
3966
|
+
const sel = window.getSelection();
|
|
3967
|
+
sel.removeAllRanges();
|
|
3968
|
+
sel.addRange(range);
|
|
3969
|
+
const result = await manager.upload(file, kind);
|
|
3970
|
+
node.remove();
|
|
3971
|
+
editor.commitHistory();
|
|
3972
|
+
return result;
|
|
3973
|
+
};
|
|
3974
|
+
return manager;
|
|
3975
|
+
}
|
|
3976
|
+
function resolveTarget(target, id) {
|
|
3977
|
+
if (typeof target === "string") {
|
|
3978
|
+
const el = document.querySelector(target);
|
|
3979
|
+
if (!el) throw new Error(`[KEditor] 找不到挂载节点:${target}`);
|
|
3980
|
+
return el;
|
|
3981
|
+
}
|
|
3982
|
+
if (target instanceof HTMLElement) return target;
|
|
3983
|
+
if ((target == null ? void 0 : target.$el) instanceof HTMLElement) return target.$el;
|
|
3984
|
+
throw new Error(`[KEditor] 无效的挂载目标(${typeof target})`);
|
|
3985
|
+
}
|
|
3986
|
+
function mergeOptions(options) {
|
|
3987
|
+
const out = { ...defaults, ...options };
|
|
3988
|
+
out.image = { ...defaults.image, ...options.image || {} };
|
|
3989
|
+
out.paste = { ...defaults.paste, ...options.paste || {} };
|
|
3990
|
+
out.upload = { ...defaults.upload, ...options.upload || {} };
|
|
3991
|
+
if (Array.isArray(options.toolbar)) out.toolbar = options.toolbar;
|
|
3992
|
+
if (options.toolbar === false) out.toolbar = [];
|
|
3993
|
+
if (options.toolbar === true) out.toolbar = DEFAULT_TOOLBAR;
|
|
3994
|
+
out.height = clamp$1(out.height ?? 460, 0, 4e3);
|
|
3995
|
+
return out;
|
|
3996
|
+
}
|
|
3997
|
+
function buildStatusbar(editor) {
|
|
3998
|
+
const chars = h("b", { text: "0" });
|
|
3999
|
+
const words = h("b", { text: "0" });
|
|
4000
|
+
const images = h("b", { text: "0" });
|
|
4001
|
+
const videos = h("b", { text: "0" });
|
|
4002
|
+
const chip = h("span.ke-chip", { hidden: true });
|
|
4003
|
+
const hint = h("span.ke-status-hint", { text: "支持拖拽 / 粘贴上传,Ctrl/⌘ + S 保存" });
|
|
4004
|
+
const tail = h("span.ke-status-tail");
|
|
4005
|
+
const el = h(
|
|
4006
|
+
"div.ke-status",
|
|
4007
|
+
{},
|
|
4008
|
+
[
|
|
4009
|
+
h("span", {}, ["字数 ", chars, " · ", words, " 词"]),
|
|
4010
|
+
h("span", {}, ["图片 ", images, " · 视频 ", videos]),
|
|
4011
|
+
chip,
|
|
4012
|
+
hint,
|
|
4013
|
+
tail
|
|
4014
|
+
]
|
|
4015
|
+
);
|
|
4016
|
+
const api = {
|
|
4017
|
+
update: (counts) => {
|
|
4018
|
+
chars.textContent = String(counts.chars);
|
|
4019
|
+
words.textContent = String(counts.words);
|
|
4020
|
+
images.textContent = String(counts.images);
|
|
4021
|
+
videos.textContent = String(counts.videos);
|
|
4022
|
+
if (counts.uploading > 0) {
|
|
4023
|
+
chip.hidden = false;
|
|
4024
|
+
chip.className = "ke-chip ke-is-busy";
|
|
4025
|
+
chip.textContent = `${counts.uploading} 个上传进行中`;
|
|
4026
|
+
} else {
|
|
4027
|
+
chip.hidden = true;
|
|
4028
|
+
}
|
|
4029
|
+
},
|
|
4030
|
+
addExtra: (node) => tail.appendChild(node)
|
|
4031
|
+
};
|
|
4032
|
+
editor.statusApi = api;
|
|
4033
|
+
if (!editor.options.wordCount) el.style.display = "none";
|
|
4034
|
+
return el;
|
|
4035
|
+
}
|
|
4036
|
+
function findAnchor(range, root) {
|
|
4037
|
+
var _a;
|
|
4038
|
+
let node = range == null ? void 0 : range.commonAncestorContainer;
|
|
4039
|
+
if (!node || !root.contains(node)) return null;
|
|
4040
|
+
if (node.nodeType === 3) node = node.parentElement;
|
|
4041
|
+
const anchor = (_a = node == null ? void 0 : node.closest) == null ? void 0 : _a.call(node, "a");
|
|
4042
|
+
return anchor && root.contains(anchor) ? anchor : null;
|
|
4043
|
+
}
|
|
4044
|
+
function currentAlign(range, block) {
|
|
4045
|
+
var _a, _b;
|
|
4046
|
+
const node = block || (range == null ? void 0 : range.commonAncestorContainer);
|
|
4047
|
+
const styles = [node, node == null ? void 0 : node.parentElement].filter((n) => n && n.nodeType === 1);
|
|
4048
|
+
for (const el of styles) {
|
|
4049
|
+
const align = (_a = el.style) == null ? void 0 : _a.textAlign;
|
|
4050
|
+
if (align) return align === "-webkit-justify" ? "justify" : align;
|
|
4051
|
+
const cs = (_b = el.getAttribute) == null ? void 0 : _b.call(el, "align");
|
|
4052
|
+
if (cs) return cs;
|
|
4053
|
+
}
|
|
4054
|
+
try {
|
|
4055
|
+
if (document.queryCommandState("justifyCenter")) return "center";
|
|
4056
|
+
if (document.queryCommandState("justifyRight")) return "right";
|
|
4057
|
+
if (document.queryCommandState("justifyFull")) return "justify";
|
|
4058
|
+
} catch {
|
|
4059
|
+
}
|
|
4060
|
+
return "left";
|
|
4061
|
+
}
|
|
4062
|
+
function countWords(text) {
|
|
4063
|
+
const cjk = (text.match(/[\u4e00-\u9fa5\u3040-\u30ff]/g) || []).length;
|
|
4064
|
+
const latin = (text.match(/[a-zA-Z0-9'’-]+/g) || []).length;
|
|
4065
|
+
return cjk + latin;
|
|
4066
|
+
}
|
|
4067
|
+
function exportHtml(html) {
|
|
4068
|
+
const doc = new DOMParser().parseFromString(`<div>${html}</div>`, "text/html");
|
|
4069
|
+
const root = doc.body.firstChild;
|
|
4070
|
+
root.querySelectorAll("[contenteditable]").forEach((n) => n.removeAttribute("contenteditable"));
|
|
4071
|
+
root.querySelectorAll("[data-k-id]").forEach((n) => n.removeAttribute("data-k-id"));
|
|
4072
|
+
root.querySelectorAll("[data-k-state]").forEach((n) => n.removeAttribute("data-k-state"));
|
|
4073
|
+
root.querySelectorAll("[data-ke-marker]").forEach((n) => n.removeAttribute("data-ke-marker"));
|
|
4074
|
+
root.querySelectorAll("[data-placeholder]").forEach((n) => n.removeAttribute("data-placeholder"));
|
|
4075
|
+
root.querySelectorAll(".ke-is-selected-media").forEach((n) => n.classList.remove("ke-is-selected-media"));
|
|
4076
|
+
root.querySelectorAll('[data-k-state="uploading"], [data-k-state="error"]').forEach((n) => n.remove());
|
|
4077
|
+
return root.innerHTML.trim();
|
|
4078
|
+
}
|
|
4079
|
+
function previewHtml(html) {
|
|
4080
|
+
const doc = new DOMParser().parseFromString(`<div>${html}</div>`, "text/html");
|
|
4081
|
+
const root = doc.body.firstChild;
|
|
4082
|
+
root.querySelectorAll("[data-k-media]").forEach((n) => {
|
|
4083
|
+
n.removeAttribute("data-k-media");
|
|
4084
|
+
n.removeAttribute("data-k-url");
|
|
4085
|
+
});
|
|
4086
|
+
return root.innerHTML;
|
|
4087
|
+
}
|
|
4088
|
+
const version = "1.0.0";
|
|
4089
|
+
function create(target, options = {}) {
|
|
4090
|
+
return new KEditor(target, options);
|
|
4091
|
+
}
|
|
4092
|
+
const mount = create;
|
|
4093
|
+
function replace(target, options = {}) {
|
|
4094
|
+
const el = typeof target === "string" ? document.querySelector(target) : target;
|
|
4095
|
+
if (el == null ? void 0 : el.__keditor__) el.__keditor__.destroy();
|
|
4096
|
+
return create(el, options);
|
|
4097
|
+
}
|
|
4098
|
+
exports2.ChunkUploader = ChunkUploader;
|
|
4099
|
+
exports2.DEFAULT_TOOLBAR = DEFAULT_TOOLBAR;
|
|
4100
|
+
exports2.KEditor = KEditor;
|
|
4101
|
+
exports2.cleanWordHtml = cleanWordHtml;
|
|
4102
|
+
exports2.create = create;
|
|
4103
|
+
exports2.createUploader = createUploader;
|
|
4104
|
+
exports2.default = KEditor;
|
|
4105
|
+
exports2.defaults = defaults;
|
|
4106
|
+
exports2.escapeHtml = escapeHtml;
|
|
4107
|
+
exports2.exportHtml = exportHtml;
|
|
4108
|
+
exports2.fastFingerprint = fastFingerprint;
|
|
4109
|
+
exports2.formatHtml = formatHtml;
|
|
4110
|
+
exports2.httpAdapter = httpAdapter;
|
|
4111
|
+
exports2.isSafeUrl = isSafeUrl;
|
|
4112
|
+
exports2.maybeCompress = maybeCompress;
|
|
4113
|
+
exports2.mockAdapter = mockAdapter;
|
|
4114
|
+
exports2.mount = mount;
|
|
4115
|
+
exports2.replace = replace;
|
|
4116
|
+
exports2.sanitizeHtml = sanitizeHtml;
|
|
4117
|
+
exports2.simpleAdapter = simpleAdapter;
|
|
4118
|
+
exports2.strongFingerprint = strongFingerprint;
|
|
4119
|
+
exports2.version = version;
|
|
4120
|
+
Object.defineProperties(exports2, { __esModule: { value: true }, [Symbol.toStringTag]: { value: "Module" } });
|
|
4121
|
+
});
|