jvs-ppt-ui 0.0.38 → 0.0.39

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.
@@ -30,6 +30,7 @@ if (currentApp) {
30
30
 
31
31
  import { useSlides } from '../composables/useSlides'
32
32
  import { builtinSlideTemplates, setCustomTemplates, addCustomTemplate } from '../configs/slideTemplates'
33
+ import { saveDraftToIndexedDB, loadDraftFromIndexedDB, clearDraftFromIndexedDB } from '../utils/localDraftStorage'
33
34
  import type { Slide, SlideMaster, DeckData, PptEditorProps, PptEditorApi, SaveOptions, LoadSourceOptions, LoadSourceResult } from '../types'
34
35
 
35
36
  const props = withDefaults(defineProps<PptEditorProps>(), {
@@ -57,6 +58,8 @@ const props = withDefaults(defineProps<PptEditorProps>(), {
57
58
  templates: undefined,
58
59
  templateBaseUrl: '',
59
60
  replaceBuiltinTemplates: undefined,
61
+ localStorageCache: undefined,
62
+ localStorageKey: '',
60
63
  config: () => ({})
61
64
  })
62
65
 
@@ -78,6 +81,12 @@ const {
78
81
  activeSlide,
79
82
  presentationTitle,
80
83
  slideMasters,
84
+ activeMasterId,
85
+ globalFontFamily,
86
+ globalFontColor,
87
+ globalBgColor,
88
+ globalThemeColor,
89
+ themeSchemeFillMap,
81
90
  themeClrScheme,
82
91
  slideRatio,
83
92
  slideHeight,
@@ -265,13 +274,26 @@ if (props.config?.title) {
265
274
 
266
275
  // 获取当前完整 Deck 工程数据
267
276
  function getDeck(): DeckData {
277
+ const serializedMasters = JSON.parse(JSON.stringify(toRaw(slideMasters.value) || []))
268
278
  return {
269
279
  title: presentationTitle.value || '未命名演示文稿',
280
+ width: logicalWidth.value,
281
+ height: logicalHeight.value,
282
+ ratio: slideRatio.value,
283
+ theme: {
284
+ fontFamily: globalFontFamily.value,
285
+ fontColor: globalFontColor.value,
286
+ themeColor: toRaw(globalThemeColor.value),
287
+ backgroundColor: globalBgColor.value
288
+ },
289
+ activeMasterId: activeMasterId.value,
270
290
  // toRaw 序列化:避免 stringify 遍历响应式代理时把调用方的 active effect 订阅到整册
271
291
  // (曾在 computed 里调用 getDeck 导致拖拽每步都整册深拷贝,页数越多越卡)
272
292
  slides: JSON.parse(JSON.stringify(toRaw(slides.value) || [])),
273
- slideMasters: JSON.parse(JSON.stringify(toRaw(slideMasters.value) || [])),
274
- themeClrScheme: themeClrScheme.value,
293
+ masters: serializedMasters,
294
+ slideMasters: serializedMasters,
295
+ schemeFillMap: toRaw(themeSchemeFillMap.value),
296
+ themeClrScheme: toRaw(themeClrScheme.value),
275
297
  slideRatio: slideRatio.value,
276
298
  slideHeight: slideHeight.value,
277
299
  logicalWidth: logicalWidth.value,
@@ -295,11 +317,11 @@ function setSlides(newSlides: Slide[]) {
295
317
  }
296
318
 
297
319
  // 加载完整 Deck 工程数据
298
- function loadDeck(deck: DeckData | Slide[]) {
320
+ function loadDeck(deck: DeckData | Slide[], options?: { silent?: boolean }) {
299
321
  if (!deck) return
300
322
  isInternalUpdating = true
301
323
  if (Array.isArray(deck)) {
302
- importSlides(deck)
324
+ importSlides(deck, options)
303
325
  } else {
304
326
  if (deck.title) {
305
327
  presentationTitle.value = deck.title
@@ -308,7 +330,7 @@ function loadDeck(deck: DeckData | Slide[]) {
308
330
  slideMasters.value = deck.slideMasters
309
331
  }
310
332
  if (deck.slides && Array.isArray(deck.slides)) {
311
- importSlides(deck.slides)
333
+ importSlides(deck, options)
312
334
  }
313
335
  }
314
336
  nextTick(() => {
@@ -790,6 +812,48 @@ watch(
790
812
  { immediate: true, deep: true }
791
813
  )
792
814
 
815
+ // 是否开启浏览器本地 IndexedDB 自动缓存
816
+ const isLocalCacheEnabled = computed(() => {
817
+ if (props.localStorageCache !== undefined) return Boolean(props.localStorageCache)
818
+ if (props.config?.localStorageCache !== undefined) return Boolean(props.config.localStorageCache)
819
+ return false
820
+ })
821
+
822
+ const resolvedLocalStorageKey = computed(() => {
823
+ return props.localStorageKey || props.config?.localStorageKey || 'default_workspace_draft'
824
+ })
825
+
826
+ let isRestoringLocalDraft = false
827
+
828
+ async function saveLocalDraft(): Promise<boolean> {
829
+ if (isRestoringLocalDraft) return false
830
+ const currentDeck = getDeck()
831
+ return await saveDraftToIndexedDB(currentDeck, activeIndex.value, resolvedLocalStorageKey.value)
832
+ }
833
+
834
+ async function restoreLocalDraft(): Promise<boolean> {
835
+ try {
836
+ isRestoringLocalDraft = true
837
+ const record = await loadDraftFromIndexedDB(resolvedLocalStorageKey.value)
838
+ if (!record || !record.deck || !Array.isArray(record.deck.slides) || record.deck.slides.length === 0) {
839
+ return false
840
+ }
841
+ loadDeck(record.deck, { silent: true })
842
+ if (typeof record.activeIndex === 'number' && record.activeIndex >= 0 && record.activeIndex < record.deck.slides.length) {
843
+ selectSlide(record.activeIndex)
844
+ }
845
+ return true
846
+ } finally {
847
+ nextTick(() => {
848
+ isRestoringLocalDraft = false
849
+ })
850
+ }
851
+ }
852
+
853
+ async function clearLocalDraft(): Promise<boolean> {
854
+ return await clearDraftFromIndexedDB(resolvedLocalStorageKey.value)
855
+ }
856
+
793
857
  // 对外 deck 同步防抖:打字/连续微编辑不再每次都整册 getDeck 深拷贝+emit,
794
858
  // 300ms 静默后统一发一次;拖拽落沿/翻页/卸载时立即冲刷,宿主侧最终一致
795
859
  let emitDeckTimer: ReturnType<typeof setTimeout> | null = null
@@ -812,6 +876,9 @@ function emitDeckNow() {
812
876
  activeIndex: activeIndex.value,
813
877
  title: presentationTitle.value
814
878
  })
879
+ if (isLocalCacheEnabled.value && !isRestoringLocalDraft) {
880
+ saveDraftToIndexedDB(currentDeck, activeIndex.value, resolvedLocalStorageKey.value)
881
+ }
815
882
  nextTick(() => {
816
883
  isInternalUpdating = false
817
884
  })
@@ -849,7 +916,11 @@ watch([() => isCanvasDragging?.value, () => pauseHistory?.value], ([isDragging,
849
916
  watch(
850
917
  () => activeIndex.value,
851
918
  (idx) => {
919
+ const hadPending = emitDeckPending
852
920
  emitDeckNow()
921
+ if (!hadPending && isLocalCacheEnabled.value && !isRestoringLocalDraft && !isInternalUpdating) {
922
+ saveDraftToIndexedDB(getDeck(), idx, resolvedLocalStorageKey.value)
923
+ }
853
924
  emit('slideChange', {
854
925
  index: idx,
855
926
  slide: activeSlide.value || null
@@ -857,6 +928,17 @@ watch(
857
928
  }
858
929
  )
859
930
 
931
+ // 监听标题修改同步到本地 IndexedDB
932
+ watch(
933
+ () => presentationTitle.value,
934
+ () => {
935
+ if (isInternalUpdating || isRestoringLocalDraft) return
936
+ if (isLocalCacheEnabled.value) {
937
+ scheduleEmitDeck()
938
+ }
939
+ }
940
+ )
941
+
860
942
  // 公式编辑确认
861
943
  function handleFormulaConfirm(latex: string) {
862
944
  if (currentEditingFormulaEl.value) {
@@ -929,6 +1011,9 @@ const editorApi: PptEditorApi = {
929
1011
  addTemplate: (template) => addCustomTemplate(template),
930
1012
  getTemplates: () => [...builtinSlideTemplates],
931
1013
  isTemplateEnabled,
1014
+ saveLocalDraft,
1015
+ restoreLocalDraft,
1016
+ clearLocalDraft,
932
1017
  slidesComposable: slidesState
933
1018
  }
934
1019
 
@@ -1039,6 +1124,7 @@ onMounted(async () => {
1039
1124
  emit('ready', editorApi)
1040
1125
 
1041
1126
  // 若启用 MCP 自动拉取
1127
+ let loadedFromMcp = false
1042
1128
  if (props.enableMcp) {
1043
1129
  const params = new URLSearchParams(window.location.search)
1044
1130
  const deckId = params.get('deckId')
@@ -1054,12 +1140,18 @@ onMounted(async () => {
1054
1140
  }
1055
1141
  const deck = await response.json()
1056
1142
  loadDeck(deck)
1143
+ loadedFromMcp = true
1057
1144
  notify('已从 MCP 打开可编辑稿')
1058
1145
  } catch (error: any) {
1059
1146
  notify(`打开 MCP 稿件失败:${error?.message || error}`)
1060
1147
  }
1061
1148
  }
1062
1149
  }
1150
+
1151
+ // 若启用了浏览器本地 IndexedDB 自动缓存,且未通过外部 modelValue 或 MCP 载入初始数据,则自动从 IndexedDB 恢复上次编辑内容
1152
+ if (isLocalCacheEnabled.value && !loadedFromMcp && !props.modelValue) {
1153
+ await restoreLocalDraft()
1154
+ }
1063
1155
  })
1064
1156
 
1065
1157
  onBeforeUnmount(() => {
@@ -156,6 +156,9 @@ function sortGroupElements(elements: any[]) {
156
156
  @text-blur="emit('textBlur', $event, child)"
157
157
  @text-input="emit('textInput', $event, child)"
158
158
  @text-key-down="emit('textKeyDown', $event, child)"
159
+ @mousemove="emit('textMouseMove', $event, child)"
160
+ @mouseleave="emit('textMouseLeave', $event, child)"
161
+ @dblclick="emit('startEditing', child.id, $event)"
159
162
  @start-editing="(ev) => emit('startEditing', child.id, ev)"
160
163
  />
161
164
  </template>
@@ -30,7 +30,7 @@ function syncContentToDom(force = false) {
30
30
  if (!editableRef.value) return
31
31
  // 编辑中(焦点在元素自身或其内部——表格编辑时焦点在动态设 contenteditable 的 td 上)
32
32
  // 绝不强制用 HTML 冲刷 DOM,防止光标/选中丢失;结构操作经 commitTableContent 强制同步
33
- if (!force && document.activeElement && editableRef.value.contains(document.activeElement)) {
33
+ if (!force && props.isEditingText && document.activeElement && editableRef.value.contains(document.activeElement)) {
34
34
  return
35
35
  }
36
36
  const newHtml = targetHtml.value || ''
@@ -238,27 +238,36 @@ export function useCanvasText(options: TextOptions) {
238
238
  selectedElementIds.value = [elId]
239
239
  }
240
240
  isEditingText.value = true
241
+ const isClearingPlaceholder = Boolean(el && isPlaceholderElement(el))
241
242
  if (el) {
242
243
  const currentVal = el.text || ''
243
244
  if (currentVal && currentVal !== '<div><br></div>') {
244
245
  initialTextContent.value[elId] = currentVal
245
246
  }
246
- if (isPlaceholderElement(el)) {
247
+ if (isClearingPlaceholder) {
247
248
  if (!editingPlaceholderOriginalValue.value[elId]) {
248
249
  editingPlaceholderOriginalValue.value[elId] = currentVal
249
250
  }
250
251
  el.text = '<div><br></div>'
251
252
  }
252
253
  }
254
+ const syncContainer = document.getElementById(`editable-${elId}`)
255
+ if (syncContainer && !isClearingPlaceholder) {
256
+ syncContainer.setAttribute('contenteditable', 'true')
257
+ syncContainer.style.userSelect = 'text'
258
+ ;(syncContainer.style as any).webkitUserSelect = 'text'
259
+ syncContainer.style.pointerEvents = 'auto'
260
+ }
253
261
  nextTick(() => {
254
262
  const container = document.getElementById(`editable-${elId}`)
255
263
  if (container) {
256
- if (el && isPlaceholderElement(el)) {
264
+ if (isClearingPlaceholder) {
257
265
  container.innerHTML = '<div><br></div>'
258
266
  }
259
267
  const existingSel = window.getSelection()
260
- const hasActiveSelection = existingSel && existingSel.rangeCount > 0 && !existingSel.isCollapsed &&
261
- existingSel.anchorNode && container.contains(existingSel.anchorNode)
268
+ const hasActiveSelection = !isClearingPlaceholder && existingSel && existingSel.rangeCount > 0 &&
269
+ existingSel.anchorNode && container.contains(existingSel.anchorNode) &&
270
+ (!existingSel.isCollapsed || mouseEvent?.type === 'mousedown')
262
271
  if (!hasActiveSelection) {
263
272
  setCaretAtPointOrEnd(container, mouseEvent)
264
273
  requestAnimationFrame(() => {
@@ -289,27 +298,37 @@ export function useCanvasText(options: TextOptions) {
289
298
  selectedElementIds.value = [elId]
290
299
  isEditingText.value = true
291
300
  const el = findElementInSlide(elId) || activeSlide.value?.elements.find((x: any) => x.id === elId)
301
+ const isClearingPlaceholder = Boolean(!isMasterEditingView?.value && el && isPlaceholderElement(el))
292
302
  if (el) {
293
303
  const currentVal = el.content || ''
294
304
  if (currentVal && currentVal !== '<div><br></div>') {
295
305
  initialTextContent.value[el.id] = currentVal
296
306
  }
297
- if (!isMasterEditingView?.value && isPlaceholderElement(el)) {
307
+ if (isClearingPlaceholder) {
298
308
  if (!editingPlaceholderOriginalValue.value[el.id]) {
299
309
  editingPlaceholderOriginalValue.value[el.id] = currentVal
300
310
  }
301
311
  el.content = '<div><br></div>'
302
312
  }
303
313
  }
314
+ const isTableOrLatex = Boolean(el && (el.latex || (typeof el.content === 'string' && el.content.includes('<table'))))
315
+ const syncContainer = document.getElementById(`editable-${elId}`)
316
+ if (syncContainer && !isClearingPlaceholder && !isTableOrLatex) {
317
+ syncContainer.setAttribute('contenteditable', 'true')
318
+ syncContainer.style.userSelect = 'text'
319
+ ;(syncContainer.style as any).webkitUserSelect = 'text'
320
+ syncContainer.style.pointerEvents = 'auto'
321
+ }
304
322
  nextTick(() => {
305
323
  const container = document.getElementById(`editable-${elId}`)
306
324
  if (container) {
307
- if (!isMasterEditingView?.value && el && isPlaceholderElement(el)) {
325
+ if (isClearingPlaceholder) {
308
326
  container.innerHTML = '<div><br></div>'
309
327
  }
310
328
  const existingSel = window.getSelection()
311
- const hasActiveSelection = existingSel && existingSel.rangeCount > 0 && !existingSel.isCollapsed &&
312
- existingSel.anchorNode && container.contains(existingSel.anchorNode)
329
+ const hasActiveSelection = !isClearingPlaceholder && existingSel && existingSel.rangeCount > 0 &&
330
+ existingSel.anchorNode && container.contains(existingSel.anchorNode) &&
331
+ (!existingSel.isCollapsed || mouseEvent?.type === 'mousedown')
313
332
  if (!hasActiveSelection) {
314
333
  setCaretAtPointOrEnd(container, mouseEvent)
315
334
  requestAnimationFrame(() => {
@@ -8872,7 +8872,7 @@ function extractAndApplyThemeFromImportedContent(newSlides: any, parsedSlides: a
8872
8872
  console.log('✅ 已成功从导入内容解析颜色并设置主题:', importedRecipe)
8873
8873
  }
8874
8874
 
8875
- function importSlides(newSlides: any) {
8875
+ function importSlides(newSlides: any, options?: { silent?: boolean }) {
8876
8876
  if (slides.value && slides.value.length > 0) {
8877
8877
  revokeSlideBlobUrls(slides.value)
8878
8878
  }
@@ -8880,7 +8880,7 @@ function importSlides(newSlides: any) {
8880
8880
  // 智能识别 Pitch Transit-JSON 模板数据并自动转换为本地 DeckData
8881
8881
  if (isPitchTemplateData(newSlides)) {
8882
8882
  const convertedPitchDeck = convertPitchTemplateToDeck(newSlides)
8883
- return importSlides(convertedPitchDeck)
8883
+ return importSlides(convertedPitchDeck, options)
8884
8884
  }
8885
8885
 
8886
8886
  // 若包含 styleRecipes(如 Pitch 转换器生成的自定义多主题配方),注册到 builtinStyleRecipes
@@ -8909,7 +8909,7 @@ function importSlides(newSlides: any) {
8909
8909
  })()
8910
8910
  if (isRawPPTX) {
8911
8911
  const parsedData = pptParserFn(newSlides)
8912
- return importSlides(parsedData)
8912
+ return importSlides(parsedData, options)
8913
8913
  }
8914
8914
  }
8915
8915
 
@@ -8995,7 +8995,9 @@ function importSlides(newSlides: any) {
8995
8995
 
8996
8996
  initHistory()
8997
8997
  fitTrigger.value++
8998
- notify('导入幻灯片成功')
8998
+ if (!options?.silent) {
8999
+ notify('导入幻灯片成功')
9000
+ }
8999
9001
  }
9000
9002
 
9001
9003
  function startPresentation() {
package/src/index.ts CHANGED
@@ -23,8 +23,15 @@ import './style.css'
23
23
  // 导出核心组件
24
24
  export { PptEditor, PptEditor as JvsPptEditor }
25
25
 
26
- // 导出 composables
26
+ // 导出 composables 与本地 IndexedDB 持久化工具
27
27
  export { useSlides }
28
+ export {
29
+ saveDraftToIndexedDB,
30
+ loadDraftFromIndexedDB,
31
+ clearDraftFromIndexedDB,
32
+ saveMediaBlobToIndexedDB,
33
+ type LocalDraftRecord
34
+ } from './utils/localDraftStorage'
28
35
 
29
36
  // 导出所有类型
30
37
  export * from './types'
package/src/style.css CHANGED
@@ -4800,7 +4800,7 @@ td.selected-cell.focused-cell,
4800
4800
  /* Custom cursor for format painter mode */
4801
4801
  .main-slide.format-painting-mode,
4802
4802
  .main-slide.format-painting-mode * {
4803
- cursor: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 1024 1024" fill="%231E6FFF" stroke="white" stroke-width="40"><path d="M730.624 102.7072q20.736 20.7872 20.736 50.176V228.352h134.2464q33.9456 0 58.0096 24.1664 24.064 24.1152 24.064 58.2144v235.4688q0 66.56-64.9728 80.4864l-465.92 100.096v191.488q0 18.3296-12.9024 31.3344-12.9536 12.9536-31.232 12.9536-18.3296 0-31.232-12.9536-12.9536-13.0048-12.9536-31.3344v-196.5568q0-66.5088 64.9728-80.4864l465.92-100.096V317.0304h-128v79.7184q0 29.3888-20.6848 50.176-20.736 20.736-50.0224 20.736H127.0272q-29.2864 0-49.9712-20.736-20.736-20.7872-20.736-50.176V152.8832q0-29.3888 20.736-50.176 20.6848-20.7872 49.9712-20.7872h553.6256q29.2864 0 50.0224 20.7872zM150.6816 373.0432q5.9392 5.9904 14.336 5.9904h477.7984q8.3968 0 14.336-5.9392 5.9392-5.9392 5.9392-14.336V190.8224q0-8.3968-5.9392-14.336-5.9904-5.9904-14.336-5.9904H164.9664q-8.3968 0-14.336 5.9904-5.9392 5.9392-5.9392 14.336v167.8336q0 8.448 5.9392 14.336z"/></svg>') 4 3, copy !important;
4803
+ cursor: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 1024 1024" fill="%231E6FFF" stroke="white" stroke-width="40"><path d="M730.624 102.7072q20.736 20.7872 20.736 50.176V228.352h134.2464q33.9456 0 58.0096 24.1664 24.064 24.1152 24.064 58.2144v235.4688q0 66.56-64.9728 80.4864l-465.92 100.096v191.488q0 18.3296-12.9024 31.3344-12.9536 12.9536-31.232 12.9536-18.3296 0-31.232-12.9536-12.9536-13.0048-12.9536-31.3344v-196.5568q0-66.5088 64.9728-80.4864l465.92-100.096V317.0304h-128v79.7184q0 29.3888-20.6848 50.176-20.736 20.736-50.0224 20.736H127.0272q-29.2864 0-49.9712-20.736-20.736-20.7872-20.736-50.176V152.8832q0-29.3888 20.736-50.176 20.6848-20.7872 49.9712-20.7872h553.6256q29.2864 0 50.0224 20.7872zM150.6816 373.0432q5.9392 5.9904 14.336 5.9904h477.7984q8.3968 0 14.336-5.9392 5.9392-5.9392 5.9392-14.336V190.8224q0-8.3968-5.9392-14.336-5.9904-5.9904-14.336-5.9904H164.9664q-8.3968 0-14.336 5.9904-5.9392 5.9392-5.9392 14.336v167.8336q0 8.448 5.9392 14.336z"/></svg>') 12 9, copy !important;
4804
4804
  }
4805
4805
 
4806
4806
  /* ==========================================================================
@@ -139,6 +139,10 @@ export interface PptEditorConfig {
139
139
  templateBaseUrl?: string
140
140
  /** 传入自定义 templates 时是否替换默认内置模板,默认为 true(设为 false 则与默认内置模板合并) */
141
141
  replaceBuiltinTemplates?: boolean
142
+ /** 是否开启浏览器本地 IndexedDB 自动缓存与刷新恢复(独立运行模式可开启,作为受控插件时默认 false) */
143
+ localStorageCache?: boolean
144
+ /** 浏览器本地 IndexedDB 缓存的自定义键名,默认为 'default_workspace_draft' */
145
+ localStorageKey?: string
142
146
  /** 其它扩展配置 */
143
147
  [key: string]: any
144
148
  }
@@ -199,6 +203,10 @@ export interface PptEditorProps {
199
203
  templateBaseUrl?: string
200
204
  /** 传入自定义 templates 时是否替换默认内置模板,默认为 true(设为 false 则与默认内置模板合并) */
201
205
  replaceBuiltinTemplates?: boolean
206
+ /** 是否开启浏览器本地 IndexedDB 自动缓存与刷新恢复(独立运行模式可开启,作为受控插件时默认 false) */
207
+ localStorageCache?: boolean
208
+ /** 浏览器本地 IndexedDB 缓存的自定义键名,默认为 'default_workspace_draft' */
209
+ localStorageKey?: string
202
210
  /** 编辑器扩展配置 */
203
211
  config?: PptEditorConfig
204
212
  }
@@ -315,6 +323,12 @@ export interface PptEditorApi {
315
323
  getTemplates: () => SlideTemplateItem[]
316
324
  /** 当前模板库功能是否启用 */
317
325
  isTemplateEnabled: Ref<boolean>
326
+ /** 立即将当前工程草稿保存到浏览器 IndexedDB */
327
+ saveLocalDraft?: () => Promise<boolean>
328
+ /** 从浏览器 IndexedDB 恢复上次保存的工程草稿 */
329
+ restoreLocalDraft?: () => Promise<boolean>
330
+ /** 清空浏览器 IndexedDB 中保存的工程草稿 */
331
+ clearLocalDraft?: () => Promise<boolean>
318
332
  /** 底层 useSlides composable 完整实例(供深度扩展) */
319
333
  slidesComposable: any
320
334
  }
@@ -24,7 +24,8 @@ export interface ElementFormat {
24
24
  fontStyle?: string
25
25
  textDecoration?: string
26
26
  textAlign?: string
27
- lineHeight?: string
27
+ verticalAlign?: string
28
+ lineHeight?: string | number
28
29
  letterSpacing?: string
29
30
  textBackground?: string
30
31
 
@@ -86,14 +87,19 @@ export function getFormatFromElement(el: any): ElementFormat | null {
86
87
  }
87
88
  } else {
88
89
  // 2. Extract typography from Rich Text HTML (for shape: el.text; for text: el.content)
89
- // Rich text styles have highest priority because they reflect the user's explicit formatting
90
- const rawHtml = (el.type === 'shape' ? el.text : el.content) || ''
90
+ // Prefer live DOM innerHTML if the element is currently mounted in the editor
91
+ const liveContainer = (typeof document !== 'undefined' && el.id)
92
+ ? document.getElementById(`editable-${el.id}`)
93
+ : null
94
+ const rawHtml = (liveContainer && liveContainer.innerHTML)
95
+ ? liveContainer.innerHTML
96
+ : ((el.type === 'shape' ? (typeof el.text === 'string' ? el.text : el.text?.content) : el.content) || '')
91
97
  if (rawHtml && typeof rawHtml === 'string' && rawHtml.includes('<')) {
92
98
  const div = document.createElement('div')
93
99
  div.innerHTML = rawHtml
94
100
 
95
101
  const styledNodes = Array.from(
96
- div.querySelectorAll('[style], font, b, strong, i, em, u, s, del, p, span')
102
+ div.querySelectorAll('[style], font, b, strong, i, em, u, s, del, p, div, li, span')
97
103
  ) as HTMLElement[]
98
104
 
99
105
  for (const node of styledNodes) {
@@ -106,17 +112,24 @@ export function getFormatFromElement(el: any): ElementFormat | null {
106
112
  if (!format.fontFamily && s.fontFamily) format.fontFamily = s.fontFamily
107
113
  if (!format.fontWeight && (s.fontWeight === 'bold' || Number(s.fontWeight) >= 600 || node.tagName === 'B' || node.tagName === 'STRONG')) {
108
114
  format.fontWeight = 'bold'
115
+ } else if (!format.fontWeight && (s.fontWeight === 'normal' || s.fontWeight === '400')) {
116
+ format.fontWeight = 'normal'
109
117
  }
110
118
  if (!format.fontStyle && (s.fontStyle === 'italic' || node.tagName === 'I' || node.tagName === 'EM')) {
111
119
  format.fontStyle = 'italic'
120
+ } else if (!format.fontStyle && s.fontStyle === 'normal') {
121
+ format.fontStyle = 'normal'
112
122
  }
113
- if (!format.textDecoration && (s.textDecoration || node.tagName === 'U' || node.tagName === 'S' || node.tagName === 'DEL')) {
114
- format.textDecoration = s.textDecoration || (node.tagName === 'U' ? 'underline' : 'line-through')
123
+ if (!format.textDecoration && (s.textDecoration || s.textDecorationLine || node.tagName === 'U' || node.tagName === 'S' || node.tagName === 'DEL')) {
124
+ const rawDec = s.textDecorationLine || s.textDecoration || (node.tagName === 'U' ? 'underline' : 'line-through')
125
+ if (rawDec && rawDec !== 'none') {
126
+ format.textDecoration = rawDec
127
+ }
115
128
  }
116
129
  if (!format.textAlign && s.textAlign) {
117
130
  format.textAlign = s.textAlign
118
131
  }
119
- if (!format.textBackground && s.backgroundColor && s.backgroundColor !== 'transparent') {
132
+ if (!format.textBackground && s.backgroundColor && !isTransparentTextBg(s.backgroundColor)) {
120
133
  format.textBackground = s.backgroundColor
121
134
  }
122
135
  }
@@ -127,13 +140,14 @@ export function getFormatFromElement(el: any): ElementFormat | null {
127
140
  if (!format.color) format.color = style.color || style.textColor || el.color || el.textColor || undefined
128
141
  if (!format.fontSize) format.fontSize = style.fontSize || el.fontSize || undefined
129
142
  if (!format.fontFamily) format.fontFamily = style.fontFamily || el.fontFamily || undefined
130
- if (!format.fontWeight) format.fontWeight = style.fontWeight || undefined
131
- if (!format.fontStyle) format.fontStyle = style.fontStyle || undefined
132
- if (!format.textDecoration) format.textDecoration = style.textDecoration || undefined
133
- if (!format.textAlign) format.textAlign = style.textAlign || undefined
134
- if (!format.lineHeight) format.lineHeight = style.lineHeight || undefined
135
- if (!format.letterSpacing) format.letterSpacing = style.letterSpacing || undefined
136
- if (!format.textBackground) format.textBackground = style.textBackground || undefined
143
+ if (!format.fontWeight) format.fontWeight = style.fontWeight || (el.type === 'text' || el.type === 'shape' ? 'normal' : undefined)
144
+ if (!format.fontStyle) format.fontStyle = style.fontStyle || (el.type === 'text' || el.type === 'shape' ? 'normal' : undefined)
145
+ if (!format.textDecoration) format.textDecoration = style.textDecoration || (el.type === 'text' || el.type === 'shape' ? 'none' : undefined)
146
+ if (!format.textAlign) format.textAlign = style.textAlign || (el.type === 'shape' ? 'center' : (el.type === 'text' ? 'left' : undefined))
147
+ if (!format.verticalAlign) format.verticalAlign = style.verticalAlign || el.verticalAlign || (el.type === 'text' || el.type === 'shape' ? 'middle' : undefined)
148
+ if (!format.lineHeight) format.lineHeight = style.lineHeight !== undefined ? style.lineHeight : undefined
149
+ if (!format.letterSpacing) format.letterSpacing = style.letterSpacing !== undefined ? style.letterSpacing : undefined
150
+ if (!format.textBackground) format.textBackground = style.textBackground || (el.type === 'text' || el.type === 'shape' ? 'transparent' : undefined)
137
151
 
138
152
  // Filter out undefined and empty string keys
139
153
  const cleaned: ElementFormat = {}
@@ -380,28 +394,25 @@ export function applyTextStyleToHtml(html: string, styles: ElementFormat): strin
380
394
  if (styles.fontWeight) elem.style.fontWeight = styles.fontWeight
381
395
  if (styles.fontStyle) elem.style.fontStyle = styles.fontStyle
382
396
  if (styles.textDecoration) elem.style.textDecoration = styles.textDecoration
383
- if (styles.lineHeight) elem.style.lineHeight = styles.lineHeight
397
+ if (styles.lineHeight !== undefined) elem.style.lineHeight = String(styles.lineHeight)
384
398
  if (styles.letterSpacing) elem.style.letterSpacing = styles.letterSpacing
385
399
  }
386
400
 
387
- const spans = div.querySelectorAll('span')
388
- if (spans.length > 0) {
389
- spans.forEach(applyStylesToElem)
401
+ const inlineStyled = div.querySelectorAll('span, b, strong, i, em, u, s, del, a')
402
+ if (inlineStyled.length > 0) {
403
+ inlineStyled.forEach((node: any) => applyStylesToElem(node as HTMLElement))
390
404
  }
391
405
 
392
- const blocks = div.querySelectorAll('p, div, li')
406
+ const blocks = div.querySelectorAll('p, div, li, h1, h2, h3, h4, h5, h6')
393
407
  blocks.forEach((b: any) => {
394
408
  if (styles.textAlign) b.style.textAlign = styles.textAlign
395
- if (spans.length === 0) {
396
- applyStylesToElem(b)
397
- } else if (styles.color) {
398
- b.style.color = styles.color
399
- }
409
+ applyStylesToElem(b as HTMLElement)
400
410
  })
401
411
 
402
412
  div.querySelectorAll('font').forEach((font: any) => {
403
413
  if (styles.color) font.setAttribute('color', styles.color)
404
414
  if (styles.fontSize) font.style.fontSize = styles.fontSize
415
+ applyStylesToElem(font as HTMLElement)
405
416
  })
406
417
 
407
418
  return div.innerHTML
@@ -491,21 +502,38 @@ export function applyFormatToElement(targetEl: any, format: ElementFormat): void
491
502
  if (format.opacity !== undefined) targetEl.style.opacity = format.opacity
492
503
 
493
504
  // Apply typography styles to style object
494
- if (format.color) targetEl.style.color = format.color
505
+ if (format.color) {
506
+ targetEl.style.color = format.color
507
+ targetEl.style.textColor = format.color
508
+ if (targetEl.color !== undefined) targetEl.color = format.color
509
+ if (targetEl.textColor !== undefined) targetEl.textColor = format.color
510
+ }
495
511
  if (format.fontSize) targetEl.style.fontSize = format.fontSize
496
- if (format.fontFamily) targetEl.style.fontFamily = format.fontFamily
512
+ if (format.fontFamily) {
513
+ targetEl.style.fontFamily = format.fontFamily
514
+ if (targetEl.fontFamily !== undefined) targetEl.fontFamily = format.fontFamily
515
+ }
497
516
  if (format.fontWeight) targetEl.style.fontWeight = format.fontWeight
498
517
  if (format.fontStyle) targetEl.style.fontStyle = format.fontStyle
499
518
  if (format.textDecoration) targetEl.style.textDecoration = format.textDecoration
500
519
  if (format.textAlign) targetEl.style.textAlign = format.textAlign
501
- if (format.lineHeight) targetEl.style.lineHeight = format.lineHeight
520
+ if (format.verticalAlign) {
521
+ targetEl.style.verticalAlign = format.verticalAlign
522
+ if (targetEl.verticalAlign !== undefined) targetEl.verticalAlign = format.verticalAlign
523
+ }
524
+ if (format.lineHeight !== undefined) targetEl.style.lineHeight = format.lineHeight
502
525
  if (format.letterSpacing) targetEl.style.letterSpacing = format.letterSpacing
526
+ if (format.textBackground !== undefined) targetEl.style.textBackground = format.textBackground
503
527
 
504
528
  // Apply typography to inner rich text:
505
529
  // For shape: update targetEl.text (NEVER touch targetEl.content which is the SVG path!)
506
530
  if (targetEl.type === 'shape') {
507
531
  if (targetEl.text) {
508
- targetEl.text = applyTextStyleToHtml(targetEl.text, format)
532
+ if (typeof targetEl.text === 'object' && targetEl.text.content !== undefined) {
533
+ targetEl.text.content = applyTextStyleToHtml(targetEl.text.content, format)
534
+ } else if (typeof targetEl.text === 'string') {
535
+ targetEl.text = applyTextStyleToHtml(targetEl.text, format)
536
+ }
509
537
  }
510
538
  } else if (targetEl.type === 'text') {
511
539
  if (targetEl.content) {
@@ -546,7 +574,7 @@ export function getFormatFromSelection(fallbackRange?: Range | null): ElementFor
546
574
 
547
575
  if (comp.color) format.color = rgbToHex(comp.color)
548
576
  if (comp.fontSize) format.fontSize = comp.fontSize
549
- if (comp.fontFamily) format.fontFamily = comp.fontFamily
577
+ if (comp.fontFamily) format.fontFamily = comp.fontFamily.replace(/^["']|["']$/g, '')
550
578
  if (comp.fontWeight === 'bold' || Number(comp.fontWeight) >= 600) {
551
579
  format.fontWeight = 'bold'
552
580
  } else {
@@ -561,9 +589,23 @@ export function getFormatFromSelection(fallbackRange?: Range | null): ElementFor
561
589
  format.textDecoration = comp.textDecorationLine
562
590
  } else if (comp.textDecoration && !comp.textDecoration.startsWith('none')) {
563
591
  format.textDecoration = comp.textDecoration.split(' ')[0]
592
+ } else {
593
+ format.textDecoration = 'none'
594
+ }
595
+ if (comp.textAlign && comp.textAlign !== 'start') {
596
+ format.textAlign = comp.textAlign
597
+ } else {
598
+ const blockEl = node.closest('p, div, li, td, th') as HTMLElement | null
599
+ if (blockEl && blockEl.style?.textAlign) {
600
+ format.textAlign = blockEl.style.textAlign
601
+ } else {
602
+ format.textAlign = 'left'
603
+ }
564
604
  }
565
- if (comp.backgroundColor && comp.backgroundColor !== 'transparent' && comp.backgroundColor !== 'rgba(0, 0, 0, 0)') {
605
+ if (comp.backgroundColor && !isTransparentTextBg(comp.backgroundColor)) {
566
606
  format.textBackground = rgbToHex(comp.backgroundColor)
607
+ } else {
608
+ format.textBackground = 'transparent'
567
609
  }
568
610
 
569
611
  return format
@@ -629,6 +671,12 @@ export function applyFormatToTextRange(
629
671
  }
630
672
 
631
673
  const parent = targetNode.parentNode as HTMLElement | null
674
+ if (format.textAlign && parent) {
675
+ const blockEl = parent.closest('p, div, li, td, th') as HTMLElement | null
676
+ if (blockEl && container.contains(blockEl) && blockEl !== container) {
677
+ blockEl.style.textAlign = format.textAlign
678
+ }
679
+ }
632
680
  if (
633
681
  parent &&
634
682
  parent.tagName === 'SPAN' &&
@@ -641,7 +689,9 @@ export function applyFormatToTextRange(
641
689
  if (format.fontWeight) parent.style.fontWeight = format.fontWeight
642
690
  if (format.fontStyle) parent.style.fontStyle = format.fontStyle
643
691
  if (format.textDecoration) parent.style.textDecoration = format.textDecoration
644
- if (format.textBackground) parent.style.backgroundColor = format.textBackground
692
+ if (format.textBackground !== undefined) {
693
+ parent.style.backgroundColor = isTransparentTextBg(format.textBackground) ? '' : format.textBackground
694
+ }
645
695
  } else if (parent) {
646
696
  const span = document.createElement('span')
647
697
  if (format.color) span.style.color = format.color
@@ -650,7 +700,9 @@ export function applyFormatToTextRange(
650
700
  if (format.fontWeight) span.style.fontWeight = format.fontWeight
651
701
  if (format.fontStyle) span.style.fontStyle = format.fontStyle
652
702
  if (format.textDecoration) span.style.textDecoration = format.textDecoration
653
- if (format.textBackground) span.style.backgroundColor = format.textBackground
703
+ if (format.textBackground !== undefined && !isTransparentTextBg(format.textBackground)) {
704
+ span.style.backgroundColor = format.textBackground
705
+ }
654
706
 
655
707
  parent.insertBefore(span, targetNode)
656
708
  span.appendChild(targetNode)
@@ -659,6 +711,13 @@ export function applyFormatToTextRange(
659
711
 
660
712
  // Sync to target element data
661
713
  if (targetEl) {
714
+ if (format.textAlign) {
715
+ const selectedLen = (range.toString() || '').trim().length
716
+ const totalLen = (container.textContent || '').trim().length
717
+ if (selectedLen > 0 && selectedLen >= totalLen && targetEl.style) {
718
+ targetEl.style.textAlign = format.textAlign
719
+ }
720
+ }
662
721
  if (targetEl.type === 'shape') {
663
722
  targetEl.text = container.innerHTML
664
723
  } else {