-
Notifications
You must be signed in to change notification settings - Fork 19
/
task_adjustor.html
1971 lines (1809 loc) · 76 KB
/
task_adjustor.html
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
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Habitica Task Adjustor</title>
<base target="_blank">
<!--
This code is licenced under the same terms as Habitica:
https://raw.githubusercontent.com/HabitRPG/habitrpg/develop/LICENSE
https://github.com/Alys/tools-for-habitrpg/blob/master/task_editor.html
AND required JavaScript libraries: // XXX_SOON needed?
https://github.com/Alys/tools-for-habitrpg/blob/master/js-for-task_editor.tar.gz
https://oldgods.net/habitrpg/task_adjustor.html
Contributors:
Alys (Alice Harris), [email protected] https://github.com/Alys
-->
<meta name="description" content="Habitica Task Adjustor" />
<meta name="author" content="Alys (Alice Harris) [email protected]" />
<!-- XXX_SOON purge -->
<link href="js/DataTables/media/css/jquery.dataTables.css" rel="stylesheet" type="text/css" />
<link href="js/DataTables/extras/ColumnFilterWidgets/media/css/ColumnFilterWidgets.css" rel="stylesheet" type="text/css" />
<link href="https://cdnjs.cloudflare.com/ajax/libs/c3/0.4.10/c3.min.css" rel="stylesheet" type="text/css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.10.3/moment.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.5/d3.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/c3/0.4.10/c3.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/remarkable/1.6.2/remarkable.min.js"></script>
<script src="js/DataTables/media/js/jquery.dataTables.js"></script>
<script src="js/DataTables/extras/ColumnFilterWidgets/media/js/ColumnFilterWidgets.js"></script>
<script src="js/emoji-images/emoji-images.js"></script>
<script type="text/javascript">
$(function() { // wraps around all our code to not pollute global namespace
//////////////////////////////////////////////////////////////////////
//// Global Variables /////////////////
//////////////////////////////////////////////////////////////////////
var user; // holds user's non-task data
var tasks; // holds user's tasks
var customDayStart;
var timezoneOffset;
var todayUser;
var todayUserPretty;
var userSpecifiedDate;
var tagsForTaskId = {};
var tagsNames = {};
var tagsSelectorButtons;
// variables for recording task order and for finding errors in task ordering:
var nextTaskOrder; // counter to set order of Tasks in Habitica; also acts as unique identifier
var orderForTask; // populated from user.tasksOrder - key is a task ID, value is that task's order from the nextTaskOrder counter.
var taskIdsFoundInTasksOrder; // initially is populated with all task IDs that are in the user.tasksOrder arrays. Later, tasks IDs are removed from it as the actual tasks are found, leaving only IDs for tasks that don't exist
var tasksWithNoOrder; // contains IDs of tasks we find that aren't in the user.tasksOrder arrays
//////////////////////////////////////////////////////////////////////
//// Global Connection Variables //////////////////////////////
//////////////////////////////////////////////////////////////////////
var serverName = 'Habitica'; // used in "loading" message
var serverUrl = 'https://habitica.com:443/api/v3';
var clientId = 'd904bd62-da08-416b-a816-ba797c9ee265-TaskAdjustor';
var userId = '';
var apiToken = '';
var debug = false;
/* TST - FOR TESTING:
userId = '3e595299-3d8a-4a10-bfe0-88f555e4aa0c';
apiToken = ''; // TST - DO NOT LET THIS GO LIVE!
$('body').css({'background-color':'#C4B4A4'});
$('#userApiDetailsForm #userId').val(userId);
$('#userApiDetailsForm #apiToken').val(apiToken);
fetchData();
*/
if (debug) console.log('debug 1');
//////////////////////////////////////////////////////////////////////
//// This function decodes -> renders markdown ////////////
//// -> escapes HTML entities -> and renders emoji ////////////
//////////////////////////////////////////////////////////////////////
var md = new Remarkable({
'html': false,
'linkify': true,
'linkTarget': '_blank',
}); // markdown parser
function renderFormattedText(text) {
function renderMarkdown(text) {
text = md.render(text);
return text;
}
function renderEmoji(text) {
return emoji(text, 'js/emoji-images/pngs', 25);
}
return renderEmoji(
renderMarkdown(
String(text).replace(/\ /g, ' ')
)
);
}
//////////////////////////////////////////////////////////////////////
//// Functions for working with tags ////////////////////////////
//////////////////////////////////////////////////////////////////////
function countNumberOfTagsForTask(taskId) {
return tagsForTaskId[taskId] ? tagsForTaskId[taskId].length : 0;
}
function displayNumberOfTagsForTask(taskId) {
var count = countNumberOfTagsForTask(taskId);
if (count === 0) return '<em>no tags</em>';
if (count === 1) return '1 tag';
return count + ' tags';
}
function displayTagNamesForTask(taskId, opt) {
if (!opt.joiner) opt.joiner = '<br />';
// opt.showNotTagged -- default false
// opt.formatText -- default false
var output = []
$.each(user.tags, function(index, tag) {
var taskContainsTag = tagsForTaskId[taskId].indexOf(tag.id) > -1;
if (( opt.showNotTagged && !taskContainsTag) ||
(!opt.showNotTagged && taskContainsTag)
) {
var name = tagsNames[tag.id];
if (opt.formatText) name = renderFormattedText(name);
output.push(name);
}
});
return output.join(opt.joiner);
}
//////////////////////////////////////////////////////////////////////
//// Allow Show/Hide Toggling to work ///////////////////////////
//////////////////////////////////////////////////////////////////////
enableShowHideToggling(); // needed here to enable Version Changes link
function enableShowHideToggling() {
// $('.showHideToggle').click(function(event)
$('body').on('click', '.paneCloser', function(event){
$(this).parent().hide();
});
$('body').on('click', '.showHideToggle', function(event){
var target = $(this).data("target");
var wantToShow = (! $('#' + target).is(':visible')
|| $(this).data("forceopen"));
// wantToShow is false if the target is already open
// (i.e., the user wants to close it)
// unless the toggle's attributes force it to always be
// opened (e.g., a link from the dashboard)
var linktext = $(this).data("linktext") || false;
if ($(this).data("closemainsections")) {
$('#MAIN > *').hide();
}
if (wantToShow) {
sectionOpen = target;
$('#' + target).show();
if (linktext) {
$(this).text('hide ' + linktext);
}
}
else {
$('#' + target).hide();
if (linktext) {
$(this).text('show ' + linktext);
}
if ($(this).data("scrolltotop")) {
window.scrollTo(0, 0);
}
}
var toggleTarget = $(this).data("resettoggletext") || false;
if (toggleTarget) {
$('#' + toggleTarget).text('show '
+ $('#' + toggleTarget).data("linktext"));
}
});
$('body').on('click', '.mainSectionClose', function(event){
$('#MAIN > *').hide();
window.scrollTo(0, 0);
});
}
//////////////////////////////////////////////////////////////////////
//// Perform selected action ////////////////////////////////////
//////////////////////////////////////////////////////////////////////
$('body').on('click', '.selector', function(event){
var taskId = $(this).parent().data('task');
var field = $(this).parent().data('field');
var fieldExtra = $(this).parent().data('fieldextra');
var type = $(this).parent().data('type');
var output = $(this).parent().data('output');
var outputExtra = $(this).parent().data('outputextra');
var newValue = $(this).data('newvalue');
var newValueExtra = $(this).data('newvalueextra');
var newValueFrom = $(this).data('newvaluefrom');
var newValuePretty = $(this).data('newvaluepretty');
var newValueOutputExtra = '';
var data = {};
if (newValueFrom && ! newValue) {
newValue = $('#' + newValueFrom).val();
}
if (type === 'date') {
if (newValue === 'noDate') {
newValue = '';
newValuePretty = 'none';
}
else {
if (newValue === 'today') {
newValue = moment(todayUser);
}
else if (newValue === 'todayPlus') {
newValue = moment(todayUser).add(24 * newValueExtra, 'hours');
}
else if (newValue === 'nextDayOfWeek') {
if (todayUser.day() === newValueExtra) {
newValueExtra = newValueExtra + 7; // NEXT day of week
}
newValue = moment(todayUser).day(newValueExtra);
}
else if (newValue === 'startOfMonth') {
newValue = moment(todayUser).startOf('month').add(1, 'month');
}
else if (newValue === 'userSpecifiedDate') {
// reuse a date we specified previously
newValue = moment(userSpecifiedDate);
}
else { // user-specified date
if(!/^\d{4}-\d{2}-\d{2}$/.test(newValue)) {
$(this).siblings('.status').html(newValue +
' is<br / >wrong date format!<br />Use yyyy-mm-dd');
$(this).siblings('.status').addClass('error');
return;
}
userSpecifiedDate = newValue; // allow date to be reused
newValue = moment(newValue);
// enable the form that allows this date to be reused:
$(".userSpecifiedDate").text(userSpecifiedDate);
$(".userSpecifiedDate").removeClass('hide');
}
// Convert from user's timezone to server timezone (UTC+0) for
// storage, and add custom day start to deal with Daily start
// dates correctly:
// NB: timezoneOffset is, for example, -600 for GMT+10
newValue = moment(newValue).add(timezoneOffset, 'minutes').
add(customDayStart, 'hours');
// format stored in database:
newValue = moment(newValue).format('YYYY-MM-DDTHH:mm:SS.000') + 'Z';
// format for display in this tool:
newValuePretty = moment(newValue).format('YYYY-MM-DD');
}
}
else if (type === 'boolean') {
if (newValue === true) {
newValuePretty = 'yes';
}
else {
newValuePretty = 'no';
}
}
else if (type === 'tags') {
// For changing tags, newValue initially contains just the ID of the
// one tag to assign or unassign, not the full set of new data to be
// submitted.
var tagId = newValue;
// Now we make newValue hold the full set of tags for that task:
newValue = tagsForTaskId[taskId];
var index = newValue.indexOf(tagId);
if (index === -1) {
// task does not currently have this tag - we are adding it
newValue.push(tagId);
}
else {
// we are removing the tag
newValue.splice(index, 1);
}
tagsForTaskId[taskId] = newValue;
newValuePretty = displayNumberOfTagsForTask(taskId);
newValueOutputExtra = displayTagNamesForTask(taskId, {formatText:true});
}
data[field] = newValue;
$(this).siblings('.status').text('updating...');
$.ajax({
url: serverUrl + '/tasks/' + taskId,
context: $(this),
type: 'PUT',
contentType: 'application/json', // needed for passing true/false
data: JSON.stringify(data), // needed for passing true/false
dataType: 'json',
cache: false,
beforeSend: function(xhr) {
xhr.setRequestHeader('x-client', clientId);
xhr.setRequestHeader('x-api-user', userId);
xhr.setRequestHeader('x-api-key', apiToken);
},
success: updateTaskSuccess,
error: updateTaskFailure,
});
function updateTaskSuccess() {
$('#' + output).html(newValuePretty || newValue);
if (outputExtra) {
$('#' + outputExtra).html(newValueOutputExtra);
}
$(this).siblings('.status').text('');
$(this).removeClass('error');
$(this).parent().hide();
var row = $(this).parents('tr').children('td');
row.removeClass('uncertain');
row.addClass('justChanged');
setTimeout(function(row) {
row.removeClass('justChanged');
row.addClass('uncertain');
}, 1000, row);
}
function updateTaskFailure(data) {
$(this).siblings('.status').text('Update failed! Try again. ' + taskId);
$(this).siblings('.status').addClass('error');
}
});
//////////////////////////////////////////////////////////////////////
//// Get UUID from URL ////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
var url_vars = getUrlVars();
if (url_vars.uuid) {
$("#userId").val(url_vars.uuid);
}
function getUrlVars() {
// Function found at http://stackoverflow.com/questions/4656843/jquery-get-querystring-from-url#answer-4656873
var vars = [], hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for(var i = 0; i < hashes.length; i++)
{
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
}
//////////////////////////////////////////////////////////////////////
//// Login events /////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
$('#userApiDetailsForm').submit(function(event){
/* The user manually submitted the API connection form. */
userId = $('#userId').val();
apiToken = $('#apiToken').val();
fetchData();
});
//////////////////////////////////////////////////////////////////////
//// Login and Data Fetch Functions //////////////////////////////
//////////////////////////////////////////////////////////////////////
function fetchData() {
var ajaxRunningCount = 2; // drops to 0 when all calls have succeeded
if (debug) console.log('debug 2');
$('#loading #serverName').text(serverName);
$('#loading .good').show();
$('#loading .bad' ).hide();
$.ajax({
url: serverUrl + '/user',
type: 'GET',
dataType: 'json',
cache: false,
beforeSend: function(xhr){
xhr.setRequestHeader('x-client', clientId);
xhr.setRequestHeader('x-api-user', userId);
xhr.setRequestHeader('x-api-key', apiToken);
},
success: fetchUserSuccess,
error: fetchFailure
});
$.ajax({
url: serverUrl + '/tasks/user',
type: 'GET',
dataType: 'json',
cache: false,
beforeSend: function(xhr){
xhr.setRequestHeader('x-client', clientId);
xhr.setRequestHeader('x-api-user', userId);
xhr.setRequestHeader('x-api-key', apiToken);
},
success: fetchTasksSuccess,
error: fetchFailure
});
function fetchFailure() {
if (debug) console.log('debug fetchFailureUser start');
$('#loading .good').hide();
$('#loading .bad' ).show();
$('#documentationAndForm').show(); // in case user has done a re-fetch
$('#documentationAndFormClose').hide();
if (debug) console.log('debug fetchFailureUser end');
}
function fetchUserSuccess(data) {
if (debug) console.log('debug parseData User success start');
user = data.data;
ajaxRunningCount--;
if (ajaxRunningCount === 0) { // all ajax calls have finished
parseData();
}
}
function fetchTasksSuccess(data) {
if (debug) console.log('debug parseData Tasks success start');
tasks = data.data;
ajaxRunningCount--;
if (ajaxRunningCount === 0) { // all ajax calls have finished
parseData();
}
}
}
function parseData() {
if (debug) console.log('debug parseData start');
// variables for storing the content:
var MAIN = {}; // XXX_SOON improve
// save the fetch time early:
var fetchtime = myDateConverter(new Date(), 'pretty');
// extract some commonly-used data:
customDayStart = user.preferences.dayStart || 0; // CDS
timezoneOffset = user.preferences.timezoneOffset || 0;
// Find the correct date for "today". If the user has a CDS set, then
// we need to subtract the CDS hour from the current date and time to
// see if today is actually "yesterday". E.g., if the CDS is 5am, and
// the user is using this tool at 4am on Monday, then the actual
// "Habitica day" is Sunday (not Monday) because the CDS time has not
// yet been reached; subtracting 5 hours from the current date and time
// gives us yesterday's date. We then ignore the time portion of the
// date because from now on we're comparing only days, not hours.
todayUser = moment().subtract(customDayStart, 'hours');
todayUser = todayUser.startOf('day');
todayUserPretty = moment(todayUser).format('YYYY-MM-DD');
tagsSelectorButtons = ''; // needed in case we're re-fetching data now
tagsNames = {}; // needed in case we're re-fetching data now
$.each(user.tags, function(index, tag) {
tagsNames[tag.id] = tag.name;
tagsSelectorButtons += '<button class="selector"' +
' data-newvalue="' + tag.id + '"' +
'>' + renderFormattedText(tag.name) + '</button><br />\n';
});
userDataInHeader();
collateAndDisplayTaskData();
//////////////////////////////////////////////////////////////////////
//// Display the HTML that the functions have created ////////////
//////////////////////////////////////////////////////////////////////
$('#loading .good').hide();
$('#documentationAndFormClose').show();
$('#documentationAndForm').hide();
formatAndDisplayMAIN(); // XXX_SOON improve
// everything below here is functions used within this function
function formatAndDisplayMAIN() { // XXX_SOON purge
var keys = ['taskOverview'];
var html = '';
var functions = []; // functions to run after HTML code has been loaded
for (var i=0,ic=keys.length; i<ic; i++) {
var data = MAIN[keys[i]];
if (! data) {
continue;
}
html += '<div id="' +
data.id + '">' +
data.html +
'</div>';
if (data['function']) {
functions.push(data['function']);
}
}
$('#MAIN').html(html);
// execute any functions that need to be run AFTER the bulk of the
// HTML has been created:
$.each(functions, function(index,fn){
fn();
});
}
function myDateConverter(date, style) { // XXX_SOON replace with moment
if (typeof date === 'string' || typeof date === 'number') {
date = new Date(date);
}
if (!date || isNaN(date.getTime())) {
// Either the object that was passed in is not a Date object,
// OR the date string that was passed in could not be converted
// to a Date object, presumably because it's in a non-standard
// format. We handle this by using today's date. It's a nasty
// hack, but it's unlikely to occur, and no one's paying for
// anything better.
date = new Date();
}
if (style === 'pretty') {
// Format date as (weekday date month) and hh:mm:ss;
// toDateString ordering might be locale-specific
// var dateStr = date.toDateString().split(' ').slice(0,3).join(' ') +
// ' ' + date.toTimeString().split(' ')[0];
var dateStr = date.toLocaleString(undefined,
{ weekday: 'long', day: 'numeric', month: 'long',
hour: '2-digit', minute: '2-digit' });
}
else {
var y = date.getFullYear();
var m = date.getMonth() + 1;
var d = date.getDate();
var H = date.getHours();
var M = date.getMinutes();
var S = date.getSeconds();
var dateStr = y +
'-' + (m<=9 ? '0'+m : m) +
'-' + (d<=9 ? '0'+d : d);
if (style === 'short') {
dateStr = dateStr.replace(/^20/, ""); // remove century
}
if (style === 'long') {
dateStr += ' ' + (H<=9 ? '0'+H : H) +
':' + (M<=9 ? '0'+M : M) +
':' + (S<=9 ? '0'+S : S);
}
}
return dateStr;
}
function pluralise(word, number) {
var lcWord = word.toLowerCase();
var needUpperCase = (lcWord == word) ? false : true;
if (number != 1) {
var pluralWords = {
'has': 'have',
'it': 'them',
'this': 'these',
'is': 'are',
'daily': 'dailies',
'Daily': 'Dailies',
};
if (pluralWords[lcWord]) { word = pluralWords[lcWord]; }
else { word += 's'; }
}
if (needUpperCase) { // must improve this if ever need ALL upper case
word = upperCaseFirst(word);
}
return word;
}
function displayNumberWithPluralisation(number, word) {
return number + ' ' + pluralise(word, number);
}
function upperCaseFirst(word) {
return word.charAt(0).toUpperCase() + word.slice(1);
}
function userDataInHeader() {
// var displayName = renderFormattedText(user.profile.name);
var userName = user.auth.local.username;
$('#headerExtras').html('<div id="userNameDisplay">' +
'@' + userName +
'</div>' +
'<div id="explanationAndClearLinks">' +
'<input id="refetch" type="submit" value="' +
'Re-Fetch Data (last fetched ' + fetchtime + ')" />' +
// '<span id="documentationAndFormToggle" class="showHideToggle" data-target="documentationAndForm" data-linktext="documentation" data-closemainsections="true">show documentation</span>' +
'</div>'
);
$('#refetch').click(function(event){
/* The user clicked on the Re-Fetch My Data button. */
fetchData();
});
}
function collateAndDisplayTaskData() {
// Set up data structures for storing task information:
var allTasks = [];
var count = {'habit':0, 'daily':0, 'todo':0, 'reward':0};
// var valueMin = -47.27; // task values are capped ...
// var valueMax = 21.27; // ... for some purposes
// Define some static stuff:
var attributesPretty = { 'str': 'Physical (STR)',
'int': 'Mental (INT)',
'con': 'Social (CON)',
'per': 'Other (PER)',
};
var entityMap = { "&": "&",
"<": "<",
">": ">",
'"': '"',
"'": ''',
"/": '/'
};
var colours = { 1: {'order':1, 'name':'Bright Blue',
'label': '1) Bright Blue',
'nameNoSpace': 'BrightBlue',
'id': 'colourBrightBlue'
},
2: {'order':2, 'name':'Blue Grey',
'label': '2) Blue Grey',
'nameNoSpace': 'BlueGrey',
'id': 'colourBlueGrey'
},
3: {'order':3, 'name':'Green',
'label': '3) Green',
'nameNoSpace': 'Green',
'id': 'colourGreen'
},
4: {'order':4, 'name':'Yellow',
'label': '4) Yellow',
'nameNoSpace': 'Yellow',
'id': 'colourYellow'
},
5: {'order':5, 'name':'Orange',
'label': '5) Orange',
'nameNoSpace': 'Orange',
'id': 'colourOrange'
},
6: {'order':6, 'name':'Red',
'label': '6) Red',
'nameNoSpace': 'Red',
'id': 'colourRed'
},
7: {'order':7, 'name':'Dark Red',
'label': '8) Dark Red',
'nameNoSpace': 'DarkRed',
'id': 'colourDarkRed'
}
};
// find the order the tasks are in - first initialise some variables (needed in case we're re-fetching data now):
nextTaskOrder = 0;
orderForTask = {};
taskIdsFoundInTasksOrder = {'habit':[], 'daily':[], 'todo':[], 'reward':[]};
tasksWithNoOrder = {'habit':[], 'daily':[], 'todo':[], 'reward':[]};
$.each(user.tasksOrder.habits, function(index, taskId){
orderForTask[taskId] = nextTaskOrder;
nextTaskOrder++;
taskIdsFoundInTasksOrder['habit'].push(taskId);
});
$.each(user.tasksOrder.dailys, function(index, taskId){
orderForTask[taskId] = nextTaskOrder;
nextTaskOrder++;
taskIdsFoundInTasksOrder['daily'].push(taskId);
});
$.each(user.tasksOrder.todos, function(index, taskId){
orderForTask[taskId] = nextTaskOrder;
nextTaskOrder++;
taskIdsFoundInTasksOrder['todo'].push(taskId);
});
$.each(user.tasksOrder.rewards, function(index, taskId){
orderForTask[taskId] = nextTaskOrder;
nextTaskOrder++;
taskIdsFoundInTasksOrder['reward'].push(taskId);
});
var everyXDaysInUse = false;
collateTasksData(); // populates the function's "global" variables defined above
// Report any tasksOrder errors:
var taskOrderErrors = '';
$.each(['habit', 'daily', 'todo', 'reward'], function(index, type) {
if (taskIdsFoundInTasksOrder[type].length) {
taskOrderErrors += '* ' + type + ' tasksOrder entries with no matching tasks: "' +
taskIdsFoundInTasksOrder[type].join('", "') + '"' + '<br />';
}
if (tasksWithNoOrder[type].length) {
taskOrderErrors += '* ' + type + ' tasks with no tasksOrder: "' +
tasksWithNoOrder[type].join('", "') + '"' + '<br />';
}
});
if (taskOrderErrors) {
$('#taskOrderErrorsMessage').html("Your account has a minor problem that might prevent you from sorting your tasks correctly. Habitica's staff can fix this for you. On the <a href=\"https://habitica.com/\">Habitica website</a>, go to Help > Report a Bug and paste the message below into your bug report.<hr /><br />My Habitica account has the tasksOrder bug:<br />" + taskOrderErrors + "<br /><hr />");
$('#taskOrderErrorsMessage').removeClass('hide');
}
else {
$('#taskOrderErrorsMessage').html("");
$('#taskOrderErrorsMessage').addClass('hide');
}
if (allTasks.length > 50) {
var some = 'a few';
if (allTasks.length > 100) some = 'several';
if (allTasks.length > 200) some = 'many';
$('#taskNumberMessage').text('You have ' +
displayNumberWithPluralisation(count['habit'], 'Habit') + ', ' +
displayNumberWithPluralisation(count['daily'], 'Daily') + ', ' +
displayNumberWithPluralisation(count['todo'], 'To-Do') + ', and ' +
displayNumberWithPluralisation(count['reward'], 'Reward')+
'. It might take ' + some +
' seconds before this page becomes responsive.');
$('#taskNumberMessage').removeClass('hide');
setTimeout(function() {
$('#taskNumberMessage').addClass('hide');
}, 20000);
}
// display task data:
taskOverview();
function collateTasksData() {
tagsForTaskId = {}; // needed in case we're re-fetching data now
$.each(tasks, function(index, obj){
// if (obj.text === 'copy weekly delabora backup') { // TST - FOR TESTING
count[obj.type]++;
if (obj.type === 'daily') {
fixDailiesDefaults(obj);
}
else if (obj.type === 'todo') {
obj.isDue = (obj.date &&
moment(obj.date).zone(timezoneOffset).startOf('day') <=
todayUser) ? true : false;
}
modifyTaskProperties(obj);
allTasks.push(obj);
// }
});
function fixDailiesDefaults(task) {
// Ensure that all repeat options make sense. At least one bug
// can result in bad repeat options:
// github.com/HabitRPG/habitrpg/issues/2334#issuecomment-66168155
// EDIT: IGNORE THIS COMMENT FOR NOW:
// If we find unexpected or missing repeat values, we set a flag
// that causes the Daily to be treated as due (safer than treating
// as not due - better to let the user think they will take more
// damage than they actually do).
//
// EDIT: While the Habitica api.shouldDo code and this code are
// being tweaked, we use the same behaviour here for Dailies that
// have incorrect or missing options. I.e., we treat the Dailies
// as not due because that is what Habitica does.
// task.forceDue = false;
task.forceNotDue = false;
if (!task.frequency ||
(task.frequency !== 'weekly' && task.frequency !== 'daily')) {
task.frequency = 'weekly';
// task.forceDue = true;
task.forceNotDue = true;
}
if (task.frequency === 'weekly') { // Day of Week
if (!task.repeat) {
task.repeat = { "su": true, "s": true, "f": true,
"th": true, "w": true, "t": true, "m": true };
// task.forceDue = true;
task.forceNotDue = true;
}
}
else if (task.frequency === 'daily') { // Every X Days
if (typeof task.everyX === 'undefined') { // can be zero
task.everyX = 1;
// task.forceDue = true;
task.forceNotDue = true;
}
}
if (!task.startDate) {
// This should not happen, but if it does, Habitica's code
// treats it as starting on the day being examined (i.e., today
// for the purposes of showing due Dailies). Hence we do the
// same and we don't set forceDue.
task.startDate = todayUser;
}
}
function dailyIsDueToday(task) { // ref: api.shouldDo
// returns true if the Daily is due, false otherwise
if (task.forceDue) {
return true;
}
if (task.forceNotDue) {
return false;
}
var startDate = moment(task.startDate).zone(timezoneOffset).startOf('day');
if (startDate > todayUser) {
return false;
}
if (task.frequency === 'weekly') { // Day of Week
var dayname = ["su","m","t","w","th","f","s"][todayUser.day()];
return task.repeat[dayname];
}
else if (task.frequency === 'daily') { // Every X Days
if (task.everyX > 1) { // bug not relevant if due EVERY day
everyXDaysInUse = true;
}
var daysSinceTaskStart = todayUser.diff(startDate, 'days');
return (daysSinceTaskStart % task.everyX == 0);
}
}
}
function modifyTaskProperties(obj) { // XXX_SOON purge
obj.text = renderFormattedText(obj.text);
obj.notes = renderFormattedText(obj.notes);
obj.attributePretty = attributesPretty[obj.attribute];
obj.typePretty = upperCaseFirst(
(obj.type == 'todo') ? 'To-Do' : obj.type );
if (obj.type === 'todo' && obj.completed === true) {
obj.typePretty += ' Done';
}
obj.metaType = (obj.type === 'daily' || obj.type === 'todo') ?
'dated' : 'undated';
obj.valueRounded = Math.round(obj.value * 100) / 100;
obj.magnitude = Math.abs(obj.valueRounded);
obj.creation = reformatDate(obj.dateCreated);
obj.completion = (obj.dateCompleted) ?
reformatDate(obj.dateCompleted) : {};
obj.colour = chooseColour(obj.value);
obj.valueColourHtml = '<span class="coloured ' +
obj.colour.id + '">' +
obj.valueRounded + '<br />' +
obj.colour.nameNoSpace + '</span>';
obj.difficulty = chooseDifficulty(obj.priority);
if (obj.type == 'daily') {
obj.startDatePretty = moment(obj.startDate).format('YYYY-MM-DD');
}
if (obj.type == 'todo') {
obj.datePretty =
(obj.date) ? moment(obj.date).format('YYYY-MM-DD') : 'none';
}
obj.attributesHTML = '<div class="taskAttributes ' + obj.type + '">' +
attributesHTML() + '</div>';
// remove tags that don't exist:
var knownTags = [];
$.each(obj.tags, function(index, tagId) {
if (tagsNames[tagId]) knownTags.push(tagId);
});
obj.tags = knownTags;
// store tags for tasks in a separate structure because we won't
// always have easy access to the task's object:
tagsForTaskId[obj.id] = obj.tags || [];
// set task order and warn about bad order configs:
if (typeof orderForTask[obj.id] !== 'undefined') {
obj.order = orderForTask[obj.id];
var index = taskIdsFoundInTasksOrder[obj.type].indexOf(obj.id);
if (index > -1) {
taskIdsFoundInTasksOrder[obj.type].splice(index, 1);
}
}
else {
tasksWithNoOrder[obj.type].push(obj.id);
obj.order = nextTaskOrder;
nextTaskOrder++;
}
function reformatDate(dateString) {
var formattedDate = myDateConverter(dateString, 'long');
var shortDate = myDateConverter(dateString, 'short');
return { 'dateAndTime': formattedDate,
'shortDate': shortDate };
}
function chooseColour(value) {
// from http://habitica.fandom.com/wiki/Task_Value :
// Bright Blue Greater than 10
// Blue Grey Between 5 and 10
// Green Between 1 and 5
// Yellow Between -1 and 1
// Orange Between -10 and -1
// Red Between -20 and -10
// Dark Red Less than -20
if (value < -20){ return colours[7]; }
else if (value < -10){ return colours[6]; }
else if (value < -1){ return colours[5]; }
else if (value < 1){ return colours[4]; }
else if (value < 5){ return colours[3]; }
else if (value < 10){ return colours[2]; }
else { return colours[1]; }
}
function chooseDifficulty(value) {
if (value == 0.1){ return 'trivial'; }
else if (value == 1 ){ return 'easy'; }
else if (value == 1.5){ return 'medium'; }
else if (value == 2 ){ return 'hard'; }
else { return 'unknown (' + value + ')'; }
}
function attributesHTML() {
if (obj.type == 'habit') {
return taskPartHTML(obj.up, '+') +
taskPartHTML(obj.down, '–');
}
else if (obj.type == 'daily') {
var startDateDescription = '';
if (moment(obj.startDate).isAfter(todayUser)) {
startDateDescription = '<br style="line-height:150%;" />' +
taskPartHTML(obj.isDue, 'starts ' +
obj.startDatePretty,
true);
}
if (obj.frequency === 'weekly') {
return taskPartHTML(obj.repeat['su'], 'Su') +
taskPartHTML(obj.repeat['m' ], 'Mo') +
taskPartHTML(obj.repeat['t' ], 'Tu') +
taskPartHTML(obj.repeat['w' ], 'We') +
taskPartHTML(obj.repeat['th'], 'Th') +
taskPartHTML(obj.repeat['f' ], 'Fr') +
taskPartHTML(obj.repeat['s' ], 'Sa') +
startDateDescription;
}
else if (obj.frequency === 'daily') {
return taskPartHTML(obj.isDue,
'every ' + obj.everyX + ' days') +
startDateDescription;
}
}
else if (obj.type == 'todo') {
return obj.date == null ?
'<span class="attributeOff">(no date)</span>' :
obj.date.substr(0, 10);
}
else {
return '';
}
}
function taskPartHTML(val, txt) {
return ' <span class="' +
(val ? 'attributeOn' : 'attributeOff') + '">' +
txt + '</span>';
}
}
function taskOverview() {
var title = 'Task Overview';
var id = 'taskOverviewSection';
var orderId = 'taskOverview';
sectionOpen = id; // XXX_SOON improve
MAIN[orderId] = {'id': id, 'title': title, 'longContent': true,
'function': createTaskOverviewTable,
'html':
'<div id="taskOverviewDeveloperDataToggle" class="showHideToggleClass" title="show/hide task IDs and dateCreated strings">toggle developer data</div>' +
'<table></table>'
};
function createTaskOverviewTable() {
var notApplicable = '<span class="notApplicable">n/a</span>';
// Use DataTables to build the table (the table tag must be
// visible first for layout to be correct):
$('#taskOverviewSection').show();
$('#taskOverviewSection table').dataTable({
'aaData': allTasks,
'aoColumns': [
{ 'sTitle': 'order in Habitica', 'sClass': 'center', 'sWidth':'10%',
'mData' : 'order', 'bVisible': false,
},
{ 'mData' : 'typePretty', 'sClass': 'center',
'sTitle': 'type', 'sWidth': '10%',
},
{ 'sTitle': 'attribute', 'sClass': 'center', 'sWidth': '10%',
'mData': function ( source, type, val ) {
if (type === 'set') {
return;