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.
@@ -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
+ }