- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtimer.js
More file actions
Latest commit
594 lines (523 loc) · 19.5 KB
/
Copy pathtimer.js
File metadata and controls
594 lines (523 loc) · 19.5 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
// ISO 8601 week number (week starts Monday, week 1 contains the first Thursday).
functionisoWeekNumber(date){
constd=newDate(Date.UTC(date.getFullYear(),date.getMonth(),date.getDate()));
constdayNum=d.getUTCDay()||7;
d.setUTCDate(d.getUTCDate()+4-dayNum);
constyearStart=newDate(Date.UTC(d.getUTCFullYear(),0,1));
returnMath.ceil((((d-yearStart)/86400000)+1)/7);
}
functionloadJiraSubdomain(){
conststored=localStorage.getItem('simpletimer.jiraSubdomain');
if(stored!==null)returnstored;
// one-time migration from the old full-URL key
constoldUrl=localStorage.getItem('simpletimer.jiraBaseUrl');
if(oldUrl){
constm=oldUrl.match(/^https?:\/\/([^./]+)\.atlassian\.net\/browse\/?$/i);
localStorage.removeItem('simpletimer.jiraBaseUrl');
if(m){
localStorage.setItem('simpletimer.jiraSubdomain',m[1]);
returnm[1];
}
}
return'';
}
// id must match the [data-theme=...] selectors in restyle.css. swatch mirrors
// that theme's --g1/--g2 ring gradient; light gets a hard split instead of a
// blend so it reads as "the light one" rather than as another orange.
constTHEMES=[
{id: 'light',label: 'Light',meta: '#DC5934',
swatch: 'linear-gradient(135deg, #FFFFFF 0 50%, #F26C44 50% 100%)'},
{id: 'dark-sunset',label: 'Sunset',meta: '#131315',
swatch: 'linear-gradient(135deg, #FFC46B, #FF7A4D)'},
{id: 'dark-lagoon',label: 'Lagoon',meta: '#131315',
swatch: 'linear-gradient(135deg, #6FE8C4, #3FBEDC)'},
{id: 'dark-twilight',label: 'Twilight',meta: '#131315',
swatch: 'linear-gradient(135deg, #7FA6FF, #B08BFF)'},
{id: 'dark-glow',label: 'Glow',meta: '#131315',
swatch: 'linear-gradient(135deg, #B79BFF, #FF7ABF)'},
];
functionloadTheme(){
conststored=localStorage.getItem('simpletimer.theme');
returnTHEMES.some(function(t){returnt.id===stored;}) ? stored : 'light';
}
functionapplyTheme(id){
document.documentElement.setAttribute('data-theme',id);
// keep the mobile status bar in step with the theme
consttheme=THEMES.find(function(t){returnt.id===id;});
constmeta=document.querySelector('meta[name="theme-color"]');
if(theme&&meta)meta.setAttribute('content',theme.meta);
}
// What each adjust button makes of a value, as pure functions. The button and the
// hover preview both go through this table, so the preview can never disagree with
// what pressing actually does. All four snap to a quarter or an hour and drop the
// remainder — that is deliberate, but it means the change is not always the amount
// on the button, which is exactly why the preview is worth showing.
constADJUST={
addHour: function(s){returns+3600;},
removeHour: function(s){returnMath.max(s-3600,0);},
addQuarter: function(s){returnMath.floor((s+900)/900)*900;},
removeQuarter: function(s){returnMath.max(Math.ceil((s-900)/900)*900,0);},
};
// Task colours are stepped through the palette by task id rather than by hash or by
// list position. Ids are handed out in ascending order, so the spread is the same as
// by position, but a colour then survives a removal or a re-sort — with positions,
// deleting one task recoloured every task below it. STEP is coprime with
// TASK_COLOUR_COUNT, so all eight are used before the sequence wraps around.
constTASK_COLOUR_COUNT=8;
constTASK_COLOUR_STEP=3;
// Task ids must never be derived from the list length: after a removal the next
// id would collide with an existing one, and Vue uses id as the :key — two rows
// sharing a key means it can reuse the wrong DOM node.
letnextTaskId=0;
functionloadDayGoal(){
conststored=parseFloat(localStorage.getItem('simpletimer.dayGoalHours'));
returnNumber.isFinite(stored)&&stored>0 ? stored : 8;
}
// radius of the header goal ring, kept in sync with the <circle r> in index.html
constGOAL_RING_CIRCUMFERENCE=2*Math.PI*17;
varapp=newVue({
// app initial state
data: {
workDay: null,//WeekDay.loadDay(),
tasks: [],//WeekDay.loadTasks(),
newTask: '',
beforeEditCache: null,
editedTask: null,
timedTask: null,
viewMode: 'tasks',
timerReadable: '',
elapsedSeconds: 0,
// separate from timedTask, which lingers for 320ms so the focus view can
// slide out. elapsedSeconds lingers with it, so without this flag the day
// total would count the finished session twice during that window.
timerRunning: false,
timerInterval: null,
totalReadable: '',
todaysDate: newDate().toLocaleDateString(),
todaysWeek: isoWeekNumber(newDate()),
startedAt: 0,
jiraSubdomain: loadJiraSubdomain(),
jiraSubdomainDraft: '',
dayGoalHours: loadDayGoal(),
dayGoalDraft: '',
hoveredSegment: null,
draggedTask: null,
preview: null,
themes: THEMES,
theme: loadTheme(),
themeDraft: '',
settingsOpen: false
},
computed: {
jiraBaseUrl: function(){
returnthis.jiraSubdomain
? 'https://'+this.jiraSubdomain+'.atlassian.net/browse/'
: '';
},
jiraUrlPreview: function(){
constsub=this.jiraSubdomainDraft.trim();
returnsub ? 'https://'+sub+'.atlassian.net/browse/' : '';
},
// proportional make-up of the day. The denominator is the goal, or the total
// once that runs past it, so the bar never overflows its own track.
dayBarSegments: function(){
varscale=Math.max(this.totalSeconds,this.dayGoalSeconds)||1;
varself=this;
returnthis.tasks.map(function(task){
return{
id: task.id,
title: task.title,
colour: self.taskColour(task),
width: self.liveSeconds(task)/scale*100+'%',
readable: self.formatSecondsAsReadable(self.liveSeconds(task),false)
};
});
},
// only shown once the day runs over the goal, marking where the goal sat
dayBarGoalLeft: function(){
if(this.totalSeconds<=this.dayGoalSeconds)returnnull;
return(this.dayGoalSeconds/this.totalSeconds*100)+'%';
},
dayBarRemaining: function(){
varleft=this.dayGoalSeconds-this.totalSeconds;
returnleft>0
? this.formatSecondsAsReadable(left,false)+' to go'
: this.formatSecondsAsReadable(-left,false)+' over';
},
themeLabel: function(){
constdraft=this.themeDraft;
consttheme=THEMES.find(function(t){returnt.id===draft;});
returntheme ? theme.label : '';
},
// live day total — includes the session currently running, so the goal
// ring keeps creeping up instead of only jumping on stop
totalSeconds: function(){
varsum=0;
this.tasks.forEach(function(task){
sum+=task.secondsSpent;
});
returnsum+(this.timerRunning ? this.elapsedSeconds : 0);
},
dayGoalSeconds: function(){
returnthis.dayGoalHours*3600;
},
// 0..1 — first lap of the goal ring
goalFraction: function(){
if(this.dayGoalSeconds<=0)return0;
returnMath.min(this.totalSeconds/this.dayGoalSeconds,1);
},
// 0..1 — anything beyond the goal, drawn as a second lap on top
goalOvertimeFraction: function(){
if(this.dayGoalSeconds<=0)return0;
returnMath.min(Math.max(this.totalSeconds/this.dayGoalSeconds-1,0),1);
},
goalOffset: function(){
returnGOAL_RING_CIRCUMFERENCE*(1-this.goalFraction);
},
goalOvertimeOffset: function(){
returnGOAL_RING_CIRCUMFERENCE*(1-this.goalOvertimeFraction);
},
goalProgressReadable: function(){
returnthis.formatSecondsAsHM(this.totalSeconds)+' / '+this.formatSecondsAsHM(this.dayGoalSeconds);
},
goalTitle: function(){
varremaining=this.dayGoalSeconds-this.totalSeconds;
returnremaining>0
? this.formatSecondsAsReadable(remaining,false)+' to go'
: this.formatSecondsAsReadable(-remaining,false)+' over';
},
// HH:MM (zero-padded) for the focus-screen readout
focusReadable: function(){
varh=Math.floor(this.elapsedSeconds/3600);
varm=Math.floor((this.elapsedSeconds%3600)/60);
varpad=function(n){returnn<10 ? '0'+n : ''+n;};
returnpad(h)+':'+pad(m);
},
// 0..60 — number of outer ticks lit, advances 1/sec, resets each minute
secondsTickCount: function(){
returnthis.elapsedSeconds%60;
},
// stroke-dashoffset for minutes ring (r=88, full cycle = 1h)
minutesOffset: function(){
varc=2*Math.PI*88;
varfraction=(this.elapsedSeconds%3600)/3600;
returnc*(1-fraction);
},
// stroke-dashoffset for the inner ring (r=78). This used to run on a 12-hour
// cycle of the current session, which meant it barely moved: 2% after a
// quarter of an hour, 6% after three quarters. It now carries the day
// against the goal, which is the number worth watching while working.
dayOffset: function(){
varc=2*Math.PI*78;
varfraction=this.dayGoalSeconds>0
? Math.min(this.totalSeconds/this.dayGoalSeconds,1)
: 0;
returnc*(1-fraction);
},
// the live day total, so the line above the ring agrees with the ring itself
totalLiveReadable: function(){
returnthis.formatSecondsAsReadable(this.totalSeconds,false);
},
// 60 evenly-spaced tick coordinates around the outer ring
// (svg has rotate(-90deg), so angle 0 = 12 o'clock after rotation)
tickPositions: function(){
varticks=[];
varcx=120,cy=120,innerR=104,outerR=113;
for(varn=1;n<=60;n++){
varrad=(n-1)*6*Math.PI/180;
ticks.push({
n: n,
x1: cx+Math.cos(rad)*innerR,
y1: cy+Math.sin(rad)*innerR,
x2: cx+Math.cos(rad)*outerR,
y2: cy+Math.sin(rad)*outerR
});
}
returnticks;
}
},
methods: {
addTask: function(){
varvalue=this.newTask&&this.newTask.trim();
if(!value){
return;
}
this.tasks.push({
id: nextTaskId++,
title: value,
secondsSpent: 0,
timeSpentReadable: ''
});
this.newTask='';
},
editTask: function(task){
this.beforeEditCache=task.title;
this.editedTask=task;
},
doneEditing: function(task){
if(!this.editedTask){
return;
}
this.editedTask=null;
task.title=task.title.trim();
if(!task.title){
this.removeTask(task);
}
},
cancelEditing: function(task){
this.editedTask=null;
task.title=this.beforeEditCache;
},
removeTask: function(task){
varquestion='Remove task "'+task.title+'" ?';
varconfirmation=confirm(question);
if(confirmation){
// stop the clock first — leaving timedTask pointing at a removed task
// keeps the focus view ticking on something no list holds any more,
// and its elapsed time would be written to that orphan
if(task===this.timedTask){
this.stopTimer();
}
this.tasks.splice(this.tasks.indexOf(task),1);
}
this.updateTotal();
},
adjust: function(task,key){
task.secondsSpent=ADJUST[key](task.secondsSpent);
task.timeSpentReadable=this.formatSecondsAsReadable(task.secondsSpent);
this.updateTotal();
// keep the preview live, so holding the cursor still and clicking again
// shows where the next press lands
this.showPreview(task,key);
},
showPreview: function(task,key){
// The buttons change secondsSpent, but the cell shows the live total, so the
// running session has to be carried across or the preview would contradict
// the number sitting next to it.
varopDeKlok=this.liveSeconds(task)-task.secondsSpent;
// same format as the total already in that cell, so hovering only adds the
// arrow and the result — it does not restyle the number you were reading
this.preview={
id: task.id,
was: this.formatSecondsAsReadable(this.liveSeconds(task)),
becomes: this.formatSecondsAsReadable(ADJUST[key](task.secondsSpent)+opDeKlok)
};
},
clearPreview: function(){
this.preview=null;
},
// null unless this row is the one being hovered
previewFor: function(task){
returnthis.preview&&this.preview.id===task.id ? this.preview : null;
},
// Which view is showing is no longer tied to whether the clock runs, so these
// two are plain navigation.
showList: function(){
this.viewMode='tasks';
},
showTimer: function(){
if(this.timedTask){
this.viewMode='focus';
}
},
// only the running row's live total is a way back into the timer
openTimerFor: function(task){
if(this.isRunning(task)){
this.showTimer();
}
},
isRunning: function(task){
returnthis.timerRunning&&task===this.timedTask;
},
// what the row shows: the stored total plus the session still on the clock
liveSeconds: function(task){
returntask.secondsSpent+(this.isRunning(task) ? this.elapsedSeconds : 0);
},
taskTotalReadable: function(task){
returnthis.formatSecondsAsReadable(this.liveSeconds(task));
},
// Write the running session onto its task and stop counting, without deciding
// which view should show — both stopTimer and a switch to another task need
// exactly this much. elapsedSeconds is deliberately left alone so the focus
// view can finish sliding out with its readout intact.
commitTimer: function(){
if(!this.timerRunning){
return;
}
varranForSeconds=Math.floor((Date.now()-this.startedAt)/1000);
this.timedTask.secondsSpent+=ranForSeconds;
this.timedTask.timeSpentReadable=this.formatSecondsAsReadable(this.timedTask.secondsSpent);
this.timerRunning=false;
clearInterval(this.timerInterval);
this.timerInterval=null;
this.updateTotal();
},
startTimer: function(task){
// already this task: just go and look at it
if(this.isRunning(task)){
this.showTimer();
return;
}
// pressing play on another row switches instead of being ignored, which is
// what it used to do — a console.warn and nothing else
this.commitTimer();
this.timedTask=task;
this.timerRunning=true;
this.viewMode='focus';
this.startedAt=Date.now();
this.elapsedSeconds=0;
this.timerReadable='0h 0m';
this.timerInterval=setInterval(this.updateTimer,500);
},
updateTimer: function(){
this.elapsedSeconds=Math.floor((Date.now()-this.startedAt)/1000);
this.timerReadable=this.formatSecondsAsReadable(this.elapsedSeconds,false);
},
formatSecondsAsReadable: function(secondsToFormat,includeSeconds){
if(includeSeconds===undefined)includeSeconds=true;
varhours=0,minutes=0,seconds=0;
if(secondsToFormat>=3600){
hours=Math.floor(secondsToFormat/3600);
}
if(secondsToFormat>=60){
minutes=Math.floor((secondsToFormat-(hours*3600))/60);
}
seconds=secondsToFormat-(hours*3600)-(minutes*60);
returnincludeSeconds
? hours+'h '+minutes+'m '+seconds+'s'
: hours+'h '+minutes+'m';
},
// Reordering by hand: the row is moved as soon as the pointer enters another
// one, so there is no drop indicator to maintain. Rows are keyed on task.id
// and colours come from that id too, so a task keeps its own colour while it
// travels instead of taking on the colour of the slot it lands in.
startDrag: function(task){
this.draggedTask=task;
},
dragOver: function(task){
if(!this.draggedTask||task===this.draggedTask){
return;
}
varfrom=this.tasks.indexOf(this.draggedTask);
varto=this.tasks.indexOf(task);
if(from===-1||to===-1){
return;
}
this.tasks.splice(to,0,this.tasks.splice(from,1)[0]);
},
endDrag: function(){
this.draggedTask=null;
},
taskColour: function(task){
return'var(--tc-'+((task.id*TASK_COLOUR_STEP)%TASK_COLOUR_COUNT+1)+')';
},
// H:MM — compact form used by the day-goal readout
formatSecondsAsHM: function(secondsToFormat){
varhours=Math.floor(secondsToFormat/3600);
varminutes=Math.floor((secondsToFormat%3600)/60);
returnhours+':'+(minutes<10 ? '0'+minutes : minutes);
},
formatAsJiraLink: function(title){
if(!this.jiraBaseUrl){
returntitle;
}
constpattern=/^([A-Z]{2,}-\d+)/;
if(pattern.test(title)){
returntitle.replace(pattern,'<a href="'+this.jiraBaseUrl+'$1" target="_blank">$1</a>');
}
returntitle;
},
// applied live so the choice can actually be judged; saveSettings commits
// it and closeSettings puts the previously stored theme back
previewTheme: function(id){
this.themeDraft=id;
applyTheme(id);
},
openSettings: function(){
this.jiraSubdomainDraft=this.jiraSubdomain;
this.dayGoalDraft=this.dayGoalHours;
this.themeDraft=this.theme;
this.settingsOpen=true;
},
saveSettings: function(){
this.jiraSubdomain=this.jiraSubdomainDraft.trim();
localStorage.setItem('simpletimer.jiraSubdomain',this.jiraSubdomain);
// fall back to the default rather than letting a blank or bogus
// value collapse the ring
vargoal=parseFloat(this.dayGoalDraft);
if(!Number.isFinite(goal)||goal<=0)goal=8;
this.dayGoalHours=Math.min(goal,24);
localStorage.setItem('simpletimer.dayGoalHours',this.dayGoalHours);
this.theme=this.themeDraft;
localStorage.setItem('simpletimer.theme',this.theme);
this.settingsOpen=false;
},
closeSettings: function(){
// drop any live preview that was not saved
if(this.themeDraft!==this.theme)applyTheme(this.theme);
this.settingsOpen=false;
},
stopTimer: function(){
if(null==this.timedTask){
return;
}
this.commitTimer();
this.viewMode='tasks';
// keep the focus view rendered until the slide finishes, so it slides out
// instead of vanishing. The guard matters: starting another timer inside
// those 320ms must not have its task wiped by this callback.
varself=this;
setTimeout(function(){
if(!self.timerRunning){
self.timedTask=null;
self.startedAt=0;
self.elapsedSeconds=0;
self.timerReadable='';
}
},320);
},
updateTotal: function(){
vartotalSeconds=0;
this.tasks.forEach(function(item){
totalSeconds+=item.secondsSpent;
});
this.totalReadable=this.formatSecondsAsReadable(totalSeconds);
},
print: function(){
constd=newDate();
letmonth=(d.getMonth()+1).toString();
month=month.length<2 ? '0'+month : month;
letday=d.getDate().toString();
day=day.length<2 ? '0'+day : day;
navigator.clipboard.writeText(d.getFullYear()+''+month+''+day);
window.print();
},
},// end of methods
mounted: function(){
// Escape leaves the focus view without stopping the clock. Bound on the
// document because the focus view holds no focus of its own.
varself=this;
document.addEventListener('keydown',function(event){
if(event.key==='Escape'&&self.viewMode==='focus'&&!self.settingsOpen){
self.showList();
}
});
},
directives: {
'todo-focus': function(el,binding){
if(binding.value){
el.focus()
}
}
}
});
// the inline boot script in index.html sets the attribute unvalidated,
// so re-apply the parsed value here
applyTheme(app.theme);
// mount
app.$mount('.timerapp')
/* for dev only:
app.newTask = 'ABC-123 lorem ipsum';
app.addTask();
app.startTimer(app.tasks[0]);
// */