jvs-ppt-ui 0.0.33 → 0.0.34

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.
@@ -15,7 +15,13 @@ import {
15
15
  reapplyBlockStylesToListItems
16
16
  } from '../../utils/listIndent'
17
17
  import { parseColor, hexToRgba } from './useSidebarShapeFormat'
18
- import { getFormatFromElement, getFormatFromSelection } from '../../utils/canvas/formatPainter'
18
+ import {
19
+ getFormatFromElement,
20
+ getFormatFromSelection,
21
+ isTransparentTextBg,
22
+ applyOrClearRangeHighlight,
23
+ applyTextStyleToHtml
24
+ } from '../../utils/canvas/formatPainter'
19
25
  import { resolveEffectiveElementFontSize } from '../../utils/canvas/elementStyles'
20
26
  import { isEllipseShape } from '../../utils/line'
21
27
  import { defaultStyleRecipe } from '../presetThemes'
@@ -147,6 +153,27 @@ export function useSidebarTextFormat(
147
153
  .replace(/line-height\s*:\s*[^;"]+;?/gi, '')
148
154
  .replace(/color\s*:\s*[^;"]+;?/gi, '')
149
155
  }
156
+
157
+ if (el.type === 'text' && el.autoFit?.type !== 'text') {
158
+ const fsNum = parseFloat(newSize) || typeConf.defaultFontSize || 18
159
+ const lhNum = parseFloat(String(newLineHeight)) || typeConf.defaultLineHeight || 1.2
160
+ const isVert = el.style?.writingMode === 'vertical-rl' || el.style?.writingMode === 'vertical-lr'
161
+ if (isVert) {
162
+ const minW = Math.max(48, Math.ceil(fsNum * lhNum + 16))
163
+ const curW = parseFloat(el.style?.width) || el.width || 0
164
+ if (curW > 0 && curW < minW && el.style?.width !== 'auto') {
165
+ el.style.width = `${minW}px`
166
+ el.width = minW
167
+ }
168
+ } else {
169
+ const minH = Math.max(typeConf.defaultHeight || 36, Math.ceil(fsNum * lhNum + 12))
170
+ const curH = parseFloat(el.style?.height) || el.height || 0
171
+ if (curH > 0 && curH < minH && el.style?.height !== 'auto') {
172
+ el.style.height = `${minH}px`
173
+ el.height = minH
174
+ }
175
+ }
176
+ }
150
177
  }
151
178
 
152
179
  addHistorySnapshot()
@@ -311,23 +338,187 @@ export function useSidebarTextFormat(
311
338
  }
312
339
  })
313
340
 
341
+ function extractBackgroundColorFromHtml(html: string | undefined | null): string | null {
342
+ if (!html || typeof html !== 'string') return null
343
+ const clean = html.replace(/<[^>]*>/g, '').replace(/&nbsp;/gi, '').trim()
344
+ if (!clean) return null
345
+
346
+ if (typeof document !== 'undefined') {
347
+ const div = document.createElement('div')
348
+ div.innerHTML = html
349
+ const inlineNodes = div.querySelectorAll('span, font, mark, b, strong, i, em, u, s, a')
350
+ for (const node of Array.from(inlineNodes)) {
351
+ const bg = (node as HTMLElement).style?.backgroundColor
352
+ if (bg && !isTransparentTextBg(bg)) {
353
+ return colorToHex(bg)
354
+ }
355
+ }
356
+ }
357
+
358
+ const bgMatch = html.match(/background-color\s*:\s*([^;'"\}]+)/i)
359
+ if (bgMatch && bgMatch[1]) {
360
+ const rawBg = bgMatch[1].trim()
361
+ if (!isTransparentTextBg(rawBg)) {
362
+ return colorToHex(rawBg)
363
+ }
364
+ }
365
+ return null
366
+ }
367
+
314
368
  const styleTextBackground = computed({
315
- get() { return getStyleVal('textBackground', 'transparent') },
369
+ get() {
370
+ selectionTrigger.value
371
+ const el = selectedElement.value as any
372
+ if (!el) return 'transparent'
373
+
374
+ // 1. 若存在当前选区或保存的选区,优先读取选区文字的高亮背景色
375
+ if (typeof window !== 'undefined') {
376
+ const container = document.getElementById(`editable-${el.id}`)
377
+ if (container) {
378
+ const sel = window.getSelection()
379
+ const activeRange = (sel && sel.rangeCount > 0 && container.contains(sel.getRangeAt(0).commonAncestorContainer))
380
+ ? sel.getRangeAt(0)
381
+ : (savedSidebarRange && container.contains(savedSidebarRange.commonAncestorContainer) ? savedSidebarRange : null)
382
+
383
+ if (activeRange) {
384
+ const blockTags = new Set(['P', 'DIV', 'LI', 'UL', 'OL', 'H1', 'H2', 'H3', 'H4', 'H5', 'H6', 'TD', 'TH', 'TABLE'])
385
+ let startNode: Node | null = activeRange.startContainer
386
+ if (startNode.nodeType === Node.ELEMENT_NODE && startNode.childNodes[activeRange.startOffset]) {
387
+ startNode = startNode.childNodes[activeRange.startOffset]
388
+ }
389
+ let curr: Node | null = startNode?.nodeType === Node.TEXT_NODE ? startNode.parentElement : startNode
390
+ while (curr && curr !== container) {
391
+ if (curr instanceof HTMLElement && !blockTags.has(curr.tagName)) {
392
+ const inlineBg = curr.style?.backgroundColor
393
+ if (inlineBg && !isTransparentTextBg(inlineBg)) {
394
+ return colorToHex(inlineBg)
395
+ }
396
+ }
397
+ curr = curr.parentElement
398
+ }
399
+
400
+ if (!activeRange.collapsed) {
401
+ const inlineEls = container.querySelectorAll('span, font, mark, b, strong, i, em, u, s, a')
402
+ for (const node of Array.from(inlineEls)) {
403
+ if (activeRange.intersectsNode(node)) {
404
+ const bg = (node as HTMLElement).style?.backgroundColor
405
+ if (bg && !isTransparentTextBg(bg)) {
406
+ return colorToHex(bg)
407
+ }
408
+ }
409
+ }
410
+ const elBg = getStyleVal('textBackground', 'transparent')
411
+ return (!elBg || isTransparentTextBg(elBg)) ? 'transparent' : colorToHex(elBg)
412
+ }
413
+ }
414
+ }
415
+ }
416
+
417
+ // 2. 元素级 style.textBackground
418
+ const styleBg = getStyleVal('textBackground', '')
419
+ if (styleBg && !isTransparentTextBg(styleBg)) {
420
+ return colorToHex(styleBg)
421
+ }
422
+
423
+ // 3. 从元素 HTML 内容或实时容器提取高亮色
424
+ const container = typeof document !== 'undefined' ? document.getElementById(`editable-${el.id}`) : null
425
+ const liveHtml = container?.innerHTML
426
+ const rawHtml = liveHtml || (el.type === 'shape'
427
+ ? (typeof el.text === 'string' ? el.text : el.text?.content)
428
+ : el.content)
429
+ const fromHtml = extractBackgroundColorFromHtml(rawHtml)
430
+ if (fromHtml) return fromHtml
431
+
432
+ if (el.type === 'group' && Array.isArray(el.elements)) {
433
+ for (const child of el.elements) {
434
+ if (child.style?.textBackground && !isTransparentTextBg(child.style.textBackground)) {
435
+ return colorToHex(child.style.textBackground)
436
+ }
437
+ const childHtml = child.type === 'shape'
438
+ ? (typeof child.text === 'string' ? child.text : child.text?.content)
439
+ : child.content
440
+ const childBg = extractBackgroundColorFromHtml(childHtml)
441
+ if (childBg) return childBg
442
+ }
443
+ }
444
+
445
+ return 'transparent'
446
+ },
316
447
  set(val: string) {
317
- setStyleVal('textBackground', val)
448
+ const normalizedVal = isTransparentTextBg(val) ? 'transparent' : val
318
449
  const el = selectedElement.value as any
450
+
451
+ // 1. 若当前存在非折叠的富文本划词选区,优先仅对选区应用或清除高亮色
452
+ if (el && typeof window !== 'undefined') {
453
+ const container = document.getElementById(`editable-${el.id}`)
454
+ const sel = window.getSelection()
455
+ const activeRange = (sel && sel.rangeCount > 0 && !sel.getRangeAt(0).collapsed && container && container.contains(sel.getRangeAt(0).commonAncestorContainer))
456
+ ? sel.getRangeAt(0)
457
+ : (savedSidebarRange && !savedSidebarRange.collapsed && container && container.contains(savedSidebarRange.commonAncestorContainer) ? savedSidebarRange : null)
458
+
459
+ if (activeRange && !activeRange.collapsed && container && (!el.content || !el.content.includes('<table')) && !el.latex) {
460
+ const updatedRange = applyOrClearRangeHighlight(container, activeRange, normalizedVal, el)
461
+ if (updatedRange) {
462
+ savedSidebarRange = updatedRange
463
+ }
464
+ container.style.backgroundColor = el.type === 'text' ? (el.style?.fill || 'transparent') : ''
465
+ if (el.type === 'shape') {
466
+ if (el.text && typeof el.text === 'object') {
467
+ el.text.content = container.innerHTML
468
+ } else {
469
+ el.text = container.innerHTML
470
+ }
471
+ } else {
472
+ el.content = container.innerHTML
473
+ }
474
+ selectionTrigger.value++
475
+ addHistorySnapshot()
476
+ return
477
+ }
478
+
479
+ // 2. 整框应用或清除前,若容器内已有最新编辑的 HTML,先同步到元素模型,防止丢失或漏清内联高亮
480
+ if (container && (!el.content || !el.content.includes('<table')) && !el.latex) {
481
+ const currentDomHtml = container.innerHTML
482
+ if (currentDomHtml && currentDomHtml.trim()) {
483
+ if (el.type === 'shape') {
484
+ if (el.text && typeof el.text === 'object') {
485
+ el.text.content = currentDomHtml
486
+ } else {
487
+ el.text = currentDomHtml
488
+ }
489
+ } else {
490
+ el.content = currentDomHtml
491
+ }
492
+ }
493
+ }
494
+ }
495
+
496
+ // 3. 整框应用或清除高亮色
497
+ setStyleVal('textBackground', normalizedVal)
319
498
  if (el) {
499
+ if (!el.style) el.style = {}
500
+ el.style.textBackground = normalizedVal
320
501
  const container = document.getElementById(`editable-${el.id}`)
321
- if (container) {
322
- container.style.backgroundColor = ''
502
+ if (container && (!el.content || !el.content.includes('<table')) && !el.latex) {
503
+ container.style.backgroundColor = el.type === 'text' ? (el.style?.fill || 'transparent') : ''
323
504
  if (el.type === 'shape') {
324
- const raw = typeof el.text === 'string' ? el.text : (el.text?.content || '')
325
- if (raw) container.innerHTML = raw
326
- } else if (el.content) {
327
- container.innerHTML = el.content
505
+ const raw = typeof el.text === 'string' ? el.text : (el.text?.content || container.innerHTML || '')
506
+ const formatted = applyTextStyleToHtml(raw, { textBackground: normalizedVal })
507
+ if (el.text && typeof el.text === 'object') {
508
+ el.text.content = formatted
509
+ } else {
510
+ el.text = formatted
511
+ }
512
+ container.innerHTML = formatted
513
+ } else {
514
+ const raw = el.content || container.innerHTML || ''
515
+ const formatted = applyTextStyleToHtml(raw, { textBackground: normalizedVal })
516
+ el.content = formatted
517
+ container.innerHTML = formatted
328
518
  }
329
519
  }
330
520
  }
521
+ selectionTrigger.value++
331
522
  }
332
523
  })
333
524
 
@@ -351,10 +542,26 @@ export function useSidebarTextFormat(
351
542
  if (dom) {
352
543
  if (!selectedElement.value.style) selectedElement.value.style = {} as any
353
544
  selectedElement.value.style.height = `${dom.offsetHeight}px`
545
+ selectedElement.value.height = dom.offsetHeight
546
+ if (selectedElement.value.autoFit?.type === 'shape') {
547
+ selectedElement.value.style.width = 'auto'
548
+ } else if (!selectedElement.value.style.width || selectedElement.value.style.width === 'auto') {
549
+ selectedElement.value.style.width = `${dom.offsetWidth}px`
550
+ selectedElement.value.width = dom.offsetWidth
551
+ }
354
552
  }
355
553
  } else if (isPrevVertical && !isNextVertical) {
356
- if (selectedElement.value.style) {
554
+ const dom = document.getElementById(`canvas-el-${selectedElement.value.id}`)
555
+ if (!selectedElement.value.style) selectedElement.value.style = {} as any
556
+ if (dom && (!selectedElement.value.style.width || selectedElement.value.style.width === 'auto')) {
557
+ selectedElement.value.style.width = `${dom.offsetWidth}px`
558
+ selectedElement.value.width = dom.offsetWidth
559
+ }
560
+ if (selectedElement.value.autoFit?.type === 'shape') {
357
561
  selectedElement.value.style.height = 'auto'
562
+ } else if (dom && (!selectedElement.value.style.height || selectedElement.value.style.height === 'auto')) {
563
+ selectedElement.value.style.height = `${dom.offsetHeight}px`
564
+ selectedElement.value.height = dom.offsetHeight
358
565
  }
359
566
  }
360
567
  }
@@ -428,16 +635,16 @@ export function useSidebarTextFormat(
428
635
  const styleAutoFitType = computed({
429
636
  get() {
430
637
  const el = selectedElement.value as any
431
- if (!el) return 'shape'
432
- if (!el.autoFit) {
433
- return ((el.style?.height && el.style.height !== 'auto') || (el.height && el.height > 0)) ? 'none' : 'shape'
638
+ if (!el) return 'none'
639
+ if (el.autoFit && el.autoFit.type) {
640
+ return el.autoFit.type
434
641
  }
435
- return el.autoFit.type || (((el.style?.height && el.style.height !== 'auto') || (el.height && el.height > 0)) ? 'none' : 'shape')
642
+ return 'none'
436
643
  },
437
644
  set(val: string) {
438
645
  const el = selectedElement.value as any
439
646
  if (!el) return
440
- const current = el.autoFit?.type || (((el.style?.height && el.style.height !== 'auto') || (el.height && el.height > 0)) ? 'none' : 'shape')
647
+ const current = el.autoFit?.type || 'none'
441
648
  if (current === val && el.autoFit) return
442
649
 
443
650
  el.autoFit = {
@@ -450,11 +657,13 @@ export function useSidebarTextFormat(
450
657
  const dom = document.getElementById(`canvas-el-${el.id}`)
451
658
  if (dom) {
452
659
  if (!el.style) el.style = {}
453
- if (el.style.height === 'auto') {
660
+ if (!el.style.height || el.style.height === 'auto') {
454
661
  el.style.height = `${dom.offsetHeight}px`
662
+ el.height = dom.offsetHeight
455
663
  }
456
- if (el.style.width === 'auto') {
664
+ if (!el.style.width || el.style.width === 'auto') {
457
665
  el.style.width = `${dom.offsetWidth}px`
666
+ el.width = dom.offsetWidth
458
667
  }
459
668
  }
460
669
  } else if (val === 'shape') {
@@ -462,8 +671,20 @@ export function useSidebarTextFormat(
462
671
  if (!el.style) el.style = {}
463
672
  if (el.style.writingMode === 'vertical-rl' || el.style.writingMode === 'vertical-lr') {
464
673
  el.style.width = 'auto'
674
+ nextTick(() => {
675
+ const container = document.getElementById(`editable-${el.id}`)
676
+ const dom = document.getElementById(`canvas-el-${el.id}`)
677
+ const actualW = Math.max(container?.scrollWidth || 0, container?.offsetWidth || 0, dom?.offsetWidth || 0)
678
+ if (actualW > 0) el.width = actualW
679
+ })
465
680
  } else {
466
681
  el.style.height = 'auto'
682
+ nextTick(() => {
683
+ const container = document.getElementById(`editable-${el.id}`)
684
+ const dom = document.getElementById(`canvas-el-${el.id}`)
685
+ const actualH = Math.max(container?.offsetHeight || 0, container?.scrollHeight || 0, dom?.offsetHeight || 0)
686
+ if (actualH > 0) el.height = actualH
687
+ })
467
688
  }
468
689
  } else if (el.type === 'shape') {
469
690
  nextTick(() => {
@@ -497,11 +718,13 @@ export function useSidebarTextFormat(
497
718
  const dom = document.getElementById(`canvas-el-${el.id}`)
498
719
  if (dom) {
499
720
  if (!el.style) el.style = {}
500
- if (el.style.height === 'auto') {
721
+ if (!el.style.height || el.style.height === 'auto') {
501
722
  el.style.height = `${dom.offsetHeight}px`
723
+ el.height = dom.offsetHeight
502
724
  }
503
- if (el.style.width === 'auto') {
725
+ if (!el.style.width || el.style.width === 'auto') {
504
726
  el.style.width = `${dom.offsetWidth}px`
727
+ el.width = dom.offsetWidth
505
728
  }
506
729
  }
507
730
  nextTick(() => {
@@ -4548,7 +4548,7 @@ function addElement(
4548
4548
  const lineHeight = textCfg.lineHeight || typeConf.defaultLineHeight
4549
4549
  const letterSpacing = textCfg.letterSpacing !== undefined ? `${textCfg.letterSpacing}px` : '0px'
4550
4550
  const defaultW = typeConf.defaultWidth
4551
- const defaultH = typeConf.defaultHeight
4551
+ const defaultH = Math.max(typeConf.defaultHeight, Math.ceil((parseFloat(fontSize) || typeConf.defaultFontSize) * (parseFloat(String(lineHeight)) || 1.2) + 12))
4552
4552
 
4553
4553
  content = customContent || `<div style="color:${textColor}; font-family:${textFont}; font-size:${fontSize}; font-weight:${fontWeight};">${typeConf.defaultPlaceholder}</div>`
4554
4554
  style = {
@@ -4564,7 +4564,7 @@ function addElement(
4564
4564
  lineHeight: lineHeight,
4565
4565
  letterSpacing: letterSpacing,
4566
4566
  width: initialDimensions?.width !== undefined ? `${initialDimensions.width}px` : (latex ? 'auto' : `${defaultW}px`),
4567
- height: initialDimensions?.height !== undefined ? `${initialDimensions.height}px` : 'auto',
4567
+ height: initialDimensions?.height !== undefined ? `${initialDimensions.height}px` : (latex ? 'auto' : `${defaultH}px`),
4568
4568
  whiteSpace: 'normal',
4569
4569
  verticalAlign: 'middle'
4570
4570
  }
@@ -4674,7 +4674,7 @@ function addElement(
4674
4674
  newElement.textColor = style.color
4675
4675
  newElement.fontFamily = style.fontFamily
4676
4676
  newElement.autoFit = {
4677
- type: 'shape',
4677
+ type: 'none',
4678
4678
  fontScale: 100,
4679
4679
  lnSpcReduction: 0
4680
4680
  }
@@ -4803,14 +4803,14 @@ function addElementAt(
4803
4803
  fontStyle: 'normal',
4804
4804
  fontSize: '20px',
4805
4805
  width: '260px',
4806
- height: 'auto',
4806
+ height: '40px',
4807
4807
  rotate: 0,
4808
4808
  writingMode: 'horizontal-tb',
4809
4809
  whiteSpace: 'normal',
4810
4810
  verticalAlign: 'middle'
4811
4811
  }
4812
4812
  if (subtype === 'vertical') {
4813
- style.width = 'auto'
4813
+ style.width = '48px'
4814
4814
  style.height = '180px'
4815
4815
  style.writingMode = 'vertical-rl'
4816
4816
  }
@@ -4926,7 +4926,7 @@ function addElementAt(
4926
4926
  newElement.textColor = style.color
4927
4927
  newElement.fontFamily = style.fontFamily
4928
4928
  newElement.autoFit = {
4929
- type: 'shape',
4929
+ type: 'none',
4930
4930
  fontScale: 100,
4931
4931
  lnSpcReduction: 0
4932
4932
  }
@@ -7540,7 +7540,7 @@ function convertPPTistToLocalIfNeed(newSlides: any): Slide[] {
7540
7540
  content: content,
7541
7541
  text: text,
7542
7542
  style: style,
7543
- autoFit: el.autoFit || (type === 'text' ? { type: 'shape', fontScale: 100, lnSpcReduction: 0 } : undefined),
7543
+ autoFit: el.autoFit ? { ...el.autoFit } : (type === 'text' ? { type: 'none', fontScale: 100, lnSpcReduction: 0 } : undefined),
7544
7544
  viewBox: el.viewBox,
7545
7545
  path: (type === 'shape' && content && (content.startsWith('M') || content.startsWith('m'))) ? content : el.path,
7546
7546
  start: start,
@@ -145,6 +145,129 @@ export function getFormatFromElement(el: any): ElementFormat | null {
145
145
  return cleaned
146
146
  }
147
147
 
148
+ export function isTransparentTextBg(val: any): boolean {
149
+ if (!val || typeof val !== 'string') return true
150
+ const s = val.trim().toLowerCase()
151
+ if (s === 'transparent' || s === 'none' || s === 'initial' || s === 'inherit') return true
152
+ if (/^rgba\(\s*\d+\s*,\s*\d+\s*,\s*\d+\s*,\s*0(?:\.0+)?\s*\)$/.test(s)) return true
153
+ if (/^#[0-9a-f]{6}00$/.test(s) || /^#[0-9a-f]{3}0$/.test(s)) return true
154
+ return false
155
+ }
156
+
157
+ /**
158
+ * Apply or clear text highlight color on a specific DOM Range inside an editable container.
159
+ * Returns the updated Range (if still valid) so callers can preserve selection.
160
+ */
161
+ export function applyOrClearRangeHighlight(
162
+ container: HTMLElement,
163
+ range: Range,
164
+ color: string,
165
+ el?: any
166
+ ): Range | null {
167
+ const isClear = isTransparentTextBg(color)
168
+ const prevEditable = container.getAttribute('contenteditable')
169
+ if (prevEditable !== 'true') {
170
+ container.setAttribute('contenteditable', 'true')
171
+ }
172
+
173
+ try {
174
+ // If element had a whole-box style.textBackground that wasn't materialized into inline spans yet,
175
+ // materialize it first before clearing a partial selection, then clear style.textBackground.
176
+ if (isClear && el?.style?.textBackground && !isTransparentTextBg(el.style.textBackground)) {
177
+ if (!container.innerHTML.includes('background-color')) {
178
+ container.innerHTML = applyTextStyleToHtml(container.innerHTML, { textBackground: el.style.textBackground })
179
+ }
180
+ el.style.textBackground = 'transparent'
181
+ }
182
+
183
+ const selectedTxt = (range.toString() || '').replace(/\s+/g, '')
184
+ const totalTxt = (container.textContent || '').replace(/\s+/g, '')
185
+
186
+ // If clearing and the selection covers all text in the container, strip all inline text background-color cleanly
187
+ const tableCellTags = new Set(['TABLE', 'THEAD', 'TBODY', 'TFOOT', 'TR', 'TD', 'TH', 'COL', 'COLGROUP'])
188
+ if (isClear && selectedTxt.length > 0 && selectedTxt.length >= totalTxt.length) {
189
+ container.querySelectorAll('*').forEach((node: any) => {
190
+ if (node.style && !tableCellTags.has(node.tagName)) {
191
+ node.style.backgroundColor = ''
192
+ node.style.removeProperty('background-color')
193
+ node.style.background = ''
194
+ node.style.removeProperty('background')
195
+ }
196
+ })
197
+ if (el?.style) {
198
+ el.style.textBackground = 'transparent'
199
+ }
200
+ const sel = window.getSelection()
201
+ if (sel && container.contains(range.commonAncestorContainer)) {
202
+ sel.removeAllRanges()
203
+ sel.addRange(range)
204
+ return sel.rangeCount > 0 ? sel.getRangeAt(0).cloneRange() : null
205
+ }
206
+ return null
207
+ }
208
+
209
+ const sel = window.getSelection()
210
+ if (!sel) return null
211
+
212
+ if (document.activeElement !== container && !container.contains(document.activeElement)) {
213
+ container.focus({ preventScroll: true })
214
+ }
215
+ sel.removeAllRanges()
216
+ sel.addRange(range)
217
+
218
+ const hiliteCmd = document.queryCommandSupported('hiliteColor') ? 'hiliteColor' : 'backColor'
219
+ if (isClear) {
220
+ // Use a sentinel opaque color first so Blink splits any parent <span style="background-color: ...">
221
+ const sentinelHex = '#010203'
222
+ const executed = document.execCommand(hiliteCmd, false, sentinelHex)
223
+ if (!executed && hiliteCmd !== 'backColor') {
224
+ document.execCommand('backColor', false, sentinelHex)
225
+ }
226
+ container.querySelectorAll('*').forEach((node: any) => {
227
+ if (node.style) {
228
+ const bg = (node.style.backgroundColor || '').toLowerCase().replace(/\s+/g, '')
229
+ if (bg === 'rgb(1,2,3)' || bg === '#010203' || bg === 'transparent' || bg === 'rgba(0,0,0,0)') {
230
+ node.style.backgroundColor = ''
231
+ node.style.removeProperty('background-color')
232
+ node.style.background = ''
233
+ node.style.removeProperty('background')
234
+ }
235
+ }
236
+ })
237
+ } else {
238
+ const executed = document.execCommand(hiliteCmd, false, color)
239
+ if (!executed && hiliteCmd !== 'backColor') {
240
+ document.execCommand('backColor', false, color)
241
+ }
242
+ if (sel.rangeCount > 0) {
243
+ const newRange = sel.getRangeAt(0)
244
+ container.querySelectorAll('span, font, mark, b, strong, i, em, u, s, a').forEach((node: any) => {
245
+ if (newRange.intersectsNode(node) && newRange.isPointInRange(node, 0) && node.style?.backgroundColor) {
246
+ node.style.backgroundColor = color
247
+ }
248
+ })
249
+ }
250
+ }
251
+
252
+ // Ensure block elements inside container never keep a full-line background color
253
+ container.querySelectorAll('p, div, li, h1, h2, h3, h4, h5, h6, ul, ol').forEach((block: any) => {
254
+ if (block.style) {
255
+ block.style.backgroundColor = ''
256
+ block.style.removeProperty('background-color')
257
+ block.style.background = ''
258
+ block.style.removeProperty('background')
259
+ }
260
+ })
261
+
262
+ return sel.rangeCount > 0 ? sel.getRangeAt(0).cloneRange() : null
263
+ } finally {
264
+ if (prevEditable !== 'true') {
265
+ if (prevEditable === null) container.removeAttribute('contenteditable')
266
+ else container.setAttribute('contenteditable', prevEditable)
267
+ }
268
+ }
269
+ }
270
+
148
271
  /**
149
272
  * Apply typography styles directly to an HTML string.
150
273
  */
@@ -154,54 +277,78 @@ export function applyTextStyleToHtml(html: string, styles: ElementFormat): strin
154
277
  div.innerHTML = html
155
278
 
156
279
  // 1. 保证所有块级元素(p, div, li 等)背景色透明,绝不被整行涂满
157
- div.querySelectorAll('p, div, li, h1, h2, h3, h4, h5, h6').forEach((block: any) => {
280
+ div.querySelectorAll('p, div, li, h1, h2, h3, h4, h5, h6, ul, ol').forEach((block: any) => {
158
281
  block.style.backgroundColor = ''
159
282
  block.style.removeProperty('background-color')
283
+ block.style.background = ''
284
+ block.style.removeProperty('background')
160
285
  })
161
286
 
162
287
  // 2. 处理文字高亮背景色 textBackground
163
288
  if (styles.textBackground !== undefined) {
164
- const isClear = styles.textBackground === 'transparent' || !styles.textBackground
289
+ const isClear = isTransparentTextBg(styles.textBackground)
165
290
  const bgVal = isClear ? '' : styles.textBackground
166
291
 
167
- const existingSpans = div.querySelectorAll('span')
168
292
  if (isClear) {
169
- existingSpans.forEach((s: HTMLElement) => {
170
- s.style.backgroundColor = ''
171
- s.style.removeProperty('background-color')
293
+ const tableCellTags = new Set(['TABLE', 'THEAD', 'TBODY', 'TFOOT', 'TR', 'TD', 'TH', 'COL', 'COLGROUP'])
294
+ div.querySelectorAll('*').forEach((elem: any) => {
295
+ if (elem.style && !tableCellTags.has(elem.tagName)) {
296
+ elem.style.backgroundColor = ''
297
+ elem.style.removeProperty('background-color')
298
+ elem.style.background = ''
299
+ elem.style.removeProperty('background')
300
+ }
301
+ if (elem.tagName === 'MARK' && elem.parentNode) {
302
+ while (elem.firstChild) {
303
+ elem.parentNode.insertBefore(elem.firstChild, elem)
304
+ }
305
+ elem.parentNode.removeChild(elem)
306
+ }
172
307
  })
173
308
  } else {
174
- const blocks = div.querySelectorAll('p, div, li')
175
- if (blocks.length > 0) {
176
- blocks.forEach((block: any) => {
177
- const spansInBlock = block.querySelectorAll('span')
178
- if (spansInBlock.length > 0) {
179
- spansInBlock.forEach((s: HTMLElement) => {
180
- s.style.backgroundColor = bgVal
181
- })
182
- } else if (block.childNodes.length > 0) {
183
- const span = document.createElement('span')
184
- span.style.backgroundColor = bgVal
185
- while (block.firstChild) {
186
- span.appendChild(block.firstChild)
187
- }
188
- block.appendChild(span)
309
+ const leafBlocks = Array.from(
310
+ div.querySelectorAll('p, div, li, h1, h2, h3, h4, h5, h6, td, th')
311
+ ).filter((b: Element) => !b.querySelector('p, div, li, h1, h2, h3, h4, h5, h6, ul, ol, table')) as HTMLElement[]
312
+
313
+ const applyBgToBlock = (block: HTMLElement) => {
314
+ const textContent = (block.textContent || '').replace(/\u200B/g, '').trim()
315
+ if (!textContent) return
316
+
317
+ // Clear any inner background overrides first so we have a clean uniform highlight
318
+ block.querySelectorAll('*').forEach((child: any) => {
319
+ if (child.style) {
320
+ child.style.backgroundColor = ''
321
+ child.style.removeProperty('background-color')
322
+ child.style.background = ''
323
+ child.style.removeProperty('background')
189
324
  }
190
325
  })
191
- } else {
192
- if (existingSpans.length > 0) {
193
- existingSpans.forEach((s: HTMLElement) => {
194
- s.style.backgroundColor = bgVal
195
- })
196
- } else if (div.childNodes.length > 0) {
326
+
327
+ // If block already has a single SPAN element covering all non-empty children, apply to it directly
328
+ const nonEmptyNodes = Array.from(block.childNodes).filter(
329
+ n => !(n.nodeType === Node.TEXT_NODE && !(n.textContent || '').trim())
330
+ )
331
+ if (
332
+ nonEmptyNodes.length === 1 &&
333
+ nonEmptyNodes[0].nodeType === Node.ELEMENT_NODE &&
334
+ (nonEmptyNodes[0] as HTMLElement).tagName === 'SPAN'
335
+ ) {
336
+ ;(nonEmptyNodes[0] as HTMLElement).style.backgroundColor = bgVal
337
+ } else if (block.childNodes.length > 0) {
197
338
  const span = document.createElement('span')
198
339
  span.style.backgroundColor = bgVal
199
- while (div.firstChild) {
200
- span.appendChild(div.firstChild)
340
+ while (block.firstChild) {
341
+ span.appendChild(block.firstChild)
201
342
  }
202
- div.appendChild(span)
343
+ block.appendChild(span)
203
344
  }
204
345
  }
346
+
347
+ if (leafBlocks.length > 0) {
348
+ leafBlocks.forEach(applyBgToBlock)
349
+ } else {
350
+ applyBgToBlock(div)
351
+ }
205
352
  }
206
353
  }
207
354