work_time-1.0.x-dev/js/work-time-block.js
js/work-time-block.js
import History from "./components/history-block";
import Store from "./components/store";
(function (Drupal, once) {
Drupal.behaviors.workTime = {
attach(context) {
once('worktimeBlock', '.btn-work-time-block', context).forEach((element) => {
let id = element.getAttribute('id');
let app = []; // Run application.
const App = {
data() {
return {
csrfToken: null,
isPlay: false,
time: '',
timeUp: '',
interval: null,
label: '',
buttonRef: {},
limit: 'week',
}
},
methods: {
// Counter.
countUp(time) {
let nowTimestamp = time;
this.interval = setInterval(() => {
this.timeUp = Store.updateDisplay(nowTimestamp++);
localStorage.setItem(id, nowTimestamp);
}, 1000);
},
// Button Play.
play(entity_id, event) {
let state = this.isPlay;
if (!this.isPlay) {
this.countUp(0);
} else {
localStorage.removeItem(id);
// this.isPlay = false;
clearInterval(this.interval);
}
// Todo review state.
this.buttonRef.play = state;
axios.post('/api/work-time?_format=json', this.buttonRef, {
headers: {
'Content-Type': 'application/json',
'X-CSRF-Token': Store.csrfToken
}
}).then((response) => {
}).catch(error => {
console.error("There was an error!", error);
});
this.isPlay = !this.isPlay;
},
},
created() {
if (Store.csrfToken === '') {
Store.csrfTokenLoader();
}
},
mounted() {
this.buttonRef = this.$refs.btnTimeBlock.dataset;
this.label = this.buttonRef.label;
if (this.label == '') {
this.label = document.title.split(" | ")[0];
}
// Get total in limit.
this.limit = this.buttonRef.limit;
let url = '/api/work-time-list/' + this.limit + '?_format=json';
for (const key in this.buttonRef) {
url += `&${key}=${this.buttonRef[key]}`;
}
axios.get(url, {
headers: {
'Content-Type': 'application/json',
'X-CSRF-Token': Store.csrfToken
}
}).then((response) => {
Store.history = response.data.worktime;
Store.projects = response.data.projects.reduce((itemMap, item) => {
itemMap[item.id] = item.label;
return itemMap;
}, {});
let total = Store.history.reduce((sum, item) => sum + (+item.time_total), 0);
this.timeUp = Store.updateDisplay(total);
if (response.data.playing.time != undefined) {
this.isPlay = true;
this.countUp(response.data.playing.time);
} else {
this.isPlay = false;
}
}).catch(error => {
console.error("There was an error!", error);
});
},
components: {
'history': History
}
};
app[id] = Vue.createApp(App);
app[id].mount(element);
});
}
};
}(Drupal, once));
