jvs-ppt-ui 0.0.37 → 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.
@@ -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 {
@@ -0,0 +1,340 @@
1
+ import type { DeckData } from '../types'
2
+
3
+ export interface LocalDraftRecord {
4
+ key: string
5
+ deck: DeckData
6
+ activeIndex: number
7
+ updatedAt: number
8
+ }
9
+
10
+ const DB_NAME = 'jvs_ppt_local_storage'
11
+ const DB_VERSION = 1
12
+ const DRAFT_STORE = 'drafts'
13
+ const MEDIA_STORE = 'media_blobs'
14
+ const DEFAULT_DRAFT_KEY = 'default_workspace_draft'
15
+
16
+ let dbPromise: Promise<IDBDatabase> | null = null
17
+
18
+ // 内存级 BlobURL <-> mediaId 双向映射缓存,避免重复读写 IndexedDB
19
+ const blobUrlToMediaId = new Map<string, string>()
20
+ const mediaIdToBlobUrl = new Map<string, string>()
21
+
22
+ function openLocalDb(): Promise<IDBDatabase> {
23
+ if (typeof indexedDB === 'undefined') {
24
+ return Promise.reject(new Error('当前环境不支持 IndexedDB'))
25
+ }
26
+ if (dbPromise) return dbPromise
27
+
28
+ dbPromise = new Promise((resolve, reject) => {
29
+ const request = indexedDB.open(DB_NAME, DB_VERSION)
30
+
31
+ request.onupgradeneeded = () => {
32
+ const db = request.result
33
+ if (!db.objectStoreNames.contains(DRAFT_STORE)) {
34
+ db.createObjectStore(DRAFT_STORE, { keyPath: 'key' })
35
+ }
36
+ if (!db.objectStoreNames.contains(MEDIA_STORE)) {
37
+ db.createObjectStore(MEDIA_STORE, { keyPath: 'id' })
38
+ }
39
+ }
40
+
41
+ request.onsuccess = () => {
42
+ const db = request.result
43
+ db.onversionchange = () => {
44
+ db.close()
45
+ dbPromise = null
46
+ }
47
+ resolve(db)
48
+ }
49
+
50
+ request.onerror = () => {
51
+ dbPromise = null
52
+ reject(request.error || new Error('打开 IndexedDB 失败'))
53
+ }
54
+ })
55
+
56
+ return dbPromise
57
+ }
58
+
59
+ /**
60
+ * 将本地 File / Blob 存入 IndexedDB 的 media_blobs 表,并返回可渲染的 blob: URL(同时建立持久化 ID 映射)
61
+ */
62
+ export async function saveMediaBlobToIndexedDB(fileOrBlob: File | Blob, customId?: string): Promise<string> {
63
+ const blobUrl = URL.createObjectURL(fileOrBlob)
64
+ try {
65
+ const db = await openLocalDb()
66
+ const id = customId || `media_${Date.now()}_${Math.random().toString(36).slice(2, 10)}`
67
+ await new Promise<void>((resolve, reject) => {
68
+ const tx = db.transaction(MEDIA_STORE, 'readwrite')
69
+ const store = tx.objectStore(MEDIA_STORE)
70
+ store.put({
71
+ id,
72
+ blob: fileOrBlob,
73
+ type: fileOrBlob.type || 'application/octet-stream',
74
+ size: fileOrBlob.size,
75
+ updatedAt: Date.now()
76
+ })
77
+ tx.oncomplete = () => resolve()
78
+ tx.onerror = () => reject(tx.error)
79
+ })
80
+ blobUrlToMediaId.set(blobUrl, id)
81
+ mediaIdToBlobUrl.set(id, blobUrl)
82
+ } catch (err) {
83
+ console.warn('[LocalDraftStorage] 保存媒体二进制到 IndexedDB 失败:', err)
84
+ }
85
+ return blobUrl
86
+ }
87
+
88
+ /**
89
+ * 根据持久化媒体 ID 从 IndexedDB 还原出当前会话可用的 blob: URL
90
+ */
91
+ async function resolveMediaIdToBlobUrl(mediaId: string): Promise<string | null> {
92
+ if (!mediaId) return null
93
+ if (mediaIdToBlobUrl.has(mediaId)) {
94
+ return mediaIdToBlobUrl.get(mediaId)!
95
+ }
96
+ try {
97
+ const db = await openLocalDb()
98
+ const record = await new Promise<any>((resolve, reject) => {
99
+ const tx = db.transaction(MEDIA_STORE, 'readonly')
100
+ const store = tx.objectStore(MEDIA_STORE)
101
+ const req = store.get(mediaId)
102
+ req.onsuccess = () => resolve(req.result)
103
+ req.onerror = () => reject(req.error)
104
+ })
105
+ if (record && record.blob instanceof Blob) {
106
+ const blobUrl = URL.createObjectURL(record.blob)
107
+ blobUrlToMediaId.set(blobUrl, mediaId)
108
+ mediaIdToBlobUrl.set(mediaId, blobUrl)
109
+ return blobUrl
110
+ }
111
+ } catch (err) {
112
+ console.warn('[LocalDraftStorage] 从 IndexedDB 恢复媒体失败:', mediaId, err)
113
+ }
114
+ return null
115
+ }
116
+
117
+ /**
118
+ * 若画布中存在未经 customUpload 的裸 blob: URL,自动 fetch 其 Blob 并持久化到 IndexedDB
119
+ */
120
+ async function ensureBlobUrlPersisted(blobUrl: string): Promise<string> {
121
+ if (blobUrlToMediaId.has(blobUrl)) {
122
+ return `idb-media://${blobUrlToMediaId.get(blobUrl)!}`
123
+ }
124
+ try {
125
+ const res = await fetch(blobUrl)
126
+ if (res.ok) {
127
+ const blob = await res.blob()
128
+ const id = `media_${Date.now()}_${Math.random().toString(36).slice(2, 10)}`
129
+ const db = await openLocalDb()
130
+ await new Promise<void>((resolve, reject) => {
131
+ const tx = db.transaction(MEDIA_STORE, 'readwrite')
132
+ tx.objectStore(MEDIA_STORE).put({
133
+ id,
134
+ blob,
135
+ type: blob.type || 'application/octet-stream',
136
+ size: blob.size,
137
+ updatedAt: Date.now()
138
+ })
139
+ tx.oncomplete = () => resolve()
140
+ tx.onerror = () => reject(tx.error)
141
+ })
142
+ blobUrlToMediaId.set(blobUrl, id)
143
+ mediaIdToBlobUrl.set(id, blobUrl)
144
+ return `idb-media://${id}`
145
+ }
146
+ } catch {
147
+ // 已失效的 blob: URL 保持原样
148
+ }
149
+ return blobUrl
150
+ }
151
+
152
+ /**
153
+ * 递归遍历对象中的所有字符串字段,在保存前将临时 blob: URL 替换为 idb-media://<id>,
154
+ * 或在读取后将 idb-media://<id> 还原为当前会话有效的 blob: URL
155
+ */
156
+ async function transformMediaUrlsInObject(node: any, mode: 'serialize' | 'deserialize'): Promise<any> {
157
+ if (!node) return node
158
+
159
+ if (typeof node === 'string') {
160
+ if (mode === 'serialize') {
161
+ if (node.startsWith('blob:')) {
162
+ return await ensureBlobUrlPersisted(node)
163
+ }
164
+ if (node.includes('blob:')) {
165
+ const matches = node.match(/blob:https?:\/\/[^\s"')]+|blob:null\/[^\s"')]+/g)
166
+ if (matches) {
167
+ let result = node
168
+ for (const m of matches) {
169
+ const replacement = await ensureBlobUrlPersisted(m)
170
+ result = result.split(m).join(replacement)
171
+ }
172
+ return result
173
+ }
174
+ }
175
+ return node
176
+ } else {
177
+ if (node.startsWith('idb-media://')) {
178
+ const mediaId = node.slice('idb-media://'.length)
179
+ const restored = await resolveMediaIdToBlobUrl(mediaId)
180
+ return restored || node
181
+ }
182
+ if (node.includes('idb-media://')) {
183
+ const matches = node.match(/idb-media:\/\/[a-zA-Z0-9_-]+/g)
184
+ if (matches) {
185
+ let result = node
186
+ for (const m of matches) {
187
+ const mediaId = m.slice('idb-media://'.length)
188
+ const restored = await resolveMediaIdToBlobUrl(mediaId)
189
+ if (restored) {
190
+ result = result.split(m).join(restored)
191
+ }
192
+ }
193
+ return result
194
+ }
195
+ }
196
+ return node
197
+ }
198
+ }
199
+
200
+ if (Array.isArray(node)) {
201
+ for (let i = 0; i < node.length; i++) {
202
+ node[i] = await transformMediaUrlsInObject(node[i], mode)
203
+ }
204
+ return node
205
+ }
206
+
207
+ if (typeof node === 'object') {
208
+ const keys = Object.keys(node)
209
+ for (const k of keys) {
210
+ const val = node[k]
211
+ if (typeof val === 'string' || Array.isArray(val) || (val && typeof val === 'object')) {
212
+ node[k] = await transformMediaUrlsInObject(val, mode)
213
+ }
214
+ }
215
+ return node
216
+ }
217
+
218
+ return node
219
+ }
220
+
221
+ /**
222
+ * 清理不再被当前草稿引用的孤立媒体 Blob,防止 IndexedDB 无限膨胀
223
+ */
224
+ async function pruneUnusedMediaBlobs(serializedDeck: DeckData): Promise<void> {
225
+ try {
226
+ const jsonStr = JSON.stringify(serializedDeck)
227
+ const usedIds = new Set<string>()
228
+ const matches = jsonStr.match(/idb-media:\/\/([a-zA-Z0-9_-]+)/g)
229
+ if (matches) {
230
+ for (const m of matches) {
231
+ usedIds.add(m.slice('idb-media://'.length))
232
+ }
233
+ }
234
+
235
+ const db = await openLocalDb()
236
+ await new Promise<void>((resolve) => {
237
+ const tx = db.transaction(MEDIA_STORE, 'readwrite')
238
+ const store = tx.objectStore(MEDIA_STORE)
239
+ const req = store.getAllKeys()
240
+ req.onsuccess = () => {
241
+ const allKeys = req.result || []
242
+ for (const k of allKeys) {
243
+ const id = String(k)
244
+ if (!usedIds.has(id)) {
245
+ store.delete(id)
246
+ }
247
+ }
248
+ }
249
+ tx.oncomplete = () => resolve()
250
+ tx.onerror = () => resolve()
251
+ })
252
+ } catch {
253
+ // 忽略清理异常
254
+ }
255
+ }
256
+
257
+ /**
258
+ * 保存 PPT 工程草稿到 IndexedDB
259
+ */
260
+ export async function saveDraftToIndexedDB(
261
+ deck: DeckData,
262
+ activeIndex = 0,
263
+ key = DEFAULT_DRAFT_KEY
264
+ ): Promise<boolean> {
265
+ if (!deck || !Array.isArray(deck.slides)) return false
266
+ try {
267
+ const clonedDeck: DeckData = JSON.parse(JSON.stringify(deck))
268
+ await transformMediaUrlsInObject(clonedDeck, 'serialize')
269
+
270
+ const db = await openLocalDb()
271
+ const record: LocalDraftRecord = {
272
+ key,
273
+ deck: clonedDeck,
274
+ activeIndex: typeof activeIndex === 'number' && activeIndex >= 0 ? activeIndex : 0,
275
+ updatedAt: Date.now()
276
+ }
277
+
278
+ await new Promise<void>((resolve, reject) => {
279
+ const tx = db.transaction(DRAFT_STORE, 'readwrite')
280
+ tx.objectStore(DRAFT_STORE).put(record)
281
+ tx.oncomplete = () => resolve()
282
+ tx.onerror = () => reject(tx.error)
283
+ })
284
+
285
+ await pruneUnusedMediaBlobs(clonedDeck)
286
+ return true
287
+ } catch (err) {
288
+ console.warn('[LocalDraftStorage] 保存草稿到 IndexedDB 失败:', err)
289
+ return false
290
+ }
291
+ }
292
+
293
+ /**
294
+ * 从 IndexedDB 读取上次保存的 PPT 工程草稿
295
+ */
296
+ export async function loadDraftFromIndexedDB(
297
+ key = DEFAULT_DRAFT_KEY
298
+ ): Promise<LocalDraftRecord | null> {
299
+ try {
300
+ const db = await openLocalDb()
301
+ const record = await new Promise<LocalDraftRecord | undefined>((resolve, reject) => {
302
+ const tx = db.transaction(DRAFT_STORE, 'readonly')
303
+ const req = tx.objectStore(DRAFT_STORE).get(key)
304
+ req.onsuccess = () => resolve(req.result)
305
+ req.onerror = () => reject(req.error)
306
+ })
307
+
308
+ if (!record || !record.deck || !Array.isArray(record.deck.slides) || record.deck.slides.length === 0) {
309
+ return null
310
+ }
311
+
312
+ await transformMediaUrlsInObject(record.deck, 'deserialize')
313
+ return record
314
+ } catch (err) {
315
+ console.warn('[LocalDraftStorage] 从 IndexedDB 读取草稿失败:', err)
316
+ return null
317
+ }
318
+ }
319
+
320
+ /**
321
+ * 清空 IndexedDB 中的草稿及关联媒体缓存
322
+ */
323
+ export async function clearDraftFromIndexedDB(key = DEFAULT_DRAFT_KEY): Promise<boolean> {
324
+ try {
325
+ const db = await openLocalDb()
326
+ await new Promise<void>((resolve, reject) => {
327
+ const tx = db.transaction([DRAFT_STORE, MEDIA_STORE], 'readwrite')
328
+ tx.objectStore(DRAFT_STORE).delete(key)
329
+ if (key === DEFAULT_DRAFT_KEY) {
330
+ tx.objectStore(MEDIA_STORE).clear()
331
+ }
332
+ tx.oncomplete = () => resolve()
333
+ tx.onerror = () => reject(tx.error)
334
+ })
335
+ return true
336
+ } catch (err) {
337
+ console.warn('[LocalDraftStorage] 清理 IndexedDB 草稿失败:', err)
338
+ return false
339
+ }
340
+ }