-
Notifications
You must be signed in to change notification settings - Fork 25
Expand file tree
/
Copy pathsettings.js
More file actions
2377 lines (2369 loc) · 106 KB
/
settings.js
File metadata and controls
2377 lines (2369 loc) · 106 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
import { settingsDialog } from '../dom/elements.js';
import { apiFetch } from '../api.js';
import { fetchProjectMembers } from '../members-cache.js';
import { escapeHTML, showToast, getAppVersion, showConfirmDialog, isAnonymousBoard, renderUserAvatar, processImageFile, renderAvatarContent, sanitizeHexColor } from '../utils.js';
import { getStoredTheme, handleThemeChange, THEME_SYSTEM, THEME_DARK, THEME_LIGHT } from '../theme.js';
import { getSlug, getTag, getSearch, getSprintIdFromUrl, getBoard, getProjectId, getProjects, getSettingsProjectId, getSettingsActiveTab, getTagColors, getUser, getAuthStatusAvailable, getBackupImportBtn, getBackupData, getBoardMembers } from '../state/selectors.js';
import { setSettingsProjectId, setSettingsActiveTab, setTagColors, setBoard, setBackupImportBtn, setBackupData, setBackupPreview, setUser, setBoardMembers, } from '../state/mutations.js';
import { renderRealBurndownChart, destroyBurndownChart, mountBurndownChart } from '../charts/burndown.js';
import { invalidateBoard, refreshSprintsAndChips } from '../orchestration/board-refresh.js';
import { emit } from '../events.js';
import { normalizeSprints } from '../sprints.js';
import { recordLocalMutation } from '../realtime/guard.js';
// AbortController for per-render listener cleanup
let settingsAbortController = null;
let settingsProfileRefetchController = null;
let settingsProfileRefetchVersion = 0;
// Only one sprint row in edit mode at a time
let editingSprintId = null;
// Burndown chart sprint navigation: index into sorted sprints list
let burndownSprintIndex = 0;
// Cache for settings modal API calls
let cachedTags = null;
let cachedTagsHTML = null;
let cachedRealBurndownData = null;
let cachedTagsURL = null;
let cachedRealBurndownURL = null;
let cachedSprintsForCharts = null;
// Helper function to invalidate tags cache (call when tags are modified)
export function invalidateTagsCache() {
cachedTags = null;
cachedTagsHTML = null;
cachedTagsURL = null;
}
/** Update all user-avatar elements outside the settings dialog (e.g. topbar) after avatar change. */
function refreshAvatarsOutsideSettings() {
const user = getUser();
const content = renderAvatarContent(user);
document.querySelectorAll('.user-avatar').forEach((el) => {
if (el.closest('#settingsDialog'))
return;
el.innerHTML = content;
});
}
function invalidateSettingsProfileRefetch() {
settingsProfileRefetchVersion++;
settingsProfileRefetchController?.abort();
settingsProfileRefetchController = null;
}
// Helper function to invalidate chart cache (call when todos are modified)
function invalidateChartCache() {
cachedRealBurndownData = null;
cachedRealBurndownURL = null;
}
// Invalidate sprints cache when sprints are created/activated/closed (so Charts tab shows fresh list)
/** Auto-select sprint for Charts: active > last closed > first planned. */
function computeDefaultBurndownSprintIndex(sprints) {
if (sprints.length === 0)
return 0;
const activeIdx = sprints.findIndex((s) => s.state === 'ACTIVE');
if (activeIdx >= 0)
return activeIdx;
const closed = sprints
.map((s, i) => ({ s, i }))
.filter((x) => x.s.state === 'CLOSED');
if (closed.length > 0) {
const lastClosed = closed.reduce((a, b) => a.s.plannedEndAt >= b.s.plannedEndAt ? a : b);
return lastClosed.i;
}
const plannedIdx = sprints.findIndex((s) => s.state === 'PLANNED');
if (plannedIdx >= 0)
return plannedIdx;
return 0;
}
function invalidateSprintsForChartsCache() {
cachedSprintsForCharts = null;
cachedRealBurndownData = null;
cachedRealBurndownURL = null;
}
// Helper function for tag color
function getTagColor(tagName) {
return getTagColors()[tagName] || null;
}
// Render backup tab HTML
function renderBackupTabHTML() {
const isAnonymousMode = !getAuthStatusAvailable();
const replaceDisabled = isAnonymousMode ? 'disabled' : '';
const replaceHidden = isAnonymousMode ? 'style="display: none;"' : '';
return `
<div class="settings-backup-section">
<div class="settings-backup-export">
<div class="settings-section__title">Export Data</div>
<div class="settings-section__description muted">Download all your projects, todos, and tags as a JSON file.</div>
<button class="btn" type="button" id="backupExportBtn">Export Backup</button>
</div>
<div class="settings-backup-import">
<div class="settings-section__title">Import Data</div>
<div class="settings-section__description muted">Restore from a backup file or merge data from another instance.</div>
<input type="file" accept=".json" id="backupFileInput" style="margin-bottom: 16px;">
<div style="margin-bottom: 16px;">
<label style="display: block; margin-bottom: 8px;">
<input type="radio" name="importMode" value="merge" checked>
<span>Merge & update (recommended)</span>
</label>
<label style="display: block; margin-bottom: 8px;" ${replaceHidden}>
<input type="radio" name="importMode" value="replace" ${replaceDisabled}>
<span>Replace all data</span>
</label>
<label style="display: block; margin-bottom: 8px;">
<input type="radio" name="importMode" value="copy">
<span>Create a copy</span>
</label>
</div>
<div id="backupPreview" class="settings-backup-preview" style="display: none; margin-bottom: 16px; padding: 12px; background: var(--panel); border-radius: 4px;"></div>
<div id="backupConfirmation" style="display: none; margin-bottom: 16px;">
<input type="text" id="backupConfirmationInput" placeholder="Type REPLACE to confirm" class="settings-backup-confirmation" style="width: 100%; padding: 8px;">
</div>
<div id="backupWarnings" class="settings-backup-warnings" style="display: none; margin-bottom: 16px; padding: 12px; background: var(--panel); border-radius: 4px; color: var(--muted);"></div>
<button class="btn" type="button" id="backupImportBtn" disabled>Import</button>
</div>
</div>
`;
}
// Backup handlers
async function handleBackupExport() {
try {
const response = await fetch("/api/backup/export", {
headers: {
"X-Scrumboy": "1"
}
});
if (!response.ok) {
const err = await response.json();
showToast(err.error?.message || "Export failed");
return;
}
const blob = await response.blob();
const url = window.URL.createObjectURL(blob);
const a = document.createElement("a");
a.href = url;
// Format: scrumboy-backup-2026-01-24-03-45-PM.json
const now = new Date();
const dateStr = now.toISOString().split('T')[0];
const hours = now.getHours();
const minutes = now.getMinutes().toString().padStart(2, '0');
const ampm = hours >= 12 ? 'PM' : 'AM';
const hours12 = (hours % 12 || 12).toString().padStart(2, '0');
a.download = `scrumboy-backup-${dateStr}-${hours12}-${minutes}-${ampm}.json`;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
window.URL.revokeObjectURL(url);
showToast("Backup exported successfully");
}
catch (err) {
showToast(err.message || "Export failed");
}
}
async function handleBackupFileSelect(e) {
const target = e.target;
const file = target.files?.[0];
if (!file) {
return;
}
try {
const text = await file.text();
const data = JSON.parse(text);
// Validate structure
if (!data.version || !data.projects || !Array.isArray(data.projects)) {
showToast("Invalid backup file format");
return;
}
// Store the data for import
setBackupData(data);
// Get selected import mode
const importMode = document.querySelector('input[name="importMode"]:checked')?.value || "merge";
// Call preview endpoint
const preview = await apiFetch("/api/backup/preview", {
method: "POST",
body: JSON.stringify({
data: data,
importMode: importMode
})
});
// Display preview
const previewEl = document.getElementById("backupPreview");
if (previewEl) {
let previewHTML = `<strong>Preview:</strong><br>`;
previewHTML += `Projects: ${preview.projects}<br>`;
previewHTML += `Todos: ${preview.todos}<br>`;
previewHTML += `Tags: ${preview.tags}<br>`;
if (preview.links !== undefined && preview.links > 0) {
previewHTML += `Links: ${preview.links}<br>`;
}
if (preview.willDelete !== undefined) {
previewHTML += `Will delete: ${preview.willDelete} projects<br>`;
}
if (preview.willUpdate !== undefined) {
previewHTML += `Will update: ${preview.willUpdate} items<br>`;
}
if (preview.willCreate !== undefined) {
previewHTML += `Will create: ${preview.willCreate} items<br>`;
}
previewEl.innerHTML = previewHTML;
previewEl.style.display = "block";
}
// Display warnings if any
if (preview.warnings && preview.warnings.length > 0) {
const warningsEl = document.getElementById("backupWarnings");
if (warningsEl) {
warningsEl.innerHTML = `<strong>Warnings:</strong><br>${preview.warnings.map((w) => escapeHTML(w)).join("<br>")}`;
warningsEl.style.display = "block";
}
}
setBackupPreview(preview);
updateBackupUI();
}
catch (err) {
showToast(err.message || "Failed to read backup file");
setBackupData(null);
setBackupPreview(null);
updateBackupUI();
}
}
function updateBackupUI() {
// Use stored reference if available, otherwise find by ID
const importBtn = (getBackupImportBtn() || document.getElementById("backupImportBtn"));
const confirmationDiv = document.getElementById("backupConfirmation");
const confirmationInput = document.getElementById("backupConfirmationInput");
const importMode = document.querySelector('input[name="importMode"]:checked')?.value || "merge";
if (!getBackupData()) {
if (importBtn) {
importBtn.disabled = true;
}
if (confirmationDiv) {
confirmationDiv.style.display = "none";
}
return;
}
// Show confirmation input for replace mode
if (importMode === "replace") {
if (confirmationDiv) {
confirmationDiv.style.display = "block";
}
const isValid = confirmationInput && confirmationInput.value.trim() === "REPLACE";
if (importBtn) {
importBtn.disabled = !isValid;
// Force update the disabled state
if (isValid) {
importBtn.removeAttribute("disabled");
}
else {
importBtn.setAttribute("disabled", "disabled");
}
}
}
else {
if (confirmationDiv) {
confirmationDiv.style.display = "none";
}
if (importBtn) {
importBtn.disabled = false;
importBtn.removeAttribute("disabled");
}
}
}
async function handleBackupImport() {
console.log("handleBackupImport: Function called");
if (!getBackupData()) {
console.log("handleBackupImport: No backup data");
showToast("No backup file selected");
return;
}
// Use stored reference if available, otherwise find by ID
const importBtn = (getBackupImportBtn() || document.getElementById("backupImportBtn"));
console.log("handleBackupImport: Button found", {
hasButton: !!importBtn,
isDisabled: importBtn?.disabled,
buttonText: importBtn?.textContent
});
if (importBtn && importBtn.disabled) {
console.log("handleBackupImport: Button is disabled, returning");
showToast("Please complete the confirmation to enable import");
return;
}
const importMode = document.querySelector('input[name="importMode"]:checked')?.value || "merge";
const confirmationInput = document.getElementById("backupConfirmationInput");
console.log("handleBackupImport: Mode and confirmation", {
importMode,
confirmationValue: confirmationInput?.value,
confirmationTrimmed: confirmationInput?.value?.trim()
});
// Validate confirmation for replace mode
if (importMode === "replace") {
if (!confirmationInput || confirmationInput.value.trim() !== "REPLACE") {
console.log("handleBackupImport: Invalid confirmation");
showToast("Please type REPLACE in the confirmation field");
return;
}
}
try {
console.log("handleBackupImport: Starting", { importMode, hasData: !!getBackupData() });
const body = {
data: getBackupData(),
importMode: importMode
};
if (importMode === "replace") {
body.confirmation = confirmationInput.value.trim();
}
// In anonymous mode, import into current board (if viewing one)
const currentSlug = getSlug();
if (currentSlug) {
body.targetSlug = currentSlug;
}
console.log("handleBackupImport: Request body prepared", {
importMode: body.importMode,
targetSlug: body.targetSlug,
hasData: !!body.data,
hasConfirmation: !!body.confirmation,
projectsCount: body.data?.projects?.length
});
// Show loading state
if (importBtn) {
importBtn.disabled = true;
importBtn.setAttribute("disabled", "disabled");
const originalText = importBtn.textContent;
importBtn.textContent = "Importing...";
}
console.log("handleBackupImport: Calling API...");
const result = await apiFetch("/api/backup/import", {
method: "POST",
body: JSON.stringify(body)
});
console.log("handleBackupImport: API call completed", result);
// Show results
let message = `Import completed: `;
if (result.imported !== undefined)
message += `${result.imported} projects imported, `;
if (result.updated !== undefined)
message += `${result.updated} updated, `;
if (result.created !== undefined)
message += `${result.created} created`;
showToast(message);
// Show warnings if any
if (result.warnings && result.warnings.length > 0) {
const warningsEl = document.getElementById("backupWarnings");
if (warningsEl) {
warningsEl.innerHTML = `<strong>Warnings:</strong><br>${result.warnings.map((w) => escapeHTML(w)).join("<br>")}`;
warningsEl.style.display = "block";
}
}
// Reload the page to show updated data
setTimeout(() => {
window.location.reload();
}, 1500);
}
catch (err) {
console.error("handleBackupImport: ERROR CAUGHT", err);
console.error("handleBackupImport: Error details", {
message: err.message,
status: err.status,
data: err.data,
stack: err.stack
});
const errorMsg = err.message || err.data?.error?.message || "Import failed";
console.error("handleBackupImport: Showing toast with message:", errorMsg);
showToast(errorMsg);
// Re-enable button on error - use stored reference if available
const importBtn = (getBackupImportBtn() || document.getElementById("backupImportBtn"));
if (importBtn) {
importBtn.disabled = false;
importBtn.removeAttribute("disabled");
importBtn.textContent = "Import";
console.log("handleBackupImport: Button restored");
}
else {
console.error("handleBackupImport: Could not find button to restore");
}
}
}
async function setupBackupTab(signal) {
// Export button
const exportBtn = document.getElementById("backupExportBtn");
if (exportBtn) {
exportBtn.addEventListener("click", handleBackupExport, signal ? { signal } : undefined);
}
// File input
const fileInput = document.getElementById("backupFileInput");
if (fileInput) {
fileInput.addEventListener("change", handleBackupFileSelect, signal ? { signal } : undefined);
}
// Import mode radio buttons
document.querySelectorAll('input[name="importMode"]').forEach(radio => {
radio.addEventListener("change", () => {
// Clear confirmation input when switching modes
const confirmationInput = document.getElementById("backupConfirmationInput");
if (confirmationInput) {
confirmationInput.value = "";
}
// Update UI when mode changes
setTimeout(() => updateBackupUI(), 0);
}, signal ? { signal } : undefined);
});
// Confirmation input
const confirmationInput = document.getElementById("backupConfirmationInput");
if (confirmationInput) {
confirmationInput.addEventListener("input", () => {
// Update UI immediately when typing
updateBackupUI();
}, signal ? { signal } : undefined);
// Also trigger on paste
confirmationInput.addEventListener("paste", () => {
setTimeout(() => updateBackupUI(), 0);
}, signal ? { signal } : undefined);
// Trigger on keyup as well to catch all changes
confirmationInput.addEventListener("keyup", () => {
updateBackupUI();
}, signal ? { signal } : undefined);
}
// Import button
const importBtn = document.getElementById("backupImportBtn");
if (importBtn) {
importBtn.addEventListener("click", handleBackupImport, signal ? { signal } : undefined);
setBackupImportBtn(importBtn);
}
// Call updateBackupUI to set initial state after a brief delay to ensure DOM is ready
setTimeout(() => {
updateBackupUI();
}, 0);
}
// updateTagColor and deleteTag call view functions, so they need to import from app.js
// For durable projects: tag_id required (same authority rule as delete). For anonymous boards only: name-based allowed.
async function updateTagColor(tagName, tagId, color) {
const projectId = getSettingsProjectId();
const slug = getSlug();
const isDurable = !!projectId;
// Durable project: require tagId; never use name-based mutation.
if (isDurable) {
if (tagId == null || tagId <= 0) {
showToast("Cannot update color: tag ID missing");
return;
}
const url = `/api/projects/${projectId}/tags/id/${tagId}/color`;
try {
recordLocalMutation();
await apiFetch(url, {
method: "PATCH",
body: JSON.stringify({ color }),
});
await applyTagColorSuccess(tagName, color, url);
}
catch (err) {
showToast(err.message);
}
return;
}
// Board (slug): prefer tag_id; fall back to name only for anonymous boards.
if (slug) {
let url;
if (tagId != null && tagId > 0) {
url = `/api/board/${slug}/tags/id/${tagId}/color`;
}
else {
url = `/api/board/${slug}/tags/${encodeURIComponent(tagName)}/color`;
}
try {
recordLocalMutation();
await apiFetch(url, {
method: "PATCH",
body: JSON.stringify({ color }),
});
await applyTagColorSuccess(tagName, color, url);
}
catch (err) {
showToast(err.message);
}
return;
}
showToast("No project available");
}
async function applyTagColorSuccess(tagName, color, _url) {
try {
// Update local state
const tagColors = { ...getTagColors() };
if (color) {
tagColors[tagName] = color;
}
else {
delete tagColors[tagName];
}
setTagColors(tagColors);
// Save tag colors to backend (user preference)
if (getUser()) {
try {
await apiFetch("/api/user/preferences", {
method: "PUT",
body: JSON.stringify({ key: "tagColors", value: JSON.stringify(tagColors) }),
});
}
catch (err) {
// Ignore errors saving preferences
}
}
// Update clear button visibility
const clearBtn = document.querySelector(`.settings-color-clear[data-tag="${escapeHTML(tagName)}"]`);
if (clearBtn) {
clearBtn.style.display = color ? "" : "none";
}
invalidateTagsCache();
// Refresh board to apply colors
if (getSlug()) {
await invalidateBoard(getSlug(), getTag(), getSearch(), getSprintIdFromUrl());
}
showToast("Tag color updated");
}
catch (err) {
showToast(err.message);
}
}
async function deleteTag(tagName, tagId) {
// Authority by tag_id only. For durable projects, tagId is required; no fallback to name.
let url = null;
const isDurableMode = !!getSettingsProjectId(); // Projects handler is durable-only
if (getSlug()) {
// Board view: prefer tag_id; fall back to name only for anonymous boards
url = tagId != null ? `/api/board/${getSlug()}/tags/id/${tagId}` : `/api/board/${getSlug()}/tags/${encodeURIComponent(tagName)}`;
}
else if (isDurableMode) {
// Durable projects: tagId required; no fallback to name
if (tagId == null) {
showToast("Cannot delete: tag ID missing");
return;
}
url = `/api/projects/${getSettingsProjectId()}/tags/id/${tagId}`;
}
else {
showToast("No project available");
return;
}
try {
recordLocalMutation();
await apiFetch(url, {
method: "DELETE",
});
const tagColors = { ...getTagColors() };
delete tagColors[tagName];
setTagColors(tagColors);
if (getUser()) {
try {
await apiFetch("/api/user/preferences", {
method: "PUT",
body: JSON.stringify({ key: "tagColors", value: JSON.stringify(tagColors) }),
});
}
catch (err) {
// Ignore errors saving preferences
}
}
invalidateTagsCache();
await renderSettingsModal();
if (getSlug()) {
await invalidateBoard(getSlug(), getTag(), getSearch(), getSprintIdFromUrl());
}
showToast(`Tag "${tagName}" deleted`);
}
catch (err) {
showToast(err.message);
}
}
function msToDateTimeLocalStr(ms) {
const d = new Date(ms);
const y = d.getFullYear();
const m = String(d.getMonth() + 1).padStart(2, "0");
const day = String(d.getDate()).padStart(2, "0");
const hh = String(d.getHours()).padStart(2, "0");
const mm = String(d.getMinutes()).padStart(2, "0");
return `${y}-${m}-${day}T${hh}:${mm}`;
}
const DEFAULT_WORKFLOW_LANE_COLOR = "#64748b";
function normalizeWorkflowLaneColorForInput(color) {
const s = color?.trim();
return s && /^#[0-9a-fA-F]{6}$/.test(s) ? s : DEFAULT_WORKFLOW_LANE_COLOR;
}
function renderWorkflowTabContent() {
const board = getBoard();
const workflow = board?.columnOrder ?? [];
const canDeleteAnyLane = workflow.length > 2;
if (!getSlug()) {
return `<div class="settings-section"><div class="muted">No project in context.</div></div>`;
}
if (workflow.length === 0) {
return `<div class="settings-section"><div class="muted">Workflow lanes are unavailable.</div></div>`;
}
return `
<div class="settings-section">
<div class="settings-section__title">Workflow</div>
<div class="settings-section__description muted">Rename lane labels and colors, or add a non-done lane inserted immediately before the done lane (whatever its label). Keys stay immutable.</div>
<div class="settings-workflow-create" style="display:flex; gap:12px; align-items:flex-end; margin-bottom:16px;">
<label class="field" style="flex:1; min-width:0; margin:0;">
<div class="field__label">New lane name</div>
<input
class="input"
data-workflow-new-name
maxlength="200"
placeholder="e.g. Review"
aria-label="New workflow lane name"
/>
</label>
<button class="btn btn--small" type="button" data-workflow-add>Add Lane</button>
</div>
<div class="settings-workflow-list">
${workflow.map((lane) => `
<div class="settings-workflow-row" data-workflow-key="${escapeHTML(lane.key)}" style="display:flex; gap:12px; align-items:center; margin-bottom:12px;">
<div class="muted" style="min-width:110px; font-family:monospace;">${escapeHTML(lane.key)}</div>
<input
class="input"
data-workflow-name="${escapeHTML(lane.key)}"
value="${escapeHTML(lane.name)}"
maxlength="200"
aria-label="Lane label for ${escapeHTML(lane.key)}"
style="flex:1; min-width:0;"
/>
<input
type="color"
class="settings-color-picker"
data-workflow-color="${escapeHTML(lane.key)}"
value="${escapeHTML(normalizeWorkflowLaneColorForInput(lane.color))}"
aria-label="Lane color for ${escapeHTML(lane.key)}"
title="Lane color"
/>
<button class="btn btn--ghost btn--small" type="button" data-workflow-save="${escapeHTML(lane.key)}">Save</button>
${lane.isDone ? `<button class="btn btn--ghost btn--small" type="button" disabled aria-disabled="true" title="Done lane cannot be deleted">Delete</button>` : `<button class="btn btn--danger btn--small" type="button" data-workflow-delete="${escapeHTML(lane.key)}" ${canDeleteAnyLane ? "" : `disabled aria-disabled="true" title="Workflow must keep at least 2 lanes"`}>Delete</button>`}
</div>
`).join("")}
</div>
</div>
`;
}
async function addWorkflowLane(name) {
const slug = getSlug();
if (!slug) {
showToast("No project available");
return;
}
const trimmed = name.trim();
if (!trimmed) {
showToast("Lane name is required");
return;
}
try {
recordLocalMutation();
await apiFetch(`/api/board/${slug}/workflow`, {
method: "POST",
body: JSON.stringify({ name: trimmed }),
});
await invalidateBoard(slug, getTag(), getSearch(), getSprintIdFromUrl());
await renderSettingsModal();
showToast("Lane added");
}
catch (err) {
showToast(err.message || "Failed to add lane");
}
}
async function updateWorkflowLane(key, payload) {
const slug = getSlug();
if (!slug) {
showToast("No project available");
return;
}
const trimmed = payload.name.trim();
if (!trimmed) {
showToast("Lane name is required");
return;
}
const color = payload.color.trim();
const lane = getBoard()?.columnOrder?.find((l) => l.key === key);
const prevColor = (lane?.color ?? DEFAULT_WORKFLOW_LANE_COLOR).toLowerCase();
if (trimmed === lane?.name?.trim() && color.toLowerCase() === prevColor) {
return;
}
try {
recordLocalMutation();
await apiFetch(`/api/board/${slug}/workflow/${encodeURIComponent(key)}`, {
method: "PATCH",
body: JSON.stringify({ name: trimmed, color }),
});
await invalidateBoard(slug, getTag(), getSearch(), getSprintIdFromUrl());
await renderSettingsModal();
showToast("Lane updated");
}
catch (err) {
showToast(err.message || "Failed to update lane");
}
}
async function deleteWorkflowLane(key) {
const slug = getSlug();
if (!slug) {
showToast("No project available");
return;
}
const lane = getBoard()?.columnOrder?.find((item) => item.key === key);
if (!lane) {
showToast("Lane not found");
return;
}
if (lane.isDone) {
showToast("Done lane cannot be deleted");
return;
}
const confirmed = await showConfirmDialog(`Delete lane "${lane.name}"? Only empty non-done lanes can be deleted.`, "Delete lane?", "Delete");
if (!confirmed)
return;
try {
recordLocalMutation();
await apiFetch(`/api/board/${slug}/workflow/${encodeURIComponent(key)}`, {
method: "DELETE",
});
await invalidateBoard(slug, getTag(), getSearch(), getSprintIdFromUrl());
await renderSettingsModal();
showToast("Lane deleted");
}
catch (err) {
showToast(err.message || "Failed to delete lane");
}
}
function computeDefaultSprintStart(now) {
const daysToMonday = (now.getDay() + 6) % 7; // 0=Sun, 1=Mon, ..., 6=Sat
const monday = new Date(now.getTime());
monday.setDate(monday.getDate() - daysToMonday);
monday.setHours(9, 0, 0, 0);
return monday;
}
function computeDefaultSprintEnd(start, weeks) {
const normalizedWeeks = weeks === 1 || weeks === 2 ? weeks : 2;
const end = new Date(start.getTime());
end.setDate(end.getDate() + (normalizedWeeks * 7 - 1));
end.setHours(23, 59, 0, 0);
return end;
}
// Main render function
async function renderSprintsTabContent() {
const slug = getSlug();
if (!slug)
return "<div class='muted'>No project in context.</div>";
try {
const res = await apiFetch(`/api/board/${slug}/sprints`);
const sprints = normalizeSprints(res);
const formatDate = (ms) => new Date(ms).toLocaleString(undefined, {
month: "short",
day: "numeric",
year: "numeric",
hour: "numeric",
minute: "2-digit",
});
const listHTML = sprints.length === 0
? "<div class='muted'>No sprints yet. Create one below.</div>"
: sprints.map((sp) => {
const isEditing = editingSprintId === sp.id;
const dateRange = `${formatDate(sp.plannedStartAt)} – ${formatDate(sp.plannedEndAt)}`;
const stateBadge = `<span class="status-pill status-pill--${sp.state.toLowerCase()}">${sp.state}</span>`;
const activateBtn = sp.state === "PLANNED" ? `<button class="btn btn--ghost btn--sm" data-sprint-activate="${sp.id}">Activate</button>` : "";
const closeBtn = sp.state === "ACTIVE" ? `<button class="btn btn--ghost btn--sm" data-sprint-close="${sp.id}">Close</button>` : (sp.state === "CLOSED" ? `<button type="button" class="btn btn--ghost btn--sm settings-sprint-row__action-placeholder" aria-hidden="true" tabindex="-1">Close</button>` : "");
const editBtn = `<button class="btn btn--ghost btn--sm" data-sprint-edit="${sp.id}">Edit</button>`;
const deleteBtn = `<button class="btn btn--danger btn--sm" data-sprint-delete="${sp.id}">Delete</button>`;
if (isEditing) {
const editingClass = " settings-sprint-row--editing";
const todoCount = sp.todoCount ?? 0;
const nameInput = (sp.state === "PLANNED" || sp.state === "CLOSED") ? `<input class="input" data-sprint-edit-name value="${escapeHTML(sp.name)}" style="min-width: 120px;" />` : `<strong>${escapeHTML(sp.name)}</strong>`;
const startDisplay = `<span class="muted">${formatDate(sp.plannedStartAt)}</span>`;
const startInput = sp.state === "PLANNED" ? `<input class="input" type="datetime-local" data-sprint-edit-start value="${msToDateTimeLocalStr(sp.plannedStartAt)}" style="min-width: 180px;" />` : startDisplay;
const endDisplay = `<span class="muted">${formatDate(sp.plannedEndAt)}</span>`;
const endInput = (sp.state === "PLANNED" || sp.state === "ACTIVE") ? `<input class="input" type="datetime-local" data-sprint-edit-end value="${msToDateTimeLocalStr(sp.plannedEndAt)}" style="min-width: 180px;" />` : endDisplay;
const endBlock = sp.state === "ACTIVE"
? `<div class="settings-sprint-edit-end-block" style="display: inline-flex; align-items: center; gap: 6px;"><div class="field__label" style="margin-bottom: 0;">End</div>${endInput}</div>`
: endInput;
const saveCancelBlock = `<div class="settings-sprint-edit-save-cancel" style="display: inline-flex; align-items: center; gap: 8px;"><button class="btn btn--sm" data-sprint-save="${sp.id}">Save</button><button class="btn btn--ghost btn--sm" data-sprint-cancel="${sp.id}">Cancel</button></div>`;
return `
<div class="settings-sprint-row${editingClass}" data-sprint-id="${sp.id}" data-sprint-state="${sp.state}" data-sprint-todo-count="${todoCount}" data-sprint-planned-start-at="${sp.plannedStartAt}" data-sprint-name="${escapeHTML(sp.name)}">
<div class="settings-sprint-row__info" style="display: flex; align-items: center; gap: 8px; flex-wrap: wrap; flex: 1;">
${nameInput}
${startInput}
${endBlock}
${saveCancelBlock}
</div>
<div class="settings-sprint-row__actions" style="display: flex; align-items: center; gap: 8px;">
${stateBadge}
</div>
</div>`;
}
const todoCount = sp.todoCount ?? 0;
return `
<div class="settings-sprint-row" data-sprint-id="${sp.id}" data-sprint-state="${sp.state}" data-sprint-todo-count="${todoCount}" data-sprint-planned-start-at="${sp.plannedStartAt}" data-sprint-name="${escapeHTML(sp.name)}">
<div class="settings-sprint-row__info">
<strong>${escapeHTML(sp.name)}</strong>
<span class="muted" style="margin-left: 8px;">${escapeHTML(dateRange)}</span>
</div>
<div class="settings-sprint-row__actions" style="display: flex; align-items: center; gap: 8px;">
${stateBadge}
${activateBtn}
${closeBtn}
${editBtn}
${deleteBtn}
</div>
</div>`;
}).join("");
const defaultWeeks = getBoard()?.project?.defaultSprintWeeks === 1 ? 1 : 2;
const now = new Date();
const defaultStart = computeDefaultSprintStart(now);
const defaultEnd = computeDefaultSprintEnd(defaultStart, defaultWeeks);
const defaultStartStr = msToDateTimeLocalStr(defaultStart.getTime());
const defaultEndStr = msToDateTimeLocalStr(defaultEnd.getTime());
return `
<div class="settings-section">
<div class="settings-section__title">Create Sprint</div>
<div class="settings-section__description muted">
Default duration is
<select id="sprintDefaultWeeksSelect" class="input" style="display: inline-block; width: auto; min-width: 64px; margin: 0 4px;">
<option value="1" ${defaultWeeks === 1 ? "selected" : ""}>1</option>
<option value="2" ${defaultWeeks === 2 ? "selected" : ""}>2</option>
</select>
weeks. You can customize start and end dates.
</div>
<div class="settings-create-sprint-form" style="display: flex; flex-wrap: wrap; gap: 12px; align-items: flex-end;">
<label class="field settings-create-sprint-form__name" style="flex: 1; min-width: 120px;">
<div class="field__label">Name</div>
<input class="input" id="sprintNameInput" placeholder="e.g. Sprint 1 or 2026 Q1 Sprint 1" />
</label>
<div class="settings-create-sprint-form__dates" style="display: flex; gap: 12px; align-items: flex-end;">
<label class="field" style="min-width: 140px;">
<div class="field__label">Start</div>
<input class="input" type="datetime-local" id="sprintStartInput" value="${defaultStartStr}" />
</label>
<label class="field" style="min-width: 140px;">
<div class="field__label">End</div>
<input class="input" type="datetime-local" id="sprintEndInput" value="${defaultEndStr}" />
</label>
</div>
<div class="settings-create-sprint-form__submit">
<button class="btn" id="createSprintBtn">Create Sprint</button>
</div>
</div>
<div class="settings-section__title" style="margin-top: 24px;">Sprints</div>
<div class="settings-section__description muted">Create and manage sprints for this project. Only one sprint can be active at a time.</div>
<div class="settings-sprints-list" style="margin-bottom: 24px;">
${listHTML}
</div>
</div>`;
}
catch (err) {
return `<div class='muted'>Error loading sprints: ${escapeHTML(err.message)}</div>`;
}
}
export async function renderSettingsModal(options) {
const contentEl = document.querySelector("#settingsDialog .dialog__content");
if (!contentEl) {
console.error("Settings dialog content element not found");
return;
}
// Full mode only: show Profile tab (auth status endpoint exists only in full mode).
const showProfileTab = !!getAuthStatusAvailable();
// Show Users tab only if user has admin or owner role
const currentUser = getUser();
const showUsersTab = showProfileTab && (currentUser?.systemRole === "owner" || currentUser?.systemRole === "admin");
// In board view we have a slug and can use capability routes.
// In projects listing view (full mode), show all tags from all projects the user has access to.
let tagsURL = null;
let realBurndownURL = null;
let hasProjectAccess = false;
if (getSlug()) {
// Board view: show tags from this specific board
tagsURL = `/api/board/${getSlug()}/tags`;
realBurndownURL = `/api/board/${getSlug()}/burndown`;
setSettingsProjectId(null);
hasProjectAccess = true;
}
else {
// Projects listing view: show all tags from all projects the user has access to
if (getUser()) {
tagsURL = `/api/tags/mine`;
hasProjectAccess = true;
}
// For charts, still need a project ID (use first available project)
let projectId = getProjectId() || getSettingsProjectId();
if (!projectId && Array.isArray(getProjects()) && getProjects().length > 0) {
// Prefer a durable project if available; otherwise fall back to any project.
const durable = getProjects().find((p) => !p.expiresAt);
projectId = (durable || getProjects()[0]).id;
}
if (projectId) {
setSettingsProjectId(projectId);
realBurndownURL = `/api/projects/${projectId}/burndown`;
}
}
// Show Sprints tab only when in board view and user is Maintainer+ for that project
let boardMembers = getBoardMembers();
// If in board view but members not yet loaded (e.g. race on open, or opened before fetch completed), fetch them
const slug = getSlug();
const projectId = getProjectId();
if (slug && projectId && currentUser && boardMembers.length === 0 && getBoard() && !isAnonymousBoard(getBoard())) {
try {
boardMembers = await fetchProjectMembers(projectId);
setBoardMembers(boardMembers);
}
catch {
boardMembers = [];
}
}
const myMember = currentUser ? boardMembers.find((m) => m.userId === currentUser.id) : null;
const showSprintsTab = !!slug && hasProjectAccess && myMember?.role === "maintainer";
const showWorkflowTab = !!slug && hasProjectAccess && myMember?.role === "maintainer";
// Charts tab only applies in durable project board view (not Dashboard/Projects/Temporary Boards, not anonymous mode, not temporary boards)
const board = getBoard();
const isTemporaryBoard = !!(board?.project?.expiresAt);
const showChartsTab = !!slug &&
hasProjectAccess &&
getAuthStatusAvailable() &&
!isTemporaryBoard;
// Initialize active tab (default to Profile or Customization if no projects)
if (!getSettingsActiveTab()) {
if (showProfileTab) {
setSettingsActiveTab("profile");
}
else if (hasProjectAccess) {
setSettingsActiveTab("tag-colors");
}
else {
setSettingsActiveTab("customization");
}
}
else if (!showProfileTab && getSettingsActiveTab() === "profile") {
setSettingsActiveTab(hasProjectAccess ? "tag-colors" : "customization");
}
else if (!showChartsTab && getSettingsActiveTab() === "charts") {
setSettingsActiveTab(hasProjectAccess ? "tag-colors" : "customization");
}
else if (!showWorkflowTab && getSettingsActiveTab() === "workflow") {
setSettingsActiveTab(hasProjectAccess ? "tag-colors" : "customization");
}
// Fetch full user profile (including avatar) when Profile tab is shown (skip when re-rendering after avatar change)
if (showProfileTab && getUser() && !options?.skipProfileRefetch) {
const profileRefetchVersion = ++settingsProfileRefetchVersion;
settingsProfileRefetchController?.abort();
settingsProfileRefetchController = new AbortController();
try {
const me = await apiFetch("/api/me", { signal: settingsProfileRefetchController.signal });
if (me && profileRefetchVersion === settingsProfileRefetchVersion) {
setUser(me);
}
}
catch {
// Ignore - user may have logged out, or this refetch was invalidated by a newer render/avatar mutation.
}
finally {
if (profileRefetchVersion === settingsProfileRefetchVersion) {
settingsProfileRefetchController = null;
}
}
}
// Fetch tags and chart data only if we have project access
let tags = [];
let tagsHTML = "";
let realBurndownData = [];
// Check if URLs changed (invalidate cache)
const tagsURLChanged = cachedTagsURL !== tagsURL;
const realBurndownURLChanged = cachedRealBurndownURL !== realBurndownURL;
if (hasProjectAccess) {
try {
// Fetch tags only if URL changed or cache is empty
if (tagsURLChanged || cachedTags === null) {
tags = await apiFetch(tagsURL);
// Sort tags alphabetically by name
tags.sort((a, b) => a.name.localeCompare(b.name));
// Update tag colors map
const tagColors = {};
tags.forEach((tag) => {
if (tag.color) {
tagColors[tag.name] = tag.color;
}
});
setTagColors(tagColors);
const isDurableProject = !!getSettingsProjectId();
tagsHTML = tags.length === 0
? "<div class='muted'>No tags yet. Create todos with tags to see them here.</div>"
: tags.map((tag) => {
const colorValue = sanitizeHexColor(tag.color, "#9CA3AF") || "#9CA3AF";
// Show delete only when: canDelete === true AND tagId != null (both required)
const showDelete = tag.canDelete === true && tag.tagId != null;
// Durable project: require tagId for color update; disable picker if missing
const hasTagId = tag.tagId != null && tag.tagId > 0;
const colorDisabled = isDurableProject && !hasTagId;
const tagIdAttr = hasTagId ? ` data-tag-id="${String(tag.tagId)}"` : "";
return `
<div class="settings-tag-item">
<span class="settings-tag-name" title="${escapeHTML(tag.name)}">${escapeHTML(tag.name)}</span>
<div class="settings-tag-color-controls">
<input
type="color"
class="settings-color-picker"
data-tag="${escapeHTML(tag.name)}"${tagIdAttr}
value="${colorValue}"
title="${colorDisabled ? "Tag ID missing — cannot update color" : "Tag color"}"