Skip to content

Commit 76f64b6

Browse files
committed
modified: src/services/webStorage.ts
1 parent fc96f43 commit 76f64b6

File tree

1 file changed

+33
-2
lines changed

1 file changed

+33
-2
lines changed

src/services/webStorage.ts

Lines changed: 33 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -26,10 +26,12 @@ export class WebStorageService {
2626
const existingNote = notes.find(n => n.id === note.id);
2727

2828
const updatedNote = {
29+
...existingNote,
2930
...note,
3031
updated_at: now,
31-
created_at: note.created_at || now,
32+
created_at: note.created_at || existingNote?.created_at || now,
3233
attachments: existingNote?.attachments || note.attachments || [],
34+
pending_sync: note.pending_sync || existingNote?.pending_sync || false
3335
} as Note;
3436

3537
if (!updatedNote.id) {
@@ -280,6 +282,12 @@ export class WebStorageService {
280282
throw new Error(`File size exceeds limit of ${MAX_FILE_SIZE / (1024 * 1024)}MB`);
281283
}
282284

285+
const estimatedSize = file.size * 1.37;
286+
const availableSpace = this.getAvailableStorageSpace();
287+
if (estimatedSize > availableSpace) {
288+
throw new Error(`Not enough storage space. Need ${Math.ceil(estimatedSize / (1024 * 1024))}MB but only ${Math.ceil(availableSpace / (1024 * 1024))}MB available.`);
289+
}
290+
283291
const notesJson = localStorage.getItem(this.NOTES_KEY);
284292
const notes: Note[] = notesJson ? JSON.parse(notesJson) : [];
285293
const note = notes.find(n => n.id === noteId);
@@ -311,7 +319,14 @@ export class WebStorageService {
311319
notes[index] = note;
312320
}
313321

314-
localStorage.setItem(this.NOTES_KEY, JSON.stringify(notes));
322+
try {
323+
localStorage.setItem(this.NOTES_KEY, JSON.stringify(notes));
324+
} catch (error: unknown) {
325+
if (error instanceof Error && error.name === 'QuotaExceededError') {
326+
throw new Error(`Storage quota exceeded. Try removing some attachments first.`);
327+
}
328+
throw error;
329+
}
315330
return note;
316331
}
317332

@@ -375,4 +390,20 @@ export class WebStorageService {
375390
throw new Error('Failed to decrypt attachment');
376391
}
377392
}
393+
394+
private static getAvailableStorageSpace(): number {
395+
let total = 0;
396+
try {
397+
for (let key in localStorage) {
398+
if (localStorage.hasOwnProperty(key)) {
399+
total += localStorage[key].length * 2;
400+
}
401+
}
402+
const maxSpace = 5 * 1024 * 1024;
403+
return maxSpace - total;
404+
} catch (e) {
405+
console.error('Failed to calculate storage space:', e);
406+
return 0;
407+
}
408+
}
378409
}

0 commit comments

Comments
 (0)