kyle-editor 1.0.0 → 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.
@@ -1,465 +0,0 @@
1
- /** 工具栏:声明式配置,可整体替换或裁剪(options.toolbar) */
2
- import { h } from '../core/utils.js'
3
- import { icon } from '../core/icons.js'
4
- import { colorPanel, headingPanel, fontSizePanel, tablePanel, linkPanel, mediaPanel, normalizeUrl } from '../ui/popover.js'
5
-
6
- 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>'
7
-
8
- /** 首次引导:告知工具栏可左右滑动(localStorage 记忆,不重复打扰) */
9
- const SCROLL_HINT_KEY = 'keditor.toolbarScrollHint'
10
- 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>'
11
-
12
- /** 段落样式:label 是名称,desc 说明用途与字号,sample 用真实样式预览 */
13
- export const HEADINGS = [
14
- { value: 'p', label: '正文', desc: '默认段落 · 17px,正文内容都用它', sample: '正文示例文字', sampleClass: 's-body' },
15
- { value: 'h1', label: '标题一', desc: '大标题 · 22px 加粗,全文主标题(建议只用一次)', sample: '标题一示例', sampleClass: 's-h1' },
16
- { value: 'h2', label: '标题二', desc: '章节标题 · 20px 加粗,划分小节', sample: '标题二示例', sampleClass: 's-h2' },
17
- { value: 'h3', label: '标题三', desc: '小标题 · 18px 加粗,章节内的层级', sample: '标题三示例', sampleClass: 's-h3' },
18
- ]
19
- const FONT_SIZES = [12, 14, 15, 16, 17, 18, 20, 22, 24, 28, 32]
20
-
21
- export const DEFAULT_TOOLBAR = [
22
- 'undo', 'redo', '|',
23
- 'heading', 'fontsize', '|',
24
- 'bold', 'italic', 'underline', 'strike', '|',
25
- 'foreColor', 'backColor', '|',
26
- 'alignLeft', 'alignCenter', 'alignRight', 'alignJustify', '|',
27
- 'ul', 'ol', 'quote', '|',
28
- 'link', 'image', 'video', 'table', 'code', 'hr', 'clear',
29
- ':tail', 'source', 'preview', 'fullscreen',
30
- ]
31
-
32
- const ITEMS = {
33
- undo: { icon: 'undo', title: '撤销 (⌘/Ctrl+Z)', run: (e) => e.undo(), active: (s) => !!s.canUndo, enabled: (s) => s.canUndo },
34
- redo: { icon: 'redo', title: '重做 (⌘/Ctrl+Shift+Z)', run: (e) => e.redo(), active: (s) => !!s.canRedo, enabled: (s) => s.canRedo },
35
- bold: { glyph: ['B', 'ke-glyph'], title: '加粗 (⌘/Ctrl+B)', cmd: 'bold', active: (s) => s.bold },
36
- italic: { glyph: ['I', 'ke-glyph ke-glyph-i'], title: '斜体 (⌘/Ctrl+I)', cmd: 'italic', active: (s) => s.italic },
37
- underline: { glyph: ['U', 'ke-glyph ke-glyph-u'], title: '下划线 (⌘/Ctrl+U)', cmd: 'underline', active: (s) => s.underline },
38
- strike: { glyph: ['S', 'ke-glyph ke-glyph-s'], title: '删除线', cmd: 'strike', active: (s) => s.strikeThrough },
39
- alignLeft: { icon: 'alignLeft', title: '左对齐', run: (e) => e.commands.setAlign('left'), active: (s) => s.align === 'left' },
40
- alignCenter: { icon: 'alignCenter', title: '居中', run: (e) => e.commands.setAlign('center'), active: (s) => s.align === 'center' },
41
- alignRight: { icon: 'alignRight', title: '右对齐', run: (e) => e.commands.setAlign('right'), active: (s) => s.align === 'right' },
42
- alignJustify: { icon: 'alignJustify', title: '两端对齐', run: (e) => e.commands.setAlign('justify'), active: (s) => s.align === 'justify' },
43
- ul: { icon: 'ul', title: '无序列表', run: (e) => e.commands.toggleList('unordered'), active: (s) => s.ul },
44
- ol: { icon: 'ol', title: '有序列表', run: (e) => e.commands.toggleList('ordered'), active: (s) => s.ol },
45
- quote: { icon: 'quote', title: '引用', run: (e) => e.commands.toggleBlockquote(), active: (s) => s.block === 'blockquote' },
46
- link: { icon: 'link', title: '插入链接', run: (e) => e.toolbar.openLink(), active: (s) => s.link, toggles: true },
47
- image: { icon: 'image', title: '图片(本地上传 / 网络链接)', run: (e) => e.toolbar.openMedia('image'), toggles: true },
48
- video: { icon: 'video', title: '视频(本地上传 / 网络链接,支持分片上传)', run: (e) => e.toolbar.openMedia('video'), toggles: true },
49
- table: { icon: 'table', title: '插入表格', run: (e) => e.toolbar.openTable(), toggles: true },
50
- code: { icon: 'code', title: '代码块', run: (e) => e.commands.insertCodeBlock() },
51
- hr: { icon: 'hr', title: '分割线', run: (e) => e.commands.insertDivider() },
52
- clear: { icon: 'clear', title: '清除格式', run: (e) => e.commands.clearFormat() },
53
- source: { icon: 'source', title: '查看 / 编辑 HTML 源码(⌘/Ctrl+Shift+K)', text: '源码', run: (e) => e.toggleSource(), active: (s) => s.source },
54
- preview: { icon: 'preview', title: '预览效果(手机 / 平板 / 电脑宽度)', text: '预览', run: (e) => e.togglePreview(), active: (s) => s.preview },
55
- fullscreen: { icon: 'expand', title: '全屏编辑', text: '全屏', run: (e) => e.toggleFullscreen(), active: (s) => s.fullscreen },
56
- foreColor: { pop: 'fore', title: '字体颜色', toggles: true, swatch: 'fore' },
57
- backColor: { pop: 'back', title: '背景高亮色', toggles: true, swatch: 'back' },
58
- }
59
-
60
- export class Toolbar {
61
- constructor(editor, items = DEFAULT_TOOLBAR) {
62
- this.editor = editor
63
- this.buttons = new Map()
64
- this.colorState = { foreColor: '#3f3f3f', backColor: '#f6c344' }
65
- this.recent = { foreColor: [], backColor: [] }
66
- this.el = editor.tbEl
67
- this.build(items)
68
- this.setupScrollHints()
69
- }
70
-
71
- build(items) {
72
- const group = h('div.ke-tb-group')
73
- this.el.appendChild(group)
74
- let tail = null
75
- const target = () => tail || group
76
- for (const key of items) {
77
- if (key === '|') {
78
- group.appendChild(h('span.ke-tb-sep'))
79
- continue
80
- }
81
- if (key === ':tail') {
82
- tail = h('div.ke-tb-tail')
83
- this.el.appendChild(tail)
84
- continue
85
- }
86
- if (key === 'heading') {
87
- target().appendChild(this.buildHeading())
88
- continue
89
- }
90
- if (key === 'fontsize') {
91
- target().appendChild(this.buildFontSize())
92
- continue
93
- }
94
- const spec = ITEMS[key]
95
- if (!spec) continue
96
- target().appendChild(this.buildButton(key, spec))
97
- }
98
- }
99
-
100
- buildButton(name, spec) {
101
- const button = h('button.ke-btn', {
102
- type: 'button',
103
- title: spec.title,
104
- 'data-k-item': name,
105
- onclick: (event) => {
106
- event.preventDefault()
107
- if (spec.pop) this.toggleColor(name, button)
108
- else if (spec.cmd) this.editor.commands.toggleMark(spec.cmd)
109
- else spec.run?.(this.editor)
110
- if (!spec.toggles) this.editor.popover.close()
111
- },
112
- })
113
- if (spec.icon) button.innerHTML = icon(spec.icon)
114
- if (spec.text) button.appendChild(h('span.ke-btn-text', { text: spec.text }))
115
- if (spec.glyph) {
116
- const [text, cls] = spec.glyph
117
- button.appendChild(h('span', { class: cls, text }))
118
- }
119
- if (spec.swatch) {
120
- // 经典「A + 色条」(字体色)/「A + 高亮块」(底色),一眼可辨
121
- const color = spec.swatch === 'fore' ? this.colorState.foreColor : this.colorState.backColor
122
- const face = h('span', { class: spec.swatch === 'fore' ? 'ke-glyph ke-glyph-a' : 'ke-glyph ke-glyph-a ke-glyph-hl' })
123
- face.appendChild(h('span', { text: 'A' }))
124
- button.appendChild(face)
125
- if (spec.swatch === 'fore') button.appendChild(h('span', { class: 'ke-dot' }))
126
- this.paintButton(button, spec.swatch, color)
127
- button.dataset.kPop = spec.swatch === 'fore' ? 'foreColor' : 'backColor'
128
- }
129
- if (spec.toggles && !spec.swatch) button.dataset.kPop = name
130
- this.buttons.set(name, button)
131
- return button
132
- }
133
-
134
- paintButton(button, kind, color) {
135
- if (!button || !color) return
136
- button.style.setProperty(kind === 'fore' ? '--ke-fore' : '--ke-back', color)
137
- }
138
-
139
- /* ---------------- 下拉面板 ---------------- */
140
-
141
- openPop(anchor, builder, options = {}) {
142
- this.editor.saveSelection()
143
- this.editor.popover.open(anchor, builder, {
144
- align: 'start',
145
- ...options,
146
- onClose: () => {
147
- anchor.classList.remove('ke-is-open')
148
- options.onClose?.()
149
- },
150
- })
151
- anchor.classList.add('ke-is-open')
152
- }
153
-
154
- /** 同一个按钮再次点击 = 关闭;颜色按钮点击直接展开面板 */
155
- togglePop(name, button, builder, options = {}) {
156
- const pop = this.editor.popover
157
- if (pop.isOpen && pop.anchor === button) {
158
- pop.close()
159
- return
160
- }
161
- this.openPop(button, builder, options)
162
- }
163
-
164
- buildHeading() {
165
- const current = HEADINGS[0]
166
- const button = h('button.ke-btn.ke-btn-label', {
167
- type: 'button',
168
- title: '段落样式:正文 / 标题一 / 标题二 / 标题三',
169
- 'data-k-item': 'heading',
170
- dataset: { kPop: 'heading' },
171
- onclick: (event) => {
172
- event.preventDefault()
173
- this.togglePop('heading', button, () =>
174
- headingPanel(HEADINGS, {
175
- value: this.editor.getState().block,
176
- onPick: (value) => {
177
- this.editor.restoreSelection()
178
- this.editor.commands.setHeading(value)
179
- this.editor.popover.close()
180
- this.editor.refresh()
181
- },
182
- }))
183
- },
184
- })
185
- button.innerHTML = `<span class="ke-btn-text">${current.label}</span>${CARET}`
186
- this.headingEl = button
187
- this.buttons.set('heading', button)
188
- return button
189
- }
190
-
191
- buildFontSize() {
192
- const button = h('button.ke-btn.ke-btn-label', {
193
- type: 'button',
194
- title: '字号',
195
- 'data-k-item': 'fontsize',
196
- dataset: { kPop: 'fontsize' },
197
- onclick: (event) => {
198
- event.preventDefault()
199
- this.togglePop('fontsize', button, () =>
200
- fontSizePanel(FONT_SIZES, {
201
- value: this.editor.getState().fontSize,
202
- onPick: (size) => {
203
- this.editor.restoreSelection()
204
- this.editor.commands.setFontSize(Number(size))
205
- this.editor.popover.close()
206
- this.editor.refresh()
207
- },
208
- }))
209
- },
210
- })
211
- button.innerHTML = `<span class="ke-btn-text">字号</span>${CARET}`
212
- this.fontSizeEl = button
213
- this.buttons.set('fontsize', button)
214
- return button
215
- }
216
-
217
- toggleColor(name, button) {
218
- const kind = name === 'foreColor' ? 'fore' : 'back'
219
- this.togglePop(name, button, () =>
220
- colorPanel({
221
- title: kind === 'fore' ? '字体颜色' : '背景高亮色',
222
- kind,
223
- value: this.colorState[name],
224
- recents: this.recent[name],
225
- onPick: (color) => this.applyColor(name, kind, color, button),
226
- onClear: () => this.applyColor(name, kind, null, button),
227
- }),
228
- {
229
- onClose: () => button.classList.remove('ke-is-active'),
230
- },
231
- )
232
- }
233
-
234
- applyColor(name, kind, color, button) {
235
- this.editor.restoreSelection()
236
- const value = color || (kind === 'fore' ? '#3f3f3f' : 'transparent')
237
- if (color) {
238
- this.colorState[name] = color
239
- this.recent[name] = [color, ...this.recent[name].filter((x) => x.toLowerCase() !== color.toLowerCase())].slice(0, 8)
240
- this.paintButton(button, kind, color)
241
- }
242
- this.editor.commands.setColor(kind, color)
243
- this.editor.popover.close()
244
- }
245
-
246
- openTable() {
247
- const button = this.buttons.get('table')
248
- this.togglePop('table', button, () =>
249
- tablePanel((cols, rows) => {
250
- this.editor.restoreSelection()
251
- this.editor.commands.insertTable(cols, rows)
252
- this.editor.popover.close()
253
- }))
254
- }
255
-
256
- openLink() {
257
- const button = this.buttons.get('link')
258
- const state = this.editor.getState()
259
- const existing = state.linkUrl
260
- this.togglePop('link', button, () =>
261
- linkPanel({
262
- url: existing || '',
263
- text: existing ? '' : state.selectionText || '',
264
- target: existing ? state.linkTarget : true,
265
- onCancel: () => this.editor.popover.close(),
266
- onRemove: existing ? () => { this.editor.restoreSelection(); this.editor.commands.removeLink(); this.editor.popover.close() } : null,
267
- onSubmit: ({ url, text, target }) => {
268
- this.editor.restoreSelection()
269
- this.editor.commands.createLink({ url: normalizeUrl(url), text, target })
270
- this.editor.popover.close()
271
- },
272
- }))
273
- }
274
-
275
- /** 图片 / 视频:本地上传 + 网络链接输入 */
276
- openMedia(kind) {
277
- const button = this.buttons.get(kind)
278
- const editor = this.editor
279
- const options = editor.options
280
- this.togglePop(kind, button, () =>
281
- mediaPanel(kind, {
282
- multiple: kind === 'image',
283
- maxText: `${kind === 'image' ? '图片' : '视频'}上限 ${formatLimit(kind === 'image' ? options.maxImageSize : options.maxVideoSize)}`,
284
- hint: kind === 'image' ? '支持 PNG / JPG / GIF / WebP / SVG' : '支持 MP4 / MOV / WebM,大文件自动分片',
285
- onFiles: (files) => {
286
- editor.popover.close()
287
- if (files && files.length) editor.media.addFiles([...files])
288
- else editor.media.pickFiles(kind)
289
- },
290
- onUrl: ({ url, name }) => {
291
- editor.popover.close()
292
- editor.restoreSelection()
293
- editor.media.insertFromUrl(kind, url, name)
294
- },
295
- }))
296
- }
297
-
298
- /** 根据编辑器状态同步按钮高亮 / 下拉值 / 禁用 */
299
- refresh(state) {
300
- for (const [name, button] of this.buttons) {
301
- const spec = ITEMS[name]
302
- if (!spec) continue
303
- const active = spec.active?.(state) || false
304
- if (button.dataset.kPop || !spec.pop) button.classList.toggle('ke-is-active', active)
305
- if (spec.enabled) button.disabled = !spec.enabled(state)
306
- }
307
- if (this.headingEl) {
308
- const match = HEADINGS.find((x) => x.value === state.block)
309
- const label = this.headingEl.querySelector('.ke-btn-text')
310
- if (label) label.textContent = match ? match.label : '正文'
311
- this.headingEl.title = match ? `${match.label}:${match.desc}` : '段落样式'
312
- }
313
- if (this.fontSizeEl) {
314
- const label = this.fontSizeEl.querySelector('.ke-btn-text')
315
- if (label) label.textContent = state.fontSize ? `${state.fontSize}px` : '字号'
316
- }
317
- if (state.linkUrl) {
318
- const btn = this.buttons.get('link')
319
- btn?.classList.add('ke-is-active')
320
- }
321
- }
322
-
323
- /* ---------------- 可滑动提示 ---------------- */
324
-
325
- /**
326
- * 工具栏溢出时给出四重可发现性提示:
327
- * 常显滚动条(CSS)、右侧被遮工具的动态阴影、左侧渐隐、鼠标拖拽,
328
- * 外加首次加载的引导气泡。
329
- */
330
- setupScrollHints() {
331
- const tb = this.el
332
- const host = this.editor.el
333
- if (!tb.isConnected) return // hideToolbar:未挂载则无需提示
334
-
335
- // 渐隐层挂在 .ke 上(不随工具栏内容滚动)
336
- this.scrollFades = h('div.ke-tb-fades', { 'aria-hidden': 'true' }, [h('i.ke-tb-fade ke-tb-fade-l')])
337
- tb.insertAdjacentElement('afterend', this.scrollFades)
338
-
339
- this.syncScrollHints = () => {
340
- if (!tb.isConnected || !host.isConnected) return
341
- const max = tb.scrollWidth - tb.clientWidth
342
- const overflow = max > 1
343
- const left = tb.scrollLeft
344
- host.classList.toggle('ke-tb-scrollable', overflow)
345
- host.classList.toggle('ke-tb-can-l', overflow && left > 1)
346
- host.classList.toggle('ke-tb-can-r', overflow && left < max - 1)
347
- host.style.setProperty('--ke-tb-h', `${tb.offsetHeight}px`)
348
- if (overflow && !this.hintSettled) this.showScrollHint()
349
- }
350
-
351
- this.onTbScroll = () => {
352
- this.syncScrollHints()
353
- this.hideScrollHint()
354
- }
355
- tb.addEventListener('scroll', this.onTbScroll, { passive: true })
356
-
357
- if (typeof ResizeObserver !== 'undefined') {
358
- this.tbRO = new ResizeObserver(() => this.syncScrollHints())
359
- this.tbRO.observe(tb)
360
- }
361
-
362
- this.onTbPointerDown = (event) => {
363
- this.hideScrollHint()
364
- this.startDragScroll(event)
365
- }
366
- tb.addEventListener('pointerdown', this.onTbPointerDown)
367
-
368
- requestAnimationFrame(this.syncScrollHints)
369
- }
370
-
371
- /** 鼠标按住拖动平移工具栏(触屏已有原生滑动,不介入) */
372
- startDragScroll(event) {
373
- const tb = this.el
374
- const host = this.editor.el
375
- if (event.button !== 0 || event.pointerType !== 'mouse') return
376
- if (tb.scrollWidth <= tb.clientWidth + 1) return
377
- if (event.target.closest('input, textarea, select')) return
378
-
379
- const startX = event.clientX
380
- const startLeft = tb.scrollLeft
381
- let dragging = false
382
-
383
- const move = (ev) => {
384
- const dx = ev.clientX - startX
385
- if (!dragging) {
386
- if (Math.abs(dx) < 5) return // 小于阈值视为点击,不抢走按钮交互
387
- dragging = true
388
- try { tb.setPointerCapture(event.pointerId) } catch { /* 忽略 */ }
389
- host.classList.add('ke-tb-dragging')
390
- this.editor.popover?.close() // 面板定位会随滚动错位,拖拽时先关闭
391
- }
392
- ev.preventDefault()
393
- tb.scrollLeft = startLeft - dx
394
- }
395
-
396
- const up = () => {
397
- tb.removeEventListener('pointermove', move)
398
- tb.removeEventListener('pointerup', up)
399
- tb.removeEventListener('pointercancel', up)
400
- host.classList.remove('ke-tb-dragging')
401
- if (!dragging) return
402
- try { tb.releasePointerCapture(event.pointerId) } catch { /* 已释放 */ }
403
- // 吞掉拖拽结束时落下的那一次 click,避免误触发按钮
404
- const stop = (ev) => { ev.preventDefault(); ev.stopPropagation(); release() }
405
- const release = () => {
406
- clearTimeout(fallback)
407
- tb.removeEventListener('click', stop, true)
408
- }
409
- const fallback = setTimeout(release, 400)
410
- tb.addEventListener('click', stop, true)
411
- }
412
-
413
- tb.addEventListener('pointermove', move)
414
- tb.addEventListener('pointerup', up)
415
- tb.addEventListener('pointercancel', up)
416
- }
417
-
418
- showScrollHint() {
419
- this.hintSettled = true // 每个实例只尝试一次,避免 resize 反复弹
420
- let seen = false
421
- try { seen = localStorage.getItem(SCROLL_HINT_KEY) === '1' } catch { /* 隐私模式忽略 */ }
422
- if (seen) return
423
- this.hintEl = h('div.ke-tb-hint', { 'aria-hidden': 'true' }, [
424
- h('span.ke-tb-hint-ico', { html: SCROLL_HINT_ICON }),
425
- h('span', { text: '工具栏可左右滑动' }),
426
- ])
427
- this.editor.el.appendChild(this.hintEl)
428
- this.hintTimer = setTimeout(() => this.hideScrollHint(), 3800)
429
- }
430
-
431
- hideScrollHint() {
432
- if (this.hintTimer) { clearTimeout(this.hintTimer); this.hintTimer = null }
433
- const pill = this.hintEl
434
- if (!pill) return
435
- this.hintEl = null
436
- try { localStorage.setItem(SCROLL_HINT_KEY, '1') } catch { /* 忽略 */ }
437
- pill.classList.add('ke-is-out')
438
- setTimeout(() => pill.remove(), 260)
439
- }
440
-
441
- destroy() {
442
- const tb = this.el
443
- if (this.tbRO) { this.tbRO.disconnect(); this.tbRO = null }
444
- if (this.hintTimer) { clearTimeout(this.hintTimer); this.hintTimer = null }
445
- if (this.onTbScroll) tb.removeEventListener('scroll', this.onTbScroll)
446
- if (this.onTbPointerDown) tb.removeEventListener('pointerdown', this.onTbPointerDown)
447
- this.scrollFades?.remove()
448
- this.hintEl?.remove()
449
- this.scrollFades = null
450
- this.hintEl = null
451
- const host = this.editor?.el
452
- if (host) {
453
- host.classList.remove('ke-tb-scrollable', 'ke-tb-can-l', 'ke-tb-can-r', 'ke-tb-dragging')
454
- host.style.removeProperty('--ke-tb-h')
455
- }
456
- tb.innerHTML = ''
457
- this.buttons.clear()
458
- }
459
- }
460
-
461
- function formatLimit(bytes) {
462
- if (!bytes) return '不限'
463
- const mb = bytes / 1024 / 1024
464
- return mb >= 1 ? `${Math.round(mb)}MB` : `${Math.round(bytes / 1024)}KB`
465
- }
package/src/core/utils.js DELETED
@@ -1,95 +0,0 @@
1
- /** 通用小工具 */
2
-
3
- export const uid = (prefix = 'k') => `${prefix}${Date.now().toString(36)}${Math.random().toString(36).slice(2, 7)}`
4
-
5
- export function debounce(fn, wait = 300) {
6
- let timer = null
7
- const wrapped = (...args) => {
8
- clearTimeout(timer)
9
- timer = setTimeout(() => fn(...args), wait)
10
- }
11
- wrapped.cancel = () => clearTimeout(timer)
12
- wrapped.flush = (...args) => {
13
- clearTimeout(timer)
14
- fn(...args)
15
- }
16
- return wrapped
17
- }
18
-
19
- export const clamp = (num, min, max) => Math.min(Math.max(num, min), max)
20
-
21
- export function formatSize(bytes) {
22
- if (!bytes && bytes !== 0) return '-'
23
- const units = ['B', 'KB', 'MB', 'GB']
24
- let i = 0
25
- let value = bytes
26
- while (value >= 1024 && i < units.length - 1) {
27
- value /= 1024
28
- i += 1
29
- }
30
- return `${value.toFixed(value >= 10 || i === 0 ? 0 : 1)}${units[i]}`
31
- }
32
-
33
- /** 极简 DOM 构造器:h('div.k-btn', {title}, [child, '文本']) */
34
- export function h(spec, attrs = {}, children = []) {
35
- let tag = 'div'
36
- let className = ''
37
- const parts = String(spec).split('.')
38
- tag = parts[0] || 'div'
39
- className = parts.slice(1).join(' ')
40
- const node = document.createElement(tag)
41
- if (className) node.className = className
42
- for (const [key, val] of Object.entries(attrs || {})) {
43
- if (val === undefined || val === null || val === false) continue
44
- if (key === 'class') node.className = `${node.className} ${val}`.trim()
45
- else if (key === 'style' && typeof val === 'object') Object.assign(node.style, val)
46
- else if (key === 'html') node.innerHTML = val
47
- else if (key === 'text') node.textContent = val
48
- else if (key === 'dataset') Object.assign(node.dataset, val)
49
- else if (key.startsWith('on') && typeof val === 'function') node.addEventListener(key.slice(2).toLowerCase(), val)
50
- else node.setAttribute(key, val === true ? '' : String(val))
51
- }
52
- const list = Array.isArray(children) ? children : [children]
53
- for (const child of list) {
54
- if (child === null || child === undefined || child === false) continue
55
- node.appendChild(typeof child === 'string' || typeof child === 'number' ? document.createTextNode(String(child)) : child)
56
- }
57
- return node
58
- }
59
-
60
- export function on(root, selector, type, handler) {
61
- root.addEventListener(type, (event) => {
62
- const target = event.target.closest(selector)
63
- if (target && root.contains(target)) handler(event, target)
64
- })
65
- }
66
-
67
- export const isFunction = (val) => typeof val === 'function'
68
-
69
- /**
70
- * 媒体(图片)对齐:正文里的 img 是 display:block,居中等对齐靠 margin:auto 实现。
71
- * 工具栏命令与气泡工具条共用同一套逻辑,保证两条入口行为一致。
72
- */
73
- export function getMediaAlign(img) {
74
- if (!img) return 'left'
75
- const ml = img.style.marginLeft
76
- const mr = img.style.marginRight
77
- if (ml === 'auto' && mr === 'auto') return 'center'
78
- if (ml === 'auto') return 'right'
79
- return 'left'
80
- }
81
-
82
- export function setMediaAlign(img, align) {
83
- if (!img) return
84
- img.style.maxWidth = '100%'
85
- if (align === 'center') {
86
- img.style.marginLeft = 'auto'
87
- img.style.marginRight = 'auto'
88
- } else if (align === 'right') {
89
- img.style.marginLeft = 'auto'
90
- img.style.marginRight = '0'
91
- } else {
92
- img.style.marginLeft = '0'
93
- img.style.marginRight = 'auto'
94
- }
95
- }
package/src/index.js DELETED
@@ -1,33 +0,0 @@
1
- /**
2
- * KEditor — 微信公众号风格富文本编辑器(纯前端)
3
- * 支持 <script> 直接引入(全局 KEditor)与 ESM / Vue3 安装
4
- */
5
- import { KEditor, exportHtml, defaults } from './core/editor.js'
6
-
7
- export const version = '1.0.0'
8
-
9
- /** 创建一个编辑器实例,target 可为选择器 / DOM / Vue ref */
10
- export function create(target, options = {}) {
11
- return new KEditor(target, options)
12
- }
13
-
14
- /** 语法糖:与 create 相同,便于 `KEditor.mount('#el')` 这类调用 */
15
- export const mount = create
16
-
17
- /** 销毁并替换目标节点上的旧实例 */
18
- export function replace(target, options = {}) {
19
- const el = typeof target === 'string' ? document.querySelector(target) : target
20
- if (el?.__keditor__) el.__keditor__.destroy()
21
- return create(el, options)
22
- }
23
-
24
- export { KEditor, defaults, exportHtml }
25
- export { DEFAULT_TOOLBAR } from './core/toolbar.js'
26
- export { sanitizeHtml, escapeHtml, isSafeUrl, cleanWordHtml } from './core/sanitize.js'
27
- export { formatHtml } from './core/format.js'
28
- export { ChunkUploader, simpleAdapter } from './upload/chunk-uploader.js'
29
- export { createUploader, mockAdapter, httpAdapter } from './upload/adapters.js'
30
- export { fastFingerprint, strongFingerprint } from './upload/fingerprint.js'
31
- export { maybeCompress } from './media/media.js'
32
-
33
- export default KEditor