-
Notifications
You must be signed in to change notification settings - Fork 24
Expand file tree
/
Copy pathindex.html
More file actions
790 lines (718 loc) · 26.6 KB
/
index.html
File metadata and controls
790 lines (718 loc) · 26.6 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
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
<!-- User Stories & Requirements for the code below:
- I want the web app to be a single page html file
- For the font use CONSOLAS, monospace
Main user stories:
- As a father I want to have a web app where I can playfully note down every time my newborn learns a new skill. I want to do this in form of a predefined "tech tree" that my baby unlocks
- I want in the tech tree to see the typical achievements my baby will unlock and also how they are connected. For example I want to see one tree item that says "Plays with her hands" with a time point of "Typically unlocked at month 3"
- I want to educate myself on what the next items in the tech tree will be that my baby will most likely start doing
- I want to enter my babies birthday at the top center of the app so that when I unlock achievements it can automatically compare the typical achievement date vs mine
Storage & Datamodel:
- I want the web app to not have any backend, everything should be stored locally in my browsers local storage.
- The data should be stored in a json structure.
- I should be able to dump the entire state of the app as a json text file to back up my data on my computer. The content of the json text file should be formatted so that I can edit it with a text editor.
- An entry in that json should have these fields:
- id (number)
- title (string)
- description (string, The description of the tree entries should typically contain brief, research-backed tips or activity suggestions to support my baby's development related to that specific milestone)
- icon (string, optional, if e.g. "face" -> uses the Material Icon "face")
- typical_achievement_weeks (time in weeks when it's typically achieved)
- follow_up_ids (array of id numbers, can be empty, follow up item that can be unlocked afterwards)
- achievement_time_weeks (number, allow null & not in json, time in weeks when my baby unlocked the item)
- comment (string, allow null & not in json, comment that I can make when I complete the tree item)
- The birth date the user enters at the top center should also be stored into the local storage and reloaded on app start
- The default data that should be loaded if no data is found in the storage should be loaded from https://raw.githubusercontent.com/cs-util-com/BabyStepsJs/refs/heads/main/defaultData.json.txt
- I want to be able to add an optional image when I complete an achievement. The image should be stored in the local storage and displayed in the side panel when the achievement is selected.
Tech Tree:
- I should be able to pan around, zoom in and out of and interact with the tree items in the tech tree
- I want the tech tree UI to automatically arrange itself. The earliest items should start left and the latest items should end right.
- The UI for each node should be a rounded rectangle with the caption on the top left, the week info on the bottom left and the optional icon on the right center (being quite large and if overlap happens behind the text). The icon should be grayish to not distract too much
Coloring:
- If there is an item that is typically achieved after 3 weeks but the birth date is already 4 weeks ago then color the related node in a different color
- Highlight nodes that will be unlocked next in a different color. A node will likely be unlocked next if the previous node is already unlocked.
- Once the user completes an achievement, the colors are refreshed to highlight the next unlockable node.
Side Panel:
- If a node is clicked the UI with details should show in a side panel (not a popup) and the user should be able to enter the date when it was achieved and an optional comment
- When the user clicks a node and the side panel opens fill in the current date for the date when the achievement was unlocked
- If the side panel is open and the user clicks somewhere outside of the side panel, close it. This way also no dedicated “close” button is needed
- When the user selects a node that is already completed, load the date and comment from the data when it was unlocked into the side panel ui that opens
Top Bar:
- I want the top bar to be responsive on mobile devices in portrait mode. The UI should reorganize or adapt as needed.
- Based on the entered birthdate show also the current week the baby is in in the top header bar (right next to the date)
- The import and export buttons should use the Material Icons “cloud_download” and “save” respectively
Keep this comment block in the code.
Simplify the code if possible (without removing the functionality described above).
You MUST keep all comments in the code below, even if you think they are redundant.
Always respond with the full new html file (including these comments here),
additional explanations what you change are nice to have but not necessary.
-->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<title>BabyStepsJs</title>
<!-- D3 -->
<script src="https://d3js.org/d3.v7.min.js"></script>
<!-- Material Icons -->
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet" />
<!-- Canvas Confetti Library -->
<script src="https://cdn.jsdelivr.net/npm/canvas-confetti@1.9.3/dist/confetti.browser.min.js"></script>
<style>
/* GLOBAL */
html, body {
margin: 0;
padding: 0;
overflow: hidden;
background-color: #1e1e2f;
font-family: CONSOLAS, monospace;
}
/* PANELS & RESPONSIVENESS */
.top-panel {
position: absolute;
top: 10px;
width: 100%;
z-index: 999;
display: flex;
flex-wrap: wrap;
justify-content: center;
align-items: center;
gap: 20px;
color: white;
font-size: 14px;
}
@media (max-width: 600px) {
.top-panel {
flex-direction: column;
align-items: flex-start;
gap: 10px;
}
.top-panel .birthdate-container,
.top-panel > div {
width: 100%;
display: flex;
justify-content: center;
}
}
/* BIRTHDATE + BUTTONS */
.birthdate-container {
display: flex;
align-items: center;
gap: 8px;
}
.top-panel input[type="date"] {
padding: 5px 8px;
border: none;
border-radius: 5px;
color: black;
}
.top-panel button {
display: inline-flex;
align-items: center;
justify-content: center;
padding: 5px 10px;
border: none;
border-radius: 5px;
background-color: #4caf50;
color: white;
font-weight: bold;
cursor: pointer;
}
.top-panel button:hover {
background-color: #388e3c;
}
.top-panel .material-icons {
margin-right: 4px;
font-size: 18px;
vertical-align: middle;
}
.top-panel input#importFile {
display: none;
}
/* SIDE PANEL */
.side-panel {
position: absolute;
right: 0;
width: 300px;
height: 100%;
background-color: #2c2c3e;
color: #fff;
border-left: 1px solid #444;
padding: 20px;
display: none;
box-sizing: border-box;
flex-direction: column;
gap: 10px;
font-size: 14px;
z-index: 1000; /* Added z-index to ensure side panel is on top */
}
.side-panel h2 {
margin: 0;
font-size: 16px;
}
.side-panel input[type="date"],
.side-panel textarea,
.side-panel input[type="file"] {
margin-top: 5px;
padding: 5px;
border: none;
border-radius: 5px;
color: black;
font-family: CONSOLAS, monospace;
}
.side-panel textarea {
height: 80px;
resize: vertical;
}
#sidePanelImagePreview {
max-width: 100%;
max-height: 120px;
object-fit: cover;
display: none;
margin-top: 5px;
border: 1px solid #444;
}
.side-panel button.save-btn {
margin-top: 5px;
width: 100%;
padding: 5px;
border: none;
border-radius: 5px;
background-color: #4caf50;
color: white;
font-weight: bold;
cursor: pointer;
}
.side-panel button.save-btn:hover {
background-color: #388e3c;
}
/* MAIN SVG / LINKS */
svg {
width: 100%;
height: 100vh;
box-sizing: border-box;
}
.link {
stroke: #888;
stroke-width: 2px;
marker-end: url(#arrowhead);
}
/* NODES */
.node-rect {
stroke: #fff;
stroke-width: 1.5px;
cursor: pointer;
fill: #a88615c5; /* default locked color */
rx: 10;
ry: 10; /* rounded corners */
}
.node-rect.overdue {
fill: #cc5a5ad7;
}
.node-rect.next {
fill: #5d50d0c7;
}
.node-rect.unlocked {
fill: rgba(9, 126, 19, 0.856);
}
.title-text {
fill: #fff;
font-size: 12px;
pointer-events: none;
}
.description-text {
fill: #ccc;
font-size: 10px;
pointer-events: none;
}
.weeks-text {
fill: #ececec;
font-size: 10px;
pointer-events: none;
}
.node-icon {
font-family: "Material Icons";
font-size: 36px;
fill: #fff;
fill-opacity: 0.65;
pointer-events: none;
}
</style>
</head>
<body>
<div class="top-panel">
<div class="birthdate-container">
<label for="birthDate">Birthday:</label>
<input type="date" id="birthDate"/>
<span id="currentWeekLabel"></span>
</div>
<div>
<button id="importBtn">
<span class="material-icons">cloud_download</span>
Import
</button>
<button id="exportBtn">
<span class="material-icons">save</span>
Export
</button>
<input id="importFile" type="file" accept=".json" />
</div>
</div>
<!-- SIDE PANEL -->
<div class="side-panel" id="sidePanel">
<h2 id="sidePanelTitle"></h2>
<div id="sidePanelDescription" style="font-size: 12px; color: #ccc;"></div>
<label for="sidePanelAchievementDate">Unlock Date:</label>
<input type="date" id="sidePanelAchievementDate" />
<label for="sidePanelComment">Notes:</label>
<textarea id="sidePanelComment" placeholder="Enter any notes..."></textarea>
<label for="sidePanelImageFile">Add an image:</label>
<input type="file" id="sidePanelImageFile" accept="image/*" />
<img id="sidePanelImagePreview" />
<button class="save-btn" id="sidePanelSaveBtn">Save</button>
</div>
<!-- MAIN SVG -->
<svg id="graph"></svg>
<script>
(async function main() {
// HELPER to compute age in weeks between two dates
function weeksBetween(firstDate, secondDate) {
const millisecondsPerWeek = 7 * 24 * 60 * 60 * 1000;
return Math.floor((secondDate - firstDate) / millisecondsPerWeek);
}
function formatAge(weeks) {
if (weeks >= 52) {
const years = weeks / 52;
return `${years.toFixed(1)} years`;
} else {
return `Week ${weeks}`;
}
}
// 1) Load data from localStorage if possible
let babyData = {
birthday: "",
latestCameraPosition: null,
items: []
};
const savedData = localStorage.getItem("babyData");
if (savedData) {
try {
const parsed = JSON.parse(savedData);
if (parsed && Array.isArray(parsed.items)) {
babyData = parsed;
} else {
console.warn("Local storage babyData is invalid, ignoring it.");
}
} catch (e) {
console.warn("Local storage babyData was corrupt, ignoring it.");
}
}
// If no valid local data, load from remote (defaultData.json.txt)
if (!babyData.items.length) {
try {
const resp = await fetch("https://raw.githubusercontent.com/cs-util-com/BabyStepsJs/refs/heads/main/defaultData.json.txt");
babyData = await resp.json();
} catch (error) {
console.error("Could not fetch baby data from remote:", error);
babyData.items = [];
}
}
// Set birthDate input from babyData.birthday
if (babyData.birthday) {
document.getElementById("birthDate").value = babyData.birthday;
}
const svg = d3.select("#graph");
const width = window.innerWidth;
const height = window.innerHeight;
svg.attr("width", width).attr("height", height);
// A group to handle pan & zoom
const zoomG = svg.append("g");
// Arrowhead definition
svg.append("defs").append("marker")
.attr("id", "arrowhead")
.attr("viewBox", "0 -5 10 10")
.attr("refX", 110)
.attr("refY", 0)
.attr("markerWidth", 6)
.attr("markerHeight", 6)
.attr("orient", "auto")
.attr("markerUnits", "strokeWidth")
.append("path")
.attr("d", "M0,-5L10,0L0,5")
.attr("fill", "#888");
// Zoom behavior with saving latestCameraPosition
const zoomBehavior = d3.zoom().on("zoom", (event) => {
zoomG.attr("transform", event.transform);
// Save the latest camera position
babyData.latestCameraPosition = {
x: event.transform.x,
y: event.transform.y,
k: event.transform.k
};
saveToLocalStorage();
});
svg.call(zoomBehavior);
// Build graph data (nodes & links) from babyData.items
function buildGraphData(data) {
const validIds = new Set(data.map(d => d.id));
return {
nodes: data, // Use the same objects to keep them in sync
links: data.flatMap(d =>
d.follow_up_ids
.filter(fuId => validIds.has(fuId))
.map(fuId => ({ source: d.id, target: fuId }))
)
};
}
const NODE_WIDTH = 194; // Golden ratio
const NODE_HEIGHT = 120;
let simulation, nodeGroup, link, nodes, links;
function renderGraph() {
zoomG.selectAll("*").remove();
const graphData = buildGraphData(babyData.items);
nodes = graphData.nodes;
links = graphData.links;
// Setup force simulation
simulation = d3.forceSimulation(nodes)
// Link force keeps connected nodes (parent->child) closer together
.force("link", d3.forceLink(links).id(d => d.id).distance(100))
// Charge force repels nodes from each other
.force("charge", d3.forceManyBody().strength(-300))
// Position along X axis, using typical_achievement_weeks to anchor:
.force("x", d3.forceX(d => d.typical_achievement_weeks * 80).strength(1.0))
// Gently position everything in the vertical center, but not too strong:
.force("y", d3.forceY(height / 2).strength(0.1))
// Small collision radius so that it doesn’t “push” nodes too drastically left and right:
.force("collision", d3.forceCollide().radius(120))
.on("tick", () => {
link.attr("x1", d => d.source.x)
.attr("y1", d => d.source.y)
.attr("x2", d => d.target.x)
.attr("y2", d => d.target.y);
nodeGroup.attr("transform", d => `translate(${d.x},${d.y})`);
});
// Draw links
link = zoomG.selectAll(".link")
.data(links)
.enter().append("line")
.attr("class", "link");
// Draw node groups
nodeGroup = zoomG.selectAll(".node")
.data(nodes)
.enter().append("g")
.attr("class", "node")
.call(d3.drag()
.on("start", (event, d) => {
if (!event.active) simulation.alphaTarget(0.3).restart();
d.fx = d.x; d.fy = d.y;
})
.on("drag", (event, d) => {
d.fx = event.x; d.fy = event.y;
})
.on("end", (event, d) => {
if (!event.active) simulation.alphaTarget(0);
d.fx = null; d.fy = null;
})
);
// Node rect
nodeGroup.append("rect")
.attr("class", "node-rect")
.attr("width", NODE_WIDTH)
.attr("height", NODE_HEIGHT)
.attr("x", -NODE_WIDTH / 2)
.attr("y", -NODE_HEIGHT / 2)
.on("click", (event, d) => {
event.stopPropagation(); // so we don't close side-panel
onNodeClick(d);
});
// Node icon (right center)
nodeGroup.append("text")
.attr("class", "node-icon")
.attr("x", (NODE_WIDTH / 2) - 32)
.attr("y", 48)
.attr("text-anchor", "middle")
.text(d => d.icon || "");
// Title text (top-left corner)
nodeGroup.append("text")
.attr("class", "title-text")
.attr("x", -(NODE_WIDTH / 2) + 8)
.attr("y", -(NODE_HEIGHT / 2) + 16)
.text(d => d.title)
.each(function() { wrapText(d3.select(this), NODE_WIDTH - 40); });
// Description text (below title)
nodeGroup.append("text")
.attr("class", "description-text")
.attr("x", -(NODE_WIDTH / 2) + 8)
.attr("y", function(d) {
// Position below title-text; adjust after wrapping
const titleNode = d3.select(this.parentNode).select(".title-text").node();
const titleHeight = titleNode.getBBox().height;
return -(NODE_HEIGHT / 2) + 16 + titleHeight + 4; // 4px padding
})
.text(d => d.description)
.each(function() { wrapText(d3.select(this), NODE_WIDTH - 40); });
// Weeks info (bottom-left corner)
nodeGroup.append("text")
.attr("class", "weeks-text")
.attr("x", -(NODE_WIDTH / 2) + 8)
.attr("y", function(d) {
// Position weeks-text at bottom, adjust based on description height
const descNode = d3.select(this.parentNode).select(".description-text").node();
const descHeight = descNode.getBBox().height;
const titleNode = d3.select(this.parentNode).select(".title-text").node();
const titleHeight = titleNode.getBBox().height;
return -(NODE_HEIGHT / 2) + 16 + titleHeight + descHeight + 12; // 24px padding
})
.text(formatWeeks);
// Apply saved camera position if available
if (babyData.latestCameraPosition) {
const { x, y, k } = babyData.latestCameraPosition;
svg.transition().duration(750).call(
zoomBehavior.transform,
d3.zoomIdentity.translate(x, y).scale(k)
);
} else {
// If no camera position is saved, center on the first nodes
simulation.on("end", () => {
if (!babyData.latestCameraPosition) {
// Find the minimum typical achievement weeks
const minWeeks = d3.min(nodes, d => d.typical_achievement_weeks);
// Get all nodes with the minimum weeks
const firstNodes = nodes.filter(d => d.typical_achievement_weeks === minWeeks);
if (firstNodes.length) {
// Calculate the average position of the first nodes
const avgX = d3.mean(firstNodes, d => d.x);
const avgY = d3.mean(firstNodes, d => d.y);
// Define desired scale
const desiredScale = 1.5;
// Calculate the translation to center the first nodes
const translateX = width / 2 - avgX * desiredScale;
const translateY = height / 2 - avgY * desiredScale;
// Create the zoom transform
const transform = d3.zoomIdentity.translate(translateX, translateY).scale(desiredScale);
// Apply the transform with a transition
svg.transition().duration(750).call(
zoomBehavior.transform,
transform
);
// Save the transform
babyData.latestCameraPosition = { x: translateX, y: translateY, k: desiredScale };
saveToLocalStorage();
}
}
});
}
refreshGraph();
}
// Simple text-wrap function for node titles
function wrapText(textSelection, width) {
textSelection.each(function() {
const text = d3.select(this);
const words = text.text().split(/\s+/);
let line = [];
let lineNumber = 0;
const lineHeight = 1.2;
const y = text.attr("y");
const x = text.attr("x");
let tspan = text.text(null).append("tspan").attr("x", x).attr("y", y);
for (const word of words) {
line.push(word);
tspan.text(line.join(" "));
if (tspan.node().getComputedTextLength() > width) {
line.pop();
tspan.text(line.join(" "));
line = [word];
tspan = text.append("tspan")
.attr("x", x).attr("y", y)
.attr("dy", ++lineNumber * lineHeight + "em")
.text(word);
}
}
});
}
function formatWeeks(d) {
if (d.achievement_time_weeks == null) {
return `~ ${formatAge(d.typical_achievement_weeks)}`;
}
const diff = d.typical_achievement_weeks - d.achievement_time_weeks;
if (diff === 0) {
return `Unlocked right on time`;
}
const timing = diff > 0 ? 'early' : 'late';
const diffWeeks = Math.abs(diff);
const diffText = diffWeeks >= 52 ? `${(diffWeeks / 52).toFixed(1)} years` : `${diffWeeks} weeks`;
return `Unlocked ${diffText} ${timing}`;
}
// 4) COLORING & “NEXT” / “OVERDUE”
function refreshGraph() {
updateCurrentWeekLabel();
const birthDateStr = babyData.birthday;
const ageInWeeks = birthDateStr ? weeksBetween(new Date(birthDateStr), new Date()) : null;
nodeGroup.selectAll(".node-rect")
.classed("unlocked", d => d.achievement_time_weeks != null)
.classed("overdue", d => d.achievement_time_weeks == null && ageInWeeks && ageInWeeks > d.typical_achievement_weeks)
.classed("next", d => {
if (d.achievement_time_weeks != null) return false;
const parents = babyData.items.filter(p => p.follow_up_ids.includes(d.id));
return parents.length === 0 || parents.every(p => p.achievement_time_weeks != null);
});
// Update weeks text again (in case it changed)
nodeGroup.selectAll(".weeks-text").text(formatWeeks);
}
// 5) SIDE PANEL
let currentNode = null;
const sidePanel = document.getElementById("sidePanel");
const titleEl = document.getElementById("sidePanelTitle");
const descEl = document.getElementById("sidePanelDescription");
const dateEl = document.getElementById("sidePanelAchievementDate");
const commentEl = document.getElementById("sidePanelComment");
const saveBtn = document.getElementById("sidePanelSaveBtn");
const imageFileInput = document.getElementById("sidePanelImageFile");
const imagePreview = document.getElementById("sidePanelImagePreview");
function onNodeClick(d) {
currentNode = d;
titleEl.textContent = d.title;
descEl.textContent = d.description;
commentEl.value = d.comment || "";
// If there's an existing image, show it; otherwise hide preview
if (d.imageData) {
imagePreview.src = d.imageData;
imagePreview.style.display = "block";
} else {
imagePreview.style.display = "none";
}
imageFileInput.value = null; // reset file input
const birthDateStr = babyData.birthday;
if (d.achievement_time_weeks === null) {
// If locked, fill today's date by default
dateEl.value = new Date().toISOString().split("T")[0];
} else if (birthDateStr) {
// If already unlocked, reconstruct date from birth + achievement_time_weeks
const bd = new Date(birthDateStr);
bd.setDate(bd.getDate() + 7 * d.achievement_time_weeks);
dateEl.value = bd.toISOString().split("T")[0];
} else {
dateEl.value = "";
}
sidePanel.style.display = "flex";
}
function hideSidePanel() {
sidePanel.style.display = "none";
currentNode = null;
}
// Handle image file selection
imageFileInput.addEventListener("change", (event) => {
const file = event.target.files[0];
if (!file) return;
const reader = new FileReader();
reader.onload = (ev) => {
if (currentNode) {
currentNode.imageData = ev.target.result; // store base64
imagePreview.src = currentNode.imageData;
imagePreview.style.display = "block";
saveToLocalStorage();
}
};
reader.readAsDataURL(file);
});
// Save button event listener
saveBtn.addEventListener("click", () => {
if (!currentNode) return;
const wasLocked = currentNode.achievement_time_weeks === null;
const achievementDate = dateEl.value ? new Date(dateEl.value) : null;
const birthDateStr = babyData.birthday;
if (achievementDate && birthDateStr) {
// Convert the difference to weeks
const bd = new Date(birthDateStr);
const w = weeksBetween(bd, achievementDate);
currentNode.achievement_time_weeks = w > 0 ? w : 0;
} else if (achievementDate && !birthDateStr) {
// If no birth date, just assume typical_achievement_weeks
currentNode.achievement_time_weeks = currentNode.typical_achievement_weeks;
} else {
// No date => treat as locked
currentNode.achievement_time_weeks = null;
}
currentNode.comment = commentEl.value.trim();
refreshGraph();
saveToLocalStorage();
hideSidePanel();
// Trigger confetti if the node was just unlocked
confetti({
particleCount: 200,
spread: 70,
origin: { y: 0.6 }
});
});
// Close side panel if user clicks outside it
document.addEventListener("click", (event) => {
if (!sidePanel.contains(event.target)) {
hideSidePanel();
}
});
// 6) SAVE & LOAD from LOCAL STORAGE
function saveToLocalStorage() {
localStorage.setItem("babyData", JSON.stringify(babyData));
}
// 7) IMPORT / EXPORT
document.getElementById("exportBtn").addEventListener("click", () => {
const exportData = JSON.stringify(babyData, null, 2);
const blob = new Blob([exportData], { type: "application/json" });
const url = URL.createObjectURL(blob);
const a = document.createElement("a");
a.href = url;
a.download = "babyData_backup.json";
a.click();
URL.revokeObjectURL(url);
});
document.getElementById("importBtn").addEventListener("click", () => {
document.getElementById("importFile").click();
});
document.getElementById("importFile").addEventListener("change", (e) => {
const file = e.target.files[0];
if (!file) return;
const reader = new FileReader();
reader.onload = (ev) => {
try {
const importedData = JSON.parse(ev.target.result);
if (importedData && Array.isArray(importedData.items)) {
babyData = importedData;
saveToLocalStorage();
renderGraph();
} else if (Array.isArray(importedData)) {
// Handle case where imported data is directly the items array
babyData.items = importedData;
saveToLocalStorage();
renderGraph();
} else {
alert("JSON must be an object with an 'items' array.");
}
} catch (err) {
alert("Error parsing JSON. Check file format.");
}
};
reader.readAsText(file);
e.target.value = null;
});
// 8) HELPER: Update “Current Week” label
function updateCurrentWeekLabel() {
const birthDateStr = babyData.birthday;
const label = document.getElementById("currentWeekLabel");
if (birthDateStr) {
const weeks = weeksBetween(new Date(birthDateStr), new Date());
label.textContent = `(${formatAge(weeks)})`;
} else {
label.textContent = "";
}
}
// 9) RE-RENDER ON BIRTHDATE CHANGE
document.getElementById("birthDate").addEventListener("change", () => {
babyData.birthday = document.getElementById("birthDate").value;
saveToLocalStorage();
refreshGraph();
});
// 10) INITIAL RENDER
renderGraph();
})();
</script>
</body>
</html>