-
Notifications
You must be signed in to change notification settings - Fork 25
Expand file tree
/
Copy pathtodo.js
More file actions
1032 lines (1032 loc) · 41.8 KB
/
todo.js
File metadata and controls
1032 lines (1032 loc) · 41.8 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 { todoDialog, todoDialogTitle, todoTitle, todoBody, todoTags, addTagBtn, todoStatus, todoEstimationField, todoEstimationPoints, deleteTodoBtn, shareTodoBtn, closeTodoBtn } from '../dom/elements.js';
import { apiFetch } from '../api.js';
import { getSlug, getTagColors, getAvailableTags, getAvailableTagsMap, getAutocompleteSuggestion, getUser, getBoard, getBoardMembers, getEditingTodo } from '../state/selectors.js';
import { setEditingTodo, setAvailableTags, setAvailableTagsMap, setTagColors, setAutocompleteSuggestion } from '../state/mutations.js';
import { escapeHTML, isAnonymousBoard, showToast, sanitizeHexColor } from '../utils.js';
import { normalizeSprints } from '../sprints.js';
import { recordLocalMutation } from '../realtime/guard.js';
// Symbol for idempotent listener attachment
const BOUND_FLAG = Symbol('bound');
// Module-level state for tag autocomplete
let tagInputHandlersSetup = false;
let permissions = {
canChangeSprint: false,
canChangeEstimation: false,
canEditTags: false,
canEditNotes: false,
canEditAssignment: false,
canDeleteTodo: false,
};
let linksSearchDebounce = null;
let linksSearchController = null;
let lastLoadedLinksForTodo = null;
let dialogLinkLifecycleBound = false;
let currentLinks = { outbound: [], inbound: [] };
let linkAutocompleteSuggestion = null;
function resolveColumnKey(raw) {
const v = (raw || "").trim();
if (!v)
return "";
const upper = v.toUpperCase();
switch (upper) {
case "BACKLOG": return "backlog";
case "NOT_STARTED": return "not_started";
case "IN_PROGRESS": return "doing";
case "TESTING": return "testing";
case "DONE": return "done";
default: return v.toLowerCase();
}
}
function populateTodoStatusOptions(preferredKey) {
const select = todoStatus;
const board = getBoard();
const order = board?.columnOrder;
if (!order || order.length === 0) {
return preferredKey || "backlog";
}
select.innerHTML = order.map((c) => `<option value="${escapeHTML(c.key)}">${escapeHTML(c.name)}</option>`).join("");
const hasPreferred = order.some((c) => c.key === preferredKey);
const selected = hasPreferred ? preferredKey : order[0].key;
select.value = selected;
return selected;
}
// Helper functions
function getTagColor(tagName) {
return getTagColors()[tagName] || null;
}
function isModifiedFibonacciMode() {
const mode = getBoard()?.project?.estimationMode;
return mode == null || mode === "MODIFIED_FIBONACCI";
}
function getTagInput() {
return document.getElementById("todoTags");
}
export function getTagsFromChips() {
const chipsContainer = document.getElementById("tagsChips");
if (!chipsContainer)
return [];
return Array.from(chipsContainer.querySelectorAll(".tag-chip")).map(chip => chip.getAttribute("data-tag") || "");
}
function normalizeTagName(tagName) {
// Check if there's an existing tag with the same name (case-insensitive)
const lowerTag = tagName.toLowerCase();
if (getAvailableTagsMap()[lowerTag]) {
return getAvailableTagsMap()[lowerTag];
}
// Also check currently added tags in the chips (case-insensitive)
const currentTags = getTagsFromChips();
const existingTag = currentTags.find(t => t.toLowerCase() === lowerTag);
if (existingTag) {
return existingTag;
}
// No existing tag found, return the input as-is
return tagName;
}
export function renderTagsChips(tags, opts) {
const chipsContainer = document.getElementById("tagsChips");
if (!chipsContainer)
return;
const canRemove = opts?.canRemove ?? true;
chipsContainer.innerHTML = tags.map(tagName => {
const tagColor = getTagColor(tagName);
const safe = sanitizeHexColor(tagColor);
const colorStyle = safe ? `style="border-color: ${safe}; background: ${safe}20; color: ${safe};"` : "";
const removeBtn = canRemove ? `<button type="button" class="tag-chip-remove" aria-label="Remove tag">×</button>` : "";
return `
<span class="tag-chip" data-tag="${escapeHTML(tagName)}" ${colorStyle}>
${escapeHTML(tagName)}
${removeBtn}
</span>
`;
}).join("");
// Add remove handlers only when canRemove (with guard for delegated clicks)
chipsContainer.querySelectorAll(".tag-chip-remove").forEach(btn => {
if (!btn[BOUND_FLAG]) {
btn.addEventListener("click", (e) => {
if (!permissions.canEditTags)
return;
e.stopPropagation();
const chip = btn.closest(".tag-chip");
const tagName = chip?.getAttribute("data-tag");
if (tagName) {
removeTag(tagName);
}
});
btn[BOUND_FLAG] = true;
}
});
}
function updateTagAutocomplete() {
const input = getTagInput();
if (!input)
return;
const value = input.value;
const cursorPos = input.selectionStart || 0;
// Find the current tag being typed (last segment after comma)
const beforeCursor = value.substring(0, cursorPos);
const lastCommaIndex = beforeCursor.lastIndexOf(",");
const currentTagRaw = beforeCursor.substring(lastCommaIndex + 1);
const currentTag = currentTagRaw.trim();
if (currentTag.length === 0 || getAvailableTags().length === 0) {
setAutocompleteSuggestion(null);
renderTagAutocomplete();
return;
}
// Get all tags that have already been entered (excluding the current one being typed)
const fullValue = input.value;
const existingTags = fullValue
.split(",")
.map(t => t.trim().toLowerCase())
.filter(t => t.length > 0 && t !== currentTag.toLowerCase());
// Find matching tag (case-insensitive prefix match) that hasn't been used yet
const matchingTag = getAvailableTags().find(tag => {
const tagLower = tag.toLowerCase();
const currentTagLower = currentTag.toLowerCase();
return tagLower.startsWith(currentTagLower) &&
tagLower !== currentTagLower &&
!existingTags.includes(tagLower);
});
// Use normalized version if found (to get proper capitalization)
if (matchingTag) {
setAutocompleteSuggestion(normalizeTagName(matchingTag));
}
else {
setAutocompleteSuggestion(null);
}
// Update the visual suggestion
renderTagAutocomplete();
}
export function renderTagAutocomplete() {
// Remove existing suggestion overlay
const existing = document.getElementById("tagAutocompleteSuggestion");
if (existing) {
existing.remove();
}
if (!getAutocompleteSuggestion()) {
return;
}
const input = getTagInput();
if (!input)
return;
const value = input.value;
const cursorPos = input.selectionStart || 0;
const beforeCursor = value.substring(0, cursorPos);
const lastCommaIndex = beforeCursor.lastIndexOf(",");
const currentTagRaw = beforeCursor.substring(lastCommaIndex + 1);
const currentTag = currentTagRaw.trim();
if (currentTag.length === 0) {
return;
}
const suggestion = getAutocompleteSuggestion();
if (!suggestion)
return;
const remaining = suggestion.substring(currentTag.length);
if (remaining.length === 0)
return;
// Create overlay element for suggestion
const overlay = document.createElement("div");
overlay.id = "tagAutocompleteSuggestion";
overlay.className = "tag-autocomplete-suggestion";
overlay.textContent = remaining;
// Position overlay to match input text position
const inputRect = input.getBoundingClientRect();
const style = window.getComputedStyle(input);
const paddingLeft = parseFloat(style.paddingLeft) || 0;
const paddingTop = parseFloat(style.paddingTop) || 0;
const borderLeft = parseFloat(style.borderLeftWidth) || 0;
const borderTop = parseFloat(style.borderTopWidth) || 0;
// Create temporary span to measure text width (up to cursor)
const measureSpan = document.createElement("span");
measureSpan.style.position = "absolute";
measureSpan.style.visibility = "hidden";
measureSpan.style.whiteSpace = "pre";
measureSpan.style.fontSize = style.fontSize;
measureSpan.style.fontFamily = style.fontFamily;
measureSpan.style.fontWeight = style.fontWeight;
measureSpan.style.fontStyle = style.fontStyle;
measureSpan.style.letterSpacing = style.letterSpacing;
measureSpan.style.padding = "0";
measureSpan.style.margin = "0";
measureSpan.style.border = "none";
measureSpan.style.lineHeight = style.lineHeight;
measureSpan.textContent = beforeCursor;
document.body.appendChild(measureSpan);
const textWidth = measureSpan.getBoundingClientRect().width;
// Create another span to measure vertical text position within input
const measureVerticalSpan = document.createElement("span");
measureVerticalSpan.style.position = "absolute";
measureVerticalSpan.style.visibility = "hidden";
measureVerticalSpan.style.whiteSpace = "pre";
measureVerticalSpan.style.fontSize = style.fontSize;
measureVerticalSpan.style.fontFamily = style.fontFamily;
measureVerticalSpan.style.fontWeight = style.fontWeight;
measureVerticalSpan.style.fontStyle = style.fontStyle;
measureVerticalSpan.style.letterSpacing = style.letterSpacing;
measureVerticalSpan.style.textTransform = style.textTransform;
measureVerticalSpan.style.padding = "0";
measureVerticalSpan.style.margin = "0";
measureVerticalSpan.style.border = "none";
measureVerticalSpan.style.lineHeight = style.lineHeight;
measureVerticalSpan.textContent = "X"; // Single character to measure baseline
// Position it exactly where input text would be
measureVerticalSpan.style.top = `${inputRect.top + borderTop + paddingTop}px`;
measureVerticalSpan.style.left = `${inputRect.left + borderLeft + paddingLeft}px`;
document.body.appendChild(measureVerticalSpan);
const textTop = measureVerticalSpan.getBoundingClientRect().top;
measureVerticalSpan.remove();
measureSpan.remove();
// Find the input's container (tags-input-container) to position relative to it
const inputContainer = input.closest(".tags-input-container") || input.parentElement;
if (!inputContainer)
return;
const containerRect = inputContainer.getBoundingClientRect();
// Position absolutely relative to the input container
// Use measured text position for accurate vertical alignment
overlay.style.position = "absolute";
overlay.style.left = `${inputRect.left - containerRect.left + borderLeft + paddingLeft + textWidth - input.scrollLeft}px`;
overlay.style.top = `${textTop - containerRect.top}px`;
overlay.style.fontSize = style.fontSize;
overlay.style.fontFamily = style.fontFamily;
overlay.style.fontWeight = style.fontWeight;
overlay.style.fontStyle = style.fontStyle;
overlay.style.letterSpacing = style.letterSpacing;
overlay.style.textTransform = style.textTransform;
// pointer-events: none on desktop (CSS); auto on mobile so tap accepts suggestion
overlay.style.zIndex = "10000";
overlay.style.lineHeight = style.lineHeight;
overlay.style.color = "var(--muted)";
// On mobile there is no Tab key; single tap on the suggestion accepts it
overlay.addEventListener("click", (e) => {
e.preventDefault();
acceptAutocompleteSuggestion();
});
// Ensure container has relative positioning for absolute children
const containerStyle = window.getComputedStyle(inputContainer);
if (containerStyle.position === "static") {
inputContainer.style.position = "relative";
}
// Append to the input container so it's positioned relative to it
inputContainer.appendChild(overlay);
}
function handleTagInput(e) {
updateTagAutocomplete();
}
function handleTagKeydown(e) {
if (!permissions.canEditTags)
return;
if (getAutocompleteSuggestion() && (e.key === "Tab" || e.key === "Enter")) {
e.preventDefault();
acceptAutocompleteSuggestion();
}
else if (e.key === "Escape") {
setAutocompleteSuggestion(null);
renderTagAutocomplete();
}
else if (e.key === "Enter" && !getAutocompleteSuggestion()) {
e.preventDefault();
addTagFromInput();
}
else if (e.key === "Tab" && !getAutocompleteSuggestion() && getTagInput()?.value.trim()) {
e.preventDefault();
addTagFromInput();
}
else if (e.key === "," && !getAutocompleteSuggestion()) {
e.preventDefault();
addTagFromInput();
}
}
function acceptAutocompleteSuggestion() {
if (!permissions.canEditTags)
return;
if (!getAutocompleteSuggestion())
return;
// Normalize the suggestion to ensure proper capitalization
const normalized = normalizeTagName(getAutocompleteSuggestion());
addTag(normalized);
setAutocompleteSuggestion(null);
renderTagAutocomplete();
}
function addTag(tagName) {
if (!permissions.canEditTags)
return;
const trimmed = tagName.trim();
if (!trimmed)
return;
// Normalize to existing tag capitalization if it exists
const normalized = normalizeTagName(trimmed);
const currentTags = getTagsFromChips();
// Check for duplicates (case-insensitive)
if (currentTags.some(t => t.toLowerCase() === normalized.toLowerCase())) {
return; // Don't add duplicates
}
currentTags.push(normalized);
renderTagsChips(currentTags, { canRemove: permissions.canEditTags });
const input = getTagInput();
if (input)
input.value = "";
updateTagAutocomplete();
}
export function removeTag(tagName) {
if (!permissions.canEditTags)
return;
const currentTags = getTagsFromChips();
const filtered = currentTags.filter(t => t !== tagName);
renderTagsChips(filtered, { canRemove: permissions.canEditTags });
updateTagAutocomplete();
}
function addTagFromInput() {
if (!permissions.canEditTags)
return;
const input = getTagInput();
if (!input)
return;
const value = input.value.trim();
if (!value)
return;
// If there's an autocomplete suggestion, use that
if (getAutocompleteSuggestion()) {
acceptAutocompleteSuggestion();
return;
}
// Otherwise, add the current input value
const tags = value.split(",").map(t => t.trim()).filter(Boolean);
tags.forEach(tag => addTag(tag));
input.value = "";
}
export function setupTagAutocomplete() {
setAutocompleteSuggestion(null);
const input = getTagInput();
if (!input)
return;
// Only setup once per element (tagInputHandlersSetup is reset when we clone)
if (tagInputHandlersSetup) {
updateTagAutocomplete();
return;
}
input.addEventListener("input", handleTagInput);
input.addEventListener("keydown", handleTagKeydown);
input.addEventListener("blur", () => {
setTimeout(() => {
setAutocompleteSuggestion(null);
renderTagAutocomplete();
}, 200);
});
if (addTagBtn && !addTagBtn[BOUND_FLAG]) {
addTagBtn[BOUND_FLAG] = true;
addTagBtn.addEventListener("click", () => {
addTagFromInput();
getTagInput()?.focus();
});
}
tagInputHandlersSetup = true;
updateTagAutocomplete();
}
function clearLinkSearchInFlight() {
if (linksSearchDebounce) {
clearTimeout(linksSearchDebounce);
linksSearchDebounce = null;
}
if (linksSearchController) {
linksSearchController.abort();
linksSearchController = null;
}
}
function removeLinksAutocompleteOverlay() {
const existing = document.getElementById("linksAutocompleteSuggestion");
if (existing)
existing.remove();
}
function formatLinkedStoryLabel(item) {
return `#${item.localId} ${item.title || ""}`.trim();
}
function getLinkedStorySuggestionText(item, q) {
const label = formatLinkedStoryLabel(item);
const normalizedQ = q.toLowerCase();
if (label.toLowerCase().startsWith(normalizedQ))
return label;
const title = (item.title || "").trim();
if (title.toLowerCase().startsWith(normalizedQ))
return title;
const hashID = `#${item.localId}`;
if (hashID.toLowerCase().startsWith(normalizedQ))
return hashID;
return null;
}
function renderLinksAutocomplete(input) {
removeLinksAutocompleteOverlay();
if (!linkAutocompleteSuggestion)
return;
const q = input.value.trim();
if (!q)
return;
const suggestionText = getLinkedStorySuggestionText(linkAutocompleteSuggestion, q);
if (!suggestionText)
return;
let remaining = suggestionText.substring(q.length);
if (!remaining)
return;
remaining = remaining.replace(/^\s+/, ""); // avoid double space if suggestion had leading space
if (!remaining)
return;
const overlay = document.createElement("div");
overlay.id = "linksAutocompleteSuggestion";
overlay.className = "tag-autocomplete-suggestion";
overlay.textContent = " " + remaining;
const inputRect = input.getBoundingClientRect();
const style = window.getComputedStyle(input);
const paddingLeft = parseFloat(style.paddingLeft) || 0;
const paddingTop = parseFloat(style.paddingTop) || 0;
const borderLeft = parseFloat(style.borderLeftWidth) || 0;
const borderTop = parseFloat(style.borderTopWidth) || 0;
const measureSpan = document.createElement("span");
measureSpan.style.position = "absolute";
measureSpan.style.visibility = "hidden";
measureSpan.style.whiteSpace = "pre";
measureSpan.style.fontSize = style.fontSize;
measureSpan.style.fontFamily = style.fontFamily;
measureSpan.style.fontWeight = style.fontWeight;
measureSpan.style.fontStyle = style.fontStyle;
measureSpan.style.letterSpacing = style.letterSpacing;
measureSpan.style.padding = "0";
measureSpan.style.margin = "0";
measureSpan.style.border = "none";
measureSpan.style.lineHeight = style.lineHeight;
measureSpan.textContent = q;
document.body.appendChild(measureSpan);
const textWidth = measureSpan.getBoundingClientRect().width;
measureSpan.remove();
const inputContainer = input.closest(".tags-input-container") || input.parentElement;
if (!inputContainer)
return;
const containerRect = inputContainer.getBoundingClientRect();
overlay.style.position = "absolute";
overlay.style.left = `${inputRect.left - containerRect.left + borderLeft + paddingLeft + textWidth - input.scrollLeft}px`;
overlay.style.top = `${inputRect.top - containerRect.top + borderTop + paddingTop}px`;
overlay.style.fontSize = style.fontSize;
overlay.style.fontFamily = style.fontFamily;
overlay.style.fontWeight = style.fontWeight;
overlay.style.fontStyle = style.fontStyle;
overlay.style.letterSpacing = style.letterSpacing;
overlay.style.textTransform = style.textTransform;
overlay.style.zIndex = "10000";
overlay.style.lineHeight = style.lineHeight;
overlay.style.color = "var(--muted)";
overlay.style.whiteSpace = "pre";
overlay.addEventListener("click", (e) => {
e.preventDefault();
input.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true }));
});
const containerStyle = window.getComputedStyle(inputContainer);
if (containerStyle.position === "static") {
inputContainer.style.position = "relative";
}
inputContainer.appendChild(overlay);
}
function getAllLinkedLocalIDs() {
const ids = new Set();
currentLinks.outbound.forEach((l) => ids.add(l.localId));
currentLinks.inbound.forEach((l) => ids.add(l.localId));
return Array.from(ids.values());
}
async function addLinkedStoryByLocalID(slug, currentLocalId, targetLocalId, onNavigateToLinkedTodo) {
if (!targetLocalId || targetLocalId === currentLocalId)
return;
recordLocalMutation();
await apiFetch(`/api/board/${slug}/todos/${currentLocalId}/links`, {
method: "POST",
body: JSON.stringify({ targetLocalId }),
});
lastLoadedLinksForTodo = null;
await loadLinksForTodo(slug, currentLocalId);
renderLinksChips(slug, currentLocalId, onNavigateToLinkedTodo);
}
function parseLocalIDFromLinkInput(raw) {
const trimmed = raw.trim();
if (!trimmed)
return null;
const match = trimmed.match(/^#?(\d+)$/);
if (!match)
return null;
const parsed = parseInt(match[1], 10);
return parsed > 0 ? parsed : null;
}
function renderLinksChips(slug, currentLocalId, onNavigateToLinkedTodo) {
const container = document.getElementById("linksChips");
if (!container)
return;
const outbound = currentLinks.outbound.map((item) => `
<span class="tag-chip" data-link-local-id="${item.localId}" data-link-direction="outbound">
<button type="button" class="tag-chip-link" data-link-open="${item.localId}">#${item.localId} ${escapeHTML(item.title)}</button>
<button type="button" class="tag-chip-remove" data-link-remove="${item.localId}" aria-label="Remove link">×</button>
</span>
`).join("");
const inbound = currentLinks.inbound.map((item) => `
<span class="tag-chip" data-link-local-id="${item.localId}" data-link-direction="inbound">
<button type="button" class="tag-chip-link" data-link-open="${item.localId}">#${item.localId} ${escapeHTML(item.title)}</button>
</span>
`).join("");
container.innerHTML = `${outbound}${inbound}`;
container.querySelectorAll("[data-link-open]").forEach((btn) => {
if (!btn[BOUND_FLAG]) {
btn[BOUND_FLAG] = true;
btn.addEventListener("click", () => {
const id = parseInt(btn.getAttribute("data-link-open") || "0", 10);
if (!id)
return;
const nextPath = `/${slug}/t/${id}`;
if (onNavigateToLinkedTodo) {
onNavigateToLinkedTodo(nextPath);
}
});
}
});
container.querySelectorAll("[data-link-remove]").forEach((btn) => {
if (!btn[BOUND_FLAG]) {
btn[BOUND_FLAG] = true;
btn.addEventListener("click", async (e) => {
e.stopPropagation();
const id = parseInt(btn.getAttribute("data-link-remove") || "0", 10);
if (!id)
return;
try {
recordLocalMutation();
await apiFetch(`/api/board/${slug}/todos/${currentLocalId}/links/${id}`, { method: "DELETE" });
lastLoadedLinksForTodo = null;
await loadLinksForTodo(slug, currentLocalId);
renderLinksChips(slug, currentLocalId, onNavigateToLinkedTodo);
}
catch (err) {
showToast(err.message || "Failed to remove link");
}
});
}
});
}
async function loadLinksForTodo(slug, localId) {
const alreadyLoaded = !!lastLoadedLinksForTodo &&
lastLoadedLinksForTodo.slug === slug &&
lastLoadedLinksForTodo.localId === localId;
if (alreadyLoaded)
return;
const res = await apiFetch(`/api/board/${slug}/todos/${localId}/links`);
currentLinks = {
outbound: Array.isArray(res?.outbound) ? res.outbound : [],
inbound: Array.isArray(res?.inbound) ? res.inbound : [],
};
lastLoadedLinksForTodo = { slug, localId };
}
function setupLinkedStoriesSearch(slug, currentLocalId, onNavigateToLinkedTodo) {
const existing = document.getElementById("linksSearchInput");
if (!existing || !existing.parentNode)
return;
const existingAddBtn = document.getElementById("addLinkBtn");
const input = existing.cloneNode(true);
existing.parentNode.replaceChild(input, existing);
let addBtn = null;
if (existingAddBtn && existingAddBtn.parentNode) {
addBtn = existingAddBtn.cloneNode(true);
existingAddBtn.parentNode.replaceChild(addBtn, existingAddBtn);
}
input.value = "";
linkAutocompleteSuggestion = null;
removeLinksAutocompleteOverlay();
clearLinkSearchInFlight();
const submitLinkFromInput = async () => {
const directLocalID = parseLocalIDFromLinkInput(input.value);
const target = linkAutocompleteSuggestion?.localId ?? directLocalID;
if (!target) {
showToast("Type #id or title, then tap Add");
return;
}
try {
await addLinkedStoryByLocalID(slug, currentLocalId, target, onNavigateToLinkedTodo);
input.value = "";
linkAutocompleteSuggestion = null;
removeLinksAutocompleteOverlay();
clearLinkSearchInFlight();
}
catch (err) {
showToast(err.message || "Failed to link story");
}
};
const updateAutocomplete = () => {
const q = input.value.trim();
clearLinkSearchInFlight();
if (!q) {
linkAutocompleteSuggestion = null;
removeLinksAutocompleteOverlay();
return;
}
linksSearchDebounce = setTimeout(async () => {
linksSearchDebounce = null;
const exclude = Array.from(new Set([currentLocalId, ...getAllLinkedLocalIDs()])).join(",");
const searchQ = q.match(/^#(\d+)$/)?.[1] ?? q;
linksSearchController = new AbortController();
try {
const params = new URLSearchParams();
params.set("q", searchQ);
params.set("limit", "20");
if (exclude)
params.set("exclude", exclude);
const list = await apiFetch(`/api/board/${slug}/todos/search?${params.toString()}`, { signal: linksSearchController.signal });
const items = Array.isArray(list) ? list : [];
linkAutocompleteSuggestion = items.length > 0 ? items[0] : null;
renderLinksAutocomplete(input);
}
catch (err) {
if (err?.name === "AbortError")
return;
showToast(err.message || "Failed to search stories");
}
finally {
linksSearchController = null;
}
}, 300);
};
input.addEventListener("input", updateAutocomplete);
input.addEventListener("keydown", async (e) => {
if (e.key === "Tab" || e.key === "Enter") {
e.preventDefault();
await submitLinkFromInput();
return;
}
if (e.key === "Escape") {
linkAutocompleteSuggestion = null;
removeLinksAutocompleteOverlay();
}
});
if (addBtn) {
addBtn.addEventListener("click", async () => {
await submitLinkFromInput();
input.focus();
});
}
input.addEventListener("blur", () => {
setTimeout(() => {
removeLinksAutocompleteOverlay();
}, 150);
});
}
function bindDialogLinkLifecycle() {
if (dialogLinkLifecycleBound)
return;
dialogLinkLifecycleBound = true;
todoDialog.addEventListener("close", () => {
clearLinkSearchInFlight();
linkAutocompleteSuggestion = null;
removeLinksAutocompleteOverlay();
lastLoadedLinksForTodo = null;
currentLinks = { outbound: [], inbound: [] };
});
}
function bindShareTodoButton() {
if (!shareTodoBtn || shareTodoBtn[BOUND_FLAG])
return;
shareTodoBtn[BOUND_FLAG] = true;
shareTodoBtn.addEventListener("click", async () => {
const slug = getSlug();
const editing = getEditingTodo();
if (!slug || !editing?.localId) {
showToast("Cannot share: no story in context");
return;
}
const url = `${window.location.origin}/${slug}/t/${editing.localId}`;
const title = editing.title ? `${editing.title} (#${editing.localId})` : `Story #${editing.localId}`;
if (typeof navigator.share === "function") {
try {
await navigator.share({
url,
title: title,
text: editing.title || undefined,
});
showToast("Link shared");
}
catch (err) {
if (err?.name !== "AbortError") {
showToast(err?.message || "Share failed");
}
}
}
else {
try {
await navigator.clipboard.writeText(url);
showToast("Link copied");
}
catch {
showToast("Share not supported");
}
}
});
}
export async function openTodoDialog(opts) {
const { mode, todo, status, onNavigateToLinkedTodo } = opts;
setEditingTodo(mode === "edit" ? todo : null);
bindDialogLinkLifecycle();
// Compute permissions once (mode-aware so create never inherits stale assignment state)
const board = getBoard();
const anonymousBoard = isAnonymousBoard(board);
const isMaintainer = (opts.role ?? "") === "maintainer" || anonymousBoard;
const currentUser = getUser();
const isAssignedToMe = currentUser &&
mode === "edit" &&
Number(todo?.assigneeUserId) === Number(currentUser.id);
permissions = {
canChangeSprint: isMaintainer && !anonymousBoard,
canChangeEstimation: isMaintainer,
canEditTags: isMaintainer,
canEditNotes: isMaintainer || (!anonymousBoard && opts.role === "contributor" && !!isAssignedToMe),
canEditAssignment: isMaintainer && !anonymousBoard,
canDeleteTodo: isMaintainer,
};
// Fetch available tags for autocomplete
// Authenticated boards: fetch ALL user-owned tags from full library (/api/tags/mine)
// This allows autocomplete to suggest tags not yet used on this board
// Anonymous boards: fetch board-scoped tags (/api/board/{slug}/tags)
if (getSlug()) {
try {
let tagsResponse;
if (getUser()) {
// Authenticated: fetch ALL user-owned tags from full library (cross-project)
// This allows autocomplete to suggest tags from other projects
tagsResponse = await apiFetch(`/api/tags/mine`);
}
else {
// Anonymous: fetch board-scoped tags (only tags used on this board)
tagsResponse = await apiFetch(`/api/board/${getSlug()}/tags`);
}
// Extract tag names from the response (tags are objects with name and color)
setAvailableTags(tagsResponse.map((tag) => typeof tag === 'string' ? tag : tag.name));
// Build map for case-insensitive lookup (lowercase -> proper capitalization)
const tagsMap = {};
tagsResponse.forEach((tag) => {
const tagName = typeof tag === 'string' ? tag : tag.name;
tagsMap[tagName.toLowerCase()] = tagName;
if (tag.color) {
const tagColors = { ...getTagColors() };
tagColors[tagName] = tag.color;
setTagColors(tagColors);
}
});
setAvailableTagsMap(tagsMap);
}
catch (err) {
console.error("Failed to fetch tags:", err);
setAvailableTags([]);
setAvailableTagsMap({});
}
}
else {
// No slug - no autocomplete
setAvailableTags([]);
setAvailableTagsMap({});
}
// Assignee field: visible when board supports assignments (not anonymous).
// Contributors see it but dropdown is disabled; maintainers can change assignment.
const assigneeField = document.getElementById("todoAssigneeField");
const assigneeSelect = document.getElementById("todoAssignee");
const showAssignee = assigneeField && assigneeSelect && !isAnonymousBoard(getBoard());
if (assigneeField) {
assigneeField.style.display = showAssignee ? "" : "none";
}
// Sprint field: visible when board is not anonymous, has slug, and user is Maintainer
const sprintField = document.getElementById("todoSprintField");
const sprintSelect = document.getElementById("todoSprint");
const showSprint = sprintField && sprintSelect && !isAnonymousBoard(getBoard()) && !!getSlug() && opts.role === "maintainer";
if (sprintField) {
sprintField.style.display = showSprint ? "" : "none";
}
if (sprintSelect) {
if (!showSprint) {
sprintSelect.value = "";
}
else {
try {
const res = await apiFetch(`/api/board/${getSlug()}/sprints`);
const sprints = normalizeSprints(res);
const defaultOpt = document.createElement("option");
defaultOpt.value = "";
defaultOpt.textContent = "—";
const options = [defaultOpt];
for (const sp of sprints) {
const opt = document.createElement("option");
opt.value = String(sp.id);
opt.textContent = `${sp.name} (${sp.state})`;
options.push(opt);
}
sprintSelect.replaceChildren(...options);
const fromTodo = todo?.sprintId != null ? String(todo.sprintId) : "";
sprintSelect.value = fromTodo;
}
catch (err) {
console.error("Failed to fetch sprints:", err);
}
}
}
if (assigneeSelect) {
if (showAssignee) {
// Only maintainers can assign to others; contributors see only Unassigned + self
const user = getUser();
const members = getBoardMembers();
const myMember = user ? members.find((m) => m.userId === user.id) : null;
const canAssignOthers = myMember?.role === "maintainer";
assigneeSelect.innerHTML = "";
const unassigned = document.createElement("option");
unassigned.value = "";
unassigned.textContent = "Unassigned";
assigneeSelect.appendChild(unassigned);
if (canAssignOthers) {
for (const m of members) {
const opt = document.createElement("option");
opt.value = String(m.userId);
opt.textContent = m.name || m.email || String(m.userId);
assigneeSelect.appendChild(opt);
}
}
else {
// Contributor (or non-maintainer): in edit mode show current assignee as disabled if different from self; then self only
if (mode === "edit") {
const currentAssigneeId = todo?.assigneeUserId;
if (currentAssigneeId != null &&
user &&
Number(currentAssigneeId) !== Number(user.id)) {
const assigneeMember = members.find((m) => Number(m.userId) === Number(currentAssigneeId));
if (assigneeMember) {
const opt = document.createElement("option");
opt.value = String(assigneeMember.userId);
opt.textContent = `Current: ${assigneeMember.name || assigneeMember.email || String(assigneeMember.userId)}`;
opt.disabled = true;
assigneeSelect.appendChild(opt);
}
}
}
if (user) {
const opt = document.createElement("option");
opt.value = String(user.id);
opt.textContent = user.name || user.email || "Me";
assigneeSelect.appendChild(opt);
}
}
assigneeSelect.value = todo?.assigneeUserId != null ? String(todo.assigneeUserId) : "";
}
else {
assigneeSelect.innerHTML = '<option value="">Unassigned</option>';
}
}
const linksField = document.getElementById("todoLinksField");
const slug = getSlug();
const editableWithLinks = mode === "edit" && !!todo?.localId && !!slug;
if (linksField) {
linksField.style.display = editableWithLinks ? "" : "none";
}
if (editableWithLinks) {
try {
await loadLinksForTodo(slug, todo.localId);
renderLinksChips(slug, todo.localId, onNavigateToLinkedTodo);
setupLinkedStoriesSearch(slug, todo.localId, onNavigateToLinkedTodo);
}
catch (err) {
showToast(err.message || "Failed to load linked stories");
}
}
else {
const linksChips = document.getElementById("linksChips");
if (linksChips)
linksChips.innerHTML = "";
clearLinkSearchInFlight();
linkAutocompleteSuggestion = null;
removeLinksAutocompleteOverlay();
currentLinks = { outbound: [], inbound: [] };
}
const estimationField = todoEstimationField;
const estimationSelect = todoEstimationPoints;
const showEstimation = isModifiedFibonacciMode();
if (estimationField) {
estimationField.style.display = showEstimation ? "" : "none";
}
if (estimationSelect) {
if (!showEstimation) {
estimationSelect.value = "";
}
else if (mode === "create") {
estimationSelect.value = "";
}
else {
estimationSelect.value = todo?.estimationPoints != null ? String(todo.estimationPoints) : "";
}
}
const createdEl = document.getElementById("todoDialogCreated");
const updatedEl = document.getElementById("todoDialogUpdated");
const formatDate = (d) => new Date(d).toLocaleString(undefined, { year: "2-digit", month: "numeric", day: "numeric", hour: "numeric", minute: "2-digit" });
const setDates = (createdAt, updatedAt) => {
if (createdEl) {
const valueEl = createdEl.querySelector(".todo-dialog-datetime-value");
if (createdAt == null) {
if (valueEl)
valueEl.textContent = "";
createdEl.setAttribute("aria-hidden", "true");
}
else {
if (valueEl)
valueEl.textContent = formatDate(createdAt);
createdEl.setAttribute("aria-hidden", "false");
}
}
if (updatedEl) {
const valueEl = updatedEl.querySelector(".todo-dialog-datetime-value");
if (updatedAt == null) {
if (valueEl)
valueEl.textContent = "";
updatedEl.setAttribute("aria-hidden", "true");
}
else {
if (valueEl)
valueEl.textContent = formatDate(updatedAt);
updatedEl.setAttribute("aria-hidden", "false");
}
}
};
if (mode === "create") {
todoDialogTitle.textContent = "New Todo";
todoTitle.value = "";
todoBody.value = "";
todoTags.value = "";
const initialKey = resolveColumnKey(status);
const selected = populateTodoStatusOptions(initialKey);
todoStatus.value = selected;
deleteTodoBtn.style.display = "none";
if (shareTodoBtn)
shareTodoBtn.style.display = "none";
setDates(undefined, undefined);
}
else {
todoDialogTitle.textContent = "Edit Todo";
todoTitle.value = todo.title || "";
todoBody.value = todo.body || "";
todoTags.value = "";
const initialKey = resolveColumnKey(todo.columnKey || todo.status);
const selected = populateTodoStatusOptions(initialKey);
todoStatus.value = selected;
deleteTodoBtn.style.display = permissions.canDeleteTodo ? "" : "none";
if (shareTodoBtn)
shareTodoBtn.style.display = "";
setDates(todo.createdAt, todo.updatedAt);
}
// 1. Clone tag input to clear previous autocomplete listeners (maintainer→contributor would otherwise keep handlers)
const tagInputEl = document.getElementById("todoTags");
if (tagInputEl) {
tagInputEl.replaceWith(tagInputEl.cloneNode(true));
tagInputHandlersSetup = false;
}
// 2. Refetch (clone clears input; tags live in chips)
const tagInputRefetched = document.getElementById("todoTags");
if (tagInputRefetched) {
tagInputRefetched.value = "";
}
// 3. Reset block (every open) - set disabled/readOnly from current permissions (use getTagInput for tag input after clone)
if (assigneeSelect)
assigneeSelect.disabled = !permissions.canEditAssignment;
if (estimationSelect)
estimationSelect.disabled = !permissions.canChangeEstimation;
const tagInput = getTagInput();
if (tagInput)
tagInput.disabled = !permissions.canEditTags;
if (addTagBtn)
addTagBtn.disabled = !permissions.canEditTags;
todoBody.readOnly = !permissions.canEditNotes;
// 4. Tag chips: clear and re-render so old chips (with "×" from previous maintainer open) are not reused
const tagsChips = document.getElementById("tagsChips");
if (tagsChips)
tagsChips.innerHTML = "";
const tagsToShow = mode === "create" ? [] : (todo?.tags || []);