-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
1286 lines (1061 loc) · 38.3 KB
/
Copy pathapp.js
File metadata and controls
1286 lines (1061 loc) · 38.3 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
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* ===========================
Circle Planner - app.js
JS + IndexedDB
Updated:
- Ring layering fix (no clearing dragCreateLayer)
- Gradients + glow for rings
- Drag-to-create: continuous angle (no full-ring jump)
=========================== */
(() => {
"use strict";
/* ========= DOM helpers ========= */
const $ = (sel) => document.querySelector(sel);
/* ========= DOM refs ========= */
const prevDayBtn = $("#prevDayBtn");
const nextDayBtn = $("#nextDayBtn");
const dayViewBtn = $("#dayViewBtn");
const weekViewBtn = $("#weekViewBtn");
const activeDateText = $("#activeDateText");
const activeViewText = $("#activeViewText");
const catStudyBtn = $("#catStudyBtn");
const catWorkBtn = $("#catWorkBtn");
const catSportBtn = $("#catSportBtn");
const dialSvg = $("#dialSvg");
const dialTicks = $("#dialTicks");
const ringStudy = $("#ringStudy");
const ringWork = $("#ringWork");
const ringSport = $("#ringSport");
const dragCreateLayer = $("#dragCreateLayer");
const rangeText = $("#rangeText");
const durationText = $("#durationText");
const activeCategoryText = $("#activeCategoryText");
const taskForm = $("#taskForm");
const taskTitleInput = $("#taskTitleInput");
const taskCategorySelect = $("#taskCategorySelect");
const taskStartInput = $("#taskStartInput");
const taskEndInput = $("#taskEndInput");
const taskNotesInput = $("#taskNotesInput");
const clearSelectionBtn = $("#clearSelectionBtn");
const exportJsonBtn = $("#exportJsonBtn");
const importJsonBtn = $("#importJsonBtn");
const importFileInput = $("#importFileInput");
const jsonPreview = $("#jsonPreview");
const statusFilter = $("#statusFilter");
const categoryFilter = $("#categoryFilter");
const searchInput = $("#searchInput");
const progressText = $("#progressText");
const statTotal = $("#statTotal");
const statDone = $("#statDone");
const statPlannedMins = $("#statPlannedMins");
const weeklyChart = $("#weeklyChart");
const chartCtx = weeklyChart.getContext("2d");
const taskList = $("#taskList");
const activePomodoroTask = $("#activePomodoroTask");
const pomodoroModeText = $("#pomodoroModeText");
const pomodoroTimeText = $("#pomodoroTimeText");
const pomodoroStartBtn = $("#pomodoroStartBtn");
const pomodoroPauseBtn = $("#pomodoroPauseBtn");
const pomodoroResetBtn = $("#pomodoroResetBtn");
const focusMinutes = $("#focusMinutes");
const breakMinutes = $("#breakMinutes");
const requestNotifBtn = $("#requestNotifBtn");
const notifStatusText = $("#notifStatusText");
const storageStatusText = $("#storageStatusText");
const useIndexedDbBtn = $("#useIndexedDbBtn");
const useBackendBtn = $("#useBackendBtn");
/* ========= Constants ========= */
const DB_NAME = "circle_planner_db";
const DB_VER = 1;
const STORE_TASKS = "tasks";
const STORE_SETTINGS = "settings";
const CATS = {
study: { label: "درس", color: "#6ee7ff", ringR: 150 },
work: { label: "کار", color: "#7c6cff", ringR: 130 },
sport: { label: "ورزش", color: "#40f5a3", ringR: 110 },
};
const SVG_CX = 210;
const SVG_CY = 210;
const MAX_SELECT_MINS = 10 * 60; // max 10 hours selection (prevents full-ring fill)
const SNAP_MINS = 5; // snap step
/* ========= State ========= */
const state = {
view: "day",
activeDate: new Date(),
activeCategory: "study",
selection: {
has: false,
startM: 9 * 60,
endM: 10 * 60,
cat: "study",
},
pomodoro: {
activeTaskId: null,
mode: "focus",
running: false,
remainingSec: 25 * 60,
timerId: null,
focusMin: 25,
breakMin: 5,
},
tasks: [],
};
/* ========= Utils ========= */
const pad2 = (n) => String(n).padStart(2, "0");
function dateKey(d = new Date()) {
const y = d.getFullYear();
const m = pad2(d.getMonth() + 1);
const dd = pad2(d.getDate());
return `${y}-${m}-${dd}`;
}
function addDays(d, delta) {
const x = new Date(d);
x.setDate(x.getDate() + delta);
return x;
}
function minsToHHMM(m) {
m = ((m % 1440) + 1440) % 1440;
const h = Math.floor(m / 60);
const mm = m % 60;
return `${pad2(h)}:${pad2(mm)}`;
}
function hhmmToMins(s) {
if (!s || !s.includes(":")) return 0;
const [h, m] = s.split(":").map(Number);
return (h * 60) + (m || 0);
}
function durationMins(startM, endM) {
startM = ((startM % 1440) + 1440) % 1440;
endM = ((endM % 1440) + 1440) % 1440;
if (endM >= startM) return endM - startM;
return (1440 - startM) + endM;
}
function makeId() {
return Math.random().toString(16).slice(2) + Date.now().toString(16);
}
/* ========= SVG math ========= */
function minsToAngle(mins) {
mins = ((mins % 1440) + 1440) % 1440;
return (mins / 1440) * Math.PI * 2;
}
function angleToMins(ang) {
const two = Math.PI * 2;
ang = (ang % two + two) % two;
return Math.round((ang / two) * 1440);
}
// dialAngle: 0 at top, clockwise
function pointerToDialAngle(clientX, clientY, rect) {
const cx = rect.left + rect.width / 2;
const cy = rect.top + rect.height / 2;
const dx = clientX - cx;
const dy = clientY - cy;
const a = Math.atan2(dy, dx);
let dial = (Math.PI / 2 - a);
const two = Math.PI * 2;
dial = (dial % two + two) % two;
return dial;
}
function normalizeAngle(a) {
const two = Math.PI * 2;
return (a % two + two) % two;
}
// signed smallest diff from a -> b in (-pi..pi)
function angleDiff(a, b) {
const two = Math.PI * 2;
let d = normalizeAngle(b) - normalizeAngle(a);
if (d > Math.PI) d -= two;
if (d < -Math.PI) d += two;
return d;
}
function arcPath(cx, cy, r, startAng, endAng) {
const start = { x: cx + r * Math.sin(startAng), y: cy - r * Math.cos(startAng) };
const end = { x: cx + r * Math.sin(endAng), y: cy - r * Math.cos(endAng) };
let delta = endAng - startAng;
if (delta < 0) delta += Math.PI * 2;
const largeArc = delta > Math.PI ? 1 : 0;
const sweep = 1;
return `M ${start.x.toFixed(2)} ${start.y.toFixed(2)} A ${r} ${r} 0 ${largeArc} ${sweep} ${end.x.toFixed(2)} ${end.y.toFixed(2)}`;
}
function svgEl(tag, attrs = {}) {
const el = document.createElementNS("http://www.w3.org/2000/svg", tag);
for (const [k, v] of Object.entries(attrs)) el.setAttribute(k, v);
return el;
}
function getPointerAngleAndMins(e) {
const rect = dialSvg.getBoundingClientRect();
const p = (e.touches && e.touches[0]) ? e.touches[0] : e;
const ang = pointerToDialAngle(p.clientX, p.clientY, rect);
const mins = Math.round(angleToMins(ang) / SNAP_MINS) * SNAP_MINS;
return { ang, mins };
}
/* ========= IndexedDB ========= */
let db = null;
function openDB() {
return new Promise((resolve, reject) => {
const req = indexedDB.open(DB_NAME, DB_VER);
req.onupgradeneeded = () => {
const dbx = req.result;
if (!dbx.objectStoreNames.contains(STORE_TASKS)) {
const store = dbx.createObjectStore(STORE_TASKS, { keyPath: "id" });
store.createIndex("by_day", "dayKey", { unique: false });
store.createIndex("by_done", "done", { unique: false });
store.createIndex("by_cat", "category", { unique: false });
}
if (!dbx.objectStoreNames.contains(STORE_SETTINGS)) {
dbx.createObjectStore(STORE_SETTINGS, { keyPath: "key" });
}
};
req.onsuccess = () => {
db = req.result;
resolve(db);
};
req.onerror = () => reject(req.error);
});
}
function tx(storeName, mode = "readonly") {
const t = db.transaction(storeName, mode);
return t.objectStore(storeName);
}
function dbPut(store, value) {
return new Promise((resolve, reject) => {
const req = store.put(value);
req.onsuccess = () => resolve(true);
req.onerror = () => reject(req.error);
});
}
function dbGet(store, key) {
return new Promise((resolve, reject) => {
const req = store.get(key);
req.onsuccess = () => resolve(req.result || null);
req.onerror = () => reject(req.error);
});
}
function dbGetAll(store) {
return new Promise((resolve, reject) => {
const req = store.getAll();
req.onsuccess = () => resolve(req.result || []);
req.onerror = () => reject(req.error);
});
}
function dbDelete(store, key) {
return new Promise((resolve, reject) => {
const req = store.delete(key);
req.onsuccess = () => resolve(true);
req.onerror = () => reject(req.error);
});
}
async function loadAll() {
state.tasks = await dbGetAll(tx(STORE_TASKS));
const s = await dbGet(tx(STORE_SETTINGS), "app_settings");
if (s && s.value) {
const v = s.value;
if (v.activeCategory && CATS[v.activeCategory]) state.activeCategory = v.activeCategory;
if (v.view) state.view = v.view;
if (v.activeDate) state.activeDate = new Date(v.activeDate);
if (v.pomodoro) {
state.pomodoro.focusMin = v.pomodoro.focusMin ?? 25;
state.pomodoro.breakMin = v.pomodoro.breakMin ?? 5;
state.pomodoro.activeTaskId = v.pomodoro.activeTaskId ?? null;
state.pomodoro.mode = v.pomodoro.mode ?? "focus";
state.pomodoro.remainingSec = v.pomodoro.remainingSec ?? state.pomodoro.focusMin * 60;
state.pomodoro.running = false;
}
}
focusMinutes.value = state.pomodoro.focusMin;
breakMinutes.value = state.pomodoro.breakMin;
taskCategorySelect.value = state.activeCategory;
}
async function saveSettings() {
const store = tx(STORE_SETTINGS, "readwrite");
const payload = {
key: "app_settings",
value: {
activeCategory: state.activeCategory,
view: state.view,
activeDate: state.activeDate.toISOString(),
pomodoro: {
activeTaskId: state.pomodoro.activeTaskId,
mode: state.pomodoro.mode,
remainingSec: state.pomodoro.remainingSec,
focusMin: state.pomodoro.focusMin,
breakMin: state.pomodoro.breakMin,
},
},
updatedAt: new Date().toISOString(),
};
await dbPut(store, payload);
}
/* ========= Gradients ========= */
function ensureGradients() {
const old = dialSvg.querySelector("defs#ringDefs");
if (old) old.remove();
const defs = svgEl("defs", { id: "ringDefs" });
const mkGrad = (id, c1, c2) => {
const lg = svgEl("linearGradient", { id, x1: "0", y1: "0", x2: "1", y2: "1" });
lg.appendChild(svgEl("stop", { offset: "0%", "stop-color": c1, "stop-opacity": "0.95" }));
lg.appendChild(svgEl("stop", { offset: "100%", "stop-color": c2, "stop-opacity": "0.95" }));
return lg;
};
defs.appendChild(mkGrad("grad-study", "#7df3ff", "#4aa8ff"));
defs.appendChild(mkGrad("grad-work", "#b69cff", "#6b55ff"));
defs.appendChild(mkGrad("grad-sport", "#63ffd2", "#25c3ff"));
dialSvg.insertBefore(defs, dialSvg.firstChild);
}
/* ========= Ticks ========= */
function renderTicks() {
dialTicks.innerHTML = "";
// major hour ticks + labels
for (let h = 0; h < 24; h++) {
const ang = minsToAngle(h * 60);
const rOuter = 170;
const rInner = 152;
dialTicks.appendChild(svgEl("line", {
x1: SVG_CX + rOuter * Math.sin(ang),
y1: SVG_CY - rOuter * Math.cos(ang),
x2: SVG_CX + rInner * Math.sin(ang),
y2: SVG_CY - rInner * Math.cos(ang),
stroke: "rgba(255,255,255,0.18)",
"stroke-width": "2"
}));
const lr = 132;
const lx = SVG_CX + lr * Math.sin(ang);
const ly = SVG_CY - lr * Math.cos(ang) + 4;
const t = svgEl("text", {
x: lx, y: ly,
"text-anchor": "middle",
"font-size": "11",
fill: "rgba(234,240,255,0.75)"
});
t.textContent = String(h);
dialTicks.appendChild(t);
}
// minor ticks
for (let i = 0; i < 48; i++) {
if (i % 2 === 0) continue;
const ang = minsToAngle(i * 30);
const rOuter = 170;
const rInner = 160;
dialTicks.appendChild(svgEl("line", {
x1: SVG_CX + rOuter * Math.sin(ang),
y1: SVG_CY - rOuter * Math.cos(ang),
x2: SVG_CX + rInner * Math.sin(ang),
y2: SVG_CY - rInner * Math.cos(ang),
stroke: "rgba(255,255,255,0.10)",
"stroke-width": "1.2"
}));
}
// base ring (once)
if (!dialSvg.querySelector("#baseRing")) {
const baseRing = svgEl("circle", {
id: "baseRing",
cx: SVG_CX, cy: SVG_CY, r: 170,
fill: "none",
stroke: "rgba(255,255,255,0.10)",
"stroke-width": "22"
});
const defs = dialSvg.querySelector("defs");
dialSvg.insertBefore(baseRing, defs ? defs.nextSibling : dialSvg.firstChild);
}
}
/* ========= Visible tasks (day/week) ========= */
function visibleDayKeys() {
if (state.view === "day") return [dateKey(state.activeDate)];
const keys = [];
for (let i = 6; i >= 0; i--) keys.push(dateKey(addDays(state.activeDate, -i)));
return keys;
}
function getVisibleTasks() {
const keys = new Set(visibleDayKeys());
return state.tasks.filter(t => keys.has(t.dayKey));
}
/* ========= Rings ========= */
function clearRings() {
ringStudy.innerHTML = "";
ringWork.innerHTML = "";
ringSport.innerHTML = "";
// IMPORTANT: do not clear dragCreateLayer here
}
function taskArcForRing(task, ringR) {
return arcPath(SVG_CX, SVG_CY, ringR, minsToAngle(task.startM), minsToAngle(task.endM));
}
function renderRings() {
clearRings();
const visible = getVisibleTasks();
const groups = {
study: visible.filter(t => t.category === "study"),
work: visible.filter(t => t.category === "work"),
sport: visible.filter(t => t.category === "sport"),
};
for (const [cat, items] of Object.entries(groups)) {
const ringG = cat === "study" ? ringStudy : cat === "work" ? ringWork : ringSport;
const ringR = CATS[cat].ringR;
// tinted background ring (if color-mix unsupported, browser will just ignore it)
const bg = svgEl("circle", {
cx: SVG_CX, cy: SVG_CY, r: ringR,
fill: "none",
stroke: `color-mix(in srgb, ${CATS[cat].color} 18%, rgba(255,255,255,0.06))`,
"stroke-width": "16",
opacity: "0.55"
});
ringG.appendChild(bg);
for (const t of items) {
const p = svgEl("path", {
d: taskArcForRing(t, ringR),
fill: "none",
stroke: `url(#grad-${cat})`,
"stroke-width": "16",
"stroke-linecap": "round",
opacity: t.done ? "0.28" : "0.90",
"data-id": t.id
});
p.style.cursor = "pointer";
p.style.filter = t.done
? "none"
: "drop-shadow(0 0 10px rgba(255,255,255,.10)) drop-shadow(0 0 20px rgba(124,108,255,.08))";
// click arc -> set pomodoro task
p.addEventListener("click", () => {
state.pomodoro.activeTaskId = t.id;
saveSettings();
renderPomodoro();
toast(`پومودورو روی: ${t.title}`);
});
ringG.appendChild(p);
}
}
highlightActiveRing();
}
function highlightActiveRing() {
const old = dragCreateLayer.querySelector("#activeRingGlow");
if (old) old.remove();
const cat = state.activeCategory;
const ringR = CATS[cat].ringR;
const glow = svgEl("circle", {
id: "activeRingGlow",
cx: SVG_CX, cy: SVG_CY, r: ringR,
fill: "none",
stroke: `url(#grad-${cat})`,
"stroke-width": "20",
opacity: "0.22"
});
glow.style.filter =
"drop-shadow(0 0 10px rgba(110,231,255,.22)) drop-shadow(0 0 22px rgba(124,108,255,.18))";
dragCreateLayer.appendChild(glow);
}
/* ========= Drag-to-create (continuous, no jump) ========= */
const drag = {
active: false,
startM: 0,
endM: 0,
lastAng: 0,
accumAng: 0,
startAng: 0,
directionLocked: null, // "cw" | "ccw" | null
};
function renderSelectionPreview() {
// remove old preview only
const prev = dragCreateLayer.querySelector("#dragPreviewArc");
if (prev) prev.remove();
highlightActiveRing();
const sel = state.selection;
if (!sel.has) {
rangeText.textContent = `--:-- تا --:--`;
durationText.textContent = `مدت: -- دقیقه`;
return;
}
const dur = durationMins(sel.startM, sel.endM);
rangeText.textContent = `${minsToHHMM(sel.startM)} تا ${minsToHHMM(sel.endM)}`;
durationText.textContent = `مدت: ${dur} دقیقه`;
const cat = sel.cat;
const ringR = CATS[cat].ringR;
const p = svgEl("path", {
id: "dragPreviewArc",
d: arcPath(SVG_CX, SVG_CY, ringR, minsToAngle(sel.startM), minsToAngle(sel.endM)),
fill: "none",
stroke: `url(#grad-${cat})`,
"stroke-width": "20",
"stroke-linecap": "round",
opacity: "0.62"
});
p.style.filter = "drop-shadow(0 0 12px rgba(255,255,255,.12))";
dragCreateLayer.appendChild(p);
}
function applySelectionToForm() {
if (!state.selection.has) return;
taskCategorySelect.value = state.selection.cat;
taskStartInput.value = minsToHHMM(state.selection.startM);
taskEndInput.value = minsToHHMM(state.selection.endM);
taskTitleInput.focus();
}
function onDialDown(e) {
// If clicking on a task arc, don't start drag
if (e.target && e.target.getAttribute && e.target.getAttribute("data-id")) return;
const { ang, mins } = getPointerAngleAndMins(e);
drag.active = true;
drag.startM = mins;
drag.endM = mins;
drag.startAng = ang;
drag.lastAng = ang;
drag.accumAng = 0;
drag.directionLocked = null;
state.selection.has = true;
state.selection.startM = drag.startM;
state.selection.endM = drag.endM;
state.selection.cat = state.activeCategory;
renderSelectionPreview();
applySelectionToForm();
e.preventDefault();
}
function onDialMove(e) {
if (!drag.active) return;
const { ang } = getPointerAngleAndMins(e);
let d = angleDiff(drag.lastAng, ang);
// lock direction after small movement
if (drag.directionLocked === null) {
if (Math.abs(d) > 0.03) { // ~1.7deg
drag.directionLocked = d >= 0 ? "cw" : "ccw";
}
} else {
if (drag.directionLocked === "cw" && d < 0) d = 0;
if (drag.directionLocked === "ccw" && d > 0) d = 0;
}
drag.accumAng += d;
drag.lastAng = ang;
// convert to minutes delta
let deltaM = Math.round((drag.accumAng / (Math.PI * 2)) * 1440);
deltaM = Math.round(deltaM / SNAP_MINS) * SNAP_MINS;
// clamp selection size
if (deltaM > MAX_SELECT_MINS) deltaM = MAX_SELECT_MINS;
if (deltaM < -MAX_SELECT_MINS) deltaM = -MAX_SELECT_MINS;
const newEnd = drag.startM + deltaM;
state.selection.has = true;
state.selection.startM = ((drag.startM % 1440) + 1440) % 1440;
state.selection.endM = ((newEnd % 1440) + 1440) % 1440;
state.selection.cat = state.activeCategory;
renderSelectionPreview();
applySelectionToForm();
e.preventDefault();
}
function onDialUp() {
if (!drag.active) return;
drag.active = false;
const dur = durationMins(state.selection.startM, state.selection.endM);
if (dur < 5) {
state.selection.has = false;
renderSelectionPreview();
toast("بازه خیلی کوچیک بود. دوباره درگ کن.");
return;
}
renderSelectionPreview();
applySelectionToForm();
}
/* ========= Task list + CRUD ========= */
function filterTasksForList(tasks) {
let out = tasks.slice();
const sf = statusFilter.value;
const cf = categoryFilter.value;
const q = (searchInput.value || "").trim().toLowerCase();
if (sf === "done") out = out.filter(t => t.done);
if (sf === "todo") out = out.filter(t => !t.done);
if (cf !== "all") out = out.filter(t => t.category === cf);
if (q) out = out.filter(t => (t.title || "").toLowerCase().includes(q));
out.sort((a, b) => (a.startM - b.startM) || ((a.createdAt || "").localeCompare(b.createdAt || "")));
return out;
}
async function addTaskFromForm(e) {
e.preventDefault();
const title = (taskTitleInput.value || "").trim();
if (!title) {
toast("عنوان رو بده 😅");
taskTitleInput.focus();
return;
}
const cat = taskCategorySelect.value;
const startM = hhmmToMins(taskStartInput.value || "00:00");
const endM = hhmmToMins(taskEndInput.value || "00:00");
const dur = durationMins(startM, endM);
if (dur < 5) {
toast("بازه زمانی باید حداقل ۵ دقیقه باشه.");
return;
}
const now = new Date();
const task = {
id: makeId(),
title,
category: cat,
startM,
endM,
durM: dur,
notes: (taskNotesInput.value || "").trim(),
done: false,
createdAt: now.toISOString(),
doneAt: null,
dayKey: dateKey(state.activeDate),
};
await dbPut(tx(STORE_TASKS, "readwrite"), task);
state.tasks.unshift(task);
taskTitleInput.value = "";
taskNotesInput.value = "";
state.selection.has = false;
renderSelectionPreview();
renderAll();
toast("تسک اضافه شد ✅");
}
async function toggleDone(id) {
const t = state.tasks.find(x => x.id === id);
if (!t) return;
t.done = !t.done;
t.doneAt = t.done ? new Date().toISOString() : null;
await dbPut(tx(STORE_TASKS, "readwrite"), t);
renderAll();
}
async function deleteTask(id) {
await dbDelete(tx(STORE_TASKS, "readwrite"), id);
state.tasks = state.tasks.filter(x => x.id !== id);
if (state.pomodoro.activeTaskId === id) {
state.pomodoro.activeTaskId = null;
await saveSettings();
renderPomodoro();
}
renderAll();
}
function renderTaskList() {
taskList.innerHTML = "";
const visible = getVisibleTasks();
const items = filterTasksForList(visible);
if (items.length === 0) {
const empty = document.createElement("div");
empty.style.color = "rgba(159,176,218,.95)";
empty.style.padding = "8px 4px";
empty.textContent = "اینجا فعلاً خلوته. از دایره درگ کن یا از فرم تسک بساز 👈";
taskList.appendChild(empty);
return;
}
for (const t of items) {
const wrap = document.createElement("div");
wrap.className = "taskItem";
const chk = document.createElement("button");
chk.className = "taskCheck";
chk.type = "button";
chk.title = "انجام شد/نشد";
chk.style.borderColor = t.done ? "rgba(64,245,163,.45)" : "rgba(255,255,255,.10)";
chk.style.background = t.done ? "rgba(64,245,163,.12)" : "rgba(0,0,0,.10)";
chk.textContent = t.done ? "✓" : "";
chk.addEventListener("click", () => toggleDone(t.id));
const mid = document.createElement("div");
const title = document.createElement("div");
title.className = "taskTitle";
title.textContent = t.title;
title.style.opacity = t.done ? ".65" : "1";
title.style.textDecoration = t.done ? "line-through" : "none";
title.addEventListener("dblclick", async () => {
const v = prompt("عنوان جدید:", t.title);
if (v === null) return;
const nv = v.trim();
if (!nv) return;
t.title = nv;
await dbPut(tx(STORE_TASKS, "readwrite"), t);
renderAll();
});
const meta = document.createElement("div");
meta.className = "taskMeta";
const tagCat = document.createElement("span");
tagCat.textContent = `#${CATS[t.category].label}`;
tagCat.style.color = CATS[t.category].color;
const tagTime = document.createElement("span");
tagTime.textContent = `${minsToHHMM(t.startM)} → ${minsToHHMM(t.endM)} (${t.durM}m)`;
const tagDay = document.createElement("span");
tagDay.textContent = `روز: ${t.dayKey}`;
meta.appendChild(tagCat);
meta.appendChild(tagTime);
meta.appendChild(tagDay);
mid.appendChild(title);
mid.appendChild(meta);
const actions = document.createElement("div");
actions.className = "taskActions";
const btnPom = document.createElement("button");
btnPom.type = "button";
btnPom.textContent = "پومودورو";
btnPom.addEventListener("click", async () => {
state.pomodoro.activeTaskId = t.id;
await saveSettings();
renderPomodoro();
toast("تسک پومودورو ست شد 🍅");
});
const btnDel = document.createElement("button");
btnDel.type = "button";
btnDel.textContent = "حذف";
btnDel.style.borderColor = "rgba(255,92,122,.35)";
btnDel.style.background = "rgba(255,92,122,.10)";
btnDel.addEventListener("click", () => deleteTask(t.id));
actions.appendChild(btnPom);
actions.appendChild(btnDel);
wrap.appendChild(chk);
wrap.appendChild(mid);
wrap.appendChild(actions);
taskList.appendChild(wrap);
}
}
function renderStats() {
const visible = getVisibleTasks();
const total = visible.length;
const done = visible.filter(t => t.done).length;
const mins = visible.reduce((a, t) => a + (t.durM || 0), 0);
const pct = total ? Math.round((done / total) * 100) : 0;
progressText.textContent = `${pct}٪ انجامشده`;
statTotal.textContent = total;
statDone.textContent = done;
statPlannedMins.textContent = mins;
}
/* ========= Chart ========= */
function lastNDaysKeys(n = 7) {
const keys = [];
const d = new Date();
for (let i = n - 1; i >= 0; i--) keys.push(dateKey(addDays(d, -i)));
return keys;
}
function renderChart() {
const keys = lastNDaysKeys(7);
const counts = keys.map(k => state.tasks.filter(t => t.done && t.dayKey === k).length);
const cssW = weeklyChart.clientWidth;
const cssH = weeklyChart.clientHeight;
const dpr = window.devicePixelRatio || 1;
weeklyChart.width = Math.floor(cssW * dpr);
weeklyChart.height = Math.floor(cssH * dpr);
chartCtx.setTransform(dpr, 0, 0, dpr, 0, 0);
chartCtx.clearRect(0, 0, cssW, cssH);
const pad = 18;
const w = cssW, h = cssH;
const innerW = w - pad * 2;
const innerH = h - pad * 2;
chartCtx.lineWidth = 1;
chartCtx.strokeStyle = "rgba(255,255,255,0.10)";
for (let i = 0; i < 4; i++) {
const y = pad + innerH * (i / 3);
chartCtx.beginPath();
chartCtx.moveTo(pad, y);
chartCtx.lineTo(w - pad, y);
chartCtx.stroke();
}
const max = Math.max(1, ...counts);
const barW = innerW / counts.length;
const baseY = pad + innerH;
for (let i = 0; i < counts.length; i++) {
const val = counts[i];
const bh = (val / max) * (innerH - 26);
const x = pad + i * barW + barW * 0.18;
const y = baseY - bh;
const bw = barW * 0.64;
chartCtx.fillStyle = "rgba(110,231,255,0.45)";
chartCtx.fillRect(x, y, bw, bh);
chartCtx.fillStyle = "rgba(124,108,255,0.45)";
chartCtx.fillRect(x, y, bw, 4);
chartCtx.fillStyle = "rgba(234,240,255,0.80)";
chartCtx.font = "12px system-ui";
chartCtx.textAlign = "center";
chartCtx.fillText(String(val), x + bw / 2, y - 6);
const lab = keys[i].slice(5).replace("-", "/");
chartCtx.fillStyle = "rgba(159,176,218,0.95)";
chartCtx.font = "11px system-ui";
chartCtx.fillText(lab, x + bw / 2, baseY + 16);
}
chartCtx.fillStyle = "rgba(234,240,255,0.85)";
chartCtx.font = "13px system-ui";
chartCtx.textAlign = "left";
chartCtx.fillText("Done tasks (7 days)", pad, pad - 6);
}
/* ========= Header + view ========= */
function renderHeader() {
const d = state.activeDate;
const wd = d.toLocaleDateString("fa-IR", { weekday: "long" });
const full = d.toLocaleDateString("fa-IR", { year: "numeric", month: "long", day: "numeric" });
activeDateText.textContent = `${wd} • ${full}`;
activeViewText.textContent = state.view === "day" ? "نمای روزانه" : "نمای هفتگی";
}
function setView(v) {
state.view = v;
saveSettings();
renderAll();
}
/* ========= Category ========= */
function setActiveCategory(cat) {
if (!CATS[cat]) return;
state.activeCategory = cat;
taskCategorySelect.value = cat;
activeCategoryText.textContent = `دسته فعال: ${CATS[cat].label}`;
saveSettings();
renderSelectionPreview();
renderRings();
}
/* ========= Export/Import ========= */
async function exportJSON() {
const payload = {
version: 1,
exportedAt: new Date().toISOString(),
tasks: state.tasks,
settings: {
activeCategory: state.activeCategory,
view: state.view,
activeDate: state.activeDate.toISOString(),
pomodoro: {
activeTaskId: state.pomodoro.activeTaskId,
focusMin: state.pomodoro.focusMin,
breakMin: state.pomodoro.breakMin,
}
}
};
const text = JSON.stringify(payload, null, 2);
jsonPreview.value = text;
const blob = new Blob([text], { type: "application/json" });
const a = document.createElement("a");
a.href = URL.createObjectURL(blob);
a.download = `circle-planner-${dateKey(new Date())}.json`;
a.click();
URL.revokeObjectURL(a.href);
}
async function importJSONFromText(text) {
let data;
try { data = JSON.parse(text); }
catch { toast("JSON خراب بود."); return; }
if (!data || !Array.isArray(data.tasks)) {
toast("ساختار JSON معتبر نیست.");
return;
}
const store = tx(STORE_TASKS, "readwrite");