-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
200 lines (172 loc) · 6.13 KB
/
app.js
File metadata and controls
200 lines (172 loc) · 6.13 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
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
// app.js (fixed)
// Dexie DB with single table for infinite nesting
const db = new Dexie("GoalsDB");
db.version(1).stores({
items: "++id,parentId,title,createdAt,doneAt,archived,media"
});
// --- Render recursively ---
async function renderItems(parentId = null, container = null) {
const items = await db.items.where("parentId").equals(parentId).toArray();
// Robust sort: handle numeric timestamps or ISO strings
items.sort((a, b) => {
const ta = (typeof a.createdAt === 'number') ? a.createdAt : Date.parse(a.createdAt || 0);
const tb = (typeof b.createdAt === 'number') ? b.createdAt : Date.parse(b.createdAt || 0);
return (ta || 0) - (tb || 0);
});
const target = container || document.getElementById("items");
target.innerHTML = "";
for (let it of items) {
const div = document.createElement("div");
div.className = "item";
// Title + done indicator
const titleEl = document.createElement("b");
titleEl.textContent = it.title || "(no title)";
div.appendChild(titleEl);
if (it.doneAt) div.appendChild(document.createTextNode(" ✅"));
// Buttons
const btnDone = document.createElement("button");
btnDone.textContent = it.doneAt ? "Undo" : "Done";
btnDone.addEventListener("click", () => toggleDone(it.id));
const btnDel = document.createElement("button");
btnDel.textContent = "🗑";
btnDel.addEventListener("click", () => {
if (confirm("Delete this item and all its children?")) deleteItem(it.id);
});
div.appendChild(document.createElement("br"));
div.appendChild(btnDone);
div.appendChild(btnDel);
// Input for adding a child
const input = document.createElement("input");
input.type = "text";
input.placeholder = "Add substep...";
input.addEventListener("keydown", (e) => {
if (e.key === "Enter") {
const val = input.value.trim();
if (val) addItem(it.id, val);
input.value = "";
}
});
div.appendChild(input);
// File input for media attachment
const file = document.createElement("input");
file.type = "file";
file.addEventListener("change", () => {
if (file.files.length) attachMedia(it.id, file.files[0]);
});
div.appendChild(file);
// Show media link if present
if (it.media) {
const a = document.createElement("a");
a.href = it.media;
a.target = "_blank";
a.textContent = " 📎 Media";
div.appendChild(a);
}
// Child container and recursive render
const childContainer = document.createElement("div");
childContainer.className = "children";
childContainer.id = `children-${it.id}`;
div.appendChild(childContainer);
target.appendChild(div);
// recurse
await renderItems(it.id, childContainer);
}
}
// --- Add new item (parentId=null for root) ---
async function addItem(parentId, text = null) {
if (parentId === null) {
// root-level add from #rootInput
text = document.getElementById("rootInput").value.trim();
if (!text) return;
document.getElementById("rootInput").value = "";
} else {
if (!text || !text.trim()) return;
}
const payload = {
// store explicit null for top-level
parentId: parentId === undefined ? null : parentId,
title: text,
createdAt: Date.now()
};
// Do NOT include 'id' property here — let Dexie generate it
await db.items.add(payload);
await renderItems();
}
// --- Delete item and all children recursively ---
async function deleteItem(id) {
async function deleteRecursive(itemId) {
const children = await db.items.where("parentId").equals(itemId).toArray();
for (let c of children) {
await deleteRecursive(c.id);
}
await db.items.delete(itemId);
}
await deleteRecursive(id);
await renderItems();
}
// --- Toggle done/undone ---
async function toggleDone(id) {
const it = await db.items.get(id);
await db.items.update(id, { doneAt: it.doneAt ? null : Date.now() });
await renderItems();
}
// --- Attach media to an item (stores DataURL) ---
async function attachMedia(id, file) {
const reader = new FileReader();
reader.onload = async () => {
// store the data URL in `media` field
await db.items.update(id, { media: reader.result, updatedAt: Date.now() });
await renderItems();
};
reader.readAsDataURL(file);
}
// --- Export DB to JSON ---
async function exportData() {
const data = await db.items.toArray();
const blob = new Blob([JSON.stringify(data, null, 2)], { type: "application/json" });
// FileSaver must be available (FileSaver.min.js)
saveAs(blob, "goals-backup.json");
}
// --- Import DB from JSON ---
// IMPORTANT: sanitize items so any item with id === null/undefined does NOT include id property.
// That allows Dexie to auto-generate an id for it.
async function importData(file) {
try {
const text = await file.text();
let data = JSON.parse(text);
// support wrapped format { items: [...] }
if (data && data.items && Array.isArray(data.items)) data = data.items;
if (!Array.isArray(data)) {
alert("Import failed: JSON must be an array of items (or { items: [...] }).");
return;
}
const cleaned = data.map(orig => {
const item = Object.assign({}, orig); // shallow copy
// remove explicit null/undefined id so DB will auto-generate
if (item.id === null || item.id === undefined) {
delete item.id;
}
// normalize parentId (missing/undefined -> null)
if (!("parentId" in item) || item.parentId === undefined) item.parentId = null;
// keep media as-is (expecting data URLs if present)
return item;
});
await db.transaction('rw', db.items, async () => {
await db.items.clear();
await db.items.bulkAdd(cleaned);
});
await renderItems();
alert("Import complete.");
} catch (err) {
console.error(err);
alert("Import failed: " + (err && err.message ? err.message : String(err)));
}
}
// --- Init on load ---
window.addEventListener("load", () => {
// ensure there's a root input in the DOM
if (!document.getElementById("rootInput")) {
console.warn("rootInput not found in DOM. Make sure index.html contains: <input id=\"rootInput\">");
}
renderItems();
});