const calendarSVG = `
`;
const doorClosedSVG = `
`;
const doorOpenSVG = `
`;
const dateTimeFormat = Intl.DateTimeFormat([], {dateStyle: "medium", timeStyle: "short"});
async function linkElementClickListener(event) {
try {
await browser.tabs.create({url: event.currentTarget.dataset.url});
} catch (error) {
console.error(error);
}
}
async function init() {
const linkElements = Array.from(document.getElementsByClassName('link'));
linkElements.forEach((linkElement) => {
linkElement.addEventListener('click', linkElementClickListener);
});
try {
const page = await browser.runtime.getBackgroundPage();
updateNextEvent(page.calendar);
updateSpaceApiJson(page.spaceApi);
updateState(page.spaceApi);
} catch (error) {
console.error(error);
}
}
init();
function updateNextEvent(nextEvents) {
const calendarElement = document.getElementById('calendar');
calendarElement.innerText = '';
if (nextEvents.length === 0) {
const hintNode = document.createTextNode('Keine Termine in den nächsten 4 Wochen!');
const strongElement = document.createElement('strong');
strongElement.append(hintNode);
calendarElement.append(strongElement);
return;
}
const nextEventDate = nextEvents[0].begin.substr(0, 10);
const nextEventDateEvents = nextEvents.filter((nextEvent) => (nextEvent.begin.startsWith(nextEventDate)));
nextEventDateEvents.forEach((nextEventDateEvent) => {
const divElement = document.createElement('div');
divElement.innerHTML = calendarSVG;
const beginDate = new Date(nextEventDateEvent.begin);
const strongElement = document.createElement('strong');
const timeElement = document.createElement('time');
strongElement.textContent = nextEventDateEvent.name;
timeElement.datetime = beginDate.toISOString();
const dateNode = document.createTextNode(dateTimeFormat.format(beginDate));
// divElement.innerText = '';
divElement.append(strongElement, ' ', timeElement);
timeElement.append(dateNode);
if (nextEventDateEvent.location) {
const locationNode = document.createTextNode(` (${nextEventDateEvent.location})`);
divElement.append(locationNode);
}
calendarElement.append(divElement);
});
}
function updateSpaceApiJson(spaceApi) {
const spaceApiElement = document.querySelector('#space-api code');
const json = JSON.stringify(spaceApi, null, 2).replace(/ /g, ' ').replace(/\n/g, '
');
spaceApiElement.innerHTML = json;
// const jsonNode = document.createTextNode(json);
// spaceApiElement.innerText = '';
// spaceApiElement.append(jsonNode);
}
function updateState(spaceApi) {
const stateElement = document.getElementById('state');
const since = new Date(spaceApi.state.lastchange * 1000);
const sinceStr = ` seit `;
if (spaceApi.state.open) {
stateElement.innerHTML = `${doorOpenSVG}Offen ${sinceStr}`;
} else {
stateElement.innerHTML = `${doorClosedSVG}Geschlossen ${sinceStr}`;
}
}