From 2f33e9ecdb1a12879a942b4b17c7a87ffa82d5de Mon Sep 17 00:00:00 2001 From: Stefano Apostolico Date: Mon, 23 Dec 2024 10:49:30 +0100 Subject: [PATCH 1/6] removes TAILWIND_DEV_MODE env var --- src/country_workspace/config/__init__.py | 2 -- src/country_workspace/config/fragments/tailwind.py | 3 --- 2 files changed, 5 deletions(-) diff --git a/src/country_workspace/config/__init__.py b/src/country_workspace/config/__init__.py index 2a4523c..ee48926 100644 --- a/src/country_workspace/config/__init__.py +++ b/src/country_workspace/config/__init__.py @@ -206,8 +206,6 @@ class Group(Enum): "SOCIAL_AUTH_REDIRECT_IS_HTTPS": (bool, True, False, False, ""), "STATIC_ROOT": (str, "/var/static", "/tmp/static", True, setting("static-root")), # nosec "STATIC_URL": (str, "/static/", "/static/", False, setting("static-url")), # nosec - "TAILWIND_DEV_MODE": (bool, False, False, False, "Enable tailwind development mode"), - "TAILWIND_DEV_MODE": (bool, False, False, False, "Enable tailwind development mode"), "TIME_ZONE": (str, "UTC", "UTC", False, setting("std-setting-TIME_ZONE")), "AZURE_CLIENT_SECRET": (str, "", "", False, "Azure client secret for SSO"), "AZURE_TENANT_ID": (str, "", "", False, "Azure tenant ID for SSO"), diff --git a/src/country_workspace/config/fragments/tailwind.py b/src/country_workspace/config/fragments/tailwind.py index 08541d0..6bf4c03 100644 --- a/src/country_workspace/config/fragments/tailwind.py +++ b/src/country_workspace/config/fragments/tailwind.py @@ -1,5 +1,2 @@ -from .. import env - TAILWIND_APP_NAME = "country_workspace.workspaces.theme" -TAILWIND_DEV_MODE = env("TAILWIND_DEV_MODE") TAILWIND_CSS_PATH = "css/styles.css" From 4e597da1a763908d32bd279167da6527ef9c191b Mon Sep 17 00:00:00 2001 From: Stefano Apostolico Date: Mon, 23 Dec 2024 13:25:31 +0100 Subject: [PATCH 2/6] add ruff checking --- .github/PULL_REQUEST_TEMPLATE.md | 6 +- .github/actions/docker_build/action.yml | 8 +- .github/actions/last_commit/action.yml | 16 ++-- .github/dependabot.yml | 2 +- .github/workflows/test.yml | 2 +- .pre-commit-config.yaml | 39 +++------- docker/Dockerfile | 4 +- docs/_theme/css/style.css.map | 2 +- docs/src/contributing.md | 10 +-- docs/src/dev_helpers.md | 2 +- docs/src/flows/import.md | 2 +- docs/src/flows/model.md | 4 +- ruff.toml | 65 ++++++++++++++++ src/country_workspace/admin/filters.py | 1 - src/country_workspace/admin/individual.py | 1 - src/country_workspace/admin/job.py | 4 +- src/country_workspace/admin/locations.py | 4 +- src/country_workspace/admin/program.py | 3 - src/country_workspace/admin/user.py | 4 +- src/country_workspace/cache/ddt.py | 2 +- src/country_workspace/cache/handlers.py | 8 +- src/country_workspace/cache/manager.py | 23 ++---- src/country_workspace/cache/middleware.py | 19 ----- .../compat/admin_extra_buttons.py | 2 +- src/country_workspace/config/__init__.py | 51 +++--------- src/country_workspace/config/celery.py | 2 +- src/country_workspace/config/fragments/csp.py | 3 - .../config/fragments/rest_framework.py | 34 +------- .../config/fragments/social_auth.py | 1 - src/country_workspace/config/settings.py | 5 -- src/country_workspace/config/urls.py | 5 -- .../contrib/aurora/client.py | 7 +- src/country_workspace/contrib/aurora/forms.py | 1 - src/country_workspace/contrib/aurora/sync.py | 25 +++--- src/country_workspace/contrib/hope/client.py | 27 +++---- src/country_workspace/contrib/hope/ddt.py | 3 +- src/country_workspace/contrib/hope/geo.py | 7 +- .../contrib/hope/remotes/country.py | 8 +- .../contrib/hope/sync/office.py | 8 +- .../contrib/hope/validators.py | 1 - src/country_workspace/datasources/rdi.py | 7 +- .../management/commands/demo.py | 4 +- .../management/commands/sync.py | 1 - .../management/commands/trigger_error.py | 4 +- src/country_workspace/middleware/exception.py | 2 +- .../migrations/0001_initial.py | 7 +- src/country_workspace/models/base.py | 14 ++-- src/country_workspace/models/jobs.py | 16 ++-- src/country_workspace/models/program.py | 8 +- src/country_workspace/models/sync.py | 8 +- src/country_workspace/security/backends.py | 12 +-- src/country_workspace/security/utils.py | 5 -- src/country_workspace/social/pipeline.py | 6 +- src/country_workspace/state.py | 14 ++-- src/country_workspace/types.pyi | 4 +- src/country_workspace/utils/constance.py | 11 +-- src/country_workspace/utils/fields.py | 5 +- src/country_workspace/utils/flags.py | 4 +- src/country_workspace/utils/flex_fields.py | 2 +- src/country_workspace/utils/http.py | 6 +- src/country_workspace/versioning/checkers.py | 5 +- .../management/commands/upgradescripts.py | 4 +- .../versioning/management/manager.py | 9 +-- .../versioning/migrations/0001_initial.py | 1 - .../migrations/0002_rename_version_script.py | 1 - src/country_workspace/versioning/models.py | 3 + src/country_workspace/web/static/hr.css.map | 2 +- .../web/static/smart_admin/console.css.map | 2 +- .../static/smart_admin/smart_admin.css.map | 2 +- .../web/static/workspace/css/constance.css | 2 +- .../web/static/workspace/css/cw.css.map | 2 +- .../web/static/workspace/css/dark_mode.css | 14 ++-- .../workspace/img/gis/move_vertex_off.svg | 2 +- .../workspace/img/gis/move_vertex_on.svg | 2 +- .../web/static/workspace/js/SelectBox.min.js | 2 +- .../static/workspace/js/SelectBox.min.min.js | 1 + .../web/static/workspace/js/SelectFilter2.js | 6 +- .../web/static/workspace/js/actions.min.js | 2 +- .../static/workspace/js/actions.min.min.js | 1 + .../js/admin/DateTimeShortcuts.min.js | 2 +- .../js/admin/DateTimeShortcuts.min.min.js | 1 + .../js/admin/RelatedObjectLookups.js | 4 +- .../static/workspace/js/autocomplete.min.js | 2 +- .../workspace/js/autocomplete.min.min.js | 1 + .../web/static/workspace/js/calendar.min.js | 2 +- .../static/workspace/js/calendar.min.min.js | 1 + .../web/static/workspace/js/cancel.min.js | 2 +- .../web/static/workspace/js/cancel.min.min.js | 1 + .../static/workspace/js/change_form.min.js | 2 +- .../workspace/js/change_form.min.min.js | 1 + .../web/static/workspace/js/constance.min.js | 2 +- .../static/workspace/js/constance.min.min.js | 1 + .../web/static/workspace/js/core.min.js | 2 +- .../web/static/workspace/js/core.min.min.js | 1 + .../web/static/workspace/js/filters.min.js | 2 +- .../static/workspace/js/filters.min.min.js | 1 + .../web/static/workspace/js/inlines.min.js | 2 +- .../static/workspace/js/inlines.min.min.js | 1 + .../static/workspace/js/jquery.init.min.js | 2 +- .../workspace/js/jquery.init.min.min.js | 1 + .../static/workspace/js/nav_sidebar.min.js | 2 +- .../workspace/js/nav_sidebar.min.min.js | 1 + .../static/workspace/js/popup_response.min.js | 2 +- .../workspace/js/popup_response.min.min.js | 1 + .../static/workspace/js/prepopulate.min.js | 2 +- .../workspace/js/prepopulate.min.min.js | 1 + .../workspace/js/prepopulate_init.min.js | 2 +- .../workspace/js/prepopulate_init.min.min.js | 1 + .../web/static/workspace/js/theme.min.js | 2 +- .../web/static/workspace/js/theme.min.min.js | 1 + .../js/unusable_password_field.min.js | 2 +- .../js/unusable_password_field.min.min.js | 1 + .../web/static/workspace/js/urlify.min.js | 2 +- .../web/static/workspace/js/urlify.min.min.js | 1 + .../workspace/js/vendor/jquery/jquery.min.js | 2 +- .../js/vendor/jquery/jquery.min.min.js | 1 + .../workspace/js/vendor/select2/i18n/af.js | 2 +- .../workspace/js/vendor/select2/i18n/ar.js | 2 +- .../workspace/js/vendor/select2/i18n/az.js | 2 +- .../workspace/js/vendor/select2/i18n/bg.js | 2 +- .../workspace/js/vendor/select2/i18n/bn.js | 2 +- .../workspace/js/vendor/select2/i18n/bs.js | 2 +- .../workspace/js/vendor/select2/i18n/ca.js | 2 +- .../workspace/js/vendor/select2/i18n/cs.js | 2 +- .../workspace/js/vendor/select2/i18n/da.js | 2 +- .../workspace/js/vendor/select2/i18n/de.js | 2 +- .../workspace/js/vendor/select2/i18n/dsb.js | 2 +- .../workspace/js/vendor/select2/i18n/el.js | 2 +- .../workspace/js/vendor/select2/i18n/en.js | 2 +- .../workspace/js/vendor/select2/i18n/es.js | 2 +- .../workspace/js/vendor/select2/i18n/et.js | 2 +- .../workspace/js/vendor/select2/i18n/eu.js | 2 +- .../workspace/js/vendor/select2/i18n/fa.js | 2 +- .../workspace/js/vendor/select2/i18n/fi.js | 2 +- .../workspace/js/vendor/select2/i18n/fr.js | 2 +- .../workspace/js/vendor/select2/i18n/gl.js | 2 +- .../workspace/js/vendor/select2/i18n/he.js | 2 +- .../workspace/js/vendor/select2/i18n/hi.js | 2 +- .../workspace/js/vendor/select2/i18n/hr.js | 2 +- .../workspace/js/vendor/select2/i18n/hsb.js | 2 +- .../workspace/js/vendor/select2/i18n/hu.js | 2 +- .../workspace/js/vendor/select2/i18n/hy.js | 2 +- .../workspace/js/vendor/select2/i18n/id.js | 2 +- .../workspace/js/vendor/select2/i18n/is.js | 2 +- .../workspace/js/vendor/select2/i18n/it.js | 2 +- .../workspace/js/vendor/select2/i18n/ja.js | 2 +- .../workspace/js/vendor/select2/i18n/ka.js | 2 +- .../workspace/js/vendor/select2/i18n/km.js | 2 +- .../workspace/js/vendor/select2/i18n/ko.js | 2 +- .../workspace/js/vendor/select2/i18n/lt.js | 2 +- .../workspace/js/vendor/select2/i18n/lv.js | 2 +- .../workspace/js/vendor/select2/i18n/mk.js | 2 +- .../workspace/js/vendor/select2/i18n/ms.js | 2 +- .../workspace/js/vendor/select2/i18n/nb.js | 2 +- .../workspace/js/vendor/select2/i18n/ne.js | 2 +- .../workspace/js/vendor/select2/i18n/nl.js | 2 +- .../workspace/js/vendor/select2/i18n/pl.js | 2 +- .../workspace/js/vendor/select2/i18n/ps.js | 2 +- .../workspace/js/vendor/select2/i18n/pt-BR.js | 2 +- .../workspace/js/vendor/select2/i18n/pt.js | 2 +- .../workspace/js/vendor/select2/i18n/ro.js | 2 +- .../workspace/js/vendor/select2/i18n/ru.js | 2 +- .../workspace/js/vendor/select2/i18n/sk.js | 2 +- .../workspace/js/vendor/select2/i18n/sl.js | 2 +- .../workspace/js/vendor/select2/i18n/sq.js | 2 +- .../js/vendor/select2/i18n/sr-Cyrl.js | 2 +- .../workspace/js/vendor/select2/i18n/sr.js | 2 +- .../workspace/js/vendor/select2/i18n/sv.js | 2 +- .../workspace/js/vendor/select2/i18n/th.js | 2 +- .../workspace/js/vendor/select2/i18n/tk.js | 2 +- .../workspace/js/vendor/select2/i18n/tr.js | 2 +- .../workspace/js/vendor/select2/i18n/uk.js | 2 +- .../workspace/js/vendor/select2/i18n/vi.js | 2 +- .../workspace/js/vendor/select2/i18n/zh-CN.js | 2 +- .../workspace/js/vendor/select2/i18n/zh-TW.js | 2 +- .../js/vendor/select2/select2.full.min.js | 2 +- .../js/vendor/select2/select2.full.min.min.js | 1 + .../js/vendor/xregexp/xregexp.min.js | 2 +- .../js/vendor/xregexp/xregexp.min.min.js | 1 + .../workspaces/admin/batch.py | 5 +- .../workspaces/admin/cleaners/__init__.py | 6 -- .../workspaces/admin/cleaners/actions.py | 78 +++++++++---------- .../workspaces/admin/cleaners/bulk_update.py | 22 +----- .../workspaces/admin/cleaners/mass_update.py | 27 ++----- .../workspaces/admin/cleaners/regex.py | 2 +- .../workspaces/admin/cleaners/validate.py | 2 +- .../workspaces/admin/filters.py | 26 +++---- .../workspaces/admin/forms.py | 2 +- .../workspaces/admin/hh_ind.py | 55 +++---------- .../workspaces/admin/individual.py | 9 +-- .../workspaces/admin/program.py | 31 +++++--- src/country_workspace/workspaces/backend.py | 17 ++-- src/country_workspace/workspaces/config.py | 18 +---- .../workspaces/migrations/0001_initial.py | 1 - src/country_workspace/workspaces/models.py | 3 - src/country_workspace/workspaces/options.py | 10 +-- src/country_workspace/workspaces/sites.py | 48 +++--------- .../workspaces/static/workspace/js/cl.min.js | 2 +- .../static/workspace/js/import_data.min.js | 2 +- .../static/workspace/js/program.min.js | 2 +- .../workspaces/templatetags/base.py | 5 +- .../workspaces/templatetags/workspace_list.py | 34 ++++---- .../workspaces/templatetags/workspace_urls.py | 12 ++- src/country_workspace/workspaces/utils.py | 22 +++--- 204 files changed, 506 insertions(+), 741 deletions(-) create mode 100644 ruff.toml create mode 100644 src/country_workspace/web/static/workspace/js/SelectBox.min.min.js create mode 100644 src/country_workspace/web/static/workspace/js/actions.min.min.js create mode 100644 src/country_workspace/web/static/workspace/js/admin/DateTimeShortcuts.min.min.js create mode 100644 src/country_workspace/web/static/workspace/js/autocomplete.min.min.js create mode 100644 src/country_workspace/web/static/workspace/js/calendar.min.min.js create mode 100644 src/country_workspace/web/static/workspace/js/cancel.min.min.js create mode 100644 src/country_workspace/web/static/workspace/js/change_form.min.min.js create mode 100644 src/country_workspace/web/static/workspace/js/constance.min.min.js create mode 100644 src/country_workspace/web/static/workspace/js/core.min.min.js create mode 100644 src/country_workspace/web/static/workspace/js/filters.min.min.js create mode 100644 src/country_workspace/web/static/workspace/js/inlines.min.min.js create mode 100644 src/country_workspace/web/static/workspace/js/jquery.init.min.min.js create mode 100644 src/country_workspace/web/static/workspace/js/nav_sidebar.min.min.js create mode 100644 src/country_workspace/web/static/workspace/js/popup_response.min.min.js create mode 100644 src/country_workspace/web/static/workspace/js/prepopulate.min.min.js create mode 100644 src/country_workspace/web/static/workspace/js/prepopulate_init.min.min.js create mode 100644 src/country_workspace/web/static/workspace/js/theme.min.min.js create mode 100644 src/country_workspace/web/static/workspace/js/unusable_password_field.min.min.js create mode 100644 src/country_workspace/web/static/workspace/js/urlify.min.min.js create mode 100644 src/country_workspace/web/static/workspace/js/vendor/jquery/jquery.min.min.js create mode 100644 src/country_workspace/web/static/workspace/js/vendor/select2/select2.full.min.min.js create mode 100644 src/country_workspace/web/static/workspace/js/vendor/xregexp/xregexp.min.min.js diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md index 06fb206..34aedcb 100644 --- a/.github/PULL_REQUEST_TEMPLATE.md +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -1,6 +1,6 @@ # Legal Boilerplate -Look, I get it. -Contributing to HOPE Workspace, I retain all rights, title and interest in and to my contributions, and by keeping -this boilerplate intact I confirm that HOPE Workspace can use, modify, copy, and redistribute my contributions, +Look, I get it. +Contributing to HOPE Workspace, I retain all rights, title and interest in and to my contributions, and by keeping +this boilerplate intact I confirm that HOPE Workspace can use, modify, copy, and redistribute my contributions, under HOPE's choice of terms. diff --git a/.github/actions/docker_build/action.yml b/.github/actions/docker_build/action.yml index e44afee..2e466a2 100644 --- a/.github/actions/docker_build/action.yml +++ b/.github/actions/docker_build/action.yml @@ -84,7 +84,7 @@ runs: run: | build_date=$(date +"%Y-%m-%d %H:%M") echo "BUILD_DATE=$build_date" >> $GITHUB_ENV - + if [[ "${{inputs.target}}" == "dist" ]]; then echo "TAG_PREFIX=" >> $GITHUB_ENV else @@ -114,7 +114,7 @@ runs: - name: "Check Image" id: image_status shell: bash - run: | + run: | set +e echo "::notice::ℹ Checking checksum for ${{ steps.image_name.outputs.name }}" image_checksum=$(regctl image inspect \ @@ -134,7 +134,7 @@ runs: echo "::warning::🤬 Checksum: found '${image_checksum}' expected '${code_checksum}'" echo "updated=false" >> $GITHUB_OUTPUT fi - if [[ "${{inputs.rebuild}}" == "true" ]]; then + if [[ "${{inputs.rebuild}}" == "true" ]]; then echo "::warning::⚠ Forced build due input parameter" fi - name: Set up Docker BuildX @@ -188,7 +188,7 @@ runs: if: (steps.image_status.outputs.updated != 'true' || inputs.rebuild == 'true') && inputs.dryrun != 'true' shell: bash run: | - echo "${{ toJSON(steps.build_push.outputs) }}" + echo "${{ toJSON(steps.build_push.outputs) }}" regctl image inspect -p linux/amd64 ${{ steps.image_name.outputs.name }} echo "::notice:: Image ${{ steps.meta.outputs.tags }} successfully built and pushed" echo "created=true" >> $GITHUB_OUTPUT diff --git a/.github/actions/last_commit/action.yml b/.github/actions/last_commit/action.yml index e42013e..0b65c11 100644 --- a/.github/actions/last_commit/action.yml +++ b/.github/actions/last_commit/action.yml @@ -13,19 +13,19 @@ outputs: runs: using: "composite" steps: - - name: Setup Environment (PR) - if: ${{ github.event_name == 'pull_request' }} - shell: bash - run: | + - name: Setup Environment (PR) + if: ${{ github.event_name == 'pull_request' }} + shell: bash + run: | echo "LAST_COMMIT_SHA=${{ github.event.pull_request.head.sha }}" >> $GITHUB_ENV - - name: Setup Environment (Push) - if: ${{ github.event_name == 'push' }} + - name: Setup Environment (Push) + if: ${{ github.event_name == 'push' }} shell: bash - run: | + run: | echo "LAST_COMMIT_SHA=${GITHUB_SHA}" >> $GITHUB_ENV - id: result shell: bash run: | - raw=${{env.LAST_COMMIT_SHA}} + raw=${{env.LAST_COMMIT_SHA}} echo "last_commit_sha=$raw" >> $GITHUB_OUTPUT echo "last_commit_short_sha=${raw::8}" >> $GITHUB_OUTPUT diff --git a/.github/dependabot.yml b/.github/dependabot.yml index 669a7d2..da66e27 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -5,7 +5,7 @@ The property '#/updates/0/package-ecosystem' value "" did not match one of the following values: npm, bundler, composer, devcontainers, maven, mix, cargo, gradle, nuget, gomod, docker, elm, gitsubmodule, github-actions, pip, terraform, pub, swift version: 2 updates: - - package-ecosystem: "pip" + - package-ecosystem: "pip" directory: "/" schedule: interval: "weekly" diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index c20fa32..e090b45 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -229,7 +229,7 @@ jobs: # django-admin upgrade - name: Publish images - run: | + run: | docker push ${{needs.test.outputs.image}} docker inspect ${{needs.test.outputs.image}} | jq -r '.[0].Config.Labels' echo "::notice::✅ Image ${{needs.test.outputs.image}} built and pushed" diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index e945198..eb957ea 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -1,4 +1,9 @@ repos: + - repo: https://github.com/pre-commit/pre-commit-hooks + rev: v5.0.0 + hooks: + - id: end-of-file-fixer + - id: trailing-whitespace - repo: https://github.com/adamchainz/djade-pre-commit rev: "1.3.2" hooks: @@ -10,28 +15,17 @@ repos: hooks: - id: isort stages: [pre-commit] - - repo: https://github.com/ambv/black - rev: 24.10.0 - hooks: - - id: black - args: [--config=pyproject.toml] - exclude: "migrations|snapshots" - stages: [pre-commit] - - repo: https://github.com/PyCQA/flake8 - rev: 7.1.1 - hooks: - - id: flake8 - args: [--config=.flake8] - stages: [ pre-commit ] - - repo: https://github.com/PyCQA/bandit - rev: '1.7.10' # Update me! - hooks: - - id: bandit - args: ["-c", "bandit.yaml"] - repo: https://github.com/twisted/towncrier rev: 24.8.0 hooks: - id: towncrier-check + - repo: https://github.com/astral-sh/ruff-pre-commit + rev: v0.8.4 + hooks: + - id: ruff + - id: ruff-format + args: + - --check - repo: https://github.com/saxix/pch rev: '0.1' @@ -47,12 +41,3 @@ repos: - src - tests stages: [ pre-push ] - - - id: check-forbidden - args: - - -p - - /\.showbrowser\(/ - - -p - - /print\(111/ - stages: [ pre-commit ] - additional_dependencies: [ setuptools ] diff --git a/docker/Dockerfile b/docker/Dockerfile index b29219f..9caf5c3 100644 --- a/docker/Dockerfile +++ b/docker/Dockerfile @@ -92,7 +92,7 @@ RUN --mount=type=cache,target=/root/.uv-cache \ # ------- production only deps------- FROM builder AS production -ENV PATH=/app/.venv/bin:/usr/local/bin/:/usr/bin:/bin \ +ENV PATH=/venv/bin:/usr/local/bin/:/usr/bin:/bin \ DJANGO_SETTINGS_MODULE=country_workspace.config.settings \ PYTHONUNBUFFERED=1 \ PYTHONDONTWRITEBYTECODE=1 \ @@ -147,7 +147,7 @@ COPY . /app/ COPY --chown=hope:unicef --from=production /venv /venv COPY --from=builder /usr/local/bin/uwsgi /usr/local/bin/uv /usr/local/bin/ RUN --mount=type=cache,target=/root/.uv-cache \ - uv --cache-dir=/root/.uv-cache pip install --link-mode=copy --no-deps . \ + uv --cache-dir=/root/.uv-cache pip install --no-deps . \ && rm -fr /app diff --git a/docs/_theme/css/style.css.map b/docs/_theme/css/style.css.map index 594fe81..fa5bb01 100644 --- a/docs/_theme/css/style.css.map +++ b/docs/_theme/css/style.css.map @@ -1 +1 @@ -{"version":3,"sourceRoot":"","sources":["style.scss"],"names":[],"mappings":"AAAA;EACE;EACA;EACA;;;AAEF;EACE;;;AAGF;EACE","file":"style.css"} \ No newline at end of file +{"version":3,"sourceRoot":"","sources":["style.scss"],"names":[],"mappings":"AAAA;EACE;EACA;EACA;;;AAEF;EACE;;;AAGF;EACE","file":"style.css"} diff --git a/docs/src/contributing.md b/docs/src/contributing.md index 41fb29b..09c15a7 100644 --- a/docs/src/contributing.md +++ b/docs/src/contributing.md @@ -22,15 +22,15 @@ Install [uv](https://docs.astral.sh/uv/) wget https://github.com/sqreen/PyMiniRacer/files/7575004/libmini_racer.dylib.zip 1. Unzip The Dylib file - + unzip libmini_racer.dylib.zip - + 1. MV Dylib file to your site-packages mv libmini_racer.dylib /opt/homebrew/Caskroom/miniconda/base/lib/python3.8/site-packages/py_mini_racer/. 1. Import Success. - + >>> from py_mini_racer import MiniRacer @@ -42,11 +42,11 @@ CSS. CSS sources are located in the `country_workspace/workspaces/theme/static_s If you need to edit the CSS follow the below steps: 1. Install node dependencies - + ./manage.py tailwind install 1. Configure the enviroment - + export EXTRA_APPS="country_workspace.contrib.hope,django_browser_reload" export EXTRA_MIDDLEWARES="django_browser_reload.middleware.BrowserReloadMiddleware," diff --git a/docs/src/dev_helpers.md b/docs/src/dev_helpers.md index 66e602e..866ad41 100644 --- a/docs/src/dev_helpers.md +++ b/docs/src/dev_helpers.md @@ -6,4 +6,4 @@ show_bases: false show_bases: false show_root_heading: true - show_source: true + show_source: true diff --git a/docs/src/flows/import.md b/docs/src/flows/import.md index 8b1da60..f09cc4e 100644 --- a/docs/src/flows/import.md +++ b/docs/src/flows/import.md @@ -3,7 +3,7 @@ ## Spreadsheet import -```mermaid +```mermaid graph TD A[Upload file] --> B{All records are valid?} diff --git a/docs/src/flows/model.md b/docs/src/flows/model.md index b1312d0..4da62c1 100644 --- a/docs/src/flows/model.md +++ b/docs/src/flows/model.md @@ -6,13 +6,13 @@ erDiagram Spreadsheet { string title } - + Error { string sheet int row string column } - + Program ||--o{ Spreadsheet: has Program ||--o{ Individual: has Program ||--o{ Household: has diff --git a/ruff.toml b/ruff.toml new file mode 100644 index 0000000..271a402 --- /dev/null +++ b/ruff.toml @@ -0,0 +1,65 @@ +target-version = "py312" +line-length = 120 + +[lint.isort] +case-sensitive = true + +[lint] +select = [ + "A", ## prevent using keywords that clobber python builtins + "B", # bugbear: security warnings + "BLE", # blind exceptions + "C4", # flake8-comprehensions + "C901", # McCabe complexity + "D", # pydocstyle + "DJ", # flake8-django + "E", # pycodestylex + "E4", "E7", "E9", + "ERA", # eradicate + "F", # pyflakes + "FURB", # refurb + "I", # isort + "ISC", # implicit string concatenation + "PERF", # perflint + "PIE", # flake8-pie + "PL", # PyLint + "S", # bandit, + "SIM", # flake8-simplify + "T10", # flake8-debugger + "UP", # pyupgrade +] +extend-select = ["UP", ] +ignore = [ + "B904", # raise-without-from-inside-except: syntax not compatible with py2 + "D100", # Missing docstring in public module + "D101", # Missing docstring in public class + "D102", # Missing docstring in public method + "D103", # Missing docstring in public function + "D104", # Missing docstring in public package + "D105", # Missing docstring in magic method + "D106", # Missing docstring in public nested class + "D107", # Missing docstring in `__init__` + "D203", # one-blank-line-before-class + "D212", # multi-line-summary-first-line + "D213", # multi-line-summary-second-line + "E731", # lambda-assignment: lambdas are substential in maintenance of py2/3 codebase + "ISC001", # conflicts with ruff format command + "RUF005", # collection-literal-concatenation: syntax not compatible with py2 + "RUF012", # mutable-class-default: typing is not available for py2 + "I001", # unsorted imports https://docs.astral.sh/ruff/rules/unsorted-imports/#unsorted-imports-i001 + "UP037", # [*] Remove quotes from type annotation + "UP035", # Import from `collections.abc` instead: `Sequence` + "UP031", # Use format specifiers instead of percent format + "SIM108", # Use ternary operator instead of... + "PLR2004", # Magic value used in comparison + "DJ001", # Avoid using `null=True` on string-based fields such as `CharField` +] + +[format] +quote-style = "double" +indent-style = "space" +skip-magic-trailing-comma = false +line-ending = "auto" + +[lint.per-file-ignores] +"tests/**.py" = ["S101", "PLR2004", "S", "SIM117", "D"] diff --git a/src/country_workspace/admin/filters.py b/src/country_workspace/admin/filters.py index ca87e3a..e0d6b06 100644 --- a/src/country_workspace/admin/filters.py +++ b/src/country_workspace/admin/filters.py @@ -39,7 +39,6 @@ def html_attrs(self): class IsValidFilter(SimpleListFilter): title = "Valid" parameter_name = "valid" - # template = "workspace/adminfilters/combobox.html" def lookups(self, request, model_admin): return ( diff --git a/src/country_workspace/admin/individual.py b/src/country_workspace/admin/individual.py index 69acd46..cdce73d 100644 --- a/src/country_workspace/admin/individual.py +++ b/src/country_workspace/admin/individual.py @@ -13,7 +13,6 @@ @admin.register(Individual) class IndividualAdmin(BaseModelAdmin): list_display = ("name", "batch") - # readonly_fields = ("country_office",) search_fields = ("name",) list_filter = ( ("batch__country_office", LinkedAutoCompleteFilter.factory(parent=None)), diff --git a/src/country_workspace/admin/job.py b/src/country_workspace/admin/job.py index 0b95326..d79c230 100644 --- a/src/country_workspace/admin/job.py +++ b/src/country_workspace/admin/job.py @@ -1,4 +1,4 @@ -from typing import Optional, Sequence +from typing import Sequence from django.contrib import admin from django.http import HttpRequest @@ -23,7 +23,7 @@ class AsyncJobAdmin(CeleryTaskModelAdmin, BaseModelAdmin): FailedFilter, ) - def get_readonly_fields(self, request: "HttpRequest", obj: "Optional[AsyncJob]" = None) -> Sequence[str]: + def get_readonly_fields(self, request: "HttpRequest", obj: "AsyncJob | None" = None) -> Sequence[str]: if obj: return ("program", "batch", "owner", "local_status", "type", "action", "sentry_id") return super().get_readonly_fields(request, obj) diff --git a/src/country_workspace/admin/locations.py b/src/country_workspace/admin/locations.py index c9755e9..e0bc605 100644 --- a/src/country_workspace/admin/locations.py +++ b/src/country_workspace/admin/locations.py @@ -1,5 +1,5 @@ import logging -from typing import TYPE_CHECKING, Any, List, Tuple +from typing import TYPE_CHECKING, Any from django.contrib import admin from django.contrib.admin import ModelAdmin, RelatedFieldListFilter @@ -44,7 +44,7 @@ class AreaTypeAdmin(AdminFiltersMixin, admin.ModelAdmin): class AreaTypeFilter(RelatedFieldListFilter): - def field_choices(self, field: Any, request: "HttpRequest", model_admin: ModelAdmin) -> List[Tuple[str, str]]: + def field_choices(self, field: Any, request: "HttpRequest", model_admin: ModelAdmin) -> list[tuple[str, str]]: if "area_type__country__exact" not in request.GET: return [] return AreaType.objects.filter(country=request.GET["area_type__country__exact"]).values_list("id", "name") diff --git a/src/country_workspace/admin/program.py b/src/country_workspace/admin/program.py index d2009e4..ac76d89 100644 --- a/src/country_workspace/admin/program.py +++ b/src/country_workspace/admin/program.py @@ -57,9 +57,6 @@ def _action(request: HttpRequest) -> HttpResponse: success_message="Successfully executed", ) - # base = reverse("admin:country_workspace_individual_changelist") - # btn.href = f"{base}?household__exact={obj.pk}" - @button() def sync(self, request: HttpRequest) -> None: from country_workspace.contrib.hope.sync.office import sync_programs diff --git a/src/country_workspace/admin/user.py b/src/country_workspace/admin/user.py index f261ba0..f6b1eff 100644 --- a/src/country_workspace/admin/user.py +++ b/src/country_workspace/admin/user.py @@ -24,8 +24,6 @@ def autocomplete(self, request): qs = qs.filter( Q(roles__program__id=program) | Q(is_superuser=True) | Q(roles__country_office__programs__pk=program) ) - results = [] - for user in qs.all(): - results.append({"id": user.id, "text": user.username}) + results = [{"id": user.id, "text": user.username} for user in qs.all()] res = {"results": results, "pagination": {"more": False}} return JsonResponse(res) diff --git a/src/country_workspace/cache/ddt.py b/src/country_workspace/cache/ddt.py index 1cd7762..c5a1ab0 100644 --- a/src/country_workspace/cache/ddt.py +++ b/src/country_workspace/cache/ddt.py @@ -54,7 +54,7 @@ def process_request(self, request): @property def nav_subtitle(self): - return "~{} gets / ~{} sets".format(len(self.gets), len(self.sets)) + return f"~{len(self.gets)} gets / ~{len(self.sets)} sets" def generate_stats(self, request, response): self.record_stats( diff --git a/src/country_workspace/cache/handlers.py b/src/country_workspace/cache/handlers.py index 8856c75..3829093 100644 --- a/src/country_workspace/cache/handlers.py +++ b/src/country_workspace/cache/handlers.py @@ -10,13 +10,11 @@ @receiver(post_save) def update_cache(sender: "type[Model]", instance: Model, **kwargs): program = None - if isinstance(instance, (Household, Individual, CountryHousehold, CountryIndividual)): + if isinstance(instance, (Household | Individual | CountryHousehold | CountryIndividual)): program = instance.program - elif isinstance(instance, (Program, CountryProgram)): + elif isinstance(instance, (Program | CountryProgram)): program = instance - elif isinstance(instance, (AsyncJob, CountryAsyncJob)): - program = instance.program - elif isinstance(instance, (Batch, CountryBatch)): + elif isinstance(instance, (AsyncJob | CountryAsyncJob | Batch | CountryBatch)): program = instance.program if program: cache_manager.incr_cache_version(program=program) diff --git a/src/country_workspace/cache/manager.py b/src/country_workspace/cache/manager.py index a4e96b5..37703bc 100644 --- a/src/country_workspace/cache/manager.py +++ b/src/country_workspace/cache/manager.py @@ -1,5 +1,5 @@ import logging -from typing import TYPE_CHECKING, Any, Optional +from typing import TYPE_CHECKING, Any from django.core.cache import caches from django.core.cache.backends.redis import RedisCacheClient @@ -62,9 +62,8 @@ def store(self, key: str, value: Any, timeout: int = 0, **kwargs): timeout = 1 self.cache.set(key, value, timeout=timeout or self.cache_timeout, **kwargs) - def _get_version_key(self, office: "Optional[Office]" = None, program: "Optional[Program]" = None): + def _get_version_key(self, office: "Office | None" = None, program: "Program | None" = None): if program: - program = program office = program.country_office elif office: program = None @@ -72,11 +71,11 @@ def _get_version_key(self, office: "Optional[Office]" = None, program: "Optional parts = [self.prefix, "key", office.slug if office else "-", str(program.pk) if program else "-"] return ":".join(parts) - def reset_cache_version(self, *, office: "Optional[Office]" = None, program: "Optional[Program]" = None): + def reset_cache_version(self, *, office: "Office | None" = None, program: "Program | None" = None): key = self._get_version_key(office, program) self.cache.delete(key) - def get_cache_version(self, *, office: "Optional[Office]" = None, program: "Optional[Program]" = None): + def get_cache_version(self, *, office: "Office | None" = None, program: "Program | None" = None): key = self._get_version_key(office, program) version = self.cache.get(key) if not version: @@ -84,7 +83,7 @@ def get_cache_version(self, *, office: "Optional[Office]" = None, program: "Opti self.cache.set(key, version, timeout=self.cache_timeout) return version - def incr_cache_version(self, *, office: "Optional[Office]" = None, program: "Optional[Program]" = None): + def incr_cache_version(self, *, office: "Office | None" = None, program: "Program | None" = None): if office and program: raise ValueError("Cannot use both office and program") key = self._get_version_key(office, program) @@ -128,17 +127,5 @@ def build_key_from_request(self, request, prefix="view", *args): prefix, slugify(request.path), slugify(str(sorted(request.GET.items()))), *[str(e) for e in args] ) - # - # def store(self, request, value): - # key = self._build_key_from_request(request) - # cache_store.send(CacheManager, key=key, request=request, value=value) - # self.set(key, value) - # - # def retrieve(self, request, prefix=""): - # key = self.build_key_from_request(request) - # if data := cache.get(key): - # return pickle.loads(data) - # return None - cache_manager = CacheManager() diff --git a/src/country_workspace/cache/middleware.py b/src/country_workspace/cache/middleware.py index 3b1cba6..4d490de 100644 --- a/src/country_workspace/cache/middleware.py +++ b/src/country_workspace/cache/middleware.py @@ -25,11 +25,6 @@ def process_response(self, request, response): if response.streaming or response.status_code not in (200, 304): return response - # Don't cache responses that set a user-specific (and maybe security - # sensitive) cookie in response to a cookie-less request. - # if not request.COOKIES and response.cookies and has_vary_header(response, "Cookie"): - # return response - # Don't cache a response with 'Cache-Control: private' if "private" in response.get("Cache-Control", ()): return response @@ -37,15 +32,6 @@ def process_response(self, request, response): # Page timeout takes precedence over the "max-age" and the default # cache timeout. timeout = self.page_timeout - # if timeout is None: - # # The timeout from the "max-age" section of the "Cache-Control" - # # header takes precedence over the default cache timeout. - # timeout = get_max_age(response) - # if timeout is None: - # timeout = self.cache_timeout - # elif timeout == 0: - # # max-age was set to 0, don't cache. - # return response patch_response_headers(response, timeout) if response.status_code == 200: cache_key = self.manager.build_key_from_request(request) @@ -68,7 +54,6 @@ def process_request(self, request): return None # Don't bother checking the cache. # try and get the cached GET response - # cache_key = get_cache_key(request, self.key_prefix, "GET", cache=self.cache) cache_key = self.manager.build_key_from_request(request) if cache_key is None: request._cache_update_cache = True @@ -76,10 +61,6 @@ def process_request(self, request): if request.headers.get("etag") == cache_key: return HttpResponse(status=304, headers={"Etag": cache_key}) response = self.manager.retrieve(cache_key) - # if it wasn't found and we are looking for a HEAD, try looking just for that - # if response is None and request.method == "HEAD": - # cache_key = get_cache_key(request, self.key_prefix, "HEAD", cache=self.cache) - # response = self.manager.get(cache_key) if response is None: request._cache_update_cache = True diff --git a/src/country_workspace/compat/admin_extra_buttons.py b/src/country_workspace/compat/admin_extra_buttons.py index 453da4c..45c8f51 100644 --- a/src/country_workspace/compat/admin_extra_buttons.py +++ b/src/country_workspace/compat/admin_extra_buttons.py @@ -5,7 +5,7 @@ from django.urls import reverse -def confirm_action( +def confirm_action( # noqa: PLR0913 modeladmin, request, action, diff --git a/src/country_workspace/config/__init__.py b/src/country_workspace/config/__init__.py index ee48926..3898e59 100644 --- a/src/country_workspace/config/__init__.py +++ b/src/country_workspace/config/__init__.py @@ -1,15 +1,15 @@ from enum import Enum -from typing import TYPE_CHECKING, Any, Dict, Optional, TypeAlias, Union +from typing import TYPE_CHECKING, Any from smart_env import SmartEnv if TYPE_CHECKING: - ConfigItem: TypeAlias = Union[ - tuple[type, Any, Any, bool, str], - tuple[type, Optional[Any], Optional[Any], bool], - tuple[type, Any, Any], - tuple[type, Any], - ] + ConfigItem: type = ( + tuple[type, Any, Any, bool, str] + | tuple[type, Any | None, Any | None, bool] + | tuple[type, Any, Any] + | tuple[type, Any] + ) DJANGO_HELP_BASE = "https://docs.djangoproject.com/en/5.0/ref/settings" @@ -26,7 +26,7 @@ class Group(Enum): DJANGO = 1 -CONFIG: "Dict[str, ConfigItem]" = { +CONFIG: "dict[str, ConfigItem]" = { "SUPERUSERS": ( list, [], @@ -107,12 +107,6 @@ class Group(Enum): "https://django-environ.readthedocs.io/en/latest/types.html#environ-env-db-url", ), "DEBUG": (bool, False, True, False, setting("debug")), - # "EMAIL_BACKEND": ( - # str, - # "django.core.mail.backends.smtp.EmailBackend", - # setting("email-backend"), - # True, - # ), "EMAIL_HOST": (str, "", "", False, setting("email-host")), "EMAIL_HOST_USER": (str, "", "", False, setting("email-host-user")), "EMAIL_HOST_PASSWORD": (str, "", "", False, setting("email-host-password")), @@ -168,9 +162,8 @@ class Group(Enum): "Hope API token", ), "HOPE_API_TOKEN": (str, "", "", False, "Hope API token"), - "MEDIA_ROOT": (str, "/var/media/", "/tmp/media", True, setting("media-root")), # nosec - "MEDIA_URL": (str, "/media/", "/media", False, setting("media-root")), # nosec - # "ROOT_TOKEN": (str, "", ""), + "MEDIA_ROOT": (str, "/var/media/", "/tmp/media", True, setting("media-root")), # noqa: S108 + "MEDIA_URL": (str, "/media/", "/media", False, setting("media-root")), # noqa: S108 "SECRET_KEY": ( str, "", @@ -180,38 +173,18 @@ class Group(Enum): ), "ROOT_TOKEN_HEADER": (str, "x-root-token", "x-root-token"), "ROOT_TOKEN": (str, "", ""), - # "SECURE_HSTS_PRELOAD": (bool, True, setting("secure-hsts-preload"), False), - # "SECURE_HSTS_SECONDS": (int, 60, setting("secure-hsts-seconds")), - # "SECURE_SSL_REDIRECT": (bool, True, setting("secure-ssl-redirect"), False), "SENTRY_DSN": (str, "", "", False, "Sentry DSN"), "SENTRY_URL": (str, "", "", False, "Sentry server url"), "SENTRY_ENVIRONMENT": (str, ""), - # "SESSION_COOKIE_DOMAIN": ( - # str, - # "", - # setting("std-setting-SESSION_COOKIE_DOMAIN"), - # "localhost", - # ), - # "SESSION_COOKIE_HTTPONLY": (bool, True, setting("session-cookie-httponly"), False), - # "SESSION_COOKIE_NAME": (str, "dedupe_session", setting("session-cookie-name")), - # "SESSION_COOKIE_PATH": (str, "/", setting("session-cookie-path")), - # "SESSION_COOKIE_SECURE": (bool, True, setting("session-cookie-secure"), False), - # "SIGNING_BACKEND": ( - # str, - # "django.core.signing.TimestampSigner", - # setting("signing-backend"), - # ), "SOCIAL_AUTH_LOGIN_URL": (str, "/login/", "", False, ""), "SOCIAL_AUTH_RAISE_EXCEPTIONS": (bool, False, True, False), "SOCIAL_AUTH_REDIRECT_IS_HTTPS": (bool, True, False, False, ""), - "STATIC_ROOT": (str, "/var/static", "/tmp/static", True, setting("static-root")), # nosec - "STATIC_URL": (str, "/static/", "/static/", False, setting("static-url")), # nosec + "STATIC_ROOT": (str, "/var/static", "/tmp/static", True, setting("static-root")), # noqa: S108 + "STATIC_URL": (str, "/static/", "/static/", False, setting("static-url")), # noqa: S108 "TIME_ZONE": (str, "UTC", "UTC", False, setting("std-setting-TIME_ZONE")), "AZURE_CLIENT_SECRET": (str, "", "", False, "Azure client secret for SSO"), "AZURE_TENANT_ID": (str, "", "", False, "Azure tenant ID for SSO"), "AZURE_CLIENT_KEY": (str, "", "", False, "Azure client key for SSO"), - # "AZURE_CONNECTION_STRING": (str, ""), - # "CV2DNN_PATH": (str, ""), } env = SmartEnv(**CONFIG) diff --git a/src/country_workspace/config/celery.py b/src/country_workspace/config/celery.py index bf4f2e2..42871db 100644 --- a/src/country_workspace/config/celery.py +++ b/src/country_workspace/config/celery.py @@ -31,7 +31,7 @@ def on_failure(self, exc, task_id, args, kwargs, einfo): super().on_failure(exc, task_id, args, kwargs, einfo) def __call__(self, *args, **kwargs): - h = hashlib.new("md5") # nosec + h = hashlib.new("md5") # noqa: S324 h.update(json.dumps(kwargs, sort_keys=True).encode("utf-8")) self.lock_key = f"lock:{self.name}:{'-'.join(map(str, args)).encode('utf-8')}:{h.hexdigest()}" if self.acquire_lock(): diff --git a/src/country_workspace/config/fragments/csp.py b/src/country_workspace/config/fragments/csp.py index 56eac05..07daa1a 100644 --- a/src/country_workspace/config/fragments/csp.py +++ b/src/country_workspace/config/fragments/csp.py @@ -1,6 +1,3 @@ -# CSP_DEFAULT_SRC = ["'self'", "'unsafe-inline'", "'same-origin'", -# "fonts.googleapis.com", 'fonts.gstatic.com', 'data:', -# 'blob:', "cdn.redoc.ly"] CSP_DEFAULT_SRC = ["'self'", "'unsafe-inline'", "cdnjs.cloudflare.com"] CSP_STYLE_SRC = [ "'self'", diff --git a/src/country_workspace/config/fragments/rest_framework.py b/src/country_workspace/config/fragments/rest_framework.py index 4ff99a8..f4357ff 100644 --- a/src/country_workspace/config/fragments/rest_framework.py +++ b/src/country_workspace/config/fragments/rest_framework.py @@ -1,19 +1,8 @@ -from typing import Any, Dict +from typing import Any -REST_FRAMEWORK: Dict[str, Any] = { - # "DEFAULT_PAGINATION_CLASS": "rest_framework.pagination.PageNumberPagination", - # "DEFAULT_VERSIONING_CLASS": "rest_framework.versioning.NamespaceVersioning", - # "DEFAULT_FILTER_BACKENDS": ("django_filters.rest_framework.DjangoFilterBackend",), - # "DEFAULT_RENDERER_CLASSES": ( - # "rest_framework.renderers.JSONRenderer", - # "rest_framework.renderers.BrowsableAPIRenderer", - # "rest_framework_datatables.renderers.DatatablesRenderer", - # ), - # "PAGE_SIZE": 30, +REST_FRAMEWORK: dict[str, Any] = { "DEFAULT_AUTHENTICATION_CLASSES": [ - # "rest_framework.authentication.BasicAuthentication", "rest_framework.authentication.SessionAuthentication", - # "rest_framework.authentication.TokenAuthentication", ], "DEFAULT_PERMISSION_CLASSES": [ "rest_framework.permissions.DjangoModelPermissions", @@ -21,21 +10,4 @@ "DEFAULT_SCHEMA_CLASS": "drf_spectacular.openapi.AutoSchema", } -JWT_AUTH: Dict[str, Any] = { - # "JWT_VERIFY": False, # this requires private key - # "JWT_VERIFY_EXPIRATION": True, - # "JWT_LEEWAY": 60, - # "JWT_EXPIRATION_DELTA": datetime.timedelta(seconds=30000), - # "JWT_AUDIENCE": None, - # "JWT_ISSUER": None, - # "JWT_ALLOW_REFRESH": False, - # "JWT_REFRESH_EXPIRATION_DELTA": datetime.timedelta(days=7), - # "JWT_AUTH_HEADER_PREFIX": "JWT", - # "JWT_SECRET_KEY": SECRET_KEY, - # "JWT_DECODE_HANDLER": "rest_framework_jwt.utils.jwt_decode_handler", - # Keys will be set in core.apps.Config.ready() - # "JWT_PUBLIC_KEY": "?", - # 'JWT_PRIVATE_KEY': wallet.get_private(), - # 'JWT_PRIVATE_KEY': None, - # "JWT_ALGORITHM": "RS256", -} +JWT_AUTH: dict[str, Any] = {} diff --git a/src/country_workspace/config/fragments/social_auth.py b/src/country_workspace/config/fragments/social_auth.py index 7d7603b..ddd0f92 100644 --- a/src/country_workspace/config/fragments/social_auth.py +++ b/src/country_workspace/config/fragments/social_auth.py @@ -13,7 +13,6 @@ ] SOCIAL_AUTH_JSONFIELD_ENABLED = True SOCIAL_AUTH_URL_NAMESPACE = "social" -# SOCIAL_AUTH_REQUIRE_POST = True SOCIAL_AUTH_STRATEGY = "country_workspace.social.strategy.HDEStrategy" diff --git a/src/country_workspace/config/settings.py b/src/country_workspace/config/settings.py index fb033e8..1278dde 100644 --- a/src/country_workspace/config/settings.py +++ b/src/country_workspace/config/settings.py @@ -2,7 +2,6 @@ from . import env -# BASE_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir)) SETTINGS_DIR = Path(__file__).parent PACKAGE_DIR = SETTINGS_DIR.parent DEVELOPMENT_DIR = PACKAGE_DIR.parent.parent @@ -86,13 +85,10 @@ # path MEDIA_ROOT = env("MEDIA_ROOT") MEDIA_URL = env("MEDIA_URL") -# STATIC_ROOT = env("STATIC_ROOT") STATIC_URL = env("STATIC_URL") # # -# # STATICFILES_DIRS = [] STATICFILES_FINDERS = [ - # "django.contrib.staticfiles.finders.FileSystemFinder", "django.contrib.staticfiles.finders.AppDirectoriesFinder", ] @@ -132,7 +128,6 @@ CACHE_URL = env("CACHE_URL") SELECT2_CACHE = env("SELECT2_CACHE") -# REDIS_URL = urlparse(CACHE_URL).hostname CACHES = { "default": { "BACKEND": "redis_lock.django_cache.RedisCache", diff --git a/src/country_workspace/config/urls.py b/src/country_workspace/config/urls.py index 2b89246..27f2694 100644 --- a/src/country_workspace/config/urls.py +++ b/src/country_workspace/config/urls.py @@ -23,8 +23,3 @@ urlpatterns += [path(r"__reload__/", include("django_browser_reload.urls"))] urlpatterns += [path(r"", workspace.urls)] - -# -# admin.site.site_header = "Workspace Admin" -# admin.site.site_title = "Workspace Admin Portal" -# admin.site.index_title = "Welcome to HOPE Workspace" diff --git a/src/country_workspace/contrib/aurora/client.py b/src/country_workspace/contrib/aurora/client.py index 75ef590..613a50c 100644 --- a/src/country_workspace/contrib/aurora/client.py +++ b/src/country_workspace/contrib/aurora/client.py @@ -23,6 +23,7 @@ def __init__(self, token: str | None = None) -> None: Args: token (str | None): An optional API token for authentication. If not provided, the token is retrieved from the Constance configuration (config.AURORA_API_TOKEN). + """ self.token = token or config.AURORA_API_TOKEN @@ -35,6 +36,7 @@ def _get_url(self, path: str) -> str: Returns: str: The full URL, ensuring it ends with a trailing slash. + """ url = urljoin(config.AURORA_API_URL, path) if not url.endswith("/"): @@ -55,6 +57,7 @@ def get(self, path: str) -> Generator[dict[str, Any], None, None]: RemoteError: If the API response has a non-200 status code, if there's an issue with the network request, or if the response contains invalid JSON. + """ url = self._get_url(path) while url: @@ -70,7 +73,5 @@ def get(self, path: str) -> Generator[dict[str, Any], None, None]: except JSONDecodeError: raise RemoteError(f"Wrong JSON response fetching {url}") - for record in data["results"]: - yield record - + yield from data["results"] url = data.get("next") diff --git a/src/country_workspace/contrib/aurora/forms.py b/src/country_workspace/contrib/aurora/forms.py index 792bc0b..6bb8f40 100644 --- a/src/country_workspace/contrib/aurora/forms.py +++ b/src/country_workspace/contrib/aurora/forms.py @@ -2,7 +2,6 @@ class ImportAuroraForm(forms.Form): - batch_name = forms.CharField(required=False, help_text="Label for this batch") check_before = forms.BooleanField(required=False, help_text="Prevent import if errors") diff --git a/src/country_workspace/contrib/aurora/sync.py b/src/country_workspace/contrib/aurora/sync.py index 1852609..e067ddd 100644 --- a/src/country_workspace/contrib/aurora/sync.py +++ b/src/country_workspace/contrib/aurora/sync.py @@ -8,14 +8,14 @@ def sync_aurora_job(job: AsyncJob) -> dict[str, int]: - """ - Synchronizes data from the Aurora system into the database for the given job within an atomic transaction. + """Synchronize data from the Aurora system into the database for the given job within an atomic transaction. Args: job (AsyncJob): The job instance containing configuration and context for synchronization. Returns: dict[str, int]: A dictionary with counts of households and individuals created. + """ batch_name = job.config["batch_name"] batch = Batch.objects.create( @@ -40,15 +40,15 @@ def sync_aurora_job(job: AsyncJob) -> dict[str, int]: def _create_household(batch: Batch, fields: dict[str, Any]) -> Household: - """ - Creates a household entity associated with the given job and batch. + """Create a household entity associated with the given job and batch. Args: - job (AsyncJob): The job instance containing context for household creation. + batch (Batch): The job instance containing context for household creation. fields (dict[str, Any]): A dictionary containing household data fields. Returns: Household: The newly created household instance. + """ return batch.program.households.create(batch=batch, flex_fields={clean_field_name(k): v for k, v in fields.items()}) @@ -56,16 +56,16 @@ def _create_household(batch: Batch, fields: dict[str, Any]) -> Household: def _create_individuals( household: Household, data: list[dict[str, Any]], household_name_column: str ) -> list[Individual]: - """ - Creates individuals associated with a household and updates the household name if necessary. + """Create individuals associated with a household and updates the household name if necessary. Args: - job (AsyncJob): The job instance containing configuration and context for individual creation. household (Household): The household to associate with the individuals. - fields (list[dict[str, Any]]): A list of dictionaries containing individual data fields. + data (list[dict[str, Any]]): A list of dictionaries containing individual data fields. + household_name_column (str): The name of the column in household that contains the name of the individuals. Returns: list[Individual]: The list of newly created individual instances. + """ individuals = [] head_found = False @@ -89,24 +89,23 @@ def _create_individuals( def _update_household_name_from_individual( household: Household, individual: dict[str, Any], household_name_column: str ) -> bool: - """ - Updates the household name based on an individual's relationship and name field. + """Update the household name based on an individual's relationship and name field. This method checks if the individual is marked as the head of the household and updates the household name accordingly. Args: - job (AsyncJob): The job instance containing configuration details. household (Household): The household to update. individual (dict[str, Any]): The individual data containing potential household name information. + household_name_column (str): The name of the column in household that contains the name of the individuals. Returns: None + """ if any(individual.get(k) == "head" for k in individual if k.startswith("relationship")): for k, v in individual.items(): if clean_field_name(k) == household_name_column: household.name = v household.save() - # household.program.households.filter(pk=household.pk).update(name=v) return True diff --git a/src/country_workspace/contrib/hope/client.py b/src/country_workspace/contrib/hope/client.py index c5917b2..038c47f 100644 --- a/src/country_workspace/contrib/hope/client.py +++ b/src/country_workspace/contrib/hope/client.py @@ -2,7 +2,7 @@ import re import time from json import JSONDecodeError -from typing import TYPE_CHECKING, Any, Generator, Optional, Union +from typing import TYPE_CHECKING, Any, Generator import requests from constance import config @@ -13,8 +13,8 @@ from .signals import hope_request_end, hope_request_start if TYPE_CHECKING: - JsonType = Union[None, int, str, bool, list["JsonType"], dict[str, "JsonType"]] - FlatJsonType = dict[str, Union[str, int, bool]] + JsonType = None | int | str | bool | list["JsonType"] | dict[str, "JsonType"] + FlatJsonType = dict[str, str | int | bool] def sanitize_url(url: str) -> str: @@ -22,8 +22,7 @@ def sanitize_url(url: str) -> str: class HopeClient: - - def __init__(self, token: Optional[str] = None): + def __init__(self, token: str | None = None): self.token = token or config.HOPE_API_TOKEN def get_url(self, path: str) -> str: @@ -34,23 +33,21 @@ def get_url(self, path: str) -> str: def get_lookup(self, path: str) -> "FlatJsonType": url = self.get_url(path) - ret = requests.get(url, headers={"Authorization": f"Token {self.token}"}) # nosec + ret = requests.get(url, headers={"Authorization": f"Token {self.token}"}, timeout=60) # nosec if ret.status_code != 200: raise RemoteError(f"Error {ret.status_code} fetching {url}") return ret.json() - def get(self, path: str, params: Optional[dict[str, Any]] = None) -> "Generator[FlatJsonType, None, None]": + def get(self, path: str, params: dict[str, Any] | None = None) -> "Generator[FlatJsonType, None, None]": url: "str|None" = self.get_url(path) - signature = hashlib.sha256(f"{url}{params}{time.perf_counter_ns()}".encode("utf-8")).hexdigest() + signature = hashlib.sha256(f"{url}{params}{time.perf_counter_ns()}".encode()).hexdigest() pages = 0 hope_request_start.send(self.__class__, url=url, params=params, signature=signature) while True: if not url: break try: - ret = requests.get( - url, params=params, headers={"Authorization": f"Token {self.token}"}, timeout=10 - ) # nosec + ret = requests.get(url, params=params, headers={"Authorization": f"Token {self.token}"}, timeout=10) # nosec if ret.status_code != 200: raise RemoteError(f"Error {ret.status_code} fetching {url}") pages += 1 @@ -62,12 +59,8 @@ def get(self, path: str, params: Optional[dict[str, Any]] = None) -> "Generator[ except JSONDecodeError: raise RemoteError(f"Wrong JSON response fetching {url}") try: - for record in data["results"]: - yield record - if "next" in data: - url = data["next"] - else: - url = None + yield from data["results"] + url = data.get("next", None) except TypeError: raise RemoteError(f"Malformed JSON fetching {url}") hope_request_end.send(self.__class__, url=url, params=params, pages=pages, signature=signature) diff --git a/src/country_workspace/contrib/hope/ddt.py b/src/country_workspace/contrib/hope/ddt.py index 8cc1da0..d85f427 100644 --- a/src/country_workspace/contrib/hope/ddt.py +++ b/src/country_workspace/contrib/hope/ddt.py @@ -34,7 +34,6 @@ def enable_instrumentation(self): hope_request_end.connect(functools.partial(self.log, action="end")) def log(self, **kwargs): - if kwargs["action"] == "start": self.timing[kwargs["signature"]] = time.perf_counter() self.calls.append(ApiCall(self, kwargs)) @@ -50,7 +49,7 @@ def process_request(self, request): @property def nav_subtitle(self): - return "{} calls".format(len(self.calls)) + return f"{len(self.calls)} calls" def generate_stats(self, request, response): self.record_stats({"calls": self.calls}) diff --git a/src/country_workspace/contrib/hope/geo.py b/src/country_workspace/contrib/hope/geo.py index 0301542..d7a7af1 100644 --- a/src/country_workspace/contrib/hope/geo.py +++ b/src/country_workspace/contrib/hope/geo.py @@ -39,7 +39,7 @@ def get_choices_for_parent_value(self, parent_value: Any, only_codes=False) -> l logger.exception(e) return ret - for i, record in enumerate(data): + for record in data: if only_codes: ret.append(record["p_code"]) else: @@ -48,7 +48,6 @@ def get_choices_for_parent_value(self, parent_value: Any, only_codes=False) -> l class CountryChoice(forms.ChoiceField): - def get_choices(self) -> list[tuple[str, str]]: ret = [] key = "lookups/country" @@ -60,9 +59,7 @@ def get_choices(self) -> list[tuple[str, str]]: except RemoteError as e: logger.exception(e) return ret - for i, record in enumerate(data): - ret.append((record["iso_code3"], record["name"])) - + ret = [(record["iso_code3"], record["name"]) for record in data] return ret def __init__(self, **kwargs): diff --git a/src/country_workspace/contrib/hope/remotes/country.py b/src/country_workspace/contrib/hope/remotes/country.py index 0d34bb5..4a7e986 100644 --- a/src/country_workspace/contrib/hope/remotes/country.py +++ b/src/country_workspace/contrib/hope/remotes/country.py @@ -1,4 +1,4 @@ -from typing import TYPE_CHECKING, Optional +from typing import TYPE_CHECKING from django import forms @@ -24,13 +24,11 @@ class CountryAttributeHandler(AbstractAttributeHandler): def set(self, value: "Json"): pass - def get(self, instance: "Optional[FlexField]" = None) -> "Json": + def get(self, instance: "FlexField | None" = None) -> "Json": from country_workspace.contrib.hope.client import HopeClient client = HopeClient() results = client.get(self.config["remote_url"]) - data = [] self.owner.strategy_config = {} - for row in results: - data.append((row["id"], row["name"])) + data = [(row["id"], row["name"]) for row in results] return {"choices": data} diff --git a/src/country_workspace/contrib/hope/sync/office.py b/src/country_workspace/contrib/hope/sync/office.py index be5c7b5..721bb40 100644 --- a/src/country_workspace/contrib/hope/sync/office.py +++ b/src/country_workspace/contrib/hope/sync/office.py @@ -1,5 +1,3 @@ -from typing import Optional - from django.core.cache import cache from hope_flex_fields.models import DataChecker @@ -14,7 +12,7 @@ def sync_offices() -> dict[str, int]: client = HopeClient() totals = {"add": 0, "upd": 0} with cache.lock("sync-offices"): - for i, record in enumerate(client.get("business_areas")): + for record in client.get("business_areas"): if record["active"]: __, created = Office.objects.get_or_create( hope_id=record["id"], @@ -34,7 +32,7 @@ def sync_offices() -> dict[str, int]: return totals -def sync_programs(limit_to_office: "Optional[Office]" = None) -> dict[str, int]: +def sync_programs(limit_to_office: "Office | None" = None) -> dict[str, int]: client = HopeClient() hh_chk = DataChecker.objects.filter(name=constants.HOUSEHOLD_CHECKER_NAME).first() ind_chk = DataChecker.objects.filter(name=constants.INDIVIDUAL_CHECKER_NAME).first() @@ -42,7 +40,7 @@ def sync_programs(limit_to_office: "Optional[Office]" = None) -> dict[str, int]: if limit_to_office: office = limit_to_office with cache.lock("sync-programs"): - for i, record in enumerate(client.get("programs")): + for record in client.get("programs"): try: if limit_to_office and record["business_area_code"] != office.code: continue diff --git a/src/country_workspace/contrib/hope/validators.py b/src/country_workspace/contrib/hope/validators.py index 4dff3a8..4ba990b 100644 --- a/src/country_workspace/contrib/hope/validators.py +++ b/src/country_workspace/contrib/hope/validators.py @@ -5,7 +5,6 @@ class FullHouseholdValidator(BeneficiaryGroupValidator): - def validate(self, hh: "Household") -> list: errs = [] try: diff --git a/src/country_workspace/datasources/rdi.py b/src/country_workspace/datasources/rdi.py index c9a4888..d4c222c 100644 --- a/src/country_workspace/datasources/rdi.py +++ b/src/country_workspace/datasources/rdi.py @@ -1,5 +1,4 @@ import io -from typing import Union from django.db.transaction import atomic @@ -8,7 +7,7 @@ from country_workspace.models import AsyncJob, Batch, Household from country_workspace.utils.fields import clean_field_name -RDI = Union[str, io.BytesIO] +RDI = str | io.BytesIO def import_from_rdi(job: AsyncJob) -> dict[str, int]: @@ -20,8 +19,6 @@ def import_from_rdi(job: AsyncJob) -> dict[str, int]: master_column_label = job.config["master_column_label"] detail_column_label = job.config["detail_column_label"] rdi = job.file - # household_pk_col = form.cleaned_data["pk_column_name"] - # total_hh = total_ind = 0 batch = Batch.objects.create( name=batch_name, program=job.program, @@ -56,6 +53,6 @@ def import_from_rdi(job: AsyncJob) -> dict[str, int]: flex_fields=record, ) ret["individual"] += 1 - except Exception as e: + except Exception as e: # noqa: BLE001 raise Exception("Error processing sheet %s line %s: %s" % (1 + sheet_index, line, e)) return ret diff --git a/src/country_workspace/management/commands/demo.py b/src/country_workspace/management/commands/demo.py index cf8efb0..5c8b367 100644 --- a/src/country_workspace/management/commands/demo.py +++ b/src/country_workspace/management/commands/demo.py @@ -35,7 +35,7 @@ def handle(self, *args: Any, **options: Any) -> None: ) Site.objects.clear_cache() - for flag in settings.FLAGS.keys(): + for flag in settings.FLAGS: FlagState.objects.get_or_create(name=flag, condition="hostname", value="127.0.0.1,localhost") Office.objects.get_or_create( @@ -49,7 +49,7 @@ def handle(self, *args: Any, **options: Any) -> None: user, __ = User.objects.get_or_create(username="user") test_utils_dir = Path(__file__).parent.parent.parent.parent.parent / "tests/extras" - assert test_utils_dir.exists(), str(test_utils_dir.absolute()) + " does not exist" # nosec B101 + assert test_utils_dir.exists(), str(test_utils_dir.absolute()) + " does not exist" # noqa: S101 sys.path.append(str(test_utils_dir.absolute())) import vcr diff --git a/src/country_workspace/management/commands/sync.py b/src/country_workspace/management/commands/sync.py index f116340..a1b2400 100644 --- a/src/country_workspace/management/commands/sync.py +++ b/src/country_workspace/management/commands/sync.py @@ -13,5 +13,4 @@ class Command(BaseCommand): requires_system_checks = [] def handle(self, *args: Any, **options: Any) -> None: - sync_all() diff --git a/src/country_workspace/management/commands/trigger_error.py b/src/country_workspace/management/commands/trigger_error.py index b40089b..fb7c4af 100644 --- a/src/country_workspace/management/commands/trigger_error.py +++ b/src/country_workspace/management/commands/trigger_error.py @@ -14,6 +14,6 @@ class Command(BaseCommand): def handle(self, *args: Any, **options: Any) -> None: # noqa try: - 1 / 0 - except Exception as e: # pragma: no cover + 1 / 0 # noqa: B018 + except ValueError as e: # pragma: no cover sentry_sdk.capture_exception(e) diff --git a/src/country_workspace/middleware/exception.py b/src/country_workspace/middleware/exception.py index cccd3d8..5cd0c32 100644 --- a/src/country_workspace/middleware/exception.py +++ b/src/country_workspace/middleware/exception.py @@ -10,6 +10,6 @@ class ExceptionMiddleware(MiddlewareMixin): def process_exception(self, request: "HttpRequest", exception: Exception) -> "HttpResponse": - if isinstance(exception, (PermissionDenied,)): + if isinstance(exception, PermissionDenied): return render(request, "403.html", {"message": "Permission denied"}, status=403) raise exception diff --git a/src/country_workspace/migrations/0001_initial.py b/src/country_workspace/migrations/0001_initial.py index 6d4eda5..ed1e54e 100644 --- a/src/country_workspace/migrations/0001_initial.py +++ b/src/country_workspace/migrations/0001_initial.py @@ -14,7 +14,6 @@ class Migration(migrations.Migration): - initial = True dependencies = [ @@ -96,7 +95,8 @@ class Migration(migrations.Migration): "is_active", models.BooleanField( default=True, - help_text="Designates whether this user should be treated as active. Unselect this instead of deleting accounts.", + help_text="Designates whether this user should be treated as active. " + "Unselect this instead of deleting accounts.", verbose_name="active", ), ), @@ -108,7 +108,8 @@ class Migration(migrations.Migration): "groups", models.ManyToManyField( blank=True, - help_text="The groups this user belongs to. A user will get all permissions granted to each of their groups.", + help_text="The groups this user belongs to. " + "A user will get all permissions granted to each of their groups.", related_name="user_set", related_query_name="user", to="auth.group", diff --git a/src/country_workspace/models/base.py b/src/country_workspace/models/base.py index 039d688..2f02851 100644 --- a/src/country_workspace/models/base.py +++ b/src/country_workspace/models/base.py @@ -1,4 +1,4 @@ -from typing import TYPE_CHECKING, Any, Optional +from typing import TYPE_CHECKING, Any from django.db import models from django.urls import reverse @@ -18,7 +18,6 @@ class BaseQuerySet(models.QuerySet["models.Model"]): - def get(self, *args: Any, **kwargs: Any) -> "models.Model": try: return super().get(*args, **kwargs) @@ -42,7 +41,6 @@ class ValidableManager(models.Manager["Validable"]): class Cachable: - def country_office(self): raise NotImplementedError @@ -78,10 +76,6 @@ class Meta: ("export_beneficiary", "Can Export Beneficiary Records"), ) - def __init__(self, *args, **kwargs): - super().__init__(*args, **kwargs) - self._checksum = self.checksum - def __str__(self) -> str: return self.name or "%s %s" % (self._meta.verbose_name, self.id) @@ -97,6 +91,10 @@ def save(self, *args, force_insert=False, force_update=False, using=None, update if state.request: reversion.set_user(state.request.user) + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + self._checksum = self.checksum + def checker(self) -> "DataChecker": raise NotImplementedError @@ -118,7 +116,7 @@ def last_changes(self) -> "Any": current_status = self.flex_fields return list(dictdiffer.diff(stored_status, current_status)) - def diff(self, first: Optional[int] = None, second: Optional[int] = None) -> "Any": + def diff(self, first: int | None = None, second: int | None = None) -> "Any": from reversion.models import Version qs = Version.objects.get_for_object(self).order_by("pk") diff --git a/src/country_workspace/models/jobs.py b/src/country_workspace/models/jobs.py index 0d3c224..8944c44 100644 --- a/src/country_workspace/models/jobs.py +++ b/src/country_workspace/models/jobs.py @@ -22,25 +22,19 @@ class JobType(models.TextChoices): sentry_id = models.CharField(max_length=255, blank=True, null=True) celery_task_name = "country_workspace.tasks.sync_job_task" - def __str__(self): - return self.description or f"Background Job #{self.pk}" - class Meta: permissions = (("debug_job", "Can debug background jobs"),) + def __str__(self): + return self.description or f"Background Job #{self.pk}" + @property def queue_position(self) -> int: - try: - return super().queue_position - except Exception: - return 0 + return super().queue_position @property def started(self) -> str: - try: - return self.task_info["started_at"] - except Exception: - return "=" + return self.task_info["started_at"] def execute(self): sid = None diff --git a/src/country_workspace/models/program.py b/src/country_workspace/models/program.py index bb5704a..56902b7 100644 --- a/src/country_workspace/models/program.py +++ b/src/country_workspace/models/program.py @@ -1,4 +1,4 @@ -from typing import TYPE_CHECKING, Union +from typing import TYPE_CHECKING from django.db import models from django.db.models import QuerySet @@ -104,13 +104,13 @@ def individuals(self) -> "QuerySet[Individual]": return Individual.objects.filter(batch__program=self) - def get_checker_for(self, m: Union[type[Validable], Validable]) -> DataChecker: + def get_checker_for(self, m: type[Validable] | Validable) -> DataChecker: from country_workspace.models import Household, Individual from country_workspace.workspaces.models import CountryHousehold, CountryIndividual - if isinstance(m, (Household, CountryHousehold)) or m in (Household, CountryHousehold): + if isinstance(m, (Household | CountryHousehold)) or m in (Household, CountryHousehold): return self.household_checker - elif isinstance(m, (Individual, CountryIndividual)) or m in (Individual, CountryIndividual): + elif isinstance(m, (Individual | CountryIndividual)) or m in (Individual, CountryIndividual): return self.individual_checker else: raise ValueError(m) diff --git a/src/country_workspace/models/sync.py b/src/country_workspace/models/sync.py index ca4fa1c..22fc0fb 100644 --- a/src/country_workspace/models/sync.py +++ b/src/country_workspace/models/sync.py @@ -18,12 +18,10 @@ def create_lookups(self) -> None: ct = ContentType.objects.get_for_model(FieldDefinition) for m in settings.HH_LOOKUPS: - fd = FieldDefinition.objects.get(name="HOPE HH {m}".format(m=m)) - SyncLog.objects.get_or_create( - content_type=ct, object_id=fd.pk, data={"remote_url": "lookups/%s" % m.lower()} - ) + fd = FieldDefinition.objects.get(name=f"HOPE HH {m}") + SyncLog.objects.get_or_create(content_type=ct, object_id=fd.pk, data={"remote_url": f"lookups/{m.lower()}"}) for m in settings.IND_LOOKUPS: - fd = FieldDefinition.objects.get(name="HOPE IND {m}".format(m=m)) + fd = FieldDefinition.objects.get(name=f"HOPE IND {m}") SyncLog.objects.get_or_create( content_type=ct, object_id=fd.pk, data={"remote_url": "lookups/%s" % m.lower()} ) diff --git a/src/country_workspace/security/backends.py b/src/country_workspace/security/backends.py index 4bbe149..c13305c 100644 --- a/src/country_workspace/security/backends.py +++ b/src/country_workspace/security/backends.py @@ -1,4 +1,4 @@ -from typing import TYPE_CHECKING, Any, Optional +from typing import TYPE_CHECKING, Any from django.conf import settings from django.contrib.auth import get_user_model @@ -13,11 +13,11 @@ class AnyUserAuthBackend(ModelBackend): - """DEBUG Only smart auth backend auto-create users""" + """DEBUG Only smart auth backend auto-create users.""" def authenticate( self, - request: "Optional[HttpRequest]", + request: "HttpRequest | None", username: str | None = None, password: str | None = None, **kwargs: Any, @@ -28,7 +28,7 @@ def authenticate( if username in offices: user, __ = get_user_model().objects.update_or_create( username=username, - defaults=dict(is_staff=True, is_active=True, is_superuser=False), + defaults={"is_staff": True, "is_active": True, "is_superuser": False}, ) office = Office.objects.get(slug=username) g = Group.objects.get(name=settings.ANALYST_GROUP_NAME) @@ -37,7 +37,7 @@ def authenticate( elif username in ["admin", "superuser", "administrator", "sax"]: user, __ = get_user_model().objects.update_or_create( username=username, - defaults=dict(is_staff=True, is_active=True, is_superuser=True), + defaults={"is_staff": True, "is_active": True, "is_superuser": True}, ) return user elif username in [ @@ -45,7 +45,7 @@ def authenticate( ]: user, __ = get_user_model().objects.update_or_create( username=username, - defaults=dict(is_staff=True, is_active=True, is_superuser=False), + defaults={"is_staff": True, "is_active": True, "is_superuser": False}, ) return user return None diff --git a/src/country_workspace/security/utils.py b/src/country_workspace/security/utils.py index 6c2e115..ce34c54 100644 --- a/src/country_workspace/security/utils.py +++ b/src/country_workspace/security/utils.py @@ -5,10 +5,5 @@ def setup_workspace_group() -> None: ws_group, __ = Group.objects.get_or_create(name=settings.ANALYST_GROUP_NAME) Group.objects.get_or_create(name=settings.NEW_USER_DEFAULT_GROUP) - # perms = [ - # "workspaces.view_countryhousehold", - # "workspaces.view_countryindividual", - # ] for perm in Permission.objects.filter(content_type__app_label="workspaces"): - # app, codename= perm_code.split(".") ws_group.permissions.add(perm) diff --git a/src/country_workspace/social/pipeline.py b/src/country_workspace/social/pipeline.py index d07906c..d0576b4 100644 --- a/src/country_workspace/social/pipeline.py +++ b/src/country_workspace/social/pipeline.py @@ -1,4 +1,4 @@ -from typing import Any, Optional +from typing import Any from django.conf import settings from django.contrib.auth.models import Group, User @@ -6,14 +6,14 @@ from constance import config -def save_to_group(user: Optional[User] = None, **kwargs: Any) -> dict[str, Any]: +def save_to_group(user: User | None = None, **kwargs: Any) -> dict[str, Any]: if user: grp = Group.objects.get(name=config.NEW_USER_DEFAULT_GROUP) user.groups.add(grp) return {} -def set_superusers(user: Optional[User] = None, is_new: bool = False, **kwargs: Any) -> dict[str, Any]: +def set_superusers(user: User | None = None, is_new: bool = False, **kwargs: Any) -> dict[str, Any]: if user and is_new and user.email in settings.SUPERUSERS: user.is_superuser = True user.save() diff --git a/src/country_workspace/state.py b/src/country_workspace/state.py index f91780c..f9f0a20 100644 --- a/src/country_workspace/state.py +++ b/src/country_workspace/state.py @@ -1,14 +1,14 @@ import contextlib from copy import copy from threading import local -from typing import TYPE_CHECKING, Dict +from typing import TYPE_CHECKING from django.core.signing import get_cookie_signer from django.http import HttpRequest, HttpResponse if TYPE_CHECKING: from collections.abc import Iterator - from typing import Any, List + from typing import Any from .models import Office, Program @@ -21,15 +21,15 @@ class State(local): program_cookie: "str|None" = None tenant: "Office|None" = None program: "Program|None" = None - cookies: "dict[str, List[Any]]" = {} - filters: "List[Any]" = [] + cookies: "dict[str, list[Any]]" = {} + filters: "list[Any]" = [] inspecting: bool = False def __repr__(self) -> str: return f"" @contextlib.contextmanager - def configure(self, **kwargs: "Dict[str,Any]") -> "Iterator[None]": + def configure(self, **kwargs: "dict[str,Any]") -> "Iterator[None]": pre = copy(self.__dict__) self.reset() with self.set(**kwargs): @@ -38,7 +38,7 @@ def configure(self, **kwargs: "Dict[str,Any]") -> "Iterator[None]": setattr(self, k, v) @contextlib.contextmanager - def set(self, **kwargs: "Dict[str,Any]") -> "Iterator[None]": + def set(self, **kwargs: "dict[str,Any]") -> "Iterator[None]": pre = {} for k, v in kwargs.items(): if hasattr(self, k): @@ -65,7 +65,7 @@ def set_selected_program(self, program: "Program") -> None: signer = get_cookie_signer() self.add_cookies("selected_program", signer.sign(program.id)) - def add_cookies( + def add_cookies( # noqa: PLR0913 self, key: str, value: str, diff --git a/src/country_workspace/types.pyi b/src/country_workspace/types.pyi index d8736b3..2730047 100644 --- a/src/country_workspace/types.pyi +++ b/src/country_workspace/types.pyi @@ -1,5 +1,3 @@ -from typing import TypeVar, Union - from country_workspace.models import Household, Individual -Beneficiary = Union[Household, Individual] +Beneficiary = Household | Individual diff --git a/src/country_workspace/utils/constance.py b/src/country_workspace/utils/constance.py index c5b2738..26c22af 100644 --- a/src/country_workspace/utils/constance.py +++ b/src/country_workspace/utils/constance.py @@ -1,5 +1,5 @@ import logging -from typing import Any, Optional +from typing import Any from django.forms import ChoiceField, HiddenInput, Textarea, TextInput from django.template import Context, Template @@ -11,16 +11,15 @@ class ObfuscatedInput(HiddenInput): - def render( - self, name: str, value: Any, attrs: Optional[dict[str, str]] = None, renderer: Optional[Any] = None + self, name: str, value: Any, attrs: dict[str, str] | None = None, renderer: Any | None = None ) -> "SafeString": context = self.get_context(name, value, attrs) context["value"] = str(value) context["label"] = "Set" if value else "Not Set" tpl = Template('{{ label }}') - return mark_safe(tpl.render(Context(context))) # nosec B308 B703 + return mark_safe(tpl.render(Context(context))) # noqa: S308 class WriteOnlyWidget: @@ -46,8 +45,6 @@ class GroupChoiceField(ChoiceField): def __init__(self, **kwargs: Any) -> None: from django.contrib.auth.models import Group - ret: list[tuple[str | int, str]] = [] - for c in Group.objects.values("pk", "name"): - ret.append((c["name"], c["name"])) + ret: list[tuple[str | int, str]] = [(c["name"], c["name"]) for c in Group.objects.values("pk", "name")] kwargs["choices"] = ret super().__init__(**kwargs) diff --git a/src/country_workspace/utils/fields.py b/src/country_workspace/utils/fields.py index 1e3fa65..5fcc85c 100644 --- a/src/country_workspace/utils/fields.py +++ b/src/country_workspace/utils/fields.py @@ -2,15 +2,14 @@ def clean_field_name(v: str) -> str: - """ - Normalize a field name by removing specific substrings (case-insensitive) - and converting it to lowercase. + """Normalize a field name by removing specific substrings (case-insensitive) and converting it to lowercase. Args: v (str): The original field name. Returns: str: The cleaned field name. + """ to_remove = ("_h_c", "_h_f", "_i_c", "_i_f") return reduce(lambda name, substr: name.replace(substr, ""), to_remove, v.lower()) diff --git a/src/country_workspace/utils/flags.py b/src/country_workspace/utils/flags.py index da8253e..bc6c2f3 100644 --- a/src/country_workspace/utils/flags.py +++ b/src/country_workspace/utils/flags.py @@ -16,7 +16,7 @@ def validate_bool(value: Any) -> None: - if not str(value).lower() in [ + if str(value).lower() not in [ "true", "1", "yes", @@ -39,7 +39,7 @@ def superuser(value: str, request: "HttpRequest|None", **kwargs: "Any") -> bool: @conditions.register("debug", validator=validate_bool) def debug(value: str, **kwargs: "Any") -> bool: - return settings.DEBUG == parse_bool(value) + return settings.DEBUG is parse_bool(value) @conditions.register("hostname") diff --git a/src/country_workspace/utils/flex_fields.py b/src/country_workspace/utils/flex_fields.py index 3d528f4..7ac47f4 100644 --- a/src/country_workspace/utils/flex_fields.py +++ b/src/country_workspace/utils/flex_fields.py @@ -15,7 +15,7 @@ def get_checker_fields(checker: DataChecker) -> tuple[str, str]: def get_obj_checksum(obj: "Validable") -> str: - h = hashlib.new("md5") # nosec + h = hashlib.new("md5") # noqa: S324 data = json.dumps(obj.flex_fields, sort_keys=True).encode("utf-8") h.update(data) if obj.flex_files: diff --git a/src/country_workspace/utils/http.py b/src/country_workspace/utils/http.py index 575fc11..6d37b2d 100644 --- a/src/country_workspace/utils/http.py +++ b/src/country_workspace/utils/http.py @@ -1,4 +1,4 @@ -from typing import TYPE_CHECKING, Any, Dict, Optional, Sequence +from typing import TYPE_CHECKING, Any, Sequence from urllib.parse import urljoin from django.conf import settings @@ -12,7 +12,7 @@ from ..types.http import AnyRequest -def get_server_host(request: "Optional[AnyRequest]" = None) -> str: +def get_server_host(request: "AnyRequest | None" = None) -> str: req: HttpRequest | None = request or state.request host = req.get_host() domain, port = split_domain_port(host) @@ -42,7 +42,7 @@ def absolute_uri(url: str | None = None) -> str: return uri -def absolute_reverse(name: str, args: Sequence[Any] | None = None, kwargs: Dict[str, Any] | None = None) -> str: +def absolute_reverse(name: str, args: Sequence[Any] | None = None, kwargs: dict[str, Any] | None = None) -> str: return absolute_uri(reverse(name, args=args, kwargs=kwargs)) diff --git a/src/country_workspace/versioning/checkers.py b/src/country_workspace/versioning/checkers.py index ec88fae..96f5d24 100644 --- a/src/country_workspace/versioning/checkers.py +++ b/src/country_workspace/versioning/checkers.py @@ -5,7 +5,7 @@ from country_workspace.contrib.hope.constants import HOUSEHOLD_CHECKER_NAME, INDIVIDUAL_CHECKER_NAME -def create_hope_checkers() -> None: +def create_hope_checkers() -> None: # noqa: PLR0915 _char = FieldDefinition.objects.get(field_type=forms.CharField) _date = FieldDefinition.objects.get(field_type=forms.DateField) _bool = FieldDefinition.objects.get(field_type=forms.BooleanField) @@ -60,9 +60,6 @@ def create_hope_checkers() -> None: ]: hh_fs.fields.get_or_create(name=segment, definition=_int, attrs={"required": False}) - # hh_fs.fields.get_or_create(definition=_bf, name="hh_latrine_h_f", attrs={"label": "Latrine"}) - # hh_fs.fields.get_or_create(definition=_bf, name="hh_electricity_h_f") - ind_fs, __ = Fieldset.objects.get_or_create(name=INDIVIDUAL_CHECKER_NAME) ind_fs.fields.get_or_create(name="address", attrs={"label": "Address", "required": True}, definition=_char) ind_fs.fields.get_or_create( diff --git a/src/country_workspace/versioning/management/commands/upgradescripts.py b/src/country_workspace/versioning/management/commands/upgradescripts.py index 80cfc90..9387f92 100644 --- a/src/country_workspace/versioning/management/commands/upgradescripts.py +++ b/src/country_workspace/versioning/management/commands/upgradescripts.py @@ -53,13 +53,13 @@ def handle(self, command, label=None, num=None, fake=None, zero=False, **options for entry in m.existing: stem = Path(entry).stem x = "x" if m.is_processed(entry) else " " - self.stdout.write("[{x}] {name}".format(x=x, name=stem)) + self.stdout.write(f"[{x}] {stem}") elif command == "create": new_ver = m.max_version + 1 ts = now().strftime("%Y_%m_%d_%H%M%S") today = now().strftime("%Y %m %d %H:%M:%S") - dest_file = m.folder / "{:>04}_{}.py".format(new_ver, label or ts) + dest_file = m.folder / f"{new_ver:>04}_{label or ts}.py" with dest_file.open("w") as f: f.write(VERSION_TEMPLATE % {"timestamp": ts, "version": country_workspace.VERSION, "today": today}) if options["verbosity"] > 0: diff --git a/src/country_workspace/versioning/management/manager.py b/src/country_workspace/versioning/management/manager.py index 11396f1..01aeb42 100644 --- a/src/country_workspace/versioning/management/manager.py +++ b/src/country_workspace/versioning/management/manager.py @@ -25,16 +25,15 @@ def get_funcs(filename: Path, direction: str = "forward"): spec.loader.exec_module(module) funcs = [] for op in module.Scripts.operations: - if isinstance(op, (list, tuple)): + if isinstance(op, (list | tuple)): if direction == "forward": funcs.append(op[0]) else: funcs.append(op[1]) + elif direction == "forward": + funcs.append(op) else: - if direction == "forward": - funcs.append(op) - else: - funcs.append(lambda: True) + funcs.append(lambda: True) return funcs diff --git a/src/country_workspace/versioning/migrations/0001_initial.py b/src/country_workspace/versioning/migrations/0001_initial.py index ff88d7c..d5edece 100644 --- a/src/country_workspace/versioning/migrations/0001_initial.py +++ b/src/country_workspace/versioning/migrations/0001_initial.py @@ -5,7 +5,6 @@ class Migration(migrations.Migration): - initial = True dependencies = [] diff --git a/src/country_workspace/versioning/migrations/0002_rename_version_script.py b/src/country_workspace/versioning/migrations/0002_rename_version_script.py index b150796..cf2a339 100644 --- a/src/country_workspace/versioning/migrations/0002_rename_version_script.py +++ b/src/country_workspace/versioning/migrations/0002_rename_version_script.py @@ -4,7 +4,6 @@ class Migration(migrations.Migration): - dependencies = [ ("versioning", "0001_initial"), ] diff --git a/src/country_workspace/versioning/models.py b/src/country_workspace/versioning/models.py index 2745317..9cc5499 100644 --- a/src/country_workspace/versioning/models.py +++ b/src/country_workspace/versioning/models.py @@ -7,6 +7,9 @@ class Script(models.Model): version = models.CharField(max_length=255) applied = models.DateTimeField(default=now) + def __str__(self): + return self.name + def num(self) -> str: return self.name.split("_", 1)[0] diff --git a/src/country_workspace/web/static/hr.css.map b/src/country_workspace/web/static/hr.css.map index 713a4c5..f2ba31a 100644 --- a/src/country_workspace/web/static/hr.css.map +++ b/src/country_workspace/web/static/hr.css.map @@ -1 +1 @@ -{"version":3,"sourceRoot":"","sources":["hr.scss"],"names":[],"mappings":"AAEA;AAAA;EAGE;EACA;EACA;;;AAOF;AAAA;EAEE;EACA;EACA;EACA;EACA;EACA;AAAA;;;AA+BF;EACE;EACA;;AAGA;EACE,kBAzDU;;AA6DV;EACE;;AAIJ;EACE,kBAnEU;;AAwEV;EACE,OAzEQ;;;AA8Ed;EACE;EACA;;AACA;EACE;;AAEF;EACE;;AAEF;EACE;EACA;;AAEF;EACE;;AAEF;EACE;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;;AACA;EACE;;AAEF;EACE;EACA;;AAEF;EACI;;AAEJ;EAIE;EACA;;AAJA;EACE;;;AAQR;EACE;;AAEA;EACE;;;AAIJ;EACE;;;AAGF;EACE;EACA;EACA;;;AAGF;EACE;EACA;;;AAGF;EACE;EACA;;;AAIF;EACE;EACA;EACA","file":"hr.css"} \ No newline at end of file +{"version":3,"sourceRoot":"","sources":["hr.scss"],"names":[],"mappings":"AAEA;AAAA;EAGE;EACA;EACA;;;AAOF;AAAA;EAEE;EACA;EACA;EACA;EACA;EACA;AAAA;;;AA+BF;EACE;EACA;;AAGA;EACE,kBAzDU;;AA6DV;EACE;;AAIJ;EACE,kBAnEU;;AAwEV;EACE,OAzEQ;;;AA8Ed;EACE;EACA;;AACA;EACE;;AAEF;EACE;;AAEF;EACE;EACA;;AAEF;EACE;;AAEF;EACE;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;;AACA;EACE;;AAEF;EACE;EACA;;AAEF;EACI;;AAEJ;EAIE;EACA;;AAJA;EACE;;;AAQR;EACE;;AAEA;EACE;;;AAIJ;EACE;;;AAGF;EACE;EACA;EACA;;;AAGF;EACE;EACA;;;AAGF;EACE;EACA;;;AAIF;EACE;EACA;EACA","file":"hr.css"} diff --git a/src/country_workspace/web/static/smart_admin/console.css.map b/src/country_workspace/web/static/smart_admin/console.css.map index 0d79ddf..fea37e0 100644 --- a/src/country_workspace/web/static/smart_admin/console.css.map +++ b/src/country_workspace/web/static/smart_admin/console.css.map @@ -1 +1 @@ -{"version":3,"sourceRoot":"","sources":["console.scss"],"names":[],"mappings":"AAKE,mBACE,sBACA,kBAEF,uBACE,4BAIF,4BACE,WAEF,iBACE,iBACA,kBACA,sBACA,WACA,aACA","file":"console.css"} \ No newline at end of file +{"version":3,"sourceRoot":"","sources":["console.scss"],"names":[],"mappings":"AAKE,mBACE,sBACA,kBAEF,uBACE,4BAIF,4BACE,WAEF,iBACE,iBACA,kBACA,sBACA,WACA,aACA","file":"console.css"} diff --git a/src/country_workspace/web/static/smart_admin/smart_admin.css.map b/src/country_workspace/web/static/smart_admin/smart_admin.css.map index 64c1b86..c442243 100644 --- a/src/country_workspace/web/static/smart_admin/smart_admin.css.map +++ b/src/country_workspace/web/static/smart_admin/smart_admin.css.map @@ -1 +1 @@ -{"version":3,"sourceRoot":"","sources":["smart_admin.scss"],"names":[],"mappings":"AAAA,OACE,aACA,cACE,cAUA,kCACE,yBAQF,2BACE","file":"smart_admin.css"} \ No newline at end of file +{"version":3,"sourceRoot":"","sources":["smart_admin.scss"],"names":[],"mappings":"AAAA,OACE,aACA,cACE,cAUA,kCACE,yBAQF,2BACE","file":"smart_admin.css"} diff --git a/src/country_workspace/web/static/workspace/css/constance.css b/src/country_workspace/web/static/workspace/css/constance.css index b6bb583..db02b46 100644 --- a/src/country_workspace/web/static/workspace/css/constance.css +++ b/src/country_workspace/web/static/workspace/css/constance.css @@ -19,7 +19,7 @@ .item-anchor { visibility: hidden; margin-left: .1em; -} +} .item-name { white-space: nowrap; } diff --git a/src/country_workspace/web/static/workspace/css/cw.css.map b/src/country_workspace/web/static/workspace/css/cw.css.map index 801694c..3669436 100644 --- a/src/country_workspace/web/static/workspace/css/cw.css.map +++ b/src/country_workspace/web/static/workspace/css/cw.css.map @@ -1 +1 @@ -{"version":3,"sourceRoot":"","sources":["cw.scss"],"names":[],"mappings":"AAIA;AAAA;EAEE;EACA;EACA;EACA;;;AAGF;AAAA;EAEE;EACA;EACA;EACA;EACA;EACA;;;AAEF;EAEE;EACA;EACA;EACA;;;AAOF;EACE;EACA;;AAGA;EACE,kBAtCU;;AA0CV;EACE;;AAIJ;EACE,kBAhDU;;AAqDV;EACE,OAtDQ;;;AA2Dd;EACE;EACA;;AACA;EACE;;AAEF;EACE;;AAEF;EACE;EACA;;AAEF;EACE;;AAEF;EACE;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;;AACA;EACE;;AAEF;EACE;EACA;;AAEF;EACI;;AAEJ;EAIE;EACA;;AAJA;EACE;;;AAQR;EACE;;AAEA;EACE;;;AAIJ;EACE;;;AAGF;EACE;EACA;EACA;;;AAGF;EACE;EACA;;;AAGF;EACE;EACA;;;AAIF;EACE;EACA;EACA;;;AAGF;EACI;;;AAEJ;EACE;EACA;;;AAIA;EACE;;;AAIJ;EACE;EACA;;;AAEF;EACE;;;AAGF;EACE;EACA;EACA;EACA;;;AAGF;EACI;;;AAGJ;EACE;;;AAEF;EACE;EACA;EACA;EACA;EACA;;;AAGA;EACE,kBA3LU;;;AA8Ld;EACE;EACA;EACA;EACA;EACA;;AACA;EACE;;AAEF;EACE;EACA","file":"cw.css"} \ No newline at end of file +{"version":3,"sourceRoot":"","sources":["cw.scss"],"names":[],"mappings":"AAIA;AAAA;EAEE;EACA;EACA;EACA;;;AAGF;AAAA;EAEE;EACA;EACA;EACA;EACA;EACA;;;AAEF;EAEE;EACA;EACA;EACA;;;AAOF;EACE;EACA;;AAGA;EACE,kBAtCU;;AA0CV;EACE;;AAIJ;EACE,kBAhDU;;AAqDV;EACE,OAtDQ;;;AA2Dd;EACE;EACA;;AACA;EACE;;AAEF;EACE;;AAEF;EACE;EACA;;AAEF;EACE;;AAEF;EACE;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;;AACA;EACE;;AAEF;EACE;EACA;;AAEF;EACI;;AAEJ;EAIE;EACA;;AAJA;EACE;;;AAQR;EACE;;AAEA;EACE;;;AAIJ;EACE;;;AAGF;EACE;EACA;EACA;;;AAGF;EACE;EACA;;;AAGF;EACE;EACA;;;AAIF;EACE;EACA;EACA;;;AAGF;EACI;;;AAEJ;EACE;EACA;;;AAIA;EACE;;;AAIJ;EACE;EACA;;;AAEF;EACE;;;AAGF;EACE;EACA;EACA;EACA;;;AAGF;EACI;;;AAGJ;EACE;;;AAEF;EACE;EACA;EACA;EACA;EACA;;;AAGA;EACE,kBA3LU;;;AA8Ld;EACE;EACA;EACA;EACA;EACA;;AACA;EACE;;AAEF;EACE;EACA","file":"cw.css"} diff --git a/src/country_workspace/web/static/workspace/css/dark_mode.css b/src/country_workspace/web/static/workspace/css/dark_mode.css index 7e12a81..869127d 100644 --- a/src/country_workspace/web/static/workspace/css/dark_mode.css +++ b/src/country_workspace/web/static/workspace/css/dark_mode.css @@ -2,32 +2,32 @@ :root { --primary: #264b5d; --primary-fg: #f7f7f7; - + --body-fg: #eeeeee; --body-bg: #121212; --body-quiet-color: #d0d0d0; --body-medium-color: #e0e0e0; --body-loud-color: #ffffff; - + --breadcrumbs-link-fg: #e0e0e0; --breadcrumbs-bg: var(--primary); - + --link-fg: #81d4fa; --link-hover-color: #4ac1f7; --link-selected-fg: #6f94c6; - + --hairline-color: #272727; --border-color: #353535; - + --error-fg: #e35f5f; --message-success-bg: #006b1b; --message-warning-bg: #583305; --message-error-bg: #570808; - + --darkened-bg: #212121; --selected-bg: #1b1b1b; --selected-row: #00363a; - + --close-button-bg: #333333; --close-button-hover-bg: #666666; diff --git a/src/country_workspace/web/static/workspace/img/gis/move_vertex_off.svg b/src/country_workspace/web/static/workspace/img/gis/move_vertex_off.svg index 228854f..c9d16e0 100644 --- a/src/country_workspace/web/static/workspace/img/gis/move_vertex_off.svg +++ b/src/country_workspace/web/static/workspace/img/gis/move_vertex_off.svg @@ -1 +1 @@ - \ No newline at end of file + diff --git a/src/country_workspace/web/static/workspace/img/gis/move_vertex_on.svg b/src/country_workspace/web/static/workspace/img/gis/move_vertex_on.svg index 96b87fd..12f81ae 100644 --- a/src/country_workspace/web/static/workspace/img/gis/move_vertex_on.svg +++ b/src/country_workspace/web/static/workspace/img/gis/move_vertex_on.svg @@ -1 +1 @@ - \ No newline at end of file + diff --git a/src/country_workspace/web/static/workspace/js/SelectBox.min.js b/src/country_workspace/web/static/workspace/js/SelectBox.min.js index 0092fb5..7586f95 100644 --- a/src/country_workspace/web/static/workspace/js/SelectBox.min.js +++ b/src/country_workspace/web/static/workspace/js/SelectBox.min.js @@ -1 +1 @@ -"use strict";{const SelectBox={cache:{},init:function(id){const box=document.getElementById(id);SelectBox.cache[id]=[];const cache=SelectBox.cache[id];for(const node of box.options){cache.push({value:node.value,text:node.text,displayed:1})}},redisplay:function(id){const box=document.getElementById(id);const scroll_value_from_top=box.scrollTop;box.innerHTML="";for(const node of SelectBox.cache[id]){if(node.displayed){const new_option=new Option(node.text,node.value,false,false);new_option.title=node.text;box.appendChild(new_option)}}box.scrollTop=scroll_value_from_top},filter:function(id,text){const tokens=text.toLowerCase().split(/\s+/);for(const node of SelectBox.cache[id]){node.displayed=1;const node_text=node.text.toLowerCase();for(const token of tokens){if(!node_text.includes(token)){node.displayed=0;break}}}SelectBox.redisplay(id)},get_hidden_node_count(id){const cache=SelectBox.cache[id]||[];return cache.filter(node=>node.displayed===0).length},delete_from_cache:function(id,value){let delete_index=null;const cache=SelectBox.cache[id];for(const[i,node]of cache.entries()){if(node.value===value){delete_index=i;break}}cache.splice(delete_index,1)},add_to_cache:function(id,option){SelectBox.cache[id].push({value:option.value,text:option.text,displayed:1})},cache_contains:function(id,value){for(const node of SelectBox.cache[id]){if(node.value===value){return true}}return false},move:function(from,to){const from_box=document.getElementById(from);for(const option of from_box.options){const option_value=option.value;if(option.selected&&SelectBox.cache_contains(from,option_value)){SelectBox.add_to_cache(to,{value:option_value,text:option.text,displayed:1});SelectBox.delete_from_cache(from,option_value)}}SelectBox.redisplay(from);SelectBox.redisplay(to)},move_all:function(from,to){const from_box=document.getElementById(from);for(const option of from_box.options){const option_value=option.value;if(SelectBox.cache_contains(from,option_value)){SelectBox.add_to_cache(to,{value:option_value,text:option.text,displayed:1});SelectBox.delete_from_cache(from,option_value)}}SelectBox.redisplay(from);SelectBox.redisplay(to)},sort:function(id){SelectBox.cache[id].sort(function(a,b){a=a.text.toLowerCase();b=b.text.toLowerCase();if(a>b){return 1}if(anode.displayed===0).length},delete_from_cache:function(id,value){let delete_index=null;const cache=SelectBox.cache[id];for(const[i,node]of cache.entries()){if(node.value===value){delete_index=i;break}}cache.splice(delete_index,1)},add_to_cache:function(id,option){SelectBox.cache[id].push({value:option.value,text:option.text,displayed:1})},cache_contains:function(id,value){for(const node of SelectBox.cache[id]){if(node.value===value){return true}}return false},move:function(from,to){const from_box=document.getElementById(from);for(const option of from_box.options){const option_value=option.value;if(option.selected&&SelectBox.cache_contains(from,option_value)){SelectBox.add_to_cache(to,{value:option_value,text:option.text,displayed:1});SelectBox.delete_from_cache(from,option_value)}}SelectBox.redisplay(from);SelectBox.redisplay(to)},move_all:function(from,to){const from_box=document.getElementById(from);for(const option of from_box.options){const option_value=option.value;if(SelectBox.cache_contains(from,option_value)){SelectBox.add_to_cache(to,{value:option_value,text:option.text,displayed:1});SelectBox.delete_from_cache(from,option_value)}}SelectBox.redisplay(from);SelectBox.redisplay(to)},sort:function(id){SelectBox.cache[id].sort(function(a,b){a=a.text.toLowerCase();b=b.text.toLowerCase();if(a>b){return 1}if(anode.displayed===0).length},delete_from_cache:function(id,value){let delete_index=null;const cache=SelectBox.cache[id];for(const[i,node]of cache.entries()){if(node.value===value){delete_index=i;break}}cache.splice(delete_index,1)},add_to_cache:function(id,option){SelectBox.cache[id].push({value:option.value,text:option.text,displayed:1})},cache_contains:function(id,value){for(const node of SelectBox.cache[id]){if(node.value===value){return true}}return false},move:function(from,to){const from_box=document.getElementById(from);for(const option of from_box.options){const option_value=option.value;if(option.selected&&SelectBox.cache_contains(from,option_value)){SelectBox.add_to_cache(to,{value:option_value,text:option.text,displayed:1});SelectBox.delete_from_cache(from,option_value)}}SelectBox.redisplay(from);SelectBox.redisplay(to)},move_all:function(from,to){const from_box=document.getElementById(from);for(const option of from_box.options){const option_value=option.value;if(SelectBox.cache_contains(from,option_value)){SelectBox.add_to_cache(to,{value:option_value,text:option.text,displayed:1});SelectBox.delete_from_cache(from,option_value)}}SelectBox.redisplay(from);SelectBox.redisplay(to)},sort:function(id){SelectBox.cache[id].sort(function(a,b){a=a.text.toLowerCase();b=b.text.toLowerCase();if(a>b){return 1}if(a{shiftPressed=event.shiftKey});document.addEventListener("keyup",event=>{shiftPressed=event.shiftKey});document.getElementById(options.allToggleId).addEventListener("click",function(event){checker(actionCheckboxes,options,this.checked);updateCounter(actionCheckboxes,options)});document.querySelectorAll(options.acrossQuestions+" a").forEach(function(el){el.addEventListener("click",function(event){event.preventDefault();const acrossInputs=document.querySelectorAll(options.acrossInput);acrossInputs.forEach(function(acrossInput){acrossInput.value=1});showClear(options)})});document.querySelectorAll(options.acrossClears+" a").forEach(function(el){el.addEventListener("click",function(event){event.preventDefault();document.getElementById(options.allToggleId).checked=false;clearAcross(options);checker(actionCheckboxes,options,false);updateCounter(actionCheckboxes,options)})});function affectedCheckboxes(target,withModifier){const multiSelect=lastChecked&&withModifier&&lastChecked!==target;if(!multiSelect){return[target]}const checkboxes=Array.from(actionCheckboxes);const targetIndex=checkboxes.findIndex(el=>el===target);const lastCheckedIndex=checkboxes.findIndex(el=>el===lastChecked);const startIndex=Math.min(targetIndex,lastCheckedIndex);const endIndex=Math.max(targetIndex,lastCheckedIndex);const filtered=checkboxes.filter((el,index)=>startIndex<=index&&index<=endIndex);return filtered}Array.from(document.getElementById("result_list").tBodies).forEach(function(el){el.addEventListener("change",function(event){const target=event.target;if(target.classList.contains("action-select")){const checkboxes=affectedCheckboxes(target,shiftPressed);checker(checkboxes,options,target.checked);updateCounter(actionCheckboxes,options);lastChecked=target}else{list_editable_changed=true}})});document.querySelector("#changelist-form button[name=index]").addEventListener("click",function(event){if(list_editable_changed){const confirmed=confirm(gettext("You have unsaved changes on individual editable fields. If you run an action, your unsaved changes will be lost."));if(!confirmed){event.preventDefault()}}});const el=document.querySelector("#changelist-form input[name=_save]");if(el){el.addEventListener("click",function(event){if(document.querySelector("[name=action]").value){const text=list_editable_changed?gettext("You have selected an action, but you haven’t saved your changes to individual fields yet. Please click OK to save. You’ll need to re-run the action."):gettext("You have selected an action, and you haven’t made any changes on individual fields. You’re probably looking for the Go button rather than the Save button.");if(!confirm(text)){event.preventDefault()}}})}window.addEventListener("pageshow",event=>updateCounter(actionCheckboxes,options))};function ready(fn){if(document.readyState!=="loading"){fn()}else{document.addEventListener("DOMContentLoaded",fn)}}ready(function(){const actionsEls=document.querySelectorAll("tr input.action-select");if(actionsEls.length>0){Actions(actionsEls)}})} \ No newline at end of file +"use strict";{function show(selector){document.querySelectorAll(selector).forEach(function(el){el.classList.remove("hidden")})}function hide(selector){document.querySelectorAll(selector).forEach(function(el){el.classList.add("hidden")})}function showQuestion(options){hide(options.acrossClears);show(options.acrossQuestions);hide(options.allContainer)}function showClear(options){show(options.acrossClears);hide(options.acrossQuestions);document.querySelector(options.actionContainer).classList.remove(options.selectedClass);show(options.allContainer);hide(options.counterContainer)}function reset(options){hide(options.acrossClears);hide(options.acrossQuestions);hide(options.allContainer);show(options.counterContainer)}function clearAcross(options){reset(options);const acrossInputs=document.querySelectorAll(options.acrossInput);acrossInputs.forEach(function(acrossInput){acrossInput.value=0});document.querySelector(options.actionContainer).classList.remove(options.selectedClass)}function checker(actionCheckboxes,options,checked){if(checked){showQuestion(options)}else{reset(options)}actionCheckboxes.forEach(function(el){el.checked=checked;el.closest("tr").classList.toggle(options.selectedClass,checked)})}function updateCounter(actionCheckboxes,options){const sel=Array.from(actionCheckboxes).filter(function(el){return el.checked}).length;const counter=document.querySelector(options.counterContainer);const actions_icnt=Number(counter.dataset.actionsIcnt);counter.textContent=interpolate(ngettext("%(sel)s of %(cnt)s selected","%(sel)s of %(cnt)s selected",sel),{sel:sel,cnt:actions_icnt},true);const allToggle=document.getElementById(options.allToggleId);allToggle.checked=sel===actionCheckboxes.length;if(allToggle.checked){showQuestion(options)}else{clearAcross(options)}}const defaults={actionContainer:"div.actions",counterContainer:"span.action-counter",allContainer:"div.actions span.all",acrossInput:"div.actions input.select-across",acrossQuestions:"div.actions span.question",acrossClears:"div.actions span.clear",allToggleId:"action-toggle",selectedClass:"selected"};window.Actions=function(actionCheckboxes,options){options=Object.assign({},defaults,options);let list_editable_changed=false;let lastChecked=null;let shiftPressed=false;document.addEventListener("keydown",event=>{shiftPressed=event.shiftKey});document.addEventListener("keyup",event=>{shiftPressed=event.shiftKey});document.getElementById(options.allToggleId).addEventListener("click",function(event){checker(actionCheckboxes,options,this.checked);updateCounter(actionCheckboxes,options)});document.querySelectorAll(options.acrossQuestions+" a").forEach(function(el){el.addEventListener("click",function(event){event.preventDefault();const acrossInputs=document.querySelectorAll(options.acrossInput);acrossInputs.forEach(function(acrossInput){acrossInput.value=1});showClear(options)})});document.querySelectorAll(options.acrossClears+" a").forEach(function(el){el.addEventListener("click",function(event){event.preventDefault();document.getElementById(options.allToggleId).checked=false;clearAcross(options);checker(actionCheckboxes,options,false);updateCounter(actionCheckboxes,options)})});function affectedCheckboxes(target,withModifier){const multiSelect=lastChecked&&withModifier&&lastChecked!==target;if(!multiSelect){return[target]}const checkboxes=Array.from(actionCheckboxes);const targetIndex=checkboxes.findIndex(el=>el===target);const lastCheckedIndex=checkboxes.findIndex(el=>el===lastChecked);const startIndex=Math.min(targetIndex,lastCheckedIndex);const endIndex=Math.max(targetIndex,lastCheckedIndex);const filtered=checkboxes.filter((el,index)=>startIndex<=index&&index<=endIndex);return filtered}Array.from(document.getElementById("result_list").tBodies).forEach(function(el){el.addEventListener("change",function(event){const target=event.target;if(target.classList.contains("action-select")){const checkboxes=affectedCheckboxes(target,shiftPressed);checker(checkboxes,options,target.checked);updateCounter(actionCheckboxes,options);lastChecked=target}else{list_editable_changed=true}})});document.querySelector("#changelist-form button[name=index]").addEventListener("click",function(event){if(list_editable_changed){const confirmed=confirm(gettext("You have unsaved changes on individual editable fields. If you run an action, your unsaved changes will be lost."));if(!confirmed){event.preventDefault()}}});const el=document.querySelector("#changelist-form input[name=_save]");if(el){el.addEventListener("click",function(event){if(document.querySelector("[name=action]").value){const text=list_editable_changed?gettext("You have selected an action, but you haven’t saved your changes to individual fields yet. Please click OK to save. You’ll need to re-run the action."):gettext("You have selected an action, and you haven’t made any changes on individual fields. You’re probably looking for the Go button rather than the Save button.");if(!confirm(text)){event.preventDefault()}}})}window.addEventListener("pageshow",event=>updateCounter(actionCheckboxes,options))};function ready(fn){if(document.readyState!=="loading"){fn()}else{document.addEventListener("DOMContentLoaded",fn)}}ready(function(){const actionsEls=document.querySelectorAll("tr input.action-select");if(actionsEls.length>0){Actions(actionsEls)}})} diff --git a/src/country_workspace/web/static/workspace/js/actions.min.min.js b/src/country_workspace/web/static/workspace/js/actions.min.min.js new file mode 100644 index 0000000..01083b9 --- /dev/null +++ b/src/country_workspace/web/static/workspace/js/actions.min.min.js @@ -0,0 +1 @@ +"use strict";{function show(selector){document.querySelectorAll(selector).forEach(function(el){el.classList.remove("hidden")})}function hide(selector){document.querySelectorAll(selector).forEach(function(el){el.classList.add("hidden")})}function showQuestion(options){hide(options.acrossClears);show(options.acrossQuestions);hide(options.allContainer)}function showClear(options){show(options.acrossClears);hide(options.acrossQuestions);document.querySelector(options.actionContainer).classList.remove(options.selectedClass);show(options.allContainer);hide(options.counterContainer)}function reset(options){hide(options.acrossClears);hide(options.acrossQuestions);hide(options.allContainer);show(options.counterContainer)}function clearAcross(options){reset(options);const acrossInputs=document.querySelectorAll(options.acrossInput);acrossInputs.forEach(function(acrossInput){acrossInput.value=0});document.querySelector(options.actionContainer).classList.remove(options.selectedClass)}function checker(actionCheckboxes,options,checked){if(checked){showQuestion(options)}else{reset(options)}actionCheckboxes.forEach(function(el){el.checked=checked;el.closest("tr").classList.toggle(options.selectedClass,checked)})}function updateCounter(actionCheckboxes,options){const sel=Array.from(actionCheckboxes).filter(function(el){return el.checked}).length;const counter=document.querySelector(options.counterContainer);const actions_icnt=Number(counter.dataset.actionsIcnt);counter.textContent=interpolate(ngettext("%(sel)s of %(cnt)s selected","%(sel)s of %(cnt)s selected",sel),{sel:sel,cnt:actions_icnt},true);const allToggle=document.getElementById(options.allToggleId);allToggle.checked=sel===actionCheckboxes.length;if(allToggle.checked){showQuestion(options)}else{clearAcross(options)}}const defaults={actionContainer:"div.actions",counterContainer:"span.action-counter",allContainer:"div.actions span.all",acrossInput:"div.actions input.select-across",acrossQuestions:"div.actions span.question",acrossClears:"div.actions span.clear",allToggleId:"action-toggle",selectedClass:"selected"};window.Actions=function(actionCheckboxes,options){options=Object.assign({},defaults,options);let list_editable_changed=false;let lastChecked=null;let shiftPressed=false;document.addEventListener("keydown",event=>{shiftPressed=event.shiftKey});document.addEventListener("keyup",event=>{shiftPressed=event.shiftKey});document.getElementById(options.allToggleId).addEventListener("click",function(event){checker(actionCheckboxes,options,this.checked);updateCounter(actionCheckboxes,options)});document.querySelectorAll(options.acrossQuestions+" a").forEach(function(el){el.addEventListener("click",function(event){event.preventDefault();const acrossInputs=document.querySelectorAll(options.acrossInput);acrossInputs.forEach(function(acrossInput){acrossInput.value=1});showClear(options)})});document.querySelectorAll(options.acrossClears+" a").forEach(function(el){el.addEventListener("click",function(event){event.preventDefault();document.getElementById(options.allToggleId).checked=false;clearAcross(options);checker(actionCheckboxes,options,false);updateCounter(actionCheckboxes,options)})});function affectedCheckboxes(target,withModifier){const multiSelect=lastChecked&&withModifier&&lastChecked!==target;if(!multiSelect){return[target]}const checkboxes=Array.from(actionCheckboxes);const targetIndex=checkboxes.findIndex(el=>el===target);const lastCheckedIndex=checkboxes.findIndex(el=>el===lastChecked);const startIndex=Math.min(targetIndex,lastCheckedIndex);const endIndex=Math.max(targetIndex,lastCheckedIndex);const filtered=checkboxes.filter((el,index)=>startIndex<=index&&index<=endIndex);return filtered}Array.from(document.getElementById("result_list").tBodies).forEach(function(el){el.addEventListener("change",function(event){const target=event.target;if(target.classList.contains("action-select")){const checkboxes=affectedCheckboxes(target,shiftPressed);checker(checkboxes,options,target.checked);updateCounter(actionCheckboxes,options);lastChecked=target}else{list_editable_changed=true}})});document.querySelector("#changelist-form button[name=index]").addEventListener("click",function(event){if(list_editable_changed){const confirmed=confirm(gettext("You have unsaved changes on individual editable fields. If you run an action, your unsaved changes will be lost."));if(!confirmed){event.preventDefault()}}});const el=document.querySelector("#changelist-form input[name=_save]");if(el){el.addEventListener("click",function(event){if(document.querySelector("[name=action]").value){const text=list_editable_changed?gettext("You have selected an action, but you haven’t saved your changes to individual fields yet. Please click OK to save. You’ll need to re-run the action."):gettext("You have selected an action, and you haven’t made any changes on individual fields. You’re probably looking for the Go button rather than the Save button.");if(!confirm(text)){event.preventDefault()}}})}window.addEventListener("pageshow",event=>updateCounter(actionCheckboxes,options))};function ready(fn){if(document.readyState!=="loading"){fn()}else{document.addEventListener("DOMContentLoaded",fn)}}ready(function(){const actionsEls=document.querySelectorAll("tr input.action-select");if(actionsEls.length>0){Actions(actionsEls)}})} diff --git a/src/country_workspace/web/static/workspace/js/admin/DateTimeShortcuts.min.js b/src/country_workspace/web/static/workspace/js/admin/DateTimeShortcuts.min.js index 3dd2664..cecbb21 100644 --- a/src/country_workspace/web/static/workspace/js/admin/DateTimeShortcuts.min.js +++ b/src/country_workspace/web/static/workspace/js/admin/DateTimeShortcuts.min.js @@ -1 +1 @@ -"use strict";{const DateTimeShortcuts={calendars:[],calendarInputs:[],clockInputs:[],clockHours:{default_:[[gettext_noop("Now"),-1],[gettext_noop("Midnight"),0],[gettext_noop("6 a.m."),6],[gettext_noop("Noon"),12],[gettext_noop("6 p.m."),18]]},dismissClockFunc:[],dismissCalendarFunc:[],calendarDivName1:"calendarbox",calendarDivName2:"calendarin",calendarLinkName:"calendarlink",clockDivName:"clockbox",clockLinkName:"clocklink",shortCutsClass:"datetimeshortcuts",timezoneWarningClass:"timezonewarning",timezoneOffset:0,init:function(){const serverOffset=document.body.dataset.adminUtcOffset;if(serverOffset){const localOffset=(new Date).getTimezoneOffset()*-60;DateTimeShortcuts.timezoneOffset=localOffset-serverOffset}for(const inp of document.getElementsByTagName("input")){if(inp.type==="text"&&inp.classList.contains("vTimeField")){DateTimeShortcuts.addClock(inp);DateTimeShortcuts.addTimezoneWarning(inp)}else if(inp.type==="text"&&inp.classList.contains("vDateField")){DateTimeShortcuts.addCalendar(inp);DateTimeShortcuts.addTimezoneWarning(inp)}}},now:function(){const serverOffset=document.body.dataset.adminUtcOffset;if(serverOffset){const localNow=new Date;const localOffset=localNow.getTimezoneOffset()*-60;localNow.setTime(localNow.getTime()+1e3*(serverOffset-localOffset));return localNow}else{return new Date}},addTimezoneWarning:function(inp){const warningClass=DateTimeShortcuts.timezoneWarningClass;let timezoneOffset=DateTimeShortcuts.timezoneOffset/3600;if(!timezoneOffset){return}if(inp.parentNode.querySelectorAll("."+warningClass).length){return}let message;if(timezoneOffset>0){message=ngettext("Note: You are %s hour ahead of server time.","Note: You are %s hours ahead of server time.",timezoneOffset)}else{timezoneOffset*=-1;message=ngettext("Note: You are %s hour behind server time.","Note: You are %s hours behind server time.",timezoneOffset)}message=interpolate(message,[timezoneOffset]);const warning=document.createElement("div");warning.classList.add("help",warningClass);warning.textContent=message;inp.parentNode.appendChild(warning)},addClock:function(inp){const num=DateTimeShortcuts.clockInputs.length;DateTimeShortcuts.clockInputs[num]=inp;DateTimeShortcuts.dismissClockFunc[num]=function(){DateTimeShortcuts.dismissClock(num);return true};const shortcuts_span=document.createElement("span");shortcuts_span.className=DateTimeShortcuts.shortCutsClass;inp.parentNode.insertBefore(shortcuts_span,inp.nextSibling);const now_link=document.createElement("a");now_link.href="#";now_link.textContent=gettext("Now");now_link.addEventListener("click",function(e){e.preventDefault();DateTimeShortcuts.handleClockQuicklink(num,-1)});const clock_link=document.createElement("a");clock_link.href="#";clock_link.id=DateTimeShortcuts.clockLinkName+num;clock_link.addEventListener("click",function(e){e.preventDefault();e.stopPropagation();DateTimeShortcuts.openClock(num)});quickElement("span",clock_link,"","class","clock-icon","title",gettext("Choose a Time"));shortcuts_span.appendChild(document.createTextNode(" "));shortcuts_span.appendChild(now_link);shortcuts_span.appendChild(document.createTextNode(" | "));shortcuts_span.appendChild(clock_link);const clock_box=document.createElement("div");clock_box.style.display="none";clock_box.style.position="absolute";clock_box.className="clockbox module";clock_box.id=DateTimeShortcuts.clockDivName+num;document.body.appendChild(clock_box);clock_box.addEventListener("click",function(e){e.stopPropagation()});quickElement("h2",clock_box,gettext("Choose a time"));const time_list=quickElement("ul",clock_box);time_list.className="timelist";const name=typeof DateTimeShortcuts.clockHours[inp.name]==="undefined"?"default_":inp.name;DateTimeShortcuts.clockHours[name].forEach(function(element){const time_link=quickElement("a",quickElement("li",time_list),gettext(element[0]),"href","#");time_link.addEventListener("click",function(e){e.preventDefault();DateTimeShortcuts.handleClockQuicklink(num,element[1])})});const cancel_p=quickElement("p",clock_box);cancel_p.className="calendar-cancel";const cancel_link=quickElement("a",cancel_p,gettext("Cancel"),"href","#");cancel_link.addEventListener("click",function(e){e.preventDefault();DateTimeShortcuts.dismissClock(num)});document.addEventListener("keyup",function(event){if(event.which===27){DateTimeShortcuts.dismissClock(num);event.preventDefault()}})},openClock:function(num){const clock_box=document.getElementById(DateTimeShortcuts.clockDivName+num);const clock_link=document.getElementById(DateTimeShortcuts.clockLinkName+num);if(window.getComputedStyle(document.body).direction!=="rtl"){clock_box.style.left=findPosX(clock_link)+17+"px"}else{clock_box.style.left=findPosX(clock_link)-110+"px"}clock_box.style.top=Math.max(0,findPosY(clock_link)-30)+"px";clock_box.style.display="block";document.addEventListener("click",DateTimeShortcuts.dismissClockFunc[num])},dismissClock:function(num){document.getElementById(DateTimeShortcuts.clockDivName+num).style.display="none";document.removeEventListener("click",DateTimeShortcuts.dismissClockFunc[num])},handleClockQuicklink:function(num,val){let d;if(val===-1){d=DateTimeShortcuts.now()}else{d=new Date(1970,1,1,val,0,0,0)}DateTimeShortcuts.clockInputs[num].value=d.strftime(get_format("TIME_INPUT_FORMATS")[0]);DateTimeShortcuts.clockInputs[num].focus();DateTimeShortcuts.dismissClock(num)},addCalendar:function(inp){const num=DateTimeShortcuts.calendars.length;DateTimeShortcuts.calendarInputs[num]=inp;DateTimeShortcuts.dismissCalendarFunc[num]=function(){DateTimeShortcuts.dismissCalendar(num);return true};const shortcuts_span=document.createElement("span");shortcuts_span.className=DateTimeShortcuts.shortCutsClass;inp.parentNode.insertBefore(shortcuts_span,inp.nextSibling);const today_link=document.createElement("a");today_link.href="#";today_link.appendChild(document.createTextNode(gettext("Today")));today_link.addEventListener("click",function(e){e.preventDefault();DateTimeShortcuts.handleCalendarQuickLink(num,0)});const cal_link=document.createElement("a");cal_link.href="#";cal_link.id=DateTimeShortcuts.calendarLinkName+num;cal_link.addEventListener("click",function(e){e.preventDefault();e.stopPropagation();DateTimeShortcuts.openCalendar(num)});quickElement("span",cal_link,"","class","date-icon","title",gettext("Choose a Date"));shortcuts_span.appendChild(document.createTextNode(" "));shortcuts_span.appendChild(today_link);shortcuts_span.appendChild(document.createTextNode(" | "));shortcuts_span.appendChild(cal_link);const cal_box=document.createElement("div");cal_box.style.display="none";cal_box.style.position="absolute";cal_box.className="calendarbox module";cal_box.id=DateTimeShortcuts.calendarDivName1+num;document.body.appendChild(cal_box);cal_box.addEventListener("click",function(e){e.stopPropagation()});const cal_nav=quickElement("div",cal_box);const cal_nav_prev=quickElement("a",cal_nav,"<","href","#");cal_nav_prev.className="calendarnav-previous";cal_nav_prev.addEventListener("click",function(e){e.preventDefault();DateTimeShortcuts.drawPrev(num)});const cal_nav_next=quickElement("a",cal_nav,">","href","#");cal_nav_next.className="calendarnav-next";cal_nav_next.addEventListener("click",function(e){e.preventDefault();DateTimeShortcuts.drawNext(num)});const cal_main=quickElement("div",cal_box,"","id",DateTimeShortcuts.calendarDivName2+num);cal_main.className="calendar";DateTimeShortcuts.calendars[num]=new Calendar(DateTimeShortcuts.calendarDivName2+num,DateTimeShortcuts.handleCalendarCallback(num));DateTimeShortcuts.calendars[num].drawCurrent();const shortcuts=quickElement("div",cal_box);shortcuts.className="calendar-shortcuts";let day_link=quickElement("a",shortcuts,gettext("Yesterday"),"href","#");day_link.addEventListener("click",function(e){e.preventDefault();DateTimeShortcuts.handleCalendarQuickLink(num,-1)});shortcuts.appendChild(document.createTextNode(" | "));day_link=quickElement("a",shortcuts,gettext("Today"),"href","#");day_link.addEventListener("click",function(e){e.preventDefault();DateTimeShortcuts.handleCalendarQuickLink(num,0)});shortcuts.appendChild(document.createTextNode(" | "));day_link=quickElement("a",shortcuts,gettext("Tomorrow"),"href","#");day_link.addEventListener("click",function(e){e.preventDefault();DateTimeShortcuts.handleCalendarQuickLink(num,+1)});const cancel_p=quickElement("p",cal_box);cancel_p.className="calendar-cancel";const cancel_link=quickElement("a",cancel_p,gettext("Cancel"),"href","#");cancel_link.addEventListener("click",function(e){e.preventDefault();DateTimeShortcuts.dismissCalendar(num)});document.addEventListener("keyup",function(event){if(event.which===27){DateTimeShortcuts.dismissCalendar(num);event.preventDefault()}})},openCalendar:function(num){const cal_box=document.getElementById(DateTimeShortcuts.calendarDivName1+num);const cal_link=document.getElementById(DateTimeShortcuts.calendarLinkName+num);const inp=DateTimeShortcuts.calendarInputs[num];if(inp.value){const format=get_format("DATE_INPUT_FORMATS")[0];const selected=inp.value.strptime(format);const year=selected.getUTCFullYear();const month=selected.getUTCMonth()+1;const re=/\d{4}/;if(re.test(year.toString())&&month>=1&&month<=12){DateTimeShortcuts.calendars[num].drawDate(month,year,selected)}}if(window.getComputedStyle(document.body).direction!=="rtl"){cal_box.style.left=findPosX(cal_link)+17+"px"}else{cal_box.style.left=findPosX(cal_link)-180+"px"}cal_box.style.top=Math.max(0,findPosY(cal_link)-75)+"px";cal_box.style.display="block";document.addEventListener("click",DateTimeShortcuts.dismissCalendarFunc[num])},dismissCalendar:function(num){document.getElementById(DateTimeShortcuts.calendarDivName1+num).style.display="none";document.removeEventListener("click",DateTimeShortcuts.dismissCalendarFunc[num])},drawPrev:function(num){DateTimeShortcuts.calendars[num].drawPreviousMonth()},drawNext:function(num){DateTimeShortcuts.calendars[num].drawNextMonth()},handleCalendarCallback:function(num){const format=get_format("DATE_INPUT_FORMATS")[0];return function(y,m,d){DateTimeShortcuts.calendarInputs[num].value=new Date(y,m-1,d).strftime(format);DateTimeShortcuts.calendarInputs[num].focus();document.getElementById(DateTimeShortcuts.calendarDivName1+num).style.display="none"}},handleCalendarQuickLink:function(num,offset){const d=DateTimeShortcuts.now();d.setDate(d.getDate()+offset);DateTimeShortcuts.calendarInputs[num].value=d.strftime(get_format("DATE_INPUT_FORMATS")[0]);DateTimeShortcuts.calendarInputs[num].focus();DateTimeShortcuts.dismissCalendar(num)}};window.addEventListener("load",DateTimeShortcuts.init);window.DateTimeShortcuts=DateTimeShortcuts} \ No newline at end of file +"use strict";{const DateTimeShortcuts={calendars:[],calendarInputs:[],clockInputs:[],clockHours:{default_:[[gettext_noop("Now"),-1],[gettext_noop("Midnight"),0],[gettext_noop("6 a.m."),6],[gettext_noop("Noon"),12],[gettext_noop("6 p.m."),18]]},dismissClockFunc:[],dismissCalendarFunc:[],calendarDivName1:"calendarbox",calendarDivName2:"calendarin",calendarLinkName:"calendarlink",clockDivName:"clockbox",clockLinkName:"clocklink",shortCutsClass:"datetimeshortcuts",timezoneWarningClass:"timezonewarning",timezoneOffset:0,init:function(){const serverOffset=document.body.dataset.adminUtcOffset;if(serverOffset){const localOffset=(new Date).getTimezoneOffset()*-60;DateTimeShortcuts.timezoneOffset=localOffset-serverOffset}for(const inp of document.getElementsByTagName("input")){if(inp.type==="text"&&inp.classList.contains("vTimeField")){DateTimeShortcuts.addClock(inp);DateTimeShortcuts.addTimezoneWarning(inp)}else if(inp.type==="text"&&inp.classList.contains("vDateField")){DateTimeShortcuts.addCalendar(inp);DateTimeShortcuts.addTimezoneWarning(inp)}}},now:function(){const serverOffset=document.body.dataset.adminUtcOffset;if(serverOffset){const localNow=new Date;const localOffset=localNow.getTimezoneOffset()*-60;localNow.setTime(localNow.getTime()+1e3*(serverOffset-localOffset));return localNow}else{return new Date}},addTimezoneWarning:function(inp){const warningClass=DateTimeShortcuts.timezoneWarningClass;let timezoneOffset=DateTimeShortcuts.timezoneOffset/3600;if(!timezoneOffset){return}if(inp.parentNode.querySelectorAll("."+warningClass).length){return}let message;if(timezoneOffset>0){message=ngettext("Note: You are %s hour ahead of server time.","Note: You are %s hours ahead of server time.",timezoneOffset)}else{timezoneOffset*=-1;message=ngettext("Note: You are %s hour behind server time.","Note: You are %s hours behind server time.",timezoneOffset)}message=interpolate(message,[timezoneOffset]);const warning=document.createElement("div");warning.classList.add("help",warningClass);warning.textContent=message;inp.parentNode.appendChild(warning)},addClock:function(inp){const num=DateTimeShortcuts.clockInputs.length;DateTimeShortcuts.clockInputs[num]=inp;DateTimeShortcuts.dismissClockFunc[num]=function(){DateTimeShortcuts.dismissClock(num);return true};const shortcuts_span=document.createElement("span");shortcuts_span.className=DateTimeShortcuts.shortCutsClass;inp.parentNode.insertBefore(shortcuts_span,inp.nextSibling);const now_link=document.createElement("a");now_link.href="#";now_link.textContent=gettext("Now");now_link.addEventListener("click",function(e){e.preventDefault();DateTimeShortcuts.handleClockQuicklink(num,-1)});const clock_link=document.createElement("a");clock_link.href="#";clock_link.id=DateTimeShortcuts.clockLinkName+num;clock_link.addEventListener("click",function(e){e.preventDefault();e.stopPropagation();DateTimeShortcuts.openClock(num)});quickElement("span",clock_link,"","class","clock-icon","title",gettext("Choose a Time"));shortcuts_span.appendChild(document.createTextNode(" "));shortcuts_span.appendChild(now_link);shortcuts_span.appendChild(document.createTextNode(" | "));shortcuts_span.appendChild(clock_link);const clock_box=document.createElement("div");clock_box.style.display="none";clock_box.style.position="absolute";clock_box.className="clockbox module";clock_box.id=DateTimeShortcuts.clockDivName+num;document.body.appendChild(clock_box);clock_box.addEventListener("click",function(e){e.stopPropagation()});quickElement("h2",clock_box,gettext("Choose a time"));const time_list=quickElement("ul",clock_box);time_list.className="timelist";const name=typeof DateTimeShortcuts.clockHours[inp.name]==="undefined"?"default_":inp.name;DateTimeShortcuts.clockHours[name].forEach(function(element){const time_link=quickElement("a",quickElement("li",time_list),gettext(element[0]),"href","#");time_link.addEventListener("click",function(e){e.preventDefault();DateTimeShortcuts.handleClockQuicklink(num,element[1])})});const cancel_p=quickElement("p",clock_box);cancel_p.className="calendar-cancel";const cancel_link=quickElement("a",cancel_p,gettext("Cancel"),"href","#");cancel_link.addEventListener("click",function(e){e.preventDefault();DateTimeShortcuts.dismissClock(num)});document.addEventListener("keyup",function(event){if(event.which===27){DateTimeShortcuts.dismissClock(num);event.preventDefault()}})},openClock:function(num){const clock_box=document.getElementById(DateTimeShortcuts.clockDivName+num);const clock_link=document.getElementById(DateTimeShortcuts.clockLinkName+num);if(window.getComputedStyle(document.body).direction!=="rtl"){clock_box.style.left=findPosX(clock_link)+17+"px"}else{clock_box.style.left=findPosX(clock_link)-110+"px"}clock_box.style.top=Math.max(0,findPosY(clock_link)-30)+"px";clock_box.style.display="block";document.addEventListener("click",DateTimeShortcuts.dismissClockFunc[num])},dismissClock:function(num){document.getElementById(DateTimeShortcuts.clockDivName+num).style.display="none";document.removeEventListener("click",DateTimeShortcuts.dismissClockFunc[num])},handleClockQuicklink:function(num,val){let d;if(val===-1){d=DateTimeShortcuts.now()}else{d=new Date(1970,1,1,val,0,0,0)}DateTimeShortcuts.clockInputs[num].value=d.strftime(get_format("TIME_INPUT_FORMATS")[0]);DateTimeShortcuts.clockInputs[num].focus();DateTimeShortcuts.dismissClock(num)},addCalendar:function(inp){const num=DateTimeShortcuts.calendars.length;DateTimeShortcuts.calendarInputs[num]=inp;DateTimeShortcuts.dismissCalendarFunc[num]=function(){DateTimeShortcuts.dismissCalendar(num);return true};const shortcuts_span=document.createElement("span");shortcuts_span.className=DateTimeShortcuts.shortCutsClass;inp.parentNode.insertBefore(shortcuts_span,inp.nextSibling);const today_link=document.createElement("a");today_link.href="#";today_link.appendChild(document.createTextNode(gettext("Today")));today_link.addEventListener("click",function(e){e.preventDefault();DateTimeShortcuts.handleCalendarQuickLink(num,0)});const cal_link=document.createElement("a");cal_link.href="#";cal_link.id=DateTimeShortcuts.calendarLinkName+num;cal_link.addEventListener("click",function(e){e.preventDefault();e.stopPropagation();DateTimeShortcuts.openCalendar(num)});quickElement("span",cal_link,"","class","date-icon","title",gettext("Choose a Date"));shortcuts_span.appendChild(document.createTextNode(" "));shortcuts_span.appendChild(today_link);shortcuts_span.appendChild(document.createTextNode(" | "));shortcuts_span.appendChild(cal_link);const cal_box=document.createElement("div");cal_box.style.display="none";cal_box.style.position="absolute";cal_box.className="calendarbox module";cal_box.id=DateTimeShortcuts.calendarDivName1+num;document.body.appendChild(cal_box);cal_box.addEventListener("click",function(e){e.stopPropagation()});const cal_nav=quickElement("div",cal_box);const cal_nav_prev=quickElement("a",cal_nav,"<","href","#");cal_nav_prev.className="calendarnav-previous";cal_nav_prev.addEventListener("click",function(e){e.preventDefault();DateTimeShortcuts.drawPrev(num)});const cal_nav_next=quickElement("a",cal_nav,">","href","#");cal_nav_next.className="calendarnav-next";cal_nav_next.addEventListener("click",function(e){e.preventDefault();DateTimeShortcuts.drawNext(num)});const cal_main=quickElement("div",cal_box,"","id",DateTimeShortcuts.calendarDivName2+num);cal_main.className="calendar";DateTimeShortcuts.calendars[num]=new Calendar(DateTimeShortcuts.calendarDivName2+num,DateTimeShortcuts.handleCalendarCallback(num));DateTimeShortcuts.calendars[num].drawCurrent();const shortcuts=quickElement("div",cal_box);shortcuts.className="calendar-shortcuts";let day_link=quickElement("a",shortcuts,gettext("Yesterday"),"href","#");day_link.addEventListener("click",function(e){e.preventDefault();DateTimeShortcuts.handleCalendarQuickLink(num,-1)});shortcuts.appendChild(document.createTextNode(" | "));day_link=quickElement("a",shortcuts,gettext("Today"),"href","#");day_link.addEventListener("click",function(e){e.preventDefault();DateTimeShortcuts.handleCalendarQuickLink(num,0)});shortcuts.appendChild(document.createTextNode(" | "));day_link=quickElement("a",shortcuts,gettext("Tomorrow"),"href","#");day_link.addEventListener("click",function(e){e.preventDefault();DateTimeShortcuts.handleCalendarQuickLink(num,+1)});const cancel_p=quickElement("p",cal_box);cancel_p.className="calendar-cancel";const cancel_link=quickElement("a",cancel_p,gettext("Cancel"),"href","#");cancel_link.addEventListener("click",function(e){e.preventDefault();DateTimeShortcuts.dismissCalendar(num)});document.addEventListener("keyup",function(event){if(event.which===27){DateTimeShortcuts.dismissCalendar(num);event.preventDefault()}})},openCalendar:function(num){const cal_box=document.getElementById(DateTimeShortcuts.calendarDivName1+num);const cal_link=document.getElementById(DateTimeShortcuts.calendarLinkName+num);const inp=DateTimeShortcuts.calendarInputs[num];if(inp.value){const format=get_format("DATE_INPUT_FORMATS")[0];const selected=inp.value.strptime(format);const year=selected.getUTCFullYear();const month=selected.getUTCMonth()+1;const re=/\d{4}/;if(re.test(year.toString())&&month>=1&&month<=12){DateTimeShortcuts.calendars[num].drawDate(month,year,selected)}}if(window.getComputedStyle(document.body).direction!=="rtl"){cal_box.style.left=findPosX(cal_link)+17+"px"}else{cal_box.style.left=findPosX(cal_link)-180+"px"}cal_box.style.top=Math.max(0,findPosY(cal_link)-75)+"px";cal_box.style.display="block";document.addEventListener("click",DateTimeShortcuts.dismissCalendarFunc[num])},dismissCalendar:function(num){document.getElementById(DateTimeShortcuts.calendarDivName1+num).style.display="none";document.removeEventListener("click",DateTimeShortcuts.dismissCalendarFunc[num])},drawPrev:function(num){DateTimeShortcuts.calendars[num].drawPreviousMonth()},drawNext:function(num){DateTimeShortcuts.calendars[num].drawNextMonth()},handleCalendarCallback:function(num){const format=get_format("DATE_INPUT_FORMATS")[0];return function(y,m,d){DateTimeShortcuts.calendarInputs[num].value=new Date(y,m-1,d).strftime(format);DateTimeShortcuts.calendarInputs[num].focus();document.getElementById(DateTimeShortcuts.calendarDivName1+num).style.display="none"}},handleCalendarQuickLink:function(num,offset){const d=DateTimeShortcuts.now();d.setDate(d.getDate()+offset);DateTimeShortcuts.calendarInputs[num].value=d.strftime(get_format("DATE_INPUT_FORMATS")[0]);DateTimeShortcuts.calendarInputs[num].focus();DateTimeShortcuts.dismissCalendar(num)}};window.addEventListener("load",DateTimeShortcuts.init);window.DateTimeShortcuts=DateTimeShortcuts} diff --git a/src/country_workspace/web/static/workspace/js/admin/DateTimeShortcuts.min.min.js b/src/country_workspace/web/static/workspace/js/admin/DateTimeShortcuts.min.min.js new file mode 100644 index 0000000..cecbb21 --- /dev/null +++ b/src/country_workspace/web/static/workspace/js/admin/DateTimeShortcuts.min.min.js @@ -0,0 +1 @@ +"use strict";{const DateTimeShortcuts={calendars:[],calendarInputs:[],clockInputs:[],clockHours:{default_:[[gettext_noop("Now"),-1],[gettext_noop("Midnight"),0],[gettext_noop("6 a.m."),6],[gettext_noop("Noon"),12],[gettext_noop("6 p.m."),18]]},dismissClockFunc:[],dismissCalendarFunc:[],calendarDivName1:"calendarbox",calendarDivName2:"calendarin",calendarLinkName:"calendarlink",clockDivName:"clockbox",clockLinkName:"clocklink",shortCutsClass:"datetimeshortcuts",timezoneWarningClass:"timezonewarning",timezoneOffset:0,init:function(){const serverOffset=document.body.dataset.adminUtcOffset;if(serverOffset){const localOffset=(new Date).getTimezoneOffset()*-60;DateTimeShortcuts.timezoneOffset=localOffset-serverOffset}for(const inp of document.getElementsByTagName("input")){if(inp.type==="text"&&inp.classList.contains("vTimeField")){DateTimeShortcuts.addClock(inp);DateTimeShortcuts.addTimezoneWarning(inp)}else if(inp.type==="text"&&inp.classList.contains("vDateField")){DateTimeShortcuts.addCalendar(inp);DateTimeShortcuts.addTimezoneWarning(inp)}}},now:function(){const serverOffset=document.body.dataset.adminUtcOffset;if(serverOffset){const localNow=new Date;const localOffset=localNow.getTimezoneOffset()*-60;localNow.setTime(localNow.getTime()+1e3*(serverOffset-localOffset));return localNow}else{return new Date}},addTimezoneWarning:function(inp){const warningClass=DateTimeShortcuts.timezoneWarningClass;let timezoneOffset=DateTimeShortcuts.timezoneOffset/3600;if(!timezoneOffset){return}if(inp.parentNode.querySelectorAll("."+warningClass).length){return}let message;if(timezoneOffset>0){message=ngettext("Note: You are %s hour ahead of server time.","Note: You are %s hours ahead of server time.",timezoneOffset)}else{timezoneOffset*=-1;message=ngettext("Note: You are %s hour behind server time.","Note: You are %s hours behind server time.",timezoneOffset)}message=interpolate(message,[timezoneOffset]);const warning=document.createElement("div");warning.classList.add("help",warningClass);warning.textContent=message;inp.parentNode.appendChild(warning)},addClock:function(inp){const num=DateTimeShortcuts.clockInputs.length;DateTimeShortcuts.clockInputs[num]=inp;DateTimeShortcuts.dismissClockFunc[num]=function(){DateTimeShortcuts.dismissClock(num);return true};const shortcuts_span=document.createElement("span");shortcuts_span.className=DateTimeShortcuts.shortCutsClass;inp.parentNode.insertBefore(shortcuts_span,inp.nextSibling);const now_link=document.createElement("a");now_link.href="#";now_link.textContent=gettext("Now");now_link.addEventListener("click",function(e){e.preventDefault();DateTimeShortcuts.handleClockQuicklink(num,-1)});const clock_link=document.createElement("a");clock_link.href="#";clock_link.id=DateTimeShortcuts.clockLinkName+num;clock_link.addEventListener("click",function(e){e.preventDefault();e.stopPropagation();DateTimeShortcuts.openClock(num)});quickElement("span",clock_link,"","class","clock-icon","title",gettext("Choose a Time"));shortcuts_span.appendChild(document.createTextNode(" "));shortcuts_span.appendChild(now_link);shortcuts_span.appendChild(document.createTextNode(" | "));shortcuts_span.appendChild(clock_link);const clock_box=document.createElement("div");clock_box.style.display="none";clock_box.style.position="absolute";clock_box.className="clockbox module";clock_box.id=DateTimeShortcuts.clockDivName+num;document.body.appendChild(clock_box);clock_box.addEventListener("click",function(e){e.stopPropagation()});quickElement("h2",clock_box,gettext("Choose a time"));const time_list=quickElement("ul",clock_box);time_list.className="timelist";const name=typeof DateTimeShortcuts.clockHours[inp.name]==="undefined"?"default_":inp.name;DateTimeShortcuts.clockHours[name].forEach(function(element){const time_link=quickElement("a",quickElement("li",time_list),gettext(element[0]),"href","#");time_link.addEventListener("click",function(e){e.preventDefault();DateTimeShortcuts.handleClockQuicklink(num,element[1])})});const cancel_p=quickElement("p",clock_box);cancel_p.className="calendar-cancel";const cancel_link=quickElement("a",cancel_p,gettext("Cancel"),"href","#");cancel_link.addEventListener("click",function(e){e.preventDefault();DateTimeShortcuts.dismissClock(num)});document.addEventListener("keyup",function(event){if(event.which===27){DateTimeShortcuts.dismissClock(num);event.preventDefault()}})},openClock:function(num){const clock_box=document.getElementById(DateTimeShortcuts.clockDivName+num);const clock_link=document.getElementById(DateTimeShortcuts.clockLinkName+num);if(window.getComputedStyle(document.body).direction!=="rtl"){clock_box.style.left=findPosX(clock_link)+17+"px"}else{clock_box.style.left=findPosX(clock_link)-110+"px"}clock_box.style.top=Math.max(0,findPosY(clock_link)-30)+"px";clock_box.style.display="block";document.addEventListener("click",DateTimeShortcuts.dismissClockFunc[num])},dismissClock:function(num){document.getElementById(DateTimeShortcuts.clockDivName+num).style.display="none";document.removeEventListener("click",DateTimeShortcuts.dismissClockFunc[num])},handleClockQuicklink:function(num,val){let d;if(val===-1){d=DateTimeShortcuts.now()}else{d=new Date(1970,1,1,val,0,0,0)}DateTimeShortcuts.clockInputs[num].value=d.strftime(get_format("TIME_INPUT_FORMATS")[0]);DateTimeShortcuts.clockInputs[num].focus();DateTimeShortcuts.dismissClock(num)},addCalendar:function(inp){const num=DateTimeShortcuts.calendars.length;DateTimeShortcuts.calendarInputs[num]=inp;DateTimeShortcuts.dismissCalendarFunc[num]=function(){DateTimeShortcuts.dismissCalendar(num);return true};const shortcuts_span=document.createElement("span");shortcuts_span.className=DateTimeShortcuts.shortCutsClass;inp.parentNode.insertBefore(shortcuts_span,inp.nextSibling);const today_link=document.createElement("a");today_link.href="#";today_link.appendChild(document.createTextNode(gettext("Today")));today_link.addEventListener("click",function(e){e.preventDefault();DateTimeShortcuts.handleCalendarQuickLink(num,0)});const cal_link=document.createElement("a");cal_link.href="#";cal_link.id=DateTimeShortcuts.calendarLinkName+num;cal_link.addEventListener("click",function(e){e.preventDefault();e.stopPropagation();DateTimeShortcuts.openCalendar(num)});quickElement("span",cal_link,"","class","date-icon","title",gettext("Choose a Date"));shortcuts_span.appendChild(document.createTextNode(" "));shortcuts_span.appendChild(today_link);shortcuts_span.appendChild(document.createTextNode(" | "));shortcuts_span.appendChild(cal_link);const cal_box=document.createElement("div");cal_box.style.display="none";cal_box.style.position="absolute";cal_box.className="calendarbox module";cal_box.id=DateTimeShortcuts.calendarDivName1+num;document.body.appendChild(cal_box);cal_box.addEventListener("click",function(e){e.stopPropagation()});const cal_nav=quickElement("div",cal_box);const cal_nav_prev=quickElement("a",cal_nav,"<","href","#");cal_nav_prev.className="calendarnav-previous";cal_nav_prev.addEventListener("click",function(e){e.preventDefault();DateTimeShortcuts.drawPrev(num)});const cal_nav_next=quickElement("a",cal_nav,">","href","#");cal_nav_next.className="calendarnav-next";cal_nav_next.addEventListener("click",function(e){e.preventDefault();DateTimeShortcuts.drawNext(num)});const cal_main=quickElement("div",cal_box,"","id",DateTimeShortcuts.calendarDivName2+num);cal_main.className="calendar";DateTimeShortcuts.calendars[num]=new Calendar(DateTimeShortcuts.calendarDivName2+num,DateTimeShortcuts.handleCalendarCallback(num));DateTimeShortcuts.calendars[num].drawCurrent();const shortcuts=quickElement("div",cal_box);shortcuts.className="calendar-shortcuts";let day_link=quickElement("a",shortcuts,gettext("Yesterday"),"href","#");day_link.addEventListener("click",function(e){e.preventDefault();DateTimeShortcuts.handleCalendarQuickLink(num,-1)});shortcuts.appendChild(document.createTextNode(" | "));day_link=quickElement("a",shortcuts,gettext("Today"),"href","#");day_link.addEventListener("click",function(e){e.preventDefault();DateTimeShortcuts.handleCalendarQuickLink(num,0)});shortcuts.appendChild(document.createTextNode(" | "));day_link=quickElement("a",shortcuts,gettext("Tomorrow"),"href","#");day_link.addEventListener("click",function(e){e.preventDefault();DateTimeShortcuts.handleCalendarQuickLink(num,+1)});const cancel_p=quickElement("p",cal_box);cancel_p.className="calendar-cancel";const cancel_link=quickElement("a",cancel_p,gettext("Cancel"),"href","#");cancel_link.addEventListener("click",function(e){e.preventDefault();DateTimeShortcuts.dismissCalendar(num)});document.addEventListener("keyup",function(event){if(event.which===27){DateTimeShortcuts.dismissCalendar(num);event.preventDefault()}})},openCalendar:function(num){const cal_box=document.getElementById(DateTimeShortcuts.calendarDivName1+num);const cal_link=document.getElementById(DateTimeShortcuts.calendarLinkName+num);const inp=DateTimeShortcuts.calendarInputs[num];if(inp.value){const format=get_format("DATE_INPUT_FORMATS")[0];const selected=inp.value.strptime(format);const year=selected.getUTCFullYear();const month=selected.getUTCMonth()+1;const re=/\d{4}/;if(re.test(year.toString())&&month>=1&&month<=12){DateTimeShortcuts.calendars[num].drawDate(month,year,selected)}}if(window.getComputedStyle(document.body).direction!=="rtl"){cal_box.style.left=findPosX(cal_link)+17+"px"}else{cal_box.style.left=findPosX(cal_link)-180+"px"}cal_box.style.top=Math.max(0,findPosY(cal_link)-75)+"px";cal_box.style.display="block";document.addEventListener("click",DateTimeShortcuts.dismissCalendarFunc[num])},dismissCalendar:function(num){document.getElementById(DateTimeShortcuts.calendarDivName1+num).style.display="none";document.removeEventListener("click",DateTimeShortcuts.dismissCalendarFunc[num])},drawPrev:function(num){DateTimeShortcuts.calendars[num].drawPreviousMonth()},drawNext:function(num){DateTimeShortcuts.calendars[num].drawNextMonth()},handleCalendarCallback:function(num){const format=get_format("DATE_INPUT_FORMATS")[0];return function(y,m,d){DateTimeShortcuts.calendarInputs[num].value=new Date(y,m-1,d).strftime(format);DateTimeShortcuts.calendarInputs[num].focus();document.getElementById(DateTimeShortcuts.calendarDivName1+num).style.display="none"}},handleCalendarQuickLink:function(num,offset){const d=DateTimeShortcuts.now();d.setDate(d.getDate()+offset);DateTimeShortcuts.calendarInputs[num].value=d.strftime(get_format("DATE_INPUT_FORMATS")[0]);DateTimeShortcuts.calendarInputs[num].focus();DateTimeShortcuts.dismissCalendar(num)}};window.addEventListener("load",DateTimeShortcuts.init);window.DateTimeShortcuts=DateTimeShortcuts} diff --git a/src/country_workspace/web/static/workspace/js/admin/RelatedObjectLookups.js b/src/country_workspace/web/static/workspace/js/admin/RelatedObjectLookups.js index bc3acce..157e6ba 100644 --- a/src/country_workspace/web/static/workspace/js/admin/RelatedObjectLookups.js +++ b/src/country_workspace/web/static/workspace/js/admin/RelatedObjectLookups.js @@ -11,7 +11,7 @@ relatedWindows.forEach(function(win) { if(!win.closed) { win.dismissChildPopups(); - win.close(); + win.close(); } }); } @@ -19,7 +19,7 @@ function setPopupIndex() { if(document.getElementsByName("_popup").length > 0) { const index = window.name.lastIndexOf("__") + 2; - popupIndex = parseInt(window.name.substring(index)); + popupIndex = parseInt(window.name.substring(index)); } else { popupIndex = 0; } diff --git a/src/country_workspace/web/static/workspace/js/autocomplete.min.js b/src/country_workspace/web/static/workspace/js/autocomplete.min.js index 0176a7c..da42863 100644 --- a/src/country_workspace/web/static/workspace/js/autocomplete.min.js +++ b/src/country_workspace/web/static/workspace/js/autocomplete.min.js @@ -1 +1 @@ -"use strict";{const $=django.jQuery;$.fn.djangoAdminSelect2=function(){$.each(this,function(i,element){$(element).select2({ajax:{data:params=>{return{term:params.term,page:params.page,app_label:element.dataset.appLabel,model_name:element.dataset.modelName,field_name:element.dataset.fieldName}}}})});return this};$(function(){$(".admin-autocomplete").not("[name*=__prefix__]").djangoAdminSelect2()});document.addEventListener("formset:added",event=>{$(event.target).find(".admin-autocomplete").djangoAdminSelect2()})} \ No newline at end of file +"use strict";{const $=django.jQuery;$.fn.djangoAdminSelect2=function(){$.each(this,function(i,element){$(element).select2({ajax:{data:params=>{return{term:params.term,page:params.page,app_label:element.dataset.appLabel,model_name:element.dataset.modelName,field_name:element.dataset.fieldName}}}})});return this};$(function(){$(".admin-autocomplete").not("[name*=__prefix__]").djangoAdminSelect2()});document.addEventListener("formset:added",event=>{$(event.target).find(".admin-autocomplete").djangoAdminSelect2()})} diff --git a/src/country_workspace/web/static/workspace/js/autocomplete.min.min.js b/src/country_workspace/web/static/workspace/js/autocomplete.min.min.js new file mode 100644 index 0000000..da42863 --- /dev/null +++ b/src/country_workspace/web/static/workspace/js/autocomplete.min.min.js @@ -0,0 +1 @@ +"use strict";{const $=django.jQuery;$.fn.djangoAdminSelect2=function(){$.each(this,function(i,element){$(element).select2({ajax:{data:params=>{return{term:params.term,page:params.page,app_label:element.dataset.appLabel,model_name:element.dataset.modelName,field_name:element.dataset.fieldName}}}})});return this};$(function(){$(".admin-autocomplete").not("[name*=__prefix__]").djangoAdminSelect2()});document.addEventListener("formset:added",event=>{$(event.target).find(".admin-autocomplete").djangoAdminSelect2()})} diff --git a/src/country_workspace/web/static/workspace/js/calendar.min.js b/src/country_workspace/web/static/workspace/js/calendar.min.js index 4308e4e..34193a3 100644 --- a/src/country_workspace/web/static/workspace/js/calendar.min.js +++ b/src/country_workspace/web/static/workspace/js/calendar.min.js @@ -1 +1 @@ -"use strict";{const CalendarNamespace={monthsOfYear:[gettext("January"),gettext("February"),gettext("March"),gettext("April"),gettext("May"),gettext("June"),gettext("July"),gettext("August"),gettext("September"),gettext("October"),gettext("November"),gettext("December")],monthsOfYearAbbrev:[pgettext("abbrev. month January","Jan"),pgettext("abbrev. month February","Feb"),pgettext("abbrev. month March","Mar"),pgettext("abbrev. month April","Apr"),pgettext("abbrev. month May","May"),pgettext("abbrev. month June","Jun"),pgettext("abbrev. month July","Jul"),pgettext("abbrev. month August","Aug"),pgettext("abbrev. month September","Sep"),pgettext("abbrev. month October","Oct"),pgettext("abbrev. month November","Nov"),pgettext("abbrev. month December","Dec")],daysOfWeek:[gettext("Sunday"),gettext("Monday"),gettext("Tuesday"),gettext("Wednesday"),gettext("Thursday"),gettext("Friday"),gettext("Saturday")],daysOfWeekAbbrev:[pgettext("abbrev. day Sunday","Sun"),pgettext("abbrev. day Monday","Mon"),pgettext("abbrev. day Tuesday","Tue"),pgettext("abbrev. day Wednesday","Wed"),pgettext("abbrev. day Thursday","Thur"),pgettext("abbrev. day Friday","Fri"),pgettext("abbrev. day Saturday","Sat")],daysOfWeekInitial:[pgettext("one letter Sunday","S"),pgettext("one letter Monday","M"),pgettext("one letter Tuesday","T"),pgettext("one letter Wednesday","W"),pgettext("one letter Thursday","T"),pgettext("one letter Friday","F"),pgettext("one letter Saturday","S")],firstDayOfWeek:parseInt(get_format("FIRST_DAY_OF_WEEK")),isLeapYear:function(year){return year%4===0&&year%100!==0||year%400===0},getDaysInMonth:function(month,year){let days;if(month===1||month===3||month===5||month===7||month===8||month===10||month===12){days=31}else if(month===4||month===6||month===9||month===11){days=30}else if(month===2&&CalendarNamespace.isLeapYear(year)){days=29}else{days=28}return days},draw:function(month,year,div_id,callback,selected){const today=new Date;const todayDay=today.getDate();const todayMonth=today.getMonth()+1;const todayYear=today.getFullYear();let todayClass="";let isSelectedMonth=false;if(typeof selected!=="undefined"){isSelectedMonth=selected.getUTCFullYear()===year&&selected.getUTCMonth()+1===month}month=parseInt(month);year=parseInt(year);const calDiv=document.getElementById(div_id);removeChildren(calDiv);const calTable=document.createElement("table");quickElement("caption",calTable,CalendarNamespace.monthsOfYear[month-1]+" "+year);const tableBody=quickElement("tbody",calTable);let tableRow=quickElement("tr",tableBody);for(let i=0;i<7;i++){quickElement("th",tableRow,CalendarNamespace.daysOfWeekInitial[(i+CalendarNamespace.firstDayOfWeek)%7])}const startingPos=new Date(year,month-1,1-CalendarNamespace.firstDayOfWeek).getDay();const days=CalendarNamespace.getDaysInMonth(month,year);let nonDayCell;tableRow=quickElement("tr",tableBody);for(let i=0;i=12?"PM":"AM",S:this.getTwoDigitSecond(),w:"0"+this.getDay(),x:this.toLocaleDateString(),X:this.toLocaleTimeString(),y:(""+this.getFullYear()).substr(2,4),Y:""+this.getFullYear(),"%":"%"};let result="",i=0;while(i=69){year=date[i]}else{year=new Date(Date.UTC(date[i],0)).getUTCFullYear()+100}break}++i}return new Date(Date.UTC(year,month,day))}} \ No newline at end of file +"use strict";function quickElement(){const obj=document.createElement(arguments[0]);if(arguments[2]){const textNode=document.createTextNode(arguments[2]);obj.appendChild(textNode)}const len=arguments.length;for(let i=3;i=12?"PM":"AM",S:this.getTwoDigitSecond(),w:"0"+this.getDay(),x:this.toLocaleDateString(),X:this.toLocaleTimeString(),y:(""+this.getFullYear()).substr(2,4),Y:""+this.getFullYear(),"%":"%"};let result="",i=0;while(i=69){year=date[i]}else{year=new Date(Date.UTC(date[i],0)).getUTCFullYear()+100}break}++i}return new Date(Date.UTC(year,month,day))}} diff --git a/src/country_workspace/web/static/workspace/js/core.min.min.js b/src/country_workspace/web/static/workspace/js/core.min.min.js new file mode 100644 index 0000000..537c555 --- /dev/null +++ b/src/country_workspace/web/static/workspace/js/core.min.min.js @@ -0,0 +1 @@ +"use strict";function quickElement(){const obj=document.createElement(arguments[0]);if(arguments[2]){const textNode=document.createTextNode(arguments[2]);obj.appendChild(textNode)}const len=arguments.length;for(let i=3;i=12?"PM":"AM",S:this.getTwoDigitSecond(),w:"0"+this.getDay(),x:this.toLocaleDateString(),X:this.toLocaleTimeString(),y:(""+this.getFullYear()).substr(2,4),Y:""+this.getFullYear(),"%":"%"};let result="",i=0;while(i=69){year=date[i]}else{year=new Date(Date.UTC(date[i],0)).getUTCFullYear()+100}break}++i}return new Date(Date.UTC(year,month,day))}} diff --git a/src/country_workspace/web/static/workspace/js/filters.min.js b/src/country_workspace/web/static/workspace/js/filters.min.js index 0dabb1f..962e013 100644 --- a/src/country_workspace/web/static/workspace/js/filters.min.js +++ b/src/country_workspace/web/static/workspace/js/filters.min.js @@ -1 +1 @@ -"use strict";{let filters=JSON.parse(sessionStorage.getItem("django.admin.filtersState"));if(!filters){filters={}}Object.entries(filters).forEach(([key,value])=>{const detailElement=document.querySelector(`[data-filter-title='${CSS.escape(key)}']`);if(detailElement){value?detailElement.setAttribute("open",""):detailElement.removeAttribute("open")}});const details=document.querySelectorAll("details");details.forEach(detail=>{detail.addEventListener("toggle",event=>{filters[`${event.target.dataset.filterTitle}`]=detail.open;sessionStorage.setItem("django.admin.filtersState",JSON.stringify(filters))})})} \ No newline at end of file +"use strict";{let filters=JSON.parse(sessionStorage.getItem("django.admin.filtersState"));if(!filters){filters={}}Object.entries(filters).forEach(([key,value])=>{const detailElement=document.querySelector(`[data-filter-title='${CSS.escape(key)}']`);if(detailElement){value?detailElement.setAttribute("open",""):detailElement.removeAttribute("open")}});const details=document.querySelectorAll("details");details.forEach(detail=>{detail.addEventListener("toggle",event=>{filters[`${event.target.dataset.filterTitle}`]=detail.open;sessionStorage.setItem("django.admin.filtersState",JSON.stringify(filters))})})} diff --git a/src/country_workspace/web/static/workspace/js/filters.min.min.js b/src/country_workspace/web/static/workspace/js/filters.min.min.js new file mode 100644 index 0000000..962e013 --- /dev/null +++ b/src/country_workspace/web/static/workspace/js/filters.min.min.js @@ -0,0 +1 @@ +"use strict";{let filters=JSON.parse(sessionStorage.getItem("django.admin.filtersState"));if(!filters){filters={}}Object.entries(filters).forEach(([key,value])=>{const detailElement=document.querySelector(`[data-filter-title='${CSS.escape(key)}']`);if(detailElement){value?detailElement.setAttribute("open",""):detailElement.removeAttribute("open")}});const details=document.querySelectorAll("details");details.forEach(detail=>{detail.addEventListener("toggle",event=>{filters[`${event.target.dataset.filterTitle}`]=detail.open;sessionStorage.setItem("django.admin.filtersState",JSON.stringify(filters))})})} diff --git a/src/country_workspace/web/static/workspace/js/inlines.min.js b/src/country_workspace/web/static/workspace/js/inlines.min.js index da71546..d3fa4ce 100644 --- a/src/country_workspace/web/static/workspace/js/inlines.min.js +++ b/src/country_workspace/web/static/workspace/js/inlines.min.js @@ -1 +1 @@ -"use strict";{const $=django.jQuery;$.fn.formset=function(opts){const options=$.extend({},$.fn.formset.defaults,opts);const $this=$(this);const $parent=$this.parent();const updateElementIndex=function(el,prefix,ndx){const id_regex=new RegExp("("+prefix+"-(\\d+|__prefix__))");const replacement=prefix+"-"+ndx;if($(el).prop("for")){$(el).prop("for",$(el).prop("for").replace(id_regex,replacement))}if(el.id){el.id=el.id.replace(id_regex,replacement)}if(el.name){el.name=el.name.replace(id_regex,replacement)}};const totalForms=$("#id_"+options.prefix+"-TOTAL_FORMS").prop("autocomplete","off");let nextIndex=parseInt(totalForms.val(),10);const maxForms=$("#id_"+options.prefix+"-MAX_NUM_FORMS").prop("autocomplete","off");const minForms=$("#id_"+options.prefix+"-MIN_NUM_FORMS").prop("autocomplete","off");let addButton;const addInlineAddButton=function(){if(addButton===null){if($this.prop("tagName")==="TR"){const numCols=$this.eq(-1).children().length;$parent.append(''+options.addText+"");addButton=$parent.find("tr:last a")}else{$this.filter(":last").after('");addButton=$this.filter(":last").next().find("a")}}addButton.on("click",addInlineClickHandler)};const addInlineClickHandler=function(e){e.preventDefault();const template=$("#"+options.prefix+"-empty");const row=template.clone(true);row.removeClass(options.emptyCssClass).addClass(options.formCssClass).attr("id",options.prefix+"-"+nextIndex);addInlineDeleteButton(row);row.find("*").each(function(){updateElementIndex(this,options.prefix,totalForms.val())});row.insertBefore($(template));$(totalForms).val(parseInt(totalForms.val(),10)+1);nextIndex+=1;if(maxForms.val()!==""&&maxForms.val()-totalForms.val()<=0){addButton.parent().hide()}toggleDeleteButtonVisibility(row.closest(".inline-group"));if(options.added){options.added(row)}row.get(0).dispatchEvent(new CustomEvent("formset:added",{bubbles:true,detail:{formsetName:options.prefix}}))};const addInlineDeleteButton=function(row){if(row.is("tr")){row.children(":last").append('")}else if(row.is("ul")||row.is("ol")){row.append('
  • '+options.deleteText+"
  • ")}else{row.children(":first").append(''+options.deleteText+"")}row.find("a."+options.deleteCssClass).on("click",inlineDeleteHandler.bind(this))};const inlineDeleteHandler=function(e1){e1.preventDefault();const deleteButton=$(e1.target);const row=deleteButton.closest("."+options.formCssClass);const inlineGroup=row.closest(".inline-group");const prevRow=row.prev();if(prevRow.length&&prevRow.hasClass("row-form-errors")){prevRow.remove()}row.remove();nextIndex-=1;if(options.removed){options.removed(row)}document.dispatchEvent(new CustomEvent("formset:removed",{detail:{formsetName:options.prefix}}));const forms=$("."+options.formCssClass);$("#id_"+options.prefix+"-TOTAL_FORMS").val(forms.length);if(maxForms.val()===""||maxForms.val()-forms.length>0){addButton.parent().show()}toggleDeleteButtonVisibility(inlineGroup);let i,formCount;const updateElementCallback=function(){updateElementIndex(this,options.prefix,i)};for(i=0,formCount=forms.length;i=0){inlineGroup.find(".inline-deletelink").hide()}else{inlineGroup.find(".inline-deletelink").show()}};$this.each(function(i){$(this).not("."+options.emptyCssClass).addClass(options.formCssClass)});$this.filter("."+options.formCssClass+":not(.has_original):not(."+options.emptyCssClass+")").each(function(){addInlineDeleteButton($(this))});toggleDeleteButtonVisibility($this);addButton=options.addButton;addInlineAddButton();const showAddButton=maxForms.val()===""||maxForms.val()-totalForms.val()>0;if($this.length&&showAddButton){addButton.parent().show()}else{addButton.parent().hide()}return this};$.fn.formset.defaults={prefix:"form",addText:"add another",deleteText:"remove",addCssClass:"add-row",deleteCssClass:"delete-row",emptyCssClass:"empty-row",formCssClass:"dynamic-form",added:null,removed:null,addButton:null};$.fn.tabularFormset=function(selector,options){const $rows=$(this);const reinitDateTimeShortCuts=function(){if(typeof DateTimeShortcuts!=="undefined"){$(".datetimeshortcuts").remove();DateTimeShortcuts.init()}};const updateSelectFilter=function(){if(typeof SelectFilter!=="undefined"){$(".selectfilter").each(function(index,value){SelectFilter.init(value.id,this.dataset.fieldName,false)});$(".selectfilterstacked").each(function(index,value){SelectFilter.init(value.id,this.dataset.fieldName,true)})}};const initPrepopulatedFields=function(row){row.find(".prepopulated_field").each(function(){const field=$(this),input=field.find("input, select, textarea"),dependency_list=input.data("dependency_list")||[],dependencies=[];$.each(dependency_list,function(i,field_name){dependencies.push("#"+row.find(".field-"+field_name).find("input, select, textarea").attr("id"))});if(dependencies.length){input.prepopulate(dependencies,input.attr("maxlength"))}})};$rows.formset({prefix:options.prefix,addText:options.addText,formCssClass:"dynamic-"+options.prefix,deleteCssClass:"inline-deletelink",deleteText:options.deleteText,emptyCssClass:"empty-form",added:function(row){initPrepopulatedFields(row);reinitDateTimeShortCuts();updateSelectFilter()},addButton:options.addButton});return $rows};$.fn.stackedFormset=function(selector,options){const $rows=$(this);const updateInlineLabel=function(row){$(selector).find(".inline_label").each(function(i){const count=i+1;$(this).html($(this).html().replace(/(#\d+)/g,"#"+count))})};const reinitDateTimeShortCuts=function(){if(typeof DateTimeShortcuts!=="undefined"){$(".datetimeshortcuts").remove();DateTimeShortcuts.init()}};const updateSelectFilter=function(){if(typeof SelectFilter!=="undefined"){$(".selectfilter").each(function(index,value){SelectFilter.init(value.id,this.dataset.fieldName,false)});$(".selectfilterstacked").each(function(index,value){SelectFilter.init(value.id,this.dataset.fieldName,true)})}};const initPrepopulatedFields=function(row){row.find(".prepopulated_field").each(function(){const field=$(this),input=field.find("input, select, textarea"),dependency_list=input.data("dependency_list")||[],dependencies=[];$.each(dependency_list,function(i,field_name){let field_element=row.find(".form-row .field-"+field_name);if(!field_element.length){field_element=row.find(".form-row.field-"+field_name)}dependencies.push("#"+field_element.find("input, select, textarea").attr("id"))});if(dependencies.length){input.prepopulate(dependencies,input.attr("maxlength"))}})};$rows.formset({prefix:options.prefix,addText:options.addText,formCssClass:"dynamic-"+options.prefix,deleteCssClass:"inline-deletelink",deleteText:options.deleteText,emptyCssClass:"empty-form",removed:updateInlineLabel,added:function(row){initPrepopulatedFields(row);reinitDateTimeShortCuts();updateSelectFilter();updateInlineLabel(row)},addButton:options.addButton});return $rows};$(document).ready(function(){$(".js-inline-admin-formset").each(function(){const data=$(this).data(),inlineOptions=data.inlineFormset;let selector;switch(data.inlineType){case"stacked":selector=inlineOptions.name+"-group .inline-related";$(selector).stackedFormset(selector,inlineOptions.options);break;case"tabular":selector=inlineOptions.name+"-group .tabular.inline-related tbody:first > tr.form-row";$(selector).tabularFormset(selector,inlineOptions.options);break}})})} \ No newline at end of file +"use strict";{const $=django.jQuery;$.fn.formset=function(opts){const options=$.extend({},$.fn.formset.defaults,opts);const $this=$(this);const $parent=$this.parent();const updateElementIndex=function(el,prefix,ndx){const id_regex=new RegExp("("+prefix+"-(\\d+|__prefix__))");const replacement=prefix+"-"+ndx;if($(el).prop("for")){$(el).prop("for",$(el).prop("for").replace(id_regex,replacement))}if(el.id){el.id=el.id.replace(id_regex,replacement)}if(el.name){el.name=el.name.replace(id_regex,replacement)}};const totalForms=$("#id_"+options.prefix+"-TOTAL_FORMS").prop("autocomplete","off");let nextIndex=parseInt(totalForms.val(),10);const maxForms=$("#id_"+options.prefix+"-MAX_NUM_FORMS").prop("autocomplete","off");const minForms=$("#id_"+options.prefix+"-MIN_NUM_FORMS").prop("autocomplete","off");let addButton;const addInlineAddButton=function(){if(addButton===null){if($this.prop("tagName")==="TR"){const numCols=$this.eq(-1).children().length;$parent.append(''+options.addText+"");addButton=$parent.find("tr:last a")}else{$this.filter(":last").after('");addButton=$this.filter(":last").next().find("a")}}addButton.on("click",addInlineClickHandler)};const addInlineClickHandler=function(e){e.preventDefault();const template=$("#"+options.prefix+"-empty");const row=template.clone(true);row.removeClass(options.emptyCssClass).addClass(options.formCssClass).attr("id",options.prefix+"-"+nextIndex);addInlineDeleteButton(row);row.find("*").each(function(){updateElementIndex(this,options.prefix,totalForms.val())});row.insertBefore($(template));$(totalForms).val(parseInt(totalForms.val(),10)+1);nextIndex+=1;if(maxForms.val()!==""&&maxForms.val()-totalForms.val()<=0){addButton.parent().hide()}toggleDeleteButtonVisibility(row.closest(".inline-group"));if(options.added){options.added(row)}row.get(0).dispatchEvent(new CustomEvent("formset:added",{bubbles:true,detail:{formsetName:options.prefix}}))};const addInlineDeleteButton=function(row){if(row.is("tr")){row.children(":last").append('")}else if(row.is("ul")||row.is("ol")){row.append('
  • '+options.deleteText+"
  • ")}else{row.children(":first").append(''+options.deleteText+"")}row.find("a."+options.deleteCssClass).on("click",inlineDeleteHandler.bind(this))};const inlineDeleteHandler=function(e1){e1.preventDefault();const deleteButton=$(e1.target);const row=deleteButton.closest("."+options.formCssClass);const inlineGroup=row.closest(".inline-group");const prevRow=row.prev();if(prevRow.length&&prevRow.hasClass("row-form-errors")){prevRow.remove()}row.remove();nextIndex-=1;if(options.removed){options.removed(row)}document.dispatchEvent(new CustomEvent("formset:removed",{detail:{formsetName:options.prefix}}));const forms=$("."+options.formCssClass);$("#id_"+options.prefix+"-TOTAL_FORMS").val(forms.length);if(maxForms.val()===""||maxForms.val()-forms.length>0){addButton.parent().show()}toggleDeleteButtonVisibility(inlineGroup);let i,formCount;const updateElementCallback=function(){updateElementIndex(this,options.prefix,i)};for(i=0,formCount=forms.length;i=0){inlineGroup.find(".inline-deletelink").hide()}else{inlineGroup.find(".inline-deletelink").show()}};$this.each(function(i){$(this).not("."+options.emptyCssClass).addClass(options.formCssClass)});$this.filter("."+options.formCssClass+":not(.has_original):not(."+options.emptyCssClass+")").each(function(){addInlineDeleteButton($(this))});toggleDeleteButtonVisibility($this);addButton=options.addButton;addInlineAddButton();const showAddButton=maxForms.val()===""||maxForms.val()-totalForms.val()>0;if($this.length&&showAddButton){addButton.parent().show()}else{addButton.parent().hide()}return this};$.fn.formset.defaults={prefix:"form",addText:"add another",deleteText:"remove",addCssClass:"add-row",deleteCssClass:"delete-row",emptyCssClass:"empty-row",formCssClass:"dynamic-form",added:null,removed:null,addButton:null};$.fn.tabularFormset=function(selector,options){const $rows=$(this);const reinitDateTimeShortCuts=function(){if(typeof DateTimeShortcuts!=="undefined"){$(".datetimeshortcuts").remove();DateTimeShortcuts.init()}};const updateSelectFilter=function(){if(typeof SelectFilter!=="undefined"){$(".selectfilter").each(function(index,value){SelectFilter.init(value.id,this.dataset.fieldName,false)});$(".selectfilterstacked").each(function(index,value){SelectFilter.init(value.id,this.dataset.fieldName,true)})}};const initPrepopulatedFields=function(row){row.find(".prepopulated_field").each(function(){const field=$(this),input=field.find("input, select, textarea"),dependency_list=input.data("dependency_list")||[],dependencies=[];$.each(dependency_list,function(i,field_name){dependencies.push("#"+row.find(".field-"+field_name).find("input, select, textarea").attr("id"))});if(dependencies.length){input.prepopulate(dependencies,input.attr("maxlength"))}})};$rows.formset({prefix:options.prefix,addText:options.addText,formCssClass:"dynamic-"+options.prefix,deleteCssClass:"inline-deletelink",deleteText:options.deleteText,emptyCssClass:"empty-form",added:function(row){initPrepopulatedFields(row);reinitDateTimeShortCuts();updateSelectFilter()},addButton:options.addButton});return $rows};$.fn.stackedFormset=function(selector,options){const $rows=$(this);const updateInlineLabel=function(row){$(selector).find(".inline_label").each(function(i){const count=i+1;$(this).html($(this).html().replace(/(#\d+)/g,"#"+count))})};const reinitDateTimeShortCuts=function(){if(typeof DateTimeShortcuts!=="undefined"){$(".datetimeshortcuts").remove();DateTimeShortcuts.init()}};const updateSelectFilter=function(){if(typeof SelectFilter!=="undefined"){$(".selectfilter").each(function(index,value){SelectFilter.init(value.id,this.dataset.fieldName,false)});$(".selectfilterstacked").each(function(index,value){SelectFilter.init(value.id,this.dataset.fieldName,true)})}};const initPrepopulatedFields=function(row){row.find(".prepopulated_field").each(function(){const field=$(this),input=field.find("input, select, textarea"),dependency_list=input.data("dependency_list")||[],dependencies=[];$.each(dependency_list,function(i,field_name){let field_element=row.find(".form-row .field-"+field_name);if(!field_element.length){field_element=row.find(".form-row.field-"+field_name)}dependencies.push("#"+field_element.find("input, select, textarea").attr("id"))});if(dependencies.length){input.prepopulate(dependencies,input.attr("maxlength"))}})};$rows.formset({prefix:options.prefix,addText:options.addText,formCssClass:"dynamic-"+options.prefix,deleteCssClass:"inline-deletelink",deleteText:options.deleteText,emptyCssClass:"empty-form",removed:updateInlineLabel,added:function(row){initPrepopulatedFields(row);reinitDateTimeShortCuts();updateSelectFilter();updateInlineLabel(row)},addButton:options.addButton});return $rows};$(document).ready(function(){$(".js-inline-admin-formset").each(function(){const data=$(this).data(),inlineOptions=data.inlineFormset;let selector;switch(data.inlineType){case"stacked":selector=inlineOptions.name+"-group .inline-related";$(selector).stackedFormset(selector,inlineOptions.options);break;case"tabular":selector=inlineOptions.name+"-group .tabular.inline-related tbody:first > tr.form-row";$(selector).tabularFormset(selector,inlineOptions.options);break}})})} diff --git a/src/country_workspace/web/static/workspace/js/inlines.min.min.js b/src/country_workspace/web/static/workspace/js/inlines.min.min.js new file mode 100644 index 0000000..d3fa4ce --- /dev/null +++ b/src/country_workspace/web/static/workspace/js/inlines.min.min.js @@ -0,0 +1 @@ +"use strict";{const $=django.jQuery;$.fn.formset=function(opts){const options=$.extend({},$.fn.formset.defaults,opts);const $this=$(this);const $parent=$this.parent();const updateElementIndex=function(el,prefix,ndx){const id_regex=new RegExp("("+prefix+"-(\\d+|__prefix__))");const replacement=prefix+"-"+ndx;if($(el).prop("for")){$(el).prop("for",$(el).prop("for").replace(id_regex,replacement))}if(el.id){el.id=el.id.replace(id_regex,replacement)}if(el.name){el.name=el.name.replace(id_regex,replacement)}};const totalForms=$("#id_"+options.prefix+"-TOTAL_FORMS").prop("autocomplete","off");let nextIndex=parseInt(totalForms.val(),10);const maxForms=$("#id_"+options.prefix+"-MAX_NUM_FORMS").prop("autocomplete","off");const minForms=$("#id_"+options.prefix+"-MIN_NUM_FORMS").prop("autocomplete","off");let addButton;const addInlineAddButton=function(){if(addButton===null){if($this.prop("tagName")==="TR"){const numCols=$this.eq(-1).children().length;$parent.append(''+options.addText+"");addButton=$parent.find("tr:last a")}else{$this.filter(":last").after('");addButton=$this.filter(":last").next().find("a")}}addButton.on("click",addInlineClickHandler)};const addInlineClickHandler=function(e){e.preventDefault();const template=$("#"+options.prefix+"-empty");const row=template.clone(true);row.removeClass(options.emptyCssClass).addClass(options.formCssClass).attr("id",options.prefix+"-"+nextIndex);addInlineDeleteButton(row);row.find("*").each(function(){updateElementIndex(this,options.prefix,totalForms.val())});row.insertBefore($(template));$(totalForms).val(parseInt(totalForms.val(),10)+1);nextIndex+=1;if(maxForms.val()!==""&&maxForms.val()-totalForms.val()<=0){addButton.parent().hide()}toggleDeleteButtonVisibility(row.closest(".inline-group"));if(options.added){options.added(row)}row.get(0).dispatchEvent(new CustomEvent("formset:added",{bubbles:true,detail:{formsetName:options.prefix}}))};const addInlineDeleteButton=function(row){if(row.is("tr")){row.children(":last").append('")}else if(row.is("ul")||row.is("ol")){row.append('
  • '+options.deleteText+"
  • ")}else{row.children(":first").append(''+options.deleteText+"")}row.find("a."+options.deleteCssClass).on("click",inlineDeleteHandler.bind(this))};const inlineDeleteHandler=function(e1){e1.preventDefault();const deleteButton=$(e1.target);const row=deleteButton.closest("."+options.formCssClass);const inlineGroup=row.closest(".inline-group");const prevRow=row.prev();if(prevRow.length&&prevRow.hasClass("row-form-errors")){prevRow.remove()}row.remove();nextIndex-=1;if(options.removed){options.removed(row)}document.dispatchEvent(new CustomEvent("formset:removed",{detail:{formsetName:options.prefix}}));const forms=$("."+options.formCssClass);$("#id_"+options.prefix+"-TOTAL_FORMS").val(forms.length);if(maxForms.val()===""||maxForms.val()-forms.length>0){addButton.parent().show()}toggleDeleteButtonVisibility(inlineGroup);let i,formCount;const updateElementCallback=function(){updateElementIndex(this,options.prefix,i)};for(i=0,formCount=forms.length;i=0){inlineGroup.find(".inline-deletelink").hide()}else{inlineGroup.find(".inline-deletelink").show()}};$this.each(function(i){$(this).not("."+options.emptyCssClass).addClass(options.formCssClass)});$this.filter("."+options.formCssClass+":not(.has_original):not(."+options.emptyCssClass+")").each(function(){addInlineDeleteButton($(this))});toggleDeleteButtonVisibility($this);addButton=options.addButton;addInlineAddButton();const showAddButton=maxForms.val()===""||maxForms.val()-totalForms.val()>0;if($this.length&&showAddButton){addButton.parent().show()}else{addButton.parent().hide()}return this};$.fn.formset.defaults={prefix:"form",addText:"add another",deleteText:"remove",addCssClass:"add-row",deleteCssClass:"delete-row",emptyCssClass:"empty-row",formCssClass:"dynamic-form",added:null,removed:null,addButton:null};$.fn.tabularFormset=function(selector,options){const $rows=$(this);const reinitDateTimeShortCuts=function(){if(typeof DateTimeShortcuts!=="undefined"){$(".datetimeshortcuts").remove();DateTimeShortcuts.init()}};const updateSelectFilter=function(){if(typeof SelectFilter!=="undefined"){$(".selectfilter").each(function(index,value){SelectFilter.init(value.id,this.dataset.fieldName,false)});$(".selectfilterstacked").each(function(index,value){SelectFilter.init(value.id,this.dataset.fieldName,true)})}};const initPrepopulatedFields=function(row){row.find(".prepopulated_field").each(function(){const field=$(this),input=field.find("input, select, textarea"),dependency_list=input.data("dependency_list")||[],dependencies=[];$.each(dependency_list,function(i,field_name){dependencies.push("#"+row.find(".field-"+field_name).find("input, select, textarea").attr("id"))});if(dependencies.length){input.prepopulate(dependencies,input.attr("maxlength"))}})};$rows.formset({prefix:options.prefix,addText:options.addText,formCssClass:"dynamic-"+options.prefix,deleteCssClass:"inline-deletelink",deleteText:options.deleteText,emptyCssClass:"empty-form",added:function(row){initPrepopulatedFields(row);reinitDateTimeShortCuts();updateSelectFilter()},addButton:options.addButton});return $rows};$.fn.stackedFormset=function(selector,options){const $rows=$(this);const updateInlineLabel=function(row){$(selector).find(".inline_label").each(function(i){const count=i+1;$(this).html($(this).html().replace(/(#\d+)/g,"#"+count))})};const reinitDateTimeShortCuts=function(){if(typeof DateTimeShortcuts!=="undefined"){$(".datetimeshortcuts").remove();DateTimeShortcuts.init()}};const updateSelectFilter=function(){if(typeof SelectFilter!=="undefined"){$(".selectfilter").each(function(index,value){SelectFilter.init(value.id,this.dataset.fieldName,false)});$(".selectfilterstacked").each(function(index,value){SelectFilter.init(value.id,this.dataset.fieldName,true)})}};const initPrepopulatedFields=function(row){row.find(".prepopulated_field").each(function(){const field=$(this),input=field.find("input, select, textarea"),dependency_list=input.data("dependency_list")||[],dependencies=[];$.each(dependency_list,function(i,field_name){let field_element=row.find(".form-row .field-"+field_name);if(!field_element.length){field_element=row.find(".form-row.field-"+field_name)}dependencies.push("#"+field_element.find("input, select, textarea").attr("id"))});if(dependencies.length){input.prepopulate(dependencies,input.attr("maxlength"))}})};$rows.formset({prefix:options.prefix,addText:options.addText,formCssClass:"dynamic-"+options.prefix,deleteCssClass:"inline-deletelink",deleteText:options.deleteText,emptyCssClass:"empty-form",removed:updateInlineLabel,added:function(row){initPrepopulatedFields(row);reinitDateTimeShortCuts();updateSelectFilter();updateInlineLabel(row)},addButton:options.addButton});return $rows};$(document).ready(function(){$(".js-inline-admin-formset").each(function(){const data=$(this).data(),inlineOptions=data.inlineFormset;let selector;switch(data.inlineType){case"stacked":selector=inlineOptions.name+"-group .inline-related";$(selector).stackedFormset(selector,inlineOptions.options);break;case"tabular":selector=inlineOptions.name+"-group .tabular.inline-related tbody:first > tr.form-row";$(selector).tabularFormset(selector,inlineOptions.options);break}})})} diff --git a/src/country_workspace/web/static/workspace/js/jquery.init.min.js b/src/country_workspace/web/static/workspace/js/jquery.init.min.js index d6f2183..ee42072 100644 --- a/src/country_workspace/web/static/workspace/js/jquery.init.min.js +++ b/src/country_workspace/web/static/workspace/js/jquery.init.min.js @@ -1 +1 @@ -"use strict";window.django={jQuery:jQuery.noConflict(true)}; \ No newline at end of file +"use strict";window.django={jQuery:jQuery.noConflict(true)}; diff --git a/src/country_workspace/web/static/workspace/js/jquery.init.min.min.js b/src/country_workspace/web/static/workspace/js/jquery.init.min.min.js new file mode 100644 index 0000000..ee42072 --- /dev/null +++ b/src/country_workspace/web/static/workspace/js/jquery.init.min.min.js @@ -0,0 +1 @@ +"use strict";window.django={jQuery:jQuery.noConflict(true)}; diff --git a/src/country_workspace/web/static/workspace/js/nav_sidebar.min.js b/src/country_workspace/web/static/workspace/js/nav_sidebar.min.js index 4ba0482..9255c50 100644 --- a/src/country_workspace/web/static/workspace/js/nav_sidebar.min.js +++ b/src/country_workspace/web/static/workspace/js/nav_sidebar.min.js @@ -1 +1 @@ -"use strict";{const toggleNavSidebar=document.getElementById("toggle-nav-sidebar");if(toggleNavSidebar!==null){const navSidebar=document.getElementById("nav-sidebar");const main=document.getElementById("main");let navSidebarIsOpen=localStorage.getItem("django.admin.navSidebarIsOpen");if(navSidebarIsOpen===null){navSidebarIsOpen="true"}main.classList.toggle("shifted",navSidebarIsOpen==="true");navSidebar.setAttribute("aria-expanded",navSidebarIsOpen);toggleNavSidebar.addEventListener("click",function(){if(navSidebarIsOpen==="true"){navSidebarIsOpen="false"}else{navSidebarIsOpen="true"}localStorage.setItem("django.admin.navSidebarIsOpen",navSidebarIsOpen);main.classList.toggle("shifted");navSidebar.setAttribute("aria-expanded",navSidebarIsOpen)})}function initSidebarQuickFilter(){const options=[];const navSidebar=document.getElementById("nav-sidebar");if(!navSidebar){return}navSidebar.querySelectorAll("th[scope=row] a").forEach(container=>{options.push({title:container.innerHTML,node:container})});function checkValue(event){let filterValue=event.target.value;if(filterValue){filterValue=filterValue.toLowerCase()}if(event.key==="Escape"){filterValue="";event.target.value=""}let matches=false;for(const o of options){let displayValue="";if(filterValue){if(o.title.toLowerCase().indexOf(filterValue)===-1){displayValue="none"}else{matches=true}}o.node.parentNode.parentNode.style.display=displayValue}if(!filterValue||matches){event.target.classList.remove("no-results")}else{event.target.classList.add("no-results")}sessionStorage.setItem("django.admin.navSidebarFilterValue",filterValue)}const nav=document.getElementById("nav-filter");nav.addEventListener("change",checkValue,false);nav.addEventListener("input",checkValue,false);nav.addEventListener("keyup",checkValue,false);const storedValue=sessionStorage.getItem("django.admin.navSidebarFilterValue");if(storedValue){nav.value=storedValue;checkValue({target:nav,key:""})}}window.initSidebarQuickFilter=initSidebarQuickFilter;initSidebarQuickFilter()} \ No newline at end of file +"use strict";{const toggleNavSidebar=document.getElementById("toggle-nav-sidebar");if(toggleNavSidebar!==null){const navSidebar=document.getElementById("nav-sidebar");const main=document.getElementById("main");let navSidebarIsOpen=localStorage.getItem("django.admin.navSidebarIsOpen");if(navSidebarIsOpen===null){navSidebarIsOpen="true"}main.classList.toggle("shifted",navSidebarIsOpen==="true");navSidebar.setAttribute("aria-expanded",navSidebarIsOpen);toggleNavSidebar.addEventListener("click",function(){if(navSidebarIsOpen==="true"){navSidebarIsOpen="false"}else{navSidebarIsOpen="true"}localStorage.setItem("django.admin.navSidebarIsOpen",navSidebarIsOpen);main.classList.toggle("shifted");navSidebar.setAttribute("aria-expanded",navSidebarIsOpen)})}function initSidebarQuickFilter(){const options=[];const navSidebar=document.getElementById("nav-sidebar");if(!navSidebar){return}navSidebar.querySelectorAll("th[scope=row] a").forEach(container=>{options.push({title:container.innerHTML,node:container})});function checkValue(event){let filterValue=event.target.value;if(filterValue){filterValue=filterValue.toLowerCase()}if(event.key==="Escape"){filterValue="";event.target.value=""}let matches=false;for(const o of options){let displayValue="";if(filterValue){if(o.title.toLowerCase().indexOf(filterValue)===-1){displayValue="none"}else{matches=true}}o.node.parentNode.parentNode.style.display=displayValue}if(!filterValue||matches){event.target.classList.remove("no-results")}else{event.target.classList.add("no-results")}sessionStorage.setItem("django.admin.navSidebarFilterValue",filterValue)}const nav=document.getElementById("nav-filter");nav.addEventListener("change",checkValue,false);nav.addEventListener("input",checkValue,false);nav.addEventListener("keyup",checkValue,false);const storedValue=sessionStorage.getItem("django.admin.navSidebarFilterValue");if(storedValue){nav.value=storedValue;checkValue({target:nav,key:""})}}window.initSidebarQuickFilter=initSidebarQuickFilter;initSidebarQuickFilter()} diff --git a/src/country_workspace/web/static/workspace/js/nav_sidebar.min.min.js b/src/country_workspace/web/static/workspace/js/nav_sidebar.min.min.js new file mode 100644 index 0000000..9255c50 --- /dev/null +++ b/src/country_workspace/web/static/workspace/js/nav_sidebar.min.min.js @@ -0,0 +1 @@ +"use strict";{const toggleNavSidebar=document.getElementById("toggle-nav-sidebar");if(toggleNavSidebar!==null){const navSidebar=document.getElementById("nav-sidebar");const main=document.getElementById("main");let navSidebarIsOpen=localStorage.getItem("django.admin.navSidebarIsOpen");if(navSidebarIsOpen===null){navSidebarIsOpen="true"}main.classList.toggle("shifted",navSidebarIsOpen==="true");navSidebar.setAttribute("aria-expanded",navSidebarIsOpen);toggleNavSidebar.addEventListener("click",function(){if(navSidebarIsOpen==="true"){navSidebarIsOpen="false"}else{navSidebarIsOpen="true"}localStorage.setItem("django.admin.navSidebarIsOpen",navSidebarIsOpen);main.classList.toggle("shifted");navSidebar.setAttribute("aria-expanded",navSidebarIsOpen)})}function initSidebarQuickFilter(){const options=[];const navSidebar=document.getElementById("nav-sidebar");if(!navSidebar){return}navSidebar.querySelectorAll("th[scope=row] a").forEach(container=>{options.push({title:container.innerHTML,node:container})});function checkValue(event){let filterValue=event.target.value;if(filterValue){filterValue=filterValue.toLowerCase()}if(event.key==="Escape"){filterValue="";event.target.value=""}let matches=false;for(const o of options){let displayValue="";if(filterValue){if(o.title.toLowerCase().indexOf(filterValue)===-1){displayValue="none"}else{matches=true}}o.node.parentNode.parentNode.style.display=displayValue}if(!filterValue||matches){event.target.classList.remove("no-results")}else{event.target.classList.add("no-results")}sessionStorage.setItem("django.admin.navSidebarFilterValue",filterValue)}const nav=document.getElementById("nav-filter");nav.addEventListener("change",checkValue,false);nav.addEventListener("input",checkValue,false);nav.addEventListener("keyup",checkValue,false);const storedValue=sessionStorage.getItem("django.admin.navSidebarFilterValue");if(storedValue){nav.value=storedValue;checkValue({target:nav,key:""})}}window.initSidebarQuickFilter=initSidebarQuickFilter;initSidebarQuickFilter()} diff --git a/src/country_workspace/web/static/workspace/js/popup_response.min.js b/src/country_workspace/web/static/workspace/js/popup_response.min.js index db1bd08..b1b206b 100644 --- a/src/country_workspace/web/static/workspace/js/popup_response.min.js +++ b/src/country_workspace/web/static/workspace/js/popup_response.min.js @@ -1 +1 @@ -"use strict";{const initData=JSON.parse(document.getElementById("django-admin-popup-response-constants").dataset.popupResponse);switch(initData.action){case"change":opener.dismissChangeRelatedObjectPopup(window,initData.value,initData.obj,initData.new_value);break;case"delete":opener.dismissDeleteRelatedObjectPopup(window,initData.value);break;default:opener.dismissAddRelatedObjectPopup(window,initData.value,initData.obj);break}} \ No newline at end of file +"use strict";{const initData=JSON.parse(document.getElementById("django-admin-popup-response-constants").dataset.popupResponse);switch(initData.action){case"change":opener.dismissChangeRelatedObjectPopup(window,initData.value,initData.obj,initData.new_value);break;case"delete":opener.dismissDeleteRelatedObjectPopup(window,initData.value);break;default:opener.dismissAddRelatedObjectPopup(window,initData.value,initData.obj);break}} diff --git a/src/country_workspace/web/static/workspace/js/popup_response.min.min.js b/src/country_workspace/web/static/workspace/js/popup_response.min.min.js new file mode 100644 index 0000000..b1b206b --- /dev/null +++ b/src/country_workspace/web/static/workspace/js/popup_response.min.min.js @@ -0,0 +1 @@ +"use strict";{const initData=JSON.parse(document.getElementById("django-admin-popup-response-constants").dataset.popupResponse);switch(initData.action){case"change":opener.dismissChangeRelatedObjectPopup(window,initData.value,initData.obj,initData.new_value);break;case"delete":opener.dismissDeleteRelatedObjectPopup(window,initData.value);break;default:opener.dismissAddRelatedObjectPopup(window,initData.value,initData.obj);break}} diff --git a/src/country_workspace/web/static/workspace/js/prepopulate.min.js b/src/country_workspace/web/static/workspace/js/prepopulate.min.js index e7c0c0d..835a913 100644 --- a/src/country_workspace/web/static/workspace/js/prepopulate.min.js +++ b/src/country_workspace/web/static/workspace/js/prepopulate.min.js @@ -1 +1 @@ -"use strict";{const $=django.jQuery;$.fn.prepopulate=function(dependencies,maxLength,allowUnicode){return this.each(function(){const prepopulatedField=$(this);const populate=function(){if(prepopulatedField.data("_changed")){return}const values=[];$.each(dependencies,function(i,field){field=$(field);if(field.val().length>0){values.push(field.val())}});prepopulatedField.val(URLify(values.join(" "),maxLength,allowUnicode))};prepopulatedField.data("_changed",false);prepopulatedField.on("change",function(){prepopulatedField.data("_changed",true)});if(!prepopulatedField.val()){$(dependencies.join(",")).on("keyup change focus",populate)}})}} \ No newline at end of file +"use strict";{const $=django.jQuery;$.fn.prepopulate=function(dependencies,maxLength,allowUnicode){return this.each(function(){const prepopulatedField=$(this);const populate=function(){if(prepopulatedField.data("_changed")){return}const values=[];$.each(dependencies,function(i,field){field=$(field);if(field.val().length>0){values.push(field.val())}});prepopulatedField.val(URLify(values.join(" "),maxLength,allowUnicode))};prepopulatedField.data("_changed",false);prepopulatedField.on("change",function(){prepopulatedField.data("_changed",true)});if(!prepopulatedField.val()){$(dependencies.join(",")).on("keyup change focus",populate)}})}} diff --git a/src/country_workspace/web/static/workspace/js/prepopulate.min.min.js b/src/country_workspace/web/static/workspace/js/prepopulate.min.min.js new file mode 100644 index 0000000..835a913 --- /dev/null +++ b/src/country_workspace/web/static/workspace/js/prepopulate.min.min.js @@ -0,0 +1 @@ +"use strict";{const $=django.jQuery;$.fn.prepopulate=function(dependencies,maxLength,allowUnicode){return this.each(function(){const prepopulatedField=$(this);const populate=function(){if(prepopulatedField.data("_changed")){return}const values=[];$.each(dependencies,function(i,field){field=$(field);if(field.val().length>0){values.push(field.val())}});prepopulatedField.val(URLify(values.join(" "),maxLength,allowUnicode))};prepopulatedField.data("_changed",false);prepopulatedField.on("change",function(){prepopulatedField.data("_changed",true)});if(!prepopulatedField.val()){$(dependencies.join(",")).on("keyup change focus",populate)}})}} diff --git a/src/country_workspace/web/static/workspace/js/prepopulate_init.min.js b/src/country_workspace/web/static/workspace/js/prepopulate_init.min.js index 9fd5ace..8c43233 100644 --- a/src/country_workspace/web/static/workspace/js/prepopulate_init.min.js +++ b/src/country_workspace/web/static/workspace/js/prepopulate_init.min.js @@ -1 +1 @@ -"use strict";{const $=django.jQuery;const fields=$("#django-admin-prepopulated-fields-constants").data("prepopulatedFields");$.each(fields,function(index,field){$(".empty-form .form-row .field-"+field.name+", .empty-form.form-row .field-"+field.name+", .empty-form .form-row.field-"+field.name).addClass("prepopulated_field");$(field.id).data("dependency_list",field.dependency_list).prepopulate(field.dependency_ids,field.maxLength,field.allowUnicode)})} \ No newline at end of file +"use strict";{const $=django.jQuery;const fields=$("#django-admin-prepopulated-fields-constants").data("prepopulatedFields");$.each(fields,function(index,field){$(".empty-form .form-row .field-"+field.name+", .empty-form.form-row .field-"+field.name+", .empty-form .form-row.field-"+field.name).addClass("prepopulated_field");$(field.id).data("dependency_list",field.dependency_list).prepopulate(field.dependency_ids,field.maxLength,field.allowUnicode)})} diff --git a/src/country_workspace/web/static/workspace/js/prepopulate_init.min.min.js b/src/country_workspace/web/static/workspace/js/prepopulate_init.min.min.js new file mode 100644 index 0000000..8c43233 --- /dev/null +++ b/src/country_workspace/web/static/workspace/js/prepopulate_init.min.min.js @@ -0,0 +1 @@ +"use strict";{const $=django.jQuery;const fields=$("#django-admin-prepopulated-fields-constants").data("prepopulatedFields");$.each(fields,function(index,field){$(".empty-form .form-row .field-"+field.name+", .empty-form.form-row .field-"+field.name+", .empty-form .form-row.field-"+field.name).addClass("prepopulated_field");$(field.id).data("dependency_list",field.dependency_list).prepopulate(field.dependency_ids,field.maxLength,field.allowUnicode)})} diff --git a/src/country_workspace/web/static/workspace/js/theme.min.js b/src/country_workspace/web/static/workspace/js/theme.min.js index cd4c99c..9b8de3e 100644 --- a/src/country_workspace/web/static/workspace/js/theme.min.js +++ b/src/country_workspace/web/static/workspace/js/theme.min.js @@ -1 +1 @@ -"use strict";{function setTheme(mode){if(mode!=="light"&&mode!=="dark"&&mode!=="auto"){console.error(`Got invalid theme mode: ${mode}. Resetting to auto.`);mode="auto"}document.documentElement.dataset.theme=mode;localStorage.setItem("theme",mode)}function cycleTheme(){const currentTheme=localStorage.getItem("theme")||"auto";const prefersDark=window.matchMedia("(prefers-color-scheme: dark)").matches;if(prefersDark){if(currentTheme==="auto"){setTheme("light")}else if(currentTheme==="light"){setTheme("dark")}else{setTheme("auto")}}else{if(currentTheme==="auto"){setTheme("dark")}else if(currentTheme==="dark"){setTheme("light")}else{setTheme("auto")}}}function initTheme(){const currentTheme=localStorage.getItem("theme");currentTheme?setTheme(currentTheme):setTheme("auto")}window.addEventListener("load",function(_){const buttons=document.getElementsByClassName("theme-toggle");Array.from(buttons).forEach(btn=>{btn.addEventListener("click",cycleTheme)})});initTheme()} \ No newline at end of file +"use strict";{function setTheme(mode){if(mode!=="light"&&mode!=="dark"&&mode!=="auto"){console.error(`Got invalid theme mode: ${mode}. Resetting to auto.`);mode="auto"}document.documentElement.dataset.theme=mode;localStorage.setItem("theme",mode)}function cycleTheme(){const currentTheme=localStorage.getItem("theme")||"auto";const prefersDark=window.matchMedia("(prefers-color-scheme: dark)").matches;if(prefersDark){if(currentTheme==="auto"){setTheme("light")}else if(currentTheme==="light"){setTheme("dark")}else{setTheme("auto")}}else{if(currentTheme==="auto"){setTheme("dark")}else if(currentTheme==="dark"){setTheme("light")}else{setTheme("auto")}}}function initTheme(){const currentTheme=localStorage.getItem("theme");currentTheme?setTheme(currentTheme):setTheme("auto")}window.addEventListener("load",function(_){const buttons=document.getElementsByClassName("theme-toggle");Array.from(buttons).forEach(btn=>{btn.addEventListener("click",cycleTheme)})});initTheme()} diff --git a/src/country_workspace/web/static/workspace/js/theme.min.min.js b/src/country_workspace/web/static/workspace/js/theme.min.min.js new file mode 100644 index 0000000..9b8de3e --- /dev/null +++ b/src/country_workspace/web/static/workspace/js/theme.min.min.js @@ -0,0 +1 @@ +"use strict";{function setTheme(mode){if(mode!=="light"&&mode!=="dark"&&mode!=="auto"){console.error(`Got invalid theme mode: ${mode}. Resetting to auto.`);mode="auto"}document.documentElement.dataset.theme=mode;localStorage.setItem("theme",mode)}function cycleTheme(){const currentTheme=localStorage.getItem("theme")||"auto";const prefersDark=window.matchMedia("(prefers-color-scheme: dark)").matches;if(prefersDark){if(currentTheme==="auto"){setTheme("light")}else if(currentTheme==="light"){setTheme("dark")}else{setTheme("auto")}}else{if(currentTheme==="auto"){setTheme("dark")}else if(currentTheme==="dark"){setTheme("light")}else{setTheme("auto")}}}function initTheme(){const currentTheme=localStorage.getItem("theme");currentTheme?setTheme(currentTheme):setTheme("auto")}window.addEventListener("load",function(_){const buttons=document.getElementsByClassName("theme-toggle");Array.from(buttons).forEach(btn=>{btn.addEventListener("click",cycleTheme)})});initTheme()} diff --git a/src/country_workspace/web/static/workspace/js/unusable_password_field.min.js b/src/country_workspace/web/static/workspace/js/unusable_password_field.min.js index f093338..01a5b4c 100644 --- a/src/country_workspace/web/static/workspace/js/unusable_password_field.min.js +++ b/src/country_workspace/web/static/workspace/js/unusable_password_field.min.js @@ -1 +1 @@ -"use strict";try{document.querySelector("form:has(input)")}catch(error){console.log("Defaulting to javascript for usable password form management: "+error);document.querySelectorAll('input[name="usable_password"]').forEach(option=>{option.addEventListener("change",function(){const usablePassword=this.value==="true"?this.checked:!this.checked;const submit1=document.querySelector('input[type="submit"].set-password');const submit2=document.querySelector('input[type="submit"].unset-password');const messages=document.querySelector("#id_unusable_warning");document.getElementById("id_password1").closest(".form-row").hidden=!usablePassword;document.getElementById("id_password2").closest(".form-row").hidden=!usablePassword;if(messages){messages.hidden=usablePassword}if(submit1&&submit2){submit1.hidden=!usablePassword;submit2.hidden=usablePassword}});option.dispatchEvent(new Event("change"))})} \ No newline at end of file +"use strict";try{document.querySelector("form:has(input)")}catch(error){console.log("Defaulting to javascript for usable password form management: "+error);document.querySelectorAll('input[name="usable_password"]').forEach(option=>{option.addEventListener("change",function(){const usablePassword=this.value==="true"?this.checked:!this.checked;const submit1=document.querySelector('input[type="submit"].set-password');const submit2=document.querySelector('input[type="submit"].unset-password');const messages=document.querySelector("#id_unusable_warning");document.getElementById("id_password1").closest(".form-row").hidden=!usablePassword;document.getElementById("id_password2").closest(".form-row").hidden=!usablePassword;if(messages){messages.hidden=usablePassword}if(submit1&&submit2){submit1.hidden=!usablePassword;submit2.hidden=usablePassword}});option.dispatchEvent(new Event("change"))})} diff --git a/src/country_workspace/web/static/workspace/js/unusable_password_field.min.min.js b/src/country_workspace/web/static/workspace/js/unusable_password_field.min.min.js new file mode 100644 index 0000000..01a5b4c --- /dev/null +++ b/src/country_workspace/web/static/workspace/js/unusable_password_field.min.min.js @@ -0,0 +1 @@ +"use strict";try{document.querySelector("form:has(input)")}catch(error){console.log("Defaulting to javascript for usable password form management: "+error);document.querySelectorAll('input[name="usable_password"]').forEach(option=>{option.addEventListener("change",function(){const usablePassword=this.value==="true"?this.checked:!this.checked;const submit1=document.querySelector('input[type="submit"].set-password');const submit2=document.querySelector('input[type="submit"].unset-password');const messages=document.querySelector("#id_unusable_warning");document.getElementById("id_password1").closest(".form-row").hidden=!usablePassword;document.getElementById("id_password2").closest(".form-row").hidden=!usablePassword;if(messages){messages.hidden=usablePassword}if(submit1&&submit2){submit1.hidden=!usablePassword;submit2.hidden=usablePassword}});option.dispatchEvent(new Event("change"))})} diff --git a/src/country_workspace/web/static/workspace/js/urlify.min.js b/src/country_workspace/web/static/workspace/js/urlify.min.js index df6f57e..019a74d 100644 --- a/src/country_workspace/web/static/workspace/js/urlify.min.js +++ b/src/country_workspace/web/static/workspace/js/urlify.min.js @@ -1 +1 @@ -"use strict";{const LATIN_MAP={"À":"A","Á":"A","Â":"A","Ã":"A","Ä":"A","Å":"A","Æ":"AE","Ç":"C","È":"E","É":"E","Ê":"E","Ë":"E","Ì":"I","Í":"I","Î":"I","Ï":"I","Ð":"D","Ñ":"N","Ò":"O","Ó":"O","Ô":"O","Õ":"O","Ö":"O","Ő":"O","Ø":"O","Ù":"U","Ú":"U","Û":"U","Ü":"U","Ű":"U","Ý":"Y","Þ":"TH","Ÿ":"Y","ß":"ss","à":"a","á":"a","â":"a","ã":"a","ä":"a","å":"a","æ":"ae","ç":"c","è":"e","é":"e","ê":"e","ë":"e","ì":"i","í":"i","î":"i","ï":"i","ð":"d","ñ":"n","ò":"o","ó":"o","ô":"o","õ":"o","ö":"o","ő":"o","ø":"o","ù":"u","ú":"u","û":"u","ü":"u","ű":"u","ý":"y","þ":"th","ÿ":"y"};const LATIN_SYMBOLS_MAP={"©":"(c)"};const GREEK_MAP={"α":"a","β":"b","γ":"g","δ":"d","ε":"e","ζ":"z","η":"h","θ":"8","ι":"i","κ":"k","λ":"l","μ":"m","ν":"n","ξ":"3","ο":"o","π":"p","ρ":"r","σ":"s","τ":"t","υ":"y","φ":"f","χ":"x","ψ":"ps","ω":"w","ά":"a","έ":"e","ί":"i","ό":"o","ύ":"y","ή":"h","ώ":"w","ς":"s","ϊ":"i","ΰ":"y","ϋ":"y","ΐ":"i","Α":"A","Β":"B","Γ":"G","Δ":"D","Ε":"E","Ζ":"Z","Η":"H","Θ":"8","Ι":"I","Κ":"K","Λ":"L","Μ":"M","Ν":"N","Ξ":"3","Ο":"O","Π":"P","Ρ":"R","Σ":"S","Τ":"T","Υ":"Y","Φ":"F","Χ":"X","Ψ":"PS","Ω":"W","Ά":"A","Έ":"E","Ί":"I","Ό":"O","Ύ":"Y","Ή":"H","Ώ":"W","Ϊ":"I","Ϋ":"Y"};const TURKISH_MAP={"ş":"s","Ş":"S","ı":"i","İ":"I","ç":"c","Ç":"C","ü":"u","Ü":"U","ö":"o","Ö":"O","ğ":"g","Ğ":"G"};const ROMANIAN_MAP={"ă":"a","î":"i","ș":"s","ț":"t","â":"a","Ă":"A","Î":"I","Ș":"S","Ț":"T","Â":"A"};const RUSSIAN_MAP={"а":"a","б":"b","в":"v","г":"g","д":"d","е":"e","ё":"yo","ж":"zh","з":"z","и":"i","й":"j","к":"k","л":"l","м":"m","н":"n","о":"o","п":"p","р":"r","с":"s","т":"t","у":"u","ф":"f","х":"h","ц":"c","ч":"ch","ш":"sh","щ":"sh","ъ":"","ы":"y","ь":"","э":"e","ю":"yu","я":"ya","А":"A","Б":"B","В":"V","Г":"G","Д":"D","Е":"E","Ё":"Yo","Ж":"Zh","З":"Z","И":"I","Й":"J","К":"K","Л":"L","М":"M","Н":"N","О":"O","П":"P","Р":"R","С":"S","Т":"T","У":"U","Ф":"F","Х":"H","Ц":"C","Ч":"Ch","Ш":"Sh","Щ":"Sh","Ъ":"","Ы":"Y","Ь":"","Э":"E","Ю":"Yu","Я":"Ya"};const UKRAINIAN_MAP={"Є":"Ye","І":"I","Ї":"Yi","Ґ":"G","є":"ye","і":"i","ї":"yi","ґ":"g"};const CZECH_MAP={"č":"c","ď":"d","ě":"e","ň":"n","ř":"r","š":"s","ť":"t","ů":"u","ž":"z","Č":"C","Ď":"D","Ě":"E","Ň":"N","Ř":"R","Š":"S","Ť":"T","Ů":"U","Ž":"Z"};const SLOVAK_MAP={"á":"a","ä":"a","č":"c","ď":"d","é":"e","í":"i","ľ":"l","ĺ":"l","ň":"n","ó":"o","ô":"o","ŕ":"r","š":"s","ť":"t","ú":"u","ý":"y","ž":"z","Á":"a","Ä":"A","Č":"C","Ď":"D","É":"E","Í":"I","Ľ":"L","Ĺ":"L","Ň":"N","Ó":"O","Ô":"O","Ŕ":"R","Š":"S","Ť":"T","Ú":"U","Ý":"Y","Ž":"Z"};const POLISH_MAP={"ą":"a","ć":"c","ę":"e","ł":"l","ń":"n","ó":"o","ś":"s","ź":"z","ż":"z","Ą":"A","Ć":"C","Ę":"E","Ł":"L","Ń":"N","Ó":"O","Ś":"S","Ź":"Z","Ż":"Z"};const LATVIAN_MAP={"ā":"a","č":"c","ē":"e","ģ":"g","ī":"i","ķ":"k","ļ":"l","ņ":"n","š":"s","ū":"u","ž":"z","Ā":"A","Č":"C","Ē":"E","Ģ":"G","Ī":"I","Ķ":"K","Ļ":"L","Ņ":"N","Š":"S","Ū":"U","Ž":"Z"};const ARABIC_MAP={"أ":"a","ب":"b","ت":"t","ث":"th","ج":"g","ح":"h","خ":"kh","د":"d","ذ":"th","ر":"r","ز":"z","س":"s","ش":"sh","ص":"s","ض":"d","ط":"t","ظ":"th","ع":"aa","غ":"gh","ف":"f","ق":"k","ك":"k","ل":"l","م":"m","ن":"n","ه":"h","و":"o","ي":"y"};const LITHUANIAN_MAP={"ą":"a","č":"c","ę":"e","ė":"e","į":"i","š":"s","ų":"u","ū":"u","ž":"z","Ą":"A","Č":"C","Ę":"E","Ė":"E","Į":"I","Š":"S","Ų":"U","Ū":"U","Ž":"Z"};const SERBIAN_MAP={"ђ":"dj","ј":"j","љ":"lj","њ":"nj","ћ":"c","џ":"dz","đ":"dj","Ђ":"Dj","Ј":"j","Љ":"Lj","Њ":"Nj","Ћ":"C","Џ":"Dz","Đ":"Dj"};const AZERBAIJANI_MAP={"ç":"c","ə":"e","ğ":"g","ı":"i","ö":"o","ş":"s","ü":"u","Ç":"C","Ə":"E","Ğ":"G","İ":"I","Ö":"O","Ş":"S","Ü":"U"};const GEORGIAN_MAP={"ა":"a","ბ":"b","გ":"g","დ":"d","ე":"e","ვ":"v","ზ":"z","თ":"t","ი":"i","კ":"k","ლ":"l","მ":"m","ნ":"n","ო":"o","პ":"p","ჟ":"j","რ":"r","ს":"s","ტ":"t","უ":"u","ფ":"f","ქ":"q","ღ":"g","ყ":"y","შ":"sh","ჩ":"ch","ც":"c","ძ":"dz","წ":"w","ჭ":"ch","ხ":"x","ჯ":"j","ჰ":"h"};const ALL_DOWNCODE_MAPS=[LATIN_MAP,LATIN_SYMBOLS_MAP,GREEK_MAP,TURKISH_MAP,ROMANIAN_MAP,RUSSIAN_MAP,UKRAINIAN_MAP,CZECH_MAP,SLOVAK_MAP,POLISH_MAP,LATVIAN_MAP,ARABIC_MAP,LITHUANIAN_MAP,SERBIAN_MAP,AZERBAIJANI_MAP,GEORGIAN_MAP];const Downcoder={Initialize:function(){if(Downcoder.map){return}Downcoder.map={};for(const lookup of ALL_DOWNCODE_MAPS){Object.assign(Downcoder.map,lookup)}Downcoder.regex=new RegExp(Object.keys(Downcoder.map).join("|"),"g")}};function downcode(slug){Downcoder.Initialize();return slug.replace(Downcoder.regex,function(m){return Downcoder.map[m]})}function URLify(s,num_chars,allowUnicode){if(!allowUnicode){s=downcode(s)}s=s.toLowerCase();if(allowUnicode){s=XRegExp.replace(s,XRegExp("[^-_\\p{L}\\p{N}\\s]","g"),"")}else{s=s.replace(/[^-\w\s]/g,"")}s=s.replace(/^\s+|\s+$/g,"");s=s.replace(/[-\s]+/g,"-");s=s.substring(0,num_chars);return s.replace(/-+$/g,"")}window.URLify=URLify} \ No newline at end of file +"use strict";{const LATIN_MAP={"À":"A","Á":"A","Â":"A","Ã":"A","Ä":"A","Å":"A","Æ":"AE","Ç":"C","È":"E","É":"E","Ê":"E","Ë":"E","Ì":"I","Í":"I","Î":"I","Ï":"I","Ð":"D","Ñ":"N","Ò":"O","Ó":"O","Ô":"O","Õ":"O","Ö":"O","Ő":"O","Ø":"O","Ù":"U","Ú":"U","Û":"U","Ü":"U","Ű":"U","Ý":"Y","Þ":"TH","Ÿ":"Y","ß":"ss","à":"a","á":"a","â":"a","ã":"a","ä":"a","å":"a","æ":"ae","ç":"c","è":"e","é":"e","ê":"e","ë":"e","ì":"i","í":"i","î":"i","ï":"i","ð":"d","ñ":"n","ò":"o","ó":"o","ô":"o","õ":"o","ö":"o","ő":"o","ø":"o","ù":"u","ú":"u","û":"u","ü":"u","ű":"u","ý":"y","þ":"th","ÿ":"y"};const LATIN_SYMBOLS_MAP={"©":"(c)"};const GREEK_MAP={"α":"a","β":"b","γ":"g","δ":"d","ε":"e","ζ":"z","η":"h","θ":"8","ι":"i","κ":"k","λ":"l","μ":"m","ν":"n","ξ":"3","ο":"o","π":"p","ρ":"r","σ":"s","τ":"t","υ":"y","φ":"f","χ":"x","ψ":"ps","ω":"w","ά":"a","έ":"e","ί":"i","ό":"o","ύ":"y","ή":"h","ώ":"w","ς":"s","ϊ":"i","ΰ":"y","ϋ":"y","ΐ":"i","Α":"A","Β":"B","Γ":"G","Δ":"D","Ε":"E","Ζ":"Z","Η":"H","Θ":"8","Ι":"I","Κ":"K","Λ":"L","Μ":"M","Ν":"N","Ξ":"3","Ο":"O","Π":"P","Ρ":"R","Σ":"S","Τ":"T","Υ":"Y","Φ":"F","Χ":"X","Ψ":"PS","Ω":"W","Ά":"A","Έ":"E","Ί":"I","Ό":"O","Ύ":"Y","Ή":"H","Ώ":"W","Ϊ":"I","Ϋ":"Y"};const TURKISH_MAP={"ş":"s","Ş":"S","ı":"i","İ":"I","ç":"c","Ç":"C","ü":"u","Ü":"U","ö":"o","Ö":"O","ğ":"g","Ğ":"G"};const ROMANIAN_MAP={"ă":"a","î":"i","ș":"s","ț":"t","â":"a","Ă":"A","Î":"I","Ș":"S","Ț":"T","Â":"A"};const RUSSIAN_MAP={"а":"a","б":"b","в":"v","г":"g","д":"d","е":"e","ё":"yo","ж":"zh","з":"z","и":"i","й":"j","к":"k","л":"l","м":"m","н":"n","о":"o","п":"p","р":"r","с":"s","т":"t","у":"u","ф":"f","х":"h","ц":"c","ч":"ch","ш":"sh","щ":"sh","ъ":"","ы":"y","ь":"","э":"e","ю":"yu","я":"ya","А":"A","Б":"B","В":"V","Г":"G","Д":"D","Е":"E","Ё":"Yo","Ж":"Zh","З":"Z","И":"I","Й":"J","К":"K","Л":"L","М":"M","Н":"N","О":"O","П":"P","Р":"R","С":"S","Т":"T","У":"U","Ф":"F","Х":"H","Ц":"C","Ч":"Ch","Ш":"Sh","Щ":"Sh","Ъ":"","Ы":"Y","Ь":"","Э":"E","Ю":"Yu","Я":"Ya"};const UKRAINIAN_MAP={"Є":"Ye","І":"I","Ї":"Yi","Ґ":"G","є":"ye","і":"i","ї":"yi","ґ":"g"};const CZECH_MAP={"č":"c","ď":"d","ě":"e","ň":"n","ř":"r","š":"s","ť":"t","ů":"u","ž":"z","Č":"C","Ď":"D","Ě":"E","Ň":"N","Ř":"R","Š":"S","Ť":"T","Ů":"U","Ž":"Z"};const SLOVAK_MAP={"á":"a","ä":"a","č":"c","ď":"d","é":"e","í":"i","ľ":"l","ĺ":"l","ň":"n","ó":"o","ô":"o","ŕ":"r","š":"s","ť":"t","ú":"u","ý":"y","ž":"z","Á":"a","Ä":"A","Č":"C","Ď":"D","É":"E","Í":"I","Ľ":"L","Ĺ":"L","Ň":"N","Ó":"O","Ô":"O","Ŕ":"R","Š":"S","Ť":"T","Ú":"U","Ý":"Y","Ž":"Z"};const POLISH_MAP={"ą":"a","ć":"c","ę":"e","ł":"l","ń":"n","ó":"o","ś":"s","ź":"z","ż":"z","Ą":"A","Ć":"C","Ę":"E","Ł":"L","Ń":"N","Ó":"O","Ś":"S","Ź":"Z","Ż":"Z"};const LATVIAN_MAP={"ā":"a","č":"c","ē":"e","ģ":"g","ī":"i","ķ":"k","ļ":"l","ņ":"n","š":"s","ū":"u","ž":"z","Ā":"A","Č":"C","Ē":"E","Ģ":"G","Ī":"I","Ķ":"K","Ļ":"L","Ņ":"N","Š":"S","Ū":"U","Ž":"Z"};const ARABIC_MAP={"أ":"a","ب":"b","ت":"t","ث":"th","ج":"g","ح":"h","خ":"kh","د":"d","ذ":"th","ر":"r","ز":"z","س":"s","ش":"sh","ص":"s","ض":"d","ط":"t","ظ":"th","ع":"aa","غ":"gh","ف":"f","ق":"k","ك":"k","ل":"l","م":"m","ن":"n","ه":"h","و":"o","ي":"y"};const LITHUANIAN_MAP={"ą":"a","č":"c","ę":"e","ė":"e","į":"i","š":"s","ų":"u","ū":"u","ž":"z","Ą":"A","Č":"C","Ę":"E","Ė":"E","Į":"I","Š":"S","Ų":"U","Ū":"U","Ž":"Z"};const SERBIAN_MAP={"ђ":"dj","ј":"j","љ":"lj","њ":"nj","ћ":"c","џ":"dz","đ":"dj","Ђ":"Dj","Ј":"j","Љ":"Lj","Њ":"Nj","Ћ":"C","Џ":"Dz","Đ":"Dj"};const AZERBAIJANI_MAP={"ç":"c","ə":"e","ğ":"g","ı":"i","ö":"o","ş":"s","ü":"u","Ç":"C","Ə":"E","Ğ":"G","İ":"I","Ö":"O","Ş":"S","Ü":"U"};const GEORGIAN_MAP={"ა":"a","ბ":"b","გ":"g","დ":"d","ე":"e","ვ":"v","ზ":"z","თ":"t","ი":"i","კ":"k","ლ":"l","მ":"m","ნ":"n","ო":"o","პ":"p","ჟ":"j","რ":"r","ს":"s","ტ":"t","უ":"u","ფ":"f","ქ":"q","ღ":"g","ყ":"y","შ":"sh","ჩ":"ch","ც":"c","ძ":"dz","წ":"w","ჭ":"ch","ხ":"x","ჯ":"j","ჰ":"h"};const ALL_DOWNCODE_MAPS=[LATIN_MAP,LATIN_SYMBOLS_MAP,GREEK_MAP,TURKISH_MAP,ROMANIAN_MAP,RUSSIAN_MAP,UKRAINIAN_MAP,CZECH_MAP,SLOVAK_MAP,POLISH_MAP,LATVIAN_MAP,ARABIC_MAP,LITHUANIAN_MAP,SERBIAN_MAP,AZERBAIJANI_MAP,GEORGIAN_MAP];const Downcoder={Initialize:function(){if(Downcoder.map){return}Downcoder.map={};for(const lookup of ALL_DOWNCODE_MAPS){Object.assign(Downcoder.map,lookup)}Downcoder.regex=new RegExp(Object.keys(Downcoder.map).join("|"),"g")}};function downcode(slug){Downcoder.Initialize();return slug.replace(Downcoder.regex,function(m){return Downcoder.map[m]})}function URLify(s,num_chars,allowUnicode){if(!allowUnicode){s=downcode(s)}s=s.toLowerCase();if(allowUnicode){s=XRegExp.replace(s,XRegExp("[^-_\\p{L}\\p{N}\\s]","g"),"")}else{s=s.replace(/[^-\w\s]/g,"")}s=s.replace(/^\s+|\s+$/g,"");s=s.replace(/[-\s]+/g,"-");s=s.substring(0,num_chars);return s.replace(/-+$/g,"")}window.URLify=URLify} diff --git a/src/country_workspace/web/static/workspace/js/urlify.min.min.js b/src/country_workspace/web/static/workspace/js/urlify.min.min.js new file mode 100644 index 0000000..019a74d --- /dev/null +++ b/src/country_workspace/web/static/workspace/js/urlify.min.min.js @@ -0,0 +1 @@ +"use strict";{const LATIN_MAP={"À":"A","Á":"A","Â":"A","Ã":"A","Ä":"A","Å":"A","Æ":"AE","Ç":"C","È":"E","É":"E","Ê":"E","Ë":"E","Ì":"I","Í":"I","Î":"I","Ï":"I","Ð":"D","Ñ":"N","Ò":"O","Ó":"O","Ô":"O","Õ":"O","Ö":"O","Ő":"O","Ø":"O","Ù":"U","Ú":"U","Û":"U","Ü":"U","Ű":"U","Ý":"Y","Þ":"TH","Ÿ":"Y","ß":"ss","à":"a","á":"a","â":"a","ã":"a","ä":"a","å":"a","æ":"ae","ç":"c","è":"e","é":"e","ê":"e","ë":"e","ì":"i","í":"i","î":"i","ï":"i","ð":"d","ñ":"n","ò":"o","ó":"o","ô":"o","õ":"o","ö":"o","ő":"o","ø":"o","ù":"u","ú":"u","û":"u","ü":"u","ű":"u","ý":"y","þ":"th","ÿ":"y"};const LATIN_SYMBOLS_MAP={"©":"(c)"};const GREEK_MAP={"α":"a","β":"b","γ":"g","δ":"d","ε":"e","ζ":"z","η":"h","θ":"8","ι":"i","κ":"k","λ":"l","μ":"m","ν":"n","ξ":"3","ο":"o","π":"p","ρ":"r","σ":"s","τ":"t","υ":"y","φ":"f","χ":"x","ψ":"ps","ω":"w","ά":"a","έ":"e","ί":"i","ό":"o","ύ":"y","ή":"h","ώ":"w","ς":"s","ϊ":"i","ΰ":"y","ϋ":"y","ΐ":"i","Α":"A","Β":"B","Γ":"G","Δ":"D","Ε":"E","Ζ":"Z","Η":"H","Θ":"8","Ι":"I","Κ":"K","Λ":"L","Μ":"M","Ν":"N","Ξ":"3","Ο":"O","Π":"P","Ρ":"R","Σ":"S","Τ":"T","Υ":"Y","Φ":"F","Χ":"X","Ψ":"PS","Ω":"W","Ά":"A","Έ":"E","Ί":"I","Ό":"O","Ύ":"Y","Ή":"H","Ώ":"W","Ϊ":"I","Ϋ":"Y"};const TURKISH_MAP={"ş":"s","Ş":"S","ı":"i","İ":"I","ç":"c","Ç":"C","ü":"u","Ü":"U","ö":"o","Ö":"O","ğ":"g","Ğ":"G"};const ROMANIAN_MAP={"ă":"a","î":"i","ș":"s","ț":"t","â":"a","Ă":"A","Î":"I","Ș":"S","Ț":"T","Â":"A"};const RUSSIAN_MAP={"а":"a","б":"b","в":"v","г":"g","д":"d","е":"e","ё":"yo","ж":"zh","з":"z","и":"i","й":"j","к":"k","л":"l","м":"m","н":"n","о":"o","п":"p","р":"r","с":"s","т":"t","у":"u","ф":"f","х":"h","ц":"c","ч":"ch","ш":"sh","щ":"sh","ъ":"","ы":"y","ь":"","э":"e","ю":"yu","я":"ya","А":"A","Б":"B","В":"V","Г":"G","Д":"D","Е":"E","Ё":"Yo","Ж":"Zh","З":"Z","И":"I","Й":"J","К":"K","Л":"L","М":"M","Н":"N","О":"O","П":"P","Р":"R","С":"S","Т":"T","У":"U","Ф":"F","Х":"H","Ц":"C","Ч":"Ch","Ш":"Sh","Щ":"Sh","Ъ":"","Ы":"Y","Ь":"","Э":"E","Ю":"Yu","Я":"Ya"};const UKRAINIAN_MAP={"Є":"Ye","І":"I","Ї":"Yi","Ґ":"G","є":"ye","і":"i","ї":"yi","ґ":"g"};const CZECH_MAP={"č":"c","ď":"d","ě":"e","ň":"n","ř":"r","š":"s","ť":"t","ů":"u","ž":"z","Č":"C","Ď":"D","Ě":"E","Ň":"N","Ř":"R","Š":"S","Ť":"T","Ů":"U","Ž":"Z"};const SLOVAK_MAP={"á":"a","ä":"a","č":"c","ď":"d","é":"e","í":"i","ľ":"l","ĺ":"l","ň":"n","ó":"o","ô":"o","ŕ":"r","š":"s","ť":"t","ú":"u","ý":"y","ž":"z","Á":"a","Ä":"A","Č":"C","Ď":"D","É":"E","Í":"I","Ľ":"L","Ĺ":"L","Ň":"N","Ó":"O","Ô":"O","Ŕ":"R","Š":"S","Ť":"T","Ú":"U","Ý":"Y","Ž":"Z"};const POLISH_MAP={"ą":"a","ć":"c","ę":"e","ł":"l","ń":"n","ó":"o","ś":"s","ź":"z","ż":"z","Ą":"A","Ć":"C","Ę":"E","Ł":"L","Ń":"N","Ó":"O","Ś":"S","Ź":"Z","Ż":"Z"};const LATVIAN_MAP={"ā":"a","č":"c","ē":"e","ģ":"g","ī":"i","ķ":"k","ļ":"l","ņ":"n","š":"s","ū":"u","ž":"z","Ā":"A","Č":"C","Ē":"E","Ģ":"G","Ī":"I","Ķ":"K","Ļ":"L","Ņ":"N","Š":"S","Ū":"U","Ž":"Z"};const ARABIC_MAP={"أ":"a","ب":"b","ت":"t","ث":"th","ج":"g","ح":"h","خ":"kh","د":"d","ذ":"th","ر":"r","ز":"z","س":"s","ش":"sh","ص":"s","ض":"d","ط":"t","ظ":"th","ع":"aa","غ":"gh","ف":"f","ق":"k","ك":"k","ل":"l","م":"m","ن":"n","ه":"h","و":"o","ي":"y"};const LITHUANIAN_MAP={"ą":"a","č":"c","ę":"e","ė":"e","į":"i","š":"s","ų":"u","ū":"u","ž":"z","Ą":"A","Č":"C","Ę":"E","Ė":"E","Į":"I","Š":"S","Ų":"U","Ū":"U","Ž":"Z"};const SERBIAN_MAP={"ђ":"dj","ј":"j","љ":"lj","њ":"nj","ћ":"c","џ":"dz","đ":"dj","Ђ":"Dj","Ј":"j","Љ":"Lj","Њ":"Nj","Ћ":"C","Џ":"Dz","Đ":"Dj"};const AZERBAIJANI_MAP={"ç":"c","ə":"e","ğ":"g","ı":"i","ö":"o","ş":"s","ü":"u","Ç":"C","Ə":"E","Ğ":"G","İ":"I","Ö":"O","Ş":"S","Ü":"U"};const GEORGIAN_MAP={"ა":"a","ბ":"b","გ":"g","დ":"d","ე":"e","ვ":"v","ზ":"z","თ":"t","ი":"i","კ":"k","ლ":"l","მ":"m","ნ":"n","ო":"o","პ":"p","ჟ":"j","რ":"r","ს":"s","ტ":"t","უ":"u","ფ":"f","ქ":"q","ღ":"g","ყ":"y","შ":"sh","ჩ":"ch","ც":"c","ძ":"dz","წ":"w","ჭ":"ch","ხ":"x","ჯ":"j","ჰ":"h"};const ALL_DOWNCODE_MAPS=[LATIN_MAP,LATIN_SYMBOLS_MAP,GREEK_MAP,TURKISH_MAP,ROMANIAN_MAP,RUSSIAN_MAP,UKRAINIAN_MAP,CZECH_MAP,SLOVAK_MAP,POLISH_MAP,LATVIAN_MAP,ARABIC_MAP,LITHUANIAN_MAP,SERBIAN_MAP,AZERBAIJANI_MAP,GEORGIAN_MAP];const Downcoder={Initialize:function(){if(Downcoder.map){return}Downcoder.map={};for(const lookup of ALL_DOWNCODE_MAPS){Object.assign(Downcoder.map,lookup)}Downcoder.regex=new RegExp(Object.keys(Downcoder.map).join("|"),"g")}};function downcode(slug){Downcoder.Initialize();return slug.replace(Downcoder.regex,function(m){return Downcoder.map[m]})}function URLify(s,num_chars,allowUnicode){if(!allowUnicode){s=downcode(s)}s=s.toLowerCase();if(allowUnicode){s=XRegExp.replace(s,XRegExp("[^-_\\p{L}\\p{N}\\s]","g"),"")}else{s=s.replace(/[^-\w\s]/g,"")}s=s.replace(/^\s+|\s+$/g,"");s=s.replace(/[-\s]+/g,"-");s=s.substring(0,num_chars);return s.replace(/-+$/g,"")}window.URLify=URLify} diff --git a/src/country_workspace/web/static/workspace/js/vendor/jquery/jquery.min.js b/src/country_workspace/web/static/workspace/js/vendor/jquery/jquery.min.js index 38599bf..57c1bf7 100644 --- a/src/country_workspace/web/static/workspace/js/vendor/jquery/jquery.min.js +++ b/src/country_workspace/web/static/workspace/js/vendor/jquery/jquery.min.js @@ -1 +1 @@ -(function(global,factory){"use strict";if(typeof module==="object"&&typeof module.exports==="object"){module.exports=global.document?factory(global,true):function(w){if(!w.document){throw new Error("jQuery requires a window with a document")}return factory(w)}}else{factory(global)}})(typeof window!=="undefined"?window:this,function(window,noGlobal){"use strict";var arr=[];var getProto=Object.getPrototypeOf;var slice=arr.slice;var flat=arr.flat?function(array){return arr.flat.call(array)}:function(array){return arr.concat.apply([],array)};var push=arr.push;var indexOf=arr.indexOf;var class2type={};var toString=class2type.toString;var hasOwn=class2type.hasOwnProperty;var fnToString=hasOwn.toString;var ObjectFunctionString=fnToString.call(Object);var support={};var isFunction=function isFunction(obj){return typeof obj==="function"&&typeof obj.nodeType!=="number"&&typeof obj.item!=="function"};var isWindow=function isWindow(obj){return obj!=null&&obj===obj.window};var document=window.document;var preservedScriptAttributes={type:true,src:true,nonce:true,noModule:true};function DOMEval(code,node,doc){doc=doc||document;var i,val,script=doc.createElement("script");script.text=code;if(node){for(i in preservedScriptAttributes){val=node[i]||node.getAttribute&&node.getAttribute(i);if(val){script.setAttribute(i,val)}}}doc.head.appendChild(script).parentNode.removeChild(script)}function toType(obj){if(obj==null){return obj+""}return typeof obj==="object"||typeof obj==="function"?class2type[toString.call(obj)]||"object":typeof obj}var version="3.7.1",rhtmlSuffix=/HTML$/i,jQuery=function(selector,context){return new jQuery.fn.init(selector,context)};jQuery.fn=jQuery.prototype={jquery:version,constructor:jQuery,length:0,toArray:function(){return slice.call(this)},get:function(num){if(num==null){return slice.call(this)}return num<0?this[num+this.length]:this[num]},pushStack:function(elems){var ret=jQuery.merge(this.constructor(),elems);ret.prevObject=this;return ret},each:function(callback){return jQuery.each(this,callback)},map:function(callback){return this.pushStack(jQuery.map(this,function(elem,i){return callback.call(elem,i,elem)}))},slice:function(){return this.pushStack(slice.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},even:function(){return this.pushStack(jQuery.grep(this,function(_elem,i){return(i+1)%2}))},odd:function(){return this.pushStack(jQuery.grep(this,function(_elem,i){return i%2}))},eq:function(i){var len=this.length,j=+i+(i<0?len:0);return this.pushStack(j>=0&&j0&&length-1 in obj}function nodeName(elem,name){return elem.nodeName&&elem.nodeName.toLowerCase()===name.toLowerCase()}var pop=arr.pop;var sort=arr.sort;var splice=arr.splice;var whitespace="[\\x20\\t\\r\\n\\f]";var rtrimCSS=new RegExp("^"+whitespace+"+|((?:^|[^\\\\])(?:\\\\.)*)"+whitespace+"+$","g");jQuery.contains=function(a,b){var bup=b&&b.parentNode;return a===bup||!!(bup&&bup.nodeType===1&&(a.contains?a.contains(bup):a.compareDocumentPosition&&a.compareDocumentPosition(bup)&16))};var rcssescape=/([\0-\x1f\x7f]|^-?\d)|^-$|[^\x80-\uFFFF\w-]/g;function fcssescape(ch,asCodePoint){if(asCodePoint){if(ch==="\0"){return"�"}return ch.slice(0,-1)+"\\"+ch.charCodeAt(ch.length-1).toString(16)+" "}return"\\"+ch}jQuery.escapeSelector=function(sel){return(sel+"").replace(rcssescape,fcssescape)};var preferredDoc=document,pushNative=push;(function(){var i,Expr,outermostContext,sortInput,hasDuplicate,push=pushNative,document,documentElement,documentIsHTML,rbuggyQSA,matches,expando=jQuery.expando,dirruns=0,done=0,classCache=createCache(),tokenCache=createCache(),compilerCache=createCache(),nonnativeSelectorCache=createCache(),sortOrder=function(a,b){if(a===b){hasDuplicate=true}return 0},booleans="checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|"+"loop|multiple|open|readonly|required|scoped",identifier="(?:\\\\[\\da-fA-F]{1,6}"+whitespace+"?|\\\\[^\\r\\n\\f]|[\\w-]|[^\0-\\x7f])+",attributes="\\["+whitespace+"*("+identifier+")(?:"+whitespace+"*([*^$|!~]?=)"+whitespace+"*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|("+identifier+"))|)"+whitespace+"*\\]",pseudos=":("+identifier+")(?:\\(("+"('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|"+"((?:\\\\.|[^\\\\()[\\]]|"+attributes+")*)|"+".*"+")\\)|)",rwhitespace=new RegExp(whitespace+"+","g"),rcomma=new RegExp("^"+whitespace+"*,"+whitespace+"*"),rleadingCombinator=new RegExp("^"+whitespace+"*([>+~]|"+whitespace+")"+whitespace+"*"),rdescend=new RegExp(whitespace+"|>"),rpseudo=new RegExp(pseudos),ridentifier=new RegExp("^"+identifier+"$"),matchExpr={ID:new RegExp("^#("+identifier+")"),CLASS:new RegExp("^\\.("+identifier+")"),TAG:new RegExp("^("+identifier+"|[*])"),ATTR:new RegExp("^"+attributes),PSEUDO:new RegExp("^"+pseudos),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+whitespace+"*(even|odd|(([+-]|)(\\d*)n|)"+whitespace+"*(?:([+-]|)"+whitespace+"*(\\d+)|))"+whitespace+"*\\)|)","i"),bool:new RegExp("^(?:"+booleans+")$","i"),needsContext:new RegExp("^"+whitespace+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+whitespace+"*((?:-\\d)?\\d*)"+whitespace+"*\\)|)(?=[^-]|$)","i")},rinputs=/^(?:input|select|textarea|button)$/i,rheader=/^h\d$/i,rquickExpr=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,rsibling=/[+~]/,runescape=new RegExp("\\\\[\\da-fA-F]{1,6}"+whitespace+"?|\\\\([^\\r\\n\\f])","g"),funescape=function(escape,nonHex){var high="0x"+escape.slice(1)-65536;if(nonHex){return nonHex}return high<0?String.fromCharCode(high+65536):String.fromCharCode(high>>10|55296,high&1023|56320)},unloadHandler=function(){setDocument()},inDisabledFieldset=addCombinator(function(elem){return elem.disabled===true&&nodeName(elem,"fieldset")},{dir:"parentNode",next:"legend"});function safeActiveElement(){try{return document.activeElement}catch(err){}}try{push.apply(arr=slice.call(preferredDoc.childNodes),preferredDoc.childNodes);arr[preferredDoc.childNodes.length].nodeType}catch(e){push={apply:function(target,els){pushNative.apply(target,slice.call(els))},call:function(target){pushNative.apply(target,slice.call(arguments,1))}}}function find(selector,context,results,seed){var m,i,elem,nid,match,groups,newSelector,newContext=context&&context.ownerDocument,nodeType=context?context.nodeType:9;results=results||[];if(typeof selector!=="string"||!selector||nodeType!==1&&nodeType!==9&&nodeType!==11){return results}if(!seed){setDocument(context);context=context||document;if(documentIsHTML){if(nodeType!==11&&(match=rquickExpr.exec(selector))){if(m=match[1]){if(nodeType===9){if(elem=context.getElementById(m)){if(elem.id===m){push.call(results,elem);return results}}else{return results}}else{if(newContext&&(elem=newContext.getElementById(m))&&find.contains(context,elem)&&elem.id===m){push.call(results,elem);return results}}}else if(match[2]){push.apply(results,context.getElementsByTagName(selector));return results}else if((m=match[3])&&context.getElementsByClassName){push.apply(results,context.getElementsByClassName(m));return results}}if(!nonnativeSelectorCache[selector+" "]&&(!rbuggyQSA||!rbuggyQSA.test(selector))){newSelector=selector;newContext=context;if(nodeType===1&&(rdescend.test(selector)||rleadingCombinator.test(selector))){newContext=rsibling.test(selector)&&testContext(context.parentNode)||context;if(newContext!=context||!support.scope){if(nid=context.getAttribute("id")){nid=jQuery.escapeSelector(nid)}else{context.setAttribute("id",nid=expando)}}groups=tokenize(selector);i=groups.length;while(i--){groups[i]=(nid?"#"+nid:":scope")+" "+toSelector(groups[i])}newSelector=groups.join(",")}try{push.apply(results,newContext.querySelectorAll(newSelector));return results}catch(qsaError){nonnativeSelectorCache(selector,true)}finally{if(nid===expando){context.removeAttribute("id")}}}}}return select(selector.replace(rtrimCSS,"$1"),context,results,seed)}function createCache(){var keys=[];function cache(key,value){if(keys.push(key+" ")>Expr.cacheLength){delete cache[keys.shift()]}return cache[key+" "]=value}return cache}function markFunction(fn){fn[expando]=true;return fn}function assert(fn){var el=document.createElement("fieldset");try{return!!fn(el)}catch(e){return false}finally{if(el.parentNode){el.parentNode.removeChild(el)}el=null}}function createInputPseudo(type){return function(elem){return nodeName(elem,"input")&&elem.type===type}}function createButtonPseudo(type){return function(elem){return(nodeName(elem,"input")||nodeName(elem,"button"))&&elem.type===type}}function createDisabledPseudo(disabled){return function(elem){if("form"in elem){if(elem.parentNode&&elem.disabled===false){if("label"in elem){if("label"in elem.parentNode){return elem.parentNode.disabled===disabled}else{return elem.disabled===disabled}}return elem.isDisabled===disabled||elem.isDisabled!==!disabled&&inDisabledFieldset(elem)===disabled}return elem.disabled===disabled}else if("label"in elem){return elem.disabled===disabled}return false}}function createPositionalPseudo(fn){return markFunction(function(argument){argument=+argument;return markFunction(function(seed,matches){var j,matchIndexes=fn([],seed.length,argument),i=matchIndexes.length;while(i--){if(seed[j=matchIndexes[i]]){seed[j]=!(matches[j]=seed[j])}}})})}function testContext(context){return context&&typeof context.getElementsByTagName!=="undefined"&&context}function setDocument(node){var subWindow,doc=node?node.ownerDocument||node:preferredDoc;if(doc==document||doc.nodeType!==9||!doc.documentElement){return document}document=doc;documentElement=document.documentElement;documentIsHTML=!jQuery.isXMLDoc(document);matches=documentElement.matches||documentElement.webkitMatchesSelector||documentElement.msMatchesSelector;if(documentElement.msMatchesSelector&&preferredDoc!=document&&(subWindow=document.defaultView)&&subWindow.top!==subWindow){subWindow.addEventListener("unload",unloadHandler)}support.getById=assert(function(el){documentElement.appendChild(el).id=jQuery.expando;return!document.getElementsByName||!document.getElementsByName(jQuery.expando).length});support.disconnectedMatch=assert(function(el){return matches.call(el,"*")});support.scope=assert(function(){return document.querySelectorAll(":scope")});support.cssHas=assert(function(){try{document.querySelector(":has(*,:jqfake)");return false}catch(e){return true}});if(support.getById){Expr.filter.ID=function(id){var attrId=id.replace(runescape,funescape);return function(elem){return elem.getAttribute("id")===attrId}};Expr.find.ID=function(id,context){if(typeof context.getElementById!=="undefined"&&documentIsHTML){var elem=context.getElementById(id);return elem?[elem]:[]}}}else{Expr.filter.ID=function(id){var attrId=id.replace(runescape,funescape);return function(elem){var node=typeof elem.getAttributeNode!=="undefined"&&elem.getAttributeNode("id");return node&&node.value===attrId}};Expr.find.ID=function(id,context){if(typeof context.getElementById!=="undefined"&&documentIsHTML){var node,i,elems,elem=context.getElementById(id);if(elem){node=elem.getAttributeNode("id");if(node&&node.value===id){return[elem]}elems=context.getElementsByName(id);i=0;while(elem=elems[i++]){node=elem.getAttributeNode("id");if(node&&node.value===id){return[elem]}}}return[]}}}Expr.find.TAG=function(tag,context){if(typeof context.getElementsByTagName!=="undefined"){return context.getElementsByTagName(tag)}else{return context.querySelectorAll(tag)}};Expr.find.CLASS=function(className,context){if(typeof context.getElementsByClassName!=="undefined"&&documentIsHTML){return context.getElementsByClassName(className)}};rbuggyQSA=[];assert(function(el){var input;documentElement.appendChild(el).innerHTML=""+"";if(!el.querySelectorAll("[selected]").length){rbuggyQSA.push("\\["+whitespace+"*(?:value|"+booleans+")")}if(!el.querySelectorAll("[id~="+expando+"-]").length){rbuggyQSA.push("~=")}if(!el.querySelectorAll("a#"+expando+"+*").length){rbuggyQSA.push(".#.+[+~]")}if(!el.querySelectorAll(":checked").length){rbuggyQSA.push(":checked")}input=document.createElement("input");input.setAttribute("type","hidden");el.appendChild(input).setAttribute("name","D");documentElement.appendChild(el).disabled=true;if(el.querySelectorAll(":disabled").length!==2){rbuggyQSA.push(":enabled",":disabled")}input=document.createElement("input");input.setAttribute("name","");el.appendChild(input);if(!el.querySelectorAll("[name='']").length){rbuggyQSA.push("\\["+whitespace+"*name"+whitespace+"*="+whitespace+"*(?:''|\"\")")}});if(!support.cssHas){rbuggyQSA.push(":has")}rbuggyQSA=rbuggyQSA.length&&new RegExp(rbuggyQSA.join("|"));sortOrder=function(a,b){if(a===b){hasDuplicate=true;return 0}var compare=!a.compareDocumentPosition-!b.compareDocumentPosition;if(compare){return compare}compare=(a.ownerDocument||a)==(b.ownerDocument||b)?a.compareDocumentPosition(b):1;if(compare&1||!support.sortDetached&&b.compareDocumentPosition(a)===compare){if(a===document||a.ownerDocument==preferredDoc&&find.contains(preferredDoc,a)){return-1}if(b===document||b.ownerDocument==preferredDoc&&find.contains(preferredDoc,b)){return 1}return sortInput?indexOf.call(sortInput,a)-indexOf.call(sortInput,b):0}return compare&4?-1:1};return document}find.matches=function(expr,elements){return find(expr,null,null,elements)};find.matchesSelector=function(elem,expr){setDocument(elem);if(documentIsHTML&&!nonnativeSelectorCache[expr+" "]&&(!rbuggyQSA||!rbuggyQSA.test(expr))){try{var ret=matches.call(elem,expr);if(ret||support.disconnectedMatch||elem.document&&elem.document.nodeType!==11){return ret}}catch(e){nonnativeSelectorCache(expr,true)}}return find(expr,document,null,[elem]).length>0};find.contains=function(context,elem){if((context.ownerDocument||context)!=document){setDocument(context)}return jQuery.contains(context,elem)};find.attr=function(elem,name){if((elem.ownerDocument||elem)!=document){setDocument(elem)}var fn=Expr.attrHandle[name.toLowerCase()],val=fn&&hasOwn.call(Expr.attrHandle,name.toLowerCase())?fn(elem,name,!documentIsHTML):undefined;if(val!==undefined){return val}return elem.getAttribute(name)};find.error=function(msg){throw new Error("Syntax error, unrecognized expression: "+msg)};jQuery.uniqueSort=function(results){var elem,duplicates=[],j=0,i=0;hasDuplicate=!support.sortStable;sortInput=!support.sortStable&&slice.call(results,0);sort.call(results,sortOrder);if(hasDuplicate){while(elem=results[i++]){if(elem===results[i]){j=duplicates.push(i)}}while(j--){splice.call(results,duplicates[j],1)}}sortInput=null;return results};jQuery.fn.uniqueSort=function(){return this.pushStack(jQuery.uniqueSort(slice.apply(this)))};Expr=jQuery.expr={cacheLength:50,createPseudo:markFunction,match:matchExpr,attrHandle:{},find:{},relative:{">":{dir:"parentNode",first:true}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:true},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(match){match[1]=match[1].replace(runescape,funescape);match[3]=(match[3]||match[4]||match[5]||"").replace(runescape,funescape);if(match[2]==="~="){match[3]=" "+match[3]+" "}return match.slice(0,4)},CHILD:function(match){match[1]=match[1].toLowerCase();if(match[1].slice(0,3)==="nth"){if(!match[3]){find.error(match[0])}match[4]=+(match[4]?match[5]+(match[6]||1):2*(match[3]==="even"||match[3]==="odd"));match[5]=+(match[7]+match[8]||match[3]==="odd")}else if(match[3]){find.error(match[0])}return match},PSEUDO:function(match){var excess,unquoted=!match[6]&&match[2];if(matchExpr.CHILD.test(match[0])){return null}if(match[3]){match[2]=match[4]||match[5]||""}else if(unquoted&&rpseudo.test(unquoted)&&(excess=tokenize(unquoted,true))&&(excess=unquoted.indexOf(")",unquoted.length-excess)-unquoted.length)){match[0]=match[0].slice(0,excess);match[2]=unquoted.slice(0,excess)}return match.slice(0,3)}},filter:{TAG:function(nodeNameSelector){var expectedNodeName=nodeNameSelector.replace(runescape,funescape).toLowerCase();return nodeNameSelector==="*"?function(){return true}:function(elem){return nodeName(elem,expectedNodeName)}},CLASS:function(className){var pattern=classCache[className+" "];return pattern||(pattern=new RegExp("(^|"+whitespace+")"+className+"("+whitespace+"|$)"))&&classCache(className,function(elem){return pattern.test(typeof elem.className==="string"&&elem.className||typeof elem.getAttribute!=="undefined"&&elem.getAttribute("class")||"")})},ATTR:function(name,operator,check){return function(elem){var result=find.attr(elem,name);if(result==null){return operator==="!="}if(!operator){return true}result+="";if(operator==="="){return result===check}if(operator==="!="){return result!==check}if(operator==="^="){return check&&result.indexOf(check)===0}if(operator==="*="){return check&&result.indexOf(check)>-1}if(operator==="$="){return check&&result.slice(-check.length)===check}if(operator==="~="){return(" "+result.replace(rwhitespace," ")+" ").indexOf(check)>-1}if(operator==="|="){return result===check||result.slice(0,check.length+1)===check+"-"}return false}},CHILD:function(type,what,_argument,first,last){var simple=type.slice(0,3)!=="nth",forward=type.slice(-4)!=="last",ofType=what==="of-type";return first===1&&last===0?function(elem){return!!elem.parentNode}:function(elem,_context,xml){var cache,outerCache,node,nodeIndex,start,dir=simple!==forward?"nextSibling":"previousSibling",parent=elem.parentNode,name=ofType&&elem.nodeName.toLowerCase(),useCache=!xml&&!ofType,diff=false;if(parent){if(simple){while(dir){node=elem;while(node=node[dir]){if(ofType?nodeName(node,name):node.nodeType===1){return false}}start=dir=type==="only"&&!start&&"nextSibling"}return true}start=[forward?parent.firstChild:parent.lastChild];if(forward&&useCache){outerCache=parent[expando]||(parent[expando]={});cache=outerCache[type]||[];nodeIndex=cache[0]===dirruns&&cache[1];diff=nodeIndex&&cache[2];node=nodeIndex&&parent.childNodes[nodeIndex];while(node=++nodeIndex&&node&&node[dir]||(diff=nodeIndex=0)||start.pop()){if(node.nodeType===1&&++diff&&node===elem){outerCache[type]=[dirruns,nodeIndex,diff];break}}}else{if(useCache){outerCache=elem[expando]||(elem[expando]={});cache=outerCache[type]||[];nodeIndex=cache[0]===dirruns&&cache[1];diff=nodeIndex}if(diff===false){while(node=++nodeIndex&&node&&node[dir]||(diff=nodeIndex=0)||start.pop()){if((ofType?nodeName(node,name):node.nodeType===1)&&++diff){if(useCache){outerCache=node[expando]||(node[expando]={});outerCache[type]=[dirruns,diff]}if(node===elem){break}}}}}diff-=last;return diff===first||diff%first===0&&diff/first>=0}}},PSEUDO:function(pseudo,argument){var args,fn=Expr.pseudos[pseudo]||Expr.setFilters[pseudo.toLowerCase()]||find.error("unsupported pseudo: "+pseudo);if(fn[expando]){return fn(argument)}if(fn.length>1){args=[pseudo,pseudo,"",argument];return Expr.setFilters.hasOwnProperty(pseudo.toLowerCase())?markFunction(function(seed,matches){var idx,matched=fn(seed,argument),i=matched.length;while(i--){idx=indexOf.call(seed,matched[i]);seed[idx]=!(matches[idx]=matched[i])}}):function(elem){return fn(elem,0,args)}}return fn}},pseudos:{not:markFunction(function(selector){var input=[],results=[],matcher=compile(selector.replace(rtrimCSS,"$1"));return matcher[expando]?markFunction(function(seed,matches,_context,xml){var elem,unmatched=matcher(seed,null,xml,[]),i=seed.length;while(i--){if(elem=unmatched[i]){seed[i]=!(matches[i]=elem)}}}):function(elem,_context,xml){input[0]=elem;matcher(input,null,xml,results);input[0]=null;return!results.pop()}}),has:markFunction(function(selector){return function(elem){return find(selector,elem).length>0}}),contains:markFunction(function(text){text=text.replace(runescape,funescape);return function(elem){return(elem.textContent||jQuery.text(elem)).indexOf(text)>-1}}),lang:markFunction(function(lang){if(!ridentifier.test(lang||"")){find.error("unsupported lang: "+lang)}lang=lang.replace(runescape,funescape).toLowerCase();return function(elem){var elemLang;do{if(elemLang=documentIsHTML?elem.lang:elem.getAttribute("xml:lang")||elem.getAttribute("lang")){elemLang=elemLang.toLowerCase();return elemLang===lang||elemLang.indexOf(lang+"-")===0}}while((elem=elem.parentNode)&&elem.nodeType===1);return false}}),target:function(elem){var hash=window.location&&window.location.hash;return hash&&hash.slice(1)===elem.id},root:function(elem){return elem===documentElement},focus:function(elem){return elem===safeActiveElement()&&document.hasFocus()&&!!(elem.type||elem.href||~elem.tabIndex)},enabled:createDisabledPseudo(false),disabled:createDisabledPseudo(true),checked:function(elem){return nodeName(elem,"input")&&!!elem.checked||nodeName(elem,"option")&&!!elem.selected},selected:function(elem){if(elem.parentNode){elem.parentNode.selectedIndex}return elem.selected===true},empty:function(elem){for(elem=elem.firstChild;elem;elem=elem.nextSibling){if(elem.nodeType<6){return false}}return true},parent:function(elem){return!Expr.pseudos.empty(elem)},header:function(elem){return rheader.test(elem.nodeName)},input:function(elem){return rinputs.test(elem.nodeName)},button:function(elem){return nodeName(elem,"input")&&elem.type==="button"||nodeName(elem,"button")},text:function(elem){var attr;return nodeName(elem,"input")&&elem.type==="text"&&((attr=elem.getAttribute("type"))==null||attr.toLowerCase()==="text")},first:createPositionalPseudo(function(){return[0]}),last:createPositionalPseudo(function(_matchIndexes,length){return[length-1]}),eq:createPositionalPseudo(function(_matchIndexes,length,argument){return[argument<0?argument+length:argument]}),even:createPositionalPseudo(function(matchIndexes,length){var i=0;for(;ilength){i=length}else{i=argument}for(;--i>=0;){matchIndexes.push(i)}return matchIndexes}),gt:createPositionalPseudo(function(matchIndexes,length,argument){var i=argument<0?argument+length:argument;for(;++i1?function(elem,context,xml){var i=matchers.length;while(i--){if(!matchers[i](elem,context,xml)){return false}}return true}:matchers[0]}function multipleContexts(selector,contexts,results){var i=0,len=contexts.length;for(;i-1){seed[temp]=!(results[temp]=elem)}}}}else{matcherOut=condense(matcherOut===results?matcherOut.splice(preexisting,matcherOut.length):matcherOut);if(postFinder){postFinder(null,results,matcherOut,xml)}else{push.apply(results,matcherOut)}}})}function matcherFromTokens(tokens){var checkContext,matcher,j,len=tokens.length,leadingRelative=Expr.relative[tokens[0].type],implicitRelative=leadingRelative||Expr.relative[" "],i=leadingRelative?1:0,matchContext=addCombinator(function(elem){return elem===checkContext},implicitRelative,true),matchAnyContext=addCombinator(function(elem){return indexOf.call(checkContext,elem)>-1},implicitRelative,true),matchers=[function(elem,context,xml){var ret=!leadingRelative&&(xml||context!=outermostContext)||((checkContext=context).nodeType?matchContext(elem,context,xml):matchAnyContext(elem,context,xml));checkContext=null;return ret}];for(;i1&&elementMatcher(matchers),i>1&&toSelector(tokens.slice(0,i-1).concat({value:tokens[i-2].type===" "?"*":""})).replace(rtrimCSS,"$1"),matcher,i0,byElement=elementMatchers.length>0,superMatcher=function(seed,context,xml,results,outermost){var elem,j,matcher,matchedCount=0,i="0",unmatched=seed&&[],setMatched=[],contextBackup=outermostContext,elems=seed||byElement&&Expr.find.TAG("*",outermost),dirrunsUnique=dirruns+=contextBackup==null?1:Math.random()||.1,len=elems.length;if(outermost){outermostContext=context==document||context||outermost}for(;i!==len&&(elem=elems[i])!=null;i++){if(byElement&&elem){j=0;if(!context&&elem.ownerDocument!=document){setDocument(elem);xml=!documentIsHTML}while(matcher=elementMatchers[j++]){if(matcher(elem,context||document,xml)){push.call(results,elem);break}}if(outermost){dirruns=dirrunsUnique}}if(bySet){if(elem=!matcher&&elem){matchedCount--}if(seed){unmatched.push(elem)}}}matchedCount+=i;if(bySet&&i!==matchedCount){j=0;while(matcher=setMatchers[j++]){matcher(unmatched,setMatched,context,xml)}if(seed){if(matchedCount>0){while(i--){if(!(unmatched[i]||setMatched[i])){setMatched[i]=pop.call(results)}}}setMatched=condense(setMatched)}push.apply(results,setMatched);if(outermost&&!seed&&setMatched.length>0&&matchedCount+setMatchers.length>1){jQuery.uniqueSort(results)}}if(outermost){dirruns=dirrunsUnique;outermostContext=contextBackup}return unmatched};return bySet?markFunction(superMatcher):superMatcher}function compile(selector,match){var i,setMatchers=[],elementMatchers=[],cached=compilerCache[selector+" "];if(!cached){if(!match){match=tokenize(selector)}i=match.length;while(i--){cached=matcherFromTokens(match[i]);if(cached[expando]){setMatchers.push(cached)}else{elementMatchers.push(cached)}}cached=compilerCache(selector,matcherFromGroupMatchers(elementMatchers,setMatchers));cached.selector=selector}return cached}function select(selector,context,results,seed){var i,tokens,token,type,find,compiled=typeof selector==="function"&&selector,match=!seed&&tokenize(selector=compiled.selector||selector);results=results||[];if(match.length===1){tokens=match[0]=match[0].slice(0);if(tokens.length>2&&(token=tokens[0]).type==="ID"&&context.nodeType===9&&documentIsHTML&&Expr.relative[tokens[1].type]){context=(Expr.find.ID(token.matches[0].replace(runescape,funescape),context)||[])[0];if(!context){return results}else if(compiled){context=context.parentNode}selector=selector.slice(tokens.shift().value.length)}i=matchExpr.needsContext.test(selector)?0:tokens.length;while(i--){token=tokens[i];if(Expr.relative[type=token.type]){break}if(find=Expr.find[type]){if(seed=find(token.matches[0].replace(runescape,funescape),rsibling.test(tokens[0].type)&&testContext(context.parentNode)||context)){tokens.splice(i,1);selector=seed.length&&toSelector(tokens);if(!selector){push.apply(results,seed);return results}break}}}}(compiled||compile(selector,match))(seed,context,!documentIsHTML,results,!context||rsibling.test(selector)&&testContext(context.parentNode)||context);return results}support.sortStable=expando.split("").sort(sortOrder).join("")===expando;setDocument();support.sortDetached=assert(function(el){return el.compareDocumentPosition(document.createElement("fieldset"))&1});jQuery.find=find;jQuery.expr[":"]=jQuery.expr.pseudos;jQuery.unique=jQuery.uniqueSort;find.compile=compile;find.select=select;find.setDocument=setDocument;find.tokenize=tokenize;find.escape=jQuery.escapeSelector;find.getText=jQuery.text;find.isXML=jQuery.isXMLDoc;find.selectors=jQuery.expr;find.support=jQuery.support;find.uniqueSort=jQuery.uniqueSort})();var dir=function(elem,dir,until){var matched=[],truncate=until!==undefined;while((elem=elem[dir])&&elem.nodeType!==9){if(elem.nodeType===1){if(truncate&&jQuery(elem).is(until)){break}matched.push(elem)}}return matched};var siblings=function(n,elem){var matched=[];for(;n;n=n.nextSibling){if(n.nodeType===1&&n!==elem){matched.push(n)}}return matched};var rneedsContext=jQuery.expr.match.needsContext;var rsingleTag=/^<([a-z][^\/\0>:\x20\t\r\n\f]*)[\x20\t\r\n\f]*\/?>(?:<\/\1>|)$/i;function winnow(elements,qualifier,not){if(isFunction(qualifier)){return jQuery.grep(elements,function(elem,i){return!!qualifier.call(elem,i,elem)!==not})}if(qualifier.nodeType){return jQuery.grep(elements,function(elem){return elem===qualifier!==not})}if(typeof qualifier!=="string"){return jQuery.grep(elements,function(elem){return indexOf.call(qualifier,elem)>-1!==not})}return jQuery.filter(qualifier,elements,not)}jQuery.filter=function(expr,elems,not){var elem=elems[0];if(not){expr=":not("+expr+")"}if(elems.length===1&&elem.nodeType===1){return jQuery.find.matchesSelector(elem,expr)?[elem]:[]}return jQuery.find.matches(expr,jQuery.grep(elems,function(elem){return elem.nodeType===1}))};jQuery.fn.extend({find:function(selector){var i,ret,len=this.length,self=this;if(typeof selector!=="string"){return this.pushStack(jQuery(selector).filter(function(){for(i=0;i1?jQuery.uniqueSort(ret):ret},filter:function(selector){return this.pushStack(winnow(this,selector||[],false))},not:function(selector){return this.pushStack(winnow(this,selector||[],true))},is:function(selector){return!!winnow(this,typeof selector==="string"&&rneedsContext.test(selector)?jQuery(selector):selector||[],false).length}});var rootjQuery,rquickExpr=/^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]+))$/,init=jQuery.fn.init=function(selector,context,root){var match,elem;if(!selector){return this}root=root||rootjQuery;if(typeof selector==="string"){if(selector[0]==="<"&&selector[selector.length-1]===">"&&selector.length>=3){match=[null,selector,null]}else{match=rquickExpr.exec(selector)}if(match&&(match[1]||!context)){if(match[1]){context=context instanceof jQuery?context[0]:context;jQuery.merge(this,jQuery.parseHTML(match[1],context&&context.nodeType?context.ownerDocument||context:document,true));if(rsingleTag.test(match[1])&&jQuery.isPlainObject(context)){for(match in context){if(isFunction(this[match])){this[match](context[match])}else{this.attr(match,context[match])}}}return this}else{elem=document.getElementById(match[2]);if(elem){this[0]=elem;this.length=1}return this}}else if(!context||context.jquery){return(context||root).find(selector)}else{return this.constructor(context).find(selector)}}else if(selector.nodeType){this[0]=selector;this.length=1;return this}else if(isFunction(selector)){return root.ready!==undefined?root.ready(selector):selector(jQuery)}return jQuery.makeArray(selector,this)};init.prototype=jQuery.fn;rootjQuery=jQuery(document);var rparentsprev=/^(?:parents|prev(?:Until|All))/,guaranteedUnique={children:true,contents:true,next:true,prev:true};jQuery.fn.extend({has:function(target){var targets=jQuery(target,this),l=targets.length;return this.filter(function(){var i=0;for(;i-1:cur.nodeType===1&&jQuery.find.matchesSelector(cur,selectors))){matched.push(cur);break}}}}return this.pushStack(matched.length>1?jQuery.uniqueSort(matched):matched)},index:function(elem){if(!elem){return this[0]&&this[0].parentNode?this.first().prevAll().length:-1}if(typeof elem==="string"){return indexOf.call(jQuery(elem),this[0])}return indexOf.call(this,elem.jquery?elem[0]:elem)},add:function(selector,context){return this.pushStack(jQuery.uniqueSort(jQuery.merge(this.get(),jQuery(selector,context))))},addBack:function(selector){return this.add(selector==null?this.prevObject:this.prevObject.filter(selector))}});function sibling(cur,dir){while((cur=cur[dir])&&cur.nodeType!==1){}return cur}jQuery.each({parent:function(elem){var parent=elem.parentNode;return parent&&parent.nodeType!==11?parent:null},parents:function(elem){return dir(elem,"parentNode")},parentsUntil:function(elem,_i,until){return dir(elem,"parentNode",until)},next:function(elem){return sibling(elem,"nextSibling")},prev:function(elem){return sibling(elem,"previousSibling")},nextAll:function(elem){return dir(elem,"nextSibling")},prevAll:function(elem){return dir(elem,"previousSibling")},nextUntil:function(elem,_i,until){return dir(elem,"nextSibling",until)},prevUntil:function(elem,_i,until){return dir(elem,"previousSibling",until)},siblings:function(elem){return siblings((elem.parentNode||{}).firstChild,elem)},children:function(elem){return siblings(elem.firstChild)},contents:function(elem){if(elem.contentDocument!=null&&getProto(elem.contentDocument)){return elem.contentDocument}if(nodeName(elem,"template")){elem=elem.content||elem}return jQuery.merge([],elem.childNodes)}},function(name,fn){jQuery.fn[name]=function(until,selector){var matched=jQuery.map(this,fn,until);if(name.slice(-5)!=="Until"){selector=until}if(selector&&typeof selector==="string"){matched=jQuery.filter(selector,matched)}if(this.length>1){if(!guaranteedUnique[name]){jQuery.uniqueSort(matched)}if(rparentsprev.test(name)){matched.reverse()}}return this.pushStack(matched)}});var rnothtmlwhite=/[^\x20\t\r\n\f]+/g;function createOptions(options){var object={};jQuery.each(options.match(rnothtmlwhite)||[],function(_,flag){object[flag]=true});return object}jQuery.Callbacks=function(options){options=typeof options==="string"?createOptions(options):jQuery.extend({},options);var firing,memory,fired,locked,list=[],queue=[],firingIndex=-1,fire=function(){locked=locked||options.once;fired=firing=true;for(;queue.length;firingIndex=-1){memory=queue.shift();while(++firingIndex-1){list.splice(index,1);if(index<=firingIndex){firingIndex--}}});return this},has:function(fn){return fn?jQuery.inArray(fn,list)>-1:list.length>0},empty:function(){if(list){list=[]}return this},disable:function(){locked=queue=[];list=memory="";return this},disabled:function(){return!list},lock:function(){locked=queue=[];if(!memory&&!firing){list=memory=""}return this},locked:function(){return!!locked},fireWith:function(context,args){if(!locked){args=args||[];args=[context,args.slice?args.slice():args];queue.push(args);if(!firing){fire()}}return this},fire:function(){self.fireWith(this,arguments);return this},fired:function(){return!!fired}};return self};function Identity(v){return v}function Thrower(ex){throw ex}function adoptValue(value,resolve,reject,noValue){var method;try{if(value&&isFunction(method=value.promise)){method.call(value).done(resolve).fail(reject)}else if(value&&isFunction(method=value.then)){method.call(value,resolve,reject)}else{resolve.apply(undefined,[value].slice(noValue))}}catch(value){reject.apply(undefined,[value])}}jQuery.extend({Deferred:function(func){var tuples=[["notify","progress",jQuery.Callbacks("memory"),jQuery.Callbacks("memory"),2],["resolve","done",jQuery.Callbacks("once memory"),jQuery.Callbacks("once memory"),0,"resolved"],["reject","fail",jQuery.Callbacks("once memory"),jQuery.Callbacks("once memory"),1,"rejected"]],state="pending",promise={state:function(){return state},always:function(){deferred.done(arguments).fail(arguments);return this},catch:function(fn){return promise.then(null,fn)},pipe:function(){var fns=arguments;return jQuery.Deferred(function(newDefer){jQuery.each(tuples,function(_i,tuple){var fn=isFunction(fns[tuple[4]])&&fns[tuple[4]];deferred[tuple[1]](function(){var returned=fn&&fn.apply(this,arguments);if(returned&&isFunction(returned.promise)){returned.promise().progress(newDefer.notify).done(newDefer.resolve).fail(newDefer.reject)}else{newDefer[tuple[0]+"With"](this,fn?[returned]:arguments)}})});fns=null}).promise()},then:function(onFulfilled,onRejected,onProgress){var maxDepth=0;function resolve(depth,deferred,handler,special){return function(){var that=this,args=arguments,mightThrow=function(){var returned,then;if(depth=maxDepth){if(handler!==Thrower){that=undefined;args=[e]}deferred.rejectWith(that,args)}}};if(depth){process()}else{if(jQuery.Deferred.getErrorHook){process.error=jQuery.Deferred.getErrorHook()}else if(jQuery.Deferred.getStackHook){process.error=jQuery.Deferred.getStackHook()}window.setTimeout(process)}}}return jQuery.Deferred(function(newDefer){tuples[0][3].add(resolve(0,newDefer,isFunction(onProgress)?onProgress:Identity,newDefer.notifyWith));tuples[1][3].add(resolve(0,newDefer,isFunction(onFulfilled)?onFulfilled:Identity));tuples[2][3].add(resolve(0,newDefer,isFunction(onRejected)?onRejected:Thrower))}).promise()},promise:function(obj){return obj!=null?jQuery.extend(obj,promise):promise}},deferred={};jQuery.each(tuples,function(i,tuple){var list=tuple[2],stateString=tuple[5];promise[tuple[1]]=list.add;if(stateString){list.add(function(){state=stateString},tuples[3-i][2].disable,tuples[3-i][3].disable,tuples[0][2].lock,tuples[0][3].lock)}list.add(tuple[3].fire);deferred[tuple[0]]=function(){deferred[tuple[0]+"With"](this===deferred?undefined:this,arguments);return this};deferred[tuple[0]+"With"]=list.fireWith});promise.promise(deferred);if(func){func.call(deferred,deferred)}return deferred},when:function(singleValue){var remaining=arguments.length,i=remaining,resolveContexts=Array(i),resolveValues=slice.call(arguments),primary=jQuery.Deferred(),updateFunc=function(i){return function(value){resolveContexts[i]=this;resolveValues[i]=arguments.length>1?slice.call(arguments):value;if(!--remaining){primary.resolveWith(resolveContexts,resolveValues)}}};if(remaining<=1){adoptValue(singleValue,primary.done(updateFunc(i)).resolve,primary.reject,!remaining);if(primary.state()==="pending"||isFunction(resolveValues[i]&&resolveValues[i].then)){return primary.then()}}while(i--){adoptValue(resolveValues[i],updateFunc(i),primary.reject)}return primary.promise()}});var rerrorNames=/^(Eval|Internal|Range|Reference|Syntax|Type|URI)Error$/;jQuery.Deferred.exceptionHook=function(error,asyncError){if(window.console&&window.console.warn&&error&&rerrorNames.test(error.name)){window.console.warn("jQuery.Deferred exception: "+error.message,error.stack,asyncError)}};jQuery.readyException=function(error){window.setTimeout(function(){throw error})};var readyList=jQuery.Deferred();jQuery.fn.ready=function(fn){readyList.then(fn).catch(function(error){jQuery.readyException(error)});return this};jQuery.extend({isReady:false,readyWait:1,ready:function(wait){if(wait===true?--jQuery.readyWait:jQuery.isReady){return}jQuery.isReady=true;if(wait!==true&&--jQuery.readyWait>0){return}readyList.resolveWith(document,[jQuery])}});jQuery.ready.then=readyList.then;function completed(){document.removeEventListener("DOMContentLoaded",completed);window.removeEventListener("load",completed);jQuery.ready()}if(document.readyState==="complete"||document.readyState!=="loading"&&!document.documentElement.doScroll){window.setTimeout(jQuery.ready)}else{document.addEventListener("DOMContentLoaded",completed);window.addEventListener("load",completed)}var access=function(elems,fn,key,value,chainable,emptyGet,raw){var i=0,len=elems.length,bulk=key==null;if(toType(key)==="object"){chainable=true;for(i in key){access(elems,fn,i,key[i],true,emptyGet,raw)}}else if(value!==undefined){chainable=true;if(!isFunction(value)){raw=true}if(bulk){if(raw){fn.call(elems,value);fn=null}else{bulk=fn;fn=function(elem,_key,value){return bulk.call(jQuery(elem),value)}}}if(fn){for(;i1,null,true)},removeData:function(key){return this.each(function(){dataUser.remove(this,key)})}});jQuery.extend({queue:function(elem,type,data){var queue;if(elem){type=(type||"fx")+"queue";queue=dataPriv.get(elem,type);if(data){if(!queue||Array.isArray(data)){queue=dataPriv.access(elem,type,jQuery.makeArray(data))}else{queue.push(data)}}return queue||[]}},dequeue:function(elem,type){type=type||"fx";var queue=jQuery.queue(elem,type),startLength=queue.length,fn=queue.shift(),hooks=jQuery._queueHooks(elem,type),next=function(){jQuery.dequeue(elem,type)};if(fn==="inprogress"){fn=queue.shift();startLength--}if(fn){if(type==="fx"){queue.unshift("inprogress")}delete hooks.stop;fn.call(elem,next,hooks)}if(!startLength&&hooks){hooks.empty.fire()}},_queueHooks:function(elem,type){var key=type+"queueHooks";return dataPriv.get(elem,key)||dataPriv.access(elem,key,{empty:jQuery.Callbacks("once memory").add(function(){dataPriv.remove(elem,[type+"queue",key])})})}});jQuery.fn.extend({queue:function(type,data){var setter=2;if(typeof type!=="string"){data=type;type="fx";setter--}if(arguments.length\x20\t\r\n\f]*)/i;var rscriptType=/^$|^module$|\/(?:java|ecma)script/i;(function(){var fragment=document.createDocumentFragment(),div=fragment.appendChild(document.createElement("div")),input=document.createElement("input");input.setAttribute("type","radio");input.setAttribute("checked","checked");input.setAttribute("name","t");div.appendChild(input);support.checkClone=div.cloneNode(true).cloneNode(true).lastChild.checked;div.innerHTML="";support.noCloneChecked=!!div.cloneNode(true).lastChild.defaultValue;div.innerHTML="";support.option=!!div.lastChild})();var wrapMap={thead:[1,"","
    "],col:[2,"","
    "],tr:[2,"","
    "],td:[3,"","
    "],_default:[0,"",""]};wrapMap.tbody=wrapMap.tfoot=wrapMap.colgroup=wrapMap.caption=wrapMap.thead;wrapMap.th=wrapMap.td;if(!support.option){wrapMap.optgroup=wrapMap.option=[1,""]}function getAll(context,tag){var ret;if(typeof context.getElementsByTagName!=="undefined"){ret=context.getElementsByTagName(tag||"*")}else if(typeof context.querySelectorAll!=="undefined"){ret=context.querySelectorAll(tag||"*")}else{ret=[]}if(tag===undefined||tag&&nodeName(context,tag)){return jQuery.merge([context],ret)}return ret}function setGlobalEval(elems,refElements){var i=0,l=elems.length;for(;i-1){if(ignored){ignored.push(elem)}continue}attached=isAttached(elem);tmp=getAll(fragment.appendChild(elem),"script");if(attached){setGlobalEval(tmp)}if(scripts){j=0;while(elem=tmp[j++]){if(rscriptType.test(elem.type||"")){scripts.push(elem)}}}}return fragment}var rtypenamespace=/^([^.]*)(?:\.(.+)|)/;function returnTrue(){return true}function returnFalse(){return false}function on(elem,types,selector,data,fn,one){var origFn,type;if(typeof types==="object"){if(typeof selector!=="string"){data=data||selector;selector=undefined}for(type in types){on(elem,type,selector,data,types[type],one)}return elem}if(data==null&&fn==null){fn=selector;data=selector=undefined}else if(fn==null){if(typeof selector==="string"){fn=data;data=undefined}else{fn=data;data=selector;selector=undefined}}if(fn===false){fn=returnFalse}else if(!fn){return elem}if(one===1){origFn=fn;fn=function(event){jQuery().off(event);return origFn.apply(this,arguments)};fn.guid=origFn.guid||(origFn.guid=jQuery.guid++)}return elem.each(function(){jQuery.event.add(this,types,fn,data,selector)})}jQuery.event={global:{},add:function(elem,types,handler,data,selector){var handleObjIn,eventHandle,tmp,events,t,handleObj,special,handlers,type,namespaces,origType,elemData=dataPriv.get(elem);if(!acceptData(elem)){return}if(handler.handler){handleObjIn=handler;handler=handleObjIn.handler;selector=handleObjIn.selector}if(selector){jQuery.find.matchesSelector(documentElement,selector)}if(!handler.guid){handler.guid=jQuery.guid++}if(!(events=elemData.events)){events=elemData.events=Object.create(null)}if(!(eventHandle=elemData.handle)){eventHandle=elemData.handle=function(e){return typeof jQuery!=="undefined"&&jQuery.event.triggered!==e.type?jQuery.event.dispatch.apply(elem,arguments):undefined}}types=(types||"").match(rnothtmlwhite)||[""];t=types.length;while(t--){tmp=rtypenamespace.exec(types[t])||[];type=origType=tmp[1];namespaces=(tmp[2]||"").split(".").sort();if(!type){continue}special=jQuery.event.special[type]||{};type=(selector?special.delegateType:special.bindType)||type;special=jQuery.event.special[type]||{};handleObj=jQuery.extend({type:type,origType:origType,data:data,handler:handler,guid:handler.guid,selector:selector,needsContext:selector&&jQuery.expr.match.needsContext.test(selector),namespace:namespaces.join(".")},handleObjIn);if(!(handlers=events[type])){handlers=events[type]=[];handlers.delegateCount=0;if(!special.setup||special.setup.call(elem,data,namespaces,eventHandle)===false){if(elem.addEventListener){elem.addEventListener(type,eventHandle)}}}if(special.add){special.add.call(elem,handleObj);if(!handleObj.handler.guid){handleObj.handler.guid=handler.guid}}if(selector){handlers.splice(handlers.delegateCount++,0,handleObj)}else{handlers.push(handleObj)}jQuery.event.global[type]=true}},remove:function(elem,types,handler,selector,mappedTypes){var j,origCount,tmp,events,t,handleObj,special,handlers,type,namespaces,origType,elemData=dataPriv.hasData(elem)&&dataPriv.get(elem);if(!elemData||!(events=elemData.events)){return}types=(types||"").match(rnothtmlwhite)||[""];t=types.length;while(t--){tmp=rtypenamespace.exec(types[t])||[];type=origType=tmp[1];namespaces=(tmp[2]||"").split(".").sort();if(!type){for(type in events){jQuery.event.remove(elem,type+types[t],handler,selector,true)}continue}special=jQuery.event.special[type]||{};type=(selector?special.delegateType:special.bindType)||type;handlers=events[type]||[];tmp=tmp[2]&&new RegExp("(^|\\.)"+namespaces.join("\\.(?:.*\\.|)")+"(\\.|$)");origCount=j=handlers.length;while(j--){handleObj=handlers[j];if((mappedTypes||origType===handleObj.origType)&&(!handler||handler.guid===handleObj.guid)&&(!tmp||tmp.test(handleObj.namespace))&&(!selector||selector===handleObj.selector||selector==="**"&&handleObj.selector)){handlers.splice(j,1);if(handleObj.selector){handlers.delegateCount--}if(special.remove){special.remove.call(elem,handleObj)}}}if(origCount&&!handlers.length){if(!special.teardown||special.teardown.call(elem,namespaces,elemData.handle)===false){jQuery.removeEvent(elem,type,elemData.handle)}delete events[type]}}if(jQuery.isEmptyObject(events)){dataPriv.remove(elem,"handle events")}},dispatch:function(nativeEvent){var i,j,ret,matched,handleObj,handlerQueue,args=new Array(arguments.length),event=jQuery.event.fix(nativeEvent),handlers=(dataPriv.get(this,"events")||Object.create(null))[event.type]||[],special=jQuery.event.special[event.type]||{};args[0]=event;for(i=1;i=1)){for(;cur!==this;cur=cur.parentNode||this){if(cur.nodeType===1&&!(event.type==="click"&&cur.disabled===true)){matchedHandlers=[];matchedSelectors={};for(i=0;i-1:jQuery.find(sel,this,null,[cur]).length}if(matchedSelectors[sel]){matchedHandlers.push(handleObj)}}if(matchedHandlers.length){handlerQueue.push({elem:cur,handlers:matchedHandlers})}}}}cur=this;if(delegateCount\s*$/g;function manipulationTarget(elem,content){if(nodeName(elem,"table")&&nodeName(content.nodeType!==11?content:content.firstChild,"tr")){return jQuery(elem).children("tbody")[0]||elem}return elem}function disableScript(elem){elem.type=(elem.getAttribute("type")!==null)+"/"+elem.type;return elem}function restoreScript(elem){if((elem.type||"").slice(0,5)==="true/"){elem.type=elem.type.slice(5)}else{elem.removeAttribute("type")}return elem}function cloneCopyEvent(src,dest){var i,l,type,pdataOld,udataOld,udataCur,events;if(dest.nodeType!==1){return}if(dataPriv.hasData(src)){pdataOld=dataPriv.get(src);events=pdataOld.events;if(events){dataPriv.remove(dest,"handle events");for(type in events){for(i=0,l=events[type].length;i1&&typeof value==="string"&&!support.checkClone&&rchecked.test(value)){return collection.each(function(index){var self=collection.eq(index);if(valueIsFunction){args[0]=value.call(this,index,self.html())}domManip(self,args,callback,ignored)})}if(l){fragment=buildFragment(args,collection[0].ownerDocument,false,collection,ignored);first=fragment.firstChild;if(fragment.childNodes.length===1){fragment=first}if(first||ignored){scripts=jQuery.map(getAll(fragment,"script"),disableScript);hasScripts=scripts.length;for(;i0){setGlobalEval(destElements,!inPage&&getAll(elem,"script"))}return clone},cleanData:function(elems){var data,elem,type,special=jQuery.event.special,i=0;for(;(elem=elems[i])!==undefined;i++){if(acceptData(elem)){if(data=elem[dataPriv.expando]){if(data.events){for(type in data.events){if(special[type]){jQuery.event.remove(elem,type)}else{jQuery.removeEvent(elem,type,data.handle)}}}elem[dataPriv.expando]=undefined}if(elem[dataUser.expando]){elem[dataUser.expando]=undefined}}}}});jQuery.fn.extend({detach:function(selector){return remove(this,selector,true)},remove:function(selector){return remove(this,selector)},text:function(value){return access(this,function(value){return value===undefined?jQuery.text(this):this.empty().each(function(){if(this.nodeType===1||this.nodeType===11||this.nodeType===9){this.textContent=value}})},null,value,arguments.length)},append:function(){return domManip(this,arguments,function(elem){if(this.nodeType===1||this.nodeType===11||this.nodeType===9){var target=manipulationTarget(this,elem);target.appendChild(elem)}})},prepend:function(){return domManip(this,arguments,function(elem){if(this.nodeType===1||this.nodeType===11||this.nodeType===9){var target=manipulationTarget(this,elem);target.insertBefore(elem,target.firstChild)}})},before:function(){return domManip(this,arguments,function(elem){if(this.parentNode){this.parentNode.insertBefore(elem,this)}})},after:function(){return domManip(this,arguments,function(elem){if(this.parentNode){this.parentNode.insertBefore(elem,this.nextSibling)}})},empty:function(){var elem,i=0;for(;(elem=this[i])!=null;i++){if(elem.nodeType===1){jQuery.cleanData(getAll(elem,false));elem.textContent=""}}return this},clone:function(dataAndEvents,deepDataAndEvents){dataAndEvents=dataAndEvents==null?false:dataAndEvents;deepDataAndEvents=deepDataAndEvents==null?dataAndEvents:deepDataAndEvents;return this.map(function(){return jQuery.clone(this,dataAndEvents,deepDataAndEvents)})},html:function(value){return access(this,function(value){var elem=this[0]||{},i=0,l=this.length;if(value===undefined&&elem.nodeType===1){return elem.innerHTML}if(typeof value==="string"&&!rnoInnerhtml.test(value)&&!wrapMap[(rtagName.exec(value)||["",""])[1].toLowerCase()]){value=jQuery.htmlPrefilter(value);try{for(;i=0){delta+=Math.max(0,Math.ceil(elem["offset"+dimension[0].toUpperCase()+dimension.slice(1)]-computedVal-delta-extra-.5))||0}return delta+marginDelta}function getWidthOrHeight(elem,dimension,extra){var styles=getStyles(elem),boxSizingNeeded=!support.boxSizingReliable()||extra,isBorderBox=boxSizingNeeded&&jQuery.css(elem,"boxSizing",false,styles)==="border-box",valueIsBorderBox=isBorderBox,val=curCSS(elem,dimension,styles),offsetProp="offset"+dimension[0].toUpperCase()+dimension.slice(1);if(rnumnonpx.test(val)){if(!extra){return val}val="auto"}if((!support.boxSizingReliable()&&isBorderBox||!support.reliableTrDimensions()&&nodeName(elem,"tr")||val==="auto"||!parseFloat(val)&&jQuery.css(elem,"display",false,styles)==="inline")&&elem.getClientRects().length){isBorderBox=jQuery.css(elem,"boxSizing",false,styles)==="border-box";valueIsBorderBox=offsetProp in elem;if(valueIsBorderBox){val=elem[offsetProp]}}val=parseFloat(val)||0;return val+boxModelAdjustment(elem,dimension,extra||(isBorderBox?"border":"content"),valueIsBorderBox,styles,val)+"px"}jQuery.extend({cssHooks:{opacity:{get:function(elem,computed){if(computed){var ret=curCSS(elem,"opacity");return ret===""?"1":ret}}}},cssNumber:{animationIterationCount:true,aspectRatio:true,borderImageSlice:true,columnCount:true,flexGrow:true,flexShrink:true,fontWeight:true,gridArea:true,gridColumn:true,gridColumnEnd:true,gridColumnStart:true,gridRow:true,gridRowEnd:true,gridRowStart:true,lineHeight:true,opacity:true,order:true,orphans:true,scale:true,widows:true,zIndex:true,zoom:true,fillOpacity:true,floodOpacity:true,stopOpacity:true,strokeMiterlimit:true,strokeOpacity:true},cssProps:{},style:function(elem,name,value,extra){if(!elem||elem.nodeType===3||elem.nodeType===8||!elem.style){return}var ret,type,hooks,origName=camelCase(name),isCustomProp=rcustomProp.test(name),style=elem.style;if(!isCustomProp){name=finalPropName(origName)}hooks=jQuery.cssHooks[name]||jQuery.cssHooks[origName];if(value!==undefined){type=typeof value;if(type==="string"&&(ret=rcssNum.exec(value))&&ret[1]){value=adjustCSS(elem,name,ret);type="number"}if(value==null||value!==value){return}if(type==="number"&&!isCustomProp){value+=ret&&ret[3]||(jQuery.cssNumber[origName]?"":"px")}if(!support.clearCloneStyle&&value===""&&name.indexOf("background")===0){style[name]="inherit"}if(!hooks||!("set"in hooks)||(value=hooks.set(elem,value,extra))!==undefined){if(isCustomProp){style.setProperty(name,value)}else{style[name]=value}}}else{if(hooks&&"get"in hooks&&(ret=hooks.get(elem,false,extra))!==undefined){return ret}return style[name]}},css:function(elem,name,extra,styles){var val,num,hooks,origName=camelCase(name),isCustomProp=rcustomProp.test(name);if(!isCustomProp){name=finalPropName(origName)}hooks=jQuery.cssHooks[name]||jQuery.cssHooks[origName];if(hooks&&"get"in hooks){val=hooks.get(elem,true,extra)}if(val===undefined){val=curCSS(elem,name,styles)}if(val==="normal"&&name in cssNormalTransform){val=cssNormalTransform[name]}if(extra===""||extra){num=parseFloat(val);return extra===true||isFinite(num)?num||0:val}return val}});jQuery.each(["height","width"],function(_i,dimension){jQuery.cssHooks[dimension]={get:function(elem,computed,extra){if(computed){return rdisplayswap.test(jQuery.css(elem,"display"))&&(!elem.getClientRects().length||!elem.getBoundingClientRect().width)?swap(elem,cssShow,function(){return getWidthOrHeight(elem,dimension,extra)}):getWidthOrHeight(elem,dimension,extra)}},set:function(elem,value,extra){var matches,styles=getStyles(elem),scrollboxSizeBuggy=!support.scrollboxSize()&&styles.position==="absolute",boxSizingNeeded=scrollboxSizeBuggy||extra,isBorderBox=boxSizingNeeded&&jQuery.css(elem,"boxSizing",false,styles)==="border-box",subtract=extra?boxModelAdjustment(elem,dimension,extra,isBorderBox,styles):0;if(isBorderBox&&scrollboxSizeBuggy){subtract-=Math.ceil(elem["offset"+dimension[0].toUpperCase()+dimension.slice(1)]-parseFloat(styles[dimension])-boxModelAdjustment(elem,dimension,"border",false,styles)-.5)}if(subtract&&(matches=rcssNum.exec(value))&&(matches[3]||"px")!=="px"){elem.style[dimension]=value;value=jQuery.css(elem,dimension)}return setPositiveNumber(elem,value,subtract)}}});jQuery.cssHooks.marginLeft=addGetHookIf(support.reliableMarginLeft,function(elem,computed){if(computed){return(parseFloat(curCSS(elem,"marginLeft"))||elem.getBoundingClientRect().left-swap(elem,{marginLeft:0},function(){return elem.getBoundingClientRect().left}))+"px"}});jQuery.each({margin:"",padding:"",border:"Width"},function(prefix,suffix){jQuery.cssHooks[prefix+suffix]={expand:function(value){var i=0,expanded={},parts=typeof value==="string"?value.split(" "):[value];for(;i<4;i++){expanded[prefix+cssExpand[i]+suffix]=parts[i]||parts[i-2]||parts[0]}return expanded}};if(prefix!=="margin"){jQuery.cssHooks[prefix+suffix].set=setPositiveNumber}});jQuery.fn.extend({css:function(name,value){return access(this,function(elem,name,value){var styles,len,map={},i=0;if(Array.isArray(name)){styles=getStyles(elem);len=name.length;for(;i1)}});function Tween(elem,options,prop,end,easing){return new Tween.prototype.init(elem,options,prop,end,easing)}jQuery.Tween=Tween;Tween.prototype={constructor:Tween,init:function(elem,options,prop,end,easing,unit){this.elem=elem;this.prop=prop;this.easing=easing||jQuery.easing._default;this.options=options;this.start=this.now=this.cur();this.end=end;this.unit=unit||(jQuery.cssNumber[prop]?"":"px")},cur:function(){var hooks=Tween.propHooks[this.prop];return hooks&&hooks.get?hooks.get(this):Tween.propHooks._default.get(this)},run:function(percent){var eased,hooks=Tween.propHooks[this.prop];if(this.options.duration){this.pos=eased=jQuery.easing[this.easing](percent,this.options.duration*percent,0,1,this.options.duration)}else{this.pos=eased=percent}this.now=(this.end-this.start)*eased+this.start;if(this.options.step){this.options.step.call(this.elem,this.now,this)}if(hooks&&hooks.set){hooks.set(this)}else{Tween.propHooks._default.set(this)}return this}};Tween.prototype.init.prototype=Tween.prototype;Tween.propHooks={_default:{get:function(tween){var result;if(tween.elem.nodeType!==1||tween.elem[tween.prop]!=null&&tween.elem.style[tween.prop]==null){return tween.elem[tween.prop]}result=jQuery.css(tween.elem,tween.prop,"");return!result||result==="auto"?0:result},set:function(tween){if(jQuery.fx.step[tween.prop]){jQuery.fx.step[tween.prop](tween)}else if(tween.elem.nodeType===1&&(jQuery.cssHooks[tween.prop]||tween.elem.style[finalPropName(tween.prop)]!=null)){jQuery.style(tween.elem,tween.prop,tween.now+tween.unit)}else{tween.elem[tween.prop]=tween.now}}}};Tween.propHooks.scrollTop=Tween.propHooks.scrollLeft={set:function(tween){if(tween.elem.nodeType&&tween.elem.parentNode){tween.elem[tween.prop]=tween.now}}};jQuery.easing={linear:function(p){return p},swing:function(p){return.5-Math.cos(p*Math.PI)/2},_default:"swing"};jQuery.fx=Tween.prototype.init;jQuery.fx.step={};var fxNow,inProgress,rfxtypes=/^(?:toggle|show|hide)$/,rrun=/queueHooks$/;function schedule(){if(inProgress){if(document.hidden===false&&window.requestAnimationFrame){window.requestAnimationFrame(schedule)}else{window.setTimeout(schedule,jQuery.fx.interval)}jQuery.fx.tick()}}function createFxNow(){window.setTimeout(function(){fxNow=undefined});return fxNow=Date.now()}function genFx(type,includeWidth){var which,i=0,attrs={height:type};includeWidth=includeWidth?1:0;for(;i<4;i+=2-includeWidth){which=cssExpand[i];attrs["margin"+which]=attrs["padding"+which]=type}if(includeWidth){attrs.opacity=attrs.width=type}return attrs}function createTween(value,prop,animation){var tween,collection=(Animation.tweeners[prop]||[]).concat(Animation.tweeners["*"]),index=0,length=collection.length;for(;index1)},removeAttr:function(name){return this.each(function(){jQuery.removeAttr(this,name)})}});jQuery.extend({attr:function(elem,name,value){var ret,hooks,nType=elem.nodeType;if(nType===3||nType===8||nType===2){return}if(typeof elem.getAttribute==="undefined"){return jQuery.prop(elem,name,value)}if(nType!==1||!jQuery.isXMLDoc(elem)){hooks=jQuery.attrHooks[name.toLowerCase()]||(jQuery.expr.match.bool.test(name)?boolHook:undefined)}if(value!==undefined){if(value===null){jQuery.removeAttr(elem,name);return}if(hooks&&"set"in hooks&&(ret=hooks.set(elem,value,name))!==undefined){return ret}elem.setAttribute(name,value+"");return value}if(hooks&&"get"in hooks&&(ret=hooks.get(elem,name))!==null){return ret}ret=jQuery.find.attr(elem,name);return ret==null?undefined:ret},attrHooks:{type:{set:function(elem,value){if(!support.radioValue&&value==="radio"&&nodeName(elem,"input")){var val=elem.value;elem.setAttribute("type",value);if(val){elem.value=val}return value}}}},removeAttr:function(elem,value){var name,i=0,attrNames=value&&value.match(rnothtmlwhite);if(attrNames&&elem.nodeType===1){while(name=attrNames[i++]){elem.removeAttribute(name)}}}});boolHook={set:function(elem,value,name){if(value===false){jQuery.removeAttr(elem,name)}else{elem.setAttribute(name,name)}return name}};jQuery.each(jQuery.expr.match.bool.source.match(/\w+/g),function(_i,name){var getter=attrHandle[name]||jQuery.find.attr;attrHandle[name]=function(elem,name,isXML){var ret,handle,lowercaseName=name.toLowerCase();if(!isXML){handle=attrHandle[lowercaseName];attrHandle[lowercaseName]=ret;ret=getter(elem,name,isXML)!=null?lowercaseName:null;attrHandle[lowercaseName]=handle}return ret}});var rfocusable=/^(?:input|select|textarea|button)$/i,rclickable=/^(?:a|area)$/i;jQuery.fn.extend({prop:function(name,value){return access(this,jQuery.prop,name,value,arguments.length>1)},removeProp:function(name){return this.each(function(){delete this[jQuery.propFix[name]||name]})}});jQuery.extend({prop:function(elem,name,value){var ret,hooks,nType=elem.nodeType;if(nType===3||nType===8||nType===2){return}if(nType!==1||!jQuery.isXMLDoc(elem)){name=jQuery.propFix[name]||name;hooks=jQuery.propHooks[name]}if(value!==undefined){if(hooks&&"set"in hooks&&(ret=hooks.set(elem,value,name))!==undefined){return ret}return elem[name]=value}if(hooks&&"get"in hooks&&(ret=hooks.get(elem,name))!==null){return ret}return elem[name]},propHooks:{tabIndex:{get:function(elem){var tabindex=jQuery.find.attr(elem,"tabindex");if(tabindex){return parseInt(tabindex,10)}if(rfocusable.test(elem.nodeName)||rclickable.test(elem.nodeName)&&elem.href){return 0}return-1}}},propFix:{for:"htmlFor",class:"className"}});if(!support.optSelected){jQuery.propHooks.selected={get:function(elem){var parent=elem.parentNode;if(parent&&parent.parentNode){parent.parentNode.selectedIndex}return null},set:function(elem){var parent=elem.parentNode;if(parent){parent.selectedIndex;if(parent.parentNode){parent.parentNode.selectedIndex}}}}}jQuery.each(["tabIndex","readOnly","maxLength","cellSpacing","cellPadding","rowSpan","colSpan","useMap","frameBorder","contentEditable"],function(){jQuery.propFix[this.toLowerCase()]=this});function stripAndCollapse(value){var tokens=value.match(rnothtmlwhite)||[];return tokens.join(" ")}function getClass(elem){return elem.getAttribute&&elem.getAttribute("class")||""}function classesToArray(value){if(Array.isArray(value)){return value}if(typeof value==="string"){return value.match(rnothtmlwhite)||[]}return[]}jQuery.fn.extend({addClass:function(value){var classNames,cur,curValue,className,i,finalValue;if(isFunction(value)){return this.each(function(j){jQuery(this).addClass(value.call(this,j,getClass(this)))})}classNames=classesToArray(value);if(classNames.length){return this.each(function(){curValue=getClass(this);cur=this.nodeType===1&&" "+stripAndCollapse(curValue)+" ";if(cur){for(i=0;i-1){cur=cur.replace(" "+className+" "," ")}}finalValue=stripAndCollapse(cur);if(curValue!==finalValue){this.setAttribute("class",finalValue)}}})}return this},toggleClass:function(value,stateVal){var classNames,className,i,self,type=typeof value,isValidValue=type==="string"||Array.isArray(value);if(isFunction(value)){return this.each(function(i){jQuery(this).toggleClass(value.call(this,i,getClass(this),stateVal),stateVal)})}if(typeof stateVal==="boolean"&&isValidValue){return stateVal?this.addClass(value):this.removeClass(value)}classNames=classesToArray(value);return this.each(function(){if(isValidValue){self=jQuery(this);for(i=0;i-1){return true}}return false}});var rreturn=/\r/g;jQuery.fn.extend({val:function(value){var hooks,ret,valueIsFunction,elem=this[0];if(!arguments.length){if(elem){hooks=jQuery.valHooks[elem.type]||jQuery.valHooks[elem.nodeName.toLowerCase()];if(hooks&&"get"in hooks&&(ret=hooks.get(elem,"value"))!==undefined){return ret}ret=elem.value;if(typeof ret==="string"){return ret.replace(rreturn,"")}return ret==null?"":ret}return}valueIsFunction=isFunction(value);return this.each(function(i){var val;if(this.nodeType!==1){return}if(valueIsFunction){val=value.call(this,i,jQuery(this).val())}else{val=value}if(val==null){val=""}else if(typeof val==="number"){val+=""}else if(Array.isArray(val)){val=jQuery.map(val,function(value){return value==null?"":value+""})}hooks=jQuery.valHooks[this.type]||jQuery.valHooks[this.nodeName.toLowerCase()];if(!hooks||!("set"in hooks)||hooks.set(this,val,"value")===undefined){this.value=val}})}});jQuery.extend({valHooks:{option:{get:function(elem){var val=jQuery.find.attr(elem,"value");return val!=null?val:stripAndCollapse(jQuery.text(elem))}},select:{get:function(elem){var value,option,i,options=elem.options,index=elem.selectedIndex,one=elem.type==="select-one",values=one?null:[],max=one?index+1:options.length;if(index<0){i=max}else{i=one?index:0}for(;i-1){optionSet=true}}if(!optionSet){elem.selectedIndex=-1}return values}}}});jQuery.each(["radio","checkbox"],function(){jQuery.valHooks[this]={set:function(elem,value){if(Array.isArray(value)){return elem.checked=jQuery.inArray(jQuery(elem).val(),value)>-1}}};if(!support.checkOn){jQuery.valHooks[this].get=function(elem){return elem.getAttribute("value")===null?"on":elem.value}}});var location=window.location;var nonce={guid:Date.now()};var rquery=/\?/;jQuery.parseXML=function(data){var xml,parserErrorElem;if(!data||typeof data!=="string"){return null}try{xml=(new window.DOMParser).parseFromString(data,"text/xml")}catch(e){}parserErrorElem=xml&&xml.getElementsByTagName("parsererror")[0];if(!xml||parserErrorElem){jQuery.error("Invalid XML: "+(parserErrorElem?jQuery.map(parserErrorElem.childNodes,function(el){return el.textContent}).join("\n"):data))}return xml};var rfocusMorph=/^(?:focusinfocus|focusoutblur)$/,stopPropagationCallback=function(e){e.stopPropagation()};jQuery.extend(jQuery.event,{trigger:function(event,data,elem,onlyHandlers){var i,cur,tmp,bubbleType,ontype,handle,special,lastElement,eventPath=[elem||document],type=hasOwn.call(event,"type")?event.type:event,namespaces=hasOwn.call(event,"namespace")?event.namespace.split("."):[];cur=lastElement=tmp=elem=elem||document;if(elem.nodeType===3||elem.nodeType===8){return}if(rfocusMorph.test(type+jQuery.event.triggered)){return}if(type.indexOf(".")>-1){namespaces=type.split(".");type=namespaces.shift();namespaces.sort()}ontype=type.indexOf(":")<0&&"on"+type;event=event[jQuery.expando]?event:new jQuery.Event(type,typeof event==="object"&&event);event.isTrigger=onlyHandlers?2:3;event.namespace=namespaces.join(".");event.rnamespace=event.namespace?new RegExp("(^|\\.)"+namespaces.join("\\.(?:.*\\.|)")+"(\\.|$)"):null;event.result=undefined;if(!event.target){event.target=elem}data=data==null?[event]:jQuery.makeArray(data,[event]);special=jQuery.event.special[type]||{};if(!onlyHandlers&&special.trigger&&special.trigger.apply(elem,data)===false){return}if(!onlyHandlers&&!special.noBubble&&!isWindow(elem)){bubbleType=special.delegateType||type;if(!rfocusMorph.test(bubbleType+type)){cur=cur.parentNode}for(;cur;cur=cur.parentNode){eventPath.push(cur);tmp=cur}if(tmp===(elem.ownerDocument||document)){eventPath.push(tmp.defaultView||tmp.parentWindow||window)}}i=0;while((cur=eventPath[i++])&&!event.isPropagationStopped()){lastElement=cur;event.type=i>1?bubbleType:special.bindType||type;handle=(dataPriv.get(cur,"events")||Object.create(null))[event.type]&&dataPriv.get(cur,"handle");if(handle){handle.apply(cur,data)}handle=ontype&&cur[ontype];if(handle&&handle.apply&&acceptData(cur)){event.result=handle.apply(cur,data);if(event.result===false){event.preventDefault()}}}event.type=type;if(!onlyHandlers&&!event.isDefaultPrevented()){if((!special._default||special._default.apply(eventPath.pop(),data)===false)&&acceptData(elem)){if(ontype&&isFunction(elem[type])&&!isWindow(elem)){tmp=elem[ontype];if(tmp){elem[ontype]=null}jQuery.event.triggered=type;if(event.isPropagationStopped()){lastElement.addEventListener(type,stopPropagationCallback)}elem[type]();if(event.isPropagationStopped()){lastElement.removeEventListener(type,stopPropagationCallback)}jQuery.event.triggered=undefined;if(tmp){elem[ontype]=tmp}}}}return event.result},simulate:function(type,elem,event){var e=jQuery.extend(new jQuery.Event,event,{type:type,isSimulated:true});jQuery.event.trigger(e,null,elem)}});jQuery.fn.extend({trigger:function(type,data){return this.each(function(){jQuery.event.trigger(type,data,this)})},triggerHandler:function(type,data){var elem=this[0];if(elem){return jQuery.event.trigger(type,data,elem,true)}}});var rbracket=/\[\]$/,rCRLF=/\r?\n/g,rsubmitterTypes=/^(?:submit|button|image|reset|file)$/i,rsubmittable=/^(?:input|select|textarea|keygen)/i;function buildParams(prefix,obj,traditional,add){var name;if(Array.isArray(obj)){jQuery.each(obj,function(i,v){if(traditional||rbracket.test(prefix)){add(prefix,v)}else{buildParams(prefix+"["+(typeof v==="object"&&v!=null?i:"")+"]",v,traditional,add)}})}else if(!traditional&&toType(obj)==="object"){for(name in obj){buildParams(prefix+"["+name+"]",obj[name],traditional,add)}}else{add(prefix,obj)}}jQuery.param=function(a,traditional){var prefix,s=[],add=function(key,valueOrFunction){var value=isFunction(valueOrFunction)?valueOrFunction():valueOrFunction;s[s.length]=encodeURIComponent(key)+"="+encodeURIComponent(value==null?"":value)};if(a==null){return""}if(Array.isArray(a)||a.jquery&&!jQuery.isPlainObject(a)){jQuery.each(a,function(){add(this.name,this.value)})}else{for(prefix in a){buildParams(prefix,a[prefix],traditional,add)}}return s.join("&")};jQuery.fn.extend({serialize:function(){return jQuery.param(this.serializeArray())},serializeArray:function(){return this.map(function(){var elements=jQuery.prop(this,"elements");return elements?jQuery.makeArray(elements):this}).filter(function(){var type=this.type;return this.name&&!jQuery(this).is(":disabled")&&rsubmittable.test(this.nodeName)&&!rsubmitterTypes.test(type)&&(this.checked||!rcheckableType.test(type))}).map(function(_i,elem){var val=jQuery(this).val();if(val==null){return null}if(Array.isArray(val)){return jQuery.map(val,function(val){return{name:elem.name,value:val.replace(rCRLF,"\r\n")}})}return{name:elem.name,value:val.replace(rCRLF,"\r\n")}}).get()}});var r20=/%20/g,rhash=/#.*$/,rantiCache=/([?&])_=[^&]*/,rheaders=/^(.*?):[ \t]*([^\r\n]*)$/gm,rlocalProtocol=/^(?:about|app|app-storage|.+-extension|file|res|widget):$/,rnoContent=/^(?:GET|HEAD)$/,rprotocol=/^\/\//,prefilters={},transports={},allTypes="*/".concat("*"),originAnchor=document.createElement("a");originAnchor.href=location.href;function addToPrefiltersOrTransports(structure){return function(dataTypeExpression,func){if(typeof dataTypeExpression!=="string"){func=dataTypeExpression;dataTypeExpression="*"}var dataType,i=0,dataTypes=dataTypeExpression.toLowerCase().match(rnothtmlwhite)||[];if(isFunction(func)){while(dataType=dataTypes[i++]){if(dataType[0]==="+"){dataType=dataType.slice(1)||"*";(structure[dataType]=structure[dataType]||[]).unshift(func)}else{(structure[dataType]=structure[dataType]||[]).push(func)}}}}}function inspectPrefiltersOrTransports(structure,options,originalOptions,jqXHR){var inspected={},seekingTransport=structure===transports;function inspect(dataType){var selected;inspected[dataType]=true;jQuery.each(structure[dataType]||[],function(_,prefilterOrFactory){var dataTypeOrTransport=prefilterOrFactory(options,originalOptions,jqXHR);if(typeof dataTypeOrTransport==="string"&&!seekingTransport&&!inspected[dataTypeOrTransport]){options.dataTypes.unshift(dataTypeOrTransport);inspect(dataTypeOrTransport);return false}else if(seekingTransport){return!(selected=dataTypeOrTransport)}});return selected}return inspect(options.dataTypes[0])||!inspected["*"]&&inspect("*")}function ajaxExtend(target,src){var key,deep,flatOptions=jQuery.ajaxSettings.flatOptions||{};for(key in src){if(src[key]!==undefined){(flatOptions[key]?target:deep||(deep={}))[key]=src[key]}}if(deep){jQuery.extend(true,target,deep)}return target}function ajaxHandleResponses(s,jqXHR,responses){var ct,type,finalDataType,firstDataType,contents=s.contents,dataTypes=s.dataTypes;while(dataTypes[0]==="*"){dataTypes.shift();if(ct===undefined){ct=s.mimeType||jqXHR.getResponseHeader("Content-Type")}}if(ct){for(type in contents){if(contents[type]&&contents[type].test(ct)){dataTypes.unshift(type);break}}}if(dataTypes[0]in responses){finalDataType=dataTypes[0]}else{for(type in responses){if(!dataTypes[0]||s.converters[type+" "+dataTypes[0]]){finalDataType=type;break}if(!firstDataType){firstDataType=type}}finalDataType=finalDataType||firstDataType}if(finalDataType){if(finalDataType!==dataTypes[0]){dataTypes.unshift(finalDataType)}return responses[finalDataType]}}function ajaxConvert(s,response,jqXHR,isSuccess){var conv2,current,conv,tmp,prev,converters={},dataTypes=s.dataTypes.slice();if(dataTypes[1]){for(conv in s.converters){converters[conv.toLowerCase()]=s.converters[conv]}}current=dataTypes.shift();while(current){if(s.responseFields[current]){jqXHR[s.responseFields[current]]=response}if(!prev&&isSuccess&&s.dataFilter){response=s.dataFilter(response,s.dataType)}prev=current;current=dataTypes.shift();if(current){if(current==="*"){current=prev}else if(prev!=="*"&&prev!==current){conv=converters[prev+" "+current]||converters["* "+current];if(!conv){for(conv2 in converters){tmp=conv2.split(" ");if(tmp[1]===current){conv=converters[prev+" "+tmp[0]]||converters["* "+tmp[0]];if(conv){if(conv===true){conv=converters[conv2]}else if(converters[conv2]!==true){current=tmp[0];dataTypes.unshift(tmp[1])}break}}}}if(conv!==true){if(conv&&s.throws){response=conv(response)}else{try{response=conv(response)}catch(e){return{state:"parsererror",error:conv?e:"No conversion from "+prev+" to "+current}}}}}}}return{state:"success",data:response}}jQuery.extend({active:0,lastModified:{},etag:{},ajaxSettings:{url:location.href,type:"GET",isLocal:rlocalProtocol.test(location.protocol),global:true,processData:true,async:true,contentType:"application/x-www-form-urlencoded; charset=UTF-8",accepts:{"*":allTypes,text:"text/plain",html:"text/html",xml:"application/xml, text/xml",json:"application/json, text/javascript"},contents:{xml:/\bxml\b/,html:/\bhtml/,json:/\bjson\b/},responseFields:{xml:"responseXML",text:"responseText",json:"responseJSON"},converters:{"* text":String,"text html":true,"text json":JSON.parse,"text xml":jQuery.parseXML},flatOptions:{url:true,context:true}},ajaxSetup:function(target,settings){return settings?ajaxExtend(ajaxExtend(target,jQuery.ajaxSettings),settings):ajaxExtend(jQuery.ajaxSettings,target)},ajaxPrefilter:addToPrefiltersOrTransports(prefilters),ajaxTransport:addToPrefiltersOrTransports(transports),ajax:function(url,options){if(typeof url==="object"){options=url;url=undefined}options=options||{};var transport,cacheURL,responseHeadersString,responseHeaders,timeoutTimer,urlAnchor,completed,fireGlobals,i,uncached,s=jQuery.ajaxSetup({},options),callbackContext=s.context||s,globalEventContext=s.context&&(callbackContext.nodeType||callbackContext.jquery)?jQuery(callbackContext):jQuery.event,deferred=jQuery.Deferred(),completeDeferred=jQuery.Callbacks("once memory"),statusCode=s.statusCode||{},requestHeaders={},requestHeadersNames={},strAbort="canceled",jqXHR={readyState:0,getResponseHeader:function(key){var match;if(completed){if(!responseHeaders){responseHeaders={};while(match=rheaders.exec(responseHeadersString)){responseHeaders[match[1].toLowerCase()+" "]=(responseHeaders[match[1].toLowerCase()+" "]||[]).concat(match[2])}}match=responseHeaders[key.toLowerCase()+" "]}return match==null?null:match.join(", ")},getAllResponseHeaders:function(){return completed?responseHeadersString:null},setRequestHeader:function(name,value){if(completed==null){name=requestHeadersNames[name.toLowerCase()]=requestHeadersNames[name.toLowerCase()]||name;requestHeaders[name]=value}return this},overrideMimeType:function(type){if(completed==null){s.mimeType=type}return this},statusCode:function(map){var code;if(map){if(completed){jqXHR.always(map[jqXHR.status])}else{for(code in map){statusCode[code]=[statusCode[code],map[code]]}}}return this},abort:function(statusText){var finalText=statusText||strAbort;if(transport){transport.abort(finalText)}done(0,finalText);return this}};deferred.promise(jqXHR);s.url=((url||s.url||location.href)+"").replace(rprotocol,location.protocol+"//");s.type=options.method||options.type||s.method||s.type;s.dataTypes=(s.dataType||"*").toLowerCase().match(rnothtmlwhite)||[""];if(s.crossDomain==null){urlAnchor=document.createElement("a");try{urlAnchor.href=s.url;urlAnchor.href=urlAnchor.href;s.crossDomain=originAnchor.protocol+"//"+originAnchor.host!==urlAnchor.protocol+"//"+urlAnchor.host}catch(e){s.crossDomain=true}}if(s.data&&s.processData&&typeof s.data!=="string"){s.data=jQuery.param(s.data,s.traditional)}inspectPrefiltersOrTransports(prefilters,s,options,jqXHR);if(completed){return jqXHR}fireGlobals=jQuery.event&&s.global;if(fireGlobals&&jQuery.active++===0){jQuery.event.trigger("ajaxStart")}s.type=s.type.toUpperCase();s.hasContent=!rnoContent.test(s.type);cacheURL=s.url.replace(rhash,"");if(!s.hasContent){uncached=s.url.slice(cacheURL.length);if(s.data&&(s.processData||typeof s.data==="string")){cacheURL+=(rquery.test(cacheURL)?"&":"?")+s.data;delete s.data}if(s.cache===false){cacheURL=cacheURL.replace(rantiCache,"$1");uncached=(rquery.test(cacheURL)?"&":"?")+"_="+nonce.guid+++uncached}s.url=cacheURL+uncached}else if(s.data&&s.processData&&(s.contentType||"").indexOf("application/x-www-form-urlencoded")===0){s.data=s.data.replace(r20,"+")}if(s.ifModified){if(jQuery.lastModified[cacheURL]){jqXHR.setRequestHeader("If-Modified-Since",jQuery.lastModified[cacheURL])}if(jQuery.etag[cacheURL]){jqXHR.setRequestHeader("If-None-Match",jQuery.etag[cacheURL])}}if(s.data&&s.hasContent&&s.contentType!==false||options.contentType){jqXHR.setRequestHeader("Content-Type",s.contentType)}jqXHR.setRequestHeader("Accept",s.dataTypes[0]&&s.accepts[s.dataTypes[0]]?s.accepts[s.dataTypes[0]]+(s.dataTypes[0]!=="*"?", "+allTypes+"; q=0.01":""):s.accepts["*"]);for(i in s.headers){jqXHR.setRequestHeader(i,s.headers[i])}if(s.beforeSend&&(s.beforeSend.call(callbackContext,jqXHR,s)===false||completed)){return jqXHR.abort()}strAbort="abort";completeDeferred.add(s.complete);jqXHR.done(s.success);jqXHR.fail(s.error);transport=inspectPrefiltersOrTransports(transports,s,options,jqXHR);if(!transport){done(-1,"No Transport")}else{jqXHR.readyState=1;if(fireGlobals){globalEventContext.trigger("ajaxSend",[jqXHR,s])}if(completed){return jqXHR}if(s.async&&s.timeout>0){timeoutTimer=window.setTimeout(function(){jqXHR.abort("timeout")},s.timeout)}try{completed=false;transport.send(requestHeaders,done)}catch(e){if(completed){throw e}done(-1,e)}}function done(status,nativeStatusText,responses,headers){var isSuccess,success,error,response,modified,statusText=nativeStatusText;if(completed){return}completed=true;if(timeoutTimer){window.clearTimeout(timeoutTimer)}transport=undefined;responseHeadersString=headers||"";jqXHR.readyState=status>0?4:0;isSuccess=status>=200&&status<300||status===304;if(responses){response=ajaxHandleResponses(s,jqXHR,responses)}if(!isSuccess&&jQuery.inArray("script",s.dataTypes)>-1&&jQuery.inArray("json",s.dataTypes)<0){s.converters["text script"]=function(){}}response=ajaxConvert(s,response,jqXHR,isSuccess);if(isSuccess){if(s.ifModified){modified=jqXHR.getResponseHeader("Last-Modified");if(modified){jQuery.lastModified[cacheURL]=modified}modified=jqXHR.getResponseHeader("etag");if(modified){jQuery.etag[cacheURL]=modified}}if(status===204||s.type==="HEAD"){statusText="nocontent"}else if(status===304){statusText="notmodified"}else{statusText=response.state;success=response.data;error=response.error;isSuccess=!error}}else{error=statusText;if(status||!statusText){statusText="error";if(status<0){status=0}}}jqXHR.status=status;jqXHR.statusText=(nativeStatusText||statusText)+"";if(isSuccess){deferred.resolveWith(callbackContext,[success,statusText,jqXHR])}else{deferred.rejectWith(callbackContext,[jqXHR,statusText,error])}jqXHR.statusCode(statusCode);statusCode=undefined;if(fireGlobals){globalEventContext.trigger(isSuccess?"ajaxSuccess":"ajaxError",[jqXHR,s,isSuccess?success:error])}completeDeferred.fireWith(callbackContext,[jqXHR,statusText]);if(fireGlobals){globalEventContext.trigger("ajaxComplete",[jqXHR,s]);if(!--jQuery.active){jQuery.event.trigger("ajaxStop")}}}return jqXHR},getJSON:function(url,data,callback){return jQuery.get(url,data,callback,"json")},getScript:function(url,callback){return jQuery.get(url,undefined,callback,"script")}});jQuery.each(["get","post"],function(_i,method){jQuery[method]=function(url,data,callback,type){if(isFunction(data)){type=type||callback;callback=data;data=undefined}return jQuery.ajax(jQuery.extend({url:url,type:method,dataType:type,data:data,success:callback},jQuery.isPlainObject(url)&&url))}});jQuery.ajaxPrefilter(function(s){var i;for(i in s.headers){if(i.toLowerCase()==="content-type"){s.contentType=s.headers[i]||""}}});jQuery._evalUrl=function(url,options,doc){return jQuery.ajax({url:url,type:"GET",dataType:"script",cache:true,async:false,global:false,converters:{"text script":function(){}},dataFilter:function(response){jQuery.globalEval(response,options,doc)}})};jQuery.fn.extend({wrapAll:function(html){var wrap;if(this[0]){if(isFunction(html)){html=html.call(this[0])}wrap=jQuery(html,this[0].ownerDocument).eq(0).clone(true);if(this[0].parentNode){wrap.insertBefore(this[0])}wrap.map(function(){var elem=this;while(elem.firstElementChild){elem=elem.firstElementChild}return elem}).append(this)}return this},wrapInner:function(html){if(isFunction(html)){return this.each(function(i){jQuery(this).wrapInner(html.call(this,i))})}return this.each(function(){var self=jQuery(this),contents=self.contents();if(contents.length){contents.wrapAll(html)}else{self.append(html)}})},wrap:function(html){var htmlIsFunction=isFunction(html);return this.each(function(i){jQuery(this).wrapAll(htmlIsFunction?html.call(this,i):html)})},unwrap:function(selector){this.parent(selector).not("body").each(function(){jQuery(this).replaceWith(this.childNodes)});return this}});jQuery.expr.pseudos.hidden=function(elem){return!jQuery.expr.pseudos.visible(elem)};jQuery.expr.pseudos.visible=function(elem){return!!(elem.offsetWidth||elem.offsetHeight||elem.getClientRects().length)};jQuery.ajaxSettings.xhr=function(){try{return new window.XMLHttpRequest}catch(e){}};var xhrSuccessStatus={0:200,1223:204},xhrSupported=jQuery.ajaxSettings.xhr();support.cors=!!xhrSupported&&"withCredentials"in xhrSupported;support.ajax=xhrSupported=!!xhrSupported;jQuery.ajaxTransport(function(options){var callback,errorCallback;if(support.cors||xhrSupported&&!options.crossDomain){return{send:function(headers,complete){var i,xhr=options.xhr();xhr.open(options.type,options.url,options.async,options.username,options.password);if(options.xhrFields){for(i in options.xhrFields){xhr[i]=options.xhrFields[i]}}if(options.mimeType&&xhr.overrideMimeType){xhr.overrideMimeType(options.mimeType)}if(!options.crossDomain&&!headers["X-Requested-With"]){headers["X-Requested-With"]="XMLHttpRequest"}for(i in headers){xhr.setRequestHeader(i,headers[i])}callback=function(type){return function(){if(callback){callback=errorCallback=xhr.onload=xhr.onerror=xhr.onabort=xhr.ontimeout=xhr.onreadystatechange=null;if(type==="abort"){xhr.abort()}else if(type==="error"){if(typeof xhr.status!=="number"){complete(0,"error")}else{complete(xhr.status,xhr.statusText)}}else{complete(xhrSuccessStatus[xhr.status]||xhr.status,xhr.statusText,(xhr.responseType||"text")!=="text"||typeof xhr.responseText!=="string"?{binary:xhr.response}:{text:xhr.responseText},xhr.getAllResponseHeaders())}}}};xhr.onload=callback();errorCallback=xhr.onerror=xhr.ontimeout=callback("error");if(xhr.onabort!==undefined){xhr.onabort=errorCallback}else{xhr.onreadystatechange=function(){if(xhr.readyState===4){window.setTimeout(function(){if(callback){errorCallback()}})}}}callback=callback("abort");try{xhr.send(options.hasContent&&options.data||null)}catch(e){if(callback){throw e}}},abort:function(){if(callback){callback()}}}}});jQuery.ajaxPrefilter(function(s){if(s.crossDomain){s.contents.script=false}});jQuery.ajaxSetup({accepts:{script:"text/javascript, application/javascript, "+"application/ecmascript, application/x-ecmascript"},contents:{script:/\b(?:java|ecma)script\b/},converters:{"text script":function(text){jQuery.globalEval(text);return text}}});jQuery.ajaxPrefilter("script",function(s){if(s.cache===undefined){s.cache=false}if(s.crossDomain){s.type="GET"}});jQuery.ajaxTransport("script",function(s){if(s.crossDomain||s.scriptAttrs){var script,callback;return{send:function(_,complete){script=jQuery("