-
Notifications
You must be signed in to change notification settings - Fork 3
/
card.js
3004 lines (2689 loc) · 120 KB
/
card.js
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
/// <reference path="intellisense.js" />
var g_inputSEClass = "agile_plus_addCardSE";
var g_strNowOption = "now";
var g_bShowSEBar = false;
const ID_BOARD_PLUSHELP = "0jHOl1As";
var g_valDayExtra = null; //for "other" date in S/E bar
var g_valUserExtra = null; //for "other" added user in S/E bar
var g_regexValidateSEKey = /[0-9]|\.|\:|\-/;
const g_iLastComboDays = 9;
var g_timeoutComboDaysUpdate = null;
var g_msdateFillDaysList = 0;
function validateSEKey(evt) {
var theEvent = evt || window.event;
var key = theEvent.keyCode || theEvent.which;
key = String.fromCharCode(key);
if (!g_regexValidateSEKey.test(key)) {
theEvent.returnValue = false;
if (theEvent.preventDefault)
theEvent.preventDefault();
}
}
var g_seCardCur = null; //null means not yet initialized review zig cleanup into a class
function rememberSEUser(user) {
if (!g_bUseLastSEBarUser)
return;
var objNew = {};
objNew[SYNCPROP_USERSEBAR_LAST] = user;
chrome.storage.sync.set(objNew, function () {
//ok if fails
if (BLastErrorDetected())
console.error(chrome.runtime.lastError.message);
});
}
/* getUserLast
** thenable
** will always resolve to "" when !g_bUseLastSEBarUser or !bUseLast
** bUseLast: does NOT mean g_bUseLastSEBarUser. its a shortcut to pass false and resolve to "" for callers that dont want to use userLast
**/
function getUserLast(bUseLast) {
var val = ""; //means "me" by callers
if (!g_bUseLastSEBarUser || !bUseLast)
return Promise.resolve(val);
return new Promise(function (resolve, reject) {
chrome.storage.sync.get([SYNCPROP_USERSEBAR_LAST], function (obj) {
if (chrome.runtime.lastError)
console.log(chrome.runtime.lastError.message); //eat it and default to "" (me)
else
val = obj[SYNCPROP_USERSEBAR_LAST] || "";
resolve(val);
});
});
}
function getSeCurForUser(user,keyword) { //note returns null when not loaded yet
assert(user);
if (g_seCardCur===null)
return null;
var retZero = { s: 0, e: 0, kw: {} };
var map = g_seCardCur[user] || retZero;
if (!keyword)
return map;
return (map.kw[keyword] || retZero);
}
function updateEOnSChange(cRetry) {
cRetry = cRetry || 0;
var comment = $("#plusCardCommentComment");
var spinS = $("#plusCardCommentSpent");
var spinE = $("#plusCardCommentEstimate");
var comboUsers = $("#plusCardCommentUsers");
var comboKeywords = $("#plusCardCommentKeyword"); //can be empty
setTimeout(function () {
var valS = spinS.val() || "";
var bHilite = false;
var bRecurring = isRecurringCard();
if (bRecurring) {
spinE.val(valS);
bHilite = true;
}
else if (!g_bAllowNegativeRemaining) {
if (g_seCardCur === null) { //user report not loaded yet
if (cRetry < 3) {
setTimeout(function () {
if (spinS.is(":focus"))
updateEOnSChange(cRetry + 1);
}, 200);
}
return;
}
var userCur = getUserFromCombo(comboUsers);
if (!userCur)
return; //timing related. card window could be gone thus no combo
var keyword = comboKeywords.val() || ""; //can be empty
var mapSeCur = getSeCurForUser(userCur, keyword);
if (!mapSeCur)
return; //shouldt happen
var sNew = mapSeCur.s + parseSEInput(spinS, false, true);
var floatDiff = sNew - mapSeCur.e; //compare with original e
if (floatDiff <= 0)
floatDiff = 0;
var diff = parseFixedFloat(floatDiff);
if (diff <= 0 || (g_bPreventIncreasedE && mapSeCur.e>0)) {
assert(!bRecurring);
diff = "";
floatDiff = 0;
}
if (spinE.val() != diff) {
if (diff) {
if (valS.indexOf(":") >= 0) {
diff = UNITS.FormatWithColon(floatDiff);
}
}
spinE.val(diff);
bHilite = true;
}
}
if (bHilite)
hiliteOnce(spinE, 500);
updateNoteR();
}, 1);
}
function updateNoteR() {
var spinS = $("#plusCardCommentSpent");
var spinE = $("#plusCardCommentEstimate");
var userElem = $("#plusCardCommentUsers");
var comboKeywords = $("#plusCardCommentKeyword"); //can be empty
var statusPre = $("#agile-se-bar-status-pre");
var statusS = $("#agile-se-bar-status-s");
var statusE = $("#agile-se-bar-status-e");
var statusR = $("#agile-se-bar-status-r");
if (statusPre.length == 0 || spinS.length == 0 || spinE.length == 0 || userElem.length == 0)
return;
var userCur = getUserFromCombo(userElem);
if (!userCur)
return; //user not loaded yet
var keyword = comboKeywords.val() || "";
var mapSe = getSeCurForUser(userCur, keyword);
if (mapSe == null)
return; // table not loaded yet. this will be called when table loads
var strLinkHelp = " <a class='agile_linkSoftColor no-print agile_unselectable' href='' target='_blank'>Help</a>";
var sRaw = spinS.val();
var eRaw = spinE.val();
function done() {
updateCurrentSEData();
var link = statusR.find("A");
link.click(function (e) {
e.preventDefault();
showSEHelpDialog();
});
}
function clearAll() {
statusPre.html(" ");
statusS.html("");
statusE.html("");
statusR.html(strLinkHelp);
}
var sParsed = parseSEInput(spinS, false, true, true);
var eParsed = parseSEInput(spinE, false, true, true);
if (sParsed == null) {
clearAll();
statusPre.html("Bad S format!");
done();
return;
}
if (eParsed == null) {
clearAll();
statusPre.html("Bad E format!");
done();
return;
}
var sumS = sParsed + mapSe.s;
var sumE = eParsed + mapSe.e;
var rDiff = parseFixedFloat(sumE - sumS);
var rDiffFormatted = rDiff;
var sSumFormatted = parseFixedFloat(sumS);
var eSumFormatted = parseFixedFloat(sumE);
var prefixNote = "sums will be:";
if (sParsed == 0 && eParsed == 0) {
if (sumE == 0 && sumS == 0) {
clearAll();
done();
return;
}
prefixNote = "sums are:";
}
if (sumS < 0 || (!g_bNoEst && (sumE < 0 || (!g_bAllowNegativeRemaining && rDiff < 0))))
statusPre.closest("tr").addClass("agile_SER_negative").removeClass("agile_SER_normal");
else
statusPre.closest("tr").addClass("agile_SER_normal").removeClass("agile_SER_negative");
statusPre.html(prefixNote);
statusS.html("S=​" + sSumFormatted); //see http://stackoverflow.com/a/41913332/2213940 about the zero-width space so it line-breaks on long strings
statusE.html(g_bNoEst? "" : "E=​" + eSumFormatted);
statusR.html(g_bNoEst ? "" : " R=" + rDiffFormatted + (g_bAllowNegativeRemaining || rDiff != 0 ? "" : ". Increase E if not done.") + strLinkHelp);
done();
}
var g_timeoutUpdateCurrentSEData = null;
function updateCurrentSEData(bForceNow) {
if (g_timeoutUpdateCurrentSEData) {
clearTimeout(g_timeoutUpdateCurrentSEData);
g_timeoutUpdateCurrentSEData = null;
}
function worker() {
var idCardCur = getIdCardFromUrl(document.URL);
if (!idCardCur)
return;
var comment = $("#plusCardCommentComment");
var spinS = $("#plusCardCommentSpent");
var spinE = $("#plusCardCommentEstimate");
var comboUsers = $("#plusCardCommentUsers");
var comboDays = $("#plusCardCommentDays");
var comboKeywords = $("#plusCardCommentKeyword");
var valComment = comment.val();
var valS = spinS.val();
var valE = spinE.val();
var valUser = comboUsers.val() || "";
var valDays = comboDays.val() || "";
var valKeyword = (comboKeywords.length==0?"": comboKeywords.val()); //can be empty if combo doesnt exist
if (valUser == g_strUserOtherOption || valDays == g_strDateOtherOption)
return;
g_currentCardSEData.setValues(idCardCur, valKeyword, valUser, valDays, valS, valE, valComment);
}
if (bForceNow) {
worker();
}
else {
g_timeoutUpdateCurrentSEData = setTimeout(function () {
worker();
}, 300); //fast-typing users shall not suffer
}
}
function getUserFromCombo(combo) {
var userCur = combo.val() || "";
if (userCur == g_strUserMeOption)
userCur = getCurrentTrelloUser();
return userCur || ""; //prevent null
}
function isRecurringCard() {
var elemTitle = $(".card-detail-title-assist");
if (elemTitle.length == 0)
return false; //no longer in card window. just pretend not recurring
var titleCur = elemTitle.text();
var bRecurring = (titleCur.indexOf(TAG_RECURRING_CARD) >= 0);
return bRecurring;
}
function fillComboKeywords(comboKeywords, rg, kwSelected, classItem, strPrependNonDisabled, bNoPrependKWHeader) {
function add(elem, kwSelected) {
var str;
var val;
var title = "";
var disabled=false;
if (typeof (elem) == "string") {
str = elem;
val = elem;
}
else {
str=elem.str;
val = elem.val;
title = elem.title;
disabled = elem.disabled || false;
}
if (!disabled && strPrependNonDisabled)
str = strPrependNonDisabled + str;
var elemOption;
if (disabled)
elemOption = $('<optgroup label="' + str + '">');
else {
elemOption = $(new Option(str, val));
if (val == kwSelected)
elemOption[0].selected = true;
}
if (classItem)
elemOption.addClass(classItem);
if (title)
elemOption.attr("title", title);
comboKeywords.append(elemOption);
}
comboKeywords.empty();
if (!bNoPrependKWHeader)
comboKeywords.append($("<optgroup label='keyword:'></optgroup>"));
for (var i = 0; i < rg.length; i++) {
add(rg[i], kwSelected);
}
}
function fillComboUsers(bUseLast, comboUsers, userSelected, idCard, nameBoard, bDontEmpty, callbackParam) {
getUserLast(bUseLast).then(userLast => fillComboUsersWorker(comboUsers, userSelected || userLast, idCard, nameBoard, bDontEmpty, callbackParam));
}
function fillComboUsersWorker(comboUsers, userSelected, idCard, nameBoard, bDontEmpty, callbackParam) {
function callback(status) {
if (status != STATUS_OK)
sendDesktopNotification(status);
if (callbackParam)
callbackParam(status);
}
var sql = "select username from USERS order by username";
var userMe = getCurrentTrelloUser();
var user = g_strUserMeOption;
var userGlobal = g_globalUser; //make a copy
if (!bDontEmpty) {
comboUsers.empty();
comboUsers.append($("<optgroup label='user:'></optgroup>"));
}
comboUsers.append($(new Option(user, user))); //make it available right away as caller might select it
getSQLReport(sql, [],
function (response) {
var map = {};
function add(user) {
if (g_rgExcludedUsers.indexOf(user)>=0)
return;
var opt = new Option(user, user);
if (user == userSelected)
opt.selected = true;
comboUsers.append($(opt));
}
if (response.status == STATUS_OK) {
var mapUsers = {};
for (var i = 0; i < response.rows.length; i++) {
user = response.rows[i].username;
mapUsers[user] = true;
if (user == userGlobal)
userGlobal = "";
if (user == g_valUserExtra)
g_valUserExtra = null;
if (user == userMe)
continue;
add(user);
}
FindIdBoardFromBoardName(nameBoard, idCard, function (idBoardFound) {
if (!idBoardFound) {
callback("board not found. Sync and try again.");
return;
}
getTrelloBoardMembers(idBoardFound, 1000*60*2, function (members) {
for (var i = 0; i < members.length; i++) {
var member = members[i].member;
if (!member || !member.username || mapUsers[member.username] || member.username == userMe)
continue;
add(member.username);
}
if (userGlobal)
add(userGlobal);
if (g_valUserExtra)
add(g_valUserExtra);
add(g_strUserOtherOption);
callback(STATUS_OK);
});
});
} else {
callback(response.status);
}
});
}
function showSEButtonBubble(elem) {
var step = {
selector: elem,
text: "Add Plus S/E<br>from here!",
angle: 180,
distance: 5,
size: 150,
hiliteTime:10000
};
showBubbleFromStep(step, true, true, 0);
}
function createSEButton(parent) {
if (parent.length == 1) {
var a = $("<A class='comment-box-options-item agile-addSEButton' href='#' title='Add Plus S/E'>");
var spanIcon = $("<span class='icon-sm'/>");
var icon = $("<img style='margin-top:2px;'>").attr("src", chrome.extension.getURL("images/iconaddse.png"));
//icon.addClass("agile-spent-icon-cardcommentSE");
spanIcon.append(icon);
a.append(spanIcon);
parent.before(a);
a.click(function () {
showSEBarContainer(false,true,false, true);
});
}
}
function showSEBarContainer(bDontRemember, bFocusS, bFocusE, bDontHilite) {
$(".agile-se-bar-entry").show();
if (!bDontRemember)
g_bShowSEBar = true;
if (bFocusS || bFocusE) {
setTimeout(function () {
var elemSE = $(bFocusS ? ".agile_spent_box_input" : ".agile_estimation_box_input");
elemSE.focus();
if (!bDontHilite) {
hiliteOnce(elemSE);
hiliteOnce($("#plusCardCommentUsers"));
}
}, 0);
}
}
function fillDaysList(comboDays, cDaySelected) {
var iDays = null;
const bStrSelected = (typeof (cDaySelected) === "string");
g_msdateFillDaysList = Date.now();
function addItem(iDays, iDaysSelected) {
var bSelected = (iDays === iDaysSelected);
var str = null;
var title = "";
if (iDays == g_strDateOtherOption)
str = iDays;
else if (iDays == 0) {
str = g_strNowOption;
title = "today";
}
else {
str = "-" + iDays + "d";
title = "" + iDays + (iDays == 1 ? " day ago" : " days ago");
var dateNow = new Date();
dateNow.setDate(dateNow.getDate() - iDays);
title = title + ": " + getWeekdayName(dateNow.getDay()) + " " + dateNow.toLocaleDateString();
}
var optAdd = new Option(str, str);
if (bStrSelected)
bSelected = (str === iDaysSelected);
if (bSelected)
optAdd.selected = true;
comboDays.append($(optAdd).attr("title", title));
}
comboDays.empty();
comboDays.append($("<optgroup label='days ago:'></optgroup>"));
addItem(0, cDaySelected);
for (iDays = 1; iDays <= g_iLastComboDays; iDays++)
addItem(iDays, cDaySelected);
if (g_valDayExtra)
addItem(g_valDayExtra, cDaySelected);
addItem(g_strDateOtherOption, -1); //-1 so its different from all others
}
function promptNewUser(combo, idCardCur, callbackParam) {
function callback() {
if (callbackParam)
callbackParam();
}
var userNew = prompt("Enter the Trello username.\nThat member will see s/e only if is a board member.\n\nTo hide users from the s/e bar, see Plus Preferences.", userNew);
if (userNew)
userNew = userNew.trim().toLowerCase();
if (userNew && userNew.indexOf("@") == 0)
userNew = userNew.substring(1);
if (userNew == g_strUserOtherOption)
userNew = "";
if (userNew)
g_valUserExtra = userNew;
board = getCurrentBoard(); //refresh
if (!board)
return;
fillComboUsers(false, combo, userNew, idCardCur, board, false, function (status) {
if (status != STATUS_OK) {
callback(status);
return;
}
if (userNew && userNew.toLowerCase().indexOf(DEFAULTGLOBAL_USER.toLowerCase()) != 0 && userNew.toLowerCase().indexOf(g_globalUser.toLowerCase()) != 0) {
if (!idCardCur)
return; //shouldnt happen and no biggie if does
board = getCurrentBoard();
if (!board)
return; //shouldnt happen and no biggie if does
FindIdBoardFromBoardName(board, idCardCur, function (idBoardFound) {
verifyBoardMember(userNew, idBoardFound,
function () {
//user not found as board member
if (!confirm("'" + userNew + "' is not a member of '" + board + "'.\nAre you sure you want to use this user?\nPress OK to use it. Press Cancel to type it again.")) {
promptNewUser(combo, idCardCur, callbackParam);
} else {
callback(STATUS_OK);
}
}, function () {
callback(STATUS_OK);
});
});
} else {
callback(STATUS_OK);
}
});
}
function alertNoIncE() {
alert("You cannot increase the estimate (hey, just following your Preferences.)\nYour manager can increase estimates for you.\n\nTip: Are you typing in the correct Spent / Estimate box?");
}
/**
* @param {HTMLElement} parentSEInput
* @param {*} idCardCur
* @param {*} board
*/
function createCardSEInput(parentSEInput, idCardCur, board) {
assert(idCardCur);
var bHasSpentBackend = isBackendMode();
g_seCardCur = null; //remains null for a short time, until card report is loaded. code must check for ===null
const prevMenu = parentSEInput.parentElement?.querySelector('.' + g_inputSEClass);
if (prevMenu) {
prevMenu.remove();
}
var container = $("<div class='notranslate'></div>").addClass(g_inputSEClass).hide();
var containerStats = $("<div></div>");
var tableStats = $("<table class='agile-se-bar-table agile-se-stats tablesorter'></table>");
var containerBar = $("<table class='agile-se-bar-table agile-se-bar-entry no-print'></table>");
if (!g_bShowSEBar && !g_bAlwaysShowSEBar)
containerBar.hide();
containerStats.append(tableStats);
container.append(containerStats);
container.append(containerBar);
var row = $("<tr></tr>").addClass("agile-card-background");
var rowStatus = $("<tr>").addClass("agile-card-background");
var rowPad = $("<tr>").addClass("agile-card-background").append($("<td style='font-size:50%;'> </td>").addClass("agile_tablecellItem"));
containerBar.append($('<tbody class="agile-card-background">')).append(row).append(rowStatus).append(rowPad);
var comboUsers = setSmallFont($('<select id="plusCardCommentUsers"></select>').addClass("agile_general_box_input agile_combo_input"));
comboUsers.attr("title", "Click to select the user for this new S/E row.");
fillComboUsers(true, comboUsers, "", idCardCur, board);
comboUsers.change(function () {
updateNoteR();
var combo = $(this);
var val = combo.val();
if (!val)
return;
if (val == g_strUserOtherOption)
promptNewUser(combo, idCardCur);
else
rememberSEUser(val);
});
var comboDays = setSmallFont($('<select id="plusCardCommentDays"></select>').addClass("agile_days_box_input agile_combo_input"));
comboDays.attr("title", "Click to pick how many days ago it happened.");
fillDaysList(comboDays, 0);
if (g_timeoutComboDaysUpdate == null) {
function prepareNextCheck() {
assert(g_msdateFillDaysList > 0);
var dateNext = new Date(g_msdateFillDaysList);
dateNext = new Date(dateNext.getFullYear(), dateNext.getMonth(), dateNext.getDate() + 1);
g_timeoutComboDaysUpdate = setTimeout(function () {
var comboDaysCheck = $("#plusCardCommentDays");
if (comboDaysCheck.length == 0) {
g_timeoutComboDaysUpdate = null; //will create timeout again next time
return;
}
fillDaysList(comboDaysCheck, comboDaysCheck.val());
prepareNextCheck();
}, dateNext.getTime() - g_msdateFillDaysList + 500);
}
prepareNextCheck();
}
comboDays.change(function () {
var combo = $(this);
var val = combo.val();
if (!val)
return;
updateCurrentSEData();
if (val == g_strDateOtherOption) {
function process(dayNew) {
if (dayNew) {
if (dayNew > g_iLastComboDays)
g_valDayExtra = dayNew;
}
fillDaysList(comboDays, dayNew);
}
var dateNow = new Date();
getSEDate(function (dateIn) {
if (!getIdCardFromUrl(document.URL))
return; //rare. user managed to close the card but not the date dialog.
var date = 0;
if (dateIn)
date = getDeltaDates(dateNow, dateIn);
process(date);
});
}
});
var spinS = setNormalFont($('<input id="plusCardCommentSpent" placeholder="S" maxlength="10"></input>').addClass("agile_spent_box_input agile_placeholder_small agile_text_input"));
spinS.attr("title", "Click to type Spent.\nIf needed, Plus will increase E (right) when your total S goes over E.");
spinS[0].onkeypress = function (e) { validateSEKey(e); checkEnterKey(e); };
//thanks for "input" http://stackoverflow.com/a/14029861/2213940
spinS.bind("input", function (e) { updateEOnSChange(); });
var spinE = setNormalFont($('<input id="plusCardCommentEstimate" placeholder="E" maxlength="10"></input>').addClass("agile_estimation_box_input agile_placeholder_small agile_text_input"));
var spanSpinE = $('<span>');
spanSpinE.append(spinE);
spinE.attr("title", "Click to type Estimate.");
spinE[0].onkeypress = function (e) { validateSEKey(e); checkEnterKey(e); };
spinE.bind("input", function (e) { updateNoteR(); });
var slashSeparator = setSmallFont($("<span>").text("/"));
var comment = setNormalFont($('<input maxlength="250" name="Comment" placeholder="Comment"/>').attr("id", "plusCardCommentComment").addClass("agile_comment_box_input agile_placeholder_small agile_text_input"));
if (g_bNoEst) {
slashSeparator.addClass("agile_hidden");
spanSpinE.addClass("agile_hidden");
}
spinS.focus(function () { $(this).select(); });
spinE.focus(function () { $(this).select(); }); //selection on focus helps in case card is recurring, user types S and clicks on E to type it too. since we typed it for them, might get unexpected results
var spanIcon = $("<span />");
var icon = $("<img>").attr("src", chrome.extension.getURL("images/iconspent.png"));
icon.attr('title', 'Add S/E to this card. Use negative numbers to reduce.');
icon.addClass("agile-spent-icon-cardcommentSE");
spanIcon.append(icon);
var buttonEnter = setSmallFont($('<button id="plusCardCommentEnterButton"/>').addClass("agile_enter_box_input").addClass("agile_buton").text("Enter"));
buttonEnter.attr('title', 'Click to enter this S/E.');
row.append($('<td />').addClass("agile_tablecellItem").append(spanIcon));
var bAppendKW = false;
var comboKeyword = null; //stays null when the user only uses one keyword
if (g_optEnterSEByComment.IsEnabled()) {
var rgkeywords = g_optEnterSEByComment.getAllKeywordsExceptLegacy();
if (rgkeywords.length > 1) {
bAppendKW = true;
comboKeyword = setSmallFont($('<select id="plusCardCommentKeyword"></select>').addClass("agile_general_box_input"));
comboKeyword.attr("title", "Click to pick a different keyword for this new S/E row.");
fillComboKeywords(comboKeyword, rgkeywords, null);
row.append($('<td />').addClass("agile_tablecellItem").append($("<div>").addClass("agile_keywordsComboContainer").append(comboKeyword)));
comboKeyword.change(function () {
updateNoteR();
});
}
}
rowStatus.append($("<td>").addClass("agile_tablecellItem agile_tablecellItemStatus")); //space for the icon on above it
var tdStatusPre = $("<td style='text-align: right;' colspan='" + (bAppendKW ? "3" : "2") + "'>").addClass("agile_tablecellItem agile_tablecellItemStatus");
var elemStatusPre = $("<div id='agile-se-bar-status-pre' class='agile-se-bar-status'>").html("");
tdStatusPre.append(elemStatusPre);
var tdStatusS = $("<td style='text-align: center;'>").addClass("agile_tablecellItem agile_tablecellItemStatus");
var elemStatusS = $("<div id='agile-se-bar-status-s' class='agile-se-bar-status'>").html("");
tdStatusS.append(elemStatusS);
var tdStatusSep = $("<td>").addClass("agile_tablecellItem agile_tablecellItemStatus"); //space for the icon on above it
var tdStatusE = $("<td style='text-align: center;'>").addClass("agile_tablecellItem agile_tablecellItemStatus");
var elemStatusE = $("<div id='agile-se-bar-status-e' class='agile-se-bar-status'>").html("");
tdStatusE.append(elemStatusE);
var tdStatusR = $("<td>").addClass("agile_tablecellItem agile_tablecellItemStatus");
var elemStatusR = $("<div id='agile-se-bar-status-r' class='agile-se-bar-status'>").html("");
tdStatusR.append(elemStatusR);
rowStatus.append(tdStatusPre).append(tdStatusS).append(tdStatusSep).append(tdStatusE).append(tdStatusR);
row.append($('<td />').addClass("agile_tablecellItem").append($("<div>").addClass("agile_usersComboContainer").append(comboUsers)));
row.append($('<td />').addClass("agile_tablecellItem").append(comboDays));
row.append($('<td />').addClass("agile_tablecellItem").append(spinS));
row.append($('<td />').addClass("agile_tablecellItem").append(slashSeparator));
row.append($('<td />').addClass("agile_tablecellItem").append(spanSpinE));
row.append($('<td />').addClass("agile_tablecellItem").append(comment).width("100%")); //takes remaining hor. space
row.append($('<td />').addClass("agile_tablecellItemLast").append(buttonEnter));
function doEnter() {
testExtension(function () {
clearBlinkButtonInterval();
buttonEnter.removeClass("agile_box_input_hilite");
var keyword = null;
if (comboKeyword)
keyword = comboKeyword.val() || "";
var s = parseSEInput(spinS, false, false, true);
var e = parseSEInput(spinE, false, false, true);
if (s == null) {
hiliteOnce(spinS, 500);
return;
}
if (e == null) {
hiliteOnce(spinE, 500);
return;
}
if (g_seCardCur === null) {
alert("Not ready. Try in a few seconds.");
return;
}
var userCur = getUserFromCombo(comboUsers);
if (!userCur)
return; //shouldnt happen but for safety
var mapSe = getSeCurForUser(userCur, keyword);
assert(mapSe); //we checked g_seCardCur above so it should exist
if (g_bPreventIncreasedE && mapSe.e > 0 && e > 0 && !isRecurringCard()) {
alertNoIncE();
hiliteOnce(spinE, 500);
spinE.focus();
return;
}
var sTotal = parseFixedFloat(mapSe.s + s);
var eTotal = parseFixedFloat(mapSe.e + e);
if (!verifyValidInput(sTotal, eTotal))
return;
var prefix = comboDays.val() || "";
if (!prefix || prefix == g_strDateOtherOption) {
hiliteOnce(comboDays, 500);
return;
}
var valComment = comment.val();
if (s == 0 && e == 0 && valComment.length == 0) {
hiliteOnce(spinS, 500);
hiliteOnce(spinE, 500);
return;
}
if (valComment && valComment.length > 0 && valComment.trim().indexOf(PREFIX_PLUSCOMMAND) == 0) {
alert("Plus commands (starting with " + PREFIX_PLUSCOMMAND + ") cannot be entered from the S/E bar.");
hiliteOnce(comment, 500);
return;
}
function onBeforeStartCommit() {
var seBarElems = $(".agile-se-bar-table *");
seBarElems.prop('disabled', true);
$(".agile_enter_box_input").text("...");
setBusy(true);
updateCurrentSEData(true);
}
function onFinished(bOK) {
var seBarElems = $(".agile-se-bar-table *");
//enable S/E bar
setBusy(false);
seBarElems.prop('disabled', false);
$(".agile_spent_box_input").focus();
$(".agile_enter_box_input").text("Enter");
if (bOK) {
if (idCardCur == getIdCardFromUrl(document.URL)) {
if (!g_bUseLastSEBarUser)
comboUsers.val(g_strUserMeOption); //if we dont reset it, a future timer could end up in the wrong user
comboDays.val(g_strNowOption);
$("#plusCardCommentSpent").val("");
$("#plusCardCommentEstimate").val("");
$("#plusCardCommentComment").val("");
}
g_currentCardSEData.removeValue(idCardCur);
}
//reports etc will refresh in the NEW_ROWS notification handler
}
setNewCommentInCard(idCardCur, keyword, s, e, valComment, prefix, userCur, null, onBeforeStartCommit, onFinished);
});
}
buttonEnter.click(function () {
doEnter();
});
function checkEnterKey(event) {
var keycode = (event.keyCode ? event.keyCode : event.which);
if (keycode == '13') { //enter key
doEnter();
return false;
}
}
comment.keypress(checkEnterKey);
comment.bind("input", function (e) { updateCurrentSEData(); });
parentSEInput.before(container);
fillCardSEStats(tableStats, function () {
container.show();
if (!g_bNoSE)
createSEButton(parentSEInput);
insertCardTimer();
g_currentCardSEData.loadFromStorage(idCardCur, function () {
if (g_currentCardSEData.idCard != idCardCur)
return; //timing. should never happen but just in case
if (!g_currentCardSEData.s && !g_currentCardSEData.e && !g_currentCardSEData.note)
return;
var bFocus = false;
function set(elem, val, bAddIfNotThere) {
if (val && val != elem.val()) {
elem.val(val);
if (bAddIfNotThere && elem.val() != val) {
elem.append($(new Option(val, val)));
elem.val(val);
}
if (!bFocus) {
bFocus = true;
comment.focus(); //so it scrolls there if needed
}
}
}
set(comboUsers,g_currentCardSEData.user,true);
set(comboDays,g_currentCardSEData.delta, true);
set(spinS,g_currentCardSEData.s);
set(spinE,g_currentCardSEData.e);
set(comment,g_currentCardSEData.note);
if (comboKeyword)
set(comboKeyword,g_currentCardSEData.keyword, true);
updateNoteR();
if (bFocus) {
if (g_currentCardSEData.s != 0 || g_currentCardSEData.e != 0) {
if (!g_timerStatus || !g_timerStatus.bRunning || g_timerStatus.idCard != idCardCur) {
$("#plusCardCommentEnterButton").addClass("agile_box_input_hilite");
var strWhen = getTimeDifferenceAsString(g_currentCardSEData.msTime, true);
sendDesktopNotification("Card has a draft s/e row (" + strWhen + ")\n• Click 'Enter', or\n• Click the timer to unpause it, or\n• Clear the bar to forget it.", 15000);
}
}
showSEBarContainer();
}
});
});
}
var g_cacheBoardMembers = {};
function getTrelloBoardMembers(idShortBoard, msCacheMax, callback) { //callback only on success
var cached = g_cacheBoardMembers[idShortBoard];
var msNow = Date.now();
if (cached && msNow - cached.ms < msCacheMax) {
callback(cached.members);
return;
}
sendExtensionMessage({ method: "getTrelloBoardData", tokenTrello: null, idBoard: idShortBoard, fields: "memberships&memberships_member=true&memberships_member_fields=username" },
function (response) {
if (response.status != STATUS_OK || !response.board) {
sendDesktopNotification("Error while checking board memberships. (status: " + response.status+")", 5000);
return;
}
var members = response.board.memberships;
if (!members)
return;
g_cacheBoardMembers[idShortBoard] = { ms: msNow, members: members };
callback(members);
});
}
function verifyBoardMember(userLowercase, idShortBoard, callbackNotFound, callbackFound) {
assert(callbackNotFound);
getTrelloBoardMembers(idShortBoard, 0, function (members) {
for (var i = 0; i < members.length; i++) {
var member = members[i].member;
if (member && member.username && member.username.toLowerCase() == userLowercase)
break; //found
}
if (i == members.length)
callbackNotFound();
else if (callbackFound)
callbackFound();
});
}
function getSEDate(callback) {
function getDate(elemDate) {
var str = elemDate.val();
var rg = str.split("-");
if (rg.length != 3) {
return null;
}
var year = parseInt(rg[0], 10);
var month = parseInt(rg[1], 10) - 1;
var day = parseInt(rg[2], 10);
return new Date(year, month, day);
}
var divDialog = $(".agile_dialog_SEDate");
var elemDate = null;
var elemCommentDate = null;
var dateNow = new Date();
var dateMin = new Date();
dateMin.setDate(dateMin.getDate() + g_dDaysMinimum);
if (divDialog.length == 0) {
divDialog = $('\
<dialog class="agile_dialog_SEDate agile_dialog_DefaultStyle"> \
<h2>Pick a date</h2><br> \
<input id="dialog_SEDate_date" type="date"/> \
<div id="dialog_SEDate_comment"></div><br> \
<button id="agile_dialog_SEDate_ok">Select</button> \
<button id="agile_dialog_SEDate_cancel">Cancel</button> \
</dialog>');
getDialogParent().append(divDialog); //dialog inside card fixes issue with trello closing the card on clicks
divDialog = $(".agile_dialog_SEDate");
elemDate = divDialog.find("#dialog_SEDate_date");
elemCommentDate = divDialog.find("#dialog_SEDate_comment");
elemDate.change(function () {
var dateCur = getDate(elemDate);
var strMsg = "";
if (dateCur) {
var delta = getDeltaDates(new Date(), dateCur);
if (delta > 0)
strMsg = "" +delta + (delta==1? " day" : " days")+" ago.";
}
elemCommentDate.text(strMsg);
});
}
elemCommentDate = divDialog.find("#dialog_SEDate_comment");
var strDateNow = makeDateCustomString(dateNow);
elemDate = divDialog.find("#dialog_SEDate_date");
elemDate.prop("min", makeDateCustomString(dateMin));
elemDate.prop("max", strDateNow);
elemDate.prop("value", strDateNow);
elemCommentDate.text("");
divDialog.find("#agile_dialog_SEDate_cancel").off("click.plusForTrello").on("click.plusForTrello", function (e) {
callback(null);
divDialog[0].close();
});
divDialog.find("#agile_dialog_SEDate_ok").off("click.plusForTrello").on("click.plusForTrello", function (e) {
var dateCur = getDate(elemDate);
var bOK = false;
if (dateCur) {
var delta = getDeltaDates(new Date(), dateCur);
if (delta >= 0 && delta <= (-1 * g_dDaysMinimum))
bOK = true;
}
if (!bOK) {
alert("pick a date before today");
return;
}
callback(dateCur);
divDialog[0].close();
});
divDialog.off("keydown.plusForTrello").on("keydown.plusForTrello", function (evt) {
//need to capture manually before trello captures it and closes the card.
//note this doesnt cover all cases like focus being in another dialog element
if (evt.keyCode === $.ui.keyCode.ESCAPE) {
evt.stopPropagation();
callback(null);
divDialog[0].close();
}
});
showModalDialog(divDialog[0]);
}