2019-05-22 12:00:05 +02:00
|
|
|
import { ajax, delegate } from '@utils';
|
2019-05-21 14:21:55 +02:00
|
|
|
|
|
|
|
addEventListener('turbolinks:load', () => {
|
|
|
|
checker.deactivate();
|
|
|
|
|
|
|
|
const attachments = document.querySelectorAll('[data-attachment-check-url]');
|
|
|
|
|
|
|
|
for (let attachment of attachments) {
|
|
|
|
checker.add(attachment.dataset.attachmentCheckUrl);
|
|
|
|
}
|
|
|
|
});
|
|
|
|
|
|
|
|
addEventListener('attachment:update', ({ detail: { url } }) => {
|
|
|
|
checker.add(url);
|
|
|
|
});
|
|
|
|
|
2019-05-22 12:00:05 +02:00
|
|
|
delegate('click', '[data-attachment-refresh]', event => {
|
|
|
|
event.preventDefault();
|
|
|
|
checker.check();
|
|
|
|
});
|
|
|
|
|
2019-05-21 14:21:55 +02:00
|
|
|
class AttachmentChecker {
|
|
|
|
urls = new Set();
|
|
|
|
timeout;
|
|
|
|
checks = 0;
|
|
|
|
|
|
|
|
constructor(settings = {}) {
|
|
|
|
this.interval = settings.interval || 5000;
|
|
|
|
this.maxChecks = settings.maxChecks || 5;
|
|
|
|
}
|
|
|
|
|
|
|
|
get isEnabled() {
|
|
|
|
return this.checks <= this.maxChecks;
|
|
|
|
}
|
|
|
|
|
|
|
|
get isActive() {
|
|
|
|
return this.timeout !== undefined;
|
|
|
|
}
|
|
|
|
|
|
|
|
add(url) {
|
|
|
|
if (this.isEnabled) {
|
|
|
|
if (!this.isActive) {
|
|
|
|
this.activate();
|
|
|
|
}
|
|
|
|
this.urls.add(url);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-05-22 12:00:05 +02:00
|
|
|
check() {
|
|
|
|
let urls = this.urls;
|
|
|
|
this.reset();
|
|
|
|
for (let url of urls) {
|
|
|
|
ajax({ url, type: 'get' });
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-05-21 14:21:55 +02:00
|
|
|
activate() {
|
2019-05-22 12:00:05 +02:00
|
|
|
clearTimeout(this.timeout);
|
2019-05-21 14:21:55 +02:00
|
|
|
this.timeout = setTimeout(() => {
|
|
|
|
this.checks++;
|
2019-05-22 12:00:05 +02:00
|
|
|
this.check();
|
2019-05-21 14:21:55 +02:00
|
|
|
}, this.interval);
|
|
|
|
}
|
|
|
|
|
|
|
|
deactivate() {
|
|
|
|
this.checks = 0;
|
|
|
|
this.reset();
|
|
|
|
}
|
|
|
|
|
|
|
|
reset() {
|
|
|
|
clearTimeout(this.timeout);
|
|
|
|
this.urls = new Set();
|
|
|
|
this.timeout = undefined;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
const checker = new AttachmentChecker();
|