-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfile-db.js
More file actions
173 lines (152 loc) · 5.33 KB
/
Copy pathfile-db.js
File metadata and controls
173 lines (152 loc) · 5.33 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
class FileDB {
constructor() {
this.dbPath = './data/tasks.json';
this.fs = null;
this.isNode = false;
this.data = {
tasks: [],
completed: [],
archived: [],
categories: ['Work', 'Personal']
};
}
async init() {
// Check if we're in a Node.js environment or browser
if (typeof window === 'undefined') {
// Node.js environment
this.isNode = true;
this.fs = require('fs').promises;
await this.ensureDataDirectory();
} else {
// Browser environment - we'll use File System Access API
console.log('Browser environment detected - using File System Access API');
}
await this.load();
}
async ensureDataDirectory() {
if (this.isNode) {
const path = require('path');
const dir = path.dirname(this.dbPath);
try {
await this.fs.mkdir(dir, { recursive: true });
} catch (e) {
// Directory already exists
}
}
}
async save() {
const jsonData = JSON.stringify(this.data, null, 2);
if (this.isNode) {
// Node.js - direct file write
await this.fs.writeFile(this.dbPath, jsonData, 'utf8');
console.log('Data saved to', this.dbPath);
} else {
// Browser - download as file
this.downloadJSON(jsonData);
}
}
downloadJSON(jsonData) {
const blob = new Blob([jsonData], { type: 'application/json' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = 'tasks.json';
a.click();
URL.revokeObjectURL(url);
console.log('Data exported as tasks.json');
}
async load() {
try {
if (this.isNode) {
const content = await this.fs.readFile(this.dbPath, 'utf8');
this.data = JSON.parse(content);
console.log('Data loaded from', this.dbPath);
} else {
// Browser - try to load from localStorage as fallback
const saved = localStorage.getItem('fileDB');
if (saved) {
this.data = JSON.parse(saved);
console.log('Data loaded from localStorage');
}
}
} catch (e) {
console.log('No existing data file, starting fresh');
this.data = { tasks: [], completed: [], archived: [], categories: ['Work', 'Personal'] };
}
}
async saveTasks(tasks) {
this.data.tasks = tasks;
await this.saveToStorage();
}
async loadTasks() {
return this.data.tasks || [];
}
async saveCompleted(completed) {
this.data.completed = completed;
await this.saveToStorage();
}
async loadCompleted() {
return this.data.completed || [];
}
async saveArchived(archived) {
this.data.archived = archived;
await this.saveToStorage();
}
async loadArchived() {
return this.data.archived || [];
}
async saveCategories(categories) {
this.data.categories = categories;
await this.saveToStorage();
}
async loadCategories() {
return this.data.categories || ['Work', 'Personal'];
}
async saveToStorage() {
// Always save to localStorage for browser persistence
localStorage.setItem('fileDB', JSON.stringify(this.data));
console.log('Auto-saved to localStorage');
}
async exportData() {
const jsonData = JSON.stringify(this.data, null, 2);
const blob = new Blob([jsonData], { type: 'application/json' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = `tasks-backup-${new Date().toISOString().split('T')[0]}.json`;
a.style.display = 'none';
// Add to document, click, then remove
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
// Clean up the URL after a short delay
setTimeout(() => URL.revokeObjectURL(url), 100);
console.log('Exported as:', a.download);
}
async importData(file) {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = async (e) => {
try {
this.data = JSON.parse(e.target.result);
// Migration: ensure categories exist
if (!this.data.categories) {
this.data.categories = ['Work', 'Personal'];
}
// Migration: add category to tasks without one
if (this.data.tasks) {
this.data.tasks.forEach(task => {
if (!task.category) task.category = this.data.categories[0];
});
}
await this.saveToStorage();
resolve(this.data);
} catch (error) {
reject(error);
}
};
reader.onerror = reject;
reader.readAsText(file);
});
}
}