kyle-editor 0.0.0-stage → 1.0.0

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.
@@ -0,0 +1,64 @@
1
+ /** HTML 美化输出(源码模式使用):含子块的容器展开,简单块保持一行 */
2
+
3
+ const BLOCK_TAGS = 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'])
4
+
5
+ export function formatHtml(html, { indent = ' ' } = {}) {
6
+ if (!html) return ''
7
+ const doc = new DOMParser().parseFromString(`<div>${html}</div>`, 'text/html')
8
+ const root = doc.body.firstChild
9
+ const lines = []
10
+
11
+ const push = (depth, text) => {
12
+ const value = text.replace(/\s+/g, ' ').trim()
13
+ if (!value) return
14
+ const last = lines[lines.length - 1]
15
+ // 同一层级的连续行内节点合并成一行,避免 <p>文字<strong>粗</strong></p> 被拆散
16
+ if (last && last.depth === depth && last.inlineRun) last.text += ` ${value}`
17
+ else lines.push({ depth, text: indent.repeat(depth) + value, inlineRun: true })
18
+ }
19
+
20
+ const walk = (parent, depth) => {
21
+ let index = 0
22
+ const nodes = [...parent.childNodes]
23
+ nodes.forEach((child) => {
24
+ if (child.nodeType === 3) {
25
+ const text = child.textContent.trim()
26
+ if (text) push(depth, text)
27
+ return
28
+ }
29
+ if (child.nodeType !== 1) return
30
+ const tag = child.tagName.toLowerCase()
31
+ if (!BLOCK_TAGS.has(tag)) {
32
+ push(depth, child.outerHTML)
33
+ return
34
+ }
35
+ const hasBlockChild = [...child.querySelectorAll('*')].some((node) => BLOCK_TAGS.has(node.tagName.toLowerCase()))
36
+ // 表格行/图片块/视频卡即使含子元素也保持单行,可读性更好
37
+ const keepOneLine = tag === 'tr' || tag === 'figure' || tag === 'video'
38
+ if (!hasBlockChild || keepOneLine) {
39
+ // 简单块:整体一行
40
+ lines.push({ depth, text: indent.repeat(depth) + collapse(child.outerHTML), inlineRun: false })
41
+ return
42
+ }
43
+ lines.push({ depth, text: indent.repeat(depth) + openTag(child), inlineRun: false })
44
+ walk(child, depth + 1)
45
+ lines.push({ depth, text: indent.repeat(depth) + `</${tag}>`, inlineRun: false })
46
+ index += 1
47
+ })
48
+ void index
49
+ }
50
+
51
+ walk(root, 0)
52
+ return lines.map((line) => line.text).join('\n').replace(/\n{3,}/g, '\n\n')
53
+ }
54
+
55
+ /** 压缩多余空白(不改动文本内容中的单个空格) */
56
+ function collapse(markup) {
57
+ return markup.replace(/\n\s+/g, ' ').replace(/\s{2,}/g, ' ').trim()
58
+ }
59
+
60
+ /** 只保留开始标签(含属性) */
61
+ function openTag(element) {
62
+ const attrs = [...element.attributes].map((attr) => `${attr.name}="${(attr.value || '').replace(/"/g, '&quot;')}"`)
63
+ return `<${element.tagName.toLowerCase()}${attrs.length ? ` ${attrs.join(' ')}` : ''}>`
64
+ }
@@ -0,0 +1,92 @@
1
+ /** 快照式撤销/重做栈,配合文本偏移恢复光标 */
2
+ import { caretOffset, setCaretOffset } from './selection.js'
3
+
4
+ export class History {
5
+ constructor(root, { limit = 60, delay = 400 } = {}) {
6
+ this.root = root
7
+ this.limit = limit
8
+ this.delay = delay
9
+ this.stack = []
10
+ this.index = -1
11
+ this.timer = null
12
+ this.locked = false
13
+ this.lastHtml = root.innerHTML
14
+ }
15
+
16
+ /** 记录当前状态(首个快照不触发 change) */
17
+ snapshot(immediate = false) {
18
+ clearTimeout(this.timer)
19
+ const push = () => {
20
+ const html = this.root.innerHTML
21
+ if (html === this.lastHtml) return
22
+ this.lastHtml = html
23
+ const point = { html, offset: caretOffset(this.root) }
24
+ this.stack = this.stack.slice(0, this.index + 1)
25
+ this.stack.push(point)
26
+ if (this.stack.length > this.limit) this.stack.shift()
27
+ this.index = this.stack.length - 1
28
+ }
29
+ if (immediate) push()
30
+ else this.timer = setTimeout(push, this.delay)
31
+ }
32
+
33
+ /** 立即落盘挂起的快照 */
34
+ flush() {
35
+ clearTimeout(this.timer)
36
+ this.snapshot(true)
37
+ }
38
+
39
+ /** 恢复内容但不产生新快照(用于 undo/redo 自身、源码模式应用) */
40
+ apply(html, offset) {
41
+ this.locked = true
42
+ this.root.innerHTML = html
43
+ this.lastHtml = html
44
+ if (offset !== undefined && offset !== null) setCaretOffset(this.root, offset)
45
+ this.locked = false
46
+ }
47
+
48
+ canUndo() {
49
+ return this.index > 0
50
+ }
51
+
52
+ canRedo() {
53
+ return this.index >= 0 && this.index < this.stack.length - 1
54
+ }
55
+
56
+ undo() {
57
+ if (!this.canUndo()) return false
58
+ clearTimeout(this.timer)
59
+ this.index -= 1
60
+ const point = this.stack[this.index]
61
+ this.apply(point.html, this.currentOffset(point, 'undo'))
62
+ this.lastHtml = point.html
63
+ return true
64
+ }
65
+
66
+ redo() {
67
+ if (!this.canRedo()) return false
68
+ const point = this.stack[this.index + 1]
69
+ this.index += 1
70
+ this.apply(point.html, this.currentOffset(point, 'redo'))
71
+ this.lastHtml = point.html
72
+ return true
73
+ }
74
+
75
+ currentOffset(point) {
76
+ // 若当前文档能算出偏移,优先沿用它,否则用快照里记录的
77
+ const now = caretOffset(this.root)
78
+ return now === null ? point.offset : point.offset
79
+ }
80
+
81
+ reset(html) {
82
+ clearTimeout(this.timer)
83
+ this.stack = [{ html, offset: 0 }]
84
+ this.index = 0
85
+ this.lastHtml = html
86
+ }
87
+
88
+ destroy() {
89
+ clearTimeout(this.timer)
90
+ this.stack = []
91
+ }
92
+ }
@@ -0,0 +1,49 @@
1
+ /** 内置图标(stroke 风格,24x24 viewBox,与 currentColor 联动) */
2
+
3
+ const S = (d) =>
4
+ `<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>`
5
+
6
+ export const icons = {
7
+ 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>`,
8
+ 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>`,
9
+ 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>`,
10
+ 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>`,
11
+ 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>`,
12
+ 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>`,
13
+ 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>`,
14
+ 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>`,
15
+ alignLeft: S('M4 6h16M4 12h10M4 18h13'),
16
+ alignCenter: S('M4 6h16M7 12h10M5.5 18h13'),
17
+ alignRight: S('M4 6h16M10 12h10M7 18h13'),
18
+ alignJustify: S('M4 6h16M4 12h16M4 18h16'),
19
+ 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>`,
20
+ 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>`,
21
+ 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>`,
22
+ 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>`,
23
+ 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>`,
24
+ 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>`,
25
+ 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>`,
26
+ 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>`,
27
+ code: S('m9 7-5 5 5 5M15 7l5 5-5 5'),
28
+ 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>`,
29
+ 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>`,
30
+ source: S('m8 7-5 5 5 5M16 7l5 5-5 5M13.5 4l-3 16'),
31
+ 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>`,
32
+ 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>`,
33
+ close: S('m6 6 12 12M18 6 6 18'),
34
+ 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>`,
35
+ format: S('M4 6h10M4 12h16M4 18h7M18 4v6m0 0 2.5-2.5M18 10l-2.5-2.5'),
36
+ check: S('m5 13 4 4L19 7'),
37
+ 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>`,
38
+ plus: S('M12 5v14M5 12h14'),
39
+ minus: S('M5 12h14'),
40
+ 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>`,
41
+ 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>`,
42
+ 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>`,
43
+ 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>`,
44
+ 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>`,
45
+ }
46
+
47
+ export function icon(name) {
48
+ return icons[name] || ''
49
+ }
@@ -0,0 +1,140 @@
1
+ /** 粘贴 / 拖拽:截图与文件直传、Word 内容净化、外链图片可选本地化 */
2
+ import { sanitizeHtml, isWordHtml, cleanWordHtml } from './sanitize.js'
3
+ import { escapeHtml } from './sanitize.js'
4
+
5
+ export function attachPaste(editor) {
6
+ editor.root.addEventListener('paste', async (event) => {
7
+ if (editor.readOnly || !editor.options.paste.enabled) return
8
+ const dt = event.clipboardData
9
+ if (!dt) return
10
+ event.preventDefault()
11
+
12
+ const files = filesFromDataTransfer(dt)
13
+ if (files.length) {
14
+ if (editor.options.paste.uploadFiles) {
15
+ await editor.media.addFiles(files)
16
+ editor.toast.show(`已上传 ${files.length} 个文件`)
17
+ } else {
18
+ editor.toast.warn('当前配置不允许粘贴上传文件')
19
+ }
20
+ return
21
+ }
22
+
23
+ const html = dt.getData('text/html')
24
+ const text = dt.getData('text/plain')
25
+
26
+ if (html && editor.options.paste.clean) {
27
+ let clean = isWordHtml(html) ? cleanWordHtml(html) : html
28
+ clean = sanitizeHtml(clean, { allowEmpty: true })
29
+ if (editor.options.paste.localizeImages) clean = await localizeImages(editor, clean)
30
+ editor.commands.insertHTML(clean, { clean: false })
31
+ if (isWordHtml(html)) editor.toast.show('已清理 Word/WPS 格式')
32
+ } else if (text) {
33
+ const htmlText = text
34
+ .split(/\r?\n/)
35
+ .map((line) => `<p>${escapeHtml(line) || '<br>'}</p>`)
36
+ .join('')
37
+ editor.commands.insertHTML(htmlText, { clean: false })
38
+ }
39
+ })
40
+ }
41
+
42
+ export function filesFromDataTransfer(dt) {
43
+ const out = []
44
+ if (dt.items?.length) {
45
+ for (const item of dt.items) {
46
+ if (item.kind === 'file') {
47
+ const file = item.getAsFile()
48
+ if (file) out.push(normalizePastedFile(file, out.length))
49
+ }
50
+ }
51
+ }
52
+ if (!out.length && dt.files?.length) out.push(...Array.from(dt.files).map((file, i) => normalizePastedFile(file, i)))
53
+ return out
54
+ }
55
+
56
+ /** 截图粘贴得到的 File 通常没有文件名,补一个便于展示 */
57
+ function normalizePastedFile(file, index) {
58
+ if (file.name && file.name !== 'image.png') return file
59
+ const ext = (file.type.split('/')[1] || 'png').replace('jpeg', 'jpg').replace('+xml', '')
60
+ const stamp = new Date().toISOString().slice(11, 19).replace(/:/g, '')
61
+ return new File([file], `pasted-${stamp}-${index}.${ext}`, { type: file.type, lastModified: file.lastModified })
62
+ }
63
+
64
+ /** 拖拽上传:把光标移到落点后插入 */
65
+ export function attachDrop(editor) {
66
+ const zone = editor.root
67
+ let depth = 0
68
+
69
+ const hasFiles = (event) => Array.from(event.dataTransfer?.types || []).includes('Files')
70
+
71
+ zone.addEventListener('dragenter', (event) => {
72
+ if (!hasFiles(event) || editor.readOnly) return
73
+ event.preventDefault()
74
+ depth += 1
75
+ editor.el.classList.add('ke-is-dragover')
76
+ })
77
+ zone.addEventListener('dragover', (event) => {
78
+ if (!hasFiles(event) || editor.readOnly) return
79
+ event.preventDefault()
80
+ event.dataTransfer.dropEffect = 'copy'
81
+ })
82
+ zone.addEventListener('dragleave', (event) => {
83
+ if (!hasFiles(event)) return
84
+ depth = Math.max(0, depth - 1)
85
+ if (depth === 0) editor.el.classList.remove('ke-is-dragover')
86
+ })
87
+ zone.addEventListener('drop', async (event) => {
88
+ if (!hasFiles(event) || editor.readOnly) return
89
+ event.preventDefault()
90
+ depth = 0
91
+ editor.el.classList.remove('ke-is-dragover')
92
+ placeCaretAtPoint(editor, event)
93
+ const files = [...(event.dataTransfer.files || [])]
94
+ if (!files.length) return
95
+ if (editor.options.paste.uploadFiles) {
96
+ const count = await editor.media.addFiles(files)
97
+ if (count) editor.toast.show(`已上传 ${count} 个文件`)
98
+ }
99
+ })
100
+ }
101
+
102
+ function placeCaretAtPoint(editor, event) {
103
+ let range = null
104
+ if (document.caretRangeFromPoint) range = document.caretRangeFromPoint(event.clientX, event.clientY)
105
+ else if (document.caretPositionFromPoint) {
106
+ const pos = document.caretPositionFromPoint(event.clientX, event.clientY)
107
+ if (pos) {
108
+ range = document.createRange()
109
+ range.setStart(pos.offsetNode, pos.offset)
110
+ range.collapse(true)
111
+ }
112
+ }
113
+ if (range && editor.root.contains(range.commonAncestorContainer)) {
114
+ const sel = window.getSelection()
115
+ sel.removeAllRanges()
116
+ sel.addRange(range)
117
+ } else {
118
+ editor.focus()
119
+ }
120
+ }
121
+
122
+ /** 外链图片 → 下载后走同一套分片上传(默认关闭,避免跨域噪音) */
123
+ async function localizeImages(editor, html) {
124
+ const doc = new DOMParser().parseFromString(`<div>${html}</div>`, 'text/html')
125
+ const imgs = [...doc.body.querySelectorAll('img')].filter((img) => /^https?:/i.test(img.getAttribute('src') || ''))
126
+ for (const img of imgs) {
127
+ try {
128
+ const res = await fetch(img.src, { mode: 'cors' })
129
+ if (!res.ok) continue
130
+ const blob = await res.blob()
131
+ const file = new File([blob], img.alt || `remote-${Date.now()}.jpg`, { type: blob.type || 'image/jpeg' })
132
+ const result = await editor.media.upload(file, 'image')
133
+ img.remove()
134
+ if (result?.url) editor.toast.show('外链图片已本地化')
135
+ } catch {
136
+ /* 跨域失败则保留原始地址 */
137
+ }
138
+ }
139
+ return doc.body.innerHTML.trim()
140
+ }
@@ -0,0 +1,182 @@
1
+ /** HTML 净化:白名单标签/属性,剔除脚本、事件属性与危险协议 */
2
+
3
+ const ALLOWED_TAGS = new Set([
4
+ 'a', 'abbr', 'b', 'blockquote', 'br', 'code', 'col', 'colgroup', 'dd', 'del', 'div', 'dl', 'dt',
5
+ 'em', 'figcaption', 'figure', 'font', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'hr', 'i', 'img', 'ins',
6
+ 'kbd', 'li', 'mark', 'ol', 'p', 'pre', 's', 'samp', 'section', 'small', 'span', 'strong', 'sub',
7
+ 'sup', 'table', 'tbody', 'td', 'tfoot', 'th', 'thead', 'tr', 'u', 'ul', 'video', 'source',
8
+ ])
9
+
10
+ /** 标签级属性白名单(* 表示所有标签通用) */
11
+ const GLOBAL_ATTRS = new Set(['style', 'class'])
12
+ const TAG_ATTRS = {
13
+ A: ['href', 'title', 'target', 'rel'],
14
+ IMG: ['src', 'alt', 'title', 'width', 'height'],
15
+ VIDEO: ['src', 'poster', 'controls', 'loop', 'muted', 'playsinline', 'preload', 'width', 'height'],
16
+ SOURCE: ['src', 'type'],
17
+ FONT: ['size', 'color'],
18
+ TD: ['colspan', 'rowspan'],
19
+ TH: ['colspan', 'rowspan'],
20
+ OL: ['start'],
21
+ LI: ['value'],
22
+ }
23
+ /** 允许透传的自定义数据属性前缀 */
24
+ const DATA_PREFIX = ['data-k-', 'data-keditor-']
25
+
26
+ const SAFE_URL_RE = /^(?:https?:|mailto:|tel:|blob:|\/|#|\.{1,2}\/|[^:]*$)/i
27
+ const SAFE_DATA_RE = /^data:image\/(?:png|jpe?g|gif|webp|svg\+xml);/i
28
+
29
+ export function isSafeUrl(url) {
30
+ if (!url) return false
31
+ const value = String(url).trim().replace(/\s+/g, '')
32
+ if (/^(javascript|vbscript|file|about):/i.test(value)) return false
33
+ if (value.startsWith('data:')) return SAFE_DATA_RE.test(value)
34
+ return SAFE_URL_RE.test(value)
35
+ }
36
+
37
+ /** 逐条清洗 style 声明,丢弃 expression / url(javascript:) 等 */
38
+ function sanitizeStyle(value) {
39
+ const out = []
40
+ for (const decl of String(value).split(';')) {
41
+ const idx = decl.indexOf(':')
42
+ if (idx < 0) continue
43
+ const prop = decl.slice(0, idx).trim().toLowerCase()
44
+ const val = decl.slice(idx + 1).trim()
45
+ if (!prop || !val) continue
46
+ if (!/^[a-z-]+$/.test(prop)) continue
47
+ if (prop.startsWith('mso-') || prop.startsWith('-mso-')) continue
48
+ if (/expression|javascript:|behavior:|url\(\s*['"]?\s*(javascript|data):/i.test(val)) continue
49
+ out.push(`${prop}:${val}`)
50
+ }
51
+ return out.join(';')
52
+ }
53
+
54
+ /** class 只保留安全字符,避免与外部样式选择器冲突时引入意外结构 */
55
+ function sanitizeClass(value) {
56
+ return String(value)
57
+ .split(/\s+/)
58
+ .filter((name) => /^[\w-]+$/.test(name) && !/^(script|javascript)/i.test(name))
59
+ .join(' ')
60
+ }
61
+
62
+ function keepAttribute(tagName, attrName, attrValue) {
63
+ const name = attrName.toLowerCase()
64
+ if (name.startsWith('on')) return false
65
+ if (GLOBAL_ATTRS.has(name)) return true
66
+ if (DATA_PREFIX.some((prefix) => name.startsWith(prefix))) return true
67
+ const list = TAG_ATTRS[tagName] || []
68
+ return list.includes(name)
69
+ }
70
+
71
+ export function sanitizeHtml(html, { allowEmpty = false } = {}) {
72
+ if (!html) return allowEmpty ? '' : '<p><br></p>'
73
+ const doc = new DOMParser().parseFromString(`<div>${html}</div>`, 'text/html')
74
+ const root = doc.body.firstChild
75
+ walk(root)
76
+ const result = root.innerHTML.trim()
77
+ if (!result && !allowEmpty) return '<p><br></p>'
78
+ return result
79
+ }
80
+
81
+ function walk(node) {
82
+ const children = Array.from(node.childNodes)
83
+ for (const child of children) {
84
+ if (child.nodeType === 8) {
85
+ child.remove() // 注释
86
+ continue
87
+ }
88
+ if (child.nodeType === 3) continue
89
+ if (child.nodeType !== 1) {
90
+ child.remove()
91
+ continue
92
+ }
93
+ const tagName = child.tagName
94
+ if (!ALLOWED_TAGS.has(tagName.toLowerCase())) {
95
+ // 未授权标签:保留其文本内容(拆解),危险标签整体丢弃
96
+ if (tagName === 'SCRIPT' || tagName === 'STYLE' || tagName === 'IFRAME' || tagName === 'OBJECT' || tagName === 'EMBED' || tagName === 'FORM' || tagName === 'LINK' || tagName === 'META') {
97
+ child.remove()
98
+ continue
99
+ }
100
+ const parent = child.parentNode
101
+ while (child.firstChild) parent.insertBefore(child.firstChild, child)
102
+ parent.removeChild(child)
103
+ continue
104
+ }
105
+ for (const attr of Array.from(child.attributes)) {
106
+ if (!keepAttribute(tagName, attr.name, attr.value)) {
107
+ child.removeAttribute(attr.name)
108
+ continue
109
+ }
110
+ const lower = attr.name.toLowerCase()
111
+ if (lower === 'style') child.setAttribute('style', sanitizeStyle(attr.value))
112
+ else if (lower === 'class') {
113
+ const cls = sanitizeClass(attr.value)
114
+ if (cls) child.setAttribute('class', cls)
115
+ else child.removeAttribute('class')
116
+ } else if (lower === 'href' || lower === 'src' || lower === 'poster') {
117
+ if (!isSafeUrl(attr.value)) child.removeAttribute(attr.name)
118
+ }
119
+ }
120
+ if (tagName === 'A' && child.getAttribute('target') === '_blank') child.setAttribute('rel', 'noopener noreferrer')
121
+ if (child.getAttribute('href') === '' || !child.getAttribute('href')) {
122
+ if (tagName === 'A') child.removeAttribute('href')
123
+ }
124
+ walk(child)
125
+ }
126
+ }
127
+
128
+ /** Word / WPS 粘贴清洗:去 office 专有节点,font 尺寸转 px */
129
+ const WORD_FONT_SIZES = { 1: 10, 2: 13, 3: 16, 4: 18, 5: 24, 6: 32, 7: 48 }
130
+
131
+ export function isWordHtml(html) {
132
+ return /urn:schemas-microsoft-com|class=["']?Mso|ProgID|w:val=/i.test(html)
133
+ }
134
+
135
+ export function cleanWordHtml(html) {
136
+ const doc = new DOMParser().parseFromString(`<div>${html}</div>`, 'text/html')
137
+ const root = doc.body.firstChild
138
+ root.querySelectorAll('*').forEach((node) => {
139
+ const tag = node.tagName.toLowerCase()
140
+ if (tag.startsWith('o:') || tag.startsWith('w:') || tag === 'style' || tag === 'script' || tag === 'link' || tag === 'meta') {
141
+ node.remove()
142
+ return
143
+ }
144
+ if (tag === 'img') {
145
+ // 丢弃 office 图标类占位图(宽或高 <= 2px)
146
+ const width = Number(node.getAttribute('width') || 0)
147
+ const height = Number(node.getAttribute('height') || 0)
148
+ if ((width && width <= 3) || (height && height <= 3)) node.remove()
149
+ return
150
+ }
151
+ if (tag === 'font') {
152
+ const size = WORD_FONT_SIZES[Number(node.getAttribute('size'))]
153
+ const span = doc.createElement('span')
154
+ const styles = []
155
+ if (size) styles.push(`font-size:${size}px`)
156
+ if (node.color) styles.push(`color:${node.color}`)
157
+ if (styles.length) span.setAttribute('style', styles.join(';'))
158
+ while (node.firstChild) span.appendChild(node.firstChild)
159
+ node.replaceWith(span)
160
+ return
161
+ }
162
+ for (const attr of Array.from(node.attributes)) {
163
+ const name = attr.name.toLowerCase()
164
+ if (name.startsWith('mso-') || name === 'class' || name.startsWith('_') || name.startsWith('w:') || name.startsWith('o:') || name === 'lang' || name === 'dir') {
165
+ node.removeAttribute(attr.name)
166
+ }
167
+ }
168
+ })
169
+ return root.innerHTML
170
+ }
171
+
172
+ export function escapeHtml(text) {
173
+ return String(text).replace(/[&<>"']/g, (ch) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[ch])
174
+ }
175
+
176
+ /** 纯文本(用于字数统计与 getData('text')) */
177
+ export function toPlainText(html) {
178
+ const doc = new DOMParser().parseFromString(`<div>${html}</div>`, 'text/html')
179
+ doc.body.querySelectorAll('style,script').forEach((n) => n.remove())
180
+ doc.body.innerHTML = doc.body.innerHTML.replace(/<\/(p|div|h[1-6]|li|blockquote|pre|tr)>/gi, '\n')
181
+ return doc.body.textContent.replace(/\u00a0/g, ' ').replace(/\n{3,}/g, '\n\n').trim()
182
+ }
@@ -0,0 +1,129 @@
1
+ /** 选区 / 光标工具 */
2
+
3
+ /** 当前选区是否落在 root 内 */
4
+ export function getRange(root) {
5
+ const sel = window.getSelection()
6
+ if (!sel || sel.rangeCount === 0) return null
7
+ const range = sel.getRangeAt(0)
8
+ if (!root.contains(range.commonAncestorContainer)) return null
9
+ return range
10
+ }
11
+
12
+ export function hasSelection(root) {
13
+ const range = getRange(root)
14
+ return !!(range && !range.collapsed && range.toString().trim() !== '')
15
+ }
16
+
17
+ export function saveRanges(root) {
18
+ const sel = window.getSelection()
19
+ if (!sel || sel.rangeCount === 0) return null
20
+ const range = sel.getRangeAt(0)
21
+ if (!root.contains(range.commonAncestorContainer)) return null
22
+ return { start: range.startOffset, end: range.endOffset, node: range.commonAncestorContainer }
23
+ }
24
+
25
+ /** 用「纯文本偏移」记录光标,便于 undo/redo 后恢复位置 */
26
+ export function caretOffset(root) {
27
+ const sel = window.getSelection()
28
+ if (!sel || sel.rangeCount === 0) return null
29
+ const range = sel.getRangeAt(0)
30
+ if (!root.contains(range.startContainer)) return null
31
+ let offset = 0
32
+ const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT, {
33
+ acceptNode(node) {
34
+ if (node === range.startContainer) return NodeFilter.FILTER_ACCEPT
35
+ offset += node.textContent.length
36
+ return NodeFilter.FILTER_SKIP
37
+ },
38
+ })
39
+ const found = walker.nextNode()
40
+ if (!found) return range.startContainer === root ? 0 : null
41
+ return offset + range.startOffset
42
+ }
43
+
44
+ export function setCaretOffset(root, offset) {
45
+ if (offset === null || offset === undefined) return
46
+ const sel = window.getSelection()
47
+ let remaining = Math.max(0, offset)
48
+ const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT)
49
+ let node = walker.nextNode()
50
+ let last = null
51
+ while (node) {
52
+ const len = node.textContent.length
53
+ if (remaining <= len) {
54
+ try {
55
+ sel.setBaseAndExtent(node, remaining, node, remaining)
56
+ } catch {
57
+ /* ignore */
58
+ }
59
+ return
60
+ }
61
+ remaining -= len
62
+ last = node
63
+ node = walker.nextNode()
64
+ }
65
+ if (last) {
66
+ try {
67
+ sel.setBaseAndExtent(last, last.textContent.length, last, last.textContent.length)
68
+ } catch {
69
+ /* ignore */
70
+ }
71
+ }
72
+ }
73
+
74
+ /**
75
+ * 在光标处插入节点
76
+ * - inline: 行内节点(链接等),直接在选区处插入
77
+ * - 默认块级:媒体/表格/代码块等始终作为独立块插入,不会嵌套进标题/列表/引用
78
+ */
79
+ export function insertNode(root, node, { inline = false, selectAfter = true } = {}) {
80
+ root.focus()
81
+ const range = getRange(root)
82
+ if (!range) {
83
+ root.appendChild(node)
84
+ ensureEditableTail(root)
85
+ return node
86
+ }
87
+ if (!range.collapsed) range.deleteContents()
88
+
89
+ if (inline) {
90
+ range.insertNode(node)
91
+ } else {
92
+ const block = closestBlock(range.startContainer, root)
93
+ if (!block || block === root) root.appendChild(node)
94
+ else block.after(node)
95
+ }
96
+
97
+ const after = document.createRange()
98
+ after.setStartAfter(node)
99
+ after.collapse(true)
100
+ const sel = window.getSelection()
101
+ sel.removeAllRanges()
102
+ sel.addRange(after)
103
+ ensureEditableTail(root)
104
+ if (selectAfter && sel.rangeCount === 0) root.focus()
105
+ return node
106
+ }
107
+
108
+ /** contenteditable 末尾若为媒体节点,补一个空段落方便继续输入 */
109
+ export function ensureEditableTail(root) {
110
+ const last = root.lastElementChild
111
+ if (!last) {
112
+ root.appendChild(document.createElement('p'))
113
+ return
114
+ }
115
+ if (/^(IMG|VIDEO|IFRAME)$/.test(last.tagName) || last.dataset.kmedia !== undefined) {
116
+ const p = document.createElement('p')
117
+ p.appendChild(document.createElement('br'))
118
+ root.appendChild(p)
119
+ }
120
+ }
121
+
122
+ export function closestBlock(node, root) {
123
+ let current = node
124
+ while (current && current !== root) {
125
+ if (current.nodeType === 1 && /^(P|DIV|H[1-6]|LI|BLOCKQUOTE|PRE|SECTION|TD|TH)$/.test(current.tagName)) return current
126
+ current = current.parentNode
127
+ }
128
+ return null
129
+ }