Format JS code

This commit is contained in:
Michael Weimann 2022-11-26 14:50:59 +01:00 committed by Igor Scheller
parent 4752c9306c
commit 9d9211c054
6 changed files with 155 additions and 155 deletions

View File

@ -2,79 +2,79 @@ const lang = document.documentElement.getAttribute('lang');
const templateFuture = 'in %value %unit'; const templateFuture = 'in %value %unit';
const templatePast = lang === 'en' const templatePast = lang === 'en'
? '%value %unit ago' ? '%value %unit ago'
: 'vor %value %unit'; : 'vor %value %unit';
const yearUnits = lang === 'en' const yearUnits = lang === 'en'
? ['year', 'years'] ? ['year', 'years']
: ['Jahr', 'Jahren']; : ['Jahr', 'Jahren'];
const monthUnits = lang === 'en' const monthUnits = lang === 'en'
? ['month', 'months'] ? ['month', 'months']
: ['Monat', 'Monaten']; : ['Monat', 'Monaten'];
const dayUnits = lang === 'en' const dayUnits = lang === 'en'
? ['day', 'days'] ? ['day', 'days']
: ['Tag', 'Tagen']; : ['Tag', 'Tagen'];
const hourUnits = lang === 'en' const hourUnits = lang === 'en'
? ['hour', 'hours'] ? ['hour', 'hours']
: ['Stunde', 'Stunden']; : ['Stunde', 'Stunden'];
const minuteUnits = lang === 'en' const minuteUnits = lang === 'en'
? ['minute', 'minutes'] ? ['minute', 'minutes']
: ['Minute', 'Minuten']; : ['Minute', 'Minuten'];
const secondUnits = lang === 'en' const secondUnits = lang === 'en'
? ['second', 'seconds'] ? ['second', 'seconds']
: ['Sekunde', 'Sekunden']; : ['Sekunde', 'Sekunden'];
const nowString = lang === 'en' ? 'now' : 'jetzt'; const nowString = lang === 'en' ? 'now' : 'jetzt';
const secondsHour = 60 * 60; const secondsHour = 60 * 60;
const timeFrames = [ const timeFrames = [
[365 * 24 * 60 * 60, yearUnits], [365 * 24 * 60 * 60, yearUnits],
[30 * 24 * 60 * 60, monthUnits], [30 * 24 * 60 * 60, monthUnits],
[24 * 60 * 60, dayUnits], [24 * 60 * 60, dayUnits],
[secondsHour, hourUnits], [secondsHour, hourUnits],
[60, minuteUnits], [60, minuteUnits],
[1, secondUnits], [1, secondUnits],
]; ];
function formatFromNow(timestamp) { function formatFromNow(timestamp) {
const now = Date.now() / 1000; const now = Date.now() / 1000;
const diff = Math.abs(timestamp - now); const diff = Math.abs(timestamp - now);
const ago = now > timestamp; const ago = now > timestamp;
for (const [duration, [singular, plural]] of timeFrames) { for (const [duration, [singular, plural]] of timeFrames) {
const value = diff < secondsHour const value = diff < secondsHour
? Math.floor(diff / duration) ? Math.floor(diff / duration)
: Math.round(diff / duration); : Math.round(diff / duration);
if (value) { if (value) {
const template = ago ? templatePast : templateFuture; const template = ago ? templatePast : templateFuture;
const unit = value === 1 ? singular : plural; const unit = value === 1 ? singular : plural;
return template return template
.replace('%value', value) .replace('%value', value)
.replace('%unit', unit); .replace('%unit', unit);
}
} }
}
return nowString; return nowString;
} }
/** /**
* Initialises all countdown fields on the page. * Initialises all countdown fields on the page.
*/ */
$(function () { $(function () {
$.each($('[data-countdown-ts]'), function (i, e) { $.each($('[data-countdown-ts]'), function (i, e) {
const span = $(e); const span = $(e);
const timestamp = span.data('countdown-ts'); const timestamp = span.data('countdown-ts');
const text = span.html(); const text = span.html();
span.html(text.replace('%c', formatFromNow(timestamp))); span.html(text.replace('%c', formatFromNow(timestamp)));
setInterval(function () { setInterval(function () {
span.html(text.replace('%c', formatFromNow(timestamp))); span.html(text.replace('%c', formatFromNow(timestamp)));
}, 1000); }, 1000);
}); });
}); });

View File

