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.
package/src/ui/popover.js DELETED
@@ -1,507 +0,0 @@
1
- /** 工具栏弹层:颜色面板、段落样式、字号、表格规格、链接表单、图片/视频插入 */
2
- import { h } from '../core/utils.js'
3
- import { icon } from '../core/icons.js'
4
-
5
- /* 颜色:分组 + 中文名称,hover 有 tooltip */
6
- const THEME_COLORS = [
7
- ['#07c160', '微信绿'], ['#2f6fed', '科技蓝'], ['#7c3aed', '极光紫'], ['#d53880', '品红'],
8
- ['#e53e3e', '中国红'], ['#ed8936', '暮橙'], ['#f6c344', '明黄'], ['#0f766e', '松石绿'],
9
- ]
10
- const STANDARD_COLORS = [
11
- ['#1f2329', '墨黑'], ['#6b7280', '深灰'], ['#b8bec7', '浅灰'], ['#f2f3f5', '云灰'], ['#ffffff', '纯白'],
12
- ['#c00000', '深红'], ['#ff0000', '正红'], ['#ffc000', '琥珀'],
13
- ['#ffff00', '柠黄'], ['#00b050', '草绿'], ['#00b0f0', '天蓝'], ['#0070c0', '海蓝'],
14
- ['#7030a0', '葡萄紫'], ['#ff69b4', '桃花粉'],
15
- ]
16
- const BG_COLORS = [
17
- ['#fef08a', '柠檬底'], ['#dcfce7', '薄荷底'], ['#e0f2fe', '天空底'], ['#ede9fe', '薰衣底'],
18
- ['#ffe4e6', '樱花底'], ['#fff4e6', '奶茶底'], ['#f2f3f5', '纸张灰'], ['#1f2329', '夜墨'],
19
- ]
20
-
21
- const HEX = /^#([0-9a-f]{3}|[0-9a-f]{6})$/i
22
-
23
- export class Popover {
24
- constructor(root) {
25
- this.root = root
26
- this.el = h('div.ke-pop', { hidden: true })
27
- this.anchor = null
28
- this.onClose = null
29
- root.appendChild(this.el)
30
- // 面板内的非输入控件不应抢焦点 / 破坏正文选区
31
- this.el.addEventListener('mousedown', (event) => {
32
- if (!/^(input|textarea|select)$/i.test(event.target.tagName)) event.preventDefault()
33
- })
34
- this.docHandler = (event) => {
35
- if (this.el.hidden) return
36
- if (this.el.contains(event.target)) return
37
- if (event.target.closest?.('.ke-btn[data-k-pop]')) return // 由按钮自身负责开合
38
- this.close()
39
- }
40
- document.addEventListener('mousedown', this.docHandler, true)
41
- this.keyHandler = (event) => {
42
- if (event.key === 'Escape') this.close()
43
- }
44
- document.addEventListener('keydown', this.keyHandler)
45
- }
46
-
47
- open(anchor, build, { align = 'start', onClose } = {}) {
48
- this.el.textContent = ''
49
- const content = build((node) => this.el.appendChild(node))
50
- if (content) this.el.appendChild(content)
51
- this.el.hidden = false
52
- this.anchor = anchor
53
- this.onClose = onClose
54
- const rootBox = this.root.getBoundingClientRect()
55
- const box = anchor.getBoundingClientRect()
56
- // 先渲染再定位,宽度依赖内容
57
- const popBox = this.el.getBoundingClientRect()
58
- let left = box.left - rootBox.left
59
- if (align === 'center') left = box.left - rootBox.left + box.width / 2 - popBox.width / 2
60
- if (align === 'end') left = box.right - rootBox.left - popBox.width
61
- left = Math.max(8, Math.min(left, rootBox.width - popBox.width - 8))
62
- let top = box.top - rootBox.top + box.height + 8
63
- // 编辑区高度不足时向上翻转
64
- if (top + popBox.height > rootBox.height - 8 && box.top - rootBox.top - popBox.height - 8 > 0) {
65
- top = box.top - rootBox.top - popBox.height - 8
66
- }
67
- this.el.style.left = `${left}px`
68
- this.el.style.top = `${top}px`
69
- // 重新触发一次入场动画
70
- this.el.classList.remove('ke-pop-in')
71
- void this.el.offsetWidth
72
- this.el.classList.add('ke-pop-in')
73
- const first = [...this.el.querySelectorAll('[data-k-autofocus]')].find((node) => node.offsetParent !== null)
74
- first?.focus?.()
75
- }
76
-
77
- close() {
78
- if (this.el.hidden) return
79
- this.el.hidden = true
80
- this.el.classList.remove('ke-pop-in')
81
- this.el.textContent = ''
82
- this.anchor = null
83
- const cb = this.onClose
84
- this.onClose = null
85
- cb?.()
86
- }
87
-
88
- get isOpen() {
89
- return !this.el.hidden
90
- }
91
-
92
- destroy() {
93
- document.removeEventListener('mousedown', this.docHandler, true)
94
- document.removeEventListener('keydown', this.keyHandler)
95
- this.el.remove()
96
- }
97
- }
98
-
99
- /* ---------------------------- 面板骨架 ---------------------------- */
100
-
101
- function panel(title, right) {
102
- const head = h('div.ke-panel-head', {}, [h('span.ke-panel-title', { text: title })])
103
- if (right) head.appendChild(right)
104
- const wrap = h('div.ke-panel', {}, [head])
105
- return wrap
106
- }
107
-
108
- function section(label) {
109
- return h('div.ke-panel-sect', { text: label })
110
- }
111
-
112
- function divider() {
113
- return h('div.ke-panel-divider')
114
- }
115
-
116
- /* ---------------------------- 颜色面板 ---------------------------- */
117
-
118
- /**
119
- * 颜色面板:主题色 + 标准色 + 最近使用 + 自定义取色
120
- * onPick(color) — color 为 null 表示恢复默认 / 清除
121
- */
122
- export function colorPanel({ title, kind, colors, value, recents = [], onPick, onClear }) {
123
- const isBg = kind === 'bg'
124
- const reset = h('button.ke-panel-reset', {
125
- type: 'button',
126
- title: isBg ? '清除高亮' : '恢复默认文字色',
127
- text: isBg ? '清除高亮' : '恢复默认',
128
- onclick: () => onClear ? onClear() : onPick(null),
129
- })
130
- const wrap = panel(title, reset)
131
-
132
- if (recents.length) {
133
- wrap.appendChild(section('最近使用'))
134
- wrap.appendChild(swatches(recents.slice(0, 8), value, onPick))
135
- }
136
-
137
- if (!isBg) {
138
- wrap.appendChild(section('主题颜色'))
139
- wrap.appendChild(swatches(THEME_COLORS, value, onPick))
140
- wrap.appendChild(section('标准颜色'))
141
- wrap.appendChild(swatches(STANDARD_COLORS, value, onPick))
142
- } else {
143
- wrap.appendChild(section('推荐底色'))
144
- wrap.appendChild(swatches(BG_COLORS.map(([c, n]) => [c, n]), value, onPick))
145
- wrap.appendChild(section('主题颜色'))
146
- wrap.appendChild(swatches(THEME_COLORS, value, onPick))
147
- }
148
-
149
- wrap.appendChild(divider())
150
- wrap.appendChild(customRow(value, onPick))
151
- return wrap
152
- }
153
-
154
- function swatches(list, value, onPick) {
155
- const grid = h('div.ke-sw-grid')
156
- list.forEach(([color, name]) => {
157
- const btn = h('button.ke-sw', {
158
- type: 'button',
159
- title: `${name} ${color}`,
160
- 'aria-label': name,
161
- style: { background: color },
162
- })
163
- if (value && HEX.test(value) && color.toLowerCase() === String(value).toLowerCase()) {
164
- btn.classList.add('ke-is-active')
165
- btn.appendChild(h('span.ke-sw-check', { html: icon('checkLight') }))
166
- }
167
- btn.addEventListener('click', () => onPick(color))
168
- grid.appendChild(btn)
169
- })
170
- return grid
171
- }
172
-
173
- function customRow(value, onPick) {
174
- const hex = HEX.test(value || '') ? value : '#07c160'
175
- const picker = h('input.ke-sw-picker', { type: 'color', value: hex, title: '自定义颜色' })
176
- const input = h('input.ke-input.ke-sw-hex', { type: 'text', value: hex, placeholder: '#000000', maxlength: 7 })
177
- const apply = h('button.ke-btn-primary', { type: 'button', text: '应用' })
178
- const commit = () => {
179
- const raw = input.value.trim()
180
- const next = raw.startsWith('#') ? raw : `#${raw}`
181
- if (!HEX.test(next)) {
182
- input.classList.add('ke-is-invalid')
183
- return
184
- }
185
- input.classList.remove('ke-is-invalid')
186
- onPick(next)
187
- }
188
- picker.addEventListener('input', () => {
189
- input.value = picker.value
190
- })
191
- picker.addEventListener('change', commit)
192
- apply.addEventListener('click', commit)
193
- input.addEventListener('keydown', (event) => {
194
- if (event.key === 'Enter') {
195
- event.preventDefault()
196
- commit()
197
- }
198
- })
199
- return h('div.ke-panel-foot', {}, [
200
- picker,
201
- input,
202
- apply,
203
- ])
204
- }
205
-
206
- /* ---------------------------- 段落样式面板 ---------------------------- */
207
-
208
- /** items: [{value, label, desc, sampleClass}] */
209
- export function headingPanel(items, { value, onPick }) {
210
- const wrap = panel('段落样式')
211
- wrap.classList.add('ke-panel-wide')
212
- items.forEach((item) => {
213
- const row = h('button.ke-hd-row', {
214
- type: 'button',
215
- dataset: { kValue: item.value },
216
- onclick: () => onPick(item.value),
217
- }, [
218
- h('span.ke-hd-sample', { class: item.sampleClass || '', text: item.sample || item.label }),
219
- h('span.ke-hd-meta', {}, [
220
- h('span.ke-hd-label', { text: item.label }),
221
- h('span.ke-hd-desc', { text: item.desc }),
222
- ]),
223
- ])
224
- if (item.value === value) row.classList.add('ke-is-active')
225
- wrap.appendChild(row)
226
- })
227
- return wrap
228
- }
229
-
230
- /* ---------------------------- 字号面板 ---------------------------- */
231
-
232
- export function fontSizePanel(sizes, { value, onPick }) {
233
- const wrap = panel('字号', h('span.ke-panel-note', { text: value ? `${value}px` : '默认 17px' }))
234
- wrap.classList.add('ke-panel-wide')
235
- const grid = h('div.ke-size-grid')
236
- sizes.forEach((size) => {
237
- const btn = h('button.ke-size-cell', { type: 'button', text: String(size), onclick: () => onPick(size) })
238
- btn.style.fontSize = `${Math.min(20, 10 + size / 6)}px`
239
- if (Number(value) === size) btn.classList.add('ke-is-active')
240
- grid.appendChild(btn)
241
- })
242
- wrap.appendChild(grid)
243
- wrap.appendChild(divider())
244
- wrap.appendChild(h('div.ke-panel-hint', { text: '仅作用于选中的文字;未选中时对新输入的文字生效' }))
245
- return wrap
246
- }
247
-
248
- export const colorPresets = { text: THEME_COLORS.map((x) => x[0]), bg: BG_COLORS.map((x) => x[0]) }
249
-
250
- /* ---------------------------- 表格规格 ---------------------------- */
251
-
252
- export function tablePanel(onPick, { cols = 10, rows = 8 } = {}) {
253
- const wrap = panel('插入表格', h('span.ke-panel-note', { text: '最大 10×8' }))
254
- const grid = h('div.ke-table-grid', { style: { gridTemplateColumns: `repeat(${cols}, 18px)` } })
255
- const cells = []
256
- for (let r = 0; r < rows; r += 1) {
257
- for (let c = 0; c < cols; c += 1) {
258
- const cell = h('span.ke-table-cell')
259
- cell.dataset.r = String(r)
260
- cell.dataset.c = String(c)
261
- cells.push(cell)
262
- grid.appendChild(cell)
263
- }
264
- }
265
- wrap.appendChild(grid)
266
- const sizeText = h('div.ke-panel-hint', { text: '1 列 × 1 行' })
267
- wrap.appendChild(sizeText)
268
- const mark = (maxR, maxC) => {
269
- cells.forEach((cell) => {
270
- const on = Number(cell.dataset.r) <= maxR && Number(cell.dataset.c) <= maxC
271
- cell.classList.toggle('ke-is-on', on)
272
- })
273
- sizeText.textContent = `${maxC + 1} 列 × ${maxR + 1} 行`
274
- }
275
- grid.addEventListener('mousemove', (event) => {
276
- const cell = event.target.closest('.ke-table-cell')
277
- if (cell) mark(Number(cell.dataset.r), Number(cell.dataset.c))
278
- })
279
- grid.addEventListener('click', (event) => {
280
- const cell = event.target.closest('.ke-table-cell')
281
- if (cell) onPick(Number(cell.dataset.c) + 1, Number(cell.dataset.r) + 1)
282
- })
283
- grid.addEventListener('mouseenter', () => mark(0, 0))
284
- mark(0, 0)
285
- return wrap
286
- }
287
-
288
- /* ---------------------------- 图片 / 视频插入面板 ---------------------------- */
289
-
290
- /**
291
- * 本地上传 + 网络链接两种入口合一
292
- * onFiles(FileList|File[]) / onUrl({url, name})
293
- */
294
- export function mediaPanel(kind, { onFiles, onUrl, multiple, hint, maxText }) {
295
- const isImage = kind === 'image'
296
- const wrap = panel(isImage ? '插入图片' : '插入视频')
297
- wrap.classList.add('ke-panel-wide', 'ke-panel-media')
298
-
299
- const local = h('div.ke-tab-body')
300
- const net = h('div.ke-tab-body', { hidden: true })
301
-
302
- /* —— 本地上传 —— */
303
- const drop = h('div.ke-drop', {}, [
304
- h('span.ke-drop-ico', { html: icon('upload') }),
305
- h('div.ke-drop-title', { text: isImage ? '点击选择图片,或拖拽到此处' : '点击选择视频,或拖拽到此处' }),
306
- h('div.ke-drop-sub', { text: [maxText, hint].filter(Boolean).join(' · ') }),
307
- ])
308
- const pickBtn = h('button.ke-btn-primary', {
309
- type: 'button',
310
- text: isImage ? '选择图片' : '选择视频',
311
- onclick: () => onFiles(null),
312
- })
313
- drop.addEventListener('click', () => onFiles(null))
314
- drop.addEventListener('dragover', (event) => {
315
- event.preventDefault()
316
- drop.classList.add('ke-is-over')
317
- })
318
- drop.addEventListener('dragleave', () => drop.classList.remove('ke-is-over'))
319
- drop.addEventListener('drop', (event) => {
320
- event.preventDefault()
321
- drop.classList.remove('ke-is-over')
322
- if (event.dataTransfer?.files?.length) onFiles(event.dataTransfer.files)
323
- })
324
- local.append(drop, h('div.ke-panel-foot', {}, [pickBtn, h('span.ke-panel-hint', { text: multiple ? '可一次插入多张' : '单文件大文件将自动分片上传' })]))
325
-
326
- /* —— 网络链接 —— */
327
- const urlInput = h('input.ke-input', {
328
- type: 'url',
329
- placeholder: isImage ? 'https://example.com/photo.jpg' : 'https://example.com/video.mp4',
330
- 'data-k-autofocus': '',
331
- })
332
- const nameInput = h('input.ke-input', { type: 'text', placeholder: isImage ? '图片描述(可选,作为 alt)' : '视频标题(可选)' })
333
- const status = h('div.ke-link-status', { text: '粘贴链接后自动校验可访问性' })
334
- const insertBtn = h('button.ke-btn-primary', { type: 'button', text: '插入', disabled: true })
335
- let timer = null
336
- let token = 0
337
- const check = () => {
338
- token += 1
339
- const mine = token
340
- clearTimeout(timer)
341
- const url = normalizeUrl(urlInput.value)
342
- insertBtn.disabled = !url
343
- status.className = 'ke-link-status'
344
- if (!url) {
345
- status.textContent = '请输入 http(s) 开头的链接'
346
- return
347
- }
348
- status.className = 'ke-link-status ke-is-checking'
349
- status.textContent = '正在校验…'
350
- timer = setTimeout(() => probe(kind, url, (ok) => {
351
- if (mine !== token) return
352
- if (ok) {
353
- status.className = 'ke-link-status ke-is-ok'
354
- status.textContent = isImage ? '图片可访问 ✓' : '视频可播放 ✓'
355
- } else {
356
- status.className = 'ke-link-status ke-is-bad'
357
- status.textContent = '未能自动加载(可能限制热链),不阻塞插入,发布前请自行确认'
358
- }
359
- }), 350)
360
- }
361
- urlInput.addEventListener('input', check)
362
- urlInput.addEventListener('paste', () => setTimeout(check, 0))
363
- const submit = () => {
364
- const url = normalizeUrl(urlInput.value)
365
- if (!url) {
366
- urlInput.classList.add('ke-is-invalid')
367
- urlInput.focus()
368
- return
369
- }
370
- onUrl({ url, name: nameInput.value.trim() })
371
- }
372
- insertBtn.addEventListener('click', submit)
373
- net.addEventListener('keydown', (event) => {
374
- if (event.key === 'Enter') {
375
- event.preventDefault()
376
- submit()
377
- }
378
- })
379
- net.append(
380
- h('div.ke-field', {}, [h('span.ke-field-label', { text: '地址' }), urlInput]),
381
- h('div.ke-field', {}, [h('span.ke-field-label', { text: isImage ? '描述' : '标题' }), nameInput]),
382
- status,
383
- h('div.ke-panel-foot', {}, [insertBtn, h('span.ke-panel-hint', { text: '外链由源站提供,不占用上传配额' })]),
384
- )
385
-
386
- const tabs = h('div.ke-tabs', {}, [
387
- h('button.ke-tab', { type: 'button', text: '本地上传' }),
388
- h('button.ke-tab', { type: 'button', text: '网络链接' }),
389
- ])
390
- const show = (index) => {
391
- [...tabs.children].forEach((tab, i) => tab.classList.toggle('ke-is-active', i === index))
392
- local.hidden = index !== 0
393
- net.hidden = index !== 1
394
- if (index === 1) urlInput.focus()
395
- }
396
- tabs.children[0].addEventListener('click', () => show(0))
397
- tabs.children[1].addEventListener('click', () => show(1))
398
- show(0)
399
-
400
- wrap.append(tabs, local, net)
401
- return wrap
402
- }
403
-
404
- /** 用 Image / video 元素探测远程地址是否可用 */
405
- function probe(kind, url, done) {
406
- let settled = false
407
- const finish = (ok) => {
408
- if (settled) return
409
- settled = true
410
- done(ok)
411
- }
412
- try {
413
- if (kind === 'image') {
414
- const img = new Image()
415
- img.onload = () => finish(true)
416
- img.onerror = () => finish(false)
417
- img.referrerPolicy = 'no-referrer'
418
- img.src = url
419
- } else {
420
- const video = document.createElement('video')
421
- video.preload = 'metadata'
422
- video.muted = true
423
- video.onloadedmetadata = () => finish(video.videoHeight > 0 || video.duration > 0 || Number.isFinite(video.duration))
424
- video.onerror = () => finish(false)
425
- video.src = url
426
- }
427
- } catch {
428
- finish(false)
429
- }
430
- }
431
-
432
- /* ---------------------------- 链接表单 ---------------------------- */
433
-
434
- export function linkPanel({ url = '', text = '', target = false, onSubmit, onCancel, onRemove }) {
435
- const urlInput = h('input.ke-input', { type: 'url', placeholder: 'https://mp.weixin.qq.com/...', value: url, 'data-k-autofocus': '' })
436
- const textInput = h('input.ke-input', { type: 'text', placeholder: '链接文字(留空使用 URL)', value: text })
437
- const check = h('input', { type: 'checkbox' })
438
- check.checked = !!target
439
- const wrap = panel(url ? '编辑链接' : '插入链接')
440
- wrap.classList.add('ke-panel-wide')
441
- const body = h('div', {}, [
442
- h('div.ke-field', {}, [h('span.ke-field-label', { text: '文字' }), textInput]),
443
- h('div.ke-field', {}, [h('span.ke-field-label', { text: '地址' }), urlInput]),
444
- h('label.ke-check', {}, [check, '新窗口打开']),
445
- h('div.ke-panel-foot', {}, [
446
- onRemove ? h('button.ke-btn-ghost', { type: 'button', text: '移除链接', style: { marginRight: 'auto', color: '#e53e3e' }, onclick: onRemove }) : null,
447
- h('button.ke-btn-ghost', { type: 'button', text: '取消', onclick: onCancel }),
448
- h('button.ke-btn-primary', { type: 'button', text: '确定', onclick: () => submit() }),
449
- ]),
450
- ])
451
- const submit = () => {
452
- const href = normalizeUrl(urlInput.value)
453
- if (!href) {
454
- urlInput.classList.add('ke-is-invalid')
455
- urlInput.focus()
456
- return
457
- }
458
- onSubmit({ url: href, text: textInput.value.trim(), target: check.checked })
459
- }
460
- body.addEventListener('keydown', (event) => {
461
- if (event.key === 'Enter') {
462
- event.preventDefault()
463
- submit()
464
- }
465
- })
466
- wrap.appendChild(body)
467
- return wrap
468
- }
469
-
470
- export function normalizeUrl(url) {
471
- const value = String(url || '').trim()
472
- if (!value) return ''
473
- if (/^(https?:|mailto:|tel:|#|\/)/i.test(value)) return value
474
- if (/^[\w-]+(\.[\w-]+)+/.test(value)) return `https://${value}`
475
- return ''
476
- }
477
-
478
- /* ---------------------------- 通用输入确认面板 ---------------------------- */
479
-
480
- export function formPanel({ fields, onSubmit, onCancel, submitText = '确定' }) {
481
- const inputs = {}
482
- const body = h('div.ke-panel', {})
483
- fields.forEach((field) => {
484
- const input = field.type === 'textarea' ? h('textarea.ke-textarea', { rows: field.rows || 5, placeholder: field.placeholder || '' }) : h(field.type === 'checkbox' ? 'input' : 'input', { type: field.type || 'text', placeholder: field.placeholder || '' })
485
- if (field.value) {
486
- if (field.type === 'checkbox') input.checked = true
487
- else input.value = field.value
488
- }
489
- inputs[field.name] = input
490
- body.appendChild(h('div.ke-field', {}, [h('span.ke-field-label', { text: field.label }), input]))
491
- })
492
- body.appendChild(
493
- h('div.ke-panel-foot', {}, [
494
- h('button.ke-btn-ghost', { type: 'button', text: '取消', onclick: onCancel }),
495
- h('button.ke-btn-primary', {
496
- type: 'button',
497
- text: submitText,
498
- onclick: () => {
499
- const values = {}
500
- for (const [key, input] of Object.entries(inputs)) values[key] = input.type === 'checkbox' ? input.checked : input.value
501
- onSubmit(values)
502
- },
503
- }),
504
- ]),
505
- )
506
- return body
507
- }
package/src/ui/preview.js DELETED
@@ -1,59 +0,0 @@
1
- /** 阅读预览:按公众号正文版式渲染,可切换屏宽 */
2
- import { h } from '../core/utils.js'
3
- import { icon } from '../core/icons.js'
4
-
5
- const DEVICES = [
6
- { key: 'mobile', label: '手机', width: 375 },
7
- { key: 'pad', label: '平板', width: 540 },
8
- { key: 'pc', label: '电脑', width: 677 },
9
- ]
10
-
11
- export class PreviewOverlay {
12
- constructor(editor) {
13
- this.editor = editor
14
- this.device = 'pc'
15
- this.el = h('div.ke-preview', { hidden: true }, [
16
- h('div.ke-preview-bar', {}, [
17
- h('span', { text: '预览' }),
18
- h('span.ke-source-tip', { text: '仅用于查看排版效果,内容不可编辑' }),
19
- h('span.ke-status-tail', {}, DEVICES.map((device) =>
20
- h('button.ke-btn', {
21
- type: 'button',
22
- 'data-k-device': device.key,
23
- text: device.label,
24
- onclick: () => this.setDevice(device.key),
25
- }),
26
- ).concat([h('span.ke-tb-sep'), h('button.ke-btn', { type: 'button', title: '关闭预览', html: icon('close'), onclick: () => editor.closePreview() })])),
27
- ]),
28
- (() => {
29
- this.body = h('div.ke-preview-body', {}, [h('div.ke-preview-frame', { style: { maxWidth: '677px' } }, [h('div.ke-content.ke-preview-content')])])
30
- this.frame = this.body.firstChild
31
- this.content = this.frame.firstChild
32
- return this.body
33
- })(),
34
- ])
35
- }
36
-
37
- setDevice(key) {
38
- this.device = key
39
- const device = DEVICES.find((d) => d.key === key) || DEVICES[2]
40
- this.frame.style.maxWidth = `${device.width}px`
41
- this.frame.style.width = key === 'mobile' ? `${device.width}px` : '100%'
42
- this.el.querySelectorAll('[data-k-device]').forEach((btn) => btn.classList.toggle('ke-is-active', btn.dataset.kDevice === key))
43
- }
44
-
45
- show(html) {
46
- this.content.innerHTML = html
47
- this.el.hidden = false
48
- this.setDevice(this.device)
49
- }
50
-
51
- hide() {
52
- this.el.hidden = true
53
- this.content.innerHTML = ''
54
- }
55
-
56
- destroy() {
57
- this.el.remove()
58
- }
59
- }
package/src/ui/source.js DELETED
@@ -1,97 +0,0 @@
1
- /** HTML 源码模式:查看 / 直接编辑,返回可视化时自动生效 */
2
- import { h } from '../core/utils.js'
3
- import { formatHtml } from '../core/format.js'
4
- import { icon } from '../core/icons.js'
5
-
6
- export class SourcePanel {
7
- constructor(editor) {
8
- this.editor = editor
9
- this.open = false
10
- this.el = h('div.ke-source', { hidden: true }, [
11
- h('div.ke-source-bar', {}, [
12
- h('span.ke-source-title', { text: 'HTML 源码' }),
13
- h('span.ke-source-tip', { text: '可直接编辑,点击「应用」或退出源码模式即生效' }),
14
- h('span.ke-source-tail', {}, [
15
- h('button.ke-btn', { type: 'button', title: '格式化', html: icon('format') + '<span>格式化</span>', onclick: () => this.format() }),
16
- h('button.ke-btn', { type: 'button', title: '复制全部', html: icon('copy') + '<span>复制</span>', onclick: () => this.copy() }),
17
- h('button.ke-btn', { type: 'button', title: '应用修改', html: icon('check') + '<span>应用</span>', onclick: () => this.apply() }),
18
- h('button.ke-btn', { type: 'button', title: '退出源码模式', html: icon('close'), onclick: () => editor.exitSource() }),
19
- ]),
20
- ]),
21
- (() => {
22
- this.code = h('pre.ke-source-code', { contenteditable: 'true', spellcheck: 'false', autocapitalize: 'off', autocomplete: 'off', wrap: 'off' })
23
- this.code.addEventListener('keydown', (event) => {
24
- if (event.key === 'Tab') {
25
- event.preventDefault()
26
- document.execCommand('insertText', false, ' ')
27
- }
28
- if ((event.ctrlKey || event.metaKey) && event.key.toLowerCase() === 's') {
29
- event.preventDefault()
30
- this.apply()
31
- }
32
- event.stopPropagation()
33
- })
34
- return this.code
35
- })(),
36
- ])
37
- }
38
-
39
- get value() {
40
- return this.code.textContent
41
- }
42
-
43
- set value(text) {
44
- this.code.textContent = text
45
- this.code.scrollTop = 0
46
- }
47
-
48
- show(html) {
49
- this.value = formatHtml(html)
50
- this.el.hidden = false
51
- this.open = true
52
- this.editor.scrollEl.hidden = true
53
- }
54
-
55
- hide() {
56
- this.el.hidden = true
57
- this.open = false
58
- this.editor.scrollEl.hidden = false
59
- }
60
-
61
- format() {
62
- this.value = formatHtml(this.value)
63
- this.editor.toast.show('已格式化')
64
- }
65
-
66
- async copy() {
67
- const text = this.value
68
- try {
69
- if (navigator.clipboard?.writeText) await navigator.clipboard.writeText(text)
70
- else {
71
- this.code.focus()
72
- document.execCommand('selectAll')
73
- document.execCommand('copy')
74
- }
75
- this.editor.toast.show('源码已复制到剪贴板')
76
- } catch {
77
- this.editor.toast.error('复制失败,请手动选择复制')
78
- }
79
- }
80
-
81
- /** 应用当前源码到编辑区(做净化) */
82
- apply({ silent = false } = {}) {
83
- const html = this.value
84
- try {
85
- this.editor.setContent(html, { sanitize: true, silent: false })
86
- if (!silent) this.editor.toast.show('源码已应用')
87
- return true
88
- } catch (error) {
89
- this.editor.toast.error(`源码解析失败:${error.message}`)
90
- return false
91
- }
92
- }
93
-
94
- destroy() {
95
- this.el.remove()
96
- }
97
- }