Improve javascript (#1077)

This commit is contained in:
Thomas Rupprecht 2023-04-01 15:14:32 +02:00 committed by GitHub
parent d4104850be
commit 84c1cc36e5
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
7 changed files with 72 additions and 99 deletions

View File

@ -212,7 +212,7 @@ function view_user_shifts()
$days = load_days(); $days = load_days();
$rooms = load_rooms(); $rooms = load_rooms();
$types = load_types(); $types = load_types();
$ownTypes = []; $ownAngelTypes = [];
/** @var EloquentCollection|UserAngelType[] $userAngelTypes */ /** @var EloquentCollection|UserAngelType[] $userAngelTypes */
$userAngelTypes = UserAngelType::whereUserId($user->id) $userAngelTypes = UserAngelType::whereUserId($user->id)
@ -223,12 +223,12 @@ function view_user_shifts()
}) })
->get(); ->get();
foreach ($userAngelTypes as $type) { foreach ($userAngelTypes as $type) {
$ownTypes[] = $type->angel_type_id; $ownAngelTypes[] = $type->angel_type_id;
} }
if (!$session->has('shifts-filter')) { if (!$session->has('shifts-filter')) {
$room_ids = $rooms->pluck('id')->toArray(); $room_ids = $rooms->pluck('id')->toArray();
$shiftsFilter = new ShiftsFilter(auth()->can('user_shifts_admin'), $room_ids, $ownTypes); $shiftsFilter = new ShiftsFilter(auth()->can('user_shifts_admin'), $room_ids, $ownAngelTypes);
$session->set('shifts-filter', $shiftsFilter->sessionExport()); $session->set('shifts-filter', $shiftsFilter->sessionExport());
} }
@ -296,13 +296,7 @@ function view_user_shifts()
$shiftsFilter->getTypes(), $shiftsFilter->getTypes(),
'types', 'types',
icon('person-lines-fill') . __('Angeltypes') . '<sup>1</sup>', icon('person-lines-fill') . __('Angeltypes') . '<sup>1</sup>',
[ $ownAngelTypes
button(
'javascript:checkOwnTypes(\'selection_types\', ' . json_encode($ownTypes) . ')',
__('Own'),
'd-print-none'
),
]
), ),
'filled_select' => make_select( 'filled_select' => make_select(
$filled, $filled,
@ -378,20 +372,23 @@ function get_ids_from_array($array)
* @param array $selected * @param array $selected
* @param string $name * @param string $name
* @param string $title * @param string $title
* @param array $additionalButtons * @param int[] $ownSelect
* @return string * @return string
*/ */
function make_select($items, $selected, $name, $title = null, $additionalButtons = []) function make_select($items, $selected, $name, $title = null, $ownSelect = [])
{ {
$html = ''; $html = '';
if (isset($title)) { if (isset($title)) {
$html .= '<h4>' . $title . '</h4>' . "\n"; $html .= '<h4>' . $title . '</h4>' . "\n";
} }
$buttons = []; $buttons = [
$buttons[] = button('javascript:checkAll(\'selection_' . $name . '\', true)', __('All'), 'd-print-none'); button_checkbox_selection($name, __('All'), 'true'),
$buttons[] = button('javascript:checkAll(\'selection_' . $name . '\', false)', __('None'), 'd-print-none'); button_checkbox_selection($name, __('None'), 'false'),
$buttons = array_merge($buttons, $additionalButtons); ];
if (count($ownSelect) > 0) {
$buttons[] = button_checkbox_selection($name, __('Own'), json_encode($ownSelect));
}
$html .= buttons($buttons); $html .= buttons($buttons);
$html .= '<div id="selection_' . $name . '" class="mb-3 selection ' . $name . '">' . "\n"; $html .= '<div id="selection_' . $name . '" class="mb-3 selection ' . $name . '">' . "\n";

View File

@ -374,16 +374,17 @@ function button($href, $label, $class = '', $id = '')
} }
/** /**
* Rendert einen Knopf mit JavaScript onclick Handler * Renders a button to select corresponding checkboxes
* *
* @param string $javascript * @param string $name
* @param string $label * @param string $label
* @param string $class * @param string $value
* @return string * @return string
*/ */
function button_js($javascript, $label, $class = '') function button_checkbox_selection($name, $label, $value)
{ {
return '<a onclick="' . $javascript . '" href="#" class="btn btn-secondary ' . $class . '">' . $label . '</a>'; return '<button type="button" class="btn btn-secondary d-print-none checkbox-selection" '
. 'data-id="selection_' . $name . '" data-value="' . $value . '">' . $label . '</button>';
} }
/** /**

View File

@ -51,23 +51,5 @@ function UserDriverLicense_edit_view($user_source, $user_driver_license)
], 'driving_license'), ], 'driving_license'),
form_submit('submit', __('Save')), form_submit('submit', __('Save')),
]), ]),
'
<script>
const drivingLicenseElement = document.getElementById("driving_license");
if (drivingLicenseElement) {
const checkbox = document.getElementById("wants_to_drive");
drivingLicenseElement.style.display = checkbox?.checked
? ""
: "none";
checkbox.addEventListener("click", () => {
drivingLicenseElement.style.display = document.getElementById("wants_to_drive")?.checked
? ""
: "none";
});
}
</script>
',
], true); ], true);
} }

View File

@ -6,7 +6,7 @@ import { ready } from './ready';
ready(() => { ready(() => {
const lang = document.documentElement.getAttribute('lang'); const lang = document.documentElement.getAttribute('lang');
const rtf = new Intl.RelativeTimeFormat(lang, { numeric: 'auto' }); const rtf = new Intl.RelativeTimeFormat(lang ?? [], { numeric: 'auto' });
const timeFrames = [ const timeFrames = [
[60 * 60 * 24 * 365, 'year'], [60 * 60 * 24 * 365, 'year'],

View File

@ -4,28 +4,24 @@ import { ready } from './ready';
/** /**
* Sets all checkboxes to the wanted state * Sets all checkboxes to the wanted state
*
* @param {string} id Id of the element containing all the checkboxes
* @param {boolean} checked True if the checkboxes should be checked
*/ */
global.checkAll = (id, checked) => { ready(() => {
document.querySelectorAll(`#${id} input[type="checkbox"]`).forEach((element) => { document.querySelectorAll('button.checkbox-selection').forEach((buttonElement) => {
element.checked = checked; buttonElement.addEventListener('click', () => {
document.querySelectorAll(`#${buttonElement.dataset.id} input[type="checkbox"]`).forEach((checkboxElement) => {
/**
* @type {boolean|int[]}
*/
const value = JSON.parse(buttonElement.dataset.value);
if (typeof value === 'boolean') {
checkboxElement.checked = value;
} else {
checkboxElement.checked = value.includes(Number(checkboxElement.value));
}
});
});
}); });
}; });
/**
* Sets the checkboxes according to the given type
*
* @param {string} id The Id of the element containing all the checkboxes
* @param {int[]} shiftsList A list of numbers
*/
global.checkOwnTypes = (id, shiftsList) => {
document.querySelectorAll(`#${id} input[type="checkbox"]`).forEach((element) => {
const value = Number(element.value);
element.checked = shiftsList.includes(value);
});
};
ready(() => { ready(() => {
/** /**
@ -284,27 +280,36 @@ ready(() => {
* Uses DOMContentLoaded to prevent flickering * Uses DOMContentLoaded to prevent flickering
*/ */
ready(() => { ready(() => {
const filter = document.getElementById('collapseShiftsFilterSelect'); const collapseElement = document.getElementById('collapseShiftsFilterSelect');
if (!filter || localStorage.getItem('collapseShiftsFilterSelect') !== 'hidden.bs.collapse') { if (collapseElement) {
return; if (localStorage.getItem('collapseShiftsFilterSelect') === 'hidden.bs.collapse') {
} collapseElement.classList.remove('show');
}
filter.classList.remove('show'); /**
* @param {Event} event
*/
const onChange = (event) => {
localStorage.setItem('collapseShiftsFilterSelect', event.type);
};
collapseElement.addEventListener('hidden.bs.collapse', onChange);
collapseElement.addEventListener('shown.bs.collapse', onChange);
}
}); });
/**
* Show/hide checkboxes for User Driver-Licenses
*/
ready(() => { ready(() => {
if (typeof localStorage === 'undefined') { const checkboxElement = document.getElementById('wants_to_drive');
return; const drivingLicenseElement = document.getElementById('driving_license');
if (checkboxElement && drivingLicenseElement) {
drivingLicenseElement.hidden = !checkboxElement.checked;
checkboxElement.addEventListener('click', () => {
drivingLicenseElement.hidden = !checkboxElement.checked;
});
} }
/**
* @param {Event} event
*/
const onChange = (event) => {
localStorage.setItem('collapseShiftsFilterSelect', event.type);
};
document.getElementById('collapseShiftsFilterSelect')?.addEventListener('hidden.bs.collapse', onChange);
document.getElementById('collapseShiftsFilterSelect')?.addEventListener('shown.bs.collapse', onChange);
}); });

View File

@ -2,9 +2,9 @@
* @param {Function} callback * @param {Function} callback
*/ */
export const ready = (callback) => { export const ready = (callback) => {
if (document.readyState !== 'loading') { if (document.readyState === 'loading') {
callback();
} else {
document.addEventListener('DOMContentLoaded', callback); document.addEventListener('DOMContentLoaded', callback);
} else {
callback();
} }
}; };

View File

@ -263,15 +263,15 @@
{{ f.checkbox('form-input-checkbox-2', 'Checkbox 2', false, '2') }} {{ f.checkbox('form-input-checkbox-2', 'Checkbox 2', false, '2') }}
{{ f.checkbox('form-input-checkbox-3', 'Checkbox 3', false, '3') }} {{ f.checkbox('form-input-checkbox-3', 'Checkbox 3', false, '3') }}
<div class="d-grid gap-2"> <div class="d-grid gap-2">
<div id="select-all-checkboxes" class="btn btn-sm btn-block btn-primary"> <button type="button" class="btn btn-secondary d-print-none checkbox-selection" data-id="checkboxes" data-value="true">
Select all Select all
</div> </button>
<div id="select-23-checkboxes" class="btn btn-sm btn-block btn-primary"> <button type="button" class="btn btn-secondary d-print-none checkbox-selection" data-id="checkboxes" data-value="[2,3]">
Select 2, 3 Select 2, 3
</div> </button>
<div id="unselect-all-checkboxes" class="btn btn-sm btn-block btn-danger"> <button type="button" class="btn btn-secondary d-print-none checkbox-selection" data-id="checkboxes" data-value="false">
Unselect all Unselect all
</div> </button>
</div> </div>
</div> </div>
<div class="col-md-3 col-lg-2 checkbox-inline"> <div class="col-md-3 col-lg-2 checkbox-inline">
@ -432,18 +432,6 @@
</div> </div>
</div> </div>
<script> <script>
document.getElementById('select-all-checkboxes').addEventListener('click', () => {
checkAll('checkboxes', true);
});
document.getElementById('unselect-all-checkboxes').addEventListener('click', () => {
checkAll('checkboxes', false);
});
document.getElementById('select-23-checkboxes').addEventListener('click', () => {
checkOwnTypes('checkboxes', [2, 3]);
});
document.getElementById('form').addEventListener('submit', (e) => { document.getElementById('form').addEventListener('submit', (e) => {
e.preventDefault(); e.preventDefault();
return false; return false;