diff --git a/.bumpversion.cfg b/.bumpversion.cfg index 6591e7cb8..0ed2373c5 100644 --- a/.bumpversion.cfg +++ b/.bumpversion.cfg @@ -1,5 +1,5 @@ [bumpversion] -current_version = 3.1.2 +current_version = 4.0.1 commit = True tag = True diff --git a/.github/workflows/check-codestyle.yml b/.github/workflows/check-codestyle.yml index 230a4826a..f64b6a15b 100644 --- a/.github/workflows/check-codestyle.yml +++ b/.github/workflows/check-codestyle.yml @@ -13,10 +13,10 @@ jobs: steps: - uses: actions/checkout@v2 - - name: Set up Python 3.9 + - name: Set up Python 3.13 uses: actions/setup-python@v2 with: - python-version: 3.9 + python-version: 3.13 - name: Install dependencies via apt run: | diff --git a/.gitignore b/.gitignore index 92c20b272..ac9198088 100644 --- a/.gitignore +++ b/.gitignore @@ -12,6 +12,9 @@ Session.vim # PyCharm .idea +# macOS +.DS_Store + # python/django *.pyc *.pyo diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index b2e41b458..cb9033518 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -2,14 +2,14 @@ # See https://pre-commit.com/hooks.html for more hooks repos: - repo: https://github.com/pre-commit/pre-commit-hooks - rev: v4.2.0 + rev: v4.4.0 hooks: - id: trailing-whitespace - id: end-of-file-fixer - id: check-yaml - id: check-added-large-files - repo: https://github.com/psf/black - rev: 22.3.0 + rev: 23.7.0 hooks: - id: black - repo: local diff --git a/CONTRIBUTORS b/CONTRIBUTORS index b9fb8b01f..f853d5f30 100644 --- a/CONTRIBUTORS +++ b/CONTRIBUTORS @@ -1,3 +1,6 @@ +Konrad Gößmann +Dominik Rimpf +franztv82 Johannes Walcher Johannes Ostner Sebastian Faul diff --git a/Dockerfile b/Dockerfile index 455467044..fb3a1821e 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,4 +1,4 @@ -FROM debian:bullseye +FROM debian:trixie ARG CONTAINER_VERSION="unknown" @@ -9,14 +9,15 @@ ENV HELFERTOOL_CONFIG_FILE="/config/helfertool.yaml" RUN apt-get update && apt-get full-upgrade -y && \ apt-get install --no-install-recommends -y \ supervisor nginx rsyslog pwgen curl \ - python3 python3-pip python3-dev uwsgi uwsgi-plugin-python3 \ - build-essential libldap2-dev libsasl2-dev libmariadb-dev libmagic1 \ + python3 python3-venv python3-dev uwsgi uwsgi-plugin-python3 \ + build-essential pkg-config ldap-utils libldap2-dev libsasl2-dev libmariadb-dev libpq-dev libmagic1 \ texlive-latex-extra texlive-plain-generic texlive-fonts-recommended texlive-lang-german && \ apt-get clean && \ rm -rf /var/lib/apt/lists/* /usr/share/doc/* && \ # add user, some directories and set file permissions useradd --shell /bin/bash --home-dir /helfertool --create-home helfertool --uid 10001 && \ mkdir -p /config /data /log /helfertool/run && \ + chmod 0755 /helfertool/ && \ chmod -R 0777 /helfertool/run && \ # nginx always writes to /var/log/nginx/error.log before reading the config # so we redirect it to a writable location @@ -34,13 +35,13 @@ COPY deployment/container/healthcheck.sh /usr/local/bin/healthcheck RUN echo $CONTAINER_VERSION > /helfertool/container_version && \ # install python libs cd /helfertool/src/ && \ - pip3 install -U pip && \ - pip3 install -r requirements.txt -r requirements_prod.txt && \ + python3 -m venv /helfertool/venv/ && \ + /helfertool/venv/bin/pip install wheel -r requirements.txt -r requirements_prod.txt && \ rm -rf /root/.cache/pip/ && \ # generate compressed CSS/JS files - HELFERTOOL_CONFIG_FILE=/dev/null python3 manage.py compress --force && \ + HELFERTOOL_CONFIG_FILE=/dev/null /helfertool/venv/bin/python manage.py compress --force && \ # copy static files - HELFERTOOL_CONFIG_FILE=/dev/null python3 manage.py collectstatic --noinput && \ + HELFERTOOL_CONFIG_FILE=/dev/null /helfertool/venv/bin/python manage.py collectstatic --noinput && \ chmod -R go+rX /helfertool/static && \ # fix permissions chmod +x /usr/local/bin/helfertool /usr/local/bin/healthcheck diff --git a/README.md b/README.md index 64ee27408..e5934880b 100644 --- a/README.md +++ b/README.md @@ -26,7 +26,7 @@ Please feel free to create issues here in Github! # License -Copyright (C) 2015-2022 Sven Hertle and contributors +Copyright (C) 2015-2026 Sven Hertle and contributors This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as diff --git a/deployment/container/etc/nginx.conf b/deployment/container/etc/nginx.conf index 16bea5cb2..137376aec 100644 --- a/deployment/container/etc/nginx.conf +++ b/deployment/container/etc/nginx.conf @@ -50,6 +50,8 @@ http { uwsgi_pass django; include /etc/nginx/uwsgi_params; + client_max_body_size 50M; + # CSP is set here, not in django add_header Content-Security-Policy "default-src 'none'; style-src 'self' 'unsafe-inline'; script-src 'self' 'unsafe-inline'; img-src 'self' data:; font-src 'self'; connect-src 'self'; form-action 'self'"; } diff --git a/deployment/container/etc/supervisord.conf b/deployment/container/etc/supervisord.conf index 2ba0a52cb..166ef875b 100644 --- a/deployment/container/etc/supervisord.conf +++ b/deployment/container/etc/supervisord.conf @@ -42,7 +42,7 @@ stderr_logfile_backups=2 priority=10 [program:celery] -command=celery -A helfertool worker -c %(ENV_HELFERTOOL_TASK_WORKERS)s --pidfile=/helfertool/run/celery.pid +command=/helfertool/venv/bin/celery -A helfertool worker -c %(ENV_HELFERTOOL_TASK_WORKERS)s --pidfile=/helfertool/run/celery.pid directory=/helfertool/src autostart=true autorestart=true @@ -53,7 +53,7 @@ stderr_logfile_backups=2 priority=20 [program:celerybeat] -command=celery -A helfertool beat --schedule=/data/tmp/celerybeat-schedule --pidfile=/helfertool/run/celerybeat.pid +command=/helfertool/venv/bin/celery -A helfertool beat --schedule=/data/tmp/celerybeat-schedule --pidfile=/helfertool/run/celerybeat.pid directory=/helfertool/src autostart=true autorestart=true diff --git a/deployment/container/etc/uwsgi.conf b/deployment/container/etc/uwsgi.conf index 170ea63a7..c397b185f 100644 --- a/deployment/container/etc/uwsgi.conf +++ b/deployment/container/etc/uwsgi.conf @@ -1,7 +1,8 @@ [uwsgi] -plugin = python39 +plugin = python313 chdir = /helfertool/src +venv = /helfertool/venv wsgi-file = /helfertool/src/helfertool/wsgi.py socket = /helfertool/run/uwsgi.sock diff --git a/deployment/container/healthcheck.sh b/deployment/container/healthcheck.sh index 3a718a81c..23bb5e054 100644 --- a/deployment/container/healthcheck.sh +++ b/deployment/container/healthcheck.sh @@ -12,7 +12,7 @@ die () { # check webserver (with a host header that is allowed) cd /helfertool/src -host="$(python3 manage.py shell -c "from django.conf import settings ; print(settings.ALLOWED_HOSTS[0] if settings.ALLOWED_HOSTS else '')")" +host="$(/helfertool/venv/bin/python manage.py shell -c "from django.conf import settings ; print(settings.ALLOWED_HOSTS[0] if settings.ALLOWED_HOSTS else '')")" curl --fail --silent --output /dev/null -H "Host: $host" http://localhost:8000 || die "Error on HTTP query" # check supervisord diff --git a/deployment/container/helfertool.sh b/deployment/container/helfertool.sh index 6e829921b..841a28552 100644 --- a/deployment/container/helfertool.sh +++ b/deployment/container/helfertool.sh @@ -34,7 +34,7 @@ mkdir -p /data/media /data/tmp /helfertool/run/tmp # command: init if [ "$1" = "init" ] ; then # initialise database with default settings - python3 manage.py loaddata toolsettings + /helfertool/venv/bin/python manage.py loaddata toolsettings # command: reload elif [ "$1" = "reload" ] ; then @@ -54,7 +54,7 @@ elif [ "$1" = "postrotate" ] ; then # command: manage elif [ "$1" = "manage" ] ; then shift - python3 manage.py $@ + /helfertool/venv/bin/python manage.py $@ # command: run elif [ "$1" = "run" ] ; then @@ -82,8 +82,8 @@ elif [ "$1" = "run" ] ; then sed "s/will_be_replaced/$(pwgen 40 1)/g" /helfertool/etc/supervisord.conf > /helfertool/run/supervisord.conf # run migrations and go - python3 manage.py migrate --noinput - python3 manage.py createcachetable + /helfertool/venv/bin/python manage.py migrate --noinput + /helfertool/venv/bin/python manage.py createcachetable exec supervisord --nodaemon --configuration /helfertool/run/supervisord.conf # help message diff --git a/scripts/container.sh b/scripts/container.sh index 4412135f9..2caf5d56d 100755 --- a/scripts/container.sh +++ b/scripts/container.sh @@ -63,8 +63,9 @@ set -u # command: build if [ "$action" = "build" ] ; then # build without cache and with updated base image - container_version="$(date --utc --iso-8601=seconds)" + container_version="$(date -u -Iseconds)" podman build --no-cache --pull \ + --arch=amd64 \ --build-arg CONTAINER_VERSION="$container_version" \ --format docker \ -t "$container_name:$container_tag" . @@ -73,6 +74,7 @@ if [ "$action" = "build" ] ; then elif [ "$action" = "fastbuild" ] ; then # build with cache, as fast as possible podman build \ + --arch=amd64 \ --build-arg CONTAINER_VERSION="fastbuild" \ --format docker \ -t "$container_name:$container_tag" . diff --git a/src/account/forms/__init__.py b/src/account/forms/__init__.py index ffcaa743a..9a4cb6a26 100644 --- a/src/account/forms/__init__.py +++ b/src/account/forms/__init__.py @@ -1,3 +1,4 @@ from .account import CreateUserForm, EditUserForm, DeleteUserForm, MergeUserForm from .agreement import AgreementForm, UserAgreementForm from .delete import DeleteForm +from .password_reset import CustomPasswordResetForm, CustomSetPasswordForm diff --git a/src/account/forms/account.py b/src/account/forms/account.py index 03c083580..8c9bfe94a 100644 --- a/src/account/forms/account.py +++ b/src/account/forms/account.py @@ -3,7 +3,8 @@ from django.contrib.auth import get_user_model from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import Group -from django.utils.translation import ugettext_lazy as _ +from django.utils.translation import gettext_lazy as _ +from django.views.decorators.debug import sensitive_variables from django_select2.forms import Select2Widget @@ -15,6 +16,7 @@ from ..templatetags.globalpermissions import has_adduser_group, has_addevent_group, has_sendnews_group +import secrets import logging logger = logging.getLogger("helfertool.account") @@ -88,18 +90,44 @@ class Meta: ), } + no_password = forms.BooleanField( + label=_("Do not set password now"), + help_text=_("The user is notified via email and can set the password (via the password reset)"), + required=False, + ) + def __init__(self, *args, **kwargs): super(CreateUserForm, self).__init__(*args, **kwargs) + # compared to the django default, we need some data for f in ("email", "first_name", "last_name"): self.fields[f].required = True + # if no_password is set, the password is not required, see clean() for more validation + for f in ("password1", "password2"): + self.fields[f].required = False + + self.fields["no_password"].widget.attrs["onChange"] = "handle_password()" + + @sensitive_variables("password") def clean(self): # add LOCAL_USER_CHAR to the beginning char = settings.LOCAL_USER_CHAR if char and not self.cleaned_data.get("username").startswith(char): self.cleaned_data["username"] = char + self.cleaned_data.get("username") + # if no_password is set, set a randomly generated password + # otherwise, check if password is set + if self.cleaned_data["no_password"]: + password = secrets.token_urlsafe(100) + self.cleaned_data["password1"] = password + self.cleaned_data["password2"] = password + else: + if not self.cleaned_data["password1"]: + self.add_error("password1", _("Password is required")) + if not self.cleaned_data["password2"]: + self.add_error("password2", _("Password is required")) + return super(CreateUserForm, self).clean() @@ -113,9 +141,15 @@ def __init__(self, *args, **kwargs): super(EditUserForm, self).__init__(*args, **kwargs) - # set required fields + # set attributes for name/email fields + # if user is local, the fields are required + # if users is from external idp, the fields cannot be changed for f in ("first_name", "last_name", "email"): - self.fields[f].required = True + if self.instance.has_usable_password(): + self.fields[f].required = True + else: + self.fields[f].help_text = _("Managed by external identity provider") + self.fields[f].disabled = True # adjust labels of active and superuser flags self._active_initial = self.instance.is_active diff --git a/src/account/forms/agreement.py b/src/account/forms/agreement.py index 93b02a72c..37d3a2964 100644 --- a/src/account/forms/agreement.py +++ b/src/account/forms/agreement.py @@ -1,8 +1,6 @@ from django import forms from django.conf import settings -from django.utils.translation import ugettext_lazy as _ - -from ckeditor.widgets import CKEditorWidget +from django.utils.translation import gettext_lazy as _ from helfertool.forms import DatePicker @@ -20,13 +18,6 @@ class Meta: "end": DatePicker, } - # According to the documentation django-modeltranslations copies the - # widget from the original field. - # But when setting BLEACH_DEFAULT_WIDGET this does not happen. - # Therefore set it manually... - for lang, name in settings.LANGUAGES: - widgets["text_{}".format(lang)] = CKEditorWidget() - def __init__(self, *args, **kwargs): super(AgreementForm, self).__init__(*args, **kwargs) diff --git a/src/account/forms/password_reset.py b/src/account/forms/password_reset.py new file mode 100644 index 000000000..2da6366fe --- /dev/null +++ b/src/account/forms/password_reset.py @@ -0,0 +1,75 @@ +from django.conf import settings +from django.contrib.auth.forms import PasswordResetForm, SetPasswordForm +from django.core.mail import EmailMessage +from django.template.loader import get_template + +from axes.helpers import get_client_ip_address + +from captcha.fields import CaptchaField +from helfertool.forms import CustomCaptchaTextInput + +import logging + +logger = logging.getLogger("helfertool.account") + + +class CustomPasswordResetForm(PasswordResetForm): + def __init__(self, *args, **kwargs): + super(CustomPasswordResetForm, self).__init__(*args, **kwargs) + + if not settings.CAPTCHAS_PASSWORD_RESET: + self.fields.pop("captcha") + + def save(self, *args, **kwargs): + super(CustomPasswordResetForm, self).save(*args, **kwargs) + + # log password reset attempt + email = self.cleaned_data["email"] + ip_address = get_client_ip_address(kwargs.get("request")) + logger.info( + "password resetattempt", + extra={ + "email": email, + "ip": ip_address, + }, + ) + + captcha = CaptchaField(widget=CustomCaptchaTextInput) + + +class CustomSetPasswordForm(SetPasswordForm): + def save(self, commit=True): + user = super(CustomSetPasswordForm, self).save(commit) + + # log password reset + logger.info( + "password reset", + extra={ + "changed_user": user.username, + }, + ) + + # sent confirmation mail to user + context = { + "firstname": user.first_name, + "page_title": settings.PAGE_TITLE, + "contact_mail": settings.CONTACT_MAIL, + } + subject_template = get_template("account/password_reset/completed_mail_subject.txt") + subject = subject_template.render(context).strip() + + text_template = get_template("account/password_reset/completed_mail.txt") + text = text_template.render(context) + + # sent it and handle errors + mail = EmailMessage( + subject, + text, + settings.EMAIL_SENDER_ADDRESS, + [user.email], # to + reply_to=[settings.EMAIL_SENDER_ADDRESS], + ) + + mail.send(fail_silently=True) + + return user diff --git a/src/account/locale/de/LC_MESSAGES/django.mo b/src/account/locale/de/LC_MESSAGES/django.mo index cd890dd7c..4364dc839 100644 Binary files a/src/account/locale/de/LC_MESSAGES/django.mo and b/src/account/locale/de/LC_MESSAGES/django.mo differ diff --git a/src/account/locale/de/LC_MESSAGES/django.po b/src/account/locale/de/LC_MESSAGES/django.po index dbd7d406d..7bcfe8db7 100644 --- a/src/account/locale/de/LC_MESSAGES/django.po +++ b/src/account/locale/de/LC_MESSAGES/django.po @@ -7,7 +7,7 @@ msgid "" msgstr "" "Project-Id-Version: \n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2022-07-25 19:30+0200\n" +"POT-Creation-Date: 2026-01-25 15:26+0100\n" "PO-Revision-Date: \n" "Last-Translator: \n" "Language-Team: \n" @@ -16,46 +16,63 @@ msgstr "" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" "Plural-Forms: nplurals=2; plural=(n != 1);\n" -"X-Generator: Poedit 3.0.1\n" +"X-Generator: Poedit 3.8\n" -#: account/forms/account.py:125 account/forms/account.py:133 +#: account/forms/account.py:94 +msgid "Do not set password now" +msgstr "Passwort jetzt nicht setzen" + +#: account/forms/account.py:95 +msgid "" +"The user is notified via email and can set the password (via the password " +"reset)" +msgstr "" +"Benutzer:in wird per E-Mail benachrichtigt und kann das Passwort festlegen " +"(durch einen Passwort Reset)" + +#: account/forms/account.py:127 account/forms/account.py:129 +msgid "Password is required" +msgstr "Passwort ist erforderlich" + +#: account/forms/account.py:151 account/forms/account.py:159 +#: account/forms/account.py:167 msgid "Managed by external identity provider" msgstr "Durch externen Identity Provider verwaltet" -#: account/forms/account.py:129 account/templates/account/list_users.html:35 +#: account/forms/account.py:163 account/templates/account/list_users.html:35 #: account/templates/account/user_permissions.html:10 msgid "Administrator" msgstr "Administrator:in" -#: account/forms/account.py:139 account/templates/account/list_users.html:43 +#: account/forms/account.py:173 account/templates/account/list_users.html:43 #: account/templates/account/user_permissions.html:19 msgid "Add users" msgstr "Benutzer:innen hinzufügen" -#: account/forms/account.py:147 account/templates/account/list_users.html:39 +#: account/forms/account.py:181 account/templates/account/list_users.html:39 #: account/templates/account/user_permissions.html:14 msgid "Add events" msgstr "Veranstaltungen hinzufügen" -#: account/forms/account.py:156 account/templates/account/list_users.html:49 +#: account/forms/account.py:190 account/templates/account/list_users.html:49 #: account/templates/account/user_permissions.html:24 msgid "Send newsletter" msgstr "Newsletter versenden" -#: account/forms/account.py:243 +#: account/forms/account.py:277 msgid "Other user, which will be deleted" msgstr "Andere Benutzer:in, welche gelöscht wird" -#: account/forms/account.py:268 +#: account/forms/account.py:302 msgid "User does not exist" msgstr "Benutzer:in existiert nicht" -#: account/forms/agreement.py:35 +#: account/forms/agreement.py:26 #, python-format msgid "Text (%(lang)s)" msgstr "Text (%(lang)s)" -#: account/models/agreement.py:13 +#: account/models/agreement.py:15 #: account/templates/account/delete_agreement.html:11 #: account/templates/account/delete_user.html:15 #: account/templates/account/merge_user.html:16 @@ -63,21 +80,21 @@ msgstr "Text (%(lang)s)" msgid "Name" msgstr "Name" -#: account/models/agreement.py:17 +#: account/models/agreement.py:21 msgid "Text" msgstr "Text" -#: account/models/agreement.py:21 +#: account/models/agreement.py:25 #: account/templates/account/delete_agreement.html:15 msgid "Start date" msgstr "Startdatum" -#: account/models/agreement.py:25 +#: account/models/agreement.py:29 #: account/templates/account/delete_agreement.html:19 msgid "End date" msgstr "Enddatum" -#: account/models/agreement.py:32 +#: account/models/agreement.py:36 msgid "End date must be after start date." msgstr "Enddatum muss nach Startdatum liegen." @@ -85,10 +102,45 @@ msgstr "Enddatum muss nach Startdatum liegen." msgid "Add user" msgstr "Benutzer:in hinzufügen" -#: account/templates/account/add_user.html:16 +#: account/templates/account/add_user.html:22 msgid "Add" msgstr "Hinzufügen" +#: account/templates/account/add_user_mail.txt:1 +#, python-format +msgid "" +"Hello %(firstname)s,\n" +"\n" +"your user for %(page_title)s was created.\n" +"\n" +"Your username is: %(username)s\n" +"\n" +"You can set your password here by using the password reset: " +"%(password_reset_url)s\n" +"\n" +"If you did not expect this mail, please contact %(contact_mail)s.\n" +"\n" +"Best regards" +msgstr "" +"Hallo %(firstname)s,\n" +"\n" +"dein Benutzer für %(page_title)s wurde erstellt.\n" +"\n" +"Der Benutzername ist: %(username)s\n" +"\n" +"Du kannst dein Passwort hier setzen, indem du den Passwort Reset nutzt: " +"%(password_reset_url)s\n" +"\n" +"Wenn du diese E-Mail nicht erwartet hast, wende dich bitte an " +"%(contact_mail)s.\n" +"\n" +"Viele Grüße" + +#: account/templates/account/add_user_mail_subject.txt:3 +#, python-format +msgid "Your access to %(page_title)s" +msgstr "Dein Zugang zu %(page_title)s" + #: account/templates/account/delete_agreement.html:5 msgid "Delete user agreement" msgstr "Nutzungsvereinbarung löschen" @@ -116,6 +168,7 @@ msgstr "Account Daten" #: account/templates/account/delete_user.html:11 #: account/templates/account/merge_user.html:12 +#: account/templates/account/password_reset/completed.html:10 #: account/templates/account/view_user.html:15 msgid "Login" msgstr "Login" @@ -209,7 +262,7 @@ msgstr "Kein Filter" msgid "Disabled" msgstr "Deaktiviert" -#: account/templates/account/list_users.html:87 +#: account/templates/account/list_users.html:99 msgid "No users found." msgstr "Keine Benutzer:in gefunden." @@ -230,6 +283,109 @@ msgstr "Benutzer:in zur Löschung" msgid "Merge" msgstr "Zusammenfassen" +#: account/templates/account/password_reset/completed.html:5 +#: account/templates/account/password_reset/confirm.html:5 +#: account/templates/account/password_reset/form.html:5 +#: account/templates/account/password_reset/sent.html:5 +msgid "Password reset" +msgstr "Passwort zurücksetzen" + +#: account/templates/account/password_reset/completed.html:7 +msgid "Your password has been set." +msgstr "Dein Passwort wurde gesetzt." + +#: account/templates/account/password_reset/completed_mail.txt:1 +#, python-format +msgid "" +"Hello %(firstname)s,\n" +"\n" +"your password for %(page_title)s has been successfully reset.\n" +"\n" +"If you have not done this yourself, please contact %(contact_mail)s " +"immediately.\n" +"\n" +"Best regards" +msgstr "" +"Hallo %(firstname)s,\n" +"\n" +"dein Passwort für %(page_title)s wurde erfolgreich zurückgesetzt.\n" +"\n" +"Wenn du dies nicht selbst getan hast, wende dich bitte umgehend an " +"%(contact_mail)s.\n" +"\n" +"Viele Grüße" + +#: account/templates/account/password_reset/completed_mail_subject.txt:3 +#, python-format +msgid "Successful password reset for %(page_title)s" +msgstr "Erfolgreicher Passwort Reset für %(page_title)s" + +#: account/templates/account/password_reset/confirm.html:20 +msgid "Set password" +msgstr "Passwort setzen" + +#: account/templates/account/password_reset/confirm.html:23 +msgid "The password reset link was invalid." +msgstr "Der Link zum Zurücksetzen des Passworts war ungültig." + +#: account/templates/account/password_reset/confirm_mail.txt:2 +#, python-format +msgid "" +"Hello %(firstname)s,\n" +"\n" +"you're receiving this email because you requested a password reset for " +"%(page_title)s.\n" +"\n" +"Please set a new password on the following page:" +msgstr "" +"Hallo %(firstname)s,\n" +"\n" +"du erhältst diese E-Mail, weil du das Zurücksetzen des Passworts für " +"%(page_title)s angefordert hast.\n" +"\n" +"Bitte setze auf der folgenden Seite ein neues Passwort:" + +#: account/templates/account/password_reset/confirm_mail.txt:10 +#, python-format +msgid "" +"Your username is: %(username)s\n" +"\n" +"Best regards" +msgstr "" +"Dein Benutzername ist: %(username)s\n" +"\n" +"Viele Grüße" + +#: account/templates/account/password_reset/confirm_mail_subject.txt:4 +#, python-format +msgid "Password reset for %(page_title)s" +msgstr "Passwort zurücksetzen für %(page_title)s" + +#: account/templates/account/password_reset/form.html:7 +msgid "" +"Enter your email address, and you will receive email instructions for " +"setting a new password." +msgstr "" +"Gib deine E-Mail Adresse ein und du wirst die Anweisungen zum Setzen eines " +"neuen Passworts per E-Mail erhalten." + +#: account/templates/account/password_reset/form.html:12 +msgid "The password reset only works for local user accounts." +msgstr "Das Zurücksetzen des Passworts funktioniert nur für lokale Accounts." + +#: account/templates/account/password_reset/form.html:32 +msgid "Reset password" +msgstr "Passwort zurücksetzen" + +#: account/templates/account/password_reset/sent.html:7 +msgid "" +"We’ve emailed you instructions for setting your password, if an account " +"exists with the email you entered." +msgstr "" +"Wir haben dir eine E-Mail mit Anweisungen zum Setzen deines Passworts " +"geschickt, falls ein Account mit der von dir angegebenen E-Mail-Adresse " +"existiert." + #: account/templates/account/view_user.html:6 msgid "My account" msgstr "Mein Account" @@ -263,16 +419,24 @@ msgstr "Gestern" msgid "%(last_login_ago)s ago" msgstr "Vor %(last_login_ago)s" -#: account/views/account.py:35 +#: account/views/account.py:70 +msgid "" +"Failed to send the notification email. Please contact the user on your own." +msgstr "" +"Die E-Mail zur Benachrichtigung konnte nicht gesendet werden. Bitte " +"kontaktiere den Benutzer selbst." + +#: account/views/account.py:73 #, python-format msgid "Added user %(username)s" msgstr "Benutzer:in %(username)s hinzugefügt" -#: account/views/account.py:90 +#: account/views/account.py:129 msgid "Changed password successfully" msgstr "Das Passwort wurde erfolgreich geändert" -#: account/views/account.py:187 +#: account/views/account.py:226 +#, python-brace-format msgid "Merged user {} into {}" msgstr "Benutzer:in {} mit {} zusammengefasst" diff --git a/src/account/migrations/0001_initial.py b/src/account/migrations/0001_initial.py index 91f079a31..6cbbf641c 100644 --- a/src/account/migrations/0001_initial.py +++ b/src/account/migrations/0001_initial.py @@ -9,7 +9,6 @@ class Migration(migrations.Migration): - initial = True dependencies = [ diff --git a/src/account/migrations/0002_auto_20190202_2336.py b/src/account/migrations/0002_auto_20190202_2336.py index 9c0c1f713..dfcc94ba7 100644 --- a/src/account/migrations/0002_auto_20190202_2336.py +++ b/src/account/migrations/0002_auto_20190202_2336.py @@ -6,7 +6,6 @@ class Migration(migrations.Migration): - dependencies = [ ("account", "0001_initial"), ] diff --git a/src/account/migrations/0003_auto_20190203_1239.py b/src/account/migrations/0003_auto_20190203_1239.py index 1436dd292..0d1169532 100644 --- a/src/account/migrations/0003_auto_20190203_1239.py +++ b/src/account/migrations/0003_auto_20190203_1239.py @@ -3,11 +3,10 @@ from __future__ import unicode_literals from django.db import migrations, models -import django.utils.datetime_safe +import datetime class Migration(migrations.Migration): - dependencies = [ ("account", "0002_auto_20190202_2336"), ] @@ -20,7 +19,7 @@ class Migration(migrations.Migration): migrations.AddField( model_name="agreement", name="start", - field=models.DateField(default=django.utils.datetime_safe.datetime.now, verbose_name="Start date"), + field=models.DateField(default=datetime.datetime.now, verbose_name="Start date"), preserve_default=False, ), ] diff --git a/src/account/migrations/0004_agreement_end.py b/src/account/migrations/0004_agreement_end.py index 66f2d5c43..1284eb485 100644 --- a/src/account/migrations/0004_agreement_end.py +++ b/src/account/migrations/0004_agreement_end.py @@ -6,7 +6,6 @@ class Migration(migrations.Migration): - dependencies = [ ("account", "0003_auto_20190203_1239"), ] diff --git a/src/account/migrations/0005_auto_20210523_1533.py b/src/account/migrations/0005_auto_20210523_1533.py index 7ceac6a0d..6c0d427ae 100644 --- a/src/account/migrations/0005_auto_20210523_1533.py +++ b/src/account/migrations/0005_auto_20210523_1533.py @@ -4,7 +4,6 @@ class Migration(migrations.Migration): - dependencies = [ ("account", "0004_agreement_end"), ] diff --git a/src/account/migrations/0006_alter_agreement_text_alter_agreement_text_de_and_more.py b/src/account/migrations/0006_alter_agreement_text_alter_agreement_text_de_and_more.py new file mode 100644 index 000000000..32cf34cdb --- /dev/null +++ b/src/account/migrations/0006_alter_agreement_text_alter_agreement_text_de_and_more.py @@ -0,0 +1,27 @@ +# Generated by Django 5.2.9 on 2026-01-12 20:17 + +from django.db import migrations, models + + +class Migration(migrations.Migration): + dependencies = [ + ("account", "0005_auto_20210523_1533"), + ] + + operations = [ + migrations.AlterField( + model_name="agreement", + name="text", + field=models.TextField(), + ), + migrations.AlterField( + model_name="agreement", + name="text_de", + field=models.TextField(null=True), + ), + migrations.AlterField( + model_name="agreement", + name="text_en", + field=models.TextField(null=True), + ), + ] diff --git a/src/account/migrations/0007_alter_agreement_text_alter_agreement_text_de_and_more.py b/src/account/migrations/0007_alter_agreement_text_alter_agreement_text_de_and_more.py new file mode 100644 index 000000000..2ce42eac7 --- /dev/null +++ b/src/account/migrations/0007_alter_agreement_text_alter_agreement_text_de_and_more.py @@ -0,0 +1,27 @@ +# Generated by Django 5.2.9 on 2026-01-12 21:21 + +from django.db import migrations, models + + +class Migration(migrations.Migration): + dependencies = [ + ("account", "0006_alter_agreement_text_alter_agreement_text_de_and_more"), + ] + + operations = [ + migrations.AlterField( + model_name="agreement", + name="text", + field=models.TextField(verbose_name="Text"), + ), + migrations.AlterField( + model_name="agreement", + name="text_de", + field=models.TextField(null=True, verbose_name="Text"), + ), + migrations.AlterField( + model_name="agreement", + name="text_en", + field=models.TextField(null=True, verbose_name="Text"), + ), + ] diff --git a/src/account/models/agreement.py b/src/account/models/agreement.py index b4593d37b..9cf10c96f 100644 --- a/src/account/models/agreement.py +++ b/src/account/models/agreement.py @@ -1,8 +1,10 @@ from django.contrib.auth import get_user_model from django.core.exceptions import ValidationError from django.db import models -from django.utils.translation import ugettext_lazy as _ -from django_bleach.models import BleachField +from django.utils.translation import gettext_lazy as _ + +from django_prose_editor.fields import ProseEditorField +from helfertool.utils import PROSE_EDITOR_DEFAULT_EXTENSIONS import datetime @@ -13,7 +15,9 @@ class Agreement(models.Model): verbose_name=_("Name"), ) - text = BleachField( + text = ProseEditorField( + extensions=PROSE_EDITOR_DEFAULT_EXTENSIONS, + sanitize=True, verbose_name=_("Text"), ) diff --git a/src/account/static/account/js/add_user.js b/src/account/static/account/js/add_user.js new file mode 100644 index 000000000..9d95b5699 --- /dev/null +++ b/src/account/static/account/js/add_user.js @@ -0,0 +1,20 @@ +function handle_password() +{ + var $no_password = $("#id_no_password").is(':checked'); + + if($no_password) { + $("#id_password1").removeAttr('required'); + $("#id_password2").removeAttr('required'); + + $("#id_password1").parent().hide() + $("#id_password2").parent().hide() + } else { + $("#id_password1").attr('required', ''); + $("#id_password2").attr('required', ''); + + $("#id_password1").parent().show() + $("#id_password2").parent().show() + } +} + +handle_password(); diff --git a/src/account/templates/account/add_user.html b/src/account/templates/account/add_user.html index 1b6840b42..5ced22246 100644 --- a/src/account/templates/account/add_user.html +++ b/src/account/templates/account/add_user.html @@ -1,5 +1,5 @@ {% extends "helfertool/admin.html" %} -{% load i18n django_bootstrap5 icons toolsettings %} +{% load i18n django_bootstrap5 icons toolsettings static %} {% block content %}

{% trans "Add user" %}

@@ -11,10 +11,18 @@

{% trans "Add user" %}

- {% bootstrap_form form layout="floating" %} + {% bootstrap_field form.username layout="floating" %} + {% bootstrap_field form.email layout="floating" %} + {% bootstrap_field form.first_name layout="floating" %} + {% bootstrap_field form.last_name layout="floating" %} + {% bootstrap_field form.no_password layout="floating" %} + {% bootstrap_field form.password1 layout="floating" %} + {% bootstrap_field form.password2 layout="floating" %}
+ + {% endblock %} diff --git a/src/account/templates/account/add_user_mail.txt b/src/account/templates/account/add_user_mail.txt new file mode 100644 index 000000000..dc77343c4 --- /dev/null +++ b/src/account/templates/account/add_user_mail.txt @@ -0,0 +1,12 @@ +{% load i18n %}{% autoescape off %}{% blocktranslate %}Hello {{ firstname }}, + +your user for {{ page_title }} was created. + +Your username is: {{ username }} + +You can set your password here by using the password reset: {{ password_reset_url }} + +If you did not expect this mail, please contact {{ contact_mail }}. + +Best regards{% endblocktranslate %} +{% endautoescape %} diff --git a/src/account/templates/account/add_user_mail_subject.txt b/src/account/templates/account/add_user_mail_subject.txt new file mode 100644 index 000000000..816af8526 --- /dev/null +++ b/src/account/templates/account/add_user_mail_subject.txt @@ -0,0 +1,4 @@ +{% load i18n %} +{% autoescape off %} +{% blocktrans %}Your access to {{ page_title }}{% endblocktrans %} +{% endautoescape %} diff --git a/src/account/templates/account/list_users.html b/src/account/templates/account/list_users.html index 144c78f51..fe024d26f 100644 --- a/src/account/templates/account/list_users.html +++ b/src/account/templates/account/list_users.html @@ -53,36 +53,48 @@

{% trans "Users" %}

{% if users %} - {% bootstrap_pagination users %} + {% bootstrap_pagination users url=paginator_search_string %} {% else %}

{% trans "No users found." %}

{% endif %} diff --git a/src/account/templates/account/password_reset/completed.html b/src/account/templates/account/password_reset/completed.html new file mode 100644 index 000000000..c498acfca --- /dev/null +++ b/src/account/templates/account/password_reset/completed.html @@ -0,0 +1,12 @@ +{% extends "helfertool/base.html" %} +{% load i18n django_bootstrap5 icons toolsettings %} + +{% block content %} +

{% trans "Password reset" %}

+ +

{% translate "Your password has been set." %}

+ + + {% icon "sign-in-alt" %} {% trans "Login" %} + +{% endblock %} diff --git a/src/account/templates/account/password_reset/completed_mail.txt b/src/account/templates/account/password_reset/completed_mail.txt new file mode 100644 index 000000000..eed682811 --- /dev/null +++ b/src/account/templates/account/password_reset/completed_mail.txt @@ -0,0 +1,8 @@ +{% load i18n %}{% autoescape off %}{% blocktranslate %}Hello {{ firstname }}, + +your password for {{ page_title }} has been successfully reset. + +If you have not done this yourself, please contact {{ contact_mail }} immediately. + +Best regards{% endblocktranslate %} +{% endautoescape %} diff --git a/src/account/templates/account/password_reset/completed_mail_subject.txt b/src/account/templates/account/password_reset/completed_mail_subject.txt new file mode 100644 index 000000000..3d97cb70a --- /dev/null +++ b/src/account/templates/account/password_reset/completed_mail_subject.txt @@ -0,0 +1,4 @@ +{% load i18n %} +{% autoescape off %} +{% blocktrans %}Successful password reset for {{ page_title }}{% endblocktrans %} +{% endautoescape %} diff --git a/src/account/templates/account/password_reset/confirm.html b/src/account/templates/account/password_reset/confirm.html new file mode 100644 index 000000000..33307d96e --- /dev/null +++ b/src/account/templates/account/password_reset/confirm.html @@ -0,0 +1,25 @@ +{% extends "helfertool/base.html" %} +{% load i18n django_bootstrap5 icons toolsettings %} + +{% block content %} +

{% trans "Password reset" %}

+ + {% if validlink %} +
+ {% csrf_token %} + +
+
+ {% bootstrap_form_errors form %} + + {% bootstrap_field form.new_password1 required_css_class="" layout="floating" %} + {% bootstrap_field form.new_password2 required_css_class="" layout="floating" %} +
+
+ + +
+ {% else %} +

{% translate "The password reset link was invalid." %}

+ {% endif %} +{% endblock %} diff --git a/src/account/templates/account/password_reset/confirm_mail.txt b/src/account/templates/account/password_reset/confirm_mail.txt new file mode 100644 index 000000000..fe0c07226 --- /dev/null +++ b/src/account/templates/account/password_reset/confirm_mail.txt @@ -0,0 +1,13 @@ +{% load i18n toolsettings %}{% djangosetting "PAGE_TITLE" as page_title %}{% autoescape off %} +{% blocktranslate with firstname=user.first_name %}Hello {{ firstname }}, + +you're receiving this email because you requested a password reset for {{ page_title }}. + +Please set a new password on the following page:{% endblocktranslate %} + +{{ protocol }}://{{ domain }}{% url 'account:password_reset_confirm' uidb64=uid token=token %} + +{% blocktranslate with username=user.get_username %}Your username is: {{ username }} + +Best regards{% endblocktranslate %} +{% endautoescape %} diff --git a/src/account/templates/account/password_reset/confirm_mail_subject.txt b/src/account/templates/account/password_reset/confirm_mail_subject.txt new file mode 100644 index 000000000..909b117b9 --- /dev/null +++ b/src/account/templates/account/password_reset/confirm_mail_subject.txt @@ -0,0 +1,5 @@ +{% load i18n toolsettings %} +{% djangosetting "PAGE_TITLE" as page_title %} +{% autoescape off %} +{% blocktrans with page_title=page_title %}Password reset for {{ page_title }}{% endblocktrans %} +{% endautoescape %} diff --git a/src/account/templates/account/password_reset/form.html b/src/account/templates/account/password_reset/form.html new file mode 100644 index 000000000..378379486 --- /dev/null +++ b/src/account/templates/account/password_reset/form.html @@ -0,0 +1,34 @@ +{% extends "helfertool/base.html" %} +{% load i18n django_bootstrap5 icons toolsettings %} + +{% block content %} +

{% trans "Password reset" %}

+ +

{% translate "Enter your email address, and you will receive email instructions for setting a new password." %}

+ + {% djangosetting "OIDC_CUSTOM_PROVIDER_NAME" as OIDC_CUSTOM_PROVIDER_NAME %} + {% djangosetting "AUTH_LDAP_SERVER_URI" as AUTH_LDAP_SERVER_URI %} + {% if OIDC_CUSTOM_PROVIDER_NAME or AUTH_LDAP_SERVER_URI %} +

{% translate "The password reset only works for local user accounts." %}

+ {%endif %} + +
+ {% csrf_token %} + +
+
+ {% bootstrap_form_errors form %} + + {% bootstrap_field form.email required_css_class="" layout="floating" %} + + {% if form.captcha %} +
+ {% bootstrap_field form.captcha required_css_class="" show_label=False %} +
+ {% endif %} +
+
+ + +
+{% endblock %} diff --git a/src/account/templates/account/password_reset/sent.html b/src/account/templates/account/password_reset/sent.html new file mode 100644 index 000000000..8b8ff3956 --- /dev/null +++ b/src/account/templates/account/password_reset/sent.html @@ -0,0 +1,8 @@ +{% extends "helfertool/base.html" %} +{% load i18n django_bootstrap5 icons toolsettings %} + +{% block content %} +

{% trans "Password reset" %}

+ +

{% translate "We’ve emailed you instructions for setting your password, if an account exists with the email you entered." %}

+{% endblock %} diff --git a/src/account/templatetags/lastlogin.py b/src/account/templatetags/lastlogin.py index e585a7702..34ce6169d 100644 --- a/src/account/templatetags/lastlogin.py +++ b/src/account/templatetags/lastlogin.py @@ -1,6 +1,6 @@ from django import template from django.utils.timesince import timesince -from django.utils.timezone import is_aware, utc +from django.utils.timezone import is_aware from django.utils.translation import gettext_lazy as _ import datetime @@ -15,7 +15,7 @@ def lastlogin(user): return _("Never") login_date = _to_date(user.last_login) - now_date = _to_date(datetime.datetime.now(utc if is_aware(login_date) else None)) + now_date = _to_date(datetime.datetime.now(datetime.timezone.utc if is_aware(login_date) else None)) if login_date == now_date: return _("Today") diff --git a/src/account/urls.py b/src/account/urls.py index 1308b63b5..ec1300bec 100644 --- a/src/account/urls.py +++ b/src/account/urls.py @@ -1,22 +1,59 @@ -from django.conf.urls import url +from django.contrib.auth import views as auth_views +from django.urls import path, reverse_lazy from . import views +from .forms import CustomPasswordResetForm, CustomSetPasswordForm app_name = "account" urlpatterns = [ + # password reset + path( + "reset/", + auth_views.PasswordResetView.as_view( + form_class=CustomPasswordResetForm, + template_name="account/password_reset/form.html", + success_url=reverse_lazy("account:password_reset_sent"), + email_template_name="account/password_reset/confirm_mail.txt", + subject_template_name="account/password_reset/confirm_mail_subject.txt", + ), + name="password_reset", + ), + path( + "reset/sent/", + auth_views.PasswordResetDoneView.as_view( + template_name="account/password_reset/sent.html", + ), + name="password_reset_sent", + ), + path( + "reset///", + auth_views.PasswordResetConfirmView.as_view( + form_class=CustomSetPasswordForm, + template_name="account/password_reset/confirm.html", + success_url=reverse_lazy("account:password_reset_completed"), + ), + name="password_reset_confirm", + ), + path( + "reset/completed/", + auth_views.PasswordResetCompleteView.as_view( + template_name="account/password_reset/completed.html", + ), + name="password_reset_completed", + ), # account - url(r"^$", views.view_user, name="view_user"), - url(r"^(?P[0-9]+)/$", views.view_user, name="view_user"), - url(r"^(?P[0-9]+)/edit/$", views.edit_user, name="edit_user"), - url(r"^(?P[0-9]+)/delete/$", views.delete_user, name="delete_user"), - url(r"^(?P[0-9]+)/merge/$", views.merge_user, name="merge_user"), - url(r"^new/$", views.add_user, name="add_user"), - url(r"^list/$", views.list_users, name="list_users"), + path("", views.view_user, name="view_user"), + path("/", views.view_user, name="view_user"), + path("/edit/", views.edit_user, name="edit_user"), + path("/delete/", views.delete_user, name="delete_user"), + path("/merge/", views.merge_user, name="merge_user"), + path("new/", views.add_user, name="add_user"), + path("list/", views.list_users, name="list_users"), # agreements - url(r"^check/$", views.check_user_agreement, name="check_user_agreement"), - url(r"^check/(?P[0-9]+)/$", views.handle_user_agreement, name="handle_user_agreement"), - url(r"^agreements/$", views.list_agreements, name="list_agreements"), - url(r"^agreements/new/$", views.edit_agreement, name="new_agreement"), - url(r"^agreements/(?P[0-9]+)/$", views.edit_agreement, name="edit_agreement"), - url(r"^agreements/(?P[0-9]+)/delete/$", views.delete_agreement, name="delete_agreement"), + path("check/", views.check_user_agreement, name="check_user_agreement"), + path("check//", views.handle_user_agreement, name="handle_user_agreement"), + path("agreements/", views.list_agreements, name="list_agreements"), + path("agreements/new/", views.edit_agreement, name="new_agreement"), + path("agreements//", views.edit_agreement, name="edit_agreement"), + path("agreements//delete/", views.delete_agreement, name="delete_agreement"), ] diff --git a/src/account/views/account.py b/src/account/views/account.py index 316cd234c..8f312b191 100644 --- a/src/account/views/account.py +++ b/src/account/views/account.py @@ -3,10 +3,14 @@ from django.contrib.auth import update_session_auth_hash, get_user_model from django.contrib.auth.decorators import login_required from django.contrib.auth.forms import PasswordChangeForm, SetPasswordForm +from django.core.mail import EmailMessage from django.core.paginator import Paginator from django.db.models import Q from django.shortcuts import render, redirect, get_object_or_404 -from django.utils.translation import ugettext as _ +from django.template.loader import get_template +from django.urls import reverse +from django.utils.http import urlencode +from django.utils.translation import gettext as _ from django.views.decorators.cache import never_cache from helfertool.utils import nopermission @@ -14,6 +18,8 @@ from ..forms import CreateUserForm, EditUserForm, DeleteUserForm, MergeUserForm from ..templatetags.globalpermissions import has_adduser_group +from smtplib import SMTPException + import logging logger = logging.getLogger("helfertool.account") @@ -31,6 +37,38 @@ def add_user(request): if form.is_valid(): user = form.save() + no_password = form.cleaned_data["no_password"] + + # if not password was set, send mail to user + if no_password: + context = { + "firstname": user.first_name, + "username": user.username, + "page_title": settings.PAGE_TITLE, + "contact_mail": settings.CONTACT_MAIL, + "password_reset_url": request.build_absolute_uri(reverse("account:password_reset")), + } + subject_template = get_template("account/add_user_mail_subject.txt") + subject = subject_template.render(context).strip() + + text_template = get_template("account/add_user_mail.txt") + text = text_template.render(context) + + # sent it and handle errors + mail = EmailMessage( + subject, + text, + settings.EMAIL_SENDER_ADDRESS, + [user.email], # to + reply_to=[settings.EMAIL_SENDER_ADDRESS], + ) + + try: + mail.send(fail_silently=False) + except (SMTPException, ConnectionError): + messages.warning( + request, _("Failed to send the notification email. Please contact the user on your own.") + ) messages.success(request, _("Added user %(username)s" % {"username": user})) @@ -39,6 +77,7 @@ def add_user(request): extra={ "user": request.user, "added_user": user.username, + "no_password": no_password, }, ) @@ -200,7 +239,7 @@ def merge_user(request, user_pk): @never_cache def list_users(request): # check permission - if not request.user.is_superuser: + if not (request.user.is_superuser or has_adduser_group(request.user)): return nopermission(request) # get users based on search term @@ -218,6 +257,7 @@ def list_users(request): ) else: all_users = get_user_model().objects.all().order_by("last_name") + search = "" # apply filters filterstr = request.GET.get("filter") @@ -251,9 +291,12 @@ def list_users(request): page = request.GET.get("page") users = paginator.get_page(page) + paginator_search_string = "?" + urlencode({"search": search, "filter": filterstr}) + context = { "users": users, - "search": search or "", + "search": search, "filter": filterstr, + "paginator_search_string": paginator_search_string, } return render(request, "account/list_users.html", context) diff --git a/src/corona/__init__.py b/src/adminautomation/__init__.py similarity index 100% rename from src/corona/__init__.py rename to src/adminautomation/__init__.py diff --git a/src/adminautomation/admin.py b/src/adminautomation/admin.py new file mode 100644 index 000000000..fb7b2c748 --- /dev/null +++ b/src/adminautomation/admin.py @@ -0,0 +1,5 @@ +from django.contrib import admin + +from .models import EventArchiveAutomation + +admin.site.register(EventArchiveAutomation) diff --git a/src/corona/apps.py b/src/adminautomation/apps.py similarity index 57% rename from src/corona/apps.py rename to src/adminautomation/apps.py index 70320ffdd..547e16f84 100644 --- a/src/corona/apps.py +++ b/src/adminautomation/apps.py @@ -1,6 +1,6 @@ from django.apps import AppConfig -class CoronaConfig(AppConfig): +class AdminautomationConfig(AppConfig): default_auto_field = "django.db.models.BigAutoField" - name = "corona" + name = "adminautomation" diff --git a/src/adminautomation/forms/__init__.py b/src/adminautomation/forms/__init__.py new file mode 100644 index 000000000..51293d2e9 --- /dev/null +++ b/src/adminautomation/forms/__init__.py @@ -0,0 +1 @@ +from .event import EventArchiveStatusForm, EventArchiveExceptionForm diff --git a/src/adminautomation/forms/event.py b/src/adminautomation/forms/event.py new file mode 100644 index 000000000..5884b5b50 --- /dev/null +++ b/src/adminautomation/forms/event.py @@ -0,0 +1,22 @@ +from django import forms +from django.utils.translation import gettext as _ + +from helfertool.forms import DatePicker + +from ..models import EventArchiveAutomation + + +class EventArchiveStatusForm(forms.Form): + months = forms.IntegerField( + min_value=0, + label=_("Months"), + ) + + +class EventArchiveExceptionForm(forms.ModelForm): + class Meta: + model = EventArchiveAutomation + fields = ["exception_date"] + widgets = { + "exception_date": DatePicker, + } diff --git a/src/adminautomation/locale/de/LC_MESSAGES/django.mo b/src/adminautomation/locale/de/LC_MESSAGES/django.mo new file mode 100644 index 000000000..7fd31ff3a Binary files /dev/null and b/src/adminautomation/locale/de/LC_MESSAGES/django.mo differ diff --git a/src/adminautomation/locale/de/LC_MESSAGES/django.po b/src/adminautomation/locale/de/LC_MESSAGES/django.po new file mode 100644 index 000000000..b8c5d1d95 --- /dev/null +++ b/src/adminautomation/locale/de/LC_MESSAGES/django.po @@ -0,0 +1,133 @@ +# SOME DESCRIPTIVE TITLE. +# Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER +# This file is distributed under the same license as the PACKAGE package. +# FIRST AUTHOR , YEAR. +# +#, fuzzy +msgid "" +msgstr "" +"Project-Id-Version: \n" +"Report-Msgid-Bugs-To: \n" +"POT-Creation-Date: 2025-12-27 10:56+0100\n" +"PO-Revision-Date: 2025-12-23 19:51+0100\n" +"Last-Translator: \n" +"Language-Team: \n" +"Language: de\n" +"MIME-Version: 1.0\n" +"Content-Type: text/plain; charset=UTF-8\n" +"Content-Transfer-Encoding: 8bit\n" +"Plural-Forms: nplurals=2; plural=(n != 1);\n" +"X-Generator: Poedit 3.8\n" + +#: adminautomation/forms/event.py:12 +msgid "Months" +msgstr "Monate" + +#: adminautomation/templates/adminautomation/edit_event_archive_exception.html:5 +msgid "Exception for automatic archiving reminders" +msgstr "Ausnahme für automatische Archivierungserinnerungen" + +#: adminautomation/templates/adminautomation/edit_event_archive_exception.html:9 +msgid "" +"No reminder mails to archive the event will be sent until the specified date." +msgstr "" +"Bis zum angegebenen Datum werden keine Erinnerungs-Mails zum Archivieren der " +"Veranstaltung versendet." + +#: adminautomation/templates/adminautomation/edit_event_archive_exception.html:23 +msgid "Save" +msgstr "Speichern" + +#: adminautomation/templates/adminautomation/edit_event_archive_exception.html:27 +msgid "Automatic archiving reminders are not configured." +msgstr "Automatische Archivierungserinnerungen sind nicht konfiguriert." + +#: adminautomation/templates/adminautomation/event_archive_status.html:5 +msgid "Event archiving" +msgstr "Archivierung von Veranstaltungen" + +#: adminautomation/templates/adminautomation/event_archive_status.html:8 +msgid "" +"This page shows events, which are older then the specified time, but not " +"archived yet." +msgstr "" +"Diese Seite zeigt Veranstaltungen an, die älter als die angegebene Zeit " +"sind, aber noch nicht archiviert sind." + +#: adminautomation/templates/adminautomation/event_archive_status.html:17 +msgid "Update" +msgstr "Aktualisieren" + +#: adminautomation/templates/adminautomation/event_archive_status.html:25 +msgid "Event" +msgstr "Veranstaltung" + +#: adminautomation/templates/adminautomation/event_archive_status.html:28 +msgid "Event date" +msgstr "Veranstaltungsdatum" + +#: adminautomation/templates/adminautomation/event_archive_status.html:32 +msgid "Automatic reminder" +msgstr "Automatische Erinnerungen" + +#: adminautomation/templates/adminautomation/event_archive_status.html:47 +#, python-format +msgid "(%(time)s ago)" +msgstr "(vor %(time)s)" + +#: adminautomation/templates/adminautomation/event_archive_status.html:64 +#, python-format +msgid "Exception until %(exception_date)s" +msgstr "Ausnahme bis %(exception_date)s" + +#: adminautomation/templates/adminautomation/event_archive_status.html:69 +#, python-format +msgid "Sent on %(last_reminder)s" +msgstr "Gesendet am %(last_reminder)s" + +#: adminautomation/templates/adminautomation/event_archive_status.html:76 +msgid "Edit exception" +msgstr "Ausnahme bearbeiten" + +#: adminautomation/templates/adminautomation/event_archive_status.html:85 +msgid "No events found." +msgstr "Keine Veranstaltungen gefunden." + +#: adminautomation/templates/adminautomation/mail/event_archive_automation.txt:1 +#, python-format +msgid "" +"Hello,\n" +"\n" +"the event %(eventname)s has meanwhile taken place. Therefore, the personal " +"data must be deleted.\n" +"\n" +"Please archive the event now (Edit event -> Archive event).\n" +"\n" +"This will delete all personal data. The remaining data will be retained and " +"can be reused for future events. The number of registered people will also " +"be saved." +msgstr "" +"Hallo,\n" +"\n" +"die Veranstaltung %(eventname)s hat inzwischen stattgefunden. Daher müssen " +"nun die personenbezogenen Daten gelöscht werden.\n" +"\n" +"Bitte archiviere die Veranstaltung jetzt (Veranstaltung bearbeiten -> " +"Veranstaltung archivieren).\n" +"\n" +"Dadurch werden alle personenbezogenen Daten gelöscht. Die übrigen Daten " +"bleiben erhalten und können für zukünftige Veranstaltungen wiederverwendet " +"werden. Die Anzahl der registrierten Personen wird ebenfalls gespeichert." + +#: adminautomation/templates/adminautomation/mail/event_archive_automation.txt:9 +msgid "Further information:" +msgstr "Weitere Informationen:" + +#: adminautomation/templates/adminautomation/mail/event_archive_automation.txt:11 +msgid "Thank you!" +msgstr "Danke!" + +#: adminautomation/templates/adminautomation/mail/event_archive_automation_subject.txt:1 +#, python-format +msgid "Deletion of personal data for %(eventname)s (%(page_title)s)" +msgstr "Löschen der personenbezogenen Daten für %(eventname)s (%(page_title)s)" diff --git a/src/corona/migrations/0001_initial.py b/src/adminautomation/migrations/0001_initial.py similarity index 55% rename from src/corona/migrations/0001_initial.py rename to src/adminautomation/migrations/0001_initial.py index 1950413b9..6eb9e9a6f 100644 --- a/src/corona/migrations/0001_initial.py +++ b/src/adminautomation/migrations/0001_initial.py @@ -1,22 +1,24 @@ -# Generated by Django 3.2.7 on 2021-09-26 12:04 +# Generated by Django 4.2.21 on 2025-12-22 21:40 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): - initial = True dependencies = [ - ("registration", "0055_event_corona"), + ("registration", "0065_alter_event_shirt_sizes_alter_helper_shirt"), ] operations = [ migrations.CreateModel( - name="CoronaSettings", + name="EventArchiveAutomation", fields=[ ("id", models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name="ID")), + ("reminder_first", models.DateTimeField(blank=True, null=True)), + ("reminder_latest", models.DateTimeField(blank=True, null=True)), + ("exception_date", models.DateField(blank=True, null=True)), ("event", models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, to="registration.event")), ], ), diff --git a/src/adminautomation/migrations/0002_rename_reminder_first_eventarchiveautomation_last_reminder_and_more.py b/src/adminautomation/migrations/0002_rename_reminder_first_eventarchiveautomation_last_reminder_and_more.py new file mode 100644 index 000000000..5bfcd6e86 --- /dev/null +++ b/src/adminautomation/migrations/0002_rename_reminder_first_eventarchiveautomation_last_reminder_and_more.py @@ -0,0 +1,21 @@ +# Generated by Django 4.2.21 on 2025-12-22 21:44 + +from django.db import migrations + + +class Migration(migrations.Migration): + dependencies = [ + ("adminautomation", "0001_initial"), + ] + + operations = [ + migrations.RenameField( + model_name="eventarchiveautomation", + old_name="reminder_first", + new_name="last_reminder", + ), + migrations.RemoveField( + model_name="eventarchiveautomation", + name="reminder_latest", + ), + ] diff --git a/src/adminautomation/migrations/0003_alter_eventarchiveautomation_last_reminder.py b/src/adminautomation/migrations/0003_alter_eventarchiveautomation_last_reminder.py new file mode 100644 index 000000000..511eef9e1 --- /dev/null +++ b/src/adminautomation/migrations/0003_alter_eventarchiveautomation_last_reminder.py @@ -0,0 +1,17 @@ +# Generated by Django 4.2.21 on 2025-12-23 14:55 + +from django.db import migrations, models + + +class Migration(migrations.Migration): + dependencies = [ + ("adminautomation", "0002_rename_reminder_first_eventarchiveautomation_last_reminder_and_more"), + ] + + operations = [ + migrations.AlterField( + model_name="eventarchiveautomation", + name="last_reminder", + field=models.DateField(blank=True, null=True), + ), + ] diff --git a/src/corona/migrations/__init__.py b/src/adminautomation/migrations/__init__.py similarity index 100% rename from src/corona/migrations/__init__.py rename to src/adminautomation/migrations/__init__.py diff --git a/src/adminautomation/models/__init__.py b/src/adminautomation/models/__init__.py new file mode 100644 index 000000000..397278405 --- /dev/null +++ b/src/adminautomation/models/__init__.py @@ -0,0 +1 @@ +from .event import EventArchiveAutomation diff --git a/src/adminautomation/models/event.py b/src/adminautomation/models/event.py new file mode 100644 index 000000000..5fe09b4ec --- /dev/null +++ b/src/adminautomation/models/event.py @@ -0,0 +1,21 @@ +from django.db import models + + +class EventArchiveAutomation(models.Model): + event = models.OneToOneField( + "registration.Event", + on_delete=models.CASCADE, + ) + + last_reminder = models.DateField( + blank=True, + null=True, + ) + + exception_date = models.DateField( + blank=True, + null=True, + ) + + def __str__(self): + return self.event.name diff --git a/src/adminautomation/tasks.py b/src/adminautomation/tasks.py new file mode 100644 index 000000000..67be8466c --- /dev/null +++ b/src/adminautomation/tasks.py @@ -0,0 +1,71 @@ +from __future__ import absolute_import + +from celery import shared_task +from django.conf import settings +from django.template.loader import get_template +from django.utils import timezone + +from dateutil.relativedelta import relativedelta +from datetime import timedelta + +from .utils import event_archive_automation_enabled + +from helfertool.utils import cache_lock + + +@shared_task(bind=True) +def event_archive_automation(self): + from .models import EventArchiveAutomation + from registration.models import Event + + if not event_archive_automation_enabled(): + return + + with cache_lock("event_archive_automation", self.app.oid) as acquired: + if acquired: + today = timezone.now().date() + + # get all events that are not archived, but should be (soon) + deadline = ( + today + - relativedelta(months=settings.AUTOMATION_EVENTS_ARCHIVE_DEADLINE) + + relativedelta(days=settings.AUTOMATION_EVENTS_ARCHIVE_START_BEFORE_DEADLINE) + ) + events = Event.objects.filter(archived=False, date__lte=deadline) + + for event in events: + automation_data, created = EventArchiveAutomation.objects.get_or_create(event=event) + + # there is an exception and it is not reached yet -> skip + if automation_data.exception_date and automation_data.exception_date >= today: + continue + + # a reminder was sent within the specified interval -> skip + if automation_data.last_reminder is not None and (today - automation_data.last_reminder) < timedelta( + days=settings.AUTOMATION_EVENTS_ARCHIVE_INTERVAL + ): + continue + + # send mail + subject_template = get_template("adminautomation/mail/event_archive_automation_subject.txt") + subject = subject_template.render( + { + "event": event, + "page_title": settings.PAGE_TITLE, + } + ).rstrip() + + text_template = get_template("adminautomation/mail/event_archive_automation.txt") + text = text_template.render( + { + "event": event, + "docs": settings.AUTOMATION_EVENTS_ARCHIVE_DOCS, + } + ) + + mail_sent = event.send_admin_mail(subject, text) + + # update timestamps + if mail_sent: + automation_data.last_reminder = today + automation_data.save() diff --git a/src/adminautomation/templates/adminautomation/edit_event_archive_exception.html b/src/adminautomation/templates/adminautomation/edit_event_archive_exception.html new file mode 100644 index 000000000..cc6706b71 --- /dev/null +++ b/src/adminautomation/templates/adminautomation/edit_event_archive_exception.html @@ -0,0 +1,30 @@ +{% extends "helfertool/admin.html" %} +{% load i18n django_bootstrap5 icons translation %} + +{% block content %} +

{% trans "Exception for automatic archiving reminders" %}

+ + {% if form %} + + +
+ {% csrf_token %} + + {% bootstrap_form_errors form %} + +
+
+ {% bootstrap_field form.exception_date layout="floating" %} +
+
+ + +
+ {% else %} + + {% endif %} +{% endblock %} diff --git a/src/adminautomation/templates/adminautomation/event_archive_status.html b/src/adminautomation/templates/adminautomation/event_archive_status.html new file mode 100644 index 000000000..fe9ef0a5e --- /dev/null +++ b/src/adminautomation/templates/adminautomation/event_archive_status.html @@ -0,0 +1,86 @@ +{% extends "helfertool/admin.html" %} +{% load i18n django_bootstrap5 icons %} + +{% block content %} +

{% trans "Event archiving" %}

+ + + +
+ {% bootstrap_form form layout="floating" %} + {% bootstrap_form_errors form %} + + +
+ + {% if events %} +
    +
  • +
    +
    + {% trans "Event" %} +
    +
    + {% trans "Event date" %} +
    + {% if archive_automation_enabled %} +
    + {% trans "Automatic reminder" %} +
    + {% endif %} +
    +
  • + + {% for event in events %} +
  • +
    + +
    + {{ event.date }} + + {% blocktrans trimmed with time=event.date|timesince %} + ({{ time }} ago) + {% endblocktrans %} + +
    + {% if archive_automation_enabled %} +
    + {% if event.eventarchiveautomation %} + {% comment %} + we show the exception date if no reminder mail was sent since then + this means: + - a exception date is set, but no last reminder date is set (= the exception was set before the first reminder) + - the last reminder was sent before the excetption date (=the exception was added after a reminder) + {% endcomment %} + {% if event.eventarchiveautomation.exception_date != None and event.eventarchiveautomation.last_reminder == None or event.eventarchiveautomation.exception_date > event.eventarchiveautomation.last_reminder %} + {% icon "check-circle" %} + {% blocktrans with exception_date=event.eventarchiveautomation.exception_date trimmed %} + Exception until {{ exception_date }} + {% endblocktrans %} + {% elif event.eventarchiveautomation.last_reminder %} + {% icon "envelope" %} + {% blocktrans with last_reminder=event.eventarchiveautomation.last_reminder trimmed %} + Sent on {{ last_reminder }} + {% endblocktrans %} + {% endif %} +
    + {% endif %} + + {% icon "pencil-alt" %} {% trans "Edit exception" %} + +
    + {% endif %} +
    +
  • + {% endfor %} +
+ {% else %} +

{% trans "No events found." %}

+ {% endif %} +{% endblock %} diff --git a/src/adminautomation/templates/adminautomation/mail/event_archive_automation.txt b/src/adminautomation/templates/adminautomation/mail/event_archive_automation.txt new file mode 100644 index 000000000..ca07046f2 --- /dev/null +++ b/src/adminautomation/templates/adminautomation/mail/event_archive_automation.txt @@ -0,0 +1,11 @@ +{% load i18n %}{% blocktrans with eventname=event.name|safe %}Hello, + +the event {{ eventname }} has meanwhile taken place. Therefore, the personal data must be deleted. + +Please archive the event now (Edit event -> Archive event). + +This will delete all personal data. The remaining data will be retained and can be reused for future events. The number of registered people will also be saved.{% endblocktrans %} +{% if docs %} +{% trans "Further information:" %} {{ docs|safe }} +{% endif %} +{% trans "Thank you!" %} diff --git a/src/adminautomation/templates/adminautomation/mail/event_archive_automation_subject.txt b/src/adminautomation/templates/adminautomation/mail/event_archive_automation_subject.txt new file mode 100644 index 000000000..36423c96a --- /dev/null +++ b/src/adminautomation/templates/adminautomation/mail/event_archive_automation_subject.txt @@ -0,0 +1 @@ +{% load i18n %}{% blocktrans with eventname=event.name|safe page_title=page_title|safe %}Deletion of personal data for {{ eventname }} ({{ page_title }}){% endblocktrans %} diff --git a/src/adminautomation/tests.py b/src/adminautomation/tests.py new file mode 100644 index 000000000..7ce503c2d --- /dev/null +++ b/src/adminautomation/tests.py @@ -0,0 +1,3 @@ +from django.test import TestCase + +# Create your tests here. diff --git a/src/adminautomation/urls.py b/src/adminautomation/urls.py new file mode 100644 index 000000000..7fc2da93e --- /dev/null +++ b/src/adminautomation/urls.py @@ -0,0 +1,13 @@ +from django.urls import path + +from . import views + +app_name = "adminautomation" +urlpatterns = [ + path("manage/archivestatus/", views.event_archive_status, name="event_archive_status"), + path( + "/archiveexception/", + views.edit_event_archive_exception, + name="edit_event_archive_exception", + ), +] diff --git a/src/adminautomation/utils.py b/src/adminautomation/utils.py new file mode 100644 index 000000000..d769b5dcd --- /dev/null +++ b/src/adminautomation/utils.py @@ -0,0 +1,8 @@ +from django.conf import settings + + +def event_archive_automation_enabled(): + return ( + settings.AUTOMATION_EVENTS_ARCHIVE_DEADLINE is not None + and settings.AUTOMATION_EVENTS_ARCHIVE_INTERVAL is not None + ) diff --git a/src/adminautomation/views/__init__.py b/src/adminautomation/views/__init__.py new file mode 100644 index 000000000..0692db22a --- /dev/null +++ b/src/adminautomation/views/__init__.py @@ -0,0 +1 @@ +from .event import event_archive_status, edit_event_archive_exception diff --git a/src/adminautomation/views/event.py b/src/adminautomation/views/event.py new file mode 100644 index 000000000..8ee171953 --- /dev/null +++ b/src/adminautomation/views/event.py @@ -0,0 +1,85 @@ +from django.conf import settings +from django.contrib.auth.decorators import login_required +from django.shortcuts import render, redirect, get_object_or_404 +from django.utils.translation import gettext as _ +from django.views.decorators.cache import never_cache + +from datetime import datetime +from dateutil.relativedelta import relativedelta + +from ..models import EventArchiveAutomation +from ..forms import ( + EventArchiveStatusForm, + EventArchiveExceptionForm, +) +from ..utils import event_archive_automation_enabled + +from helfertool.utils import nopermission +from registration.models import Event +from registration.decorators import archived_not_available + +import logging + +logger = logging.getLogger("helfertool.registration") + + +@login_required +@never_cache +def event_archive_status(request): + if not request.user.is_superuser: + return nopermission(request) + + # form for months + months = 3 + if settings.AUTOMATION_EVENTS_ARCHIVE_DEADLINE is not None: + months = max(settings.AUTOMATION_EVENTS_ARCHIVE_DEADLINE - 1, 0) + + form = EventArchiveStatusForm(request.GET or None, initial={"months": months}) + if form.is_valid(): + months = form.cleaned_data.get("months") + + # get events + deadline = datetime.today() - relativedelta(months=months) + events = Event.objects.filter(archived=False, date__lte=deadline).order_by("date") + + context = { + "form": form, + "events": events, + "archive_automation_enabled": event_archive_automation_enabled(), + } + return render(request, "adminautomation/event_archive_status.html", context) + + +@login_required +@never_cache +@archived_not_available +def edit_event_archive_exception(request, event_url_name): + if not request.user.is_superuser: + return nopermission(request) + + event = get_object_or_404(Event, url_name=event_url_name) + + form = None + if event_archive_automation_enabled(): + automation_data, created = EventArchiveAutomation.objects.get_or_create(event=event) + form = EventArchiveExceptionForm(request.POST or None, instance=automation_data) + + if form.is_valid(): + form.save() + + logger.info( + "archiveexception changed", + extra={ + "user": request.user, + "event": event, + }, + ) + + return redirect("adminautomation:event_archive_status") + + # render page + context = { + "event": event, + "form": form, + } + return render(request, "adminautomation/edit_event_archive_exception.html", context) diff --git a/src/badges/admin.py b/src/badges/admin.py index 850bc3aab..5c4d97fec 100644 --- a/src/badges/admin.py +++ b/src/badges/admin.py @@ -1,6 +1,6 @@ from django.contrib import admin -from .models import BadgeSettings, BadgeDesign, BadgePermission, BadgeRole, Badge, SpecialBadges +from .models import BadgeSettings, BadgeDesign, BadgePermission, BadgeRole, BadgeDefaults, Badge, SpecialBadges class SpecialBadgesAdmin(admin.ModelAdmin): @@ -12,4 +12,5 @@ class SpecialBadgesAdmin(admin.ModelAdmin): admin.site.register(BadgeDesign) admin.site.register(BadgePermission) admin.site.register(BadgeRole) +admin.site.register(BadgeDefaults) admin.site.register(SpecialBadges, SpecialBadgesAdmin) diff --git a/src/badges/creator.py b/src/badges/creator.py index aabb39722..d8302e0e1 100644 --- a/src/badges/creator.py +++ b/src/badges/creator.py @@ -6,6 +6,7 @@ import shutil import badges.models +from badges.encoding import LATEX_T1_CHARS class BadgeCreatorError(Exception): @@ -136,7 +137,11 @@ def generate(self): os.path.basename(self.latex_file_path), ], cwd=self.dir, + env=env, + timeout=settings.BADGE_BUILD_TIMEOUT, ) + except subprocess.TimeoutExpired: + raise BadgeCreatorError("PDF generation took too long") except subprocess.CalledProcessError as e: raise BadgeCreatorError("PDF generation failed", e.output.decode("utf8")) @@ -231,19 +236,35 @@ def _latex_color(self, string): return string.upper() def _latex_escape(self, string): - string = string.replace("\\", r"\textbackslash ") - string = string.replace(r" ", r"\ ") - string = string.replace(r"&", r"\&") - string = string.replace(r"%", r"\%") - string = string.replace(r"$", r"\$") - string = string.replace(r"#", r"\#") - string = string.replace(r"_", r"\_") - string = string.replace(r"{", r"\{") - string = string.replace(r"}", r"\}") - string = string.replace(r"~", r"\textasciitilde ") - string = string.replace(r"^", r"\textasciicircum ") - - return "{" + string + "}" + # mapping for special chars to LaTeX + mapping = [ + ["\\", "\\textbackslash "], + [" ", "\\ "], + ["&", "\\&"], + ["%", "\\%"], + ["$", "\\$"], + ["#", "\\#"], + ["_", "\\_"], + ["{", "\\{"], + ["}", "\\}"], + ["~", "\\textasciitilde "], + ["^", "\\textasciicircum "], + ] + + # allowed chars (LaTeX T1 encoding + mapped chars) + allowed_chars = LATEX_T1_CHARS + [m[0] for m in mapping] + + # remove chars that we do not want to have + string_cleaned = "" + for s in string: + if s in allowed_chars: + string_cleaned += s + + # apply mapping + for search, replace in mapping: + string_cleaned = string_cleaned.replace(search, replace) + + return "{" + string_cleaned + "}" def _copy_photo(self, src_path): return self._copy_file(src_path, self.dir_photos) diff --git a/src/badges/encoding.py b/src/badges/encoding.py new file mode 100644 index 000000000..53cde9cc8 --- /dev/null +++ b/src/badges/encoding.py @@ -0,0 +1,260 @@ +# source: https://en.wikipedia.org/w/index.php?title=Cork_encoding + +LATEX_T1_CHARS = [ + "\u0020", + "\u0021", + "\u0022", + "\u0023", + "\u0024", + "\u0025", + "\u0026", + "\u0028", + "\u0029", + "\u002a", + "\u002b", + "\u002c", + "\u002d", + "\u002e", + "\u002f", + "\u0030", + "\u0031", + "\u0032", + "\u0033", + "\u0034", + "\u0035", + "\u0036", + "\u0037", + "\u0038", + "\u0039", + "\u003a", + "\u003b", + "\u003c", + "\u003d", + "\u003e", + "\u003f", + "\u0040", + "\u0041", + "\u0042", + "\u0043", + "\u0044", + "\u0045", + "\u0046", + "\u0047", + "\u0048", + "\u0049", + "\u004a", + "\u004b", + "\u004c", + "\u004d", + "\u004e", + "\u004f", + "\u0050", + "\u0051", + "\u0052", + "\u0053", + "\u0054", + "\u0055", + "\u0056", + "\u0057", + "\u0058", + "\u0059", + "\u005a", + "\u005b", + "\u005c", + "\u005d", + "\u005e", + "\u005f", + "\u0060", + "\u0061", + "\u0062", + "\u0063", + "\u0064", + "\u0065", + "\u0066", + "\u0067", + "\u0068", + "\u0069", + "\u006a", + "\u006b", + "\u006c", + "\u006d", + "\u006e", + "\u006f", + "\u0070", + "\u0071", + "\u0072", + "\u0073", + "\u0074", + "\u0075", + "\u0076", + "\u0077", + "\u0078", + "\u0079", + "\u007a", + "\u007b", + "\u007c", + "\u007d", + "\u007e", + "\u00a1", + "\u00a3", + "\u00a7", + "\u00a8", + "\u00ab", + "\u00ad", + "\u00af", + "\u00b4", + "\u00b8", + "\u00bb", + "\u00bf", + "\u00c0", + "\u00c1", + "\u00c2", + "\u00c3", + "\u00c4", + "\u00c5", + "\u00c6", + "\u00c7", + "\u00c8", + "\u00c9", + "\u00ca", + "\u00cb", + "\u00cc", + "\u00cd", + "\u00ce", + "\u00cf", + "\u00d0", + "\u00d1", + "\u00d2", + "\u00d3", + "\u00d4", + "\u00d5", + "\u00d6", + "\u00d8", + "\u00d9", + "\u00da", + "\u00db", + "\u00dc", + "\u00dd", + "\u00de", + "\u00df", + "\u00e0", + "\u00e1", + "\u00e2", + "\u00e3", + "\u00e4", + "\u00e5", + "\u00e6", + "\u00e7", + "\u00e8", + "\u00e9", + "\u00ea", + "\u00eb", + "\u00ec", + "\u00ed", + "\u00ee", + "\u00ef", + "\u00f0", + "\u00f1", + "\u00f2", + "\u00f3", + "\u00f4", + "\u00f5", + "\u00f6", + "\u00f8", + "\u00f9", + "\u00fa", + "\u00fb", + "\u00fc", + "\u00fd", + "\u00fe", + "\u00ff", + "\u0102", + "\u0103", + "\u0104", + "\u0105", + "\u0106", + "\u0107", + "\u010c", + "\u010d", + "\u010e", + "\u010f", + "\u0111", + "\u0118", + "\u0119", + "\u011a", + "\u011b", + "\u011e", + "\u011f", + "\u0130", + "\u0131", + "\u0132", + "\u0133", + "\u0139", + "\u013a", + "\u013d", + "\u013e", + "\u0141", + "\u0142", + "\u0143", + "\u0144", + "\u0147", + "\u0148", + "\u014a", + "\u014b", + "\u0150", + "\u0151", + "\u0152", + "\u0153", + "\u0154", + "\u0155", + "\u0158", + "\u0159", + "\u015a", + "\u015b", + "\u0160", + "\u0161", + "\u0164", + "\u0165", + "\u016e", + "\u016f", + "\u0170", + "\u0171", + "\u0178", + "\u0179", + "\u017a", + "\u017b", + "\u017c", + "\u017d", + "\u017e", + "\u0218", + "\u0219", + "\u021a", + "\u021b", + "\u0237", + "\u02c6", + "\u02c7", + "\u02d8", + "\u02d9", + "\u02da", + "\u02db", + "\u02dc", + "\u02dd", + "\u1e9e", + "\u200b", + "\u2013", + "\u2014", + "\u2018", + "\u2019", + "\u201a", + "\u201c", + "\u201d", + "\u201e", + "\u2039", + "\u203a", + "\u2080", + "\ufb00", + "\ufb01", + "\ufb02", + "\ufb03", + "\ufb04", +] diff --git a/src/badges/forms/barcode.py b/src/badges/forms/barcode.py index c5b8627ec..9df0d784e 100644 --- a/src/badges/forms/barcode.py +++ b/src/badges/forms/barcode.py @@ -1,6 +1,6 @@ from django import forms from django.core.exceptions import ValidationError -from django.utils.translation import ugettext_lazy as _ +from django.utils.translation import gettext_lazy as _ from ..models import Badge diff --git a/src/badges/forms/defaults.py b/src/badges/forms/defaults.py index 3642e2c73..99e8e5310 100644 --- a/src/badges/forms/defaults.py +++ b/src/badges/forms/defaults.py @@ -1,5 +1,5 @@ from django import forms -from django.utils.translation import ugettext as _ +from django.utils.translation import gettext as _ from ..models import BadgeDesign, BadgeRole, BadgeDefaults diff --git a/src/badges/forms/settings.py b/src/badges/forms/settings.py index ca20bca69..a76a2fefc 100644 --- a/src/badges/forms/settings.py +++ b/src/badges/forms/settings.py @@ -1,6 +1,6 @@ from django import forms from django.core.exceptions import ValidationError -from django.utils.translation import ugettext_lazy as _ +from django.utils.translation import gettext_lazy as _ from ..models import BadgeSettings diff --git a/src/badges/locale/de/LC_MESSAGES/django.po b/src/badges/locale/de/LC_MESSAGES/django.po index 8d3137a0b..14fcea46b 100644 --- a/src/badges/locale/de/LC_MESSAGES/django.po +++ b/src/badges/locale/de/LC_MESSAGES/django.po @@ -7,7 +7,7 @@ msgid "" msgstr "" "Project-Id-Version: \n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2022-07-25 19:30+0200\n" +"POT-Creation-Date: 2025-12-23 19:42+0100\n" "PO-Revision-Date: \n" "Last-Translator: \n" "Language-Team: \n" @@ -287,8 +287,8 @@ msgstr "Badge für %(name)s" msgid "Special badges for %(name)s" msgstr "Spezial Badges für %(name)s" -#: badges/templates/badges/edit_badge.html:65 -#: badges/templates/badges/edit_design.html:44 +#: badges/templates/badges/edit_badge.html:69 +#: badges/templates/badges/edit_design.html:52 #: badges/templates/badges/edit_permission.html:32 #: badges/templates/badges/edit_role.html:34 #: badges/templates/badges/settings.html:141 @@ -553,10 +553,12 @@ msgstr "" "den Badge Einstellungen eine primäre Aufgabe auswählen." #: badges/views/generate.py:186 +#, python-brace-format msgid "{} (only unregistered)" msgstr "{} (nicht registrierte Badges)" #: badges/views/generate.py:188 +#, python-brace-format msgid "{} (all)" msgstr "{} (alle)" diff --git a/src/badges/migrations/0001_initial.py b/src/badges/migrations/0001_initial.py index 0b7e09b76..36cbf481c 100644 --- a/src/badges/migrations/0001_initial.py +++ b/src/badges/migrations/0001_initial.py @@ -9,7 +9,6 @@ class Migration(migrations.Migration): - dependencies = [] operations = [ diff --git a/src/badges/migrations/0002_auto_20151229_1953.py b/src/badges/migrations/0002_auto_20151229_1953.py index 7a0728faf..ef24bc42f 100644 --- a/src/badges/migrations/0002_auto_20151229_1953.py +++ b/src/badges/migrations/0002_auto_20151229_1953.py @@ -6,7 +6,6 @@ class Migration(migrations.Migration): - dependencies = [ ("badges", "0001_initial"), ("registration", "0001_initial"), diff --git a/src/badges/migrations/0003_badgedesign_bg_color.py b/src/badges/migrations/0003_badgedesign_bg_color.py index 492881c93..e5d86896c 100644 --- a/src/badges/migrations/0003_badgedesign_bg_color.py +++ b/src/badges/migrations/0003_badgedesign_bg_color.py @@ -7,7 +7,6 @@ class Migration(migrations.Migration): - dependencies = [ ("badges", "0002_auto_20151229_1953"), ] diff --git a/src/badges/migrations/0004_auto_20160306_1424.py b/src/badges/migrations/0004_auto_20160306_1424.py index 98f824688..a1f8aa1eb 100644 --- a/src/badges/migrations/0004_auto_20160306_1424.py +++ b/src/badges/migrations/0004_auto_20160306_1424.py @@ -7,7 +7,6 @@ class Migration(migrations.Migration): - dependencies = [ ("badges", "0003_badgedesign_bg_color"), ] diff --git a/src/badges/migrations/0005_auto_20160306_1426.py b/src/badges/migrations/0005_auto_20160306_1426.py index 64775858b..34d372b65 100644 --- a/src/badges/migrations/0005_auto_20160306_1426.py +++ b/src/badges/migrations/0005_auto_20160306_1426.py @@ -7,7 +7,6 @@ class Migration(migrations.Migration): - dependencies = [ ("badges", "0004_auto_20160306_1424"), ] diff --git a/src/badges/migrations/0006_badgedefaults_no_default_role.py b/src/badges/migrations/0006_badgedefaults_no_default_role.py index 311adb1f1..d79233b50 100644 --- a/src/badges/migrations/0006_badgedefaults_no_default_role.py +++ b/src/badges/migrations/0006_badgedefaults_no_default_role.py @@ -6,7 +6,6 @@ class Migration(migrations.Migration): - dependencies = [ ("badges", "0005_auto_20160306_1426"), ] diff --git a/src/badges/migrations/0007_badgesettings_language.py b/src/badges/migrations/0007_badgesettings_language.py index 3d4e863b5..892dd6bca 100644 --- a/src/badges/migrations/0007_badgesettings_language.py +++ b/src/badges/migrations/0007_badgesettings_language.py @@ -6,7 +6,6 @@ class Migration(migrations.Migration): - dependencies = [ ("badges", "0006_badgedefaults_no_default_role"), ] diff --git a/src/badges/migrations/0008_badgesettings_only_coordinators.py b/src/badges/migrations/0008_badgesettings_only_coordinators.py index a2db85fbd..806cde3de 100644 --- a/src/badges/migrations/0008_badgesettings_only_coordinators.py +++ b/src/badges/migrations/0008_badgesettings_only_coordinators.py @@ -6,7 +6,6 @@ class Migration(migrations.Migration): - dependencies = [ ("badges", "0007_badgesettings_language"), ] diff --git a/src/badges/migrations/0009_auto_20170414_1630.py b/src/badges/migrations/0009_auto_20170414_1630.py index 7d91b5c4f..d9fdbeb26 100644 --- a/src/badges/migrations/0009_auto_20170414_1630.py +++ b/src/badges/migrations/0009_auto_20170414_1630.py @@ -7,7 +7,6 @@ class Migration(migrations.Migration): - dependencies = [ ("badges", "0008_badgesettings_only_coordinators"), ] diff --git a/src/badges/migrations/0010_badge_barcode.py b/src/badges/migrations/0010_badge_barcode.py index 06a06c571..a9bb24400 100644 --- a/src/badges/migrations/0010_badge_barcode.py +++ b/src/badges/migrations/0010_badge_barcode.py @@ -6,7 +6,6 @@ class Migration(migrations.Migration): - dependencies = [ ("badges", "0009_auto_20170414_1630"), ] diff --git a/src/badges/migrations/0011_set_barcode.py b/src/badges/migrations/0011_set_barcode.py index ffd567bdc..22b88c963 100644 --- a/src/badges/migrations/0011_set_barcode.py +++ b/src/badges/migrations/0011_set_barcode.py @@ -13,7 +13,6 @@ def copy_barcode(apps, schema_editor): class Migration(migrations.Migration): - dependencies = [ ("badges", "0010_badge_barcode"), ] diff --git a/src/badges/migrations/0012_auto_20181021_1954.py b/src/badges/migrations/0012_auto_20181021_1954.py index d814b4702..a6b0a81cb 100644 --- a/src/badges/migrations/0012_auto_20181021_1954.py +++ b/src/badges/migrations/0012_auto_20181021_1954.py @@ -6,7 +6,6 @@ class Migration(migrations.Migration): - dependencies = [ ("badges", "0011_set_barcode"), ] diff --git a/src/badges/migrations/0013_auto_20200614_1918.py b/src/badges/migrations/0013_auto_20200614_1918.py index 2fbf06661..5dabed16c 100644 --- a/src/badges/migrations/0013_auto_20200614_1918.py +++ b/src/badges/migrations/0013_auto_20200614_1918.py @@ -5,7 +5,6 @@ class Migration(migrations.Migration): - dependencies = [ ("badges", "0012_auto_20181021_1954"), ] diff --git a/src/badges/migrations/0014_auto_20200907_2140.py b/src/badges/migrations/0014_auto_20200907_2140.py index 6ed806510..4ceb7bd9a 100644 --- a/src/badges/migrations/0014_auto_20200907_2140.py +++ b/src/badges/migrations/0014_auto_20200907_2140.py @@ -4,7 +4,6 @@ class Migration(migrations.Migration): - dependencies = [ ("badges", "0013_auto_20200614_1918"), ] diff --git a/src/badges/migrations/0015_badge_add_event.py b/src/badges/migrations/0015_badge_add_event.py index 2a24f439e..8d73ec826 100644 --- a/src/badges/migrations/0015_badge_add_event.py +++ b/src/badges/migrations/0015_badge_add_event.py @@ -5,7 +5,6 @@ class Migration(migrations.Migration): - dependencies = [ ("registration", "0043_auto_20200409_1711"), ("badges", "0014_auto_20200907_2140"), diff --git a/src/badges/migrations/0016_badge_fill_event.py b/src/badges/migrations/0016_badge_fill_event.py index 26e568174..ac677d164 100644 --- a/src/badges/migrations/0016_badge_fill_event.py +++ b/src/badges/migrations/0016_badge_fill_event.py @@ -12,7 +12,6 @@ def fill_event_field(apps, schema_editor): class Migration(migrations.Migration): - dependencies = [ ("badges", "0015_badge_add_event"), ] diff --git a/src/badges/migrations/0017_badge_event_required.py b/src/badges/migrations/0017_badge_event_required.py index acb8fce19..9ccde245e 100644 --- a/src/badges/migrations/0017_badge_event_required.py +++ b/src/badges/migrations/0017_badge_event_required.py @@ -5,7 +5,6 @@ class Migration(migrations.Migration): - dependencies = [ ("registration", "0043_auto_20200409_1711"), ("badges", "0016_badge_fill_event"), diff --git a/src/badges/migrations/0018_specialbadges.py b/src/badges/migrations/0018_specialbadges.py index 98ca1a4a4..a30c0c884 100644 --- a/src/badges/migrations/0018_specialbadges.py +++ b/src/badges/migrations/0018_specialbadges.py @@ -6,7 +6,6 @@ class Migration(migrations.Migration): - dependencies = [ ("registration", "0043_auto_20200409_1711"), ("badges", "0017_badge_event_required"), diff --git a/src/badges/migrations/0019_auto_20201229_2210.py b/src/badges/migrations/0019_auto_20201229_2210.py index 3e3c9144e..8ffb0b68d 100644 --- a/src/badges/migrations/0019_auto_20201229_2210.py +++ b/src/badges/migrations/0019_auto_20201229_2210.py @@ -4,7 +4,6 @@ class Migration(migrations.Migration): - dependencies = [ ("badges", "0018_specialbadges"), ] diff --git a/src/badges/migrations/0020_auto_20210110_2100.py b/src/badges/migrations/0020_auto_20210110_2100.py index 6c9c04863..3e56bedc2 100644 --- a/src/badges/migrations/0020_auto_20210110_2100.py +++ b/src/badges/migrations/0020_auto_20210110_2100.py @@ -4,7 +4,6 @@ class Migration(migrations.Migration): - dependencies = [ ("badges", "0019_auto_20201229_2210"), ] diff --git a/src/badges/migrations/0021_auto_20210523_1533.py b/src/badges/migrations/0021_auto_20210523_1533.py index 5d0e7c113..2a2863b8c 100644 --- a/src/badges/migrations/0021_auto_20210523_1533.py +++ b/src/badges/migrations/0021_auto_20210523_1533.py @@ -4,7 +4,6 @@ class Migration(migrations.Migration): - dependencies = [ ("badges", "0020_auto_20210110_2100"), ] diff --git a/src/badges/migrations/0022_auto_20211106_1716.py b/src/badges/migrations/0022_auto_20211106_1716.py index e4e88ee2d..680938b7e 100644 --- a/src/badges/migrations/0022_auto_20211106_1716.py +++ b/src/badges/migrations/0022_auto_20211106_1716.py @@ -7,7 +7,6 @@ class Migration(migrations.Migration): - dependencies = [ ("badges", "0021_auto_20210523_1533"), ] diff --git a/src/badges/migrations/0023_alter_specialbadges_badges.py b/src/badges/migrations/0023_alter_specialbadges_badges.py new file mode 100644 index 000000000..ce04e4751 --- /dev/null +++ b/src/badges/migrations/0023_alter_specialbadges_badges.py @@ -0,0 +1,17 @@ +# Generated by Django 4.1.2 on 2022-10-15 17:01 + +from django.db import migrations, models + + +class Migration(migrations.Migration): + dependencies = [ + ("badges", "0022_auto_20211106_1716"), + ] + + operations = [ + migrations.AlterField( + model_name="specialbadges", + name="badges", + field=models.ManyToManyField(blank=True, related_name="+", to="badges.badge"), + ), + ] diff --git a/src/badges/models/badge.py b/src/badges/models/badge.py index 03863fed0..13451bc8a 100644 --- a/src/badges/models/badge.py +++ b/src/badges/models/badge.py @@ -2,7 +2,7 @@ from django.db.models.signals import post_delete from django.dispatch import receiver from django.template.defaultfilters import date as date_f -from django.utils.translation import ugettext_lazy as _ +from django.utils.translation import gettext_lazy as _ from helfertool.forms import RestrictedImageField @@ -122,7 +122,7 @@ def save(self, *args, **kwargs): if not self.barcode: self.barcode = self.pk + 1000 # prevent barcodes like "10" - self.save() + self.save(update_fields=["barcode"]) if self._old_photo != self.photo and self.photo: # pylint: disable=no-member diff --git a/src/badges/models/defaults.py b/src/badges/models/defaults.py index 3e5655ddf..9e5034271 100644 --- a/src/badges/models/defaults.py +++ b/src/badges/models/defaults.py @@ -1,5 +1,5 @@ from django.db import models -from django.utils.translation import ugettext_lazy as _ +from django.utils.translation import gettext_lazy as _ from copy import deepcopy @@ -28,6 +28,11 @@ class BadgeDefaults(models.Model): verbose_name=_("Do not print default roles on badges"), ) + def __str__(self): + if hasattr(self, "badgesettings"): + return str(self.badgesettings.event) + return "Badge defaults without settings" + def duplicate(self): new_defaults = deepcopy(self) new_defaults.pk = None diff --git a/src/badges/models/design.py b/src/badges/models/design.py index d42eb2397..cdd0af10b 100644 --- a/src/badges/models/design.py +++ b/src/badges/models/design.py @@ -1,7 +1,7 @@ from django.core.files.base import ContentFile from django.core.validators import RegexValidator from django.db import models -from django.utils.translation import ugettext_lazy as _ +from django.utils.translation import gettext_lazy as _ from helfertool.forms import RestrictedImageField @@ -77,7 +77,7 @@ def get_event(self): ) def __str__(self): - return self.name + return "{} - {}".format(self.badge_settings.event, self.name) def duplicate(self, settings): new_design = deepcopy(self) diff --git a/src/badges/models/permission.py b/src/badges/models/permission.py index 070c2b5c9..be6dad39d 100644 --- a/src/badges/models/permission.py +++ b/src/badges/models/permission.py @@ -1,5 +1,5 @@ from django.db import models -from django.utils.translation import ugettext_lazy as _ +from django.utils.translation import gettext_lazy as _ from .settings import BadgeSettings @@ -24,7 +24,7 @@ class BadgePermission(models.Model): ) def __str__(self): - return self.name + return "{} - {}".format(self.badge_settings.event, self.name) def duplicate(self, settings): new_permission = deepcopy(self) diff --git a/src/badges/models/role.py b/src/badges/models/role.py index b3012f220..83a88f6b7 100644 --- a/src/badges/models/role.py +++ b/src/badges/models/role.py @@ -1,5 +1,5 @@ from django.db import models -from django.utils.translation import ugettext_lazy as _ +from django.utils.translation import gettext_lazy as _ from .settings import BadgeSettings from .permission import BadgePermission @@ -31,7 +31,7 @@ class BadgeRole(models.Model): ) def __str__(self): - return self.name + return "{} - {}".format(self.badge_settings.event, self.name) def duplicate(self, settings, permission_map): new_role = deepcopy(self) diff --git a/src/badges/models/settings.py b/src/badges/models/settings.py index 7ddba0c84..f57c5fb81 100644 --- a/src/badges/models/settings.py +++ b/src/badges/models/settings.py @@ -2,7 +2,7 @@ from django.core.files.base import ContentFile from django.core.validators import MinValueValidator from django.db import models -from django.utils.translation import ugettext_lazy as _ +from django.utils.translation import gettext_lazy as _ from .defaults import BadgeDefaults @@ -108,14 +108,24 @@ class BadgeSettings(models.Model): verbose_name=_("Print barcodes on badges to avoid duplicates"), ) - def save(self, *args, **kwargs): + def __str__(self): + return str(self.event) + + def save(self, force_insert=False, force_update=False, using=None, update_fields=None): if not hasattr(self, "defaults"): defaults = BadgeDefaults() defaults.save() self.defaults = defaults - - super(BadgeSettings, self).save(*args, **kwargs) + if update_fields is not None: + update_fields = {"defaults"}.union(update_fields) + + super(BadgeSettings, self).save( + force_insert=force_insert, + force_update=force_update, + using=using, + update_fields=update_fields, + ) def creation_possible(self): if not self.latex_template: diff --git a/src/badges/models/specialbadges.py b/src/badges/models/specialbadges.py index 30900d61e..664caa1cf 100644 --- a/src/badges/models/specialbadges.py +++ b/src/badges/models/specialbadges.py @@ -3,7 +3,7 @@ from django.db import models from django.db.models.signals import post_save, pre_delete from django.dispatch import receiver -from django.utils.translation import ugettext_lazy as _ +from django.utils.translation import gettext_lazy as _ from .badge import Badge diff --git a/src/badges/tasks.py b/src/badges/tasks.py index e322dc449..4b3bbb7ef 100644 --- a/src/badges/tasks.py +++ b/src/badges/tasks.py @@ -5,7 +5,7 @@ from django.conf import settings from django.utils import translation -from django.utils.translation import ugettext as _ +from django.utils.translation import gettext as _ from PIL import Image diff --git a/src/badges/templates/badges/edit_badge.html b/src/badges/templates/badges/edit_badge.html index 7a82e14fa..071c0e1c5 100644 --- a/src/badges/templates/badges/edit_badge.html +++ b/src/badges/templates/badges/edit_badge.html @@ -51,6 +51,10 @@

{% blocktrans with name=form.instance.firstname %}Special badges for {{ name
{{ form.photo.label_tag }} {{ form.photo }} +
{{ form.photo.help_text }}
+ {% for text in form.photo.errors %} +
{{ text }}
+ {% endfor %}
diff --git a/src/badges/templates/badges/edit_design.html b/src/badges/templates/badges/edit_design.html index d737d4816..00226a615 100644 --- a/src/badges/templates/badges/edit_design.html +++ b/src/badges/templates/badges/edit_design.html @@ -35,9 +35,17 @@

{% trans "New badge design" %}

{{ form.bg_front.label_tag }} {{ form.bg_front }} +
{{ form.bg_front.help_text }}
+ {% for text in form.bg_front.errors %} +
{{ text }}
+ {% endfor %}
{{ form.bg_back.label_tag }} {{ form.bg_back }} +
{{ form.bg_back.help_text }}
+ {% for text in form.bg_back.errors %} +
{{ text }}
+ {% endfor %}
diff --git a/src/badges/urls.py b/src/badges/urls.py index 3fa9f4279..33c3fe9a0 100644 --- a/src/badges/urls.py +++ b/src/badges/urls.py @@ -1,4 +1,4 @@ -from django.conf.urls import url +from django.urls import path from . import views @@ -7,65 +7,63 @@ # # settings # - url(r"^(?P[a-zA-Z0-9]+)/badges/settings/$", views.settings, name="settings"), - url( - r"^(?P[a-zA-Z0-9]+)/badges/settings/advanced", views.settings_advanced, name="settings_advanced" - ), - url(r"^(?P[a-zA-Z0-9]+)/badges/defaulttemplate", views.default_template, name="default_template"), - url(r"^(?P[a-zA-Z0-9]+)/badges/currenttemplate", views.current_template, name="current_template"), + path("/badges/settings/", views.settings, name="settings"), + path("/badges/settings/advanced/", views.settings_advanced, name="settings_advanced"), + path("/badges/defaulttemplate/", views.default_template, name="default_template"), + path("/badges/currenttemplate/", views.current_template, name="current_template"), # # edit badge # - url( - r"^(?P[a-zA-Z0-9]+)/helpers/(?P[0-9a-f\-]+)/badge/$", + path( + "/helpers//badge/", views.edit_badge, name="edit_badge", ), - url( - r"^(?P[a-zA-Z0-9]+)/helpers/(?P[0-9a-f\-]+)/badge/photo/$", + path( + "/helpers//badge/photo/", views.get_badge_photo, name="get_badge_photo", ), # # permission # - url( - r"^(?P[a-zA-Z0-9]+)/badges/permission/(?P[0-9]+)/$", + path( + "/badges/permission//", views.edit_permission, name="edit_permission", ), - url(r"^(?P[a-zA-Z0-9]+)/badges/permission/add/", views.edit_permission, name="new_permission"), - url( - r"^(?P[a-zA-Z0-9]+)/badges/permission/(?P[0-9]+)/delete/$", + path("/badges/permission/add/", views.edit_permission, name="new_permission"), + path( + "/badges/permission//delete/", views.delete_permission, name="delete_permission", ), # # role # - url(r"^(?P[a-zA-Z0-9]+)/badges/role/(?P[0-9]+)/$", views.edit_role, name="edit_role"), - url(r"^(?P[a-zA-Z0-9]+)/badges/role/add/", views.edit_role, name="new_role"), - url( - r"^(?P[a-zA-Z0-9]+)/badges/role/(?P[0-9]+)/delete/$", + path("/badges/role//", views.edit_role, name="edit_role"), + path("/badges/role/add/", views.edit_role, name="new_role"), + path( + "/badges/role//delete/", views.delete_role, name="delete_role", ), # # design # - url( - r"^(?P[a-zA-Z0-9]+)/badges/design/(?P[0-9]+)/$", + path( + "/badges/design//", views.edit_design, name="edit_design", ), - url(r"^(?P[a-zA-Z0-9]+)/badges/design/add/", views.edit_design, name="new_design"), - url( - r"^(?P[a-zA-Z0-9]+)/badges/design/(?P[0-9]+)/delete/$", + path("/badges/design/add/", views.edit_design, name="new_design"), + path( + "/badges/design//delete/", views.delete_design, name="delete_design", ), - url( - r"^(?P[a-zA-Z0-9]+)/badges/design/(?P[0-9]+)/bg/(?P[a-z]+)/$", + path( + "/badges/design//bg//", views.get_design_bg, name="get_design_bg", ), @@ -73,79 +71,79 @@ # badge generation # # overview page - url(r"^(?P[a-zA-Z0-9]+)/badges/$", views.index, name="index"), + path("/badges/", views.index, name="index"), # overview of generated badges (list of tasks) - url(r"^(?P[a-zA-Z0-9]+)/badges/tasklist/$", views.tasklist, name="tasklist"), + path("/badges/tasklist/", views.tasklist, name="tasklist"), # warnings - url(r"^(?P[a-zA-Z0-9]+)/badges/warnings/(?P[0-9]+)$", views.warnings, name="warnings"), + path("/badges/warnings//", views.warnings, name="warnings"), # generate for job - url( - r"^(?P[a-zA-Z0-9]+)/badges/generate/(?P[0-9]+)/$", + path( + "/badges/generate//", views.generate, {"generate": "job"}, name="generate_for_job", ), - url( - r"^(?P[a-zA-Z0-9]+)/badges/generate/(?P[0-9]+)/all/$", + path( + "/badges/generate//all/", views.generate, {"generate": "job", "skip_printed": False}, name="generate_all_for_job", ), # generate special badges - url( - r"^(?P[a-zA-Z0-9]+)/badges/generate/special/$", + path( + "/badges/generate/special/", views.generate, {"generate": "special"}, name="generate_special", ), - url( - r"^(?P[a-zA-Z0-9]+)/badges/generate/special/all/$", + path( + "/badges/generate/special/all/", views.generate, {"generate": "special", "skip_printed": False}, name="generate_all_special", ), # generate for all jobs and special badges - url(r"^(?P[a-zA-Z0-9]+)/badges/generate/$", views.generate, {"generate": "all"}, name="generate"), - url( - r"^(?P[a-zA-Z0-9]+)/badges/generate/all/$", + path("/badges/generate/", views.generate, {"generate": "all"}, name="generate"), + path( + "/badges/generate/all/", views.generate, {"generate": "all", "skip_printed": False}, name="generate_all", ), # failed page - url(r"^(?P[a-zA-Z0-9]+)/badges/failed/" r"(?P[a-z0-9\-]+)/$", views.failed, name="failed"), + path("/badges/failed//", views.failed, name="failed"), # download badges - url( - r"^(?P[a-zA-Z0-9]+)/badges/download/" r"(?P[a-z0-9\-]+)/$", + path( + "/badges/download//", views.download, name="download", ), # # register badges # - url(r"^(?P[a-zA-Z0-9]+)/badges/register/", views.register, name="register"), + path("/badges/register/", views.register, name="register"), # # special badges # - url(r"^(?P[a-zA-Z0-9]+)/badges/special/$", views.list_specialbadges, name="list_specialbadges"), - url( - r"^(?P[a-zA-Z0-9]+)/badges/special/(?P[0-9]+)/$", + path("/badges/special/", views.list_specialbadges, name="list_specialbadges"), + path( + "/badges/special//", views.edit_specialbadges, name="edit_specialbadges", ), - url(r"^(?P[a-zA-Z0-9]+)/badges/special/add/$", views.edit_specialbadges, name="new_specialbadges"), - url( - r"^(?P[a-zA-Z0-9]+)/badges/special/(?P[0-9]+)/template/$", + path("/badges/special/add/", views.edit_specialbadges, name="new_specialbadges"), + path( + "/badges/special//template/", views.edit_specialbadges_template, name="edit_specialbadges_template", ), - url( - r"^(?P[a-zA-Z0-9]+)/badges/special/(?P[0-9]+)/delete/$", + path( + "/badges/special//delete/", views.delete_specialbadges, name="delete_specialbadges", ), - url( - r"^(?P[a-zA-Z0-9]+)/badges/special/(?P[0-9]+)/template/photo/$", + path( + "/badges/special//template/photo/", views.get_specialbadges_photo, name="get_specialbadges_photo", ), diff --git a/src/badges/views/badge.py b/src/badges/views/badge.py index ea7dee2cf..de1c5b7f9 100644 --- a/src/badges/views/badge.py +++ b/src/badges/views/badge.py @@ -16,7 +16,7 @@ def edit_badge(request, event_url_name, helper_pk): event, job, shift, helper = get_or_404(event_url_name, helper_pk=helper_pk) # check permission - if not has_access(request.user, event, ACCESS_BADGES_EDIT_HELPER): + if not has_access(request.user, helper, ACCESS_BADGES_EDIT_HELPER): return nopermission(request) # check if badge system is active @@ -44,7 +44,7 @@ def get_badge_photo(request, event_url_name, helper_pk): event, job, shift, helper = get_or_404(event_url_name, helper_pk=helper_pk) # check permission - if not has_access(request.user, event, ACCESS_BADGES_EDIT_HELPER): + if not has_access(request.user, helper, ACCESS_BADGES_EDIT_HELPER): return nopermission(request) # check if badge system is active diff --git a/src/badges/views/generate.py b/src/badges/views/generate.py index f12eea3e3..2fd4fcc8c 100644 --- a/src/badges/views/generate.py +++ b/src/badges/views/generate.py @@ -2,7 +2,7 @@ from django.core.mail import mail_admins from django.http import HttpResponse from django.shortcuts import render, redirect, get_object_or_404 -from django.utils.translation import ugettext as _ +from django.utils.translation import gettext as _ from django.views.decorators.cache import never_cache from helfertool.utils import nopermission diff --git a/src/badges/views/register.py b/src/badges/views/register.py index 5e3c364ae..2690c2e94 100644 --- a/src/badges/views/register.py +++ b/src/badges/views/register.py @@ -1,7 +1,7 @@ from django.contrib import messages from django.contrib.auth.decorators import login_required from django.shortcuts import render, get_object_or_404 -from django.utils.translation import ugettext as _ +from django.utils.translation import gettext as _ from django.views.decorators.cache import never_cache from helfertool.utils import nopermission diff --git a/src/corona/admin.py b/src/corona/admin.py deleted file mode 100644 index a3c98726b..000000000 --- a/src/corona/admin.py +++ /dev/null @@ -1,6 +0,0 @@ -from django.contrib import admin - -from .models import CoronaSettings, ContactTracingData - -admin.site.register(CoronaSettings) -admin.site.register(ContactTracingData) diff --git a/src/corona/export.py b/src/corona/export.py deleted file mode 100644 index 31846bfc4..000000000 --- a/src/corona/export.py +++ /dev/null @@ -1,65 +0,0 @@ -from django.utils.translation import ugettext as _ - -import xlsxwriter -from io import BytesIO - -from registration.export.excel import Iterator, escape - -from .models import ContactTracingData - - -def excel_export(event): - # create excel file in memory - buffer = BytesIO() - workbook = xlsxwriter.Workbook(buffer) - worksheet = workbook.add_worksheet(_("Contact tracing data")) - bold = workbook.add_format({"bold": True}) - - row = Iterator() - column = Iterator() - row.next() # we need to start at 1 - - # header - worksheet.write(row.get(), column.next(), _("First name"), bold) - worksheet.write(row.get(), column.next(), _("Surname"), bold) - worksheet.write(row.get(), column.next(), _("E-Mail"), bold) - worksheet.write(row.get(), column.next(), _("Mobile phone"), bold) - worksheet.write(row.get(), column.next(), _("Street and house number"), bold) - worksheet.write(row.get(), column.next(), _("ZIP"), bold) - worksheet.write(row.get(), column.next(), _("City"), bold) - worksheet.write(row.get(), column.next(), _("Country"), bold) - worksheet.write(row.get(), column.next(), _("Shifts and jobs"), bold) - worksheet.freeze_panes(1, 0) - row.next() - - for helper in event.helper_set.all(): - column.reset() - - worksheet.write(row.get(), column.next(), escape(helper.firstname)) - worksheet.write(row.get(), column.next(), escape(helper.surname)) - worksheet.write(row.get(), column.next(), escape(helper.email)) - worksheet.write(row.get(), column.next(), escape(helper.phone)) - - try: - data = helper.contacttracingdata - worksheet.write(row.get(), column.next(), escape(data.street)) - worksheet.write(row.get(), column.next(), escape(data.zip)) - worksheet.write(row.get(), column.next(), escape(data.city)) - worksheet.write(row.get(), column.next(), escape(data.country.name)) - except ContactTracingData.DoesNotExist: - column.add(4) - - shifts_and_jobs = [] - for job in helper.coordinated_jobs: - shifts_and_jobs.append("{}: {}".format(_("Coordinator"), job.name)) - for shift in helper.shifts.all(): - shifts_and_jobs.append(str(shift)) - worksheet.write(row.get(), column.next(), escape("\n".join(shifts_and_jobs))) - - row.next() - - # return data - workbook.close() - data = buffer.getvalue() - buffer.close() - return data diff --git a/src/corona/forms/__init__.py b/src/corona/forms/__init__.py deleted file mode 100644 index 524868d4d..000000000 --- a/src/corona/forms/__init__.py +++ /dev/null @@ -1,3 +0,0 @@ -from .cleanup import CoronaCleanupForm -from .data import ContactTracingDataForm -from .settings import CoronaSettingsForm diff --git a/src/corona/forms/cleanup.py b/src/corona/forms/cleanup.py deleted file mode 100644 index b48dc1be2..000000000 --- a/src/corona/forms/cleanup.py +++ /dev/null @@ -1,8 +0,0 @@ -from django import forms - -from ..models import ContactTracingData - - -class CoronaCleanupForm(forms.Form): - def cleanup(self, event): - ContactTracingData.objects.filter(event=event).delete() diff --git a/src/corona/forms/data.py b/src/corona/forms/data.py deleted file mode 100644 index 8c3b0985d..000000000 --- a/src/corona/forms/data.py +++ /dev/null @@ -1,37 +0,0 @@ -from django import forms -from django.conf import settings -from django.utils.translation import ugettext as _ - -from ..models import ContactTracingData - - -class ContactTracingDataForm(forms.ModelForm): - class Meta: - model = ContactTracingData - exclude = [ - "event", - "helper", - ] - - def __init__(self, *args, **kwargs): - self.event = kwargs.pop("event") - - super(ContactTracingDataForm, self).__init__(*args, **kwargs) - - self.fields["country"].initial = settings.DEFAULT_COUNTRY - - def clean(self): - super(ContactTracingDataForm, self).clean() - - if not self.cleaned_data.get("agreed"): - self.add_error("agreed", _("You have to provide correct data.")) - - def save(self, helper, commit=True): - instance = super(ContactTracingDataForm, self).save(False) - instance.event = self.event - instance.helper = helper - - if commit: - instance.save() - - return instance diff --git a/src/corona/forms/settings.py b/src/corona/forms/settings.py deleted file mode 100644 index 894231063..000000000 --- a/src/corona/forms/settings.py +++ /dev/null @@ -1,18 +0,0 @@ -from django import forms - -from ..models import CoronaSettings - - -class CoronaSettingsForm(forms.ModelForm): - class Meta: - model = CoronaSettings - exclude = [ - "event", - ] - - def __init__(self, *args, **kwargs): - super(CoronaSettingsForm, self).__init__(*args, **kwargs) - - if self.instance.event.archived: - for field_id in self.fields: - self.fields[field_id].disabled = True diff --git a/src/corona/locale/de/LC_MESSAGES/django.mo b/src/corona/locale/de/LC_MESSAGES/django.mo deleted file mode 100644 index 7850b2304..000000000 Binary files a/src/corona/locale/de/LC_MESSAGES/django.mo and /dev/null differ diff --git a/src/corona/locale/de/LC_MESSAGES/django.po b/src/corona/locale/de/LC_MESSAGES/django.po deleted file mode 100644 index 154ca40f3..000000000 --- a/src/corona/locale/de/LC_MESSAGES/django.po +++ /dev/null @@ -1,302 +0,0 @@ -# SOME DESCRIPTIVE TITLE. -# Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER -# This file is distributed under the same license as the PACKAGE package. -# FIRST AUTHOR , YEAR. -# -msgid "" -msgstr "" -"Project-Id-Version: \n" -"Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2022-07-25 19:30+0200\n" -"PO-Revision-Date: 2021-11-13 21:14+0100\n" -"Last-Translator: \n" -"Language-Team: \n" -"Language: de\n" -"MIME-Version: 1.0\n" -"Content-Type: text/plain; charset=UTF-8\n" -"Content-Transfer-Encoding: 8bit\n" -"Plural-Forms: nplurals=2; plural=(n != 1);\n" -"X-Generator: Poedit 2.4.2\n" - -#: corona/export.py:15 -msgid "Contact tracing data" -msgstr "Daten zur Kontaktverfolgung" - -#: corona/export.py:23 -msgid "First name" -msgstr "Vorname" - -#: corona/export.py:24 -msgid "Surname" -msgstr "Nachname" - -#: corona/export.py:25 corona/templates/corona/view_helper.html:17 -msgid "E-Mail" -msgstr "E-Mail" - -#: corona/export.py:26 corona/templates/corona/view_helper.html:23 -msgid "Mobile phone" -msgstr "Handynummer" - -#: corona/export.py:27 corona/models/data.py:22 -msgid "Street and house number" -msgstr "Straße und Hausnummer" - -#: corona/export.py:28 -msgid "ZIP" -msgstr "PLZ" - -#: corona/export.py:29 corona/models/data.py:32 -msgid "City" -msgstr "Stadt" - -#: corona/export.py:30 corona/models/data.py:36 -msgid "Country" -msgstr "Land" - -#: corona/export.py:31 -msgid "Shifts and jobs" -msgstr "Schichten und Aufgaben" - -#: corona/export.py:54 -msgid "Coordinator" -msgstr "Koordinator:in" - -#: corona/forms/data.py:27 -msgid "You have to provide correct data." -msgstr "Du musst korrekte Daten angeben." - -#: corona/models/data.py:27 -msgid "ZIP code" -msgstr "PLZ" - -#: corona/models/data.py:41 -msgid "I assure that the provided data is correct." -msgstr "Ich versichere, dass die angegebenen Daten korrekt sind." - -#: corona/models/settings.py:14 -msgid "2G" -msgstr "2G" - -#: corona/models/settings.py:15 -msgid "2G plus" -msgstr "2G plus" - -#: corona/models/settings.py:16 -msgid "3G" -msgstr "3G" - -#: corona/models/settings.py:17 -msgid "3G plus" -msgstr "3G plus" - -#: corona/models/settings.py:29 -msgid "Admission rules" -msgstr "Einlassregeln" - -#: corona/templates/corona/cleanup.html:5 -msgid "Delete contact tracing data" -msgstr "Daten zur Kontaktverfolgung löschen" - -#: corona/templates/corona/cleanup.html:8 -msgid "Do you want to remove the contact tracing data for this event?" -msgstr "" -"Willst du die Daten zur Kontaktverfolgung für diese Veranstaltung löschen?" - -#: corona/templates/corona/cleanup.html:14 -msgid "Delete" -msgstr "Löschen" - -#: corona/templates/corona/data.html:5 -msgid "COVID-19 contact tracing" -msgstr "COVID-19 Kontaktverfolgung" - -#: corona/templates/corona/data.html:10 -#, python-format -msgid "Contact tracing data missing for %(num_missing)s helpers!" -msgstr "Daten zur Kontaktverfolgung fehlen für %(num_missing)s Helfer:innen!" - -#: corona/templates/corona/data.html:18 -msgid "Show" -msgstr "Anzeigen" - -#: corona/templates/corona/data.html:24 -msgid "Contact tracing data is available for all helpers." -msgstr "Daten zur Kontaktverfolgung sind für alle Helfer:innen verfügbar." - -#: corona/templates/corona/data.html:31 -msgid "" -"You can export names, contact information and addresses of all helpers here. " -"The export does not contain special badges." -msgstr "" -"Du kannst Namen, Kontaktdaten und Adressen aller Helfer:innen hier " -"exportieren. Der Export enthält keine Spezial Badges." - -#: corona/templates/corona/data.html:33 -msgid "Please use this data responsibly." -msgstr "Bitte gehe verantwortungsvoll mit den Daten um." - -#: corona/templates/corona/data.html:37 -msgid "Export" -msgstr "Exportieren" - -#: corona/templates/corona/edit_helper.html:5 -#: corona/templates/corona/view_helper.html:5 -#, python-format -msgid "Contact tracing for %(name)s" -msgstr "Kontaktverfolgung für %(name)s" - -#: corona/templates/corona/edit_helper.html:14 -#: corona/templates/corona/settings.html:20 -msgid "Save" -msgstr "Speichern" - -#: corona/templates/corona/missing.html:5 -msgid "Missing contact tracing data" -msgstr "Fehlende Daten zur Kontaktverfolgung" - -#: corona/templates/corona/missing.html:14 -msgid "No data missing." -msgstr "Keine fehlenden Daten." - -#: corona/templates/corona/not_active.html:5 -msgid "COVID-19" -msgstr "COVID-19" - -#: corona/templates/corona/not_active.html:8 -msgid "The COVID-19 contact tracing is not actived." -msgstr "Die COVID-19 Kontaktverfolgung ist nicht aktiv." - -#: corona/templates/corona/registration.html:4 -msgid "COVID-19 measures" -msgstr "COVID-19 Maßnahmen" - -#: corona/templates/corona/registration.html:8 -msgid "" -"At this event the 2G regulation is applied. This means that " -"you must be either vaccinated or recovered to have access. The proof will be " -"checked at the entrance and access without it is not possible." -msgstr "" -"Bei dieser Veranstaltung gilt die 2G Regelung. Das " -"bedeutet, dass du entweder geimpft oder genesen sein musst, um Zutritt zu " -"erhalten. Der Nachweis wird am Eingang kontrolliert und der Zutritt ist ohne " -"diesen nicht möglich." - -#: corona/templates/corona/registration.html:15 -msgid "A negative test is not sufficient!" -msgstr "Ein negativer Test ist nicht ausreichend!" - -#: corona/templates/corona/registration.html:18 -msgid "" -"At this event the 2G plus regulation is applied. This means " -"that you must be either vaccinated or recovered and provide " -"a negative antigen rapid test to have access. The proof will be checked at " -"the entrance and access without it is not possible." -msgstr "" -"Bei dieser Veranstaltung gilt die 2G plus Regelung. Das " -"bedeutet, dass du entweder geimpft oder genesen sein musst und einen negativen Schnelltest vorlegen musst, um Zutritt zu erhalten. " -"Der Nachweis wird am Eingang kontrolliert und der Zutritt ist ohne diesen " -"nicht möglich." - -#: corona/templates/corona/registration.html:26 -msgid "" -"At this event the 3G regulation is applied. This means that " -"you must be either vaccinated, recovered or provide a negative official test " -"to have access. The proof will be checked at the entrance and access without " -"it is not possible." -msgstr "" -"Bei dieser Veranstaltung gilt die 3G Regelung. Das " -"bedeutet, dass du entweder geimpft oder genesen sein oder einen negativen " -"offiziellen Test vorlegen musst, um Zutritt zu erhalten. Der Nachweis wird " -"am Eingang kontrolliert und der Zutritt ist ohne diesen nicht möglich." - -#: corona/templates/corona/registration.html:34 -msgid "" -"At this event the 3G plus regulation is applied. This means " -"that you must be either vaccinated, recovered or provide a negative PCR test " -"to have access. The proof will be checked at the entrance and access without " -"it is not possible." -msgstr "" -"Bei dieser Veranstaltung gilt die 3G plus Regelung. Das " -"bedeutet, dass du entweder geimpft oder genesen sein oder einen negativen " -"PCR Test vorlegen musst, um Zutritt zu erhalten. Der Nachweis wird am " -"Eingang kontrolliert und der Zutritt ist ohne diesen nicht möglich." - -#: corona/templates/corona/registration.html:41 -msgid "A negative antigen rapid test is not sufficient!" -msgstr "Ein negativer Antigen Schnelltest ist nicht ausreichend!" - -#: corona/templates/corona/registration.html:44 -msgid "" -"We are required to collect address and contact information for contact " -"tracking purposes." -msgstr "" -"Wir sind verpflichtet, Adresse und Kontaktinformationen zum Zwecke der " -"Kontaktverfolgung zu erfassen." - -#: corona/templates/corona/settings.html:5 -msgid "COVID-19 settings" -msgstr "COVID-19 Einstellungen" - -#: corona/templates/corona/settings.html:7 -msgid "Settings" -msgstr "Einstellungen" - -#: corona/templates/corona/settings.html:25 -#: corona/templates/corona/settings.html:32 -msgid "Delete data" -msgstr "Daten löschen" - -#: corona/templates/corona/settings.html:27 -msgid "" -"You can delete the addresses of the helpers as soon as you do not need it " -"anymore." -msgstr "" -"Du kannst die Adressen der Helfer:innen löschen, sobald sie nicht mehr " -"benötigt werden." - -#: corona/templates/corona/settings.html:29 -msgid "All other data is not deleted." -msgstr "Alle anderen Daten werden nicht gelöscht." - -#: corona/templates/corona/view_helper.html:10 -msgid "Personal data of helper" -msgstr "Persönliche Daten der Helfer:in" - -#: corona/templates/corona/view_helper.html:12 -msgid "Name" -msgstr "Name" - -#: corona/templates/corona/view_helper.html:30 -msgid "Address" -msgstr "Adresse" - -#: corona/templates/corona/view_helper.html:32 -msgid "Edit" -msgstr "Bearbeiten" - -#: corona/templates/corona/view_helper.html:47 -msgid "Add data" -msgstr "Daten hinzufügen" - -#: corona/templates/corona/view_helper.html:52 -msgid "COVID-19 contact tracing was not enabled while the helper registered." -msgstr "" -"Die COVID-19 Kontaktverfolgung war nicht aktiv als sich die Helfer:in " -"angemeldet hat." - -#: corona/templates/corona/view_helper.html:58 -msgid "Back" -msgstr "Zurück" - -#: corona/views/cleanup.py:47 -msgid "Contact tracing data deleted" -msgstr "Daten zur Kontaktverfolgung wurden gelöscht" - -#: corona/views/data.py:85 -msgid "Corona contact tracing" -msgstr "Corona Kontaktverfolgung" - -#~ msgid "Missing COVID-19 contact tracing" -#~ msgstr "Fehlende Daten zur Kontaktverfolgung" diff --git a/src/corona/migrations/0002_coronasettings_rules.py b/src/corona/migrations/0002_coronasettings_rules.py deleted file mode 100644 index 07f43b701..000000000 --- a/src/corona/migrations/0002_coronasettings_rules.py +++ /dev/null @@ -1,20 +0,0 @@ -# Generated by Django 3.2.7 on 2021-09-26 12:43 - -from django.db import migrations, models - - -class Migration(migrations.Migration): - - dependencies = [ - ("corona", "0001_initial"), - ] - - operations = [ - migrations.AddField( - model_name="coronasettings", - name="rules", - field=models.CharField( - choices=[("2G", "2G"), ("3G", "3G")], default="2G", max_length=20, verbose_name="Admission rules" - ), - ), - ] diff --git a/src/corona/migrations/0003_contacttracingdata.py b/src/corona/migrations/0003_contacttracingdata.py deleted file mode 100644 index 197036d35..000000000 --- a/src/corona/migrations/0003_contacttracingdata.py +++ /dev/null @@ -1,33 +0,0 @@ -# Generated by Django 3.2.7 on 2021-09-27 18:28 - -from django.db import migrations, models -import django.db.models.deletion -import django_countries.fields - - -class Migration(migrations.Migration): - - dependencies = [ - ("registration", "0055_event_corona"), - ("corona", "0002_coronasettings_rules"), - ] - - operations = [ - migrations.CreateModel( - name="ContactTracingData", - fields=[ - ("id", models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name="ID")), - ("street", models.CharField(max_length=250, verbose_name="Street and house number")), - ("zip", models.CharField(max_length=250, verbose_name="ZIP code")), - ("city", models.CharField(max_length=250, verbose_name="City")), - ("country", django_countries.fields.CountryField(max_length=2, verbose_name="Country")), - ("event", models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to="registration.event")), - ( - "helper", - models.OneToOneField( - blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to="registration.helper" - ), - ), - ], - ), - ] diff --git a/src/corona/migrations/0004_contacttracingdata_agreed.py b/src/corona/migrations/0004_contacttracingdata_agreed.py deleted file mode 100644 index cc90172c2..000000000 --- a/src/corona/migrations/0004_contacttracingdata_agreed.py +++ /dev/null @@ -1,18 +0,0 @@ -# Generated by Django 3.2.7 on 2021-09-27 18:34 - -from django.db import migrations, models - - -class Migration(migrations.Migration): - - dependencies = [ - ("corona", "0003_contacttracingdata"), - ] - - operations = [ - migrations.AddField( - model_name="contacttracingdata", - name="agreed", - field=models.BooleanField(default=False, verbose_name="I assure that the provided data is correct."), - ), - ] diff --git a/src/corona/migrations/0005_alter_coronasettings_rules.py b/src/corona/migrations/0005_alter_coronasettings_rules.py deleted file mode 100644 index c3fdffc09..000000000 --- a/src/corona/migrations/0005_alter_coronasettings_rules.py +++ /dev/null @@ -1,23 +0,0 @@ -# Generated by Django 3.2.7 on 2021-10-10 15:30 - -from django.db import migrations, models - - -class Migration(migrations.Migration): - - dependencies = [ - ("corona", "0004_contacttracingdata_agreed"), - ] - - operations = [ - migrations.AlterField( - model_name="coronasettings", - name="rules", - field=models.CharField( - choices=[("2G", "2G"), ("3G", "3G"), ("3Gplus", "3G plus")], - default="2G", - max_length=20, - verbose_name="Admission rules", - ), - ), - ] diff --git a/src/corona/migrations/0006_alter_coronasettings_rules.py b/src/corona/migrations/0006_alter_coronasettings_rules.py deleted file mode 100644 index faa33c31c..000000000 --- a/src/corona/migrations/0006_alter_coronasettings_rules.py +++ /dev/null @@ -1,23 +0,0 @@ -# Generated by Django 3.2.9 on 2021-11-13 20:16 - -from django.db import migrations, models - - -class Migration(migrations.Migration): - - dependencies = [ - ("corona", "0005_alter_coronasettings_rules"), - ] - - operations = [ - migrations.AlterField( - model_name="coronasettings", - name="rules", - field=models.CharField( - choices=[("2G", "2G"), ("2Gplus", "2G plus"), ("3G", "3G"), ("3Gplus", "3G plus")], - default="2G", - max_length=20, - verbose_name="Admission rules", - ), - ), - ] diff --git a/src/corona/models/__init__.py b/src/corona/models/__init__.py deleted file mode 100644 index 3595b6c23..000000000 --- a/src/corona/models/__init__.py +++ /dev/null @@ -1,2 +0,0 @@ -from .data import ContactTracingData -from .settings import CoronaSettings diff --git a/src/corona/models/data.py b/src/corona/models/data.py deleted file mode 100644 index 21d1191e9..000000000 --- a/src/corona/models/data.py +++ /dev/null @@ -1,45 +0,0 @@ -from django.db import models -from django.utils.translation import ugettext_lazy as _ - -from django_countries.fields import CountryField - - -class ContactTracingData(models.Model): - event = models.ForeignKey( - "registration.Event", - on_delete=models.CASCADE, - ) - - helper = models.OneToOneField( - "registration.Helper", - on_delete=models.CASCADE, - null=True, - blank=True, - ) - - street = models.CharField( - max_length=250, - verbose_name=_("Street and house number"), - ) - - zip = models.CharField( - max_length=250, - verbose_name=_("ZIP code"), - ) - - city = models.CharField( - max_length=250, - verbose_name=_("City"), - ) - - country = CountryField( - verbose_name=_("Country"), - ) - - agreed = models.BooleanField( - default=False, - verbose_name=_("I assure that the provided data is correct."), - ) - - def __str__(self): - return "{} - {}".format(self.event, self.helper.full_name) diff --git a/src/corona/models/settings.py b/src/corona/models/settings.py deleted file mode 100644 index a3fab4bb0..000000000 --- a/src/corona/models/settings.py +++ /dev/null @@ -1,41 +0,0 @@ -from django.db import models -from django.utils.translation import ugettext_lazy as _ - -from copy import deepcopy - - -class CoronaSettings(models.Model): - RULES_2G = "2G" - RULES_2Gplus = "2Gplus" - RULES_3G = "3G" - RULES_3Gplus = "3Gplus" - - RULES_CHOICES = ( - (RULES_2G, _("2G")), - (RULES_2Gplus, _("2G plus")), - (RULES_3G, _("3G")), - (RULES_3Gplus, _("3G plus")), - ) - - event = models.OneToOneField( - "registration.Event", - on_delete=models.CASCADE, - ) - - rules = models.CharField( - choices=RULES_CHOICES, - default=RULES_2G, - max_length=20, - verbose_name=_("Admission rules"), - ) - - def duplicate(self, event): - new_settings = deepcopy(self) - new_settings.pk = None - new_settings.event = event - new_settings.save() - - return new_settings - - def __str__(self): - return self.event.name diff --git a/src/corona/templates/corona/cleanup.html b/src/corona/templates/corona/cleanup.html deleted file mode 100644 index 6f2ac3736..000000000 --- a/src/corona/templates/corona/cleanup.html +++ /dev/null @@ -1,16 +0,0 @@ -{% extends "helfertool/admin.html" %} -{% load i18n django_bootstrap5 icons %} - -{% block content %} -

{% trans "Delete contact tracing data" %}

- - - -
- {% csrf_token %} - {% bootstrap_form form %} - -
-{% endblock %} diff --git a/src/corona/templates/corona/data.html b/src/corona/templates/corona/data.html deleted file mode 100644 index b66610a52..000000000 --- a/src/corona/templates/corona/data.html +++ /dev/null @@ -1,40 +0,0 @@ -{% extends "helfertool/admin.html" %} -{% load i18n django_bootstrap5 icons %} - -{% block content %} -

{% trans "COVID-19 contact tracing" %}

- - {% if num_missing %} - - {% else %} - - {% endif %} - - -{% endblock %} diff --git a/src/corona/templates/corona/edit_helper.html b/src/corona/templates/corona/edit_helper.html deleted file mode 100644 index 6e873b396..000000000 --- a/src/corona/templates/corona/edit_helper.html +++ /dev/null @@ -1,16 +0,0 @@ -{% extends "helfertool/admin.html" %} -{% load i18n django_bootstrap5 icons %} - -{% block content %} -

{% blocktrans with name=helper.full_name %}Contact tracing for {{ name }}{% endblocktrans %}

- -
- {% csrf_token %} - - {% bootstrap_form_errors form %} - - {% include "corona/partials/dataform.html" with form=form %} - - -
-{% endblock %} diff --git a/src/corona/templates/corona/missing.html b/src/corona/templates/corona/missing.html deleted file mode 100644 index 19ba23a5c..000000000 --- a/src/corona/templates/corona/missing.html +++ /dev/null @@ -1,16 +0,0 @@ -{% extends "helfertool/admin.html" %} -{% load i18n django_bootstrap5 icons %} - -{% block content %} -

{% trans "Missing contact tracing data" %}

- - {% if helpers %} - - {% else %} -

{% trans "No data missing." %}

- {% endif %} -{% endblock %} diff --git a/src/corona/templates/corona/not_active.html b/src/corona/templates/corona/not_active.html deleted file mode 100644 index 769b9ae51..000000000 --- a/src/corona/templates/corona/not_active.html +++ /dev/null @@ -1,10 +0,0 @@ -{% extends "helfertool/admin.html" %} -{% load i18n django_bootstrap5 %} - -{% block content %} -

{% trans "COVID-19" %}

- - -{% endblock %} diff --git a/src/corona/templates/corona/partials/dataform.html b/src/corona/templates/corona/partials/dataform.html deleted file mode 100644 index 9a7c91def..000000000 --- a/src/corona/templates/corona/partials/dataform.html +++ /dev/null @@ -1,16 +0,0 @@ -{% load django_bootstrap5 %} - -{% bootstrap_field form.street layout="floating" %} -
-
- {% bootstrap_field form.zip layout="floating" %} -
- -
- {% bootstrap_field form.city layout="floating" %} -
-
- -{% bootstrap_field form.country layout="floating" %} - -{% bootstrap_field form.agreed layout="floating" wrapper_class="" %} diff --git a/src/corona/templates/corona/registration.html b/src/corona/templates/corona/registration.html deleted file mode 100644 index 222fef40d..000000000 --- a/src/corona/templates/corona/registration.html +++ /dev/null @@ -1,47 +0,0 @@ -{% load i18n django_bootstrap5 icons %} - -
-

{% trans "COVID-19 measures" %} {% icon "head-side-mask" %}

- - {% if event.corona_settings.rules == "2G" %} -

- {% blocktrans trimmed %} - At this event the 2G regulation is applied. - This means that you must be either vaccinated or recovered to have access. - The proof will be checked at the entrance and access without it is not possible. - {% endblocktrans %} -

- -

{% trans "A negative test is not sufficient!" %}

- {% elif event.corona_settings.rules == "2Gplus" %} -

- {% blocktrans trimmed %} - At this event the 2G plus regulation is applied. - This means that you must be either vaccinated or recovered and provide a negative antigen rapid test to have access. - The proof will be checked at the entrance and access without it is not possible. - {% endblocktrans %} -

- {% elif event.corona_settings.rules == "3G" %} -

- {% blocktrans trimmed %} - At this event the 3G regulation is applied. - This means that you must be either vaccinated, recovered or provide a negative official test to have access. - The proof will be checked at the entrance and access without it is not possible. - {% endblocktrans %} -

- {% elif event.corona_settings.rules == "3Gplus" %} -

- {% blocktrans trimmed %} - At this event the 3G plus regulation is applied. - This means that you must be either vaccinated, recovered or provide a negative PCR test to have access. - The proof will be checked at the entrance and access without it is not possible. - {% endblocktrans %} -

- -

{% trans "A negative antigen rapid test is not sufficient!" %}

- {% endif %} - -

{% trans "We are required to collect address and contact information for contact tracking purposes." %}

- - {% include "corona/partials/dataform.html" with form=form %} -
diff --git a/src/corona/templates/corona/settings.html b/src/corona/templates/corona/settings.html deleted file mode 100644 index 97b1e28b0..000000000 --- a/src/corona/templates/corona/settings.html +++ /dev/null @@ -1,36 +0,0 @@ -{% extends "helfertool/admin.html" %} -{% load i18n django_bootstrap5 icons %} - -{% block content %} -

{% trans "COVID-19 settings" %}

- -

{% trans "Settings" %}

-
- {% csrf_token %} - -
-
- {% bootstrap_field form.rules layout="floating" %} -
-
- - {% bootstrap_form_errors form %} - - {% if not event.archived %} - - {% endif %} -
- - {% if not event.archived %} -

{% trans "Delete data" %}

- - {% endif %} -{% endblock %} diff --git a/src/corona/templates/corona/view_helper.html b/src/corona/templates/corona/view_helper.html deleted file mode 100644 index bdf27e512..000000000 --- a/src/corona/templates/corona/view_helper.html +++ /dev/null @@ -1,60 +0,0 @@ -{% extends "helfertool/admin.html" %} -{% load i18n django_bootstrap5 icons %} - -{% block content %} -

{% blocktrans with name=helper.full_name %}Contact tracing for {{ name }}{% endblocktrans %}

- - {% if data %} -
-
- - - - - - - - - - - - {% if helper.event.ask_phone %} - - - - - {% endif %} - - - - - -
{% trans "Name" %}: {{ helper.firstname }} {{ helper.surname }}
{% trans "E-Mail" %}: {{ helper.email }}
{% trans "Mobile phone" %}: {{ helper.phone }}
- {% trans "Address" %}:
- - {% icon "pencil-alt" %} {% trans "Edit" %} - -
- {{ data.street }}
- {{ data.zip }} {{ data.city }}
- {{ data.country.name }} -
-
-
- {% else %} -

- - {% icon "plus" %} {% trans "Add data" %} - -

- - - {% endif %} - - - {% icon "arrow-left" %} - {% trans "Back" %} - -{% endblock %} diff --git a/src/corona/urls.py b/src/corona/urls.py deleted file mode 100644 index b384625d0..000000000 --- a/src/corona/urls.py +++ /dev/null @@ -1,22 +0,0 @@ -from django.conf.urls import url - -from . import views - -app_name = "corona" -urlpatterns = [ - url(r"^(?P[a-zA-Z0-9]+)/corona/settings/$", views.settings, name="settings"), - url(r"^(?P[a-zA-Z0-9]+)/corona/cleanup/$", views.cleanup, name="cleanup"), - url(r"^(?P[a-zA-Z0-9]+)/corona/data/$", views.data, name="data"), - url(r"^(?P[a-zA-Z0-9]+)/corona/export/$", views.export, name="export"), - url(r"^(?P[a-zA-Z0-9]+)/corona/missing/$", views.missing, name="missing"), - url( - r"^(?P[a-zA-Z0-9]+)/helpers/(?P[0-9a-f\-]+)/corona/$", - views.view_helper, - name="view_helper", - ), - url( - r"^(?P[a-zA-Z0-9]+)/helpers/(?P[0-9a-f\-]+)/corona/edit/$", - views.edit_helper, - name="edit_helper", - ), -] diff --git a/src/corona/views/__init__.py b/src/corona/views/__init__.py deleted file mode 100644 index fca592a81..000000000 --- a/src/corona/views/__init__.py +++ /dev/null @@ -1,4 +0,0 @@ -from .cleanup import cleanup -from .data import data, missing, export -from .helper import view_helper, edit_helper -from .settings import settings diff --git a/src/corona/views/cleanup.py b/src/corona/views/cleanup.py deleted file mode 100644 index 5fe594096..000000000 --- a/src/corona/views/cleanup.py +++ /dev/null @@ -1,52 +0,0 @@ -from django.contrib import messages -from django.contrib.auth.decorators import login_required -from django.shortcuts import render, redirect, get_object_or_404 -from django.utils.translation import ugettext as _ -from django.views.decorators.cache import never_cache - -from helfertool.utils import nopermission -from registration.decorators import archived_not_available -from registration.models import Event -from registration.permissions import has_access, ACCESS_CORONA_EDIT - -from ..forms import CoronaCleanupForm -from .utils import notactive - -import logging - -logger = logging.getLogger("helfertool.corona") - - -@login_required -@never_cache -@archived_not_available -def cleanup(request, event_url_name): - event = get_object_or_404(Event, url_name=event_url_name) - - # check permission - if not has_access(request.user, event, ACCESS_CORONA_EDIT): - return nopermission(request) - - # check if corona contact tracing is active - if not event.corona: - return notactive(request) - - # form - form = CoronaCleanupForm(request.POST or None) - if form.is_valid(): - form.cleanup(event) - - logger.info( - "corona cleanup", - extra={ - "user": request.user, - "event": event, - }, - ) - - messages.success(request, _("Contact tracing data deleted")) - - return redirect("corona:settings", event_url_name=event.url_name) - - context = {"event": event, "form": form} - return render(request, "corona/cleanup.html", context) diff --git a/src/corona/views/data.py b/src/corona/views/data.py deleted file mode 100644 index a6b5002c7..000000000 --- a/src/corona/views/data.py +++ /dev/null @@ -1,93 +0,0 @@ -from django.contrib.auth.decorators import login_required -from django.http import HttpResponse -from django.shortcuts import render, get_object_or_404 -from django.utils.translation import ugettext as _ -from django.views.decorators.cache import never_cache - -from helfertool.utils import nopermission -from registration.decorators import archived_not_available -from registration.models import Event -from registration.permissions import has_access, ACCESS_CORONA_VIEW - -from ..export import excel_export -from .utils import notactive - -import logging - -logger = logging.getLogger("helfertool.corona") - - -@login_required -@never_cache -@archived_not_available -def data(request, event_url_name): - event = get_object_or_404(Event, url_name=event_url_name) - - # check permissions - if not has_access(request.user, event, ACCESS_CORONA_VIEW): - return nopermission(request) - - # check if corona contact tracing is active - if not event.corona: - return notactive(request) - - num_missing = event.helper_set.filter(contacttracingdata__isnull=True).count() - - # render page - context = {"event": event, "num_missing": num_missing} - return render(request, "corona/data.html", context) - - -@login_required -@never_cache -@archived_not_available -def missing(request, event_url_name): - event = get_object_or_404(Event, url_name=event_url_name) - - # check permissions - if not has_access(request.user, event, ACCESS_CORONA_VIEW): - return nopermission(request) - - # check if corona contact tracing is active - if not event.corona: - return notactive(request) - - helpers = event.helper_set.filter(contacttracingdata__isnull=True) - - # render page - context = {"event": event, "helpers": helpers} - return render(request, "corona/missing.html", context) - - -@login_required -@never_cache -@archived_not_available -def export(request, event_url_name): - event = get_object_or_404(Event, url_name=event_url_name) - - # check permissions - if not has_access(request.user, event, ACCESS_CORONA_VIEW): - return nopermission(request) - - # check if corona contact tracing is active - if not event.corona: - return notactive(request) - - logger.info( - "corona export", - extra={ - "user": request.user, - "event": event, - }, - ) - - # start http response - filename = "{} - {}.xlsx".format(event.name, _("Corona contact tracing")) - response = HttpResponse(content_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet") - response["Content-Disposition"] = 'attachment; filename="%s"' % filename - - # close buffer, send file - data = excel_export(event) - response.write(data) - - return response diff --git a/src/corona/views/helper.py b/src/corona/views/helper.py deleted file mode 100644 index 0e814b6d2..000000000 --- a/src/corona/views/helper.py +++ /dev/null @@ -1,79 +0,0 @@ -from django.contrib.auth.decorators import login_required -from django.shortcuts import render, redirect -from django.views.decorators.cache import never_cache - -from helfertool.utils import nopermission -from registration.permissions import has_access, ACCESS_CORONA_VIEW, ACCESS_CORONA_EDIT -from registration.utils import get_or_404 - -from ..forms import ContactTracingDataForm -from ..models import ContactTracingData -from .utils import notactive - -import logging - -logger = logging.getLogger("helfertool.corona") - - -@login_required -@never_cache -def view_helper(request, event_url_name, helper_pk): - event, job, shift, helper = get_or_404(event_url_name, helper_pk=helper_pk) - - # check permissions - if not has_access(request.user, helper, ACCESS_CORONA_VIEW): - return nopermission(request) - - # check if corona contact tracing is active - if not event.corona: - return notactive(request) - - # get data if it exists - try: - data = helper.contacttracingdata - except ContactTracingData.DoesNotExist: - data = None - - # render page - context = {"event": event, "helper": helper, "data": data} - return render(request, "corona/view_helper.html", context) - - -@login_required -@never_cache -def edit_helper(request, event_url_name, helper_pk): - event, job, shift, helper = get_or_404(event_url_name, helper_pk=helper_pk) - - # check permissions - if not has_access(request.user, helper, ACCESS_CORONA_EDIT): - return nopermission(request) - - # check if corona contact tracing is active - if not event.corona: - return notactive(request) - - # get data if it exists - try: - data = helper.contacttracingdata - except ContactTracingData.DoesNotExist: - data = None - - # form - form = ContactTracingDataForm(request.POST or None, instance=data, event=event) - if form.is_valid(): - form.save(helper=helper) - - logger.info( - "helper coronadata", - extra={ - "user": request.user, - "event": event, - "helper": helper, - }, - ) - - return redirect("corona:view_helper", event_url_name=event_url_name, helper_pk=helper.pk) - - # render page - context = {"event": event, "helper": helper, "form": form} - return render(request, "corona/edit_helper.html", context) diff --git a/src/corona/views/settings.py b/src/corona/views/settings.py deleted file mode 100644 index e97f7ebcf..000000000 --- a/src/corona/views/settings.py +++ /dev/null @@ -1,46 +0,0 @@ -from django.contrib.auth.decorators import login_required -from django.shortcuts import render, redirect, get_object_or_404 -from django.views.decorators.cache import never_cache - -from helfertool.utils import nopermission -from registration.models import Event -from registration.permissions import has_access, ACCESS_CORONA_EDIT - -from ..forms import CoronaSettingsForm -from .utils import notactive - -import logging - -logger = logging.getLogger("helfertool.corona") - - -@login_required -@never_cache -def settings(request, event_url_name): - event = get_object_or_404(Event, url_name=event_url_name) - - # check permission - if not has_access(request.user, event, ACCESS_CORONA_EDIT): - return nopermission(request) - - # check if corona contact tracing is active - if not event.corona: - return notactive(request) - - # form - form = CoronaSettingsForm(request.POST or None, instance=event.corona_settings) - if form.is_valid(): - form.save() - - logger.info( - "corona settings", - extra={ - "user": request.user, - "event": event, - }, - ) - - return redirect("corona:settings", event_url_name=event.url_name) - - context = {"event": event, "form": form} - return render(request, "corona/settings.html", context) diff --git a/src/corona/views/utils.py b/src/corona/views/utils.py deleted file mode 100644 index 61609b1f1..000000000 --- a/src/corona/views/utils.py +++ /dev/null @@ -1,5 +0,0 @@ -from django.shortcuts import render - - -def notactive(request): - return render(request, "corona/not_active.html") diff --git a/src/gifts/forms/fields.py b/src/gifts/forms/fields.py index ac5d2d00b..f64d10d66 100644 --- a/src/gifts/forms/fields.py +++ b/src/gifts/forms/fields.py @@ -1,7 +1,7 @@ from django.forms import ChoiceField, RadioSelect from django.utils.safestring import mark_safe from django.utils.text import format_lazy -from django.utils.translation import ugettext_lazy as _ +from django.utils.translation import gettext_lazy as _ from django.utils.functional import lazy from django_icons import icon diff --git a/src/gifts/forms/helpersgifts.py b/src/gifts/forms/helpersgifts.py index b2d811aa6..629c6f49d 100644 --- a/src/gifts/forms/helpersgifts.py +++ b/src/gifts/forms/helpersgifts.py @@ -1,5 +1,5 @@ from django import forms -from django.utils.translation import ugettext_lazy as _ +from django.utils.translation import gettext_lazy as _ from .fields import PresenceField from ..models import HelpersGifts diff --git a/src/gifts/forms/set.py b/src/gifts/forms/set.py index ad6d7d89a..3f5c5b44b 100644 --- a/src/gifts/forms/set.py +++ b/src/gifts/forms/set.py @@ -25,7 +25,7 @@ def __init__(self, *args, **kwargs): self.gift_form_ids[gift.pk] = gift_id number = 0 - if self.instance: + if self.instance.pk: number = self.instance.get_gift_num(gift) self.fields[gift_id] = forms.IntegerField(label=gift.name, required=False, min_value=0, initial=number) diff --git a/src/gifts/locale/de/LC_MESSAGES/django.po b/src/gifts/locale/de/LC_MESSAGES/django.po index 18cbecbcd..c010415b7 100644 --- a/src/gifts/locale/de/LC_MESSAGES/django.po +++ b/src/gifts/locale/de/LC_MESSAGES/django.po @@ -7,7 +7,7 @@ msgid "" msgstr "" "Project-Id-Version: \n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2022-07-25 19:30+0200\n" +"POT-Creation-Date: 2026-02-02 21:06+0100\n" "PO-Revision-Date: \n" "Last-Translator: \n" "Language-Team: \n" @@ -304,11 +304,11 @@ msgstr "Niemand ist für diese Schicht angemeldet." msgid "Gift deleted: %(name)s" msgstr "Geschenk gelöscht: %(name)s" -#: gifts/views/present.py:35 +#: gifts/views/present.py:36 msgid "Presence was saved" msgstr "Anwesenheit wurde gespeichert" -#: gifts/views/set.py:96 +#: gifts/views/set.py:90 #, python-format msgid "Gift set deleted: %(name)s" msgstr "Geschenkset gelöscht: %(name)s" diff --git a/src/gifts/migrations/0001_initial.py b/src/gifts/migrations/0001_initial.py index a648211c2..27ed106c8 100644 --- a/src/gifts/migrations/0001_initial.py +++ b/src/gifts/migrations/0001_initial.py @@ -6,7 +6,6 @@ class Migration(migrations.Migration): - initial = True dependencies = [] diff --git a/src/gifts/migrations/0002_auto_20160514_2307.py b/src/gifts/migrations/0002_auto_20160514_2307.py index b5e4eb711..58fef610f 100644 --- a/src/gifts/migrations/0002_auto_20160514_2307.py +++ b/src/gifts/migrations/0002_auto_20160514_2307.py @@ -8,7 +8,6 @@ class Migration(migrations.Migration): - dependencies = [ ("registration", "0009_event_gifts"), ("gifts", "0001_initial"), diff --git a/src/gifts/migrations/0003_auto_20160516_1551.py b/src/gifts/migrations/0003_auto_20160516_1551.py index 0af5166b7..b4e8ee2a8 100644 --- a/src/gifts/migrations/0003_auto_20160516_1551.py +++ b/src/gifts/migrations/0003_auto_20160516_1551.py @@ -6,7 +6,6 @@ class Migration(migrations.Migration): - dependencies = [ ("gifts", "0002_auto_20160514_2307"), ] diff --git a/src/gifts/migrations/0004_helpersgifts_got_shirt.py b/src/gifts/migrations/0004_helpersgifts_got_shirt.py index dac4ce61e..b2701fb9e 100644 --- a/src/gifts/migrations/0004_helpersgifts_got_shirt.py +++ b/src/gifts/migrations/0004_helpersgifts_got_shirt.py @@ -6,7 +6,6 @@ class Migration(migrations.Migration): - dependencies = [ ("gifts", "0003_auto_20160516_1551"), ] diff --git a/src/gifts/migrations/0005_auto_20160611_2243.py b/src/gifts/migrations/0005_auto_20160611_2243.py index 285a41324..76914dbe8 100644 --- a/src/gifts/migrations/0005_auto_20160611_2243.py +++ b/src/gifts/migrations/0005_auto_20160611_2243.py @@ -6,7 +6,6 @@ class Migration(migrations.Migration): - dependencies = [ ("gifts", "0004_helpersgifts_got_shirt"), ] diff --git a/src/gifts/migrations/0006_deservedgiftset_present.py b/src/gifts/migrations/0006_deservedgiftset_present.py index d9afb5fd3..62a1b1efd 100644 --- a/src/gifts/migrations/0006_deservedgiftset_present.py +++ b/src/gifts/migrations/0006_deservedgiftset_present.py @@ -6,7 +6,6 @@ class Migration(migrations.Migration): - dependencies = [ ("gifts", "0005_auto_20160611_2243"), ] diff --git a/src/gifts/migrations/0007_helpersgifts_buy_shirt.py b/src/gifts/migrations/0007_helpersgifts_buy_shirt.py index e16a6b298..085747552 100644 --- a/src/gifts/migrations/0007_helpersgifts_buy_shirt.py +++ b/src/gifts/migrations/0007_helpersgifts_buy_shirt.py @@ -6,7 +6,6 @@ class Migration(migrations.Migration): - dependencies = [ ("gifts", "0006_deservedgiftset_present"), ] diff --git a/src/gifts/migrations/0008_auto_20170401_1512.py b/src/gifts/migrations/0008_auto_20170401_1512.py index 304e01f5a..fe7113bf4 100644 --- a/src/gifts/migrations/0008_auto_20170401_1512.py +++ b/src/gifts/migrations/0008_auto_20170401_1512.py @@ -6,7 +6,6 @@ class Migration(migrations.Migration): - dependencies = [ ("registration", "0017_auto_20170210_1726"), ("gifts", "0007_helpersgifts_buy_shirt"), diff --git a/src/gifts/migrations/0009_giftsettings.py b/src/gifts/migrations/0009_giftsettings.py index 938d1ac24..5d44cde74 100644 --- a/src/gifts/migrations/0009_giftsettings.py +++ b/src/gifts/migrations/0009_giftsettings.py @@ -6,7 +6,6 @@ class Migration(migrations.Migration): - dependencies = [ ("gifts", "0008_auto_20170401_1512"), ] diff --git a/src/gifts/migrations/0010_add_giftsettings_for_events.py b/src/gifts/migrations/0010_add_giftsettings_for_events.py index 9d9755a48..fa614fa2f 100644 --- a/src/gifts/migrations/0010_add_giftsettings_for_events.py +++ b/src/gifts/migrations/0010_add_giftsettings_for_events.py @@ -13,7 +13,6 @@ def create_giftsettings(apps, schema_editor): class Migration(migrations.Migration): - dependencies = [ ("gifts", "0009_giftsettings"), ] diff --git a/src/gifts/migrations/0011_remove_helpersgifts_accomplished_shifts.py b/src/gifts/migrations/0011_remove_helpersgifts_accomplished_shifts.py index 81bd16d9c..49a3b6605 100644 --- a/src/gifts/migrations/0011_remove_helpersgifts_accomplished_shifts.py +++ b/src/gifts/migrations/0011_remove_helpersgifts_accomplished_shifts.py @@ -4,7 +4,6 @@ class Migration(migrations.Migration): - dependencies = [ ("gifts", "0010_add_giftsettings_for_events"), ("registration", "0036_add_helpershift_to_helper"), diff --git a/src/gifts/migrations/0012_auto_20210523_1533.py b/src/gifts/migrations/0012_auto_20210523_1533.py index 9c583ab38..e0c38b089 100644 --- a/src/gifts/migrations/0012_auto_20210523_1533.py +++ b/src/gifts/migrations/0012_auto_20210523_1533.py @@ -4,7 +4,6 @@ class Migration(migrations.Migration): - dependencies = [ ("gifts", "0011_remove_helpersgifts_accomplished_shifts"), ] diff --git a/src/gifts/models/deservedgiftset.py b/src/gifts/models/deservedgiftset.py index bb0a80d97..fb2c883b4 100644 --- a/src/gifts/models/deservedgiftset.py +++ b/src/gifts/models/deservedgiftset.py @@ -1,5 +1,5 @@ from django.db import models -from django.utils.translation import ugettext_lazy as _ +from django.utils.translation import gettext_lazy as _ from .set import GiftSet diff --git a/src/gifts/models/gift.py b/src/gifts/models/gift.py index 67c5ee52a..062941a64 100644 --- a/src/gifts/models/gift.py +++ b/src/gifts/models/gift.py @@ -1,5 +1,5 @@ from django.db import models -from django.utils.translation import ugettext_lazy as _ +from django.utils.translation import gettext_lazy as _ from copy import deepcopy diff --git a/src/gifts/models/giftsettings.py b/src/gifts/models/giftsettings.py index 5c6963681..d863dbcaa 100644 --- a/src/gifts/models/giftsettings.py +++ b/src/gifts/models/giftsettings.py @@ -1,6 +1,6 @@ from django.db import models from django.core.validators import MinValueValidator -from django.utils.translation import ugettext_lazy as _ +from django.utils.translation import gettext_lazy as _ from copy import deepcopy diff --git a/src/gifts/models/helpersgifts.py b/src/gifts/models/helpersgifts.py index 81918890e..7e6271605 100644 --- a/src/gifts/models/helpersgifts.py +++ b/src/gifts/models/helpersgifts.py @@ -1,7 +1,7 @@ from django.core.validators import MinValueValidator from django.db import models, transaction from django.utils import timezone -from django.utils.translation import ugettext_lazy as _ +from django.utils.translation import gettext_lazy as _ from registration.models.helpershift import HelperShift diff --git a/src/gifts/models/includedgift.py b/src/gifts/models/includedgift.py index 011c3b282..02fc60eed 100644 --- a/src/gifts/models/includedgift.py +++ b/src/gifts/models/includedgift.py @@ -1,6 +1,6 @@ from django.core.validators import MinValueValidator from django.db import models -from django.utils.translation import ugettext_lazy as _ +from django.utils.translation import gettext_lazy as _ from copy import deepcopy diff --git a/src/gifts/models/set.py b/src/gifts/models/set.py index dbad43a54..b23600cc6 100644 --- a/src/gifts/models/set.py +++ b/src/gifts/models/set.py @@ -1,6 +1,6 @@ from django.core.exceptions import MultipleObjectsReturned from django.db import models -from django.utils.translation import ugettext_lazy as _ +from django.utils.translation import gettext_lazy as _ from .gift import Gift from .includedgift import IncludedGift diff --git a/src/gifts/urls.py b/src/gifts/urls.py index 7b223bdad..1d7c82f8f 100644 --- a/src/gifts/urls.py +++ b/src/gifts/urls.py @@ -1,4 +1,4 @@ -from django.conf.urls import url +from django.urls import path from . import views @@ -7,44 +7,44 @@ # # list # - url(r"^(?P[a-zA-Z0-9]+)/gifts/$", views.list, name="list"), + path("/gifts/", views.list, name="list"), # # edit gifts # - url(r"^(?P[a-zA-Z0-9]+)/gifts/gift/add/$", views.edit_gift, name="add_gift"), - url(r"^(?P[a-zA-Z0-9]+)/gifts/gift/(?P[0-9]+)/$", views.edit_gift, name="edit_gift"), - url( - r"^(?P[a-zA-Z0-9]+)/gifts/gift/(?P[0-9]+)/" "delete/$", + path("/gifts/gift/add/", views.edit_gift, name="add_gift"), + path("/gifts/gift//", views.edit_gift, name="edit_gift"), + path( + "/gifts/gift//delete/", views.delete_gift, name="delete_gift", ), # # edit gift sets # - url(r"^(?P[a-zA-Z0-9]+)/gifts/giftset/add/$", views.edit_gift_set, name="add_gift_set"), - url( - r"^(?P[a-zA-Z0-9]+)/gifts/giftset/" "(?P[0-9]+)/$", + path("/gifts/giftset/add/", views.edit_gift_set, name="add_gift_set"), + path( + "/gifts/giftset//", views.edit_gift_set, name="edit_gift_set", ), - url( - r"^(?P[a-zA-Z0-9]+)/gifts/giftset/" "(?P[0-9]+)/delete/$", + path( + "/gifts/giftset//delete/", views.delete_gift_set, name="delete_gift_set", ), # # open deposits # - url(r"^(?P[a-zA-Z0-9]+)/gifts/deposit/$", views.list_deposit, name="list_deposit"), + path("/gifts/deposit/", views.list_deposit, name="list_deposit"), # # shirts that need to be bought # - url(r"^(?P[a-zA-Z0-9]+)/gifts/shirts/$", views.list_shirts, name="list_shirts"), + path("/gifts/shirts/", views.list_shirts, name="list_shirts"), # # set present flag for complete shifts # - url( - r"^(?P[a-zA-Z0-9]+)/gifts/present/" "(?P[0-9]+)/$", + path( + "/gifts/present//", views.set_present, name="set_present", ), diff --git a/src/gifts/views/gift.py b/src/gifts/views/gift.py index 6b5192c37..9773dba22 100644 --- a/src/gifts/views/gift.py +++ b/src/gifts/views/gift.py @@ -2,7 +2,7 @@ from django.contrib.auth.decorators import login_required from django.http import Http404 from django.shortcuts import render, redirect, get_object_or_404 -from django.utils.translation import ugettext as _ +from django.utils.translation import gettext as _ from django.views.decorators.cache import never_cache from helfertool.utils import nopermission diff --git a/src/gifts/views/present.py b/src/gifts/views/present.py index cc8bf7460..354b03107 100644 --- a/src/gifts/views/present.py +++ b/src/gifts/views/present.py @@ -1,7 +1,8 @@ from django.contrib import messages from django.contrib.auth.decorators import login_required from django.shortcuts import render, redirect -from django.utils.translation import ugettext as _ +from django.urls import reverse +from django.utils.translation import gettext as _ from django.views.decorators.cache import never_cache from helfertool.utils import nopermission @@ -34,7 +35,9 @@ def set_present(request, event_url_name, shift_pk): messages.success(request, _("Presence was saved")) - return redirect("gifts:set_present", event_url_name=event.url_name, shift_pk=shift.pk) + return redirect( + f"{reverse('helpers_for_job', kwargs={'event_url_name': event.url_name, 'job_pk': shift.job.pk})}#shift_{shift.pk}" + ) context = {"event": event, "shift": shift, "form": form} return render(request, "gifts/set_present.html", context) diff --git a/src/gifts/views/set.py b/src/gifts/views/set.py index 752b17d10..0989178bb 100644 --- a/src/gifts/views/set.py +++ b/src/gifts/views/set.py @@ -2,7 +2,7 @@ from django.contrib.auth.decorators import login_required from django.http import Http404 from django.shortcuts import render, redirect, get_object_or_404 -from django.utils.translation import ugettext as _ +from django.utils.translation import gettext as _ from django.views.decorators.cache import never_cache from helfertool.utils import nopermission @@ -19,18 +19,6 @@ logger = logging.getLogger("helfertool.gifts") -def _validate_gift_set(event, gift_set_pk): - if gift_set_pk: - gift_set = get_object_or_404(GiftSet, pk=gift_set_pk) - - # check if permission belongs to event - if gift_set.event != event: - raise Http404() - - return gift_set - return None - - @login_required @never_cache @archived_not_available @@ -45,7 +33,10 @@ def edit_gift_set(request, event_url_name, gift_set_pk=None): if not event.gifts: return notactive(request) - gift_set = _validate_gift_set(event, gift_set_pk) + # get gift set + gift_set = None + if gift_set_pk: + gift_set = get_object_or_404(GiftSet, pk=gift_set_pk, event=event) # form form = GiftSetForm(request.POST or None, instance=gift_set, event=event) @@ -86,7 +77,10 @@ def delete_gift_set(request, event_url_name, gift_set_pk): if not event.gifts: return notactive(request) - gift_set = _validate_gift_set(event, gift_set_pk) + # get gift set + gift_set = None + if gift_set_pk: + gift_set = get_object_or_404(GiftSet, pk=gift_set_pk, event=event) # form form = GiftSetDeleteForm(request.POST or None, instance=gift_set) diff --git a/src/helfertool.yaml b/src/helfertool.yaml index ccc569f17..1cf2756d7 100644 --- a/src/helfertool.yaml +++ b/src/helfertool.yaml @@ -15,15 +15,15 @@ language: # Default language if not specified by the browser default: "de" + # Only provide the tool in the default language (removed the language selection) + singlelanguage: false + # Language used for badges badges: "de" # Timezone timezone: "Europe/Berlin" - # Default country for Corona contact tracing (ISO-3166-1) - country: "DE" - # Database connection database: # SQLite @@ -117,8 +117,15 @@ authentication: # # # LDAP schema and attributes # schema: - # # User definition - # user_dn_template: "uid=%(user)s,ou=People,dc=helfertool,dc=org" + # # User search - option 1: search for user based on attribute, bind then + # user_search_base: "ou=People,dc=helfertool,dc=org" + # user_search_filter: "(uid=%(user)s)" + # + # # User search - option 2: direct bind + # # If this option is enabled, the search is skipped + # #user_dn_template: "uid=%(user)s,ou=People,dc=helfertool,dc=org" + # + # # User attribute definition # first_name_attr: "givenName" # last_name_attr: "sn" # email_attr: "mail" @@ -158,10 +165,12 @@ authentication: # client_id: "helfertool" # client_secret: "" # - # # Controls the session cookie SameSite attribute, forcing it to "Lax". This is necessary if your OIDC provider - # # resides on a different top level domain name than the Helfertool (error message: "Login failed") - # # Set it to true in this case. - # thirdparty_domain: false + # # The requested scopes + # scopes: "openid email profile" + # + # # The claim that should be used as username + # # Reasonable choices are email or preferred_username + # username_claim: "email" # # # It could happen that the user is disabled or claims change. So we can redirect the users from time to time # # to the OIDC provider and validate if they are still allowed to login. @@ -170,10 +179,11 @@ authentication: # # # If the session is only terminated in the application, the login via OIDC works again without asking for credentials. # # Therefore, we can also trigger a logout at the OIDC provider. - # # The URL is less well specified and depends on the provider (here: Keycloak) + # # We built URLs according to the OpenID Connect RP-Initiated Logout 1.0 standard by default # logout: # endpoint: "https://auth.helfertool.org/auth/realms/test/protocol/openid-connect/logout" # redirect_parameter: "redirect_uri" + # id_token_hint: true # # # Permissions based on claims # claims: @@ -233,6 +243,7 @@ security: debug: true # Unique and secret key + # At least 50 characters recommended, for example: pwgen -s 50 1 secret: "change_this_for_production" # URLs that are used for the software @@ -240,8 +251,8 @@ security: # - "app.helfertool.org" # - "www.app.helfertool.org" - # Application is behind additional/second proxy. In this case, the HTTP - # header X-Forwarded-Host is used. Example: Apache > nginx > uwsgi + # Application is behind reverse proxy. In this case, the HTTP header X-Forwarded-Proto + # is used to check if the application is accessed via HTTPS. behind_proxy: False # Account lockout @@ -255,6 +266,17 @@ security: # Minimal password length (for local accounts) password_length: 12 + # Enable captchas + captchas: + # for newsletter registration (recommended) + newsletter: true + + # for password reset (recommended) + password_reset: true + + # for event registration + registration: false + # Helfertool features can be disabled globally here (true means enabled, false means disabled). # If a flag is changed to disabled, all events are modified automatically after a reload (of celery). # Enabling a feature does not change event settings. @@ -269,10 +291,12 @@ features: gifts: true prerequisites: true inventory: true - corona: true # Custom URLs, mail addresses, ... customization: + # Title for all pages + title: "Helfertool" + # Modify certain properties for the general helfertool to display display: # Maximum years of events to be displayed by default on the main page @@ -319,6 +343,9 @@ badges: # Maximum number of copies for special badges special_badges_max: 50 + # Time until PDF build is aborted in minutes + build_timeout: 5 + # Time until PDF file is deleted after it was created in minutes pdf_timeout: 30 @@ -331,3 +358,20 @@ newsletter: # Newsletter subscriptions need to be confirmed with by clicking on a link. # This setting specifies how long the link is valid (days). Afterwards, the mail address is deleted. subscribe_deadline: 3 + +# Automations for Helfertool management +automation: + # Send reminder mails to event admins that did not archive the event within time + # "deadline" and "interval" need to be set to enable the feature + #event_archive: + # # Deadline (months) + # deadline: 6 + # + # # Interval of mails (days) + # interval: 7 + # + # # Start this number of days before the deadline (optional) + # start_before_deadline: 14 + # + # # Link to some documentation that is included in the mail (optional) + # #docs: "" diff --git a/src/helfertool/celery.py b/src/helfertool/celery.py index 96d46caa8..9d26f3060 100644 --- a/src/helfertool/celery.py +++ b/src/helfertool/celery.py @@ -8,6 +8,7 @@ from celery import Celery from celery.signals import task_failure +from celery.schedules import crontab # set the default Django settings module for the 'celery' program. os.environ.setdefault("DJANGO_SETTINGS_MODULE", "helfertool.settings") @@ -24,13 +25,20 @@ def setup_periodic_tasks(sender, **kwargs): # for debugging, add own exception handling that prints all exceptions # # additionally, django is not fully loaded here. importing models will fail - from mail.tasks import receive_mails + try: + from mail.tasks import receive_mails - sender.add_periodic_task(settings.RECEIVE_INTERVAL, receive_mails.s()) + sender.add_periodic_task(settings.RECEIVE_INTERVAL, receive_mails.s()) - from news.tasks import cleanup + from news.tasks import cleanup - sender.add_periodic_task(3600, cleanup.s()) + sender.add_periodic_task(3600, cleanup.s()) + + from adminautomation.tasks import event_archive_automation + + sender.add_periodic_task(crontab(hour=21, minute=0), event_archive_automation.s()) + except Exception as e: + print(f"ERROR during setup of periodic tasks (setup_periodic_tasks): {e}") @task_failure.connect diff --git a/src/helfertool/converters.py b/src/helfertool/converters.py new file mode 100644 index 000000000..f80d5bcb3 --- /dev/null +++ b/src/helfertool/converters.py @@ -0,0 +1,15 @@ +from django.utils.dateparse import parse_date + + +class DateConverter: + regex = "[0-9]{2,4}-[0-9]{1,2}-[0-9]{1,2}" + + def to_python(self, value): + tmp = parse_date(value) + # parse_date returns None if input is not well formated, but we need a ValueError here + if not tmp: + raise ValueError("invalid date") + return tmp + + def to_url(self, value): + return value.strftime("%Y-%m-%d") diff --git a/src/helfertool/forms/__init__.py b/src/helfertool/forms/__init__.py index 1b5511077..240e3cc71 100644 --- a/src/helfertool/forms/__init__.py +++ b/src/helfertool/forms/__init__.py @@ -1,2 +1,9 @@ -from .widgets import DatePicker, DateTimePicker, SingleUserSelectWidget, UserSelectWidget, ImageFileInput +from .widgets import ( + DatePicker, + DateTimePicker, + SingleUserSelectWidget, + UserSelectWidget, + ImageFileInput, + CustomCaptchaTextInput, +) from .fields import RestrictedImageField diff --git a/src/helfertool/forms/fields.py b/src/helfertool/forms/fields.py index 26792e452..461522769 100644 --- a/src/helfertool/forms/fields.py +++ b/src/helfertool/forms/fields.py @@ -1,6 +1,6 @@ from django.core.exceptions import ValidationError from django.db import models -from django.utils.translation import ugettext_lazy as _ +from django.utils.translation import gettext_lazy as _ import os diff --git a/src/helfertool/forms/widgets.py b/src/helfertool/forms/widgets.py index 7e9e38a3a..d973c6b8c 100644 --- a/src/helfertool/forms/widgets.py +++ b/src/helfertool/forms/widgets.py @@ -3,6 +3,7 @@ from django.utils.translation import gettext_lazy as _ from django_select2.forms import ModelSelect2Widget, ModelSelect2MultipleWidget +from captcha.fields import CaptchaTextInput class DatePicker(forms.DateInput): @@ -78,3 +79,7 @@ def get_context(self, name, value, attrs): context = super().get_context(name, value, attrs) context["widget"]["download_url"] = self.download_url return context + + +class CustomCaptchaTextInput(CaptchaTextInput): + template_name = "helfertool/forms/widgets/captcha.html" diff --git a/src/helfertool/locale/de/LC_MESSAGES/django.mo b/src/helfertool/locale/de/LC_MESSAGES/django.mo index 954dd6a3b..0e7be9b30 100644 Binary files a/src/helfertool/locale/de/LC_MESSAGES/django.mo and b/src/helfertool/locale/de/LC_MESSAGES/django.mo differ diff --git a/src/helfertool/locale/de/LC_MESSAGES/django.po b/src/helfertool/locale/de/LC_MESSAGES/django.po index 4ed83130a..b5d3ac902 100644 --- a/src/helfertool/locale/de/LC_MESSAGES/django.po +++ b/src/helfertool/locale/de/LC_MESSAGES/django.po @@ -7,7 +7,7 @@ msgid "" msgstr "" "Project-Id-Version: \n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2022-07-25 19:30+0200\n" +"POT-Creation-Date: 2026-01-25 15:26+0100\n" "PO-Revision-Date: \n" "Last-Translator: \n" "Language-Team: \n" @@ -15,13 +15,13 @@ msgstr "" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"X-Generator: Poedit 3.1.1\n" +"X-Generator: Poedit 3.8\n" #: helfertool/forms/fields.py:18 msgid "File type not supported, use JPG or PNG." msgstr "Dateityp nicht unterstützt, verwende JPG oder PNG." -#: helfertool/forms/widgets.py:73 +#: helfertool/forms/widgets.py:74 msgid "Delete image" msgstr "Bild löschen" @@ -29,11 +29,11 @@ msgstr "Bild löschen" msgid "User" msgstr "Benutzer:in" -#: helfertool/settings.py:62 +#: helfertool/settings.py:65 helfertool/settings.py:73 msgid "German" msgstr "Deutsch" -#: helfertool/settings.py:63 +#: helfertool/settings.py:67 helfertool/settings.py:74 msgid "English" msgstr "English" @@ -83,163 +83,154 @@ msgstr "Error 500" msgid "The admins were notified already." msgstr "Die Admins wurden bereits benachrichtigt." -#: helfertool/templates/helfertool/admin_event_menu.html:33 +#: helfertool/templates/helfertool/admin_event_menu.html:31 msgid "archived" msgstr "archiviert" -#: helfertool/templates/helfertool/admin_event_menu.html:39 +#: helfertool/templates/helfertool/admin_event_menu.html:37 #: helfertool/templates/helfertool/admin_general_menu.html:10 msgid "General" msgstr "Allgemein" -#: helfertool/templates/helfertool/admin_event_menu.html:44 +#: helfertool/templates/helfertool/admin_event_menu.html:42 msgid "Go to registration" msgstr "Zur Anmeldung" -#: helfertool/templates/helfertool/admin_event_menu.html:50 +#: helfertool/templates/helfertool/admin_event_menu.html:48 msgid "Edit event" msgstr "Veranstaltung bearbeiten" -#: helfertool/templates/helfertool/admin_event_menu.html:54 +#: helfertool/templates/helfertool/admin_event_menu.html:52 msgid "Permissions" msgstr "Berechtigungen" -#: helfertool/templates/helfertool/admin_event_menu.html:60 +#: helfertool/templates/helfertool/admin_event_menu.html:58 msgid "Jobs and shifts" msgstr "Aufgaben und Schichten" -#: helfertool/templates/helfertool/admin_event_menu.html:66 +#: helfertool/templates/helfertool/admin_event_menu.html:64 msgid "Links" msgstr "Links" -#: helfertool/templates/helfertool/admin_event_menu.html:72 +#: helfertool/templates/helfertool/admin_event_menu.html:70 msgid "Audit log" msgstr "Auditprotokoll" -#: helfertool/templates/helfertool/admin_event_menu.html:79 +#: helfertool/templates/helfertool/admin_event_menu.html:77 msgid "Helpers" msgstr "Helfer:innen" -#: helfertool/templates/helfertool/admin_event_menu.html:82 +#: helfertool/templates/helfertool/admin_event_menu.html:80 msgid "Helpers and coordinators" msgstr "Helfer:innen und Koordinator:innen" -#: helfertool/templates/helfertool/admin_event_menu.html:103 +#: helfertool/templates/helfertool/admin_event_menu.html:101 msgid "Search helper" msgstr "Helfer:in suchen" -#: helfertool/templates/helfertool/admin_event_menu.html:108 +#: helfertool/templates/helfertool/admin_event_menu.html:106 msgid "Duplicates" msgstr "Duplikate" -#: helfertool/templates/helfertool/admin_event_menu.html:113 +#: helfertool/templates/helfertool/admin_event_menu.html:111 msgid "Vacant shifts" msgstr "Unbesetzte Schichten" -#: helfertool/templates/helfertool/admin_event_menu.html:118 +#: helfertool/templates/helfertool/admin_event_menu.html:116 msgid "All coordinators" msgstr "Alle Koordinator:innen" -#: helfertool/templates/helfertool/admin_event_menu.html:127 +#: helfertool/templates/helfertool/admin_event_menu.html:125 msgid "Mail" msgstr "E-Mail" -#: helfertool/templates/helfertool/admin_event_menu.html:131 +#: helfertool/templates/helfertool/admin_event_menu.html:129 msgid "Send" msgstr "Senden" -#: helfertool/templates/helfertool/admin_event_menu.html:137 +#: helfertool/templates/helfertool/admin_event_menu.html:135 msgid "All mails" msgstr "Alle E-Mails" -#: helfertool/templates/helfertool/admin_event_menu.html:146 +#: helfertool/templates/helfertool/admin_event_menu.html:144 msgid "Statistics" msgstr "Statistik" -#: helfertool/templates/helfertool/admin_event_menu.html:150 +#: helfertool/templates/helfertool/admin_event_menu.html:148 msgid "Overview" msgstr "Übersicht" -#: helfertool/templates/helfertool/admin_event_menu.html:156 +#: helfertool/templates/helfertool/admin_event_menu.html:154 msgid "T-Shirts" msgstr "T-Shirts" -#: helfertool/templates/helfertool/admin_event_menu.html:162 +#: helfertool/templates/helfertool/admin_event_menu.html:160 msgid "Nutrition" msgstr "Ernährung" -#: helfertool/templates/helfertool/admin_event_menu.html:172 +#: helfertool/templates/helfertool/admin_event_menu.html:170 msgid "Gifts and presence" msgstr "Geschenke und Anwesenheit" -#: helfertool/templates/helfertool/admin_event_menu.html:176 -#: helfertool/templates/helfertool/admin_event_menu.html:203 -#: helfertool/templates/helfertool/admin_event_menu.html:247 -#: helfertool/templates/helfertool/admin_event_menu.html:276 +#: helfertool/templates/helfertool/admin_event_menu.html:174 +#: helfertool/templates/helfertool/admin_event_menu.html:201 +#: helfertool/templates/helfertool/admin_event_menu.html:245 #: helfertool/templates/helfertool/admin_general_menu.html:6 #: helfertool/templates/helfertool/admin_general_menu.html:90 msgid "Settings" msgstr "Einstellungen" -#: helfertool/templates/helfertool/admin_event_menu.html:182 +#: helfertool/templates/helfertool/admin_event_menu.html:180 msgid "Collected deposit" msgstr "Gesammeltes Pfand" -#: helfertool/templates/helfertool/admin_event_menu.html:187 +#: helfertool/templates/helfertool/admin_event_menu.html:185 msgid "Missing T-shirts" msgstr "Fehlende T-Shirts" -#: helfertool/templates/helfertool/admin_event_menu.html:199 +#: helfertool/templates/helfertool/admin_event_menu.html:197 msgid "Badges" msgstr "Badges" -#: helfertool/templates/helfertool/admin_event_menu.html:209 +#: helfertool/templates/helfertool/admin_event_menu.html:207 msgid "Special badges" msgstr "Spezial Badges" -#: helfertool/templates/helfertool/admin_event_menu.html:215 +#: helfertool/templates/helfertool/admin_event_menu.html:213 msgid "Generate" msgstr "Generieren" -#: helfertool/templates/helfertool/admin_event_menu.html:220 +#: helfertool/templates/helfertool/admin_event_menu.html:218 msgctxt "Badges" msgid "Registration" msgstr "Registrierung" -#: helfertool/templates/helfertool/admin_event_menu.html:231 +#: helfertool/templates/helfertool/admin_event_menu.html:229 msgid "Prerequisites" msgstr "Voraussetzungen" -#: helfertool/templates/helfertool/admin_event_menu.html:234 +#: helfertool/templates/helfertool/admin_event_menu.html:232 msgid "Settings and lists" msgstr "Einstellungen und Listen" -#: helfertool/templates/helfertool/admin_event_menu.html:243 +#: helfertool/templates/helfertool/admin_event_menu.html:241 #: helfertool/templates/helfertool/admin_general_menu.html:31 msgid "Inventory" msgstr "Inventar" -#: helfertool/templates/helfertool/admin_event_menu.html:253 +#: helfertool/templates/helfertool/admin_event_menu.html:251 msgctxt "Register item and badge" msgid "Register" msgstr "Eintragen" -#: helfertool/templates/helfertool/admin_event_menu.html:257 +#: helfertool/templates/helfertool/admin_event_menu.html:255 msgid "Take back" msgstr "Zurücknehmen" -#: helfertool/templates/helfertool/admin_event_menu.html:261 +#: helfertool/templates/helfertool/admin_event_menu.html:259 msgid "List" msgstr "Liste" -#: helfertool/templates/helfertool/admin_event_menu.html:272 -msgid "COVID-19" -msgstr "COVID-19" - -#: helfertool/templates/helfertool/admin_event_menu.html:281 -msgid "Data" -msgstr "Daten" - #: helfertool/templates/helfertool/admin_general_menu.html:13 msgid "My account" msgstr "Mein Account" @@ -249,8 +240,8 @@ msgid "New event" msgstr "Neue Veranstaltung" #: helfertool/templates/helfertool/admin_general_menu.html:24 -msgid "Past events" -msgstr "Vergangene Veranstaltungen" +msgid "Archiving" +msgstr "Archivierung" #: helfertool/templates/helfertool/admin_general_menu.html:37 msgid "Support" @@ -264,7 +255,7 @@ msgstr "Benutzer:innen" msgid "Add user" msgstr "Benutzer:in hinzufügen" -#: helfertool/templates/helfertool/admin_general_menu.html:54 +#: helfertool/templates/helfertool/admin_general_menu.html:52 msgid "All users" msgstr "Alle Benutzer:innen" @@ -300,42 +291,42 @@ msgstr "Installation überprüfen" msgid "Django Admin Interface" msgstr "Django Admin Interface" -#: helfertool/templates/helfertool/base.html:24 -msgid "Helfertool" -msgstr "Helfertool" - -#: helfertool/templates/helfertool/base.html:42 +#: helfertool/templates/helfertool/base.html:38 msgid "Events" msgstr "Veranstaltungen" -#: helfertool/templates/helfertool/base.html:49 +#: helfertool/templates/helfertool/base.html:45 msgctxt "Admin interface" msgid "Administration" msgstr "Verwaltung" -#: helfertool/templates/helfertool/base.html:87 -#: helfertool/templates/helfertool/base.html:92 +#: helfertool/templates/helfertool/base.html:86 +#: helfertool/templates/helfertool/base.html:94 msgid "Logout" msgstr "Logout" -#: helfertool/templates/helfertool/base.html:97 +#: helfertool/templates/helfertool/base.html:100 #: helfertool/templates/helfertool/login.html:5 #: helfertool/templates/helfertool/login.html:34 msgid "Login" msgstr "Login" -#: helfertool/templates/helfertool/base.html:126 +#: helfertool/templates/helfertool/base.html:127 msgid "Privacy" msgstr "Datenschutz" -#: helfertool/templates/helfertool/base.html:128 +#: helfertool/templates/helfertool/base.html:129 msgid "Imprint" msgstr "Impressum" -#: helfertool/templates/helfertool/base.html:130 +#: helfertool/templates/helfertool/base.html:131 msgid "About this software" msgstr "Über diese Software" +#: helfertool/templates/helfertool/forms/widgets/captcha.html:19 +msgid "Click on the captcha to load a new one" +msgstr "Auf das Captcha klicken, um ein neues zu laden" + #: helfertool/templates/helfertool/forms/widgets/image_file_input.html:25 msgid "Image preview" msgstr "Bild Vorschau" @@ -350,6 +341,10 @@ msgstr "Mit %(name)s einloggen" msgid "Local account" msgstr "Lokaler Account" +#: helfertool/templates/helfertool/login.html:38 +msgid "Forgot password" +msgstr "Passwort vergessen" + #: helfertool/templates/helfertool/login_banned.html:8 msgid "Too many login attempts!" msgstr "Zu viele Login Versuche!" @@ -379,6 +374,18 @@ msgstr "Kein Zugriff" msgid "You have no permission to view this page!" msgstr "Du hast keine Berechtigung, um diese Seite anzusehen!" +#~ msgid "COVID-19" +#~ msgstr "COVID-19" + +#~ msgid "Data" +#~ msgstr "Daten" + +#~ msgid "Past events" +#~ msgstr "Vergangene Veranstaltungen" + +#~ msgid "Helfertool" +#~ msgstr "Helfertool" + #~ msgid "User management" #~ msgstr "Benutzerverwaltung" diff --git a/src/helfertool/oidc.py b/src/helfertool/oidc.py index 3de81a77b..5e140dddf 100644 --- a/src/helfertool/oidc.py +++ b/src/helfertool/oidc.py @@ -7,12 +7,6 @@ from mozilla_django_oidc.auth import OIDCAuthenticationBackend import jmespath -import unicodedata - - -# the username is the mail address -def generate_username(email): - return unicodedata.normalize("NFKC", email)[:150] # whitelist logins via openid connect in django-axes as locking it the job if the identity provider @@ -27,19 +21,29 @@ def axes_whitelist(request, credentials): # logout at OIDC provider def custom_oidc_logout(request): + url_parameters = {} + if settings.OIDC_CUSTOM_LOGOUT_REDIRECT_PARAMTER: - redirect_url = request.build_absolute_uri(settings.LOGOUT_REDIRECT_URL) - query = urlencode({settings.OIDC_CUSTOM_LOGOUT_REDIRECT_PARAMTER: redirect_url}) - return "{}?{}".format(settings.OIDC_CUSTOM_LOGOUT_ENDPOINT, query) - else: - return settings.OIDC_CUSTOM_LOGOUT_ENDPOINT + url_parameters[settings.OIDC_CUSTOM_LOGOUT_REDIRECT_PARAMTER] = request.build_absolute_uri( + settings.LOGOUT_REDIRECT_URL + ) + + if settings.OIDC_CUSTOM_LOGOUT_ID_TOKEN_HINT: + url_parameters["id_token_hint"] = request.session.get("oidc_id_token", "") + + query = urlencode(url_parameters) + return "{}?{}".format(settings.OIDC_CUSTOM_LOGOUT_ENDPOINT, query) class CustomOIDCAuthenticationBackend(OIDCAuthenticationBackend): def verify_claims(self, claims): verified = super(CustomOIDCAuthenticationBackend, self).verify_claims(claims) - # we require the given_name and family_name + # we require the claim that contains the username (obviously) + if settings.OIDC_CUSTOM_USERNAME_CLAIM not in claims: + return False + + # we require the given_name and family_name, email is already checked by verify_claims if "given_name" not in claims or "family_name" not in claims: return False @@ -52,6 +56,22 @@ def verify_claims(self, claims): return verified and is_active + def get_username(self, claims): + return claims.get(settings.OIDC_CUSTOM_USERNAME_CLAIM) + + # match users based on username field + def filter_users_by_claims(self, claims): + username = self.get_username(claims) + + if not username: + return self.UserModel.objects.none() + + try: + user = self.UserModel.objects.get(username__iexact=username) + return [user] + except self.UserModel.DoesNotExist: + return self.UserModel.objects.none() + # called on first login when no user object exists def create_user(self, claims): user = super(CustomOIDCAuthenticationBackend, self).create_user(claims) @@ -61,9 +81,11 @@ def create_user(self, claims): # called on login when the user already exists, just update all attributes def update_user(self, user, claims): - # name + # name + email + # email is optional here, but will be required by verify_claims if the email scope is requested user.first_name = claims.get("given_name") user.last_name = claims.get("family_name") + user.email = claims.get("email", "") # check if login should be restricted (if not, login is allowed) if settings.OIDC_CUSTOM_CLAIM_LOGIN: diff --git a/src/helfertool/override_translations.py b/src/helfertool/override_translations.py index f4541c98d..454566c2d 100644 --- a/src/helfertool/override_translations.py +++ b/src/helfertool/override_translations.py @@ -1,4 +1,4 @@ -from django.utils.translation import ugettext_lazy as _ +from django.utils.translation import gettext_lazy as _ # Django uses the first translation it detects in an installed app. # The "helfertool" app is listed first, so we have can override default translations here. diff --git a/src/helfertool/settings.py b/src/helfertool/settings.py index 49d6e3f75..67ad67f42 100644 --- a/src/helfertool/settings.py +++ b/src/helfertool/settings.py @@ -7,7 +7,7 @@ import sys import yaml -from django.utils.translation import ugettext_lazy as _ +from django.utils.translation import gettext_lazy as _ from datetime import timedelta from pathlib import Path @@ -58,17 +58,25 @@ TIME_ZONE = dict_get(config, "Europe/Berlin", "language", "timezone") -LANGUAGES = ( - ("de", _("German")), - ("en", _("English")), -) +LANGUAGE_SINGLELANGUAGE = dict_get(config, False, "language", "singlelanguage") + +if LANGUAGE_SINGLELANGUAGE: + if LANGUAGE_CODE == "de": + LANGUAGES = (("de", _("German")),) + elif LANGUAGE_CODE == "en": + LANGUAGES = (("en", _("English")),) + else: + print("Invalid language: {}".format(LANGUAGE_CODE)) + sys.exit(1) +else: + LANGUAGES = ( + ("de", _("German")), + ("en", _("English")), + ) USE_I18N = True -USE_L10N = True USE_TZ = True -DEFAULT_COUNTRY = dict_get(config, "DE", "language", "country") - # database DATABASES = { "default": { @@ -96,8 +104,10 @@ dict_get(config, "5672", "rabbitmq", "port"), dict_get(config, "", "rabbitmq", "vhost"), ) -CELERY_RESULT_BACKEND = CELERY_BROKER_URL +CELERY_RESULT_BACKEND = "django-db" +CELERY_RESULT_EXTENDED = True CELERY_BROKER_POOL_LIMIT = None +CELERY_BROKER_CONNECTION_RETRY_ON_STARTUP = True # caches CACHES = { @@ -161,6 +171,7 @@ EMAIL_SENDER_NAME = dict_get(config, EMAIL_SENDER_ADDRESS, "mail", "sender_name") SERVER_EMAIL = EMAIL_SENDER_ADDRESS # for error messages +DEFAULT_FROM_EMAIL = EMAIL_SENDER_ADDRESS # for other messages, like password resets # forward mails that were not handled automatically to this address # the display name defaults to the mail address @@ -176,6 +187,8 @@ LOGIN_REDIRECT_URL = "/manage/account/check/" LOGOUT_REDIRECT_URL = "/" +PASSWORD_RESET_TIMEOUT = 1800 # 30 minutes + LOCAL_USER_CHAR = dict_get(config, None, "authentication", "local_user_char") # LDAP @@ -189,8 +202,19 @@ AUTH_LDAP_BIND_DN = dict_get(ldap_config, None, "server", "bind_dn") AUTH_LDAP_BIND_PASSWORD = dict_get(ldap_config, None, "server", "bind_password") - # user schema + # user search + user_search_base = dict_get(ldap_config, None, "schema", "user_search_base") + user_search_filter = dict_get(ldap_config, None, "schema", "user_search_filter") + if user_search_base is not None and user_search_filter is not None: + AUTH_LDAP_USER_SEARCH = django_auth_ldap.config.LDAPSearch( + user_search_base, + ldap.SCOPE_SUBTREE, # pylint: disable=E1101 + user_search_filter, + ) + AUTH_LDAP_USER_DN_TEMPLATE = dict_get(ldap_config, None, "schema", "user_dn_template") + + # user schema AUTH_LDAP_USER_ATTR_MAP = { "first_name": dict_get(ldap_config, "givenName", "schema", "first_name_attr"), "last_name": dict_get(ldap_config, "sn", "schema", "last_name_attr"), @@ -240,23 +264,25 @@ OIDC_OP_TOKEN_ENDPOINT = dict_get(oidc_config, None, "provider", "token_endpoint") OIDC_OP_USER_ENDPOINT = dict_get(oidc_config, None, "provider", "user_endpoint") - OIDC_RP_SCOPES = "openid email profile" # also ask for profile -> given_name and family_name + OIDC_RP_SCOPES = dict_get(oidc_config, "openid email profile", "provider", "scopes") + + OIDC_CUSTOM_USERNAME_CLAIM = dict_get(oidc_config, "email", "provider", "username_claim") oidc_renew_check_interval = dict_get(oidc_config, 0, "provider", "renew_check_interval") if oidc_renew_check_interval > 0: OIDC_RENEW_ID_TOKEN_EXPIRY_SECONDS = oidc_renew_check_interval * 60 - # username is mail address - OIDC_USERNAME_ALGO = "helfertool.oidc.generate_username" - # login and logout LOGIN_REDIRECT_URL_FAILURE = "/oidc/failed" - ALLOW_LOGOUT_GET_METHOD = True + + # store id token so that we can use it for the logout endpoint + OIDC_STORE_ID_TOKEN = True oidc_logout = dict_get(oidc_config, None, "provider", "logout") if oidc_logout: OIDC_CUSTOM_LOGOUT_ENDPOINT = dict_get(oidc_logout, None, "endpoint") - OIDC_CUSTOM_LOGOUT_REDIRECT_PARAMTER = dict_get(oidc_logout, None, "redirect_parameter") + OIDC_CUSTOM_LOGOUT_REDIRECT_PARAMTER = dict_get(oidc_logout, "post_logout_redirect_uri", "redirect_parameter") + OIDC_CUSTOM_LOGOUT_ID_TOKEN_HINT = dict_get(oidc_logout, True, "id_token_hint") OIDC_OP_LOGOUT_URL_METHOD = "helfertool.oidc.custom_oidc_logout" @@ -297,12 +323,15 @@ ] # axes: user lockout based on username, not IP or user agent +# if we remove the ip_address, axes complains... so we have both now +AXES_LOCKOUT_PARAMETERS = [ + ["username"], + ["username", "ip_address"], +] AXES_LOCK_OUT_AT_FAILURE = True -AXES_ONLY_USER_FAILURES = True -AXES_USE_USER_AGENT = False AXES_FAILURE_LIMIT = dict_get(config, 5, "security", "lockout", "limit") -AXES_COOLOFF_TIME = timedelta(minutes=dict_get(config, 10, "security", "lockout", "time")) +AXES_COOLOFF_TIME = lambda request: timedelta(minutes=dict_get(config, 10, "security", "lockout", "time")) AXES_LOCKOUT_TEMPLATE = "helfertool/login_banned.html" AXES_DISABLE_ACCESS_LOG = True @@ -312,34 +341,42 @@ # security DEBUG = dict_get(config, False, "security", "debug") SECRET_KEY = dict_get(config, "CHANGEME", "security", "secret") -ALLOWED_HOSTS = dict_get(config, [], "security", "allowed_hosts") +ALLOWED_HOSTS = dict_get(config, [], "security", "allowed_hosts") or [] # empty list in config is None, but we need [] + +CAPTCHAS_NEWSLETTER = dict_get(config, True, "security", "captchas", "newsletter") +CAPTCHAS_PASSWORD_RESET = dict_get(config, True, "security", "captchas", "password_reset") +CAPTCHAS_REGISTRATION = dict_get(config, False, "security", "captchas", "registration") # use X-Forwarded-Proto header to determine if https is used (overwritten in settings_container.py) if dict_get(config, False, "security", "behind_proxy"): SECURE_PROXY_SSL_HEADER = ("HTTP_X_FORWARDED_PROTO", "https") -# enable X-XSS-Protection (although modern browsers do not support it anymore) -SECURE_BROWSER_XSS_FILTER = True +# password hashers: use scrypt instead of PBKDF2 +PASSWORD_HASHERS = [ + "django.contrib.auth.hashers.ScryptPasswordHasher", + "django.contrib.auth.hashers.PBKDF2PasswordHasher", + "django.contrib.auth.hashers.PBKDF2SHA1PasswordHasher", + "django.contrib.auth.hashers.Argon2PasswordHasher", + "django.contrib.auth.hashers.BCryptSHA256PasswordHasher", +] # cookies LANGUAGE_COOKIE_NAME = "lang" +LANGUAGE_COOKIE_HTTPONLY = True +LANGUAGE_COOKIE_SAMESITE = "Lax" +LANGUAGE_COOKIE_AGE = 31449600 + +CSRF_COOKIE_HTTPONLY = True +CSRF_COOKIE_SAMESITE = "Strict" + +SESSION_EXPIRE_AT_BROWSER_CLOSE = True +SESSION_COOKIE_HTTPONLY = True +SESSION_COOKIE_SAMESITE = "Lax" if not DEBUG: - CSRF_COOKIE_HTTPONLY = True CSRF_COOKIE_SECURE = True - CSRF_COOKIE_SAMESITE = "Strict" - - SESSION_COOKIE_HTTPONLY = True SESSION_COOKIE_SECURE = True - # OIDC with foreign TLDs is blocked by SAMESITE=Strict, so make this configurable - if oidc_config and dict_get(oidc_config, False, "provider", "thirdparty_domain"): - SESSION_COOKIE_SAMESITE = "Lax" - else: - SESSION_COOKIE_SAMESITE = "Strict" - - LANGUAGE_COOKIE_HTTPONLY = True LANGUAGE_COOKIE_SECURE = True - LANGUAGE_COOKIE_SAMESITE = "Strict" # logging ADMINS = [(mail, mail) for mail in dict_get(config, [], "logging", "mails")] @@ -418,7 +455,6 @@ FEATURES_GIFTS = bool(dict_get(config, True, "features", "gifts")) FEATURES_PREREQUISITES = bool(dict_get(config, True, "features", "prerequisites")) FEATURES_INVENTORY = bool(dict_get(config, True, "features", "inventory")) -FEATURES_CORONA = bool(dict_get(config, True, "features", "corona")) # Display Options # Maximum years of events to be displayed by default on the main page @@ -430,6 +466,9 @@ # announcement on every page ANNOUNCEMENT_TEXT = dict_get(config, None, "announcement") +# title for all pages +PAGE_TITLE = dict_get(config, "Helfertool", "customization", "title") + # external URLs PRIVACY_URL = dict_get(config, "https://app.helfertool.org/datenschutz/", "customization", "urls", "privacy") IMPRINT_URL = dict_get(config, "https://app.helfertool.org/impressum/", "customization", "urls", "imprint") @@ -456,6 +495,7 @@ BADGE_PHOTO_MAX_SIZE = dict_get(config, 1000, "badges", "photo_max_size") BADGE_SPECIAL_MAX = dict_get(config, 50, "badges", "special_badges_max") +BADGE_BUILD_TIMEOUT = 60 * dict_get(config, 5, "badges", "build_timeout") BADGE_PDF_TIMEOUT = 60 * dict_get(config, 30, "badges", "pdf_timeout") BADGE_RM_DELAY = 60 * dict_get(config, 2, "badges", "rm_delay") @@ -472,7 +512,15 @@ BADGE_LANGUAGE_CODE = dict_get(config, "de", "language", "badges") # newsletter -NEWS_SUBSCRIBE_DEADLINE = dict_get(config, 3, "subscribe_deadline", "newsletter") +NEWS_SUBSCRIBE_DEADLINE = dict_get(config, 3, "newsletter", "subscribe_deadline") + +# automation +AUTOMATION_EVENTS_ARCHIVE_DEADLINE = dict_get(config, None, "automation", "event_archive", "deadline") # months +AUTOMATION_EVENTS_ARCHIVE_INTERVAL = dict_get(config, None, "automation", "event_archive", "interval") # days +AUTOMATION_EVENTS_ARCHIVE_START_BEFORE_DEADLINE = dict_get( + config, 0, "automation", "event_archive", "start_before_deadline" +) # days +AUTOMATION_EVENTS_ARCHIVE_DOCS = dict_get(config, None, "automation", "event_archive", "docs") # internal group names GROUP_ADDUSER = "registration_adduser" @@ -484,35 +532,6 @@ "required_css_class": "required-form", } -# HTML sanitization for text fields -BLEACH_ALLOWED_TAGS = ["p", "b", "i", "u", "em", "strong", "a", "br", "ul", "ol", "li"] -BLEACH_ALLOWED_ATTRIBUTES = [ - "href", -] -BLEACH_ALLOWED_STYLES = [] -BLEACH_STRIP_TAGS = True - -# editor for text fields -CKEDITOR_CONFIGS = { - "default": { - "toolbar": "Custom", - "toolbar_Custom": [ - ["Bold", "Italic", "Underline"], - [ - "NumberedList", - "BulletedList", - "-", - ], - ["Link", "Unlink"], - ["Source"], - ], - # we want to have a responsive ckeditor: - # 1. set width for editor itself here - # 2. set width also vor div.django-ckeditor-widget via custom CSS - "width": "100%", - } -} - # django-select2 config SELECT2_CACHE_BACKEND = "select2" @@ -526,6 +545,12 @@ }, } +# django-simple-captcha +CAPTCHA_FONT_SIZE = 30 +CAPTCHA_IMAGE_SIZE = (120, 50) +CAPTCHA_LETTER_ROTATION = (-30, 30) +CAPTCHA_FOREGROUND_COLOR = "#1ea082" + # application definition INSTALLED_APPS = ( "helfertool", # we override some default translations here, so put it first @@ -541,9 +566,10 @@ "django_bootstrap5", "django_icons", "django_select2", - "django_countries", - "ckeditor", + "django_prose_editor", + "captcha", "compressor", + "django_celery_results", "registration.apps.RegistrationConfig", "statistic.apps.StatisticConfig", "badges.apps.BadgesConfig", @@ -556,7 +582,7 @@ "toolsettings.apps.ToolsettingsConfig", "prerequisites.apps.PrerequisitesConfig", "toollog.apps.ToollogConfig", - "corona.apps.CoronaConfig", + "adminautomation.apps.AdminautomationConfig", ) # middleware diff --git a/src/helfertool/static/helfertool/img/logo/logo.svg b/src/helfertool/static/helfertool/img/logo/logo.svg deleted file mode 100644 index fe04c824a..000000000 --- a/src/helfertool/static/helfertool/img/logo/logo.svg +++ /dev/null @@ -1,154 +0,0 @@ - - - - - - - - - - Helfertool--.. - - - - - - - - - - - - - - - - - image/svg+xml - - - - - Openclipart - - - - - - - - - - - - diff --git a/src/helfertool/static/helfertool/js/captcha.js b/src/helfertool/static/helfertool/js/captcha.js new file mode 100644 index 000000000..f588794f4 --- /dev/null +++ b/src/helfertool/static/helfertool/js/captcha.js @@ -0,0 +1,6 @@ +$('.captcha').click(function () { + $.getJSON("/captcha/refresh/", function (result) { + $('.captcha').attr('src', result['image_url']); + $('#id_captcha_0').val(result['key']) + }); +}); diff --git a/src/helfertool/static/helfertool/theme/_announcement.scss b/src/helfertool/static/helfertool/theme/_announcement.scss index 491c194c9..f45aa9878 100644 --- a/src/helfertool/static/helfertool/theme/_announcement.scss +++ b/src/helfertool/static/helfertool/theme/_announcement.scss @@ -5,4 +5,6 @@ text-align: center; padding-top: 5px; + + border-bottom: 1px darken($body-bg, 20%) solid; } diff --git a/src/helfertool/static/helfertool/theme/_bootstrap.scss b/src/helfertool/static/helfertool/theme/_bootstrap.scss index c8280e8e7..a1432f9fc 100644 --- a/src/helfertool/static/helfertool/theme/_bootstrap.scss +++ b/src/helfertool/static/helfertool/theme/_bootstrap.scss @@ -10,9 +10,6 @@ $font-size-base: 0.95rem; // do not unterline links $link-decoration: none; -// navbar height -$navbar-height: 5rem; - // navbar text colors $navbar-dark-color: $primary-text; $navbar-dark-hover-color: rgba($primary-text, .75); @@ -22,9 +19,14 @@ $navbar-dark-disabled-color: rgba($primary-text, .25); $navbar-nav-link-padding-x: 0.7rem; // do not user darker colors for alert texts -$alert-bg-scale: -80%; -$alert-border-scale: -70%; -$alert-color-scale: -100%; +$primary-text-emphasis: $primary; +$secondary-text-emphasis: $secondary; +$success-text-emphasis: $success; +$info-text-emphasis: $info; +$warning-text-emphasis: $warning; +$danger-text-emphasis: $danger; +$light-text-emphasis: $success; +$dark-text-emphasis: $success; // now include bootstrap @import "bootstrap/scss/bootstrap"; diff --git a/src/helfertool/static/helfertool/theme/_ckeditor.scss b/src/helfertool/static/helfertool/theme/_ckeditor.scss deleted file mode 100644 index 265f4f143..000000000 --- a/src/helfertool/static/helfertool/theme/_ckeditor.scss +++ /dev/null @@ -1,19 +0,0 @@ -/* make ckeditor responsive (together with width in settins.py) */ -.django-ckeditor-widget { - width: 100%; -} - -/* ckeditor would hide the error message, so show it explicitly */ -.django-ckeditor-widget + .invalid-feedback { - display: block; -} - -/* highlight the invalid ckeditor by changing the border color */ -.is-invalid .django-ckeditor-widget .cke_chrome { - border-color: $danger; -} - -/* and also highlight valid ckeditors by changing the border color */ -.is-valid .django-ckeditor-widget .cke_chrome { - border-color: $success; -} diff --git a/src/helfertool/static/helfertool/theme/_colors.scss b/src/helfertool/static/helfertool/theme/_colors.scss index c679b74b7..ab479072a 100644 --- a/src/helfertool/static/helfertool/theme/_colors.scss +++ b/src/helfertool/static/helfertool/theme/_colors.scss @@ -6,8 +6,11 @@ $primary-text: #ffffff; // custom variable $body-bg: #ffffff; // bootstrap variable $body-color: #212529; // bootstrap variable (gray-900) -$danger: #d53e54; // bootstrap variable +$secondary: #6c757d; // bootstrap variable $success: #1a876e; // bootstrap variable +$info: $secondary; //bootstrap variable +$danger: #d53e54; // bootstrap variable +$warning: $danger; // bootstrap variable // contrast level: 3.0, 4.5 (bootstrap default), or 7.0 // with the bootstrap default, the buttons have a black text. white text is (imho) better readable diff --git a/src/helfertool/static/helfertool/theme/_layout.scss b/src/helfertool/static/helfertool/theme/_layout.scss index bb7e63b9e..546e8171c 100644 --- a/src/helfertool/static/helfertool/theme/_layout.scss +++ b/src/helfertool/static/helfertool/theme/_layout.scss @@ -60,6 +60,8 @@ html { padding-left: 1.5rem; padding-right: 1rem; + + overflow-wrap: break-word; } // header for different sections of sidemenu diff --git a/src/helfertool/static/helfertool/theme/apps/_statistics.scss b/src/helfertool/static/helfertool/theme/apps/_statistics.scss index 2ba701adb..d2d951fad 100644 --- a/src/helfertool/static/helfertool/theme/apps/_statistics.scss +++ b/src/helfertool/static/helfertool/theme/apps/_statistics.scss @@ -9,7 +9,7 @@ font-weight: bold; } - .placeholder { + .placeholdertext { text-align: center; color: $secondary; padding-top: 2em; diff --git a/src/helfertool/static/helfertool/theme/bootstrap/LICENSE b/src/helfertool/static/helfertool/theme/bootstrap/LICENSE new file mode 100644 index 000000000..fa7c00bc4 --- /dev/null +++ b/src/helfertool/static/helfertool/theme/bootstrap/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2011-2025 The Bootstrap Authors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/src/helfertool/static/helfertool/theme/bootstrap/dist/js/bootstrap.bundle.js b/src/helfertool/static/helfertool/theme/bootstrap/dist/js/bootstrap.bundle.js index 969ecb04b..93cbd3fee 100644 --- a/src/helfertool/static/helfertool/theme/bootstrap/dist/js/bootstrap.bundle.js +++ b/src/helfertool/static/helfertool/theme/bootstrap/dist/js/bootstrap.bundle.js @@ -1,254 +1,247 @@ /*! - * Bootstrap v5.1.0 (https://getbootstrap.com/) - * Copyright 2011-2021 The Bootstrap Authors (https://github.com/twbs/bootstrap/graphs/contributors) + * Bootstrap v5.3.8 (https://getbootstrap.com/) + * Copyright 2011-2025 The Bootstrap Authors (https://github.com/twbs/bootstrap/graphs/contributors) * Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE) */ (function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : typeof define === 'function' && define.amd ? define(factory) : (global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.bootstrap = factory()); -}(this, (function () { 'use strict'; +})(this, (function () { 'use strict'; /** * -------------------------------------------------------------------------- - * Bootstrap (v5.1.0): util/index.js + * Bootstrap dom/data.js * Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE) * -------------------------------------------------------------------------- */ - const MAX_UID = 1000000; - const MILLISECONDS_MULTIPLIER = 1000; - const TRANSITION_END = 'transitionend'; // Shoutout AngusCroll (https://goo.gl/pxwQGp) - - const toType = obj => { - if (obj === null || obj === undefined) { - return `${obj}`; - } - return {}.toString.call(obj).match(/\s([a-z]+)/i)[1].toLowerCase(); - }; /** - * -------------------------------------------------------------------------- - * Public Util Api - * -------------------------------------------------------------------------- + * Constants */ + const elementMap = new Map(); + const Data = { + set(element, key, instance) { + if (!elementMap.has(element)) { + elementMap.set(element, new Map()); + } + const instanceMap = elementMap.get(element); - const getUID = prefix => { - do { - prefix += Math.floor(Math.random() * MAX_UID); - } while (document.getElementById(prefix)); + // make it clear we only want one instance per element + // can be removed later when multiple key/instances are fine to be used + if (!instanceMap.has(key) && instanceMap.size !== 0) { + // eslint-disable-next-line no-console + console.error(`Bootstrap doesn't allow more than one instance per element. Bound instance: ${Array.from(instanceMap.keys())[0]}.`); + return; + } + instanceMap.set(key, instance); + }, + get(element, key) { + if (elementMap.has(element)) { + return elementMap.get(element).get(key) || null; + } + return null; + }, + remove(element, key) { + if (!elementMap.has(element)) { + return; + } + const instanceMap = elementMap.get(element); + instanceMap.delete(key); - return prefix; + // free up element references if there are no instances left for an element + if (instanceMap.size === 0) { + elementMap.delete(element); + } + } }; - const getSelector = element => { - let selector = element.getAttribute('data-bs-target'); - - if (!selector || selector === '#') { - let hrefAttr = element.getAttribute('href'); // The only valid content that could double as a selector are IDs or classes, - // so everything starting with `#` or `.`. If a "real" URL is used as the selector, - // `document.querySelector` will rightfully complain it is invalid. - // See https://github.com/twbs/bootstrap/issues/32273 - - if (!hrefAttr || !hrefAttr.includes('#') && !hrefAttr.startsWith('.')) { - return null; - } // Just in case some CMS puts out a full URL with the anchor appended - + /** + * -------------------------------------------------------------------------- + * Bootstrap util/index.js + * Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE) + * -------------------------------------------------------------------------- + */ - if (hrefAttr.includes('#') && !hrefAttr.startsWith('#')) { - hrefAttr = `#${hrefAttr.split('#')[1]}`; - } + const MAX_UID = 1000000; + const MILLISECONDS_MULTIPLIER = 1000; + const TRANSITION_END = 'transitionend'; - selector = hrefAttr && hrefAttr !== '#' ? hrefAttr.trim() : null; + /** + * Properly escape IDs selectors to handle weird IDs + * @param {string} selector + * @returns {string} + */ + const parseSelector = selector => { + if (selector && window.CSS && window.CSS.escape) { + // document.querySelector needs escaping to handle IDs (html5+) containing for instance / + selector = selector.replace(/#([^\s"#']+)/g, (match, id) => `#${CSS.escape(id)}`); } - return selector; }; - const getSelectorFromElement = element => { - const selector = getSelector(element); - - if (selector) { - return document.querySelector(selector) ? selector : null; + // Shout-out Angus Croll (https://goo.gl/pxwQGp) + const toType = object => { + if (object === null || object === undefined) { + return `${object}`; } - - return null; + return Object.prototype.toString.call(object).match(/\s([a-z]+)/i)[1].toLowerCase(); }; - const getElementFromSelector = element => { - const selector = getSelector(element); - return selector ? document.querySelector(selector) : null; - }; + /** + * Public Util API + */ + const getUID = prefix => { + do { + prefix += Math.floor(Math.random() * MAX_UID); + } while (document.getElementById(prefix)); + return prefix; + }; const getTransitionDurationFromElement = element => { if (!element) { return 0; - } // Get transition-duration of the element - + } + // Get transition-duration of the element let { transitionDuration, transitionDelay } = window.getComputedStyle(element); const floatTransitionDuration = Number.parseFloat(transitionDuration); - const floatTransitionDelay = Number.parseFloat(transitionDelay); // Return 0 if element or transition duration is not found + const floatTransitionDelay = Number.parseFloat(transitionDelay); + // Return 0 if element or transition duration is not found if (!floatTransitionDuration && !floatTransitionDelay) { return 0; - } // If multiple durations are defined, take the first - + } + // If multiple durations are defined, take the first transitionDuration = transitionDuration.split(',')[0]; transitionDelay = transitionDelay.split(',')[0]; return (Number.parseFloat(transitionDuration) + Number.parseFloat(transitionDelay)) * MILLISECONDS_MULTIPLIER; }; - const triggerTransitionEnd = element => { element.dispatchEvent(new Event(TRANSITION_END)); }; - - const isElement$1 = obj => { - if (!obj || typeof obj !== 'object') { + const isElement$1 = object => { + if (!object || typeof object !== 'object') { return false; } - - if (typeof obj.jquery !== 'undefined') { - obj = obj[0]; + if (typeof object.jquery !== 'undefined') { + object = object[0]; } - - return typeof obj.nodeType !== 'undefined'; + return typeof object.nodeType !== 'undefined'; }; - - const getElement = obj => { - if (isElement$1(obj)) { - // it's a jQuery object or a node element - return obj.jquery ? obj[0] : obj; + const getElement = object => { + // it's a jQuery object or a node element + if (isElement$1(object)) { + return object.jquery ? object[0] : object; } - - if (typeof obj === 'string' && obj.length > 0) { - return document.querySelector(obj); + if (typeof object === 'string' && object.length > 0) { + return document.querySelector(parseSelector(object)); } - return null; }; - - const typeCheckConfig = (componentName, config, configTypes) => { - Object.keys(configTypes).forEach(property => { - const expectedTypes = configTypes[property]; - const value = config[property]; - const valueType = value && isElement$1(value) ? 'element' : toType(value); - - if (!new RegExp(expectedTypes).test(valueType)) { - throw new TypeError(`${componentName.toUpperCase()}: Option "${property}" provided type "${valueType}" but expected type "${expectedTypes}".`); - } - }); - }; - const isVisible = element => { if (!isElement$1(element) || element.getClientRects().length === 0) { return false; } - - return getComputedStyle(element).getPropertyValue('visibility') === 'visible'; + const elementIsVisible = getComputedStyle(element).getPropertyValue('visibility') === 'visible'; + // Handle `details` element as its content may falsie appear visible when it is closed + const closedDetails = element.closest('details:not([open])'); + if (!closedDetails) { + return elementIsVisible; + } + if (closedDetails !== element) { + const summary = element.closest('summary'); + if (summary && summary.parentNode !== closedDetails) { + return false; + } + if (summary === null) { + return false; + } + } + return elementIsVisible; }; - const isDisabled = element => { if (!element || element.nodeType !== Node.ELEMENT_NODE) { return true; } - if (element.classList.contains('disabled')) { return true; } - if (typeof element.disabled !== 'undefined') { return element.disabled; } - return element.hasAttribute('disabled') && element.getAttribute('disabled') !== 'false'; }; - const findShadowRoot = element => { if (!document.documentElement.attachShadow) { return null; - } // Can find the shadow root otherwise it'll return the document - + } + // Can find the shadow root otherwise it'll return the document if (typeof element.getRootNode === 'function') { const root = element.getRootNode(); return root instanceof ShadowRoot ? root : null; } - if (element instanceof ShadowRoot) { return element; - } // when we don't find a shadow root - + } + // when we don't find a shadow root if (!element.parentNode) { return null; } - return findShadowRoot(element.parentNode); }; - const noop = () => {}; + /** * Trick to restart an element's animation * * @param {HTMLElement} element * @return void * - * @see https://www.charistheo.io/blog/2021/02/restart-a-css-animation-with-javascript/#restarting-a-css-animation + * @see https://www.harrytheo.com/blog/2021/02/restart-a-css-animation-with-javascript/#restarting-a-css-animation */ - - const reflow = element => { - // eslint-disable-next-line no-unused-expressions - element.offsetHeight; + element.offsetHeight; // eslint-disable-line no-unused-expressions }; - const getjQuery = () => { - const { - jQuery - } = window; - - if (jQuery && !document.body.hasAttribute('data-bs-no-jquery')) { - return jQuery; + if (window.jQuery && !document.body.hasAttribute('data-bs-no-jquery')) { + return window.jQuery; } - return null; }; - const DOMContentLoadedCallbacks = []; - const onDOMContentLoaded = callback => { if (document.readyState === 'loading') { // add listener on the first call when the document is in loading state if (!DOMContentLoadedCallbacks.length) { document.addEventListener('DOMContentLoaded', () => { - DOMContentLoadedCallbacks.forEach(callback => callback()); + for (const callback of DOMContentLoadedCallbacks) { + callback(); + } }); } - DOMContentLoadedCallbacks.push(callback); } else { callback(); } }; - const isRTL = () => document.documentElement.dir === 'rtl'; - const defineJQueryPlugin = plugin => { onDOMContentLoaded(() => { const $ = getjQuery(); /* istanbul ignore if */ - if ($) { const name = plugin.NAME; const JQUERY_NO_CONFLICT = $.fn[name]; $.fn[name] = plugin.jQueryInterface; $.fn[name].Constructor = plugin; - $.fn[name].noConflict = () => { $.fn[name] = JQUERY_NO_CONFLICT; return plugin.jQueryInterface; @@ -256,35 +249,27 @@ } }); }; - - const execute = callback => { - if (typeof callback === 'function') { - callback(); - } + const execute = (possibleCallback, args = [], defaultValue = possibleCallback) => { + return typeof possibleCallback === 'function' ? possibleCallback.call(...args) : defaultValue; }; - const executeAfterTransition = (callback, transitionElement, waitForTransition = true) => { if (!waitForTransition) { execute(callback); return; } - const durationPadding = 5; const emulatedDuration = getTransitionDurationFromElement(transitionElement) + durationPadding; let called = false; - const handler = ({ target }) => { if (target !== transitionElement) { return; } - called = true; transitionElement.removeEventListener(TRANSITION_END, handler); execute(callback); }; - transitionElement.addEventListener(TRANSITION_END, handler); setTimeout(() => { if (!called) { @@ -292,6 +277,7 @@ } }, emulatedDuration); }; + /** * Return the previous/next element of a list. * @@ -301,267 +287,205 @@ * @param isCycleAllowed * @return {Element|elem} The proper element */ - - const getNextActiveElement = (list, activeElement, shouldGetNext, isCycleAllowed) => { - let index = list.indexOf(activeElement); // if the element does not exist in the list return an element depending on the direction and if cycle is allowed + const listLength = list.length; + let index = list.indexOf(activeElement); + // if the element does not exist in the list return an element + // depending on the direction and if cycle is allowed if (index === -1) { - return list[!shouldGetNext && isCycleAllowed ? list.length - 1 : 0]; + return !shouldGetNext && isCycleAllowed ? list[listLength - 1] : list[0]; } - - const listLength = list.length; index += shouldGetNext ? 1 : -1; - if (isCycleAllowed) { index = (index + listLength) % listLength; } - return list[Math.max(0, Math.min(index, listLength - 1))]; }; /** * -------------------------------------------------------------------------- - * Bootstrap (v5.1.0): dom/event-handler.js + * Bootstrap dom/event-handler.js * Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE) * -------------------------------------------------------------------------- */ + + /** - * ------------------------------------------------------------------------ * Constants - * ------------------------------------------------------------------------ */ const namespaceRegex = /[^.]*(?=\..*)\.|.*/; const stripNameRegex = /\..*/; const stripUidRegex = /::\d+$/; const eventRegistry = {}; // Events storage - let uidEvent = 1; const customEvents = { mouseenter: 'mouseover', mouseleave: 'mouseout' }; - const customEventsRegex = /^(mouseenter|mouseleave)/i; const nativeEvents = new Set(['click', 'dblclick', 'mouseup', 'mousedown', 'contextmenu', 'mousewheel', 'DOMMouseScroll', 'mouseover', 'mouseout', 'mousemove', 'selectstart', 'selectend', 'keydown', 'keypress', 'keyup', 'orientationchange', 'touchstart', 'touchmove', 'touchend', 'touchcancel', 'pointerdown', 'pointermove', 'pointerup', 'pointerleave', 'pointercancel', 'gesturestart', 'gesturechange', 'gestureend', 'focus', 'blur', 'change', 'reset', 'select', 'submit', 'focusin', 'focusout', 'load', 'unload', 'beforeunload', 'resize', 'move', 'DOMContentLoaded', 'readystatechange', 'error', 'abort', 'scroll']); + /** - * ------------------------------------------------------------------------ * Private methods - * ------------------------------------------------------------------------ */ - function getUidEvent(element, uid) { + function makeEventUid(element, uid) { return uid && `${uid}::${uidEvent++}` || element.uidEvent || uidEvent++; } - - function getEvent(element) { - const uid = getUidEvent(element); + function getElementEvents(element) { + const uid = makeEventUid(element); element.uidEvent = uid; eventRegistry[uid] = eventRegistry[uid] || {}; return eventRegistry[uid]; } - function bootstrapHandler(element, fn) { return function handler(event) { - event.delegateTarget = element; - + hydrateObj(event, { + delegateTarget: element + }); if (handler.oneOff) { EventHandler.off(element, event.type, fn); } - return fn.apply(element, [event]); }; } - function bootstrapDelegationHandler(element, selector, fn) { return function handler(event) { const domElements = element.querySelectorAll(selector); - for (let { target } = event; target && target !== this; target = target.parentNode) { - for (let i = domElements.length; i--;) { - if (domElements[i] === target) { - event.delegateTarget = target; - - if (handler.oneOff) { - // eslint-disable-next-line unicorn/consistent-destructuring - EventHandler.off(element, event.type, selector, fn); - } - - return fn.apply(target, [event]); + for (const domElement of domElements) { + if (domElement !== target) { + continue; + } + hydrateObj(event, { + delegateTarget: target + }); + if (handler.oneOff) { + EventHandler.off(element, event.type, selector, fn); } + return fn.apply(target, [event]); } - } // To please ESLint - - - return null; + } }; } - - function findHandler(events, handler, delegationSelector = null) { - const uidEventList = Object.keys(events); - - for (let i = 0, len = uidEventList.length; i < len; i++) { - const event = events[uidEventList[i]]; - - if (event.originalHandler === handler && event.delegationSelector === delegationSelector) { - return event; - } - } - - return null; + function findHandler(events, callable, delegationSelector = null) { + return Object.values(events).find(event => event.callable === callable && event.delegationSelector === delegationSelector); } - - function normalizeParams(originalTypeEvent, handler, delegationFn) { - const delegation = typeof handler === 'string'; - const originalHandler = delegation ? delegationFn : handler; + function normalizeParameters(originalTypeEvent, handler, delegationFunction) { + const isDelegated = typeof handler === 'string'; + // TODO: tooltip passes `false` instead of selector, so we need to check + const callable = isDelegated ? delegationFunction : handler || delegationFunction; let typeEvent = getTypeEvent(originalTypeEvent); - const isNative = nativeEvents.has(typeEvent); - - if (!isNative) { + if (!nativeEvents.has(typeEvent)) { typeEvent = originalTypeEvent; } - - return [delegation, originalHandler, typeEvent]; + return [isDelegated, callable, typeEvent]; } - - function addHandler(element, originalTypeEvent, handler, delegationFn, oneOff) { + function addHandler(element, originalTypeEvent, handler, delegationFunction, oneOff) { if (typeof originalTypeEvent !== 'string' || !element) { return; } + let [isDelegated, callable, typeEvent] = normalizeParameters(originalTypeEvent, handler, delegationFunction); - if (!handler) { - handler = delegationFn; - delegationFn = null; - } // in case of mouseenter or mouseleave wrap the handler within a function that checks for its DOM position + // in case of mouseenter or mouseleave wrap the handler within a function that checks for its DOM position // this prevents the handler from being dispatched the same way as mouseover or mouseout does - - - if (customEventsRegex.test(originalTypeEvent)) { - const wrapFn = fn => { + if (originalTypeEvent in customEvents) { + const wrapFunction = fn => { return function (event) { if (!event.relatedTarget || event.relatedTarget !== event.delegateTarget && !event.delegateTarget.contains(event.relatedTarget)) { return fn.call(this, event); } }; }; - - if (delegationFn) { - delegationFn = wrapFn(delegationFn); - } else { - handler = wrapFn(handler); - } + callable = wrapFunction(callable); } - - const [delegation, originalHandler, typeEvent] = normalizeParams(originalTypeEvent, handler, delegationFn); - const events = getEvent(element); + const events = getElementEvents(element); const handlers = events[typeEvent] || (events[typeEvent] = {}); - const previousFn = findHandler(handlers, originalHandler, delegation ? handler : null); - - if (previousFn) { - previousFn.oneOff = previousFn.oneOff && oneOff; + const previousFunction = findHandler(handlers, callable, isDelegated ? handler : null); + if (previousFunction) { + previousFunction.oneOff = previousFunction.oneOff && oneOff; return; } - - const uid = getUidEvent(originalHandler, originalTypeEvent.replace(namespaceRegex, '')); - const fn = delegation ? bootstrapDelegationHandler(element, handler, delegationFn) : bootstrapHandler(element, handler); - fn.delegationSelector = delegation ? handler : null; - fn.originalHandler = originalHandler; + const uid = makeEventUid(callable, originalTypeEvent.replace(namespaceRegex, '')); + const fn = isDelegated ? bootstrapDelegationHandler(element, handler, callable) : bootstrapHandler(element, callable); + fn.delegationSelector = isDelegated ? handler : null; + fn.callable = callable; fn.oneOff = oneOff; fn.uidEvent = uid; handlers[uid] = fn; - element.addEventListener(typeEvent, fn, delegation); + element.addEventListener(typeEvent, fn, isDelegated); } - function removeHandler(element, events, typeEvent, handler, delegationSelector) { const fn = findHandler(events[typeEvent], handler, delegationSelector); - if (!fn) { return; } - element.removeEventListener(typeEvent, fn, Boolean(delegationSelector)); delete events[typeEvent][fn.uidEvent]; } - function removeNamespacedHandlers(element, events, typeEvent, namespace) { const storeElementEvent = events[typeEvent] || {}; - Object.keys(storeElementEvent).forEach(handlerKey => { + for (const [handlerKey, event] of Object.entries(storeElementEvent)) { if (handlerKey.includes(namespace)) { - const event = storeElementEvent[handlerKey]; - removeHandler(element, events, typeEvent, event.originalHandler, event.delegationSelector); + removeHandler(element, events, typeEvent, event.callable, event.delegationSelector); } - }); + } } - function getTypeEvent(event) { // allow to get the native events from namespaced events ('click.bs.button' --> 'click') event = event.replace(stripNameRegex, ''); return customEvents[event] || event; } - const EventHandler = { - on(element, event, handler, delegationFn) { - addHandler(element, event, handler, delegationFn, false); + on(element, event, handler, delegationFunction) { + addHandler(element, event, handler, delegationFunction, false); }, - - one(element, event, handler, delegationFn) { - addHandler(element, event, handler, delegationFn, true); + one(element, event, handler, delegationFunction) { + addHandler(element, event, handler, delegationFunction, true); }, - - off(element, originalTypeEvent, handler, delegationFn) { + off(element, originalTypeEvent, handler, delegationFunction) { if (typeof originalTypeEvent !== 'string' || !element) { return; } - - const [delegation, originalHandler, typeEvent] = normalizeParams(originalTypeEvent, handler, delegationFn); + const [isDelegated, callable, typeEvent] = normalizeParameters(originalTypeEvent, handler, delegationFunction); const inNamespace = typeEvent !== originalTypeEvent; - const events = getEvent(element); + const events = getElementEvents(element); + const storeElementEvent = events[typeEvent] || {}; const isNamespace = originalTypeEvent.startsWith('.'); - - if (typeof originalHandler !== 'undefined') { + if (typeof callable !== 'undefined') { // Simplest case: handler is passed, remove that listener ONLY. - if (!events || !events[typeEvent]) { + if (!Object.keys(storeElementEvent).length) { return; } - - removeHandler(element, events, typeEvent, originalHandler, delegation ? handler : null); + removeHandler(element, events, typeEvent, callable, isDelegated ? handler : null); return; } - if (isNamespace) { - Object.keys(events).forEach(elementEvent => { + for (const elementEvent of Object.keys(events)) { removeNamespacedHandlers(element, events, elementEvent, originalTypeEvent.slice(1)); - }); + } } - - const storeElementEvent = events[typeEvent] || {}; - Object.keys(storeElementEvent).forEach(keyHandlers => { + for (const [keyHandlers, event] of Object.entries(storeElementEvent)) { const handlerKey = keyHandlers.replace(stripUidRegex, ''); - if (!inNamespace || originalTypeEvent.includes(handlerKey)) { - const event = storeElementEvent[keyHandlers]; - removeHandler(element, events, typeEvent, event.originalHandler, event.delegationSelector); + removeHandler(element, events, typeEvent, event.callable, event.delegationSelector); } - }); + } }, - trigger(element, event, args) { if (typeof event !== 'string' || !element) { return null; } - const $ = getjQuery(); const typeEvent = getTypeEvent(event); const inNamespace = event !== typeEvent; - const isNative = nativeEvents.has(typeEvent); - let jQueryEvent; + let jQueryEvent = null; let bubbles = true; let nativeDispatch = true; let defaultPrevented = false; - let evt = null; - if (inNamespace && $) { jQueryEvent = $.Event(event, args); $(element).trigger(jQueryEvent); @@ -569,169 +493,311 @@ nativeDispatch = !jQueryEvent.isImmediatePropagationStopped(); defaultPrevented = jQueryEvent.isDefaultPrevented(); } - - if (isNative) { - evt = document.createEvent('HTMLEvents'); - evt.initEvent(typeEvent, bubbles, true); - } else { - evt = new CustomEvent(event, { - bubbles, - cancelable: true - }); - } // merge custom information in our event - - - if (typeof args !== 'undefined') { - Object.keys(args).forEach(key => { - Object.defineProperty(evt, key, { - get() { - return args[key]; - } - - }); - }); - } - + const evt = hydrateObj(new Event(event, { + bubbles, + cancelable: true + }), args); if (defaultPrevented) { evt.preventDefault(); } - if (nativeDispatch) { element.dispatchEvent(evt); } - - if (evt.defaultPrevented && typeof jQueryEvent !== 'undefined') { + if (evt.defaultPrevented && jQueryEvent) { jQueryEvent.preventDefault(); } - return evt; } - }; + function hydrateObj(obj, meta = {}) { + for (const [key, value] of Object.entries(meta)) { + try { + obj[key] = value; + } catch (_unused) { + Object.defineProperty(obj, key, { + configurable: true, + get() { + return value; + } + }); + } + } + return obj; + } /** * -------------------------------------------------------------------------- - * Bootstrap (v5.1.0): dom/data.js + * Bootstrap dom/manipulator.js * Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE) * -------------------------------------------------------------------------- */ - /** - * ------------------------------------------------------------------------ - * Constants - * ------------------------------------------------------------------------ - */ - const elementMap = new Map(); - var Data = { - set(element, key, instance) { - if (!elementMap.has(element)) { - elementMap.set(element, new Map()); - } - - const instanceMap = elementMap.get(element); // make it clear we only want one instance per element - // can be removed later when multiple key/instances are fine to be used - - if (!instanceMap.has(key) && instanceMap.size !== 0) { - // eslint-disable-next-line no-console - console.error(`Bootstrap doesn't allow more than one instance per element. Bound instance: ${Array.from(instanceMap.keys())[0]}.`); - return; - } - - instanceMap.set(key, instance); - }, - - get(element, key) { - if (elementMap.has(element)) { - return elementMap.get(element).get(key) || null; - } - + function normalizeData(value) { + if (value === 'true') { + return true; + } + if (value === 'false') { + return false; + } + if (value === Number(value).toString()) { + return Number(value); + } + if (value === '' || value === 'null') { return null; - }, - - remove(element, key) { - if (!elementMap.has(element)) { - return; + } + if (typeof value !== 'string') { + return value; + } + try { + return JSON.parse(decodeURIComponent(value)); + } catch (_unused) { + return value; + } + } + function normalizeDataKey(key) { + return key.replace(/[A-Z]/g, chr => `-${chr.toLowerCase()}`); + } + const Manipulator = { + setDataAttribute(element, key, value) { + element.setAttribute(`data-bs-${normalizeDataKey(key)}`, value); + }, + removeDataAttribute(element, key) { + element.removeAttribute(`data-bs-${normalizeDataKey(key)}`); + }, + getDataAttributes(element) { + if (!element) { + return {}; + } + const attributes = {}; + const bsKeys = Object.keys(element.dataset).filter(key => key.startsWith('bs') && !key.startsWith('bsConfig')); + for (const key of bsKeys) { + let pureKey = key.replace(/^bs/, ''); + pureKey = pureKey.charAt(0).toLowerCase() + pureKey.slice(1); + attributes[pureKey] = normalizeData(element.dataset[key]); } + return attributes; + }, + getDataAttribute(element, key) { + return normalizeData(element.getAttribute(`data-bs-${normalizeDataKey(key)}`)); + } + }; - const instanceMap = elementMap.get(element); - instanceMap.delete(key); // free up element references if there are no instances left for an element + /** + * -------------------------------------------------------------------------- + * Bootstrap util/config.js + * Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE) + * -------------------------------------------------------------------------- + */ - if (instanceMap.size === 0) { - elementMap.delete(element); - } + + /** + * Class definition + */ + + class Config { + // Getters + static get Default() { + return {}; + } + static get DefaultType() { + return {}; + } + static get NAME() { + throw new Error('You have to implement the static method "NAME", for each component!'); + } + _getConfig(config) { + config = this._mergeConfigObj(config); + config = this._configAfterMerge(config); + this._typeCheckConfig(config); + return config; + } + _configAfterMerge(config) { + return config; } + _mergeConfigObj(config, element) { + const jsonConfig = isElement$1(element) ? Manipulator.getDataAttribute(element, 'config') : {}; // try to parse - }; + return { + ...this.constructor.Default, + ...(typeof jsonConfig === 'object' ? jsonConfig : {}), + ...(isElement$1(element) ? Manipulator.getDataAttributes(element) : {}), + ...(typeof config === 'object' ? config : {}) + }; + } + _typeCheckConfig(config, configTypes = this.constructor.DefaultType) { + for (const [property, expectedTypes] of Object.entries(configTypes)) { + const value = config[property]; + const valueType = isElement$1(value) ? 'element' : toType(value); + if (!new RegExp(expectedTypes).test(valueType)) { + throw new TypeError(`${this.constructor.NAME.toUpperCase()}: Option "${property}" provided type "${valueType}" but expected type "${expectedTypes}".`); + } + } + } + } /** * -------------------------------------------------------------------------- - * Bootstrap (v5.1.0): base-component.js + * Bootstrap base-component.js * Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE) * -------------------------------------------------------------------------- */ + + /** - * ------------------------------------------------------------------------ * Constants - * ------------------------------------------------------------------------ */ - const VERSION = '5.1.0'; + const VERSION = '5.3.8'; - class BaseComponent { - constructor(element) { - element = getElement(element); + /** + * Class definition + */ + class BaseComponent extends Config { + constructor(element, config) { + super(); + element = getElement(element); if (!element) { return; } - this._element = element; + this._config = this._getConfig(config); Data.set(this._element, this.constructor.DATA_KEY, this); } + // Public dispose() { Data.remove(this._element, this.constructor.DATA_KEY); EventHandler.off(this._element, this.constructor.EVENT_KEY); - Object.getOwnPropertyNames(this).forEach(propertyName => { + for (const propertyName of Object.getOwnPropertyNames(this)) { this[propertyName] = null; - }); + } } + // Private _queueCallback(callback, element, isAnimated = true) { executeAfterTransition(callback, element, isAnimated); } - /** Static */ - + _getConfig(config) { + config = this._mergeConfigObj(config, this._element); + config = this._configAfterMerge(config); + this._typeCheckConfig(config); + return config; + } + // Static static getInstance(element) { return Data.get(getElement(element), this.DATA_KEY); } - static getOrCreateInstance(element, config = {}) { return this.getInstance(element) || new this(element, typeof config === 'object' ? config : null); } - static get VERSION() { return VERSION; } - - static get NAME() { - throw new Error('You have to implement the static method "NAME", for each component!'); - } - static get DATA_KEY() { return `bs.${this.NAME}`; } - static get EVENT_KEY() { return `.${this.DATA_KEY}`; } - + static eventName(name) { + return `${name}${this.EVENT_KEY}`; + } } /** * -------------------------------------------------------------------------- - * Bootstrap (v5.1.0): util/component-functions.js + * Bootstrap dom/selector-engine.js + * Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE) + * -------------------------------------------------------------------------- + */ + + const getSelector = element => { + let selector = element.getAttribute('data-bs-target'); + if (!selector || selector === '#') { + let hrefAttribute = element.getAttribute('href'); + + // The only valid content that could double as a selector are IDs or classes, + // so everything starting with `#` or `.`. If a "real" URL is used as the selector, + // `document.querySelector` will rightfully complain it is invalid. + // See https://github.com/twbs/bootstrap/issues/32273 + if (!hrefAttribute || !hrefAttribute.includes('#') && !hrefAttribute.startsWith('.')) { + return null; + } + + // Just in case some CMS puts out a full URL with the anchor appended + if (hrefAttribute.includes('#') && !hrefAttribute.startsWith('#')) { + hrefAttribute = `#${hrefAttribute.split('#')[1]}`; + } + selector = hrefAttribute && hrefAttribute !== '#' ? hrefAttribute.trim() : null; + } + return selector ? selector.split(',').map(sel => parseSelector(sel)).join(',') : null; + }; + const SelectorEngine = { + find(selector, element = document.documentElement) { + return [].concat(...Element.prototype.querySelectorAll.call(element, selector)); + }, + findOne(selector, element = document.documentElement) { + return Element.prototype.querySelector.call(element, selector); + }, + children(element, selector) { + return [].concat(...element.children).filter(child => child.matches(selector)); + }, + parents(element, selector) { + const parents = []; + let ancestor = element.parentNode.closest(selector); + while (ancestor) { + parents.push(ancestor); + ancestor = ancestor.parentNode.closest(selector); + } + return parents; + }, + prev(element, selector) { + let previous = element.previousElementSibling; + while (previous) { + if (previous.matches(selector)) { + return [previous]; + } + previous = previous.previousElementSibling; + } + return []; + }, + // TODO: this is now unused; remove later along with prev() + next(element, selector) { + let next = element.nextElementSibling; + while (next) { + if (next.matches(selector)) { + return [next]; + } + next = next.nextElementSibling; + } + return []; + }, + focusableChildren(element) { + const focusables = ['a', 'button', 'input', 'textarea', 'select', 'details', '[tabindex]', '[contenteditable="true"]'].map(selector => `${selector}:not([tabindex^="-"])`).join(','); + return this.find(focusables, element).filter(el => !isDisabled(el) && isVisible(el)); + }, + getSelectorFromElement(element) { + const selector = getSelector(element); + if (selector) { + return SelectorEngine.findOne(selector) ? selector : null; + } + return null; + }, + getElementFromSelector(element) { + const selector = getSelector(element); + return selector ? SelectorEngine.findOne(selector) : null; + }, + getMultipleElementsFromSelector(element) { + const selector = getSelector(element); + return selector ? SelectorEngine.find(selector) : []; + } + }; + + /** + * -------------------------------------------------------------------------- + * Bootstrap util/component-functions.js * Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE) * -------------------------------------------------------------------------- */ @@ -743,380 +809,308 @@ if (['A', 'AREA'].includes(this.tagName)) { event.preventDefault(); } - if (isDisabled(this)) { return; } + const target = SelectorEngine.getElementFromSelector(this) || this.closest(`.${name}`); + const instance = component.getOrCreateInstance(target); - const target = getElementFromSelector(this) || this.closest(`.${name}`); - const instance = component.getOrCreateInstance(target); // Method argument is left, for Alert and only, as it doesn't implement the 'hide' method - + // Method argument is left, for Alert and only, as it doesn't implement the 'hide' method instance[method](); }); }; /** * -------------------------------------------------------------------------- - * Bootstrap (v5.1.0): alert.js + * Bootstrap alert.js * Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE) * -------------------------------------------------------------------------- */ + + /** - * ------------------------------------------------------------------------ * Constants - * ------------------------------------------------------------------------ */ - const NAME$d = 'alert'; - const DATA_KEY$c = 'bs.alert'; - const EVENT_KEY$c = `.${DATA_KEY$c}`; - const EVENT_CLOSE = `close${EVENT_KEY$c}`; - const EVENT_CLOSED = `closed${EVENT_KEY$c}`; + const NAME$f = 'alert'; + const DATA_KEY$a = 'bs.alert'; + const EVENT_KEY$b = `.${DATA_KEY$a}`; + const EVENT_CLOSE = `close${EVENT_KEY$b}`; + const EVENT_CLOSED = `closed${EVENT_KEY$b}`; const CLASS_NAME_FADE$5 = 'fade'; const CLASS_NAME_SHOW$8 = 'show'; + /** - * ------------------------------------------------------------------------ - * Class Definition - * ------------------------------------------------------------------------ + * Class definition */ class Alert extends BaseComponent { // Getters static get NAME() { - return NAME$d; - } // Public - + return NAME$f; + } + // Public close() { const closeEvent = EventHandler.trigger(this._element, EVENT_CLOSE); - if (closeEvent.defaultPrevented) { return; } - this._element.classList.remove(CLASS_NAME_SHOW$8); - const isAnimated = this._element.classList.contains(CLASS_NAME_FADE$5); - this._queueCallback(() => this._destroyElement(), this._element, isAnimated); - } // Private - + } + // Private _destroyElement() { this._element.remove(); - EventHandler.trigger(this._element, EVENT_CLOSED); this.dispose(); - } // Static - + } + // Static static jQueryInterface(config) { return this.each(function () { const data = Alert.getOrCreateInstance(this); - if (typeof config !== 'string') { return; } - if (data[config] === undefined || config.startsWith('_') || config === 'constructor') { throw new TypeError(`No method named "${config}"`); } - data[config](this); }); } - } + /** - * ------------------------------------------------------------------------ - * Data Api implementation - * ------------------------------------------------------------------------ + * Data API implementation */ - enableDismissTrigger(Alert, 'close'); + /** - * ------------------------------------------------------------------------ * jQuery - * ------------------------------------------------------------------------ - * add .Alert to jQuery only if jQuery is present */ defineJQueryPlugin(Alert); /** * -------------------------------------------------------------------------- - * Bootstrap (v5.1.0): button.js + * Bootstrap button.js * Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE) * -------------------------------------------------------------------------- */ + + /** - * ------------------------------------------------------------------------ * Constants - * ------------------------------------------------------------------------ */ - const NAME$c = 'button'; - const DATA_KEY$b = 'bs.button'; - const EVENT_KEY$b = `.${DATA_KEY$b}`; - const DATA_API_KEY$7 = '.data-api'; + const NAME$e = 'button'; + const DATA_KEY$9 = 'bs.button'; + const EVENT_KEY$a = `.${DATA_KEY$9}`; + const DATA_API_KEY$6 = '.data-api'; const CLASS_NAME_ACTIVE$3 = 'active'; const SELECTOR_DATA_TOGGLE$5 = '[data-bs-toggle="button"]'; - const EVENT_CLICK_DATA_API$6 = `click${EVENT_KEY$b}${DATA_API_KEY$7}`; + const EVENT_CLICK_DATA_API$6 = `click${EVENT_KEY$a}${DATA_API_KEY$6}`; + /** - * ------------------------------------------------------------------------ - * Class Definition - * ------------------------------------------------------------------------ + * Class definition */ class Button extends BaseComponent { // Getters static get NAME() { - return NAME$c; - } // Public - + return NAME$e; + } + // Public toggle() { // Toggle class and sync the `aria-pressed` attribute with the return value of the `.toggle()` method this._element.setAttribute('aria-pressed', this._element.classList.toggle(CLASS_NAME_ACTIVE$3)); - } // Static - + } + // Static static jQueryInterface(config) { return this.each(function () { const data = Button.getOrCreateInstance(this); - if (config === 'toggle') { data[config](); } }); } - } + /** - * ------------------------------------------------------------------------ - * Data Api implementation - * ------------------------------------------------------------------------ + * Data API implementation */ - EventHandler.on(document, EVENT_CLICK_DATA_API$6, SELECTOR_DATA_TOGGLE$5, event => { event.preventDefault(); const button = event.target.closest(SELECTOR_DATA_TOGGLE$5); const data = Button.getOrCreateInstance(button); data.toggle(); }); + /** - * ------------------------------------------------------------------------ * jQuery - * ------------------------------------------------------------------------ - * add .Button to jQuery only if jQuery is present */ defineJQueryPlugin(Button); /** * -------------------------------------------------------------------------- - * Bootstrap (v5.1.0): dom/manipulator.js + * Bootstrap util/swipe.js * Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE) * -------------------------------------------------------------------------- */ - function normalizeData(val) { - if (val === 'true') { - return true; + + + /** + * Constants + */ + + const NAME$d = 'swipe'; + const EVENT_KEY$9 = '.bs.swipe'; + const EVENT_TOUCHSTART = `touchstart${EVENT_KEY$9}`; + const EVENT_TOUCHMOVE = `touchmove${EVENT_KEY$9}`; + const EVENT_TOUCHEND = `touchend${EVENT_KEY$9}`; + const EVENT_POINTERDOWN = `pointerdown${EVENT_KEY$9}`; + const EVENT_POINTERUP = `pointerup${EVENT_KEY$9}`; + const POINTER_TYPE_TOUCH = 'touch'; + const POINTER_TYPE_PEN = 'pen'; + const CLASS_NAME_POINTER_EVENT = 'pointer-event'; + const SWIPE_THRESHOLD = 40; + const Default$c = { + endCallback: null, + leftCallback: null, + rightCallback: null + }; + const DefaultType$c = { + endCallback: '(function|null)', + leftCallback: '(function|null)', + rightCallback: '(function|null)' + }; + + /** + * Class definition + */ + + class Swipe extends Config { + constructor(element, config) { + super(); + this._element = element; + if (!element || !Swipe.isSupported()) { + return; + } + this._config = this._getConfig(config); + this._deltaX = 0; + this._supportPointerEvents = Boolean(window.PointerEvent); + this._initEvents(); } - if (val === 'false') { - return false; + // Getters + static get Default() { + return Default$c; + } + static get DefaultType() { + return DefaultType$c; + } + static get NAME() { + return NAME$d; } - if (val === Number(val).toString()) { - return Number(val); + // Public + dispose() { + EventHandler.off(this._element, EVENT_KEY$9); } - if (val === '' || val === 'null') { - return null; + // Private + _start(event) { + if (!this._supportPointerEvents) { + this._deltaX = event.touches[0].clientX; + return; + } + if (this._eventIsPointerPenTouch(event)) { + this._deltaX = event.clientX; + } + } + _end(event) { + if (this._eventIsPointerPenTouch(event)) { + this._deltaX = event.clientX - this._deltaX; + } + this._handleSwipe(); + execute(this._config.endCallback); + } + _move(event) { + this._deltaX = event.touches && event.touches.length > 1 ? 0 : event.touches[0].clientX - this._deltaX; + } + _handleSwipe() { + const absDeltaX = Math.abs(this._deltaX); + if (absDeltaX <= SWIPE_THRESHOLD) { + return; + } + const direction = absDeltaX / this._deltaX; + this._deltaX = 0; + if (!direction) { + return; + } + execute(direction > 0 ? this._config.rightCallback : this._config.leftCallback); + } + _initEvents() { + if (this._supportPointerEvents) { + EventHandler.on(this._element, EVENT_POINTERDOWN, event => this._start(event)); + EventHandler.on(this._element, EVENT_POINTERUP, event => this._end(event)); + this._element.classList.add(CLASS_NAME_POINTER_EVENT); + } else { + EventHandler.on(this._element, EVENT_TOUCHSTART, event => this._start(event)); + EventHandler.on(this._element, EVENT_TOUCHMOVE, event => this._move(event)); + EventHandler.on(this._element, EVENT_TOUCHEND, event => this._end(event)); + } + } + _eventIsPointerPenTouch(event) { + return this._supportPointerEvents && (event.pointerType === POINTER_TYPE_PEN || event.pointerType === POINTER_TYPE_TOUCH); } - return val; + // Static + static isSupported() { + return 'ontouchstart' in document.documentElement || navigator.maxTouchPoints > 0; + } } - function normalizeDataKey(key) { - return key.replace(/[A-Z]/g, chr => `-${chr.toLowerCase()}`); - } + /** + * -------------------------------------------------------------------------- + * Bootstrap carousel.js + * Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE) + * -------------------------------------------------------------------------- + */ - const Manipulator = { - setDataAttribute(element, key, value) { - element.setAttribute(`data-bs-${normalizeDataKey(key)}`, value); - }, - - removeDataAttribute(element, key) { - element.removeAttribute(`data-bs-${normalizeDataKey(key)}`); - }, - - getDataAttributes(element) { - if (!element) { - return {}; - } - - const attributes = {}; - Object.keys(element.dataset).filter(key => key.startsWith('bs')).forEach(key => { - let pureKey = key.replace(/^bs/, ''); - pureKey = pureKey.charAt(0).toLowerCase() + pureKey.slice(1, pureKey.length); - attributes[pureKey] = normalizeData(element.dataset[key]); - }); - return attributes; - }, - - getDataAttribute(element, key) { - return normalizeData(element.getAttribute(`data-bs-${normalizeDataKey(key)}`)); - }, - - offset(element) { - const rect = element.getBoundingClientRect(); - return { - top: rect.top + window.pageYOffset, - left: rect.left + window.pageXOffset - }; - }, - - position(element) { - return { - top: element.offsetTop, - left: element.offsetLeft - }; - } - - }; /** - * -------------------------------------------------------------------------- - * Bootstrap (v5.1.0): dom/selector-engine.js - * Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE) - * -------------------------------------------------------------------------- - */ - const NODE_TEXT = 3; - const SelectorEngine = { - find(selector, element = document.documentElement) { - return [].concat(...Element.prototype.querySelectorAll.call(element, selector)); - }, - - findOne(selector, element = document.documentElement) { - return Element.prototype.querySelector.call(element, selector); - }, - - children(element, selector) { - return [].concat(...element.children).filter(child => child.matches(selector)); - }, - - parents(element, selector) { - const parents = []; - let ancestor = element.parentNode; - - while (ancestor && ancestor.nodeType === Node.ELEMENT_NODE && ancestor.nodeType !== NODE_TEXT) { - if (ancestor.matches(selector)) { - parents.push(ancestor); - } - - ancestor = ancestor.parentNode; - } - - return parents; - }, - - prev(element, selector) { - let previous = element.previousElementSibling; - - while (previous) { - if (previous.matches(selector)) { - return [previous]; - } - - previous = previous.previousElementSibling; - } - - return []; - }, - - next(element, selector) { - let next = element.nextElementSibling; - - while (next) { - if (next.matches(selector)) { - return [next]; - } - - next = next.nextElementSibling; - } - - return []; - }, - - focusableChildren(element) { - const focusables = ['a', 'button', 'input', 'textarea', 'select', 'details', '[tabindex]', '[contenteditable="true"]'].map(selector => `${selector}:not([tabindex^="-"])`).join(', '); - return this.find(focusables, element).filter(el => !isDisabled(el) && isVisible(el)); - } - - }; - - /** - * -------------------------------------------------------------------------- - * Bootstrap (v5.1.0): carousel.js - * Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE) - * -------------------------------------------------------------------------- - */ - /** - * ------------------------------------------------------------------------ * Constants - * ------------------------------------------------------------------------ */ - const NAME$b = 'carousel'; - const DATA_KEY$a = 'bs.carousel'; - const EVENT_KEY$a = `.${DATA_KEY$a}`; - const DATA_API_KEY$6 = '.data-api'; - const ARROW_LEFT_KEY = 'ArrowLeft'; - const ARROW_RIGHT_KEY = 'ArrowRight'; + const NAME$c = 'carousel'; + const DATA_KEY$8 = 'bs.carousel'; + const EVENT_KEY$8 = `.${DATA_KEY$8}`; + const DATA_API_KEY$5 = '.data-api'; + const ARROW_LEFT_KEY$1 = 'ArrowLeft'; + const ARROW_RIGHT_KEY$1 = 'ArrowRight'; const TOUCHEVENT_COMPAT_WAIT = 500; // Time for mouse compat events to fire after touch - const SWIPE_THRESHOLD = 40; - const Default$a = { - interval: 5000, - keyboard: true, - slide: false, - pause: 'hover', - wrap: true, - touch: true - }; - const DefaultType$a = { - interval: '(number|boolean)', - keyboard: 'boolean', - slide: '(boolean|string)', - pause: '(string|boolean)', - wrap: 'boolean', - touch: 'boolean' - }; const ORDER_NEXT = 'next'; const ORDER_PREV = 'prev'; const DIRECTION_LEFT = 'left'; const DIRECTION_RIGHT = 'right'; - const KEY_TO_DIRECTION = { - [ARROW_LEFT_KEY]: DIRECTION_RIGHT, - [ARROW_RIGHT_KEY]: DIRECTION_LEFT - }; - const EVENT_SLIDE = `slide${EVENT_KEY$a}`; - const EVENT_SLID = `slid${EVENT_KEY$a}`; - const EVENT_KEYDOWN = `keydown${EVENT_KEY$a}`; - const EVENT_MOUSEENTER = `mouseenter${EVENT_KEY$a}`; - const EVENT_MOUSELEAVE = `mouseleave${EVENT_KEY$a}`; - const EVENT_TOUCHSTART = `touchstart${EVENT_KEY$a}`; - const EVENT_TOUCHMOVE = `touchmove${EVENT_KEY$a}`; - const EVENT_TOUCHEND = `touchend${EVENT_KEY$a}`; - const EVENT_POINTERDOWN = `pointerdown${EVENT_KEY$a}`; - const EVENT_POINTERUP = `pointerup${EVENT_KEY$a}`; - const EVENT_DRAG_START = `dragstart${EVENT_KEY$a}`; - const EVENT_LOAD_DATA_API$2 = `load${EVENT_KEY$a}${DATA_API_KEY$6}`; - const EVENT_CLICK_DATA_API$5 = `click${EVENT_KEY$a}${DATA_API_KEY$6}`; + const EVENT_SLIDE = `slide${EVENT_KEY$8}`; + const EVENT_SLID = `slid${EVENT_KEY$8}`; + const EVENT_KEYDOWN$1 = `keydown${EVENT_KEY$8}`; + const EVENT_MOUSEENTER$1 = `mouseenter${EVENT_KEY$8}`; + const EVENT_MOUSELEAVE$1 = `mouseleave${EVENT_KEY$8}`; + const EVENT_DRAG_START = `dragstart${EVENT_KEY$8}`; + const EVENT_LOAD_DATA_API$3 = `load${EVENT_KEY$8}${DATA_API_KEY$5}`; + const EVENT_CLICK_DATA_API$5 = `click${EVENT_KEY$8}${DATA_API_KEY$5}`; const CLASS_NAME_CAROUSEL = 'carousel'; const CLASS_NAME_ACTIVE$2 = 'active'; const CLASS_NAME_SLIDE = 'slide'; @@ -1124,571 +1118,418 @@ const CLASS_NAME_START = 'carousel-item-start'; const CLASS_NAME_NEXT = 'carousel-item-next'; const CLASS_NAME_PREV = 'carousel-item-prev'; - const CLASS_NAME_POINTER_EVENT = 'pointer-event'; - const SELECTOR_ACTIVE$1 = '.active'; - const SELECTOR_ACTIVE_ITEM = '.active.carousel-item'; + const SELECTOR_ACTIVE = '.active'; const SELECTOR_ITEM = '.carousel-item'; + const SELECTOR_ACTIVE_ITEM = SELECTOR_ACTIVE + SELECTOR_ITEM; const SELECTOR_ITEM_IMG = '.carousel-item img'; - const SELECTOR_NEXT_PREV = '.carousel-item-next, .carousel-item-prev'; const SELECTOR_INDICATORS = '.carousel-indicators'; - const SELECTOR_INDICATOR = '[data-bs-target]'; const SELECTOR_DATA_SLIDE = '[data-bs-slide], [data-bs-slide-to]'; const SELECTOR_DATA_RIDE = '[data-bs-ride="carousel"]'; - const POINTER_TYPE_TOUCH = 'touch'; - const POINTER_TYPE_PEN = 'pen'; + const KEY_TO_DIRECTION = { + [ARROW_LEFT_KEY$1]: DIRECTION_RIGHT, + [ARROW_RIGHT_KEY$1]: DIRECTION_LEFT + }; + const Default$b = { + interval: 5000, + keyboard: true, + pause: 'hover', + ride: false, + touch: true, + wrap: true + }; + const DefaultType$b = { + interval: '(number|boolean)', + // TODO:v6 remove boolean support + keyboard: 'boolean', + pause: '(string|boolean)', + ride: '(boolean|string)', + touch: 'boolean', + wrap: 'boolean' + }; + /** - * ------------------------------------------------------------------------ - * Class Definition - * ------------------------------------------------------------------------ + * Class definition */ class Carousel extends BaseComponent { constructor(element, config) { - super(element); - this._items = null; + super(element, config); this._interval = null; this._activeElement = null; - this._isPaused = false; this._isSliding = false; this.touchTimeout = null; - this.touchStartX = 0; - this.touchDeltaX = 0; - this._config = this._getConfig(config); + this._swipeHelper = null; this._indicatorsElement = SelectorEngine.findOne(SELECTOR_INDICATORS, this._element); - this._touchSupported = 'ontouchstart' in document.documentElement || navigator.maxTouchPoints > 0; - this._pointerEvent = Boolean(window.PointerEvent); - this._addEventListeners(); - } // Getters - + if (this._config.ride === CLASS_NAME_CAROUSEL) { + this.cycle(); + } + } + // Getters static get Default() { - return Default$a; + return Default$b; + } + static get DefaultType() { + return DefaultType$b; } - static get NAME() { - return NAME$b; - } // Public - + return NAME$c; + } + // Public next() { this._slide(ORDER_NEXT); } - nextWhenVisible() { + // FIXME TODO use `document.visibilityState` // Don't call next when the page isn't visible // or the carousel or its parent isn't visible if (!document.hidden && isVisible(this._element)) { this.next(); } } - prev() { this._slide(ORDER_PREV); } - - pause(event) { - if (!event) { - this._isPaused = true; - } - - if (SelectorEngine.findOne(SELECTOR_NEXT_PREV, this._element)) { + pause() { + if (this._isSliding) { triggerTransitionEnd(this._element); - this.cycle(true); } - - clearInterval(this._interval); - this._interval = null; + this._clearInterval(); } - - cycle(event) { - if (!event) { - this._isPaused = false; - } - - if (this._interval) { - clearInterval(this._interval); - this._interval = null; + cycle() { + this._clearInterval(); + this._updateInterval(); + this._interval = setInterval(() => this.nextWhenVisible(), this._config.interval); + } + _maybeEnableCycle() { + if (!this._config.ride) { + return; } - - if (this._config && this._config.interval && !this._isPaused) { - this._updateInterval(); - - this._interval = setInterval((document.visibilityState ? this.nextWhenVisible : this.next).bind(this), this._config.interval); + if (this._isSliding) { + EventHandler.one(this._element, EVENT_SLID, () => this.cycle()); + return; } + this.cycle(); } - to(index) { - this._activeElement = SelectorEngine.findOne(SELECTOR_ACTIVE_ITEM, this._element); - - const activeIndex = this._getItemIndex(this._activeElement); - - if (index > this._items.length - 1 || index < 0) { + const items = this._getItems(); + if (index > items.length - 1 || index < 0) { return; } - if (this._isSliding) { EventHandler.one(this._element, EVENT_SLID, () => this.to(index)); return; } - + const activeIndex = this._getItemIndex(this._getActive()); if (activeIndex === index) { - this.pause(); - this.cycle(); return; } - const order = index > activeIndex ? ORDER_NEXT : ORDER_PREV; - - this._slide(order, this._items[index]); - } // Private - - - _getConfig(config) { - config = { ...Default$a, - ...Manipulator.getDataAttributes(this._element), - ...(typeof config === 'object' ? config : {}) - }; - typeCheckConfig(NAME$b, config, DefaultType$a); - return config; + this._slide(order, items[index]); } - - _handleSwipe() { - const absDeltax = Math.abs(this.touchDeltaX); - - if (absDeltax <= SWIPE_THRESHOLD) { - return; - } - - const direction = absDeltax / this.touchDeltaX; - this.touchDeltaX = 0; - - if (!direction) { - return; + dispose() { + if (this._swipeHelper) { + this._swipeHelper.dispose(); } - - this._slide(direction > 0 ? DIRECTION_RIGHT : DIRECTION_LEFT); + super.dispose(); } + // Private + _configAfterMerge(config) { + config.defaultInterval = config.interval; + return config; + } _addEventListeners() { if (this._config.keyboard) { - EventHandler.on(this._element, EVENT_KEYDOWN, event => this._keydown(event)); + EventHandler.on(this._element, EVENT_KEYDOWN$1, event => this._keydown(event)); } - if (this._config.pause === 'hover') { - EventHandler.on(this._element, EVENT_MOUSEENTER, event => this.pause(event)); - EventHandler.on(this._element, EVENT_MOUSELEAVE, event => this.cycle(event)); + EventHandler.on(this._element, EVENT_MOUSEENTER$1, () => this.pause()); + EventHandler.on(this._element, EVENT_MOUSELEAVE$1, () => this._maybeEnableCycle()); } - - if (this._config.touch && this._touchSupported) { + if (this._config.touch && Swipe.isSupported()) { this._addTouchEventListeners(); } } - _addTouchEventListeners() { - const start = event => { - if (this._pointerEvent && (event.pointerType === POINTER_TYPE_PEN || event.pointerType === POINTER_TYPE_TOUCH)) { - this.touchStartX = event.clientX; - } else if (!this._pointerEvent) { - this.touchStartX = event.touches[0].clientX; - } - }; - - const move = event => { - // ensure swiping with one touch and not pinching - this.touchDeltaX = event.touches && event.touches.length > 1 ? 0 : event.touches[0].clientX - this.touchStartX; - }; - - const end = event => { - if (this._pointerEvent && (event.pointerType === POINTER_TYPE_PEN || event.pointerType === POINTER_TYPE_TOUCH)) { - this.touchDeltaX = event.clientX - this.touchStartX; + for (const img of SelectorEngine.find(SELECTOR_ITEM_IMG, this._element)) { + EventHandler.on(img, EVENT_DRAG_START, event => event.preventDefault()); + } + const endCallBack = () => { + if (this._config.pause !== 'hover') { + return; } - this._handleSwipe(); + // If it's a touch-enabled device, mouseenter/leave are fired as + // part of the mouse compatibility events on first tap - the carousel + // would stop cycling until user tapped out of it; + // here, we listen for touchend, explicitly pause the carousel + // (as if it's the second time we tap on it, mouseenter compat event + // is NOT fired) and after a timeout (to allow for mouse compatibility + // events to fire) we explicitly restart cycling - if (this._config.pause === 'hover') { - // If it's a touch-enabled device, mouseenter/leave are fired as - // part of the mouse compatibility events on first tap - the carousel - // would stop cycling until user tapped out of it; - // here, we listen for touchend, explicitly pause the carousel - // (as if it's the second time we tap on it, mouseenter compat event - // is NOT fired) and after a timeout (to allow for mouse compatibility - // events to fire) we explicitly restart cycling - this.pause(); - - if (this.touchTimeout) { - clearTimeout(this.touchTimeout); - } - - this.touchTimeout = setTimeout(event => this.cycle(event), TOUCHEVENT_COMPAT_WAIT + this._config.interval); + this.pause(); + if (this.touchTimeout) { + clearTimeout(this.touchTimeout); } + this.touchTimeout = setTimeout(() => this._maybeEnableCycle(), TOUCHEVENT_COMPAT_WAIT + this._config.interval); }; - - SelectorEngine.find(SELECTOR_ITEM_IMG, this._element).forEach(itemImg => { - EventHandler.on(itemImg, EVENT_DRAG_START, e => e.preventDefault()); - }); - - if (this._pointerEvent) { - EventHandler.on(this._element, EVENT_POINTERDOWN, event => start(event)); - EventHandler.on(this._element, EVENT_POINTERUP, event => end(event)); - - this._element.classList.add(CLASS_NAME_POINTER_EVENT); - } else { - EventHandler.on(this._element, EVENT_TOUCHSTART, event => start(event)); - EventHandler.on(this._element, EVENT_TOUCHMOVE, event => move(event)); - EventHandler.on(this._element, EVENT_TOUCHEND, event => end(event)); - } + const swipeConfig = { + leftCallback: () => this._slide(this._directionToOrder(DIRECTION_LEFT)), + rightCallback: () => this._slide(this._directionToOrder(DIRECTION_RIGHT)), + endCallback: endCallBack + }; + this._swipeHelper = new Swipe(this._element, swipeConfig); } - _keydown(event) { if (/input|textarea/i.test(event.target.tagName)) { return; } - const direction = KEY_TO_DIRECTION[event.key]; - if (direction) { event.preventDefault(); - - this._slide(direction); + this._slide(this._directionToOrder(direction)); } } - _getItemIndex(element) { - this._items = element && element.parentNode ? SelectorEngine.find(SELECTOR_ITEM, element.parentNode) : []; - return this._items.indexOf(element); - } - - _getItemByOrder(order, activeElement) { - const isNext = order === ORDER_NEXT; - return getNextActiveElement(this._items, activeElement, isNext, this._config.wrap); - } - - _triggerSlideEvent(relatedTarget, eventDirectionName) { - const targetIndex = this._getItemIndex(relatedTarget); - - const fromIndex = this._getItemIndex(SelectorEngine.findOne(SELECTOR_ACTIVE_ITEM, this._element)); - - return EventHandler.trigger(this._element, EVENT_SLIDE, { - relatedTarget, - direction: eventDirectionName, - from: fromIndex, - to: targetIndex - }); + return this._getItems().indexOf(element); } - - _setActiveIndicatorElement(element) { - if (this._indicatorsElement) { - const activeIndicator = SelectorEngine.findOne(SELECTOR_ACTIVE$1, this._indicatorsElement); - activeIndicator.classList.remove(CLASS_NAME_ACTIVE$2); - activeIndicator.removeAttribute('aria-current'); - const indicators = SelectorEngine.find(SELECTOR_INDICATOR, this._indicatorsElement); - - for (let i = 0; i < indicators.length; i++) { - if (Number.parseInt(indicators[i].getAttribute('data-bs-slide-to'), 10) === this._getItemIndex(element)) { - indicators[i].classList.add(CLASS_NAME_ACTIVE$2); - indicators[i].setAttribute('aria-current', 'true'); - break; - } - } + _setActiveIndicatorElement(index) { + if (!this._indicatorsElement) { + return; + } + const activeIndicator = SelectorEngine.findOne(SELECTOR_ACTIVE, this._indicatorsElement); + activeIndicator.classList.remove(CLASS_NAME_ACTIVE$2); + activeIndicator.removeAttribute('aria-current'); + const newActiveIndicator = SelectorEngine.findOne(`[data-bs-slide-to="${index}"]`, this._indicatorsElement); + if (newActiveIndicator) { + newActiveIndicator.classList.add(CLASS_NAME_ACTIVE$2); + newActiveIndicator.setAttribute('aria-current', 'true'); } } - _updateInterval() { - const element = this._activeElement || SelectorEngine.findOne(SELECTOR_ACTIVE_ITEM, this._element); - + const element = this._activeElement || this._getActive(); if (!element) { return; } - const elementInterval = Number.parseInt(element.getAttribute('data-bs-interval'), 10); - - if (elementInterval) { - this._config.defaultInterval = this._config.defaultInterval || this._config.interval; - this._config.interval = elementInterval; - } else { - this._config.interval = this._config.defaultInterval || this._config.interval; - } + this._config.interval = elementInterval || this._config.defaultInterval; } - - _slide(directionOrOrder, element) { - const order = this._directionToOrder(directionOrOrder); - - const activeElement = SelectorEngine.findOne(SELECTOR_ACTIVE_ITEM, this._element); - - const activeElementIndex = this._getItemIndex(activeElement); - - const nextElement = element || this._getItemByOrder(order, activeElement); - - const nextElementIndex = this._getItemIndex(nextElement); - - const isCycling = Boolean(this._interval); - const isNext = order === ORDER_NEXT; - const directionalClassName = isNext ? CLASS_NAME_START : CLASS_NAME_END; - const orderClassName = isNext ? CLASS_NAME_NEXT : CLASS_NAME_PREV; - - const eventDirectionName = this._orderToDirection(order); - - if (nextElement && nextElement.classList.contains(CLASS_NAME_ACTIVE$2)) { - this._isSliding = false; + _slide(order, element = null) { + if (this._isSliding) { return; } - - if (this._isSliding) { + const activeElement = this._getActive(); + const isNext = order === ORDER_NEXT; + const nextElement = element || getNextActiveElement(this._getItems(), activeElement, isNext, this._config.wrap); + if (nextElement === activeElement) { return; } - - const slideEvent = this._triggerSlideEvent(nextElement, eventDirectionName); - + const nextElementIndex = this._getItemIndex(nextElement); + const triggerEvent = eventName => { + return EventHandler.trigger(this._element, eventName, { + relatedTarget: nextElement, + direction: this._orderToDirection(order), + from: this._getItemIndex(activeElement), + to: nextElementIndex + }); + }; + const slideEvent = triggerEvent(EVENT_SLIDE); if (slideEvent.defaultPrevented) { return; } - if (!activeElement || !nextElement) { // Some weirdness is happening, so we bail + // TODO: change tests that use empty divs to avoid this check return; } - + const isCycling = Boolean(this._interval); + this.pause(); this._isSliding = true; - - if (isCycling) { - this.pause(); - } - - this._setActiveIndicatorElement(nextElement); - + this._setActiveIndicatorElement(nextElementIndex); this._activeElement = nextElement; - - const triggerSlidEvent = () => { - EventHandler.trigger(this._element, EVENT_SLID, { - relatedTarget: nextElement, - direction: eventDirectionName, - from: activeElementIndex, - to: nextElementIndex - }); - }; - - if (this._element.classList.contains(CLASS_NAME_SLIDE)) { - nextElement.classList.add(orderClassName); - reflow(nextElement); - activeElement.classList.add(directionalClassName); - nextElement.classList.add(directionalClassName); - - const completeCallBack = () => { - nextElement.classList.remove(directionalClassName, orderClassName); - nextElement.classList.add(CLASS_NAME_ACTIVE$2); - activeElement.classList.remove(CLASS_NAME_ACTIVE$2, orderClassName, directionalClassName); - this._isSliding = false; - setTimeout(triggerSlidEvent, 0); - }; - - this._queueCallback(completeCallBack, activeElement, true); - } else { - activeElement.classList.remove(CLASS_NAME_ACTIVE$2); + const directionalClassName = isNext ? CLASS_NAME_START : CLASS_NAME_END; + const orderClassName = isNext ? CLASS_NAME_NEXT : CLASS_NAME_PREV; + nextElement.classList.add(orderClassName); + reflow(nextElement); + activeElement.classList.add(directionalClassName); + nextElement.classList.add(directionalClassName); + const completeCallBack = () => { + nextElement.classList.remove(directionalClassName, orderClassName); nextElement.classList.add(CLASS_NAME_ACTIVE$2); + activeElement.classList.remove(CLASS_NAME_ACTIVE$2, orderClassName, directionalClassName); this._isSliding = false; - triggerSlidEvent(); - } - + triggerEvent(EVENT_SLID); + }; + this._queueCallback(completeCallBack, activeElement, this._isAnimated()); if (isCycling) { this.cycle(); } } - - _directionToOrder(direction) { - if (![DIRECTION_RIGHT, DIRECTION_LEFT].includes(direction)) { - return direction; + _isAnimated() { + return this._element.classList.contains(CLASS_NAME_SLIDE); + } + _getActive() { + return SelectorEngine.findOne(SELECTOR_ACTIVE_ITEM, this._element); + } + _getItems() { + return SelectorEngine.find(SELECTOR_ITEM, this._element); + } + _clearInterval() { + if (this._interval) { + clearInterval(this._interval); + this._interval = null; } - + } + _directionToOrder(direction) { if (isRTL()) { return direction === DIRECTION_LEFT ? ORDER_PREV : ORDER_NEXT; } - return direction === DIRECTION_LEFT ? ORDER_NEXT : ORDER_PREV; } - _orderToDirection(order) { - if (![ORDER_NEXT, ORDER_PREV].includes(order)) { - return order; - } - if (isRTL()) { return order === ORDER_PREV ? DIRECTION_LEFT : DIRECTION_RIGHT; } - return order === ORDER_PREV ? DIRECTION_RIGHT : DIRECTION_LEFT; - } // Static - - - static carouselInterface(element, config) { - const data = Carousel.getOrCreateInstance(element, config); - let { - _config - } = data; - - if (typeof config === 'object') { - _config = { ..._config, - ...config - }; - } - - const action = typeof config === 'string' ? config : _config.slide; - - if (typeof config === 'number') { - data.to(config); - } else if (typeof action === 'string') { - if (typeof data[action] === 'undefined') { - throw new TypeError(`No method named "${action}"`); - } - - data[action](); - } else if (_config.interval && _config.ride) { - data.pause(); - data.cycle(); - } } + // Static static jQueryInterface(config) { return this.each(function () { - Carousel.carouselInterface(this, config); + const data = Carousel.getOrCreateInstance(this, config); + if (typeof config === 'number') { + data.to(config); + return; + } + if (typeof config === 'string') { + if (data[config] === undefined || config.startsWith('_') || config === 'constructor') { + throw new TypeError(`No method named "${config}"`); + } + data[config](); + } }); } - - static dataApiClickHandler(event) { - const target = getElementFromSelector(this); - - if (!target || !target.classList.contains(CLASS_NAME_CAROUSEL)) { - return; - } - - const config = { ...Manipulator.getDataAttributes(target), - ...Manipulator.getDataAttributes(this) - }; - const slideIndex = this.getAttribute('data-bs-slide-to'); - - if (slideIndex) { - config.interval = false; - } - - Carousel.carouselInterface(target, config); - - if (slideIndex) { - Carousel.getInstance(target).to(slideIndex); - } - - event.preventDefault(); - } - } + /** - * ------------------------------------------------------------------------ - * Data Api implementation - * ------------------------------------------------------------------------ + * Data API implementation */ - - EventHandler.on(document, EVENT_CLICK_DATA_API$5, SELECTOR_DATA_SLIDE, Carousel.dataApiClickHandler); - EventHandler.on(window, EVENT_LOAD_DATA_API$2, () => { + EventHandler.on(document, EVENT_CLICK_DATA_API$5, SELECTOR_DATA_SLIDE, function (event) { + const target = SelectorEngine.getElementFromSelector(this); + if (!target || !target.classList.contains(CLASS_NAME_CAROUSEL)) { + return; + } + event.preventDefault(); + const carousel = Carousel.getOrCreateInstance(target); + const slideIndex = this.getAttribute('data-bs-slide-to'); + if (slideIndex) { + carousel.to(slideIndex); + carousel._maybeEnableCycle(); + return; + } + if (Manipulator.getDataAttribute(this, 'slide') === 'next') { + carousel.next(); + carousel._maybeEnableCycle(); + return; + } + carousel.prev(); + carousel._maybeEnableCycle(); + }); + EventHandler.on(window, EVENT_LOAD_DATA_API$3, () => { const carousels = SelectorEngine.find(SELECTOR_DATA_RIDE); - - for (let i = 0, len = carousels.length; i < len; i++) { - Carousel.carouselInterface(carousels[i], Carousel.getInstance(carousels[i])); + for (const carousel of carousels) { + Carousel.getOrCreateInstance(carousel); } }); + /** - * ------------------------------------------------------------------------ * jQuery - * ------------------------------------------------------------------------ - * add .Carousel to jQuery only if jQuery is present */ defineJQueryPlugin(Carousel); /** * -------------------------------------------------------------------------- - * Bootstrap (v5.1.0): collapse.js + * Bootstrap collapse.js * Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE) * -------------------------------------------------------------------------- */ + + /** - * ------------------------------------------------------------------------ * Constants - * ------------------------------------------------------------------------ */ - const NAME$a = 'collapse'; - const DATA_KEY$9 = 'bs.collapse'; - const EVENT_KEY$9 = `.${DATA_KEY$9}`; - const DATA_API_KEY$5 = '.data-api'; - const Default$9 = { - toggle: true, - parent: null - }; - const DefaultType$9 = { - toggle: 'boolean', - parent: '(null|element)' - }; - const EVENT_SHOW$5 = `show${EVENT_KEY$9}`; - const EVENT_SHOWN$5 = `shown${EVENT_KEY$9}`; - const EVENT_HIDE$5 = `hide${EVENT_KEY$9}`; - const EVENT_HIDDEN$5 = `hidden${EVENT_KEY$9}`; - const EVENT_CLICK_DATA_API$4 = `click${EVENT_KEY$9}${DATA_API_KEY$5}`; + const NAME$b = 'collapse'; + const DATA_KEY$7 = 'bs.collapse'; + const EVENT_KEY$7 = `.${DATA_KEY$7}`; + const DATA_API_KEY$4 = '.data-api'; + const EVENT_SHOW$6 = `show${EVENT_KEY$7}`; + const EVENT_SHOWN$6 = `shown${EVENT_KEY$7}`; + const EVENT_HIDE$6 = `hide${EVENT_KEY$7}`; + const EVENT_HIDDEN$6 = `hidden${EVENT_KEY$7}`; + const EVENT_CLICK_DATA_API$4 = `click${EVENT_KEY$7}${DATA_API_KEY$4}`; const CLASS_NAME_SHOW$7 = 'show'; const CLASS_NAME_COLLAPSE = 'collapse'; const CLASS_NAME_COLLAPSING = 'collapsing'; const CLASS_NAME_COLLAPSED = 'collapsed'; + const CLASS_NAME_DEEPER_CHILDREN = `:scope .${CLASS_NAME_COLLAPSE} .${CLASS_NAME_COLLAPSE}`; const CLASS_NAME_HORIZONTAL = 'collapse-horizontal'; const WIDTH = 'width'; const HEIGHT = 'height'; - const SELECTOR_ACTIVES = '.show, .collapsing'; + const SELECTOR_ACTIVES = '.collapse.show, .collapse.collapsing'; const SELECTOR_DATA_TOGGLE$4 = '[data-bs-toggle="collapse"]'; + const Default$a = { + parent: null, + toggle: true + }; + const DefaultType$a = { + parent: '(null|element)', + toggle: 'boolean' + }; + /** - * ------------------------------------------------------------------------ - * Class Definition - * ------------------------------------------------------------------------ + * Class definition */ class Collapse extends BaseComponent { constructor(element, config) { - super(element); + super(element, config); this._isTransitioning = false; - this._config = this._getConfig(config); this._triggerArray = []; const toggleList = SelectorEngine.find(SELECTOR_DATA_TOGGLE$4); - - for (let i = 0, len = toggleList.length; i < len; i++) { - const elem = toggleList[i]; - const selector = getSelectorFromElement(elem); - const filterElement = SelectorEngine.find(selector).filter(foundElem => foundElem === this._element); - + for (const elem of toggleList) { + const selector = SelectorEngine.getSelectorFromElement(elem); + const filterElement = SelectorEngine.find(selector).filter(foundElement => foundElement === this._element); if (selector !== null && filterElement.length) { - this._selector = selector; - this._triggerArray.push(elem); } } - this._initializeChildren(); - if (!this._config.parent) { this._addAriaAndCollapsedClass(this._triggerArray, this._isShown()); } - if (this._config.toggle) { this.toggle(); } - } // Getters - + } + // Getters static get Default() { - return Default$9; + return Default$a; + } + static get DefaultType() { + return DefaultType$a; } - static get NAME() { - return NAME$a; - } // Public - + return NAME$b; + } + // Public toggle() { if (this._isShown()) { this.hide(); @@ -1696,228 +1537,151 @@ this.show(); } } - show() { if (this._isTransitioning || this._isShown()) { return; } + let activeChildren = []; - let actives = []; - let activesData; - + // find active children if (this._config.parent) { - const children = SelectorEngine.find(`.${CLASS_NAME_COLLAPSE} .${CLASS_NAME_COLLAPSE}`, this._config.parent); - actives = SelectorEngine.find(SELECTOR_ACTIVES, this._config.parent).filter(elem => !children.includes(elem)); // remove children if greater depth + activeChildren = this._getFirstLevelChildren(SELECTOR_ACTIVES).filter(element => element !== this._element).map(element => Collapse.getOrCreateInstance(element, { + toggle: false + })); } - - const container = SelectorEngine.findOne(this._selector); - - if (actives.length) { - const tempActiveData = actives.find(elem => container !== elem); - activesData = tempActiveData ? Collapse.getInstance(tempActiveData) : null; - - if (activesData && activesData._isTransitioning) { - return; - } + if (activeChildren.length && activeChildren[0]._isTransitioning) { + return; } - - const startEvent = EventHandler.trigger(this._element, EVENT_SHOW$5); - + const startEvent = EventHandler.trigger(this._element, EVENT_SHOW$6); if (startEvent.defaultPrevented) { return; } - - actives.forEach(elemActive => { - if (container !== elemActive) { - Collapse.getOrCreateInstance(elemActive, { - toggle: false - }).hide(); - } - - if (!activesData) { - Data.set(elemActive, DATA_KEY$9, null); - } - }); - + for (const activeInstance of activeChildren) { + activeInstance.hide(); + } const dimension = this._getDimension(); - this._element.classList.remove(CLASS_NAME_COLLAPSE); - this._element.classList.add(CLASS_NAME_COLLAPSING); - this._element.style[dimension] = 0; - this._addAriaAndCollapsedClass(this._triggerArray, true); - this._isTransitioning = true; - const complete = () => { this._isTransitioning = false; - this._element.classList.remove(CLASS_NAME_COLLAPSING); - this._element.classList.add(CLASS_NAME_COLLAPSE, CLASS_NAME_SHOW$7); - this._element.style[dimension] = ''; - EventHandler.trigger(this._element, EVENT_SHOWN$5); + EventHandler.trigger(this._element, EVENT_SHOWN$6); }; - const capitalizedDimension = dimension[0].toUpperCase() + dimension.slice(1); const scrollSize = `scroll${capitalizedDimension}`; - this._queueCallback(complete, this._element, true); - this._element.style[dimension] = `${this._element[scrollSize]}px`; } - hide() { if (this._isTransitioning || !this._isShown()) { return; } - - const startEvent = EventHandler.trigger(this._element, EVENT_HIDE$5); - + const startEvent = EventHandler.trigger(this._element, EVENT_HIDE$6); if (startEvent.defaultPrevented) { return; } - const dimension = this._getDimension(); - this._element.style[dimension] = `${this._element.getBoundingClientRect()[dimension]}px`; reflow(this._element); - this._element.classList.add(CLASS_NAME_COLLAPSING); - this._element.classList.remove(CLASS_NAME_COLLAPSE, CLASS_NAME_SHOW$7); - - const triggerArrayLength = this._triggerArray.length; - - for (let i = 0; i < triggerArrayLength; i++) { - const trigger = this._triggerArray[i]; - const elem = getElementFromSelector(trigger); - - if (elem && !this._isShown(elem)) { + for (const trigger of this._triggerArray) { + const element = SelectorEngine.getElementFromSelector(trigger); + if (element && !this._isShown(element)) { this._addAriaAndCollapsedClass([trigger], false); } } - this._isTransitioning = true; - const complete = () => { this._isTransitioning = false; - this._element.classList.remove(CLASS_NAME_COLLAPSING); - this._element.classList.add(CLASS_NAME_COLLAPSE); - - EventHandler.trigger(this._element, EVENT_HIDDEN$5); + EventHandler.trigger(this._element, EVENT_HIDDEN$6); }; - this._element.style[dimension] = ''; - this._queueCallback(complete, this._element, true); } + // Private _isShown(element = this._element) { return element.classList.contains(CLASS_NAME_SHOW$7); - } // Private - - - _getConfig(config) { - config = { ...Default$9, - ...Manipulator.getDataAttributes(this._element), - ...config - }; + } + _configAfterMerge(config) { config.toggle = Boolean(config.toggle); // Coerce string values - config.parent = getElement(config.parent); - typeCheckConfig(NAME$a, config, DefaultType$9); return config; } - _getDimension() { return this._element.classList.contains(CLASS_NAME_HORIZONTAL) ? WIDTH : HEIGHT; } - _initializeChildren() { if (!this._config.parent) { return; } - - const children = SelectorEngine.find(`.${CLASS_NAME_COLLAPSE} .${CLASS_NAME_COLLAPSE}`, this._config.parent); - SelectorEngine.find(SELECTOR_DATA_TOGGLE$4, this._config.parent).filter(elem => !children.includes(elem)).forEach(element => { - const selected = getElementFromSelector(element); - + const children = this._getFirstLevelChildren(SELECTOR_DATA_TOGGLE$4); + for (const element of children) { + const selected = SelectorEngine.getElementFromSelector(element); if (selected) { this._addAriaAndCollapsedClass([element], this._isShown(selected)); } - }); + } + } + _getFirstLevelChildren(selector) { + const children = SelectorEngine.find(CLASS_NAME_DEEPER_CHILDREN, this._config.parent); + // remove children if greater depth + return SelectorEngine.find(selector, this._config.parent).filter(element => !children.includes(element)); } - _addAriaAndCollapsedClass(triggerArray, isOpen) { if (!triggerArray.length) { return; } + for (const element of triggerArray) { + element.classList.toggle(CLASS_NAME_COLLAPSED, !isOpen); + element.setAttribute('aria-expanded', isOpen); + } + } - triggerArray.forEach(elem => { - if (isOpen) { - elem.classList.remove(CLASS_NAME_COLLAPSED); - } else { - elem.classList.add(CLASS_NAME_COLLAPSED); - } - - elem.setAttribute('aria-expanded', isOpen); - }); - } // Static - - + // Static static jQueryInterface(config) { + const _config = {}; + if (typeof config === 'string' && /show|hide/.test(config)) { + _config.toggle = false; + } return this.each(function () { - const _config = {}; - - if (typeof config === 'string' && /show|hide/.test(config)) { - _config.toggle = false; - } - const data = Collapse.getOrCreateInstance(this, _config); - if (typeof config === 'string') { if (typeof data[config] === 'undefined') { throw new TypeError(`No method named "${config}"`); } - data[config](); } }); } - } + /** - * ------------------------------------------------------------------------ - * Data Api implementation - * ------------------------------------------------------------------------ + * Data API implementation */ - EventHandler.on(document, EVENT_CLICK_DATA_API$4, SELECTOR_DATA_TOGGLE$4, function (event) { // preventDefault only for elements (which change the URL) not inside the collapsible element if (event.target.tagName === 'A' || event.delegateTarget && event.delegateTarget.tagName === 'A') { event.preventDefault(); } - - const selector = getSelectorFromElement(this); - const selectorElements = SelectorEngine.find(selector); - selectorElements.forEach(element => { + for (const element of SelectorEngine.getMultipleElementsFromSelector(this)) { Collapse.getOrCreateInstance(element, { toggle: false }).toggle(); - }); + } }); + /** - * ------------------------------------------------------------------------ * jQuery - * ------------------------------------------------------------------------ - * add .Collapse to jQuery only if jQuery is present */ defineJQueryPlugin(Collapse); @@ -2065,7 +1829,7 @@ } // eslint-disable-next-line import/no-unused-modules - var applyStyles$1 = { + const applyStyles$1 = { name: 'applyStyles', enabled: true, phase: 'write', @@ -2078,31 +1842,61 @@ return placement.split('-')[0]; } - var round$1 = Math.round; - function getBoundingClientRect(element, includeScale) { + var max = Math.max; + var min = Math.min; + var round = Math.round; + + function getUAString() { + var uaData = navigator.userAgentData; + + if (uaData != null && uaData.brands && Array.isArray(uaData.brands)) { + return uaData.brands.map(function (item) { + return item.brand + "/" + item.version; + }).join(' '); + } + + return navigator.userAgent; + } + + function isLayoutViewport() { + return !/^((?!chrome|android).)*safari/i.test(getUAString()); + } + + function getBoundingClientRect(element, includeScale, isFixedStrategy) { if (includeScale === void 0) { includeScale = false; } - var rect = element.getBoundingClientRect(); + if (isFixedStrategy === void 0) { + isFixedStrategy = false; + } + + var clientRect = element.getBoundingClientRect(); var scaleX = 1; var scaleY = 1; - if (isHTMLElement(element) && includeScale) { - // Fallback to 1 in case both values are `0` - scaleX = rect.width / element.offsetWidth || 1; - scaleY = rect.height / element.offsetHeight || 1; + if (includeScale && isHTMLElement(element)) { + scaleX = element.offsetWidth > 0 ? round(clientRect.width) / element.offsetWidth || 1 : 1; + scaleY = element.offsetHeight > 0 ? round(clientRect.height) / element.offsetHeight || 1 : 1; } + var _ref = isElement(element) ? getWindow(element) : window, + visualViewport = _ref.visualViewport; + + var addVisualOffsets = !isLayoutViewport() && isFixedStrategy; + var x = (clientRect.left + (addVisualOffsets && visualViewport ? visualViewport.offsetLeft : 0)) / scaleX; + var y = (clientRect.top + (addVisualOffsets && visualViewport ? visualViewport.offsetTop : 0)) / scaleY; + var width = clientRect.width / scaleX; + var height = clientRect.height / scaleY; return { - width: round$1(rect.width / scaleX), - height: round$1(rect.height / scaleY), - top: round$1(rect.top / scaleY), - right: round$1(rect.right / scaleX), - bottom: round$1(rect.bottom / scaleY), - left: round$1(rect.left / scaleX), - x: round$1(rect.left / scaleX), - y: round$1(rect.top / scaleY) + width: width, + height: height, + top: y, + right: x + width, + bottom: y + height, + left: x, + x: x, + y: y }; } @@ -2197,8 +1991,8 @@ function getContainingBlock(element) { - var isFirefox = navigator.userAgent.toLowerCase().indexOf('firefox') !== -1; - var isIE = navigator.userAgent.indexOf('Trident') !== -1; + var isFirefox = /firefox/i.test(getUAString()); + var isIE = /Trident/i.test(getUAString()); if (isIE && isHTMLElement(element)) { // In IE 9, 10 and 11 fixed elements containing block is always established by the viewport @@ -2211,6 +2005,10 @@ var currentNode = getParentNode(element); + if (isShadowRoot(currentNode)) { + currentNode = currentNode.host; + } + while (isHTMLElement(currentNode) && ['html', 'body'].indexOf(getNodeName(currentNode)) < 0) { var css = getComputedStyle$1(currentNode); // This is non-exhaustive but covers the most common CSS properties that // create a containing block. @@ -2247,13 +2045,13 @@ return ['top', 'bottom'].indexOf(placement) >= 0 ? 'x' : 'y'; } - var max = Math.max; - var min = Math.min; - var round = Math.round; - function within(min$1, value, max$1) { return max(min$1, min(value, max$1)); } + function withinMaxClamp(min, value, max) { + var v = within(min, value, max); + return v > max ? max : v; + } function getFreshSideObject() { return { @@ -2339,7 +2137,6 @@ } if (!contains(state.elements.popper, arrowElement)) { - return; } @@ -2347,7 +2144,7 @@ } // eslint-disable-next-line import/no-unused-modules - var arrow$1 = { + const arrow$1 = { name: 'arrow', enabled: true, phase: 'main', @@ -2357,6 +2154,10 @@ requiresIfExists: ['preventOverflow'] }; + function getVariation(placement) { + return placement.split('-')[1]; + } + var unsetSides = { top: 'auto', right: 'auto', @@ -2366,14 +2167,13 @@ // Zooming can change the DPR, but it seems to report a value that will // cleanly divide the values into the appropriate subpixels. - function roundOffsetsByDPR(_ref) { + function roundOffsetsByDPR(_ref, win) { var x = _ref.x, y = _ref.y; - var win = window; var dpr = win.devicePixelRatio || 1; return { - x: round(round(x * dpr) / dpr) || 0, - y: round(round(y * dpr) / dpr) || 0 + x: round(x * dpr) / dpr || 0, + y: round(y * dpr) / dpr || 0 }; } @@ -2383,18 +2183,28 @@ var popper = _ref2.popper, popperRect = _ref2.popperRect, placement = _ref2.placement, + variation = _ref2.variation, offsets = _ref2.offsets, position = _ref2.position, gpuAcceleration = _ref2.gpuAcceleration, adaptive = _ref2.adaptive, - roundOffsets = _ref2.roundOffsets; - - var _ref3 = roundOffsets === true ? roundOffsetsByDPR(offsets) : typeof roundOffsets === 'function' ? roundOffsets(offsets) : offsets, - _ref3$x = _ref3.x, - x = _ref3$x === void 0 ? 0 : _ref3$x, - _ref3$y = _ref3.y, - y = _ref3$y === void 0 ? 0 : _ref3$y; + roundOffsets = _ref2.roundOffsets, + isFixed = _ref2.isFixed; + var _offsets$x = offsets.x, + x = _offsets$x === void 0 ? 0 : _offsets$x, + _offsets$y = offsets.y, + y = _offsets$y === void 0 ? 0 : _offsets$y; + + var _ref3 = typeof roundOffsets === 'function' ? roundOffsets({ + x: x, + y: y + }) : { + x: x, + y: y + }; + x = _ref3.x; + y = _ref3.y; var hasX = offsets.hasOwnProperty('x'); var hasY = offsets.hasOwnProperty('y'); var sideX = left; @@ -2409,7 +2219,7 @@ if (offsetParent === getWindow(popper)) { offsetParent = getDocumentElement(popper); - if (getComputedStyle$1(offsetParent).position !== 'static') { + if (getComputedStyle$1(offsetParent).position !== 'static' && position === 'absolute') { heightProp = 'scrollHeight'; widthProp = 'scrollWidth'; } @@ -2418,49 +2228,63 @@ offsetParent = offsetParent; - if (placement === top) { - sideY = bottom; // $FlowFixMe[prop-missing] - - y -= offsetParent[heightProp] - popperRect.height; + if (placement === top || (placement === left || placement === right) && variation === end) { + sideY = bottom; + var offsetY = isFixed && offsetParent === win && win.visualViewport ? win.visualViewport.height : // $FlowFixMe[prop-missing] + offsetParent[heightProp]; + y -= offsetY - popperRect.height; y *= gpuAcceleration ? 1 : -1; } - if (placement === left) { - sideX = right; // $FlowFixMe[prop-missing] - - x -= offsetParent[widthProp] - popperRect.width; + if (placement === left || (placement === top || placement === bottom) && variation === end) { + sideX = right; + var offsetX = isFixed && offsetParent === win && win.visualViewport ? win.visualViewport.width : // $FlowFixMe[prop-missing] + offsetParent[widthProp]; + x -= offsetX - popperRect.width; x *= gpuAcceleration ? 1 : -1; } } - var commonStyles = Object.assign({ - position: position - }, adaptive && unsetSides); + var commonStyles = Object.assign({ + position: position + }, adaptive && unsetSides); + + var _ref4 = roundOffsets === true ? roundOffsetsByDPR({ + x: x, + y: y + }, getWindow(popper)) : { + x: x, + y: y + }; + + x = _ref4.x; + y = _ref4.y; if (gpuAcceleration) { var _Object$assign; - return Object.assign({}, commonStyles, (_Object$assign = {}, _Object$assign[sideY] = hasY ? '0' : '', _Object$assign[sideX] = hasX ? '0' : '', _Object$assign.transform = (win.devicePixelRatio || 1) < 2 ? "translate(" + x + "px, " + y + "px)" : "translate3d(" + x + "px, " + y + "px, 0)", _Object$assign)); + return Object.assign({}, commonStyles, (_Object$assign = {}, _Object$assign[sideY] = hasY ? '0' : '', _Object$assign[sideX] = hasX ? '0' : '', _Object$assign.transform = (win.devicePixelRatio || 1) <= 1 ? "translate(" + x + "px, " + y + "px)" : "translate3d(" + x + "px, " + y + "px, 0)", _Object$assign)); } return Object.assign({}, commonStyles, (_Object$assign2 = {}, _Object$assign2[sideY] = hasY ? y + "px" : '', _Object$assign2[sideX] = hasX ? x + "px" : '', _Object$assign2.transform = '', _Object$assign2)); } - function computeStyles(_ref4) { - var state = _ref4.state, - options = _ref4.options; + function computeStyles(_ref5) { + var state = _ref5.state, + options = _ref5.options; var _options$gpuAccelerat = options.gpuAcceleration, gpuAcceleration = _options$gpuAccelerat === void 0 ? true : _options$gpuAccelerat, _options$adaptive = options.adaptive, adaptive = _options$adaptive === void 0 ? true : _options$adaptive, _options$roundOffsets = options.roundOffsets, roundOffsets = _options$roundOffsets === void 0 ? true : _options$roundOffsets; - var commonStyles = { placement: getBasePlacement(state.placement), + variation: getVariation(state.placement), popper: state.elements.popper, popperRect: state.rects.popper, - gpuAcceleration: gpuAcceleration + gpuAcceleration: gpuAcceleration, + isFixed: state.options.strategy === 'fixed' }; if (state.modifiersData.popperOffsets != null) { @@ -2487,7 +2311,7 @@ } // eslint-disable-next-line import/no-unused-modules - var computeStyles$1 = { + const computeStyles$1 = { name: 'computeStyles', enabled: true, phase: 'beforeWrite', @@ -2534,7 +2358,7 @@ } // eslint-disable-next-line import/no-unused-modules - var eventListeners = { + const eventListeners = { name: 'eventListeners', enabled: true, phase: 'write', @@ -2586,31 +2410,21 @@ return getBoundingClientRect(getDocumentElement(element)).left + getWindowScroll(element).scrollLeft; } - function getViewportRect(element) { + function getViewportRect(element, strategy) { var win = getWindow(element); var html = getDocumentElement(element); var visualViewport = win.visualViewport; var width = html.clientWidth; var height = html.clientHeight; var x = 0; - var y = 0; // NB: This isn't supported on iOS <= 12. If the keyboard is open, the popper - // can be obscured underneath it. - // Also, `html.clientHeight` adds the bottom bar height in Safari iOS, even - // if it isn't open, so if this isn't available, the popper will be detected - // to overflow the bottom of the screen too early. + var y = 0; if (visualViewport) { width = visualViewport.width; - height = visualViewport.height; // Uses Layout Viewport (like Chrome; Safari does not currently) - // In Chrome, it returns a value very close to 0 (+/-) but contains rounding - // errors due to floating point numbers, so we need to check precision. - // Safari returns a number <= 0, usually < -1 when pinch-zoomed - // Feature detection fails in mobile emulation mode in Chrome. - // Math.abs(win.innerWidth / visualViewport.scale - visualViewport.width) < - // 0.001 - // Fallback here: "Not Safari" userAgent - - if (!/^((?!chrome|android).)*safari/i.test(navigator.userAgent)) { + height = visualViewport.height; + var layoutViewport = isLayoutViewport(); + + if (layoutViewport || !layoutViewport && strategy === 'fixed') { x = visualViewport.offsetLeft; y = visualViewport.offsetTop; } @@ -2704,8 +2518,8 @@ }); } - function getInnerBoundingClientRect(element) { - var rect = getBoundingClientRect(element); + function getInnerBoundingClientRect(element, strategy) { + var rect = getBoundingClientRect(element, false, strategy === 'fixed'); rect.top = rect.top + element.clientTop; rect.left = rect.left + element.clientLeft; rect.bottom = rect.top + element.clientHeight; @@ -2717,8 +2531,8 @@ return rect; } - function getClientRectFromMixedType(element, clippingParent) { - return clippingParent === viewport ? rectToClientRect(getViewportRect(element)) : isHTMLElement(clippingParent) ? getInnerBoundingClientRect(clippingParent) : rectToClientRect(getDocumentRect(getDocumentElement(element))); + function getClientRectFromMixedType(element, clippingParent, strategy) { + return clippingParent === viewport ? rectToClientRect(getViewportRect(element, strategy)) : isElement(clippingParent) ? getInnerBoundingClientRect(clippingParent, strategy) : rectToClientRect(getDocumentRect(getDocumentElement(element))); } // A "clipping parent" is an overflowable container with the characteristic of // clipping (or hiding) overflowing elements with a position different from // `initial` @@ -2741,18 +2555,18 @@ // clipping parents - function getClippingRect(element, boundary, rootBoundary) { + function getClippingRect(element, boundary, rootBoundary, strategy) { var mainClippingParents = boundary === 'clippingParents' ? getClippingParents(element) : [].concat(boundary); var clippingParents = [].concat(mainClippingParents, [rootBoundary]); var firstClippingParent = clippingParents[0]; var clippingRect = clippingParents.reduce(function (accRect, clippingParent) { - var rect = getClientRectFromMixedType(element, clippingParent); + var rect = getClientRectFromMixedType(element, clippingParent, strategy); accRect.top = max(rect.top, accRect.top); accRect.right = min(rect.right, accRect.right); accRect.bottom = min(rect.bottom, accRect.bottom); accRect.left = max(rect.left, accRect.left); return accRect; - }, getClientRectFromMixedType(element, firstClippingParent)); + }, getClientRectFromMixedType(element, firstClippingParent, strategy)); clippingRect.width = clippingRect.right - clippingRect.left; clippingRect.height = clippingRect.bottom - clippingRect.top; clippingRect.x = clippingRect.left; @@ -2760,10 +2574,6 @@ return clippingRect; } - function getVariation(placement) { - return placement.split('-')[1]; - } - function computeOffsets(_ref) { var reference = _ref.reference, element = _ref.element, @@ -2837,6 +2647,8 @@ var _options = options, _options$placement = _options.placement, placement = _options$placement === void 0 ? state.placement : _options$placement, + _options$strategy = _options.strategy, + strategy = _options$strategy === void 0 ? state.strategy : _options$strategy, _options$boundary = _options.boundary, boundary = _options$boundary === void 0 ? clippingParents : _options$boundary, _options$rootBoundary = _options.rootBoundary, @@ -2849,15 +2661,13 @@ padding = _options$padding === void 0 ? 0 : _options$padding; var paddingObject = mergePaddingObject(typeof padding !== 'number' ? padding : expandToHashMap(padding, basePlacements)); var altContext = elementContext === popper ? reference : popper; - var referenceElement = state.elements.reference; var popperRect = state.rects.popper; var element = state.elements[altBoundary ? altContext : elementContext]; - var clippingClientRect = getClippingRect(isElement(element) ? element : element.contextElement || getDocumentElement(state.elements.popper), boundary, rootBoundary); - var referenceClientRect = getBoundingClientRect(referenceElement); + var clippingClientRect = getClippingRect(isElement(element) ? element : element.contextElement || getDocumentElement(state.elements.popper), boundary, rootBoundary, strategy); + var referenceClientRect = getBoundingClientRect(state.elements.reference); var popperOffsets = computeOffsets({ reference: referenceClientRect, element: popperRect, - strategy: 'absolute', placement: placement }); var popperClientRect = rectToClientRect(Object.assign({}, popperRect, popperOffsets)); @@ -3053,7 +2863,7 @@ } // eslint-disable-next-line import/no-unused-modules - var flip$1 = { + const flip$1 = { name: 'flip', enabled: true, phase: 'main', @@ -3115,7 +2925,7 @@ } // eslint-disable-next-line import/no-unused-modules - var hide$1 = { + const hide$1 = { name: 'hide', enabled: true, phase: 'main', @@ -3167,7 +2977,7 @@ } // eslint-disable-next-line import/no-unused-modules - var offset$1 = { + const offset$1 = { name: 'offset', enabled: true, phase: 'main', @@ -3185,13 +2995,12 @@ state.modifiersData[name] = computeOffsets({ reference: state.rects.reference, element: state.rects.popper, - strategy: 'absolute', placement: state.placement }); } // eslint-disable-next-line import/no-unused-modules - var popperOffsets$1 = { + const popperOffsets$1 = { name: 'popperOffsets', enabled: true, phase: 'read', @@ -3236,6 +3045,14 @@ var tetherOffsetValue = typeof tetherOffset === 'function' ? tetherOffset(Object.assign({}, state.rects, { placement: state.placement })) : tetherOffset; + var normalizedTetherOffsetValue = typeof tetherOffsetValue === 'number' ? { + mainAxis: tetherOffsetValue, + altAxis: tetherOffsetValue + } : Object.assign({ + mainAxis: 0, + altAxis: 0 + }, tetherOffsetValue); + var offsetModifierState = state.modifiersData.offset ? state.modifiersData.offset[state.placement] : null; var data = { x: 0, y: 0 @@ -3245,13 +3062,15 @@ return; } - if (checkMainAxis || checkAltAxis) { + if (checkMainAxis) { + var _offsetModifierState$; + var mainSide = mainAxis === 'y' ? top : left; var altSide = mainAxis === 'y' ? bottom : right; var len = mainAxis === 'y' ? 'height' : 'width'; var offset = popperOffsets[mainAxis]; - var min$1 = popperOffsets[mainAxis] + overflow[mainSide]; - var max$1 = popperOffsets[mainAxis] - overflow[altSide]; + var min$1 = offset + overflow[mainSide]; + var max$1 = offset - overflow[altSide]; var additive = tether ? -popperRect[len] / 2 : 0; var minLen = variation === start ? referenceRect[len] : popperRect[len]; var maxLen = variation === start ? -popperRect[len] : -referenceRect[len]; // We need to include the arrow in the calculation so the arrow doesn't go @@ -3271,43 +3090,52 @@ // width or height) var arrowLen = within(0, referenceRect[len], arrowRect[len]); - var minOffset = isBasePlacement ? referenceRect[len] / 2 - additive - arrowLen - arrowPaddingMin - tetherOffsetValue : minLen - arrowLen - arrowPaddingMin - tetherOffsetValue; - var maxOffset = isBasePlacement ? -referenceRect[len] / 2 + additive + arrowLen + arrowPaddingMax + tetherOffsetValue : maxLen + arrowLen + arrowPaddingMax + tetherOffsetValue; + var minOffset = isBasePlacement ? referenceRect[len] / 2 - additive - arrowLen - arrowPaddingMin - normalizedTetherOffsetValue.mainAxis : minLen - arrowLen - arrowPaddingMin - normalizedTetherOffsetValue.mainAxis; + var maxOffset = isBasePlacement ? -referenceRect[len] / 2 + additive + arrowLen + arrowPaddingMax + normalizedTetherOffsetValue.mainAxis : maxLen + arrowLen + arrowPaddingMax + normalizedTetherOffsetValue.mainAxis; var arrowOffsetParent = state.elements.arrow && getOffsetParent(state.elements.arrow); var clientOffset = arrowOffsetParent ? mainAxis === 'y' ? arrowOffsetParent.clientTop || 0 : arrowOffsetParent.clientLeft || 0 : 0; - var offsetModifierValue = state.modifiersData.offset ? state.modifiersData.offset[state.placement][mainAxis] : 0; - var tetherMin = popperOffsets[mainAxis] + minOffset - offsetModifierValue - clientOffset; - var tetherMax = popperOffsets[mainAxis] + maxOffset - offsetModifierValue; + var offsetModifierValue = (_offsetModifierState$ = offsetModifierState == null ? void 0 : offsetModifierState[mainAxis]) != null ? _offsetModifierState$ : 0; + var tetherMin = offset + minOffset - offsetModifierValue - clientOffset; + var tetherMax = offset + maxOffset - offsetModifierValue; + var preventedOffset = within(tether ? min(min$1, tetherMin) : min$1, offset, tether ? max(max$1, tetherMax) : max$1); + popperOffsets[mainAxis] = preventedOffset; + data[mainAxis] = preventedOffset - offset; + } - if (checkMainAxis) { - var preventedOffset = within(tether ? min(min$1, tetherMin) : min$1, offset, tether ? max(max$1, tetherMax) : max$1); - popperOffsets[mainAxis] = preventedOffset; - data[mainAxis] = preventedOffset - offset; - } + if (checkAltAxis) { + var _offsetModifierState$2; - if (checkAltAxis) { - var _mainSide = mainAxis === 'x' ? top : left; + var _mainSide = mainAxis === 'x' ? top : left; - var _altSide = mainAxis === 'x' ? bottom : right; + var _altSide = mainAxis === 'x' ? bottom : right; - var _offset = popperOffsets[altAxis]; + var _offset = popperOffsets[altAxis]; - var _min = _offset + overflow[_mainSide]; + var _len = altAxis === 'y' ? 'height' : 'width'; - var _max = _offset - overflow[_altSide]; + var _min = _offset + overflow[_mainSide]; - var _preventedOffset = within(tether ? min(_min, tetherMin) : _min, _offset, tether ? max(_max, tetherMax) : _max); + var _max = _offset - overflow[_altSide]; - popperOffsets[altAxis] = _preventedOffset; - data[altAxis] = _preventedOffset - _offset; - } + var isOriginSide = [top, left].indexOf(basePlacement) !== -1; + + var _offsetModifierValue = (_offsetModifierState$2 = offsetModifierState == null ? void 0 : offsetModifierState[altAxis]) != null ? _offsetModifierState$2 : 0; + + var _tetherMin = isOriginSide ? _min : _offset - referenceRect[_len] - popperRect[_len] - _offsetModifierValue + normalizedTetherOffsetValue.altAxis; + + var _tetherMax = isOriginSide ? _offset + referenceRect[_len] + popperRect[_len] - _offsetModifierValue - normalizedTetherOffsetValue.altAxis : _max; + + var _preventedOffset = tether && isOriginSide ? withinMaxClamp(_tetherMin, _offset, _tetherMax) : within(tether ? _tetherMin : _min, _offset, tether ? _tetherMax : _max); + + popperOffsets[altAxis] = _preventedOffset; + data[altAxis] = _preventedOffset - _offset; } state.modifiersData[name] = data; } // eslint-disable-next-line import/no-unused-modules - var preventOverflow$1 = { + const preventOverflow$1 = { name: 'preventOverflow', enabled: true, phase: 'main', @@ -3332,8 +3160,8 @@ function isElementScaled(element) { var rect = element.getBoundingClientRect(); - var scaleX = rect.width / element.offsetWidth || 1; - var scaleY = rect.height / element.offsetHeight || 1; + var scaleX = round(rect.width) / element.offsetWidth || 1; + var scaleY = round(rect.height) / element.offsetHeight || 1; return scaleX !== 1 || scaleY !== 1; } // Returns the composite rect of an element relative to its offsetParent. // Composite means it takes into account transforms as well as layout. @@ -3347,7 +3175,7 @@ var isOffsetParentAnElement = isHTMLElement(offsetParent); var offsetParentIsScaled = isHTMLElement(offsetParent) && isElementScaled(offsetParent); var documentElement = getDocumentElement(offsetParent); - var rect = getBoundingClientRect(elementOrVirtualElement, offsetParentIsScaled); + var rect = getBoundingClientRect(elementOrVirtualElement, offsetParentIsScaled, isFixed); var scroll = { scrollLeft: 0, scrollTop: 0 @@ -3501,7 +3329,8 @@ var isDestroyed = false; var instance = { state: state, - setOptions: function setOptions(options) { + setOptions: function setOptions(setOptionsAction) { + var options = typeof setOptionsAction === 'function' ? setOptionsAction(state.options) : setOptionsAction; cleanupModifierEffects(); state.options = Object.assign({}, defaultOptions, state.options, options); state.scrollParents = { @@ -3514,8 +3343,7 @@ state.orderedModifiers = orderedModifiers.filter(function (m) { return m.enabled; - }); // Validate the provided modifiers so that the consumer will get warned - + }); runModifierEffects(); return instance.update(); }, @@ -3535,7 +3363,6 @@ // anymore if (!areValidElements(reference, popper)) { - return; } // Store the reference and popper rects to be read by modifiers @@ -3560,7 +3387,6 @@ }); for (var index = 0; index < state.orderedModifiers.length; index++) { - if (state.reset === true) { state.reset = false; index = -1; @@ -3598,7 +3424,6 @@ }; if (!areValidElements(reference, popper)) { - return instance; } @@ -3613,11 +3438,11 @@ // one. function runModifierEffects() { - state.orderedModifiers.forEach(function (_ref3) { - var name = _ref3.name, - _ref3$options = _ref3.options, - options = _ref3$options === void 0 ? {} : _ref3$options, - effect = _ref3.effect; + state.orderedModifiers.forEach(function (_ref) { + var name = _ref.name, + _ref$options = _ref.options, + options = _ref$options === void 0 ? {} : _ref$options, + effect = _ref.effect; if (typeof effect === 'function') { var cleanupFn = effect({ @@ -3656,86 +3481,87 @@ defaultModifiers: defaultModifiers }); // eslint-disable-next-line import/no-unused-modules - var Popper = /*#__PURE__*/Object.freeze({ + const Popper = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ __proto__: null, - popperGenerator: popperGenerator, - detectOverflow: detectOverflow, - createPopperBase: createPopper$2, - createPopper: createPopper, - createPopperLite: createPopper$1, - top: top, - bottom: bottom, - right: right, - left: left, - auto: auto, - basePlacements: basePlacements, - start: start, - end: end, - clippingParents: clippingParents, - viewport: viewport, - popper: popper, - reference: reference, - variationPlacements: variationPlacements, - placements: placements, - beforeRead: beforeRead, - read: read, - afterRead: afterRead, - beforeMain: beforeMain, - main: main, - afterMain: afterMain, - beforeWrite: beforeWrite, - write: write, - afterWrite: afterWrite, - modifierPhases: modifierPhases, + afterMain, + afterRead, + afterWrite, applyStyles: applyStyles$1, arrow: arrow$1, + auto, + basePlacements, + beforeMain, + beforeRead, + beforeWrite, + bottom, + clippingParents, computeStyles: computeStyles$1, - eventListeners: eventListeners, + createPopper, + createPopperBase: createPopper$2, + createPopperLite: createPopper$1, + detectOverflow, + end, + eventListeners, flip: flip$1, hide: hide$1, + left, + main, + modifierPhases, offset: offset$1, + placements, + popper, + popperGenerator, popperOffsets: popperOffsets$1, - preventOverflow: preventOverflow$1 - }); + preventOverflow: preventOverflow$1, + read, + reference, + right, + start, + top, + variationPlacements, + viewport, + write + }, Symbol.toStringTag, { value: 'Module' })); /** * -------------------------------------------------------------------------- - * Bootstrap (v5.1.0): dropdown.js + * Bootstrap dropdown.js * Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE) * -------------------------------------------------------------------------- */ + + /** - * ------------------------------------------------------------------------ * Constants - * ------------------------------------------------------------------------ */ - const NAME$9 = 'dropdown'; - const DATA_KEY$8 = 'bs.dropdown'; - const EVENT_KEY$8 = `.${DATA_KEY$8}`; - const DATA_API_KEY$4 = '.data-api'; + const NAME$a = 'dropdown'; + const DATA_KEY$6 = 'bs.dropdown'; + const EVENT_KEY$6 = `.${DATA_KEY$6}`; + const DATA_API_KEY$3 = '.data-api'; const ESCAPE_KEY$2 = 'Escape'; - const SPACE_KEY = 'Space'; const TAB_KEY$1 = 'Tab'; - const ARROW_UP_KEY = 'ArrowUp'; - const ARROW_DOWN_KEY = 'ArrowDown'; + const ARROW_UP_KEY$1 = 'ArrowUp'; + const ARROW_DOWN_KEY$1 = 'ArrowDown'; const RIGHT_MOUSE_BUTTON = 2; // MouseEvent.button value for the secondary button, usually the right button - const REGEXP_KEYDOWN = new RegExp(`${ARROW_UP_KEY}|${ARROW_DOWN_KEY}|${ESCAPE_KEY$2}`); - const EVENT_HIDE$4 = `hide${EVENT_KEY$8}`; - const EVENT_HIDDEN$4 = `hidden${EVENT_KEY$8}`; - const EVENT_SHOW$4 = `show${EVENT_KEY$8}`; - const EVENT_SHOWN$4 = `shown${EVENT_KEY$8}`; - const EVENT_CLICK_DATA_API$3 = `click${EVENT_KEY$8}${DATA_API_KEY$4}`; - const EVENT_KEYDOWN_DATA_API = `keydown${EVENT_KEY$8}${DATA_API_KEY$4}`; - const EVENT_KEYUP_DATA_API = `keyup${EVENT_KEY$8}${DATA_API_KEY$4}`; + const EVENT_HIDE$5 = `hide${EVENT_KEY$6}`; + const EVENT_HIDDEN$5 = `hidden${EVENT_KEY$6}`; + const EVENT_SHOW$5 = `show${EVENT_KEY$6}`; + const EVENT_SHOWN$5 = `shown${EVENT_KEY$6}`; + const EVENT_CLICK_DATA_API$3 = `click${EVENT_KEY$6}${DATA_API_KEY$3}`; + const EVENT_KEYDOWN_DATA_API = `keydown${EVENT_KEY$6}${DATA_API_KEY$3}`; + const EVENT_KEYUP_DATA_API = `keyup${EVENT_KEY$6}${DATA_API_KEY$3}`; const CLASS_NAME_SHOW$6 = 'show'; const CLASS_NAME_DROPUP = 'dropup'; const CLASS_NAME_DROPEND = 'dropend'; const CLASS_NAME_DROPSTART = 'dropstart'; - const CLASS_NAME_NAVBAR = 'navbar'; - const SELECTOR_DATA_TOGGLE$3 = '[data-bs-toggle="dropdown"]'; + const CLASS_NAME_DROPUP_CENTER = 'dropup-center'; + const CLASS_NAME_DROPDOWN_CENTER = 'dropdown-center'; + const SELECTOR_DATA_TOGGLE$3 = '[data-bs-toggle="dropdown"]:not(.disabled):not(:disabled)'; + const SELECTOR_DATA_TOGGLE_SHOWN = `${SELECTOR_DATA_TOGGLE$3}.${CLASS_NAME_SHOW$6}`; const SELECTOR_MENU = '.dropdown-menu'; + const SELECTOR_NAVBAR = '.navbar'; const SELECTOR_NAVBAR_NAV = '.navbar-nav'; const SELECTOR_VISIBLE_ITEMS = '.dropdown-menu .dropdown-item:not(.disabled):not(:disabled)'; const PLACEMENT_TOP = isRTL() ? 'top-end' : 'top-start'; @@ -3744,241 +3570,190 @@ const PLACEMENT_BOTTOMEND = isRTL() ? 'bottom-start' : 'bottom-end'; const PLACEMENT_RIGHT = isRTL() ? 'left-start' : 'right-start'; const PLACEMENT_LEFT = isRTL() ? 'right-start' : 'left-start'; - const Default$8 = { - offset: [0, 2], + const PLACEMENT_TOPCENTER = 'top'; + const PLACEMENT_BOTTOMCENTER = 'bottom'; + const Default$9 = { + autoClose: true, boundary: 'clippingParents', - reference: 'toggle', display: 'dynamic', + offset: [0, 2], popperConfig: null, - autoClose: true + reference: 'toggle' }; - const DefaultType$8 = { - offset: '(array|string|function)', + const DefaultType$9 = { + autoClose: '(boolean|string)', boundary: '(string|element)', - reference: '(string|element|object)', display: 'string', + offset: '(array|string|function)', popperConfig: '(null|object|function)', - autoClose: '(boolean|string)' + reference: '(string|element|object)' }; + /** - * ------------------------------------------------------------------------ - * Class Definition - * ------------------------------------------------------------------------ + * Class definition */ class Dropdown extends BaseComponent { constructor(element, config) { - super(element); + super(element, config); this._popper = null; - this._config = this._getConfig(config); - this._menu = this._getMenuElement(); + this._parent = this._element.parentNode; // dropdown wrapper + // TODO: v6 revert #37011 & change markup https://getbootstrap.com/docs/5.3/forms/input-group/ + this._menu = SelectorEngine.next(this._element, SELECTOR_MENU)[0] || SelectorEngine.prev(this._element, SELECTOR_MENU)[0] || SelectorEngine.findOne(SELECTOR_MENU, this._parent); this._inNavbar = this._detectNavbar(); - } // Getters - + } + // Getters static get Default() { - return Default$8; + return Default$9; } - static get DefaultType() { - return DefaultType$8; + return DefaultType$9; } - static get NAME() { - return NAME$9; - } // Public - + return NAME$a; + } + // Public toggle() { return this._isShown() ? this.hide() : this.show(); } - show() { - if (isDisabled(this._element) || this._isShown(this._menu)) { + if (isDisabled(this._element) || this._isShown()) { return; } - const relatedTarget = { relatedTarget: this._element }; - const showEvent = EventHandler.trigger(this._element, EVENT_SHOW$4, relatedTarget); - + const showEvent = EventHandler.trigger(this._element, EVENT_SHOW$5, relatedTarget); if (showEvent.defaultPrevented) { return; } + this._createPopper(); - const parent = Dropdown.getParentFromElement(this._element); // Totally disable Popper for Dropdowns in Navbar - - if (this._inNavbar) { - Manipulator.setDataAttribute(this._menu, 'popper', 'none'); - } else { - this._createPopper(parent); - } // If this is a touch-enabled device we add extra + // If this is a touch-enabled device we add extra // empty mouseover listeners to the body's immediate children; // only needed because of broken event delegation on iOS // https://www.quirksmode.org/blog/archives/2014/02/mouse_event_bub.html - - - if ('ontouchstart' in document.documentElement && !parent.closest(SELECTOR_NAVBAR_NAV)) { - [].concat(...document.body.children).forEach(elem => EventHandler.on(elem, 'mouseover', noop)); + if ('ontouchstart' in document.documentElement && !this._parent.closest(SELECTOR_NAVBAR_NAV)) { + for (const element of [].concat(...document.body.children)) { + EventHandler.on(element, 'mouseover', noop); + } } - this._element.focus(); - this._element.setAttribute('aria-expanded', true); - this._menu.classList.add(CLASS_NAME_SHOW$6); - this._element.classList.add(CLASS_NAME_SHOW$6); - - EventHandler.trigger(this._element, EVENT_SHOWN$4, relatedTarget); + EventHandler.trigger(this._element, EVENT_SHOWN$5, relatedTarget); } - hide() { - if (isDisabled(this._element) || !this._isShown(this._menu)) { + if (isDisabled(this._element) || !this._isShown()) { return; } - const relatedTarget = { relatedTarget: this._element }; - this._completeHide(relatedTarget); } - dispose() { if (this._popper) { this._popper.destroy(); } - super.dispose(); } - update() { this._inNavbar = this._detectNavbar(); - if (this._popper) { this._popper.update(); } - } // Private - + } + // Private _completeHide(relatedTarget) { - const hideEvent = EventHandler.trigger(this._element, EVENT_HIDE$4, relatedTarget); - + const hideEvent = EventHandler.trigger(this._element, EVENT_HIDE$5, relatedTarget); if (hideEvent.defaultPrevented) { return; - } // If this is a touch-enabled device we remove the extra - // empty mouseover listeners we added for iOS support - + } + // If this is a touch-enabled device we remove the extra + // empty mouseover listeners we added for iOS support if ('ontouchstart' in document.documentElement) { - [].concat(...document.body.children).forEach(elem => EventHandler.off(elem, 'mouseover', noop)); + for (const element of [].concat(...document.body.children)) { + EventHandler.off(element, 'mouseover', noop); + } } - if (this._popper) { this._popper.destroy(); } - this._menu.classList.remove(CLASS_NAME_SHOW$6); - this._element.classList.remove(CLASS_NAME_SHOW$6); - this._element.setAttribute('aria-expanded', 'false'); - Manipulator.removeDataAttribute(this._menu, 'popper'); - EventHandler.trigger(this._element, EVENT_HIDDEN$4, relatedTarget); + EventHandler.trigger(this._element, EVENT_HIDDEN$5, relatedTarget); } - _getConfig(config) { - config = { ...this.constructor.Default, - ...Manipulator.getDataAttributes(this._element), - ...config - }; - typeCheckConfig(NAME$9, config, this.constructor.DefaultType); - + config = super._getConfig(config); if (typeof config.reference === 'object' && !isElement$1(config.reference) && typeof config.reference.getBoundingClientRect !== 'function') { // Popper virtual elements require a getBoundingClientRect method - throw new TypeError(`${NAME$9.toUpperCase()}: Option "reference" provided type "object" without a required "getBoundingClientRect" method.`); + throw new TypeError(`${NAME$a.toUpperCase()}: Option "reference" provided type "object" without a required "getBoundingClientRect" method.`); } - return config; } - - _createPopper(parent) { + _createPopper() { if (typeof Popper === 'undefined') { - throw new TypeError('Bootstrap\'s dropdowns require Popper (https://popper.js.org)'); + throw new TypeError('Bootstrap\'s dropdowns require Popper (https://popper.js.org/docs/v2/)'); } - let referenceElement = this._element; - if (this._config.reference === 'parent') { - referenceElement = parent; + referenceElement = this._parent; } else if (isElement$1(this._config.reference)) { referenceElement = getElement(this._config.reference); } else if (typeof this._config.reference === 'object') { referenceElement = this._config.reference; } - const popperConfig = this._getPopperConfig(); - - const isDisplayStatic = popperConfig.modifiers.find(modifier => modifier.name === 'applyStyles' && modifier.enabled === false); this._popper = createPopper(referenceElement, this._menu, popperConfig); - - if (isDisplayStatic) { - Manipulator.setDataAttribute(this._menu, 'popper', 'static'); - } - } - - _isShown(element = this._element) { - return element.classList.contains(CLASS_NAME_SHOW$6); } - - _getMenuElement() { - return SelectorEngine.next(this._element, SELECTOR_MENU)[0]; + _isShown() { + return this._menu.classList.contains(CLASS_NAME_SHOW$6); } - _getPlacement() { - const parentDropdown = this._element.parentNode; - + const parentDropdown = this._parent; if (parentDropdown.classList.contains(CLASS_NAME_DROPEND)) { return PLACEMENT_RIGHT; } - if (parentDropdown.classList.contains(CLASS_NAME_DROPSTART)) { return PLACEMENT_LEFT; - } // We need to trim the value because custom properties can also include spaces - + } + if (parentDropdown.classList.contains(CLASS_NAME_DROPUP_CENTER)) { + return PLACEMENT_TOPCENTER; + } + if (parentDropdown.classList.contains(CLASS_NAME_DROPDOWN_CENTER)) { + return PLACEMENT_BOTTOMCENTER; + } + // We need to trim the value because custom properties can also include spaces const isEnd = getComputedStyle(this._menu).getPropertyValue('--bs-position').trim() === 'end'; - if (parentDropdown.classList.contains(CLASS_NAME_DROPUP)) { return isEnd ? PLACEMENT_TOPEND : PLACEMENT_TOP; } - return isEnd ? PLACEMENT_BOTTOMEND : PLACEMENT_BOTTOM; } - _detectNavbar() { - return this._element.closest(`.${CLASS_NAME_NAVBAR}`) !== null; + return this._element.closest(SELECTOR_NAVBAR) !== null; } - _getOffset() { const { offset } = this._config; - if (typeof offset === 'string') { - return offset.split(',').map(val => Number.parseInt(val, 10)); + return offset.split(',').map(value => Number.parseInt(value, 10)); } - if (typeof offset === 'function') { return popperData => offset(popperData, this._element); } - return offset; } - _getPopperConfig() { const defaultBsPopperConfig = { placement: this._getPlacement(), @@ -3993,156 +3768,114 @@ offset: this._getOffset() } }] - }; // Disable Popper if we have a static display + }; - if (this._config.display === 'static') { + // Disable Popper if we have a static display or Dropdown is in Navbar + if (this._inNavbar || this._config.display === 'static') { + Manipulator.setDataAttribute(this._menu, 'popper', 'static'); // TODO: v6 remove defaultBsPopperConfig.modifiers = [{ name: 'applyStyles', enabled: false }]; } - - return { ...defaultBsPopperConfig, - ...(typeof this._config.popperConfig === 'function' ? this._config.popperConfig(defaultBsPopperConfig) : this._config.popperConfig) + return { + ...defaultBsPopperConfig, + ...execute(this._config.popperConfig, [undefined, defaultBsPopperConfig]) }; } - _selectMenuItem({ key, target }) { - const items = SelectorEngine.find(SELECTOR_VISIBLE_ITEMS, this._menu).filter(isVisible); - + const items = SelectorEngine.find(SELECTOR_VISIBLE_ITEMS, this._menu).filter(element => isVisible(element)); if (!items.length) { return; - } // if target isn't included in items (e.g. when expanding the dropdown) - // allow cycling to get the last item in case key equals ARROW_UP_KEY - - - getNextActiveElement(items, target, key === ARROW_DOWN_KEY, !items.includes(target)).focus(); - } // Static + } + // if target isn't included in items (e.g. when expanding the dropdown) + // allow cycling to get the last item in case key equals ARROW_UP_KEY + getNextActiveElement(items, target, key === ARROW_DOWN_KEY$1, !items.includes(target)).focus(); + } + // Static static jQueryInterface(config) { return this.each(function () { const data = Dropdown.getOrCreateInstance(this, config); - if (typeof config !== 'string') { return; } - if (typeof data[config] === 'undefined') { throw new TypeError(`No method named "${config}"`); } - data[config](); }); } - static clearMenus(event) { - if (event && (event.button === RIGHT_MOUSE_BUTTON || event.type === 'keyup' && event.key !== TAB_KEY$1)) { + if (event.button === RIGHT_MOUSE_BUTTON || event.type === 'keyup' && event.key !== TAB_KEY$1) { return; } - - const toggles = SelectorEngine.find(SELECTOR_DATA_TOGGLE$3); - - for (let i = 0, len = toggles.length; i < len; i++) { - const context = Dropdown.getInstance(toggles[i]); - + const openToggles = SelectorEngine.find(SELECTOR_DATA_TOGGLE_SHOWN); + for (const toggle of openToggles) { + const context = Dropdown.getInstance(toggle); if (!context || context._config.autoClose === false) { continue; } - - if (!context._isShown()) { + const composedPath = event.composedPath(); + const isMenuTarget = composedPath.includes(context._menu); + if (composedPath.includes(context._element) || context._config.autoClose === 'inside' && !isMenuTarget || context._config.autoClose === 'outside' && isMenuTarget) { continue; } + // Tab navigation through the dropdown menu or events from contained inputs shouldn't close the menu + if (context._menu.contains(event.target) && (event.type === 'keyup' && event.key === TAB_KEY$1 || /input|select|option|textarea|form/i.test(event.target.tagName))) { + continue; + } const relatedTarget = { relatedTarget: context._element }; - - if (event) { - const composedPath = event.composedPath(); - const isMenuTarget = composedPath.includes(context._menu); - - if (composedPath.includes(context._element) || context._config.autoClose === 'inside' && !isMenuTarget || context._config.autoClose === 'outside' && isMenuTarget) { - continue; - } // Tab navigation through the dropdown menu or events from contained inputs shouldn't close the menu - - - if (context._menu.contains(event.target) && (event.type === 'keyup' && event.key === TAB_KEY$1 || /input|select|option|textarea|form/i.test(event.target.tagName))) { - continue; - } - - if (event.type === 'click') { - relatedTarget.clickEvent = event; - } + if (event.type === 'click') { + relatedTarget.clickEvent = event; } - context._completeHide(relatedTarget); } } - - static getParentFromElement(element) { - return getElementFromSelector(element) || element.parentNode; - } - static dataApiKeydownHandler(event) { - // If not input/textarea: - // - And not a key in REGEXP_KEYDOWN => not a dropdown command - // If input/textarea: - // - If space key => not a dropdown command - // - If key is other than escape - // - If key is not up or down => not a dropdown command - // - If trigger inside the menu => not a dropdown command - if (/input|textarea/i.test(event.target.tagName) ? event.key === SPACE_KEY || event.key !== ESCAPE_KEY$2 && (event.key !== ARROW_DOWN_KEY && event.key !== ARROW_UP_KEY || event.target.closest(SELECTOR_MENU)) : !REGEXP_KEYDOWN.test(event.key)) { - return; - } - - const isActive = this.classList.contains(CLASS_NAME_SHOW$6); + // If not an UP | DOWN | ESCAPE key => not a dropdown command + // If input/textarea && if key is other than ESCAPE => not a dropdown command - if (!isActive && event.key === ESCAPE_KEY$2) { + const isInput = /input|textarea/i.test(event.target.tagName); + const isEscapeEvent = event.key === ESCAPE_KEY$2; + const isUpOrDownEvent = [ARROW_UP_KEY$1, ARROW_DOWN_KEY$1].includes(event.key); + if (!isUpOrDownEvent && !isEscapeEvent) { return; } - - event.preventDefault(); - event.stopPropagation(); - - if (isDisabled(this)) { + if (isInput && !isEscapeEvent) { return; } + event.preventDefault(); - const getToggleButton = this.matches(SELECTOR_DATA_TOGGLE$3) ? this : SelectorEngine.prev(this, SELECTOR_DATA_TOGGLE$3)[0]; + // TODO: v6 revert #37011 & change markup https://getbootstrap.com/docs/5.3/forms/input-group/ + const getToggleButton = this.matches(SELECTOR_DATA_TOGGLE$3) ? this : SelectorEngine.prev(this, SELECTOR_DATA_TOGGLE$3)[0] || SelectorEngine.next(this, SELECTOR_DATA_TOGGLE$3)[0] || SelectorEngine.findOne(SELECTOR_DATA_TOGGLE$3, event.delegateTarget.parentNode); const instance = Dropdown.getOrCreateInstance(getToggleButton); - - if (event.key === ESCAPE_KEY$2) { - instance.hide(); - return; - } - - if (event.key === ARROW_UP_KEY || event.key === ARROW_DOWN_KEY) { - if (!isActive) { - instance.show(); - } - + if (isUpOrDownEvent) { + event.stopPropagation(); + instance.show(); instance._selectMenuItem(event); - return; } - - if (!isActive || event.key === SPACE_KEY) { - Dropdown.clearMenus(); + if (instance._isShown()) { + // else is escape and we check if it is shown + event.stopPropagation(); + instance.hide(); + getToggleButton.focus(); } } - } + /** - * ------------------------------------------------------------------------ - * Data Api implementation - * ------------------------------------------------------------------------ + * Data API implementation */ - EventHandler.on(document, EVENT_KEYDOWN_DATA_API, SELECTOR_DATA_TOGGLE$3, Dropdown.dataApiKeydownHandler); EventHandler.on(document, EVENT_KEYDOWN_DATA_API, SELECTOR_MENU, Dropdown.dataApiKeydownHandler); EventHandler.on(document, EVENT_CLICK_DATA_API$3, Dropdown.clearMenus); @@ -4151,319 +3884,219 @@ event.preventDefault(); Dropdown.getOrCreateInstance(this).toggle(); }); + /** - * ------------------------------------------------------------------------ * jQuery - * ------------------------------------------------------------------------ - * add .Dropdown to jQuery only if jQuery is present */ defineJQueryPlugin(Dropdown); /** * -------------------------------------------------------------------------- - * Bootstrap (v5.1.0): util/scrollBar.js + * Bootstrap util/backdrop.js * Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE) * -------------------------------------------------------------------------- - */ - const SELECTOR_FIXED_CONTENT = '.fixed-top, .fixed-bottom, .is-fixed, .sticky-top'; - const SELECTOR_STICKY_CONTENT = '.sticky-top'; - - class ScrollBarHelper { - constructor() { - this._element = document.body; - } - - getWidth() { - // https://developer.mozilla.org/en-US/docs/Web/API/Window/innerWidth#usage_notes - const documentWidth = document.documentElement.clientWidth; - return Math.abs(window.innerWidth - documentWidth); - } - - hide() { - const width = this.getWidth(); - - this._disableOverFlow(); // give padding to element to balance the hidden scrollbar width - - - this._setElementAttributes(this._element, 'paddingRight', calculatedValue => calculatedValue + width); // trick: We adjust positive paddingRight and negative marginRight to sticky-top elements to keep showing fullwidth - - - this._setElementAttributes(SELECTOR_FIXED_CONTENT, 'paddingRight', calculatedValue => calculatedValue + width); - - this._setElementAttributes(SELECTOR_STICKY_CONTENT, 'marginRight', calculatedValue => calculatedValue - width); - } - - _disableOverFlow() { - this._saveInitialAttribute(this._element, 'overflow'); - - this._element.style.overflow = 'hidden'; - } - - _setElementAttributes(selector, styleProp, callback) { - const scrollbarWidth = this.getWidth(); - - const manipulationCallBack = element => { - if (element !== this._element && window.innerWidth > element.clientWidth + scrollbarWidth) { - return; - } - - this._saveInitialAttribute(element, styleProp); - - const calculatedValue = window.getComputedStyle(element)[styleProp]; - element.style[styleProp] = `${callback(Number.parseFloat(calculatedValue))}px`; - }; - - this._applyManipulationCallback(selector, manipulationCallBack); - } - - reset() { - this._resetElementAttributes(this._element, 'overflow'); - - this._resetElementAttributes(this._element, 'paddingRight'); - - this._resetElementAttributes(SELECTOR_FIXED_CONTENT, 'paddingRight'); - - this._resetElementAttributes(SELECTOR_STICKY_CONTENT, 'marginRight'); - } - - _saveInitialAttribute(element, styleProp) { - const actualValue = element.style[styleProp]; - - if (actualValue) { - Manipulator.setDataAttribute(element, styleProp, actualValue); - } - } - - _resetElementAttributes(selector, styleProp) { - const manipulationCallBack = element => { - const value = Manipulator.getDataAttribute(element, styleProp); - - if (typeof value === 'undefined') { - element.style.removeProperty(styleProp); - } else { - Manipulator.removeDataAttribute(element, styleProp); - element.style[styleProp] = value; - } - }; - - this._applyManipulationCallback(selector, manipulationCallBack); - } - - _applyManipulationCallback(selector, callBack) { - if (isElement$1(selector)) { - callBack(selector); - } else { - SelectorEngine.find(selector, this._element).forEach(callBack); - } - } - - isOverflowing() { - return this.getWidth() > 0; - } + */ - } /** - * -------------------------------------------------------------------------- - * Bootstrap (v5.1.0): util/backdrop.js - * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) - * -------------------------------------------------------------------------- + * Constants */ - const Default$7 = { + + const NAME$9 = 'backdrop'; + const CLASS_NAME_FADE$4 = 'fade'; + const CLASS_NAME_SHOW$5 = 'show'; + const EVENT_MOUSEDOWN = `mousedown.bs.${NAME$9}`; + const Default$8 = { className: 'modal-backdrop', + clickCallback: null, + isAnimated: false, isVisible: true, // if false, we use the backdrop helper without adding any element to the dom - isAnimated: false, - rootElement: 'body', - // give the choice to place backdrop under different elements - clickCallback: null + rootElement: 'body' // give the choice to place backdrop under different elements }; - const DefaultType$7 = { + const DefaultType$8 = { className: 'string', - isVisible: 'boolean', + clickCallback: '(function|null)', isAnimated: 'boolean', - rootElement: '(element|string)', - clickCallback: '(function|null)' + isVisible: 'boolean', + rootElement: '(element|string)' }; - const NAME$8 = 'backdrop'; - const CLASS_NAME_FADE$4 = 'fade'; - const CLASS_NAME_SHOW$5 = 'show'; - const EVENT_MOUSEDOWN = `mousedown.bs.${NAME$8}`; - class Backdrop { + /** + * Class definition + */ + + class Backdrop extends Config { constructor(config) { + super(); this._config = this._getConfig(config); this._isAppended = false; this._element = null; } + // Getters + static get Default() { + return Default$8; + } + static get DefaultType() { + return DefaultType$8; + } + static get NAME() { + return NAME$9; + } + + // Public show(callback) { if (!this._config.isVisible) { execute(callback); return; } - this._append(); - + const element = this._getElement(); if (this._config.isAnimated) { - reflow(this._getElement()); + reflow(element); } - - this._getElement().classList.add(CLASS_NAME_SHOW$5); - + element.classList.add(CLASS_NAME_SHOW$5); this._emulateAnimation(() => { execute(callback); }); } - hide(callback) { if (!this._config.isVisible) { execute(callback); return; } - this._getElement().classList.remove(CLASS_NAME_SHOW$5); - this._emulateAnimation(() => { this.dispose(); execute(callback); }); - } // Private - + } + dispose() { + if (!this._isAppended) { + return; + } + EventHandler.off(this._element, EVENT_MOUSEDOWN); + this._element.remove(); + this._isAppended = false; + } + // Private _getElement() { if (!this._element) { const backdrop = document.createElement('div'); backdrop.className = this._config.className; - if (this._config.isAnimated) { backdrop.classList.add(CLASS_NAME_FADE$4); } - this._element = backdrop; } - return this._element; } - - _getConfig(config) { - config = { ...Default$7, - ...(typeof config === 'object' ? config : {}) - }; // use getElement() with the default "body" to get a fresh Element on each instantiation - + _configAfterMerge(config) { + // use getElement() with the default "body" to get a fresh Element on each instantiation config.rootElement = getElement(config.rootElement); - typeCheckConfig(NAME$8, config, DefaultType$7); return config; } - _append() { if (this._isAppended) { return; } - - this._config.rootElement.append(this._getElement()); - - EventHandler.on(this._getElement(), EVENT_MOUSEDOWN, () => { + const element = this._getElement(); + this._config.rootElement.append(element); + EventHandler.on(element, EVENT_MOUSEDOWN, () => { execute(this._config.clickCallback); }); this._isAppended = true; } - - dispose() { - if (!this._isAppended) { - return; - } - - EventHandler.off(this._element, EVENT_MOUSEDOWN); - - this._element.remove(); - - this._isAppended = false; - } - _emulateAnimation(callback) { executeAfterTransition(callback, this._getElement(), this._config.isAnimated); } - } /** * -------------------------------------------------------------------------- - * Bootstrap (v5.1.0): util/focustrap.js - * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) + * Bootstrap util/focustrap.js + * Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE) * -------------------------------------------------------------------------- */ - const Default$6 = { - trapElement: null, - // The element to trap focus inside of - autofocus: true - }; - const DefaultType$6 = { - trapElement: 'element', - autofocus: 'boolean' - }; - const NAME$7 = 'focustrap'; - const DATA_KEY$7 = 'bs.focustrap'; - const EVENT_KEY$7 = `.${DATA_KEY$7}`; - const EVENT_FOCUSIN$1 = `focusin${EVENT_KEY$7}`; - const EVENT_KEYDOWN_TAB = `keydown.tab${EVENT_KEY$7}`; + + + /** + * Constants + */ + + const NAME$8 = 'focustrap'; + const DATA_KEY$5 = 'bs.focustrap'; + const EVENT_KEY$5 = `.${DATA_KEY$5}`; + const EVENT_FOCUSIN$2 = `focusin${EVENT_KEY$5}`; + const EVENT_KEYDOWN_TAB = `keydown.tab${EVENT_KEY$5}`; const TAB_KEY = 'Tab'; const TAB_NAV_FORWARD = 'forward'; const TAB_NAV_BACKWARD = 'backward'; + const Default$7 = { + autofocus: true, + trapElement: null // The element to trap focus inside of + }; + const DefaultType$7 = { + autofocus: 'boolean', + trapElement: 'element' + }; + + /** + * Class definition + */ - class FocusTrap { + class FocusTrap extends Config { constructor(config) { + super(); this._config = this._getConfig(config); this._isActive = false; this._lastTabNavDirection = null; } - activate() { - const { - trapElement, - autofocus - } = this._config; + // Getters + static get Default() { + return Default$7; + } + static get DefaultType() { + return DefaultType$7; + } + static get NAME() { + return NAME$8; + } + // Public + activate() { if (this._isActive) { return; } - - if (autofocus) { - trapElement.focus(); + if (this._config.autofocus) { + this._config.trapElement.focus(); } - - EventHandler.off(document, EVENT_KEY$7); // guard against infinite focus loop - - EventHandler.on(document, EVENT_FOCUSIN$1, event => this._handleFocusin(event)); + EventHandler.off(document, EVENT_KEY$5); // guard against infinite focus loop + EventHandler.on(document, EVENT_FOCUSIN$2, event => this._handleFocusin(event)); EventHandler.on(document, EVENT_KEYDOWN_TAB, event => this._handleKeydown(event)); this._isActive = true; } - deactivate() { if (!this._isActive) { return; } - this._isActive = false; - EventHandler.off(document, EVENT_KEY$7); - } // Private - + EventHandler.off(document, EVENT_KEY$5); + } + // Private _handleFocusin(event) { - const { - target - } = event; const { trapElement } = this._config; - - if (target === document || target === trapElement || trapElement.contains(target)) { + if (event.target === document || event.target === trapElement || trapElement.contains(event.target)) { return; } - const elements = SelectorEngine.focusableChildren(trapElement); - if (elements.length === 0) { trapElement.focus(); } else if (this._lastTabNavDirection === TAB_NAV_BACKWARD) { @@ -4472,747 +4105,657 @@ elements[0].focus(); } } - _handleKeydown(event) { if (event.key !== TAB_KEY) { return; } - this._lastTabNavDirection = event.shiftKey ? TAB_NAV_BACKWARD : TAB_NAV_FORWARD; } + } - _getConfig(config) { - config = { ...Default$6, - ...(typeof config === 'object' ? config : {}) - }; - typeCheckConfig(NAME$7, config, DefaultType$6); - return config; + /** + * -------------------------------------------------------------------------- + * Bootstrap util/scrollBar.js + * Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE) + * -------------------------------------------------------------------------- + */ + + + /** + * Constants + */ + + const SELECTOR_FIXED_CONTENT = '.fixed-top, .fixed-bottom, .is-fixed, .sticky-top'; + const SELECTOR_STICKY_CONTENT = '.sticky-top'; + const PROPERTY_PADDING = 'padding-right'; + const PROPERTY_MARGIN = 'margin-right'; + + /** + * Class definition + */ + + class ScrollBarHelper { + constructor() { + this._element = document.body; } + // Public + getWidth() { + // https://developer.mozilla.org/en-US/docs/Web/API/Window/innerWidth#usage_notes + const documentWidth = document.documentElement.clientWidth; + return Math.abs(window.innerWidth - documentWidth); + } + hide() { + const width = this.getWidth(); + this._disableOverFlow(); + // give padding to element to balance the hidden scrollbar width + this._setElementAttributes(this._element, PROPERTY_PADDING, calculatedValue => calculatedValue + width); + // trick: We adjust positive paddingRight and negative marginRight to sticky-top elements to keep showing fullwidth + this._setElementAttributes(SELECTOR_FIXED_CONTENT, PROPERTY_PADDING, calculatedValue => calculatedValue + width); + this._setElementAttributes(SELECTOR_STICKY_CONTENT, PROPERTY_MARGIN, calculatedValue => calculatedValue - width); + } + reset() { + this._resetElementAttributes(this._element, 'overflow'); + this._resetElementAttributes(this._element, PROPERTY_PADDING); + this._resetElementAttributes(SELECTOR_FIXED_CONTENT, PROPERTY_PADDING); + this._resetElementAttributes(SELECTOR_STICKY_CONTENT, PROPERTY_MARGIN); + } + isOverflowing() { + return this.getWidth() > 0; + } + + // Private + _disableOverFlow() { + this._saveInitialAttribute(this._element, 'overflow'); + this._element.style.overflow = 'hidden'; + } + _setElementAttributes(selector, styleProperty, callback) { + const scrollbarWidth = this.getWidth(); + const manipulationCallBack = element => { + if (element !== this._element && window.innerWidth > element.clientWidth + scrollbarWidth) { + return; + } + this._saveInitialAttribute(element, styleProperty); + const calculatedValue = window.getComputedStyle(element).getPropertyValue(styleProperty); + element.style.setProperty(styleProperty, `${callback(Number.parseFloat(calculatedValue))}px`); + }; + this._applyManipulationCallback(selector, manipulationCallBack); + } + _saveInitialAttribute(element, styleProperty) { + const actualValue = element.style.getPropertyValue(styleProperty); + if (actualValue) { + Manipulator.setDataAttribute(element, styleProperty, actualValue); + } + } + _resetElementAttributes(selector, styleProperty) { + const manipulationCallBack = element => { + const value = Manipulator.getDataAttribute(element, styleProperty); + // We only want to remove the property if the value is `null`; the value can also be zero + if (value === null) { + element.style.removeProperty(styleProperty); + return; + } + Manipulator.removeDataAttribute(element, styleProperty); + element.style.setProperty(styleProperty, value); + }; + this._applyManipulationCallback(selector, manipulationCallBack); + } + _applyManipulationCallback(selector, callBack) { + if (isElement$1(selector)) { + callBack(selector); + return; + } + for (const sel of SelectorEngine.find(selector, this._element)) { + callBack(sel); + } + } } /** * -------------------------------------------------------------------------- - * Bootstrap (v5.1.0): modal.js + * Bootstrap modal.js * Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE) * -------------------------------------------------------------------------- */ + + /** - * ------------------------------------------------------------------------ * Constants - * ------------------------------------------------------------------------ */ - const NAME$6 = 'modal'; - const DATA_KEY$6 = 'bs.modal'; - const EVENT_KEY$6 = `.${DATA_KEY$6}`; - const DATA_API_KEY$3 = '.data-api'; + const NAME$7 = 'modal'; + const DATA_KEY$4 = 'bs.modal'; + const EVENT_KEY$4 = `.${DATA_KEY$4}`; + const DATA_API_KEY$2 = '.data-api'; const ESCAPE_KEY$1 = 'Escape'; - const Default$5 = { - backdrop: true, - keyboard: true, - focus: true - }; - const DefaultType$5 = { - backdrop: '(boolean|string)', - keyboard: 'boolean', - focus: 'boolean' - }; - const EVENT_HIDE$3 = `hide${EVENT_KEY$6}`; - const EVENT_HIDE_PREVENTED = `hidePrevented${EVENT_KEY$6}`; - const EVENT_HIDDEN$3 = `hidden${EVENT_KEY$6}`; - const EVENT_SHOW$3 = `show${EVENT_KEY$6}`; - const EVENT_SHOWN$3 = `shown${EVENT_KEY$6}`; - const EVENT_RESIZE = `resize${EVENT_KEY$6}`; - const EVENT_CLICK_DISMISS = `click.dismiss${EVENT_KEY$6}`; - const EVENT_KEYDOWN_DISMISS$1 = `keydown.dismiss${EVENT_KEY$6}`; - const EVENT_MOUSEUP_DISMISS = `mouseup.dismiss${EVENT_KEY$6}`; - const EVENT_MOUSEDOWN_DISMISS = `mousedown.dismiss${EVENT_KEY$6}`; - const EVENT_CLICK_DATA_API$2 = `click${EVENT_KEY$6}${DATA_API_KEY$3}`; + const EVENT_HIDE$4 = `hide${EVENT_KEY$4}`; + const EVENT_HIDE_PREVENTED$1 = `hidePrevented${EVENT_KEY$4}`; + const EVENT_HIDDEN$4 = `hidden${EVENT_KEY$4}`; + const EVENT_SHOW$4 = `show${EVENT_KEY$4}`; + const EVENT_SHOWN$4 = `shown${EVENT_KEY$4}`; + const EVENT_RESIZE$1 = `resize${EVENT_KEY$4}`; + const EVENT_CLICK_DISMISS = `click.dismiss${EVENT_KEY$4}`; + const EVENT_MOUSEDOWN_DISMISS = `mousedown.dismiss${EVENT_KEY$4}`; + const EVENT_KEYDOWN_DISMISS$1 = `keydown.dismiss${EVENT_KEY$4}`; + const EVENT_CLICK_DATA_API$2 = `click${EVENT_KEY$4}${DATA_API_KEY$2}`; const CLASS_NAME_OPEN = 'modal-open'; const CLASS_NAME_FADE$3 = 'fade'; const CLASS_NAME_SHOW$4 = 'show'; const CLASS_NAME_STATIC = 'modal-static'; + const OPEN_SELECTOR$1 = '.modal.show'; const SELECTOR_DIALOG = '.modal-dialog'; const SELECTOR_MODAL_BODY = '.modal-body'; const SELECTOR_DATA_TOGGLE$2 = '[data-bs-toggle="modal"]'; + const Default$6 = { + backdrop: true, + focus: true, + keyboard: true + }; + const DefaultType$6 = { + backdrop: '(boolean|string)', + focus: 'boolean', + keyboard: 'boolean' + }; + /** - * ------------------------------------------------------------------------ - * Class Definition - * ------------------------------------------------------------------------ + * Class definition */ class Modal extends BaseComponent { constructor(element, config) { - super(element); - this._config = this._getConfig(config); + super(element, config); this._dialog = SelectorEngine.findOne(SELECTOR_DIALOG, this._element); this._backdrop = this._initializeBackDrop(); this._focustrap = this._initializeFocusTrap(); this._isShown = false; - this._ignoreBackdropClick = false; this._isTransitioning = false; this._scrollBar = new ScrollBarHelper(); - } // Getters - + this._addEventListeners(); + } + // Getters static get Default() { - return Default$5; + return Default$6; + } + static get DefaultType() { + return DefaultType$6; } - static get NAME() { - return NAME$6; - } // Public - + return NAME$7; + } + // Public toggle(relatedTarget) { return this._isShown ? this.hide() : this.show(relatedTarget); } - show(relatedTarget) { if (this._isShown || this._isTransitioning) { return; } - - const showEvent = EventHandler.trigger(this._element, EVENT_SHOW$3, { + const showEvent = EventHandler.trigger(this._element, EVENT_SHOW$4, { relatedTarget }); - if (showEvent.defaultPrevented) { return; } - this._isShown = true; - - if (this._isAnimated()) { - this._isTransitioning = true; - } - + this._isTransitioning = true; this._scrollBar.hide(); - document.body.classList.add(CLASS_NAME_OPEN); - this._adjustDialog(); - - this._setEscapeEvent(); - - this._setResizeEvent(); - - EventHandler.on(this._dialog, EVENT_MOUSEDOWN_DISMISS, () => { - EventHandler.one(this._element, EVENT_MOUSEUP_DISMISS, event => { - if (event.target === this._element) { - this._ignoreBackdropClick = true; - } - }); - }); - - this._showBackdrop(() => this._showElement(relatedTarget)); + this._backdrop.show(() => this._showElement(relatedTarget)); } - hide() { if (!this._isShown || this._isTransitioning) { return; } - - const hideEvent = EventHandler.trigger(this._element, EVENT_HIDE$3); - + const hideEvent = EventHandler.trigger(this._element, EVENT_HIDE$4); if (hideEvent.defaultPrevented) { return; } - this._isShown = false; - - const isAnimated = this._isAnimated(); - - if (isAnimated) { - this._isTransitioning = true; - } - - this._setEscapeEvent(); - - this._setResizeEvent(); - + this._isTransitioning = true; this._focustrap.deactivate(); - - this._element.classList.remove(CLASS_NAME_SHOW$4); - - EventHandler.off(this._element, EVENT_CLICK_DISMISS); - EventHandler.off(this._dialog, EVENT_MOUSEDOWN_DISMISS); - - this._queueCallback(() => this._hideModal(), this._element, isAnimated); + this._element.classList.remove(CLASS_NAME_SHOW$4); + this._queueCallback(() => this._hideModal(), this._element, this._isAnimated()); } - dispose() { - [window, this._dialog].forEach(htmlElement => EventHandler.off(htmlElement, EVENT_KEY$6)); - + EventHandler.off(window, EVENT_KEY$4); + EventHandler.off(this._dialog, EVENT_KEY$4); this._backdrop.dispose(); - this._focustrap.deactivate(); - super.dispose(); } - handleUpdate() { this._adjustDialog(); - } // Private - + } + // Private _initializeBackDrop() { return new Backdrop({ isVisible: Boolean(this._config.backdrop), - // 'static' option will be translated to true, and booleans will keep their value + // 'static' option will be translated to true, and booleans will keep their value, isAnimated: this._isAnimated() }); } - _initializeFocusTrap() { return new FocusTrap({ trapElement: this._element }); } - - _getConfig(config) { - config = { ...Default$5, - ...Manipulator.getDataAttributes(this._element), - ...(typeof config === 'object' ? config : {}) - }; - typeCheckConfig(NAME$6, config, DefaultType$5); - return config; - } - _showElement(relatedTarget) { - const isAnimated = this._isAnimated(); - - const modalBody = SelectorEngine.findOne(SELECTOR_MODAL_BODY, this._dialog); - - if (!this._element.parentNode || this._element.parentNode.nodeType !== Node.ELEMENT_NODE) { - // Don't move modal's DOM position + // try to append dynamic modal + if (!document.body.contains(this._element)) { document.body.append(this._element); } - this._element.style.display = 'block'; - this._element.removeAttribute('aria-hidden'); - this._element.setAttribute('aria-modal', true); - this._element.setAttribute('role', 'dialog'); - this._element.scrollTop = 0; - + const modalBody = SelectorEngine.findOne(SELECTOR_MODAL_BODY, this._dialog); if (modalBody) { modalBody.scrollTop = 0; } - - if (isAnimated) { - reflow(this._element); - } - + reflow(this._element); this._element.classList.add(CLASS_NAME_SHOW$4); - const transitionComplete = () => { if (this._config.focus) { this._focustrap.activate(); } - this._isTransitioning = false; - EventHandler.trigger(this._element, EVENT_SHOWN$3, { + EventHandler.trigger(this._element, EVENT_SHOWN$4, { relatedTarget }); }; - - this._queueCallback(transitionComplete, this._dialog, isAnimated); + this._queueCallback(transitionComplete, this._dialog, this._isAnimated()); } - - _setEscapeEvent() { - if (this._isShown) { - EventHandler.on(this._element, EVENT_KEYDOWN_DISMISS$1, event => { - if (this._config.keyboard && event.key === ESCAPE_KEY$1) { - event.preventDefault(); - this.hide(); - } else if (!this._config.keyboard && event.key === ESCAPE_KEY$1) { + _addEventListeners() { + EventHandler.on(this._element, EVENT_KEYDOWN_DISMISS$1, event => { + if (event.key !== ESCAPE_KEY$1) { + return; + } + if (this._config.keyboard) { + this.hide(); + return; + } + this._triggerBackdropTransition(); + }); + EventHandler.on(window, EVENT_RESIZE$1, () => { + if (this._isShown && !this._isTransitioning) { + this._adjustDialog(); + } + }); + EventHandler.on(this._element, EVENT_MOUSEDOWN_DISMISS, event => { + // a bad trick to segregate clicks that may start inside dialog but end outside, and avoid listen to scrollbar clicks + EventHandler.one(this._element, EVENT_CLICK_DISMISS, event2 => { + if (this._element !== event.target || this._element !== event2.target) { + return; + } + if (this._config.backdrop === 'static') { this._triggerBackdropTransition(); + return; + } + if (this._config.backdrop) { + this.hide(); } }); - } else { - EventHandler.off(this._element, EVENT_KEYDOWN_DISMISS$1); - } - } - - _setResizeEvent() { - if (this._isShown) { - EventHandler.on(window, EVENT_RESIZE, () => this._adjustDialog()); - } else { - EventHandler.off(window, EVENT_RESIZE); - } + }); } - _hideModal() { this._element.style.display = 'none'; - this._element.setAttribute('aria-hidden', true); - this._element.removeAttribute('aria-modal'); - this._element.removeAttribute('role'); - this._isTransitioning = false; - this._backdrop.hide(() => { document.body.classList.remove(CLASS_NAME_OPEN); - this._resetAdjustments(); - this._scrollBar.reset(); - - EventHandler.trigger(this._element, EVENT_HIDDEN$3); - }); - } - - _showBackdrop(callback) { - EventHandler.on(this._element, EVENT_CLICK_DISMISS, event => { - if (this._ignoreBackdropClick) { - this._ignoreBackdropClick = false; - return; - } - - if (event.target !== event.currentTarget) { - return; - } - - if (this._config.backdrop === true) { - this.hide(); - } else if (this._config.backdrop === 'static') { - this._triggerBackdropTransition(); - } + EventHandler.trigger(this._element, EVENT_HIDDEN$4); }); - - this._backdrop.show(callback); } - _isAnimated() { return this._element.classList.contains(CLASS_NAME_FADE$3); } - _triggerBackdropTransition() { - const hideEvent = EventHandler.trigger(this._element, EVENT_HIDE_PREVENTED); - + const hideEvent = EventHandler.trigger(this._element, EVENT_HIDE_PREVENTED$1); if (hideEvent.defaultPrevented) { return; } - - const { - classList, - scrollHeight, - style - } = this._element; - const isModalOverflowing = scrollHeight > document.documentElement.clientHeight; // return if the following background transition hasn't yet completed - - if (!isModalOverflowing && style.overflowY === 'hidden' || classList.contains(CLASS_NAME_STATIC)) { + const isModalOverflowing = this._element.scrollHeight > document.documentElement.clientHeight; + const initialOverflowY = this._element.style.overflowY; + // return if the following background transition hasn't yet completed + if (initialOverflowY === 'hidden' || this._element.classList.contains(CLASS_NAME_STATIC)) { return; } - if (!isModalOverflowing) { - style.overflowY = 'hidden'; + this._element.style.overflowY = 'hidden'; } - - classList.add(CLASS_NAME_STATIC); - + this._element.classList.add(CLASS_NAME_STATIC); this._queueCallback(() => { - classList.remove(CLASS_NAME_STATIC); - - if (!isModalOverflowing) { - this._queueCallback(() => { - style.overflowY = ''; - }, this._dialog); - } + this._element.classList.remove(CLASS_NAME_STATIC); + this._queueCallback(() => { + this._element.style.overflowY = initialOverflowY; + }, this._dialog); }, this._dialog); - this._element.focus(); - } // ---------------------------------------------------------------------- - // the following methods are used to handle overflowing modals - // ---------------------------------------------------------------------- + } + /** + * The following methods are used to handle overflowing modals + */ _adjustDialog() { const isModalOverflowing = this._element.scrollHeight > document.documentElement.clientHeight; - const scrollbarWidth = this._scrollBar.getWidth(); - const isBodyOverflowing = scrollbarWidth > 0; - - if (!isBodyOverflowing && isModalOverflowing && !isRTL() || isBodyOverflowing && !isModalOverflowing && isRTL()) { - this._element.style.paddingLeft = `${scrollbarWidth}px`; + if (isBodyOverflowing && !isModalOverflowing) { + const property = isRTL() ? 'paddingLeft' : 'paddingRight'; + this._element.style[property] = `${scrollbarWidth}px`; } - - if (isBodyOverflowing && !isModalOverflowing && !isRTL() || !isBodyOverflowing && isModalOverflowing && isRTL()) { - this._element.style.paddingRight = `${scrollbarWidth}px`; + if (!isBodyOverflowing && isModalOverflowing) { + const property = isRTL() ? 'paddingRight' : 'paddingLeft'; + this._element.style[property] = `${scrollbarWidth}px`; } } - _resetAdjustments() { this._element.style.paddingLeft = ''; this._element.style.paddingRight = ''; - } // Static - + } + // Static static jQueryInterface(config, relatedTarget) { return this.each(function () { const data = Modal.getOrCreateInstance(this, config); - if (typeof config !== 'string') { return; } - if (typeof data[config] === 'undefined') { throw new TypeError(`No method named "${config}"`); } - data[config](relatedTarget); }); } - } + /** - * ------------------------------------------------------------------------ - * Data Api implementation - * ------------------------------------------------------------------------ + * Data API implementation */ - EventHandler.on(document, EVENT_CLICK_DATA_API$2, SELECTOR_DATA_TOGGLE$2, function (event) { - const target = getElementFromSelector(this); - + const target = SelectorEngine.getElementFromSelector(this); if (['A', 'AREA'].includes(this.tagName)) { event.preventDefault(); } - - EventHandler.one(target, EVENT_SHOW$3, showEvent => { + EventHandler.one(target, EVENT_SHOW$4, showEvent => { if (showEvent.defaultPrevented) { // only register focus restorer if modal will actually get shown return; } - - EventHandler.one(target, EVENT_HIDDEN$3, () => { + EventHandler.one(target, EVENT_HIDDEN$4, () => { if (isVisible(this)) { this.focus(); } }); }); + + // avoid conflict when clicking modal toggler while another one is open + const alreadyOpen = SelectorEngine.findOne(OPEN_SELECTOR$1); + if (alreadyOpen) { + Modal.getInstance(alreadyOpen).hide(); + } const data = Modal.getOrCreateInstance(target); data.toggle(this); }); enableDismissTrigger(Modal); + /** - * ------------------------------------------------------------------------ * jQuery - * ------------------------------------------------------------------------ - * add .Modal to jQuery only if jQuery is present */ defineJQueryPlugin(Modal); /** * -------------------------------------------------------------------------- - * Bootstrap (v5.1.0): offcanvas.js - * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) + * Bootstrap offcanvas.js + * Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE) * -------------------------------------------------------------------------- */ + + /** - * ------------------------------------------------------------------------ * Constants - * ------------------------------------------------------------------------ */ - const NAME$5 = 'offcanvas'; - const DATA_KEY$5 = 'bs.offcanvas'; - const EVENT_KEY$5 = `.${DATA_KEY$5}`; - const DATA_API_KEY$2 = '.data-api'; - const EVENT_LOAD_DATA_API$1 = `load${EVENT_KEY$5}${DATA_API_KEY$2}`; + const NAME$6 = 'offcanvas'; + const DATA_KEY$3 = 'bs.offcanvas'; + const EVENT_KEY$3 = `.${DATA_KEY$3}`; + const DATA_API_KEY$1 = '.data-api'; + const EVENT_LOAD_DATA_API$2 = `load${EVENT_KEY$3}${DATA_API_KEY$1}`; const ESCAPE_KEY = 'Escape'; - const Default$4 = { + const CLASS_NAME_SHOW$3 = 'show'; + const CLASS_NAME_SHOWING$1 = 'showing'; + const CLASS_NAME_HIDING = 'hiding'; + const CLASS_NAME_BACKDROP = 'offcanvas-backdrop'; + const OPEN_SELECTOR = '.offcanvas.show'; + const EVENT_SHOW$3 = `show${EVENT_KEY$3}`; + const EVENT_SHOWN$3 = `shown${EVENT_KEY$3}`; + const EVENT_HIDE$3 = `hide${EVENT_KEY$3}`; + const EVENT_HIDE_PREVENTED = `hidePrevented${EVENT_KEY$3}`; + const EVENT_HIDDEN$3 = `hidden${EVENT_KEY$3}`; + const EVENT_RESIZE = `resize${EVENT_KEY$3}`; + const EVENT_CLICK_DATA_API$1 = `click${EVENT_KEY$3}${DATA_API_KEY$1}`; + const EVENT_KEYDOWN_DISMISS = `keydown.dismiss${EVENT_KEY$3}`; + const SELECTOR_DATA_TOGGLE$1 = '[data-bs-toggle="offcanvas"]'; + const Default$5 = { backdrop: true, keyboard: true, scroll: false }; - const DefaultType$4 = { - backdrop: 'boolean', + const DefaultType$5 = { + backdrop: '(boolean|string)', keyboard: 'boolean', scroll: 'boolean' }; - const CLASS_NAME_SHOW$3 = 'show'; - const CLASS_NAME_BACKDROP = 'offcanvas-backdrop'; - const OPEN_SELECTOR = '.offcanvas.show'; - const EVENT_SHOW$2 = `show${EVENT_KEY$5}`; - const EVENT_SHOWN$2 = `shown${EVENT_KEY$5}`; - const EVENT_HIDE$2 = `hide${EVENT_KEY$5}`; - const EVENT_HIDDEN$2 = `hidden${EVENT_KEY$5}`; - const EVENT_CLICK_DATA_API$1 = `click${EVENT_KEY$5}${DATA_API_KEY$2}`; - const EVENT_KEYDOWN_DISMISS = `keydown.dismiss${EVENT_KEY$5}`; - const SELECTOR_DATA_TOGGLE$1 = '[data-bs-toggle="offcanvas"]'; + /** - * ------------------------------------------------------------------------ - * Class Definition - * ------------------------------------------------------------------------ + * Class definition */ class Offcanvas extends BaseComponent { constructor(element, config) { - super(element); - this._config = this._getConfig(config); + super(element, config); this._isShown = false; this._backdrop = this._initializeBackDrop(); this._focustrap = this._initializeFocusTrap(); - this._addEventListeners(); - } // Getters - - - static get NAME() { - return NAME$5; } + // Getters static get Default() { - return Default$4; - } // Public - + return Default$5; + } + static get DefaultType() { + return DefaultType$5; + } + static get NAME() { + return NAME$6; + } + // Public toggle(relatedTarget) { return this._isShown ? this.hide() : this.show(relatedTarget); } - show(relatedTarget) { if (this._isShown) { return; } - - const showEvent = EventHandler.trigger(this._element, EVENT_SHOW$2, { + const showEvent = EventHandler.trigger(this._element, EVENT_SHOW$3, { relatedTarget }); - if (showEvent.defaultPrevented) { return; } - this._isShown = true; - this._element.style.visibility = 'visible'; - this._backdrop.show(); - if (!this._config.scroll) { new ScrollBarHelper().hide(); } - - this._element.removeAttribute('aria-hidden'); - this._element.setAttribute('aria-modal', true); - this._element.setAttribute('role', 'dialog'); - - this._element.classList.add(CLASS_NAME_SHOW$3); - + this._element.classList.add(CLASS_NAME_SHOWING$1); const completeCallBack = () => { - if (!this._config.scroll) { + if (!this._config.scroll || this._config.backdrop) { this._focustrap.activate(); } - - EventHandler.trigger(this._element, EVENT_SHOWN$2, { + this._element.classList.add(CLASS_NAME_SHOW$3); + this._element.classList.remove(CLASS_NAME_SHOWING$1); + EventHandler.trigger(this._element, EVENT_SHOWN$3, { relatedTarget }); }; - this._queueCallback(completeCallBack, this._element, true); } - hide() { if (!this._isShown) { return; } - - const hideEvent = EventHandler.trigger(this._element, EVENT_HIDE$2); - + const hideEvent = EventHandler.trigger(this._element, EVENT_HIDE$3); if (hideEvent.defaultPrevented) { return; } - this._focustrap.deactivate(); - this._element.blur(); - this._isShown = false; - - this._element.classList.remove(CLASS_NAME_SHOW$3); - + this._element.classList.add(CLASS_NAME_HIDING); this._backdrop.hide(); - const completeCallback = () => { - this._element.setAttribute('aria-hidden', true); - + this._element.classList.remove(CLASS_NAME_SHOW$3, CLASS_NAME_HIDING); this._element.removeAttribute('aria-modal'); - this._element.removeAttribute('role'); - - this._element.style.visibility = 'hidden'; - if (!this._config.scroll) { new ScrollBarHelper().reset(); } - - EventHandler.trigger(this._element, EVENT_HIDDEN$2); + EventHandler.trigger(this._element, EVENT_HIDDEN$3); }; - this._queueCallback(completeCallback, this._element, true); } - dispose() { this._backdrop.dispose(); - this._focustrap.deactivate(); - super.dispose(); - } // Private - - - _getConfig(config) { - config = { ...Default$4, - ...Manipulator.getDataAttributes(this._element), - ...(typeof config === 'object' ? config : {}) - }; - typeCheckConfig(NAME$5, config, DefaultType$4); - return config; } + // Private _initializeBackDrop() { + const clickCallback = () => { + if (this._config.backdrop === 'static') { + EventHandler.trigger(this._element, EVENT_HIDE_PREVENTED); + return; + } + this.hide(); + }; + + // 'static' option will be translated to true, and booleans will keep their value + const isVisible = Boolean(this._config.backdrop); return new Backdrop({ className: CLASS_NAME_BACKDROP, - isVisible: this._config.backdrop, + isVisible, isAnimated: true, rootElement: this._element.parentNode, - clickCallback: () => this.hide() + clickCallback: isVisible ? clickCallback : null }); } - _initializeFocusTrap() { return new FocusTrap({ trapElement: this._element }); } - _addEventListeners() { EventHandler.on(this._element, EVENT_KEYDOWN_DISMISS, event => { - if (this._config.keyboard && event.key === ESCAPE_KEY) { + if (event.key !== ESCAPE_KEY) { + return; + } + if (this._config.keyboard) { this.hide(); + return; } + EventHandler.trigger(this._element, EVENT_HIDE_PREVENTED); }); - } // Static - + } + // Static static jQueryInterface(config) { return this.each(function () { const data = Offcanvas.getOrCreateInstance(this, config); - if (typeof config !== 'string') { return; } - if (data[config] === undefined || config.startsWith('_') || config === 'constructor') { throw new TypeError(`No method named "${config}"`); } - data[config](this); }); } - } + /** - * ------------------------------------------------------------------------ - * Data Api implementation - * ------------------------------------------------------------------------ + * Data API implementation */ - EventHandler.on(document, EVENT_CLICK_DATA_API$1, SELECTOR_DATA_TOGGLE$1, function (event) { - const target = getElementFromSelector(this); - + const target = SelectorEngine.getElementFromSelector(this); if (['A', 'AREA'].includes(this.tagName)) { event.preventDefault(); } - if (isDisabled(this)) { return; } - - EventHandler.one(target, EVENT_HIDDEN$2, () => { + EventHandler.one(target, EVENT_HIDDEN$3, () => { // focus on trigger when it is closed if (isVisible(this)) { this.focus(); } - }); // avoid conflict when clicking a toggler of an offcanvas, while another is open - - const allReadyOpen = SelectorEngine.findOne(OPEN_SELECTOR); + }); - if (allReadyOpen && allReadyOpen !== target) { - Offcanvas.getInstance(allReadyOpen).hide(); + // avoid conflict when clicking a toggler of an offcanvas, while another is open + const alreadyOpen = SelectorEngine.findOne(OPEN_SELECTOR); + if (alreadyOpen && alreadyOpen !== target) { + Offcanvas.getInstance(alreadyOpen).hide(); } - const data = Offcanvas.getOrCreateInstance(target); data.toggle(this); }); - EventHandler.on(window, EVENT_LOAD_DATA_API$1, () => SelectorEngine.find(OPEN_SELECTOR).forEach(el => Offcanvas.getOrCreateInstance(el).show())); + EventHandler.on(window, EVENT_LOAD_DATA_API$2, () => { + for (const selector of SelectorEngine.find(OPEN_SELECTOR)) { + Offcanvas.getOrCreateInstance(selector).show(); + } + }); + EventHandler.on(window, EVENT_RESIZE, () => { + for (const element of SelectorEngine.find('[aria-modal][class*=show][class*=offcanvas-]')) { + if (getComputedStyle(element).position !== 'fixed') { + Offcanvas.getOrCreateInstance(element).hide(); + } + } + }); enableDismissTrigger(Offcanvas); + /** - * ------------------------------------------------------------------------ * jQuery - * ------------------------------------------------------------------------ */ defineJQueryPlugin(Offcanvas); /** * -------------------------------------------------------------------------- - * Bootstrap (v5.1.0): util/sanitizer.js + * Bootstrap util/sanitizer.js * Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE) * -------------------------------------------------------------------------- */ - const uriAttrs = new Set(['background', 'cite', 'href', 'itemtype', 'longdesc', 'poster', 'src', 'xlink:href']); - const ARIA_ATTRIBUTE_PATTERN = /^aria-[\w-]*$/i; - /** - * A pattern that recognizes a commonly useful subset of URLs that are safe. - * - * Shoutout to Angular 7 https://github.com/angular/angular/blob/7.2.4/packages/core/src/sanitization/url_sanitizer.ts - */ - - const SAFE_URL_PATTERN = /^(?:(?:https?|mailto|ftp|tel|file):|[^#&/:?]*(?:[#/?]|$))/i; - /** - * A pattern that matches safe data URLs. Only matches image, video and audio types. - * - * Shoutout to Angular 7 https://github.com/angular/angular/blob/7.2.4/packages/core/src/sanitization/url_sanitizer.ts - */ - - const DATA_URL_PATTERN = /^data:(?:image\/(?:bmp|gif|jpeg|jpg|png|tiff|webp)|video\/(?:mpeg|mp4|ogg|webm)|audio\/(?:mp3|oga|ogg|opus));base64,[\d+/a-z]+=*$/i; - - const allowedAttribute = (attr, allowedAttributeList) => { - const attrName = attr.nodeName.toLowerCase(); - - if (allowedAttributeList.includes(attrName)) { - if (uriAttrs.has(attrName)) { - return Boolean(SAFE_URL_PATTERN.test(attr.nodeValue) || DATA_URL_PATTERN.test(attr.nodeValue)); - } - - return true; - } - - const regExp = allowedAttributeList.filter(attrRegex => attrRegex instanceof RegExp); // Check if a regular expression validates the attribute. - - for (let i = 0, len = regExp.length; i < len; i++) { - if (regExp[i].test(attrName)) { - return true; - } - } - - return false; - }; + // js-docs-start allow-list + const ARIA_ATTRIBUTE_PATTERN = /^aria-[\w-]*$/i; const DefaultAllowlist = { // Global attributes allowed on any supplied element below. '*': ['class', 'dir', 'id', 'lang', 'role', ARIA_ATTRIBUTE_PATTERN], @@ -5222,7 +4765,10 @@ br: [], col: [], code: [], + dd: [], div: [], + dl: [], + dt: [], em: [], hr: [], h1: [], @@ -5246,77 +4792,226 @@ u: [], ul: [] }; - function sanitizeHtml(unsafeHtml, allowList, sanitizeFn) { + // js-docs-end allow-list + + const uriAttributes = new Set(['background', 'cite', 'href', 'itemtype', 'longdesc', 'poster', 'src', 'xlink:href']); + + /** + * A pattern that recognizes URLs that are safe wrt. XSS in URL navigation + * contexts. + * + * Shout-out to Angular https://github.com/angular/angular/blob/15.2.8/packages/core/src/sanitization/url_sanitizer.ts#L38 + */ + const SAFE_URL_PATTERN = /^(?!javascript:)(?:[a-z0-9+.-]+:|[^&:/?#]*(?:[/?#]|$))/i; + const allowedAttribute = (attribute, allowedAttributeList) => { + const attributeName = attribute.nodeName.toLowerCase(); + if (allowedAttributeList.includes(attributeName)) { + if (uriAttributes.has(attributeName)) { + return Boolean(SAFE_URL_PATTERN.test(attribute.nodeValue)); + } + return true; + } + + // Check if a regular expression validates the attribute. + return allowedAttributeList.filter(attributeRegex => attributeRegex instanceof RegExp).some(regex => regex.test(attributeName)); + }; + function sanitizeHtml(unsafeHtml, allowList, sanitizeFunction) { if (!unsafeHtml.length) { return unsafeHtml; } - - if (sanitizeFn && typeof sanitizeFn === 'function') { - return sanitizeFn(unsafeHtml); + if (sanitizeFunction && typeof sanitizeFunction === 'function') { + return sanitizeFunction(unsafeHtml); } - const domParser = new window.DOMParser(); const createdDocument = domParser.parseFromString(unsafeHtml, 'text/html'); - const allowlistKeys = Object.keys(allowList); const elements = [].concat(...createdDocument.body.querySelectorAll('*')); - - for (let i = 0, len = elements.length; i < len; i++) { - const el = elements[i]; - const elName = el.nodeName.toLowerCase(); - - if (!allowlistKeys.includes(elName)) { - el.remove(); + for (const element of elements) { + const elementName = element.nodeName.toLowerCase(); + if (!Object.keys(allowList).includes(elementName)) { + element.remove(); continue; } - - const attributeList = [].concat(...el.attributes); - const allowedAttributes = [].concat(allowList['*'] || [], allowList[elName] || []); - attributeList.forEach(attr => { - if (!allowedAttribute(attr, allowedAttributes)) { - el.removeAttribute(attr.nodeName); + const attributeList = [].concat(...element.attributes); + const allowedAttributes = [].concat(allowList['*'] || [], allowList[elementName] || []); + for (const attribute of attributeList) { + if (!allowedAttribute(attribute, allowedAttributes)) { + element.removeAttribute(attribute.nodeName); } - }); + } } - return createdDocument.body.innerHTML; } /** * -------------------------------------------------------------------------- - * Bootstrap (v5.1.0): tooltip.js + * Bootstrap util/template-factory.js * Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE) * -------------------------------------------------------------------------- */ + + /** - * ------------------------------------------------------------------------ * Constants - * ------------------------------------------------------------------------ */ - const NAME$4 = 'tooltip'; - const DATA_KEY$4 = 'bs.tooltip'; - const EVENT_KEY$4 = `.${DATA_KEY$4}`; - const CLASS_PREFIX$1 = 'bs-tooltip'; - const DISALLOWED_ATTRIBUTES = new Set(['sanitize', 'allowList', 'sanitizeFn']); - const DefaultType$3 = { - animation: 'boolean', - template: 'string', - title: '(string|element|function)', - trigger: 'string', - delay: '(number|object)', + const NAME$5 = 'TemplateFactory'; + const Default$4 = { + allowList: DefaultAllowlist, + content: {}, + // { selector : text , selector2 : text2 , } + extraClass: '', + html: false, + sanitize: true, + sanitizeFn: null, + template: '
' + }; + const DefaultType$4 = { + allowList: 'object', + content: 'object', + extraClass: '(string|function)', html: 'boolean', - selector: '(string|boolean)', - placement: '(string|function)', - offset: '(array|string|function)', - container: '(string|element|boolean)', - fallbackPlacements: 'array', - boundary: '(string|element)', - customClass: '(string|function)', sanitize: 'boolean', sanitizeFn: '(null|function)', - allowList: 'object', - popperConfig: '(null|object|function)' + template: 'string' + }; + const DefaultContentType = { + entry: '(string|element|function|null)', + selector: '(string|element)' }; + + /** + * Class definition + */ + + class TemplateFactory extends Config { + constructor(config) { + super(); + this._config = this._getConfig(config); + } + + // Getters + static get Default() { + return Default$4; + } + static get DefaultType() { + return DefaultType$4; + } + static get NAME() { + return NAME$5; + } + + // Public + getContent() { + return Object.values(this._config.content).map(config => this._resolvePossibleFunction(config)).filter(Boolean); + } + hasContent() { + return this.getContent().length > 0; + } + changeContent(content) { + this._checkContent(content); + this._config.content = { + ...this._config.content, + ...content + }; + return this; + } + toHtml() { + const templateWrapper = document.createElement('div'); + templateWrapper.innerHTML = this._maybeSanitize(this._config.template); + for (const [selector, text] of Object.entries(this._config.content)) { + this._setContent(templateWrapper, text, selector); + } + const template = templateWrapper.children[0]; + const extraClass = this._resolvePossibleFunction(this._config.extraClass); + if (extraClass) { + template.classList.add(...extraClass.split(' ')); + } + return template; + } + + // Private + _typeCheckConfig(config) { + super._typeCheckConfig(config); + this._checkContent(config.content); + } + _checkContent(arg) { + for (const [selector, content] of Object.entries(arg)) { + super._typeCheckConfig({ + selector, + entry: content + }, DefaultContentType); + } + } + _setContent(template, content, selector) { + const templateElement = SelectorEngine.findOne(selector, template); + if (!templateElement) { + return; + } + content = this._resolvePossibleFunction(content); + if (!content) { + templateElement.remove(); + return; + } + if (isElement$1(content)) { + this._putElementInTemplate(getElement(content), templateElement); + return; + } + if (this._config.html) { + templateElement.innerHTML = this._maybeSanitize(content); + return; + } + templateElement.textContent = content; + } + _maybeSanitize(arg) { + return this._config.sanitize ? sanitizeHtml(arg, this._config.allowList, this._config.sanitizeFn) : arg; + } + _resolvePossibleFunction(arg) { + return execute(arg, [undefined, this]); + } + _putElementInTemplate(element, templateElement) { + if (this._config.html) { + templateElement.innerHTML = ''; + templateElement.append(element); + return; + } + templateElement.textContent = element.textContent; + } + } + + /** + * -------------------------------------------------------------------------- + * Bootstrap tooltip.js + * Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE) + * -------------------------------------------------------------------------- + */ + + + /** + * Constants + */ + + const NAME$4 = 'tooltip'; + const DISALLOWED_ATTRIBUTES = new Set(['sanitize', 'allowList', 'sanitizeFn']); + const CLASS_NAME_FADE$2 = 'fade'; + const CLASS_NAME_MODAL = 'modal'; + const CLASS_NAME_SHOW$2 = 'show'; + const SELECTOR_TOOLTIP_INNER = '.tooltip-inner'; + const SELECTOR_MODAL = `.${CLASS_NAME_MODAL}`; + const EVENT_MODAL_HIDE = 'hide.bs.modal'; + const TRIGGER_HOVER = 'hover'; + const TRIGGER_FOCUS = 'focus'; + const TRIGGER_CLICK = 'click'; + const TRIGGER_MANUAL = 'manual'; + const EVENT_HIDE$2 = 'hide'; + const EVENT_HIDDEN$2 = 'hidden'; + const EVENT_SHOW$2 = 'show'; + const EVENT_SHOWN$2 = 'shown'; + const EVENT_INSERTED = 'inserted'; + const EVENT_CLICK$1 = 'click'; + const EVENT_FOCUSIN$1 = 'focusin'; + const EVENT_FOCUSOUT$1 = 'focusout'; + const EVENT_MOUSEENTER = 'mouseenter'; + const EVENT_MOUSELEAVE = 'mouseleave'; const AttachmentMap = { AUTO: 'auto', TOP: 'top', @@ -5325,394 +5020,286 @@ LEFT: isRTL() ? 'right' : 'left' }; const Default$3 = { + allowList: DefaultAllowlist, animation: true, - template: '', - trigger: 'hover focus', - title: '', + boundary: 'clippingParents', + container: false, + customClass: '', delay: 0, + fallbackPlacements: ['top', 'right', 'bottom', 'left'], html: false, - selector: false, + offset: [0, 6], placement: 'top', - offset: [0, 0], - container: false, - fallbackPlacements: ['top', 'right', 'bottom', 'left'], - boundary: 'clippingParents', - customClass: '', + popperConfig: null, sanitize: true, sanitizeFn: null, - allowList: DefaultAllowlist, - popperConfig: null + selector: false, + template: '', + title: '', + trigger: 'hover focus' }; - const Event$2 = { - HIDE: `hide${EVENT_KEY$4}`, - HIDDEN: `hidden${EVENT_KEY$4}`, - SHOW: `show${EVENT_KEY$4}`, - SHOWN: `shown${EVENT_KEY$4}`, - INSERTED: `inserted${EVENT_KEY$4}`, - CLICK: `click${EVENT_KEY$4}`, - FOCUSIN: `focusin${EVENT_KEY$4}`, - FOCUSOUT: `focusout${EVENT_KEY$4}`, - MOUSEENTER: `mouseenter${EVENT_KEY$4}`, - MOUSELEAVE: `mouseleave${EVENT_KEY$4}` + const DefaultType$3 = { + allowList: 'object', + animation: 'boolean', + boundary: '(string|element)', + container: '(string|element|boolean)', + customClass: '(string|function)', + delay: '(number|object)', + fallbackPlacements: 'array', + html: 'boolean', + offset: '(array|string|function)', + placement: '(string|function)', + popperConfig: '(null|object|function)', + sanitize: 'boolean', + sanitizeFn: '(null|function)', + selector: '(string|boolean)', + template: 'string', + title: '(string|element|function)', + trigger: 'string' }; - const CLASS_NAME_FADE$2 = 'fade'; - const CLASS_NAME_MODAL = 'modal'; - const CLASS_NAME_SHOW$2 = 'show'; - const HOVER_STATE_SHOW = 'show'; - const HOVER_STATE_OUT = 'out'; - const SELECTOR_TOOLTIP_INNER = '.tooltip-inner'; - const SELECTOR_MODAL = `.${CLASS_NAME_MODAL}`; - const EVENT_MODAL_HIDE = 'hide.bs.modal'; - const TRIGGER_HOVER = 'hover'; - const TRIGGER_FOCUS = 'focus'; - const TRIGGER_CLICK = 'click'; - const TRIGGER_MANUAL = 'manual'; + /** - * ------------------------------------------------------------------------ - * Class Definition - * ------------------------------------------------------------------------ + * Class definition */ class Tooltip extends BaseComponent { constructor(element, config) { if (typeof Popper === 'undefined') { - throw new TypeError('Bootstrap\'s tooltips require Popper (https://popper.js.org)'); + throw new TypeError('Bootstrap\'s tooltips require Popper (https://popper.js.org/docs/v2/)'); } + super(element, config); - super(element); // private - + // Private this._isEnabled = true; this._timeout = 0; - this._hoverState = ''; + this._isHovered = null; this._activeTrigger = {}; - this._popper = null; // Protected + this._popper = null; + this._templateFactory = null; + this._newContent = null; - this._config = this._getConfig(config); + // Protected this.tip = null; - this._setListeners(); - } // Getters - + if (!this._config.selector) { + this._fixTitle(); + } + } + // Getters static get Default() { return Default$3; } - + static get DefaultType() { + return DefaultType$3; + } static get NAME() { return NAME$4; } - static get Event() { - return Event$2; - } - - static get DefaultType() { - return DefaultType$3; - } // Public - - + // Public enable() { this._isEnabled = true; } - disable() { this._isEnabled = false; } - toggleEnabled() { this._isEnabled = !this._isEnabled; } - - toggle(event) { + toggle() { if (!this._isEnabled) { return; } - - if (event) { - const context = this._initializeOnDelegatedTarget(event); - - context._activeTrigger.click = !context._activeTrigger.click; - - if (context._isWithActiveTrigger()) { - context._enter(null, context); - } else { - context._leave(null, context); - } - } else { - if (this.getTipElement().classList.contains(CLASS_NAME_SHOW$2)) { - this._leave(null, this); - - return; - } - - this._enter(null, this); + if (this._isShown()) { + this._leave(); + return; } + this._enter(); } - dispose() { clearTimeout(this._timeout); EventHandler.off(this._element.closest(SELECTOR_MODAL), EVENT_MODAL_HIDE, this._hideModalHandler); - - if (this.tip) { - this.tip.remove(); - } - - if (this._popper) { - this._popper.destroy(); + if (this._element.getAttribute('data-bs-original-title')) { + this._element.setAttribute('title', this._element.getAttribute('data-bs-original-title')); } - + this._disposePopper(); super.dispose(); } - show() { if (this._element.style.display === 'none') { throw new Error('Please use show on visible elements'); } - - if (!(this.isWithContent() && this._isEnabled)) { + if (!(this._isWithContent() && this._isEnabled)) { return; } - - const showEvent = EventHandler.trigger(this._element, this.constructor.Event.SHOW); + const showEvent = EventHandler.trigger(this._element, this.constructor.eventName(EVENT_SHOW$2)); const shadowRoot = findShadowRoot(this._element); - const isInTheDom = shadowRoot === null ? this._element.ownerDocument.documentElement.contains(this._element) : shadowRoot.contains(this._element); - + const isInTheDom = (shadowRoot || this._element.ownerDocument.documentElement).contains(this._element); if (showEvent.defaultPrevented || !isInTheDom) { return; } - const tip = this.getTipElement(); - const tipId = getUID(this.constructor.NAME); - tip.setAttribute('id', tipId); - - this._element.setAttribute('aria-describedby', tipId); - - if (this._config.animation) { - tip.classList.add(CLASS_NAME_FADE$2); - } - - const placement = typeof this._config.placement === 'function' ? this._config.placement.call(this, tip, this._element) : this._config.placement; - - const attachment = this._getAttachment(placement); - - this._addAttachmentClass(attachment); - + // TODO: v6 remove this or make it optional + this._disposePopper(); + const tip = this._getTipElement(); + this._element.setAttribute('aria-describedby', tip.getAttribute('id')); const { container } = this._config; - Data.set(tip, this.constructor.DATA_KEY, this); - if (!this._element.ownerDocument.documentElement.contains(this.tip)) { container.append(tip); - EventHandler.trigger(this._element, this.constructor.Event.INSERTED); - } - - if (this._popper) { - this._popper.update(); - } else { - this._popper = createPopper(this._element, tip, this._getPopperConfig(attachment)); + EventHandler.trigger(this._element, this.constructor.eventName(EVENT_INSERTED)); } - + this._popper = this._createPopper(tip); tip.classList.add(CLASS_NAME_SHOW$2); - const customClass = this._resolvePossibleFunction(this._config.customClass); - - if (customClass) { - tip.classList.add(...customClass.split(' ')); - } // If this is a touch-enabled device we add extra + // If this is a touch-enabled device we add extra // empty mouseover listeners to the body's immediate children; // only needed because of broken event delegation on iOS // https://www.quirksmode.org/blog/archives/2014/02/mouse_event_bub.html - - if ('ontouchstart' in document.documentElement) { - [].concat(...document.body.children).forEach(element => { + for (const element of [].concat(...document.body.children)) { EventHandler.on(element, 'mouseover', noop); - }); + } } - const complete = () => { - const prevHoverState = this._hoverState; - this._hoverState = null; - EventHandler.trigger(this._element, this.constructor.Event.SHOWN); - - if (prevHoverState === HOVER_STATE_OUT) { - this._leave(null, this); + EventHandler.trigger(this._element, this.constructor.eventName(EVENT_SHOWN$2)); + if (this._isHovered === false) { + this._leave(); } + this._isHovered = false; }; - - const isAnimated = this.tip.classList.contains(CLASS_NAME_FADE$2); - - this._queueCallback(complete, this.tip, isAnimated); + this._queueCallback(complete, this.tip, this._isAnimated()); } - hide() { - if (!this._popper) { + if (!this._isShown()) { return; } - - const tip = this.getTipElement(); - - const complete = () => { - if (this._isWithActiveTrigger()) { - return; - } - - if (this._hoverState !== HOVER_STATE_SHOW) { - tip.remove(); - } - - this._cleanTipClass(); - - this._element.removeAttribute('aria-describedby'); - - EventHandler.trigger(this._element, this.constructor.Event.HIDDEN); - - if (this._popper) { - this._popper.destroy(); - - this._popper = null; - } - }; - - const hideEvent = EventHandler.trigger(this._element, this.constructor.Event.HIDE); - + const hideEvent = EventHandler.trigger(this._element, this.constructor.eventName(EVENT_HIDE$2)); if (hideEvent.defaultPrevented) { return; } + const tip = this._getTipElement(); + tip.classList.remove(CLASS_NAME_SHOW$2); - tip.classList.remove(CLASS_NAME_SHOW$2); // If this is a touch-enabled device we remove the extra + // If this is a touch-enabled device we remove the extra // empty mouseover listeners we added for iOS support - if ('ontouchstart' in document.documentElement) { - [].concat(...document.body.children).forEach(element => EventHandler.off(element, 'mouseover', noop)); + for (const element of [].concat(...document.body.children)) { + EventHandler.off(element, 'mouseover', noop); + } } - this._activeTrigger[TRIGGER_CLICK] = false; this._activeTrigger[TRIGGER_FOCUS] = false; this._activeTrigger[TRIGGER_HOVER] = false; - const isAnimated = this.tip.classList.contains(CLASS_NAME_FADE$2); + this._isHovered = null; // it is a trick to support manual triggering - this._queueCallback(complete, this.tip, isAnimated); - - this._hoverState = ''; + const complete = () => { + if (this._isWithActiveTrigger()) { + return; + } + if (!this._isHovered) { + this._disposePopper(); + } + this._element.removeAttribute('aria-describedby'); + EventHandler.trigger(this._element, this.constructor.eventName(EVENT_HIDDEN$2)); + }; + this._queueCallback(complete, this.tip, this._isAnimated()); } - update() { - if (this._popper !== null) { + if (this._popper) { this._popper.update(); } - } // Protected - - - isWithContent() { - return Boolean(this.getTitle()); } - getTipElement() { - if (this.tip) { - return this.tip; + // Protected + _isWithContent() { + return Boolean(this._getTitle()); + } + _getTipElement() { + if (!this.tip) { + this.tip = this._createTipElement(this._newContent || this._getContentForTemplate()); } - - const element = document.createElement('div'); - element.innerHTML = this._config.template; - const tip = element.children[0]; - this.setContent(tip); - tip.classList.remove(CLASS_NAME_FADE$2, CLASS_NAME_SHOW$2); - this.tip = tip; return this.tip; } + _createTipElement(content) { + const tip = this._getTemplateFactory(content).toHtml(); - setContent(tip) { - this._sanitizeAndSetContent(tip, this.getTitle(), SELECTOR_TOOLTIP_INNER); - } - - _sanitizeAndSetContent(template, content, selector) { - const templateElement = SelectorEngine.findOne(selector, template); - - if (!content && templateElement) { - templateElement.remove(); - return; - } // we use append for html objects to maintain js events - - - this.setElementContent(templateElement, content); - } - - setElementContent(element, content) { - if (element === null) { - return; + // TODO: remove this check in v6 + if (!tip) { + return null; } - - if (isElement$1(content)) { - content = getElement(content); // content is a DOM node or a jQuery - - if (this._config.html) { - if (content.parentNode !== element) { - element.innerHTML = ''; - element.append(content); - } - } else { - element.textContent = content.textContent; - } - - return; + tip.classList.remove(CLASS_NAME_FADE$2, CLASS_NAME_SHOW$2); + // TODO: v6 the following can be achieved with CSS only + tip.classList.add(`bs-${this.constructor.NAME}-auto`); + const tipId = getUID(this.constructor.NAME).toString(); + tip.setAttribute('id', tipId); + if (this._isAnimated()) { + tip.classList.add(CLASS_NAME_FADE$2); } - - if (this._config.html) { - if (this._config.sanitize) { - content = sanitizeHtml(content, this._config.allowList, this._config.sanitizeFn); - } - - element.innerHTML = content; + return tip; + } + setContent(content) { + this._newContent = content; + if (this._isShown()) { + this._disposePopper(); + this.show(); + } + } + _getTemplateFactory(content) { + if (this._templateFactory) { + this._templateFactory.changeContent(content); } else { - element.textContent = content; + this._templateFactory = new TemplateFactory({ + ...this._config, + // the `content` var has to be after `this._config` + // to override config.content in case of popover + content, + extraClass: this._resolvePossibleFunction(this._config.customClass) + }); } + return this._templateFactory; } - - getTitle() { - const title = this._element.getAttribute('data-bs-original-title') || this._config.title; - - return this._resolvePossibleFunction(title); + _getContentForTemplate() { + return { + [SELECTOR_TOOLTIP_INNER]: this._getTitle() + }; } - - updateAttachment(attachment) { - if (attachment === 'right') { - return 'end'; - } - - if (attachment === 'left') { - return 'start'; - } - - return attachment; - } // Private - - - _initializeOnDelegatedTarget(event, context) { - return context || this.constructor.getOrCreateInstance(event.delegateTarget, this._getDelegateConfig()); + _getTitle() { + return this._resolvePossibleFunction(this._config.title) || this._element.getAttribute('data-bs-original-title'); } + // Private + _initializeOnDelegatedTarget(event) { + return this.constructor.getOrCreateInstance(event.delegateTarget, this._getDelegateConfig()); + } + _isAnimated() { + return this._config.animation || this.tip && this.tip.classList.contains(CLASS_NAME_FADE$2); + } + _isShown() { + return this.tip && this.tip.classList.contains(CLASS_NAME_SHOW$2); + } + _createPopper(tip) { + const placement = execute(this._config.placement, [this, tip, this._element]); + const attachment = AttachmentMap[placement.toUpperCase()]; + return createPopper(this._element, tip, this._getPopperConfig(attachment)); + } _getOffset() { const { offset } = this._config; - if (typeof offset === 'string') { - return offset.split(',').map(val => Number.parseInt(val, 10)); + return offset.split(',').map(value => Number.parseInt(value, 10)); } - if (typeof offset === 'function') { return popperData => offset(popperData, this._element); } - return offset; } - - _resolvePossibleFunction(content) { - return typeof content === 'function' ? content.call(this._element) : content; + _resolvePossibleFunction(arg) { + return execute(arg, [this._element, this._element]); } - _getPopperConfig(attachment) { const defaultBsPopperConfig = { placement: attachment, @@ -5737,293 +5324,202 @@ element: `.${this.constructor.NAME}-arrow` } }, { - name: 'onChange', + name: 'preSetPlacement', enabled: true, - phase: 'afterWrite', - fn: data => this._handlePopperPlacementChange(data) - }], - onFirstUpdate: data => { - if (data.options.placement !== data.placement) { - this._handlePopperPlacementChange(data); + phase: 'beforeMain', + fn: data => { + // Pre-set Popper's placement attribute in order to read the arrow sizes properly. + // Otherwise, Popper mixes up the width and height dimensions since the initial arrow style is for top placement + this._getTipElement().setAttribute('data-popper-placement', data.state.placement); } - } + }] }; - return { ...defaultBsPopperConfig, - ...(typeof this._config.popperConfig === 'function' ? this._config.popperConfig(defaultBsPopperConfig) : this._config.popperConfig) + return { + ...defaultBsPopperConfig, + ...execute(this._config.popperConfig, [undefined, defaultBsPopperConfig]) }; } - - _addAttachmentClass(attachment) { - this.getTipElement().classList.add(`${this._getBasicClassPrefix()}-${this.updateAttachment(attachment)}`); - } - - _getAttachment(placement) { - return AttachmentMap[placement.toUpperCase()]; - } - _setListeners() { const triggers = this._config.trigger.split(' '); - - triggers.forEach(trigger => { + for (const trigger of triggers) { if (trigger === 'click') { - EventHandler.on(this._element, this.constructor.Event.CLICK, this._config.selector, event => this.toggle(event)); + EventHandler.on(this._element, this.constructor.eventName(EVENT_CLICK$1), this._config.selector, event => { + const context = this._initializeOnDelegatedTarget(event); + context._activeTrigger[TRIGGER_CLICK] = !(context._isShown() && context._activeTrigger[TRIGGER_CLICK]); + context.toggle(); + }); } else if (trigger !== TRIGGER_MANUAL) { - const eventIn = trigger === TRIGGER_HOVER ? this.constructor.Event.MOUSEENTER : this.constructor.Event.FOCUSIN; - const eventOut = trigger === TRIGGER_HOVER ? this.constructor.Event.MOUSELEAVE : this.constructor.Event.FOCUSOUT; - EventHandler.on(this._element, eventIn, this._config.selector, event => this._enter(event)); - EventHandler.on(this._element, eventOut, this._config.selector, event => this._leave(event)); + const eventIn = trigger === TRIGGER_HOVER ? this.constructor.eventName(EVENT_MOUSEENTER) : this.constructor.eventName(EVENT_FOCUSIN$1); + const eventOut = trigger === TRIGGER_HOVER ? this.constructor.eventName(EVENT_MOUSELEAVE) : this.constructor.eventName(EVENT_FOCUSOUT$1); + EventHandler.on(this._element, eventIn, this._config.selector, event => { + const context = this._initializeOnDelegatedTarget(event); + context._activeTrigger[event.type === 'focusin' ? TRIGGER_FOCUS : TRIGGER_HOVER] = true; + context._enter(); + }); + EventHandler.on(this._element, eventOut, this._config.selector, event => { + const context = this._initializeOnDelegatedTarget(event); + context._activeTrigger[event.type === 'focusout' ? TRIGGER_FOCUS : TRIGGER_HOVER] = context._element.contains(event.relatedTarget); + context._leave(); + }); } - }); - + } this._hideModalHandler = () => { if (this._element) { this.hide(); } }; - EventHandler.on(this._element.closest(SELECTOR_MODAL), EVENT_MODAL_HIDE, this._hideModalHandler); - - if (this._config.selector) { - this._config = { ...this._config, - trigger: 'manual', - selector: '' - }; - } else { - this._fixTitle(); - } } - _fixTitle() { const title = this._element.getAttribute('title'); - - const originalTitleType = typeof this._element.getAttribute('data-bs-original-title'); - - if (title || originalTitleType !== 'string') { - this._element.setAttribute('data-bs-original-title', title || ''); - - if (title && !this._element.getAttribute('aria-label') && !this._element.textContent) { - this._element.setAttribute('aria-label', title); - } - - this._element.setAttribute('title', ''); - } - } - - _enter(event, context) { - context = this._initializeOnDelegatedTarget(event, context); - - if (event) { - context._activeTrigger[event.type === 'focusin' ? TRIGGER_FOCUS : TRIGGER_HOVER] = true; - } - - if (context.getTipElement().classList.contains(CLASS_NAME_SHOW$2) || context._hoverState === HOVER_STATE_SHOW) { - context._hoverState = HOVER_STATE_SHOW; + if (!title) { return; } - - clearTimeout(context._timeout); - context._hoverState = HOVER_STATE_SHOW; - - if (!context._config.delay || !context._config.delay.show) { - context.show(); - return; + if (!this._element.getAttribute('aria-label') && !this._element.textContent.trim()) { + this._element.setAttribute('aria-label', title); } - - context._timeout = setTimeout(() => { - if (context._hoverState === HOVER_STATE_SHOW) { - context.show(); - } - }, context._config.delay.show); + this._element.setAttribute('data-bs-original-title', title); // DO NOT USE IT. Is only for backwards compatibility + this._element.removeAttribute('title'); } - - _leave(event, context) { - context = this._initializeOnDelegatedTarget(event, context); - - if (event) { - context._activeTrigger[event.type === 'focusout' ? TRIGGER_FOCUS : TRIGGER_HOVER] = context._element.contains(event.relatedTarget); - } - - if (context._isWithActiveTrigger()) { + _enter() { + if (this._isShown() || this._isHovered) { + this._isHovered = true; return; } - - clearTimeout(context._timeout); - context._hoverState = HOVER_STATE_OUT; - - if (!context._config.delay || !context._config.delay.hide) { - context.hide(); + this._isHovered = true; + this._setTimeout(() => { + if (this._isHovered) { + this.show(); + } + }, this._config.delay.show); + } + _leave() { + if (this._isWithActiveTrigger()) { return; } - - context._timeout = setTimeout(() => { - if (context._hoverState === HOVER_STATE_OUT) { - context.hide(); + this._isHovered = false; + this._setTimeout(() => { + if (!this._isHovered) { + this.hide(); } - }, context._config.delay.hide); + }, this._config.delay.hide); + } + _setTimeout(handler, timeout) { + clearTimeout(this._timeout); + this._timeout = setTimeout(handler, timeout); } - _isWithActiveTrigger() { - for (const trigger in this._activeTrigger) { - if (this._activeTrigger[trigger]) { - return true; - } - } - - return false; + return Object.values(this._activeTrigger).includes(true); } - _getConfig(config) { const dataAttributes = Manipulator.getDataAttributes(this._element); - Object.keys(dataAttributes).forEach(dataAttr => { - if (DISALLOWED_ATTRIBUTES.has(dataAttr)) { - delete dataAttributes[dataAttr]; + for (const dataAttribute of Object.keys(dataAttributes)) { + if (DISALLOWED_ATTRIBUTES.has(dataAttribute)) { + delete dataAttributes[dataAttribute]; } - }); - config = { ...this.constructor.Default, + } + config = { ...dataAttributes, ...(typeof config === 'object' && config ? config : {}) }; + config = this._mergeConfigObj(config); + config = this._configAfterMerge(config); + this._typeCheckConfig(config); + return config; + } + _configAfterMerge(config) { config.container = config.container === false ? document.body : getElement(config.container); - if (typeof config.delay === 'number') { config.delay = { show: config.delay, hide: config.delay }; } - if (typeof config.title === 'number') { config.title = config.title.toString(); } - if (typeof config.content === 'number') { config.content = config.content.toString(); } - - typeCheckConfig(NAME$4, config, this.constructor.DefaultType); - - if (config.sanitize) { - config.template = sanitizeHtml(config.template, config.allowList, config.sanitizeFn); - } - return config; } - _getDelegateConfig() { const config = {}; - - for (const key in this._config) { - if (this.constructor.Default[key] !== this._config[key]) { - config[key] = this._config[key]; + for (const [key, value] of Object.entries(this._config)) { + if (this.constructor.Default[key] !== value) { + config[key] = value; } - } // In the future can be replaced with: + } + config.selector = false; + config.trigger = 'manual'; + + // In the future can be replaced with: // const keysWithDifferentValues = Object.entries(this._config).filter(entry => this.constructor.Default[entry[0]] !== this._config[entry[0]]) // `Object.fromEntries(keysWithDifferentValues)` - - return config; } - - _cleanTipClass() { - const tip = this.getTipElement(); - const basicClassPrefixRegex = new RegExp(`(^|\\s)${this._getBasicClassPrefix()}\\S+`, 'g'); - const tabClass = tip.getAttribute('class').match(basicClassPrefixRegex); - - if (tabClass !== null && tabClass.length > 0) { - tabClass.map(token => token.trim()).forEach(tClass => tip.classList.remove(tClass)); + _disposePopper() { + if (this._popper) { + this._popper.destroy(); + this._popper = null; } - } - - _getBasicClassPrefix() { - return CLASS_PREFIX$1; - } - - _handlePopperPlacementChange(popperData) { - const { - state - } = popperData; - - if (!state) { - return; + if (this.tip) { + this.tip.remove(); + this.tip = null; } + } - this.tip = state.elements.popper; - - this._cleanTipClass(); - - this._addAttachmentClass(this._getAttachment(state.placement)); - } // Static - - + // Static static jQueryInterface(config) { return this.each(function () { const data = Tooltip.getOrCreateInstance(this, config); - - if (typeof config === 'string') { - if (typeof data[config] === 'undefined') { - throw new TypeError(`No method named "${config}"`); - } - - data[config](); + if (typeof config !== 'string') { + return; + } + if (typeof data[config] === 'undefined') { + throw new TypeError(`No method named "${config}"`); } + data[config](); }); } - } + /** - * ------------------------------------------------------------------------ * jQuery - * ------------------------------------------------------------------------ - * add .Tooltip to jQuery only if jQuery is present */ - defineJQueryPlugin(Tooltip); /** * -------------------------------------------------------------------------- - * Bootstrap (v5.1.0): popover.js + * Bootstrap popover.js * Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE) * -------------------------------------------------------------------------- */ + + /** - * ------------------------------------------------------------------------ * Constants - * ------------------------------------------------------------------------ */ const NAME$3 = 'popover'; - const DATA_KEY$3 = 'bs.popover'; - const EVENT_KEY$3 = `.${DATA_KEY$3}`; - const CLASS_PREFIX = 'bs-popover'; - const Default$2 = { ...Tooltip.Default, - placement: 'right', - offset: [0, 8], - trigger: 'click', + const SELECTOR_TITLE = '.popover-header'; + const SELECTOR_CONTENT = '.popover-body'; + const Default$2 = { + ...Tooltip.Default, content: '', - template: '' - }; - const DefaultType$2 = { ...Tooltip.DefaultType, - content: '(string|element|function)' + offset: [0, 8], + placement: 'right', + template: '', + trigger: 'click' }; - const Event$1 = { - HIDE: `hide${EVENT_KEY$3}`, - HIDDEN: `hidden${EVENT_KEY$3}`, - SHOW: `show${EVENT_KEY$3}`, - SHOWN: `shown${EVENT_KEY$3}`, - INSERTED: `inserted${EVENT_KEY$3}`, - CLICK: `click${EVENT_KEY$3}`, - FOCUSIN: `focusin${EVENT_KEY$3}`, - FOCUSOUT: `focusout${EVENT_KEY$3}`, - MOUSEENTER: `mouseenter${EVENT_KEY$3}`, - MOUSELEAVE: `mouseleave${EVENT_KEY$3}` + const DefaultType$2 = { + ...Tooltip.DefaultType, + content: '(null|string|element|function)' }; - const SELECTOR_TITLE = '.popover-header'; - const SELECTOR_CONTENT = '.popover-body'; + /** - * ------------------------------------------------------------------------ - * Class Definition - * ------------------------------------------------------------------------ + * Class definition */ class Popover extends Tooltip { @@ -6031,508 +5527,590 @@ static get Default() { return Default$2; } - + static get DefaultType() { + return DefaultType$2; + } static get NAME() { return NAME$3; } - static get Event() { - return Event$1; + // Overrides + _isWithContent() { + return this._getTitle() || this._getContent(); } - static get DefaultType() { - return DefaultType$2; - } // Overrides - - - isWithContent() { - return this.getTitle() || this._getContent(); + // Private + _getContentForTemplate() { + return { + [SELECTOR_TITLE]: this._getTitle(), + [SELECTOR_CONTENT]: this._getContent() + }; } - - setContent(tip) { - this._sanitizeAndSetContent(tip, this.getTitle(), SELECTOR_TITLE); - - this._sanitizeAndSetContent(tip, this._getContent(), SELECTOR_CONTENT); - } // Private - - _getContent() { return this._resolvePossibleFunction(this._config.content); } - _getBasicClassPrefix() { - return CLASS_PREFIX; - } // Static - - + // Static static jQueryInterface(config) { return this.each(function () { const data = Popover.getOrCreateInstance(this, config); - - if (typeof config === 'string') { - if (typeof data[config] === 'undefined') { - throw new TypeError(`No method named "${config}"`); - } - - data[config](); + if (typeof config !== 'string') { + return; } + if (typeof data[config] === 'undefined') { + throw new TypeError(`No method named "${config}"`); + } + data[config](); }); } - } + /** - * ------------------------------------------------------------------------ * jQuery - * ------------------------------------------------------------------------ - * add .Popover to jQuery only if jQuery is present */ - defineJQueryPlugin(Popover); /** * -------------------------------------------------------------------------- - * Bootstrap (v5.1.0): scrollspy.js + * Bootstrap scrollspy.js * Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE) * -------------------------------------------------------------------------- */ + + /** - * ------------------------------------------------------------------------ * Constants - * ------------------------------------------------------------------------ */ const NAME$2 = 'scrollspy'; const DATA_KEY$2 = 'bs.scrollspy'; const EVENT_KEY$2 = `.${DATA_KEY$2}`; - const DATA_API_KEY$1 = '.data-api'; - const Default$1 = { - offset: 10, - method: 'auto', - target: '' - }; - const DefaultType$1 = { - offset: 'number', - method: 'string', - target: '(string|element)' - }; + const DATA_API_KEY = '.data-api'; const EVENT_ACTIVATE = `activate${EVENT_KEY$2}`; - const EVENT_SCROLL = `scroll${EVENT_KEY$2}`; - const EVENT_LOAD_DATA_API = `load${EVENT_KEY$2}${DATA_API_KEY$1}`; + const EVENT_CLICK = `click${EVENT_KEY$2}`; + const EVENT_LOAD_DATA_API$1 = `load${EVENT_KEY$2}${DATA_API_KEY}`; const CLASS_NAME_DROPDOWN_ITEM = 'dropdown-item'; const CLASS_NAME_ACTIVE$1 = 'active'; const SELECTOR_DATA_SPY = '[data-bs-spy="scroll"]'; - const SELECTOR_NAV_LIST_GROUP$1 = '.nav, .list-group'; + const SELECTOR_TARGET_LINKS = '[href]'; + const SELECTOR_NAV_LIST_GROUP = '.nav, .list-group'; const SELECTOR_NAV_LINKS = '.nav-link'; const SELECTOR_NAV_ITEMS = '.nav-item'; const SELECTOR_LIST_ITEMS = '.list-group-item'; - const SELECTOR_LINK_ITEMS = `${SELECTOR_NAV_LINKS}, ${SELECTOR_LIST_ITEMS}, .${CLASS_NAME_DROPDOWN_ITEM}`; - const SELECTOR_DROPDOWN$1 = '.dropdown'; + const SELECTOR_LINK_ITEMS = `${SELECTOR_NAV_LINKS}, ${SELECTOR_NAV_ITEMS} > ${SELECTOR_NAV_LINKS}, ${SELECTOR_LIST_ITEMS}`; + const SELECTOR_DROPDOWN = '.dropdown'; const SELECTOR_DROPDOWN_TOGGLE$1 = '.dropdown-toggle'; - const METHOD_OFFSET = 'offset'; - const METHOD_POSITION = 'position'; + const Default$1 = { + offset: null, + // TODO: v6 @deprecated, keep it for backwards compatibility reasons + rootMargin: '0px 0px -25%', + smoothScroll: false, + target: null, + threshold: [0.1, 0.5, 1] + }; + const DefaultType$1 = { + offset: '(number|null)', + // TODO v6 @deprecated, keep it for backwards compatibility reasons + rootMargin: 'string', + smoothScroll: 'boolean', + target: 'element', + threshold: 'array' + }; + /** - * ------------------------------------------------------------------------ - * Class Definition - * ------------------------------------------------------------------------ + * Class definition */ class ScrollSpy extends BaseComponent { constructor(element, config) { - super(element); - this._scrollElement = this._element.tagName === 'BODY' ? window : this._element; - this._config = this._getConfig(config); - this._offsets = []; - this._targets = []; - this._activeTarget = null; - this._scrollHeight = 0; - EventHandler.on(this._scrollElement, EVENT_SCROLL, () => this._process()); - this.refresh(); - - this._process(); - } // Getters + super(element, config); + // this._element is the observablesContainer and config.target the menu links wrapper + this._targetLinks = new Map(); + this._observableSections = new Map(); + this._rootElement = getComputedStyle(this._element).overflowY === 'visible' ? null : this._element; + this._activeTarget = null; + this._observer = null; + this._previousScrollData = { + visibleEntryTop: 0, + parentScrollTop: 0 + }; + this.refresh(); // initialize + } + // Getters static get Default() { return Default$1; } - + static get DefaultType() { + return DefaultType$1; + } static get NAME() { return NAME$2; - } // Public - + } + // Public refresh() { - const autoMethod = this._scrollElement === this._scrollElement.window ? METHOD_OFFSET : METHOD_POSITION; - const offsetMethod = this._config.method === 'auto' ? autoMethod : this._config.method; - const offsetBase = offsetMethod === METHOD_POSITION ? this._getScrollTop() : 0; - this._offsets = []; - this._targets = []; - this._scrollHeight = this._getScrollHeight(); - const targets = SelectorEngine.find(SELECTOR_LINK_ITEMS, this._config.target); - targets.map(element => { - const targetSelector = getSelectorFromElement(element); - const target = targetSelector ? SelectorEngine.findOne(targetSelector) : null; - - if (target) { - const targetBCR = target.getBoundingClientRect(); - - if (targetBCR.width || targetBCR.height) { - return [Manipulator[offsetMethod](target).top + offsetBase, targetSelector]; - } - } - - return null; - }).filter(item => item).sort((a, b) => a[0] - b[0]).forEach(item => { - this._offsets.push(item[0]); - - this._targets.push(item[1]); - }); + this._initializeTargetsAndObservables(); + this._maybeEnableSmoothScroll(); + if (this._observer) { + this._observer.disconnect(); + } else { + this._observer = this._getNewObserver(); + } + for (const section of this._observableSections.values()) { + this._observer.observe(section); + } } - dispose() { - EventHandler.off(this._scrollElement, EVENT_KEY$2); + this._observer.disconnect(); super.dispose(); - } // Private + } + // Private + _configAfterMerge(config) { + // TODO: on v6 target should be given explicitly & remove the {target: 'ss-target'} case + config.target = getElement(config.target) || document.body; - _getConfig(config) { - config = { ...Default$1, - ...Manipulator.getDataAttributes(this._element), - ...(typeof config === 'object' && config ? config : {}) - }; - config.target = getElement(config.target) || document.documentElement; - typeCheckConfig(NAME$2, config, DefaultType$1); + // TODO: v6 Only for backwards compatibility reasons. Use rootMargin only + config.rootMargin = config.offset ? `${config.offset}px 0px -30%` : config.rootMargin; + if (typeof config.threshold === 'string') { + config.threshold = config.threshold.split(',').map(value => Number.parseFloat(value)); + } return config; } + _maybeEnableSmoothScroll() { + if (!this._config.smoothScroll) { + return; + } - _getScrollTop() { - return this._scrollElement === window ? this._scrollElement.pageYOffset : this._scrollElement.scrollTop; - } + // unregister any previous listeners + EventHandler.off(this._config.target, EVENT_CLICK); + EventHandler.on(this._config.target, EVENT_CLICK, SELECTOR_TARGET_LINKS, event => { + const observableSection = this._observableSections.get(event.target.hash); + if (observableSection) { + event.preventDefault(); + const root = this._rootElement || window; + const height = observableSection.offsetTop - this._element.offsetTop; + if (root.scrollTo) { + root.scrollTo({ + top: height, + behavior: 'smooth' + }); + return; + } - _getScrollHeight() { - return this._scrollElement.scrollHeight || Math.max(document.body.scrollHeight, document.documentElement.scrollHeight); + // Chrome 60 doesn't support `scrollTo` + root.scrollTop = height; + } + }); } - - _getOffsetHeight() { - return this._scrollElement === window ? window.innerHeight : this._scrollElement.getBoundingClientRect().height; + _getNewObserver() { + const options = { + root: this._rootElement, + threshold: this._config.threshold, + rootMargin: this._config.rootMargin + }; + return new IntersectionObserver(entries => this._observerCallback(entries), options); } - _process() { - const scrollTop = this._getScrollTop() + this._config.offset; - - const scrollHeight = this._getScrollHeight(); - - const maxScroll = this._config.offset + scrollHeight - this._getOffsetHeight(); + // The logic of selection + _observerCallback(entries) { + const targetElement = entry => this._targetLinks.get(`#${entry.target.id}`); + const activate = entry => { + this._previousScrollData.visibleEntryTop = entry.target.offsetTop; + this._process(targetElement(entry)); + }; + const parentScrollTop = (this._rootElement || document.documentElement).scrollTop; + const userScrollsDown = parentScrollTop >= this._previousScrollData.parentScrollTop; + this._previousScrollData.parentScrollTop = parentScrollTop; + for (const entry of entries) { + if (!entry.isIntersecting) { + this._activeTarget = null; + this._clearActiveClass(targetElement(entry)); + continue; + } + const entryIsLowerThanPrevious = entry.target.offsetTop >= this._previousScrollData.visibleEntryTop; + // if we are scrolling down, pick the bigger offsetTop + if (userScrollsDown && entryIsLowerThanPrevious) { + activate(entry); + // if parent isn't scrolled, let's keep the first visible item, breaking the iteration + if (!parentScrollTop) { + return; + } + continue; + } - if (this._scrollHeight !== scrollHeight) { - this.refresh(); + // if we are scrolling up, pick the smallest offsetTop + if (!userScrollsDown && !entryIsLowerThanPrevious) { + activate(entry); + } } - - if (scrollTop >= maxScroll) { - const target = this._targets[this._targets.length - 1]; - - if (this._activeTarget !== target) { - this._activate(target); + } + _initializeTargetsAndObservables() { + this._targetLinks = new Map(); + this._observableSections = new Map(); + const targetLinks = SelectorEngine.find(SELECTOR_TARGET_LINKS, this._config.target); + for (const anchor of targetLinks) { + // ensure that the anchor has an id and is not disabled + if (!anchor.hash || isDisabled(anchor)) { + continue; } + const observableSection = SelectorEngine.findOne(decodeURI(anchor.hash), this._element); + // ensure that the observableSection exists & is visible + if (isVisible(observableSection)) { + this._targetLinks.set(decodeURI(anchor.hash), anchor); + this._observableSections.set(anchor.hash, observableSection); + } + } + } + _process(target) { + if (this._activeTarget === target) { return; } - - if (this._activeTarget && scrollTop < this._offsets[0] && this._offsets[0] > 0) { - this._activeTarget = null; - - this._clear(); - + this._clearActiveClass(this._config.target); + this._activeTarget = target; + target.classList.add(CLASS_NAME_ACTIVE$1); + this._activateParents(target); + EventHandler.trigger(this._element, EVENT_ACTIVATE, { + relatedTarget: target + }); + } + _activateParents(target) { + // Activate dropdown parents + if (target.classList.contains(CLASS_NAME_DROPDOWN_ITEM)) { + SelectorEngine.findOne(SELECTOR_DROPDOWN_TOGGLE$1, target.closest(SELECTOR_DROPDOWN)).classList.add(CLASS_NAME_ACTIVE$1); return; } - - for (let i = this._offsets.length; i--;) { - const isActiveTarget = this._activeTarget !== this._targets[i] && scrollTop >= this._offsets[i] && (typeof this._offsets[i + 1] === 'undefined' || scrollTop < this._offsets[i + 1]); - - if (isActiveTarget) { - this._activate(this._targets[i]); + for (const listGroup of SelectorEngine.parents(target, SELECTOR_NAV_LIST_GROUP)) { + // Set triggered links parents as active + // With both