@ -5,9 +5,9 @@
* @returns {string|undefined} Formatted time or undefined for non-Date * @returns {string|undefined} Formatted time or undefined for non-Date
*/ */
export const formatTime = (date) => { export const formatTime = (date) => {
if (!date instanceof Date) return; if (!date instanceof Date) return;
return String(date.getHours()).padStart(2, '0') + ':' return String(date.getHours()).padStart(2, '0') + ':'
+ String(date.getMinutes()).padStart(2, '0'); + String(date.getMinutes()).padStart(2, '0');
} }
@ -18,9 +18,9 @@ export const formatTime = (date) => {
* @returns {string|undefined} Formatted date or undefined for non-Date * @returns {string|undefined} Formatted date or undefined for non-Date
*/ */
export const formatDay = (date) => { export const formatDay = (date) => {
if (!date instanceof Date) return; if (!date instanceof Date) return;
return String(date.getFullYear()) + '-' return String(date.getFullYear()) + '-'
+ String(date.getMonth() + 1).padStart(2, '0') + '-' + String(date.getMonth() + 1).padStart(2, '0') + '-'
+ String(date.getDate()).padStart(2, '0'); + String(date.getDate()).padStart(2, '0');
} }

View File

@ -8,9 +8,9 @@ import { formatDay, formatTime } from './date';
* @param {boolean} checked True if the checkboxes should be checked * @param {boolean} checked True if the checkboxes should be checked
*/ */
global.checkAll = (id, checked) => { global.checkAll = (id, checked) => {
$('#' + id + ' input[type="checkbox"]').each(function () { $('#' + id + ' input[type="checkbox"]').each(function () {
this.checked = checked; this.checked = checked;
}); });
}; };
/** /**
@ -20,9 +20,9 @@ global.checkAll = (id, checked) => {
* @param {list} shiftsList A list of numbers * @param {list} shiftsList A list of numbers
*/ */
global.checkOwnTypes = (id, shiftsList) => { global.checkOwnTypes = (id, shiftsList) => {
$('#' + id + ' input[type="checkbox"]').each(function () { $('#' + id + ' input[type="checkbox"]').each(function () {
this.checked = $.inArray(parseInt(this.value), shiftsList) != -1; this.checked = $.inArray(parseInt(this.value), shiftsList) != -1;
}); });
}; };
/** /**
@ -36,63 +36,63 @@ global.checkOwnTypes = (id, shiftsList) => {
* @param {Date} to * @param {Date} to
*/ */
global.setInput = (from, to) => { global.setInput = (from, to) => {
const fromDay = $('#start_day'); const fromDay = $('#start_day');
const fromTime = $('#start_time'); const fromTime = $('#start_time');
const toDay = $('#end_day'); const toDay = $('#end_day');
const toTime = $('#end_time'); const toTime = $('#end_time');
if (!fromDay || !fromTime || !toDay || !toTime) { if (!fromDay || !fromTime || !toDay || !toTime) {
console.warn('cannot set input date because of missing field'); console.warn('cannot set input date because of missing field');
return; return;
} }
fromDay.val(formatDay(from)).trigger('change'); fromDay.val(formatDay(from)).trigger('change');
fromTime.val(formatTime(from)); fromTime.val(formatTime(from));
toDay.val(formatDay(to)).trigger('change'); toDay.val(formatDay(to)).trigger('change');
toTime.val(formatTime(to)); toTime.val(formatTime(to));
}; };
global.setDay = (days) => { global.setDay = (days) => {
days = days || 0; days = days || 0;
const from = new Date(); const from = new Date();
from.setHours(0, 0, 0, 0); from.setHours(0, 0, 0, 0);
// add days, Date handles the overflow // add days, Date handles the overflow
from.setDate(from.getDate() + days); from.setDate(from.getDate() + days);
const to = new Date(from); const to = new Date(from);
to.setHours(23, 59); to.setHours(23, 59);
setInput(from, to); setInput(from, to);
}; };
global.setHours = (hours) => { global.setHours = (hours) => {
hours = hours || 1; hours = hours || 1;
const from = new Date(); const from = new Date();
const to = new Date(from); const to = new Date(from);
// convert hours to add to milliseconds (60 minutes * 60 seconds * 1000 for milliseconds) // convert hours to add to milliseconds (60 minutes * 60 seconds * 1000 for milliseconds)
const msToAdd = hours * 60 * 60 * 1000; const msToAdd = hours * 60 * 60 * 1000;
to.setTime(to.getTime() + msToAdd, 'h'); to.setTime(to.getTime() + msToAdd, 'h');
if (to < from) { if (to < from) {
setInput(to, from); setInput(to, from);
return; return;
} }
setInput(from, to); setInput(from, to);
}; };
$(function () { $(function () {
/** /**
* Disable every submit button after clicking (to prevent double-clicking) * Disable every submit button after clicking (to prevent double-clicking)
*/ */
$('form').submit(function (ev) { $('form').submit(function (ev) {
$('input[type="submit"]').prop('readonly', true).addClass('disabled'); $('input[type="submit"]').prop('readonly', true).addClass('disabled');
return true; return true;
}); });
}); });
@ -100,44 +100,44 @@ $(function () {
* Button to set current time in time input fields. * Button to set current time in time input fields.
*/ */
$(function () { $(function () {
$('.input-group.time').each(function () { $('.input-group.time').each(function () {
const elem = $(this); const elem = $(this);
elem.find('button').on('click', function () { elem.find('button').on('click', function () {
const now = new Date(); const now = new Date();
const input = elem.children('input').first(); const input = elem.children('input').first();
input.val(formatTime(now)); input.val(formatTime(now));
const daySelector = $('#' + input.attr('id').replace('time', 'day')); const daySelector = $('#' + input.attr('id').replace('time', 'day'));
const days = daySelector.children('option'); const days = daySelector.children('option');
const yyyyMMDD = formatDay(now); const yyyyMMDD = formatDay(now);
days.each(function (i) { days.each(function (i) {
if ($(days[i]).val() === yyyyMMDD) { if ($(days[i]).val() === yyyyMMDD) {
daySelector.val($(days[i]).val()); daySelector.val($(days[i]).val());
return false; return false;
} }
}); });
});
}); });
});
}); });
$(function () { $(function () {
$('select').select2({ $('select').select2({
theme: 'bootstrap-5', theme: 'bootstrap-5',
}); });
}) })
/** /**
* Show oauth buttons on welcome title click * Show oauth buttons on welcome title click
*/ */
$(function () { $(function () {
$('#welcome-title').on('click', function () { $('#welcome-title').on('click', function () {
$('.btn-group.btn-group .btn.d-none').removeClass('d-none'); $('.btn-group.btn-group .btn.d-none').removeClass('d-none');
}); });
$('#settings-title').on('click', function () { $('#settings-title').on('click', function () {
$('.user-settings .nav-item').removeClass('d-none'); $('.user-settings .nav-item').removeClass('d-none');
}); });
$('#oauth-settings-title').on('click', function () { $('#oauth-settings-title').on('click', function () {
$('table tr.d-none').removeClass('d-none'); $('table tr.d-none').removeClass('d-none');
}); });
}); });
/** /**
@ -146,24 +146,24 @@ $(function () {
* Uses DOMContentLoaded to prevent flickering * Uses DOMContentLoaded to prevent flickering
*/ */
window.addEventListener('DOMContentLoaded', () => { window.addEventListener('DOMContentLoaded', () => {
const filter = document.getElementById('collapseShiftsFilterSelect'); const filter = document.getElementById('collapseShiftsFilterSelect');
if (!filter || localStorage.getItem('collapseShiftsFilterSelect') !== 'hidden') { if (!filter || localStorage.getItem('collapseShiftsFilterSelect') !== 'hidden') {
return; return;
} }
filter.classList.remove('show'); filter.classList.remove('show');
}); });
$(() => { $(() => {
if (typeof (localStorage) === 'undefined') { if (typeof (localStorage) === 'undefined') {
return; return;
} }
const onChange = (e) => { const onChange = (e) => {
localStorage.setItem('collapseShiftsFilterSelect', e.type); localStorage.setItem('collapseShiftsFilterSelect', e.type);
}; };
$('#collapseShiftsFilterSelect') $('#collapseShiftsFilterSelect')
.on('hidden.bs.collapse', onChange) .on('hidden.bs.collapse', onChange)
.on('shown.bs.collapse', onChange); .on('shown.bs.collapse', onChange);
}); });

View File

@ -2,31 +2,31 @@
* Enables the fixed headers and time lane for the shift-calendar and datatables * Enables the fixed headers and time lane for the shift-calendar and datatables
*/ */
$(function () { $(function () {
if ($('.shift-calendar').length) { if ($('.shift-calendar').length) {
const timeLanes = $('.shift-calendar .time'); const timeLanes = $('.shift-calendar .time');
const headers = $('.shift-calendar .header'); const headers = $('.shift-calendar .header');
const topReference = $('.container-fluid .row'); const topReference = $('.container-fluid .row');
timeLanes.css({
'position': 'relative',
'z-index': 999
});
headers.css({
'position': 'relative',
'z-index': 900
});
$(window).scroll(
function () {
const top = headers.parent().offset().top;
const left = 15;
timeLanes.css({ timeLanes.css({
'position': 'relative', 'left': Math.max(0, $(window).scrollLeft() - left) + 'px'
'z-index': 999
}); });
headers.css({ headers.css({
'position': 'relative', 'top': Math.max(0, $(window).scrollTop() - top
'z-index': 900
});
$(window).scroll(
function () {
const top = headers.parent().offset().top;
const left = 15;
timeLanes.css({
'left': Math.max(0, $(window).scrollLeft() - left) + 'px'
});
headers.css({
'top': Math.max(0, $(window).scrollTop() - top
- 13 - 13
+ topReference.offset().top) + topReference.offset().top)
+ 'px' + 'px'
}); });
}); });
} }
}); });

View File

@ -6,5 +6,5 @@ require('./sticky-headers');
require('./countdown'); require('./countdown');
$.ajaxSetup({ $.ajaxSetup({
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')} headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')}
}); });

View File

@ -28,7 +28,7 @@ const plugins = [
let themeFileNameRegex = /theme\d+/; let themeFileNameRegex = /theme\d+/;
if (process.env.THEMES) { if (process.env.THEMES) {
themeFileNameRegex = new RegExp(`theme(${process.env.THEMES.replace(/,/g, '|')})\\.`); themeFileNameRegex = new RegExp(`theme(${process.env.THEMES.replace(/,/g, '|')})\\.`);
} }
const themePath = path.resolve('resources/assets/themes'); const themePath = path.resolve('resources/assets/themes');