diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml
index 627334f..a3ff83b 100644
--- a/.github/workflows/ci.yaml
+++ b/.github/workflows/ci.yaml
@@ -6,9 +6,6 @@ on:
tags:
- 'v*'
-env:
- IMAGE_NAME: ${{ github.repository }}
-
jobs:
build-and-push-image:
runs-on: ubuntu-latest
@@ -37,7 +34,7 @@ jobs:
password: ${{ secrets.DOCKER_HUB_TOKEN }}
- name: Set up QEMU
- uses: docker/setup-qemu-action@v3.2.0
+ uses: docker/setup-qemu-action@v3
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3
@@ -46,7 +43,14 @@ jobs:
id: metadata
uses: docker/metadata-action@v5
with:
- images: ${{ github.repository }}
+ images: |
+ ${{ github.repository }}
+ ghcr.io/${{ github.repository }}
+ tags: |
+ type=semver,pattern={{version}},value=v${{ env.PACKAGE_VERSION }}
+ type=semver,pattern={{major}}.{{minor}},value=v${{ env.PACKAGE_VERSION }}
+ type=semver,pattern={{major}},value=v${{ env.PACKAGE_VERSION }}
+ type=raw,value=latest
- name: Build and push Docker image
uses: docker/build-push-action@v5
@@ -54,12 +58,11 @@ jobs:
context: .
file: Dockerfile
push: true
- platforms: linux/amd64,linux/arm64,linux/arm64/v8
+ platforms: linux/amd64,linux/arm64
build-args: |
PACKAGE_VERSION=${{ env.PACKAGE_VERSION }}
- tags: |
- ${{ github.repository }}:${{ env.PACKAGE_VERSION }}
- ${{ github.repository }}:latest
- ghcr.io/${{ github.repository }}:${{ env.PACKAGE_VERSION }}
- ghcr.io/${{ github.repository }}:latest
- annotations: ${{ steps.metadata.output.annotations }}
+ tags: ${{ steps.metadata.outputs.tags }}
+ labels: ${{ steps.metadata.outputs.labels }}
+ annotations: ${{ steps.metadata.outputs.annotations }}
+ cache-from: type=gha
+ cache-to: type=gha,mode=max
diff --git a/README.md b/README.md
index 6ccc39b..4fe6026 100644
--- a/README.md
+++ b/README.md
@@ -1,10 +1,14 @@
# Immich Public Proxy
+
+
+
+
-
+
@@ -16,7 +20,7 @@ serving straight out of my own Immich instance.
Setup takes less than a minute, and you never need to touch it again as all of your sharing stays managed within Immich.
-
+
### Table of Contents
@@ -29,7 +33,9 @@ Setup takes less than a minute, and you never need to touch it again as all of y
- [How it works](#how-it-works)
- [Additional configuration](#additional-configuration)
- [IPP options](#immich-public-proxy-options)
- - [lightGallery](#lightgallery)
+ - [Gallery options](#gallery-options)
+ - [Lightbox options](#lightbox-options)
+ - [Metadata](#metadata)
- [Custom error pages](#customising-your-error-response-pages)
- [Serving from multiple domains](#serving-from-multiple-domains)
- [Troubleshooting](#troubleshooting)
@@ -51,6 +57,10 @@ surface even further. The only things that the proxy can access are photos that
- Supports sharing photos and videos.
- Supports password-protected shares.
- If sharing a single image, by default the link will directly open the image file so that you can embed it anywhere you would a normal image. (This is configurable.)
+- Gallery styled to match Immich's native look, with light/dark mode following the visitor's system preference.
+- Handles very large shares smoothly thanks to virtualized rendering - the browser only keeps tiles near the viewport in the DOM.
+- Optional multi-select mode so visitors can pick specific photos and download them together as a zip.
+- Optional date-grouped view (off by default), with month headers like "December 2024".
- All usage happens through Immich - you won't need to touch this app after the initial configuration.
### Why not simply put Immich behind a reverse proxy and only expose the `/share/` path to the public?
@@ -149,19 +159,19 @@ Alternatively, you can [pass the configuration inline](docs/inline-configuration
### Immich Public Proxy options
-| Option | Type | Description |
-|--------------------------|----------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
-| `responseHeaders` | `object` | Change the headers sent with your web responses. By default there is `cache-control` and CORS added. |
-| `singleImageGallery` | `bool` | By default a link to a single image will directly open the image file. Set to `true` if you want to show a gallery page instead for a single item. |
-| `downloadOriginalPhoto` | `bool` | Set to `false` if you only want people to be able to download the 'preview' quality photo, rather than your original photo. |
-| `downloadedFilename` | `int` | The filename of the downloaded image. `0` for the original filename if available, falling back to the Immich asset ID `1` for the Immich asset ID number `2` for a shortened version of the asset ID: `img_` plus the first 8 characters of the asset ID |
-| `showGalleryTitle` | `bool` | Show a title on the gallery page. This is taken from the album title if it is an album being shared, otherwise the "Description" from the shared link will be used. |
-| `showGalleryDescription` | `bool` | Show the album description below the title. This only applies if it is an album which is being shared. |
-| `allowDownloadAll` | `int` | Allow visitors to download all files as a zip. `0` disable downloads `1` follow Immich setting per share ([example](https://github.com/user-attachments/assets/79ea8c08-71ce-42ab-b025-10aec384938a)) `2` always allowed |
-| `allowSlugLinks` | `bool` | Enable/disable the custom URL links. |
-| `showHomePage` | `bool` | Set to `false` to remove the IPP shield page at `/` and at `/share` |
-| `showMetadata` | `object` | See the [Metadata](#metadata) section below. |
-| `customInvalidResponse` | various | Send a custom response instead of the default 404 - see [Custom responses](docs/custom-responses.md) for more details. |
+| Option | Type | Description |
+|---------------------------------------|----------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
+| `responseHeaders` | `object` | Change the headers sent with your web responses. By default there is `cache-control` and CORS added. |
+| `downloadOriginalPhoto` | `bool` | Set to `false` if you only want people to be able to download the 'preview' quality photo, rather than your original photo. |
+| `downloadedFilename` | `int` | The filename of the downloaded image. `0` for the original filename if available, falling back to the Immich asset ID `1` for the Immich asset ID number `2` for a shortened version of the asset ID: `img_` plus the first 8 characters of the asset ID |
+| `allowDownloadAll` | `int` | Allow visitors to download all files as a zip, including the selective-download flow in multi-select mode. `0` disable downloads `1` follow Immich setting per share ([example](https://github.com/user-attachments/assets/79ea8c08-71ce-42ab-b025-10aec384938a)) `2` always allowed |
+| `downloadFromImmichConcurrencyLimit` | `int` | Maximum number of assets IPP will fetch from your Immich server in parallel when building a "download all" zip. Defaults to `8`. Lower this if your Immich server is slow or you see download timeouts on large albums; raise it for faster downloads if your server can handle the load. |
+| `allowSlugLinks` | `bool` | Enable/disable the custom URL links. |
+| `showHomePage` | `bool` | Set to `false` to remove the IPP shield page at `/` and at `/share` |
+| `gallery` | `object` | Gallery-page options, see the [Gallery options](#gallery-options) section below. |
+| `lightbox` | `object` | Lightbox option, see the [Lightbox options](#lightbox-options) section below. |
+| `showMetadata` | `object` | See the [Metadata](#metadata) section below. |
+| `customInvalidResponse` | various | Send a custom response instead of the default 404 - see [Custom responses](docs/custom-responses.md) for more details. |
For example, to disable the home page at `/` and at `/share` you need to change `showHomePage` to `false`:
@@ -174,34 +184,63 @@ For example, to disable the home page at `/` and at `/share` you need to change
}
```
-#### Metadata
+### Gallery options
-| Option | Type | Description |
-|---------------|--------|----------------------------------------------------|
-| `description` | `bool` | Show the description as a caption below the photo. |
+Options that control how the gallery page is rendered. Configured under `ipp.gallery`.
-### lightGallery
+| Option | Type | Description |
+|----------------------|--------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
+| `singleImage` | `bool` | By default a link to a single image will directly open the image file. Set to `true` if you want to show a gallery page instead for a single item. |
+| `singleItemAutoOpen` | `bool` | When a share contains a single item and is opened on its gallery page, automatically open the lightbox on the asset. Default `true`. |
+| `showTitle` | `bool` | Show a title on the gallery page. This is taken from the album title if it is an album being shared, otherwise the "Description" from the shared link will be used. |
+| `showDescription` | `bool` | Show the album description below the title. This only applies if it is an album which is being shared. |
+| `groupByDate` | `bool` | Group the gallery's thumbnails by month, with headers like "December 2024" above each group. Sorts photos newest-first. Items missing a creation date end up under an "Undated" bucket at the end. Default `false`. |
-The gallery is created using [lightGallery](https://github.com/sachinchoolur/lightGallery).
-You can find all of lightGallery's settings here:
-https://www.lightgalleryjs.com/docs/settings/
-
-For example, to disable the download button for images, you would edit the `lightGallery` section and change `download` to `false`:
+Example: show the gallery title and group photos by month:
```json
{
- "lightGallery": {
- "controls": true,
- "download": false,
- "mobileSettings": {
- "controls": false,
- "showCloseIcon": true,
- "download": false
+ "ipp": {
+ "gallery": {
+ "showTitle": true,
+ "groupByDate": true
}
}
}
```
+> **Note** for upgraders from earlier versions: the keys `singleImageGallery`, `singleItemAutoOpen`, `showGalleryTitle`, `showGalleryDescription`, and `groupGalleryByDate` used to live directly under `ipp.*`. They've been renamed and moved under `ipp.gallery.*` (see the table above). Existing configs continue to work via a backward-compatibility shim, but you'll see a deprecation notice in the startup log until you migrate them.
+
+### Lightbox options
+
+The gallery's lightbox is powered by [PhotoSwipe](https://photoswipe.com/). Configured under `ipp.lightbox`.
+
+| Option | Type | Description |
+|----------------|--------|------------------------------------------------------------------------------------------------------------------------------------------|
+| `showArrows` | `bool` | Show the prev/next arrows on desktop. They appear when the user hovers the lightbox. Default `true`. |
+| `showDownload` | `bool` | Show a download button in the lightbox toolbar. Only takes effect when downloads are also allowed by `allowDownloadAll`. Default `true`. |
+| `mobileArrows` | `bool` | Show prev/next arrows on mobile (under 640px viewport). Off by default since swipe is the natural mobile navigation. |
+
+Example: hide the download button inside the lightbox even though zip downloads are otherwise allowed:
+
+```json
+{
+ "ipp": {
+ "lightbox": {
+ "showDownload": false
+ }
+ }
+}
+```
+
+### Metadata
+
+Configured under `ipp.showMetadata`.
+
+| Option | Type | Description |
+|---------------|--------|----------------------------------------------------|
+| `description` | `bool` | Show the description as a caption below the photo. |
+
### Customising your error response pages
You can customise the responses that IPP sends for invalid requests. For example you could:
diff --git a/app/.eslintrc b/app/.eslintrc
index 5fd3f5e..c9943d2 100644
--- a/app/.eslintrc
+++ b/app/.eslintrc
@@ -22,5 +22,14 @@
"@typescript-eslint/ban-ts-comment": "off",
"no-prototype-builtins": "off",
"@typescript-eslint/no-empty-function": "off"
- }
+ },
+ "overrides": [
+ {
+ "files": ["public/web.js"],
+ "env": { "browser": true, "node": false },
+ "rules": {
+ "import/no-absolute-path": "off"
+ }
+ }
+ ]
}
diff --git a/app/config.json b/app/config.json
index 205e027..79175c5 100644
--- a/app/config.json
+++ b/app/config.json
@@ -4,28 +4,27 @@
"Cache-Control": "public, max-age=2592000",
"Access-Control-Allow-Origin": "*"
},
- "singleImageGallery": false,
- "singleItemAutoOpen": true,
"downloadOriginalPhoto": true,
"downloadedFilename": 0,
"allowDownloadAll": 0,
+ "downloadFromImmichConcurrencyLimit": 20,
"allowSlugLinks": true,
"showHomePage": true,
- "showGalleryTitle": false,
- "showGalleryDescription": false,
"showMetadata": {
"description": false
},
- "customInvalidResponse": false
- },
- "lightGallery": {
- "controls": true,
- "download": true,
- "customSlideName": true,
- "mobileSettings": {
- "controls": false,
- "showCloseIcon": true,
- "download": true
+ "customInvalidResponse": false,
+ "gallery": {
+ "singleImage": false,
+ "singleItemAutoOpen": true,
+ "showTitle": true,
+ "showDescription": false,
+ "groupByDate": false
+ },
+ "lightbox": {
+ "showArrows": true,
+ "showDownload": true,
+ "mobileArrows": false
}
}
}
diff --git a/app/package-lock.json b/app/package-lock.json
index 036790c..17396f4 100644
--- a/app/package-lock.json
+++ b/app/package-lock.json
@@ -1,20 +1,21 @@
{
"name": "immich-public-proxy",
- "version": "1.15.6",
+ "version": "2.0.2",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "immich-public-proxy",
- "version": "1.15.6",
+ "version": "2.0.2",
"license": "AGPL-3.0",
"dependencies": {
"archiver": "^7.0.1",
"cookie-session": "^2.1.0",
"dayjs": "^1.11.13",
"dotenv": "^16.4.5",
- "ejs": "^3.1.10",
"express": "^4.21.1",
+ "preact": "^10.29.2",
+ "preact-render-to-string": "^6.7.0",
"tslib": "^2.8.1"
},
"bin": {
@@ -1017,9 +1018,9 @@
"license": "MIT"
},
"node_modules/body-parser": {
- "version": "1.20.4",
- "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-1.20.4.tgz",
- "integrity": "sha512-ZTgYYLMOXY9qKU/57FAo8F+HA2dGX7bqGc71txDRC1rS4frdFI5R7NhluHxH6M0YItAP0sHB4uqAOcYKxO6uGA==",
+ "version": "1.20.5",
+ "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-1.20.5.tgz",
+ "integrity": "sha512-3grm+/2tUOvu2cjJkvsIxrv/wVpfXQW4PsQHYm7yk4vfpu7Ekl6nEsYBoJUL6qDwZUx8wUhQ8tR2qz+ad9c9OA==",
"license": "MIT",
"dependencies": {
"bytes": "~3.1.2",
@@ -1030,7 +1031,7 @@
"http-errors": "~2.0.1",
"iconv-lite": "~0.4.24",
"on-finished": "~2.4.1",
- "qs": "~6.14.0",
+ "qs": "~6.15.1",
"raw-body": "~2.5.3",
"type-is": "~1.6.18",
"unpipe": "~1.0.0"
@@ -1088,6 +1089,7 @@
"version": "1.1.14",
"resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.14.tgz",
"integrity": "sha512-MWPGfDxnyzKU7rNOW9SP/c50vi3xrmrua/+6hfPbCS2ABNWfx24vPidzvC7krjU/RTo235sV776ymlsMtGKj8g==",
+ "dev": true,
"license": "MIT",
"dependencies": {
"balanced-match": "^1.0.0",
@@ -1238,6 +1240,7 @@
"version": "4.1.2",
"resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz",
"integrity": "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==",
+ "dev": true,
"license": "MIT",
"dependencies": {
"ansi-styles": "^4.1.0",
@@ -1288,6 +1291,7 @@
"version": "0.0.1",
"resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz",
"integrity": "sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg==",
+ "dev": true,
"license": "MIT"
},
"node_modules/content-disposition": {
@@ -1634,21 +1638,6 @@
"integrity": "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==",
"license": "MIT"
},
- "node_modules/ejs": {
- "version": "3.1.10",
- "resolved": "https://registry.npmjs.org/ejs/-/ejs-3.1.10.tgz",
- "integrity": "sha512-UeJmFfOrAQS8OJWPZ4qtgHyWExa088/MtK5UEyoJGFH67cDEXkZSviOiKRCZ4Xij0zxI3JECgYs3oKx+AizQBA==",
- "license": "Apache-2.0",
- "dependencies": {
- "jake": "^10.8.5"
- },
- "bin": {
- "ejs": "bin/cli.js"
- },
- "engines": {
- "node": ">=0.10.0"
- }
- },
"node_modules/emoji-regex": {
"version": "9.2.2",
"resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-9.2.2.tgz",
@@ -2315,14 +2304,14 @@
}
},
"node_modules/express": {
- "version": "4.22.1",
- "resolved": "https://registry.npmjs.org/express/-/express-4.22.1.tgz",
- "integrity": "sha512-F2X8g9P1X7uCPZMA3MVf9wcTqlyNp7IhH5qPCI0izhaOIYXaW9L535tGA3qmjRzpH+bZczqq7hVKxTR4NWnu+g==",
+ "version": "4.22.2",
+ "resolved": "https://registry.npmjs.org/express/-/express-4.22.2.tgz",
+ "integrity": "sha512-IuL+Elrou2ZvCFHs18/CIzy2Nzvo25nZ1/D2eIZlz7c+QUayAcYoiM2BthCjs+EBHVpjYjcuLDAiCWgeIX3X1Q==",
"license": "MIT",
"dependencies": {
"accepts": "~1.3.8",
"array-flatten": "1.1.1",
- "body-parser": "~1.20.3",
+ "body-parser": "~1.20.5",
"content-disposition": "~0.5.4",
"content-type": "~1.0.4",
"cookie": "~0.7.1",
@@ -2341,7 +2330,7 @@
"parseurl": "~1.3.3",
"path-to-regexp": "~0.1.12",
"proxy-addr": "~2.0.7",
- "qs": "~6.14.0",
+ "qs": "~6.15.1",
"range-parser": "~1.2.1",
"safe-buffer": "5.2.1",
"send": "~0.19.0",
@@ -2455,36 +2444,6 @@
"node": "^10.12.0 || >=12.0.0"
}
},
- "node_modules/filelist": {
- "version": "1.0.4",
- "resolved": "https://registry.npmjs.org/filelist/-/filelist-1.0.4.tgz",
- "integrity": "sha512-w1cEuf3S+DrLCQL7ET6kz+gmlJdbq9J7yXCSjK/OZCPA+qEN1WyF4ZAf0YYJa4/shHJra2t/d/r8SV4Ji+x+8Q==",
- "license": "Apache-2.0",
- "dependencies": {
- "minimatch": "^5.0.1"
- }
- },
- "node_modules/filelist/node_modules/brace-expansion": {
- "version": "2.1.0",
- "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.1.0.tgz",
- "integrity": "sha512-TN1kCZAgdgweJhWWpgKYrQaMNHcDULHkWwQIspdtjV4Y5aurRdZpjAqn6yX3FPqTA9ngHCc4hJxMAMgGfve85w==",
- "license": "MIT",
- "dependencies": {
- "balanced-match": "^1.0.0"
- }
- },
- "node_modules/filelist/node_modules/minimatch": {
- "version": "5.1.9",
- "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-5.1.9.tgz",
- "integrity": "sha512-7o1wEA2RyMP7Iu7GNba9vc0RWWGACJOCZBJX2GJWip0ikV+wcOsgVuY9uE8CPiyQhkGFSlhuSkZPavN7u1c2Fw==",
- "license": "ISC",
- "dependencies": {
- "brace-expansion": "^2.0.1"
- },
- "engines": {
- "node": ">=10"
- }
- },
"node_modules/fill-range": {
"version": "7.1.1",
"resolved": "https://registry.npmjs.org/fill-range/-/fill-range-7.1.1.tgz",
@@ -2891,6 +2850,7 @@
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz",
"integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==",
+ "dev": true,
"license": "MIT",
"engines": {
"node": ">=8"
@@ -3567,24 +3527,6 @@
"@pkgjs/parseargs": "^0.11.0"
}
},
- "node_modules/jake": {
- "version": "10.9.2",
- "resolved": "https://registry.npmjs.org/jake/-/jake-10.9.2.tgz",
- "integrity": "sha512-2P4SQ0HrLQ+fw6llpLnOaGAvN2Zu6778SJMrCUwns4fOoG9ayrTiZk3VV8sCPkVZF8ab0zksVpS8FDY5pRCNBA==",
- "license": "Apache-2.0",
- "dependencies": {
- "async": "^3.2.3",
- "chalk": "^4.0.2",
- "filelist": "^1.0.4",
- "minimatch": "^3.1.2"
- },
- "bin": {
- "jake": "bin/cli.js"
- },
- "engines": {
- "node": ">=10"
- }
- },
"node_modules/js-yaml": {
"version": "4.1.1",
"resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.1.1.tgz",
@@ -3856,6 +3798,7 @@
"version": "3.1.5",
"resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.5.tgz",
"integrity": "sha512-VgjWUsnnT6n+NUk6eZq77zeFdpW2LWDzP6zFGrCbHXiYNul5Dzqk2HHQ5uFH2DNW5Xbp8+jVzaeNt94ssEEl4w==",
+ "dev": true,
"license": "ISC",
"dependencies": {
"brace-expansion": "^1.1.7"
@@ -4215,6 +4158,25 @@
"node": ">= 0.4"
}
},
+ "node_modules/preact": {
+ "version": "10.29.2",
+ "resolved": "https://registry.npmjs.org/preact/-/preact-10.29.2.tgz",
+ "integrity": "sha512-7tNmwg/7mzzAoB/8kSg6Hl37JraAZw3Z3A0JSY7VXlZwo82Xn0G7wKbNNs2qoF4ZEEsQGTwDAroNdqKs1ofJxQ==",
+ "license": "MIT",
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/preact"
+ }
+ },
+ "node_modules/preact-render-to-string": {
+ "version": "6.7.0",
+ "resolved": "https://registry.npmjs.org/preact-render-to-string/-/preact-render-to-string-6.7.0.tgz",
+ "integrity": "sha512-Z4WR8fmLMRpdYqJ9i7vrlXSsSrxVJydwrkEXHapexfARbWfGb7vGcnvNQnIzN0cXciMVOlz/XLoiMCi9gUsy9Q==",
+ "license": "MIT",
+ "peerDependencies": {
+ "preact": ">=10 || >= 11.0.0-0"
+ }
+ },
"node_modules/prelude-ls": {
"version": "1.2.1",
"resolved": "https://registry.npmjs.org/prelude-ls/-/prelude-ls-1.2.1.tgz",
@@ -4264,9 +4226,9 @@
}
},
"node_modules/qs": {
- "version": "6.14.2",
- "resolved": "https://registry.npmjs.org/qs/-/qs-6.14.2.tgz",
- "integrity": "sha512-V/yCWTTF7VJ9hIh18Ugr2zhJMP01MY7c5kh4J870L7imm6/DIzBsNLTXzMwUA3yZ5b/KBqLx8Kp3uRvd7xSe3Q==",
+ "version": "6.15.2",
+ "resolved": "https://registry.npmjs.org/qs/-/qs-6.15.2.tgz",
+ "integrity": "sha512-Rzq0KEyX/w/tEybncDgdkZrJgVUsUMk3xjh3t5bv3S1HTAtg+uOYt72+ZfwiQwKdysThkTBdL/rTi6HDmX9Ddw==",
"license": "BSD-3-Clause",
"dependencies": {
"side-channel": "^1.1.0"
@@ -5077,6 +5039,7 @@
"version": "7.2.0",
"resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz",
"integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==",
+ "dev": true,
"license": "MIT",
"dependencies": {
"has-flag": "^4.0.0"
diff --git a/app/package.json b/app/package.json
index c44ee6a..a0540a1 100644
--- a/app/package.json
+++ b/app/package.json
@@ -1,6 +1,6 @@
{
"name": "immich-public-proxy",
- "version": "1.15.6",
+ "version": "2.0.2",
"scripts": {
"dev": "ts-node src/index.ts",
"build": "npx tsc",
@@ -21,8 +21,9 @@
"cookie-session": "^2.1.0",
"dayjs": "^1.11.13",
"dotenv": "^16.4.5",
- "ejs": "^3.1.10",
"express": "^4.21.1",
+ "preact": "^10.29.2",
+ "preact-render-to-string": "^6.7.0",
"tslib": "^2.8.1"
},
"devDependencies": {
diff --git a/app/public/fonts/Inter-LICENSE.txt b/app/public/fonts/Inter-LICENSE.txt
new file mode 100644
index 0000000..9b2ca37
--- /dev/null
+++ b/app/public/fonts/Inter-LICENSE.txt
@@ -0,0 +1,92 @@
+Copyright (c) 2016 The Inter Project Authors (https://github.com/rsms/inter)
+
+This Font Software is licensed under the SIL Open Font License, Version 1.1.
+This license is copied below, and is also available with a FAQ at:
+http://scripts.sil.org/OFL
+
+-----------------------------------------------------------
+SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
+-----------------------------------------------------------
+
+PREAMBLE
+The goals of the Open Font License (OFL) are to stimulate worldwide
+development of collaborative font projects, to support the font creation
+efforts of academic and linguistic communities, and to provide a free and
+open framework in which fonts may be shared and improved in partnership
+with others.
+
+The OFL allows the licensed fonts to be used, studied, modified and
+redistributed freely as long as they are not sold by themselves. The
+fonts, including any derivative works, can be bundled, embedded,
+redistributed and/or sold with any software provided that any reserved
+names are not used by derivative works. The fonts and derivatives,
+however, cannot be released under any other type of license. The
+requirement for fonts to remain under this license does not apply
+to any document created using the fonts or their derivatives.
+
+DEFINITIONS
+"Font Software" refers to the set of files released by the Copyright
+Holder(s) under this license and clearly marked as such. This may
+include source files, build scripts and documentation.
+
+"Reserved Font Name" refers to any names specified as such after the
+copyright statement(s).
+
+"Original Version" refers to the collection of Font Software components as
+distributed by the Copyright Holder(s).
+
+"Modified Version" refers to any derivative made by adding to, deleting,
+or substituting -- in part or in whole -- any of the components of the
+Original Version, by changing formats or by porting the Font Software to a
+new environment.
+
+"Author" refers to any designer, engineer, programmer, technical
+writer or other person who contributed to the Font Software.
+
+PERMISSION AND CONDITIONS
+Permission is hereby granted, free of charge, to any person obtaining
+a copy of the Font Software, to use, study, copy, merge, embed, modify,
+redistribute, and sell modified and unmodified copies of the Font
+Software, subject to the following conditions:
+
+1) Neither the Font Software nor any of its individual components,
+in Original or Modified Versions, may be sold by itself.
+
+2) Original or Modified Versions of the Font Software may be bundled,
+redistributed and/or sold with any software, provided that each copy
+contains the above copyright notice and this license. These can be
+included either as stand-alone text files, human-readable headers or
+in the appropriate machine-readable metadata fields within text or
+binary files as long as those fields can be easily viewed by the user.
+
+3) No Modified Version of the Font Software may use the Reserved Font
+Name(s) unless explicit written permission is granted by the corresponding
+Copyright Holder. This restriction only applies to the primary font name as
+presented to the users.
+
+4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
+Software shall not be used to promote, endorse or advertise any
+Modified Version, except to acknowledge the contribution(s) of the
+Copyright Holder(s) and the Author(s) or with their explicit written
+permission.
+
+5) The Font Software, modified or unmodified, in part or in whole,
+must be distributed entirely under this license, and must not be
+distributed under any other license. The requirement for fonts to
+remain under this license does not apply to any document created
+using the Font Software.
+
+TERMINATION
+This license becomes null and void if any of the above conditions are
+not met.
+
+DISCLAIMER
+THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
+OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
+COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
+INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
+DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
+OTHER DEALINGS IN THE FONT SOFTWARE.
diff --git a/app/public/fonts/inter-latin-wght-normal.woff2 b/app/public/fonts/inter-latin-wght-normal.woff2
new file mode 100644
index 0000000..d15208d
Binary files /dev/null and b/app/public/fonts/inter-latin-wght-normal.woff2 differ
diff --git a/app/public/fonts/lg.svg b/app/public/fonts/lg.svg
deleted file mode 100644
index fe8b075..0000000
--- a/app/public/fonts/lg.svg
+++ /dev/null
@@ -1,54 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/app/public/fonts/lg.ttf b/app/public/fonts/lg.ttf
deleted file mode 100644
index 825f483..0000000
Binary files a/app/public/fonts/lg.ttf and /dev/null differ
diff --git a/app/public/fonts/lg.woff b/app/public/fonts/lg.woff
deleted file mode 100644
index fd02a6f..0000000
Binary files a/app/public/fonts/lg.woff and /dev/null differ
diff --git a/app/public/fonts/lg.woff2 b/app/public/fonts/lg.woff2
deleted file mode 100644
index 2c2e289..0000000
Binary files a/app/public/fonts/lg.woff2 and /dev/null differ
diff --git a/app/public/images/download-all.svg b/app/public/images/download-all.svg
deleted file mode 100644
index d5a61e1..0000000
--- a/app/public/images/download-all.svg
+++ /dev/null
@@ -1 +0,0 @@
-
diff --git a/app/public/images/loading.gif b/app/public/images/loading.gif
deleted file mode 100644
index 4744c45..0000000
Binary files a/app/public/images/loading.gif and /dev/null differ
diff --git a/app/public/lg/lg-fullscreen.min.js b/app/public/lg/lg-fullscreen.min.js
deleted file mode 100644
index 92690fa..0000000
--- a/app/public/lg/lg-fullscreen.min.js
+++ /dev/null
@@ -1,8 +0,0 @@
-/**
- * lightgallery | 2.9.0 | October 1st 2025
- * http://www.lightgalleryjs.com/
- * Copyright (c) 2020 Sachin Neravath;
- * @license GPLv3
- */
-
-!function(e,l){"object"==typeof exports&&"undefined"!=typeof module?module.exports=l():"function"==typeof define&&define.amd?define(l):(e="undefined"!=typeof globalThis?globalThis:e||self).lgFullscreen=l()}(this,(function(){"use strict";var e=function(){return(e=Object.assign||function(e){for(var l,n=1,t=arguments.length;n',this.core.$toolbar.append(e),this.fullScreen()}},n.prototype.isFullScreen=function(){return document.fullscreenElement||document.mozFullScreenElement||document.webkitFullscreenElement||document.msFullscreenElement},n.prototype.requestFullscreen=function(){var e=document.documentElement;e.requestFullscreen?e.requestFullscreen():e.msRequestFullscreen?e.msRequestFullscreen():e.mozRequestFullScreen?e.mozRequestFullScreen():e.webkitRequestFullscreen&&e.webkitRequestFullscreen()},n.prototype.exitFullscreen=function(){document.exitFullscreen?document.exitFullscreen():document.msExitFullscreen?document.msExitFullscreen():document.mozCancelFullScreen?document.mozCancelFullScreen():document.webkitExitFullscreen&&document.webkitExitFullscreen()},n.prototype.fullScreen=function(){var e=this;this.$LG(document).on("fullscreenchange.lg.global"+this.core.lgId+" \n webkitfullscreenchange.lg.global"+this.core.lgId+" \n mozfullscreenchange.lg.global"+this.core.lgId+" \n MSFullscreenChange.lg.global"+this.core.lgId,(function(){e.core.lgOpened&&e.core.outer.toggleClass("lg-fullscreen-on")})),this.core.outer.find(".lg-fullscreen").first().on("click.lg",(function(){e.isFullScreen()?e.exitFullscreen():e.requestFullscreen()}))},n.prototype.closeGallery=function(){this.isFullScreen()&&this.exitFullscreen()},n.prototype.destroy=function(){this.$LG(document).off("fullscreenchange.lg.global"+this.core.lgId+" \n webkitfullscreenchange.lg.global"+this.core.lgId+" \n mozfullscreenchange.lg.global"+this.core.lgId+" \n MSFullscreenChange.lg.global"+this.core.lgId)},n}()}));
diff --git a/app/public/lg/lg-hash.min.js b/app/public/lg/lg-hash.min.js
deleted file mode 100644
index 4ab02cf..0000000
--- a/app/public/lg/lg-hash.min.js
+++ /dev/null
@@ -1,8 +0,0 @@
-/**
- * lightgallery | 2.9.0 | October 1st 2025
- * http://www.lightgalleryjs.com/
- * Copyright (c) 2020 Sachin Neravath;
- * @license GPLv3
- */
-
-!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e():"function"==typeof define&&define.amd?define(e):(t="undefined"!=typeof globalThis?globalThis:t||self).lgHash=e()}(this,(function(){"use strict";var t=function(){return(t=Object.assign||function(t){for(var e,i=1,o=arguments.length;i0){this.$LG(document.body).addClass("lg-from-hash");var e=this.getIndexFromUrl(t);return this.core.openGallery(e),!0}},s.prototype.onCloseAfter=function(){this.oldHash&&this.oldHash.indexOf("lg="+this.settings.galleryId)<0?history.replaceState?history.replaceState(null,"",this.oldHash):window.location.hash=this.oldHash:history.replaceState?history.replaceState(null,document.title,window.location.pathname+window.location.search):window.location.hash=""},s.prototype.onHashchange=function(){if(this.core.lgOpened){var t=window.location.hash,e=this.getIndexFromUrl(t);t.indexOf("lg="+this.settings.galleryId)>-1?this.core.slide(e,!1,!1):this.core.lGalleryOn&&this.core.closeGallery()}},s.prototype.closeGallery=function(){this.settings.hash&&this.$LG(document.body).removeClass("lg-from-hash")},s.prototype.destroy=function(){this.core.LGel.off(".lg.hash"),this.core.LGel.off(".hash"),this.$LG(window).off("hashchange.lg.hash.global"+this.core.lgId)},s}()}));
diff --git a/app/public/lg/lg-thumbnail.min.js b/app/public/lg/lg-thumbnail.min.js
deleted file mode 100644
index 1da9f21..0000000
--- a/app/public/lg/lg-thumbnail.min.js
+++ /dev/null
@@ -1,8 +0,0 @@
-/**
- * lightgallery | 2.9.0 | October 1st 2025
- * http://www.lightgalleryjs.com/
- * Copyright (c) 2020 Sachin Neravath;
- * @license GPLv3
- */
-
-!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e():"function"==typeof define&&define.amd?define(e):(t="undefined"!=typeof globalThis?globalThis:t||self).lgThumbnail=e()}(this,(function(){"use strict";var t=function(){return(t=Object.assign||function(t){for(var e,i=1,s=arguments.length;i\n \n
\n ';this.core.outer.addClass("lg-has-thumb"),".lg-components"===this.settings.appendThumbnailsTo?this.core.$lgComponents.append(e):this.core.outer.append(e),this.$thumbOuter=this.core.outer.find(".lg-thumb-outer").first(),this.$lgThumb=this.core.outer.find(".lg-thumb").first(),this.settings.animateThumb&&this.core.outer.find(".lg-thumb").css("transition-duration",this.core.settings.speed+"ms").css("width",this.thumbTotalWidth+"px").css("position","relative"),this.setThumbItemHtml(this.core.galleryItems)},o.prototype.enableThumbDrag=function(){var t=this,e={cords:{startX:0,endX:0},isMoved:!1,newTranslateX:0,startTime:new Date,endTime:new Date,touchMoveTime:0},i=!1;this.$thumbOuter.addClass("lg-grab"),this.core.outer.find(".lg-thumb").first().on("mousedown.lg.thumb",(function(s){t.thumbTotalWidth>t.thumbOuterWidth&&(s.preventDefault(),e.cords.startX=s.pageX,e.startTime=new Date,t.thumbClickable=!1,i=!0,t.core.outer.get().scrollLeft+=1,t.core.outer.get().scrollLeft-=1,t.$thumbOuter.removeClass("lg-grab").addClass("lg-grabbing"))})),this.$LG(window).on("mousemove.lg.thumb.global"+this.core.lgId,(function(s){t.core.lgOpened&&i&&(e.cords.endX=s.pageX,e=t.onThumbTouchMove(e))})),this.$LG(window).on("mouseup.lg.thumb.global"+this.core.lgId,(function(){t.core.lgOpened&&(e.isMoved?e=t.onThumbTouchEnd(e):t.thumbClickable=!0,i&&(i=!1,t.$thumbOuter.removeClass("lg-grabbing").addClass("lg-grab")))}))},o.prototype.enableThumbSwipe=function(){var t=this,e={cords:{startX:0,endX:0},isMoved:!1,newTranslateX:0,startTime:new Date,endTime:new Date,touchMoveTime:0};this.$lgThumb.on("touchstart.lg",(function(i){t.thumbTotalWidth>t.thumbOuterWidth&&(i.preventDefault(),e.cords.startX=i.targetTouches[0].pageX,t.thumbClickable=!1,e.startTime=new Date)})),this.$lgThumb.on("touchmove.lg",(function(i){t.thumbTotalWidth>t.thumbOuterWidth&&(i.preventDefault(),e.cords.endX=i.targetTouches[0].pageX,e=t.onThumbTouchMove(e))})),this.$lgThumb.on("touchend.lg",(function(){e.isMoved?e=t.onThumbTouchEnd(e):t.thumbClickable=!0}))},o.prototype.rebuildThumbnails=function(){var t=this;this.$thumbOuter.addClass("lg-rebuilding-thumbnails"),setTimeout((function(){t.thumbTotalWidth=t.core.galleryItems.length*(t.settings.thumbWidth+t.settings.thumbMargin),t.$lgThumb.css("width",t.thumbTotalWidth+"px"),t.$lgThumb.empty(),t.setThumbItemHtml(t.core.galleryItems),t.animateThumb(t.core.index)}),50),setTimeout((function(){t.$thumbOuter.removeClass("lg-rebuilding-thumbnails")}),200)},o.prototype.setTranslate=function(t){this.$lgThumb.css("transform","translate3d(-"+t+"px, 0px, 0px)")},o.prototype.getPossibleTransformX=function(t){return t>this.thumbTotalWidth-this.thumbOuterWidth&&(t=this.thumbTotalWidth-this.thumbOuterWidth),t<0&&(t=0),t},o.prototype.animateThumb=function(t){if(this.$lgThumb.css("transition-duration",this.core.settings.speed+"ms"),this.settings.animateThumb){var e=0;switch(this.settings.currentPagerPosition){case"left":e=0;break;case"middle":e=this.thumbOuterWidth/2-this.settings.thumbWidth/2;break;case"right":e=this.thumbOuterWidth-this.settings.thumbWidth}this.translateX=(this.settings.thumbWidth+this.settings.thumbMargin)*t-1-e,this.translateX>this.thumbTotalWidth-this.thumbOuterWidth&&(this.translateX=this.thumbTotalWidth-this.thumbOuterWidth),this.translateX<0&&(this.translateX=0),this.setTranslate(this.translateX)}},o.prototype.onThumbTouchMove=function(t){return t.newTranslateX=this.translateX,t.isMoved=!0,t.touchMoveTime=(new Date).valueOf(),t.newTranslateX-=t.cords.endX-t.cords.startX,t.newTranslateX=this.getPossibleTransformX(t.newTranslateX),this.setTranslate(t.newTranslateX),this.$thumbOuter.addClass("lg-dragging"),t},o.prototype.onThumbTouchEnd=function(t){t.isMoved=!1,t.endTime=new Date,this.$thumbOuter.removeClass("lg-dragging");var e=t.endTime.valueOf()-t.startTime.valueOf(),i=t.cords.endX-t.cords.startX,s=Math.abs(i)/e;return s>.15&&t.endTime.valueOf()-t.touchMoveTime<30?((s+=1)>2&&(s+=1),s+=s*(Math.abs(i)/this.thumbOuterWidth),this.$lgThumb.css("transition-duration",Math.min(s-1,2)+"settings"),i*=s,this.translateX=this.getPossibleTransformX(this.translateX-i),this.setTranslate(this.translateX)):this.translateX=t.newTranslateX,Math.abs(t.cords.endX-t.cords.startX)'),this.core.outer.find(".lg-toggle-thumb").first().on("click.lg",(function(){t.core.outer.toggleClass("lg-components-open")})))},o.prototype.thumbKeyPress=function(){var t=this;this.$LG(window).on("keydown.lg.thumb.global"+this.core.lgId,(function(e){t.core.lgOpened&&t.settings.toggleThumb&&(38===e.keyCode?(e.preventDefault(),t.core.outer.addClass("lg-components-open")):40===e.keyCode&&(e.preventDefault(),t.core.outer.removeClass("lg-components-open")))}))},o.prototype.destroy=function(){this.settings.thumbnail&&(this.$LG(window).off(".lg.thumb.global"+this.core.lgId),this.core.LGel.off(".lg.thumb"),this.core.LGel.off(".thumb"),this.$thumbOuter.remove(),this.core.outer.removeClass("lg-has-thumb"))},o}()}));
diff --git a/app/public/lg/lg-video.min.js b/app/public/lg/lg-video.min.js
deleted file mode 100644
index 5e3c5fa..0000000
--- a/app/public/lg/lg-video.min.js
+++ /dev/null
@@ -1,8 +0,0 @@
-/**
- * lightgallery | 2.9.0 | October 1st 2025
- * http://www.lightgalleryjs.com/
- * Copyright (c) 2020 Sachin Neravath;
- * @license GPLv3
- */
-
-!function(e,o){"object"==typeof exports&&"undefined"!=typeof module?module.exports=o():"function"==typeof define&&define.amd?define(o):(e="undefined"!=typeof globalThis?globalThis:e||self).lgVideo=o()}(this,(function(){"use strict";var e=function(){return(e=Object.assign||function(e){for(var o,i=1,t=arguments.length;i"}else if(n.vimeo){u="lg-vimeo"+i;var h=function(e,o){if(!o||!o.vimeo)return"";var i=o.vimeo[2]||"",t=Object.assign({},{autoplay:0,muted:1},e),s=t&&0!==Object.keys(t).length?r(t):"",n=((o.vimeo[0].split("/").pop()||"").split("?")[0]||"").split("#")[0],l=o.vimeo[1]!==n;l&&(i=i.replace("/"+n,""));var d=l?"h="+n:"";return"?"+d+(s=d?"&"+s:s)+("?"==i[0]?"&"+i.slice(1):i||"")}(this.settings.vimeoPlayerParams,n);s='"}else if(n.wistia){var g="lg-wistia"+i;h=(h=r(this.settings.wistiaPlayerParams))?"?"+h:"",s='"}else if(n.html5){for(var p="",y=0;y"}if(t.tracks){var w=function(e){var o="",i=t.tracks[e];Object.keys(i||{}).forEach((function(e){o+=e+'="'+i[e]+'" '})),p+=""};for(y=0;y\n "+p+"\n Your browser does not support HTML5 video.\n "}return s},a.prototype.appendVideos=function(e,o){var i,t=this.getVideoHtml(o.src,o.addClass,o.index,o.html5Video);e.find(".lg-video-cont").append(t);var s=e.find(".lg-video-object").first();if(o.html5Video&&s.on("mousedown.lg.video",(function(e){e.stopPropagation()})),this.settings.videojs&&(null===(i=this.core.galleryItems[o.index].__slideVideoInfo)||void 0===i?void 0:i.html5))try{return videojs(s.get(),this.settings.videojsOptions)}catch(e){console.error("lightGallery:- Make sure you have included videojs")}},a.prototype.gotoNextSlideOnVideoEnd=function(e,o){var i=this,t=this.core.getSlideItem(o).find(".lg-video-object").first(),s=this.core.galleryItems[o].__slideVideoInfo||{};if(this.settings.gotoNextSlideOnVideoEnd)if(s.html5)t.on("ended",(function(){i.core.goToNextSlide()}));else if(s.vimeo)try{new Vimeo.Player(t.get()).on("ended",(function(){i.core.goToNextSlide()}))}catch(e){console.error("lightGallery:- Make sure you have included //github.com/vimeo/player.js")}else if(s.wistia)try{window._wq=window._wq||[],window._wq.push({id:t.attr("id"),onReady:function(e){e.bind("end",(function(){i.core.goToNextSlide()}))}})}catch(e){console.error("lightGallery:- Make sure you have included //fast.wistia.com/assets/external/E-v1.js")}},a.prototype.controlVideo=function(e,o){var i=this.core.getSlideItem(e).find(".lg-video-object").first(),t=this.core.galleryItems[e].__slideVideoInfo||{};if(i.get())if(t.youtube)try{i.get().contentWindow.postMessage('{"event":"command","func":"'+o+'Video","args":""}',"*")}catch(e){console.error("lightGallery:- "+e)}else if(t.vimeo)try{new Vimeo.Player(i.get())[o]()}catch(e){console.error("lightGallery:- Make sure you have included //github.com/vimeo/player.js")}else if(t.html5)if(this.settings.videojs)try{videojs(i.get())[o]()}catch(e){console.error("lightGallery:- Make sure you have included videojs")}else i.get()[o]();else if(t.wistia)try{window._wq=window._wq||[],window._wq.push({id:i.attr("id"),onReady:function(e){e[o]()}})}catch(e){console.error("lightGallery:- Make sure you have included //fast.wistia.com/assets/external/E-v1.js")}},a.prototype.loadVideoOnPosterClick=function(e,o){var i=this;if(e.hasClass("lg-video-loaded"))o&&this.playVideo(this.core.index);else if(e.hasClass("lg-has-video"))this.playVideo(this.core.index);else{e.addClass("lg-has-video");var t=void 0,s=this.core.galleryItems[this.core.index].src,n=this.core.galleryItems[this.core.index].video;n&&(t="string"==typeof n?JSON.parse(n):n);var l=this.appendVideos(e,{src:s,addClass:"",index:this.core.index,html5Video:t});this.gotoNextSlideOnVideoEnd(s,this.core.index);var r=e.find(".lg-object").first().get();e.find(".lg-video-cont").first().append(r),e.addClass("lg-video-loading"),l&&l.ready((function(){l.on("loadedmetadata",(function(){i.onVideoLoadAfterPosterClick(e,i.core.index)}))})),e.find(".lg-video-object").first().on("load.lg error.lg loadedmetadata.lg",(function(){setTimeout((function(){i.onVideoLoadAfterPosterClick(e,i.core.index)}),50)}))}},a.prototype.onVideoLoadAfterPosterClick=function(e,o){e.addClass("lg-video-loaded"),this.playVideo(o)},a.prototype.destroy=function(){this.core.LGel.off(".lg.video"),this.core.LGel.off(".video")},a}()}));
diff --git a/app/public/lg/lg-zoom.min.js b/app/public/lg/lg-zoom.min.js
deleted file mode 100644
index 5c2ef8d..0000000
--- a/app/public/lg/lg-zoom.min.js
+++ /dev/null
@@ -1,8 +0,0 @@
-/**
- * lightgallery | 2.9.0 | October 1st 2025
- * http://www.lightgalleryjs.com/
- * Copyright (c) 2020 Sachin Neravath;
- * @license GPLv3
- */
-
-!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e="undefined"!=typeof globalThis?globalThis:e||self).lgZoom=t()}(this,(function(){"use strict";var e=function(){return(e=Object.assign||function(e){for(var t,o=1,i=arguments.length;o ':"";this.settings.actualSize&&(e+=' '),this.core.outer.addClass("lg-use-transition-for-zoom"),this.core.$toolbar.first().append(e)},h.prototype.enableZoom=function(e){var t=this,o=this.settings.enableZoomAfter+e.detail.delay;this.$LG("body").first().hasClass("lg-from-hash")&&e.detail.delay?o=0:this.$LG("body").first().removeClass("lg-from-hash"),this.zoomableTimeout=setTimeout((function(){t.isImageSlide(t.core.index)&&(t.core.getSlideItem(e.detail.index).addClass("lg-zoomable"),e.detail.index===t.core.index&&t.setZoomEssentials())}),o+30)},h.prototype.enableZoomOnSlideItemLoad=function(){this.core.LGel.on(a+".zoom",this.enableZoom.bind(this))},h.prototype.getDragCords=function(e){return{x:e.pageX,y:e.pageY}},h.prototype.getSwipeCords=function(e){return{x:e.touches[0].pageX,y:e.touches[0].pageY}},h.prototype.getDragAllowedAxises=function(e,t){if(!this.containerRect)return{allowX:!1,allowY:!1};var o=this.core.getSlideItem(this.core.index).find(".lg-image").first().get(),i=0,s=0,a=o.getBoundingClientRect();e?(i=o.offsetHeight*e,s=o.offsetWidth*e):t?(i=a.height+t*a.height,s=a.width+t*a.width):(i=a.height,s=a.width);var n=i>this.containerRect.height;return{allowX:s>this.containerRect.width,allowY:n}},h.prototype.setZoomEssentials=function(){this.containerRect=this.core.$content.get().getBoundingClientRect()},h.prototype.zoomImage=function(e,t,o,i){if(this.containerRect&&!(Math.abs(t)<=0)){var s,a,n=this.containerRect.width/2+this.containerRect.left,r=this.containerRect.height/2+this.containerRect.top+this.scrollTop;1===e&&(this.positionChanged=!1);var l=this.getDragAllowedAxises(0,t),c=l.allowY,g=l.allowX;this.positionChanged&&(s=this.left/(this.scale-t),a=this.top/(this.scale-t),this.pageX=n-s,this.pageY=r-a,this.positionChanged=!1);var h,m,u=this.getPossibleSwipeDragCords(t),d=n-this.pageX,f=r-this.pageY;if(e-t>1){var p=(e-t)/Math.abs(t);h=(d=(t<0?-d:d)+this.left*(p+(t<0?-1:1)))/p,m=(f=(t<0?-f:f)+this.top*(p+(t<0?-1:1)))/p}else{h=d*(p=(e-t)*t),m=f*p}o&&(g?this.isBeyondPossibleLeft(h,u.minX)?h=u.minX:this.isBeyondPossibleRight(h,u.maxX)&&(h=u.maxX):e>1&&(hu.maxX&&(h=u.maxX)),c?this.isBeyondPossibleTop(m,u.minY)?m=u.minY:this.isBeyondPossibleBottom(m,u.maxY)&&(m=u.maxY):e>1&&(mu.maxY&&(m=u.maxY))),this.setZoomStyles({x:h,y:m,scale:e}),this.left=h,this.top=m,i&&this.setZoomImageSize()}},h.prototype.resetImageTranslate=function(e){if(this.isImageSlide(e)){var t=this.core.getSlideItem(e).find(".lg-image").first();this.imageReset=!1,t.removeClass("reset-transition reset-transition-y reset-transition-x"),this.core.outer.removeClass("lg-actual-size"),t.css("width","auto").css("height","auto"),setTimeout((function(){t.removeClass("no-transition")}),10)}},h.prototype.setZoomImageSize=function(){var e=this,t=this.core.getSlideItem(this.core.index).find(".lg-image").first();setTimeout((function(){var o=e.getCurrentImageActualSizeScale();e.scale>=o&&(t.addClass("no-transition"),e.imageReset=!0)}),500),setTimeout((function(){var o=e.getCurrentImageActualSizeScale();if(e.scale>=o){var i=e.getDragAllowedAxises(e.scale);t.css("width",t.get().naturalWidth+"px").css("height",t.get().naturalHeight+"px"),e.core.outer.addClass("lg-actual-size"),i.allowX&&i.allowY?t.addClass("reset-transition"):i.allowX&&!i.allowY?t.addClass("reset-transition-x"):!i.allowX&&i.allowY&&t.addClass("reset-transition-y")}}),550)},h.prototype.setZoomStyles=function(e){var t=this.core.getSlideItem(this.core.index).find(".lg-img-wrap").first(),o=this.core.getSlideItem(this.core.index).find(".lg-image").first(),i=this.core.outer.find(".lg-current .lg-dummy-img").first();this.scale=e.scale,o.css("transform","scale3d("+e.scale+", "+e.scale+", 1)"),i.css("transform","scale3d("+e.scale+", "+e.scale+", 1)");var s="translate3d("+e.x+"px, "+e.y+"px, 0)";t.css("transform",s)},h.prototype.setActualSize=function(e,t){var o=this;if(!this.zoomInProgress){this.zoomInProgress=!0;var i=this.core.galleryItems[this.core.index];this.resetImageTranslate(e),setTimeout((function(){if(i.src&&!o.core.outer.hasClass("lg-first-slide-loading")){var e=o.getCurrentImageActualSizeScale(),s=o.scale;o.core.outer.hasClass("lg-zoomed")?o.scale=1:o.scale=o.getScale(e),o.setPageCords(t),o.beginZoom(o.scale),o.zoomImage(o.scale,o.scale-s,!0,!0)}}),50),setTimeout((function(){o.core.outer.removeClass("lg-grabbing").addClass("lg-grab")}),60),setTimeout((function(){o.zoomInProgress=!1}),610)}},h.prototype.getNaturalWidth=function(e){var t=this.core.getSlideItem(e).find(".lg-image").first(),o=this.core.galleryItems[e].width;return o?parseFloat(o):t.get().naturalWidth},h.prototype.getActualSizeScale=function(e,t){return e>=t?e/t||2:1},h.prototype.getCurrentImageActualSizeScale=function(){var e=this.core.getSlideItem(this.core.index).find(".lg-image").first().get().offsetWidth,t=this.getNaturalWidth(this.core.index)||e;return this.getActualSizeScale(t,e)},h.prototype.getPageCords=function(e){var t={};if(e)t.x=e.pageX||e.touches[0].pageX,t.y=e.pageY||e.touches[0].pageY;else{var o=this.core.$content.get().getBoundingClientRect();t.x=o.width/2+o.left,t.y=o.height/2+this.scrollTop+o.top}return t},h.prototype.setPageCords=function(e){var t=this.getPageCords(e);this.pageX=t.x,this.pageY=t.y},h.prototype.manageActualPixelClassNames=function(){this.core.getElementById("lg-actual-size").removeClass(this.settings.actualSizeIcons.zoomIn).addClass(this.settings.actualSizeIcons.zoomOut)},h.prototype.beginZoom=function(e){return this.core.outer.removeClass("lg-zoom-drag-transition lg-zoom-dragging"),e>1?(this.core.outer.addClass("lg-zoomed"),this.manageActualPixelClassNames()):this.resetZoom(),e>1},h.prototype.getScale=function(e){var t=this.getCurrentImageActualSizeScale();return e<1?e=1:e>t&&(e=t),e},h.prototype.init=function(){var e=this;if(this.settings.zoom){this.buildTemplates(),this.enableZoomOnSlideItemLoad();var t=null;this.core.outer.on("dblclick.lg",(function(t){e.$LG(t.target).hasClass("lg-image")&&e.setActualSize(e.core.index,t)})),this.core.outer.on("touchstart.lg",(function(o){var i=e.$LG(o.target);1===o.touches.length&&i.hasClass("lg-image")&&(t?(clearTimeout(t),t=null,o.preventDefault(),e.setActualSize(e.core.index,o)):t=setTimeout((function(){t=null}),300))})),this.core.LGel.on(o+".zoom "+l+".zoom "+r+".zoom "+c+".zoom "+g+".zoom",(function(){if(e.core.lgOpened&&e.isImageSlide(e.core.index)&&!e.core.touchAction){var t=e.core.getSlideItem(e.core.index).find(".lg-img-wrap").first();e.top=0,e.left=0,e.setZoomEssentials(),e.setZoomSwipeStyles(t,{x:0,y:0}),e.positionChanged=!0}})),this.$LG(window).on("scroll.lg.zoom.global"+this.core.lgId,(function(){e.core.lgOpened&&(e.scrollTop=e.$LG(window).scrollTop())})),this.core.getElementById("lg-zoom-out").on("click.lg",(function(){if(e.isImageSlide(e.core.index)){var t=0;e.imageReset&&(e.resetImageTranslate(e.core.index),t=50),setTimeout((function(){var t=e.scale-e.settings.scale;t<1&&(t=1),e.beginZoom(t),e.zoomImage(t,-e.settings.scale,!0,!e.settings.infiniteZoom)}),t)}})),this.core.getElementById("lg-zoom-in").on("click.lg",(function(){e.zoomIn()})),this.core.getElementById("lg-actual-size").on("click.lg",(function(){e.setActualSize(e.core.index)})),this.core.LGel.on(i+".zoom",(function(){e.core.outer.find(".lg-item").removeClass("lg-zoomable")})),this.core.LGel.on(s+".zoom",(function(){e.scrollTop=e.$LG(window).scrollTop(),e.pageX=e.core.outer.width()/2,e.pageY=e.core.outer.height()/2+e.scrollTop,e.scale=1})),this.core.LGel.on(n+".zoom",(function(t){var o=t.detail.prevIndex;e.scale=1,e.positionChanged=!1,e.zoomInProgress=!1,e.resetZoom(o),e.resetImageTranslate(o),e.isImageSlide(e.core.index)&&e.setZoomEssentials()})),this.zoomDrag(),this.pinchZoom(),this.zoomSwipe(),this.zoomableTimeout=!1,this.positionChanged=!1,this.zoomInProgress=!1}},h.prototype.zoomIn=function(){if(this.isImageSlide(this.core.index)){var e=this.scale+this.settings.scale;this.settings.infiniteZoom||(e=this.getScale(e)),this.beginZoom(e),this.zoomImage(e,Math.min(this.settings.scale,e-this.scale),!0,!this.settings.infiniteZoom)}},h.prototype.resetZoom=function(e){this.core.outer.removeClass("lg-zoomed lg-zoom-drag-transition");var t=this.core.getElementById("lg-actual-size"),o=this.core.getSlideItem(void 0!==e?e:this.core.index);t.removeClass(this.settings.actualSizeIcons.zoomOut).addClass(this.settings.actualSizeIcons.zoomIn),o.find(".lg-img-wrap").first().removeAttr("style"),o.find(".lg-image").first().removeAttr("style"),this.scale=1,this.left=0,this.top=0,this.setPageCords()},h.prototype.getTouchDistance=function(e){return Math.sqrt((e.touches[0].pageX-e.touches[1].pageX)*(e.touches[0].pageX-e.touches[1].pageX)+(e.touches[0].pageY-e.touches[1].pageY)*(e.touches[0].pageY-e.touches[1].pageY))},h.prototype.pinchZoom=function(){var e=this,t=0,o=!1,i=1,s=0,a=this.core.getSlideItem(this.core.index);this.core.outer.on("touchstart.lg",(function(o){if(a=e.core.getSlideItem(e.core.index),e.isImageSlide(e.core.index)&&2===o.touches.length){if(o.preventDefault(),e.core.outer.hasClass("lg-first-slide-loading"))return;i=e.scale||1,e.core.outer.removeClass("lg-zoom-drag-transition lg-zoom-dragging"),e.setPageCords(o),e.resetImageTranslate(e.core.index),e.core.touchAction="pinch",t=e.getTouchDistance(o)}})),this.core.$inner.on("touchmove.lg",(function(n){if(2===n.touches.length&&"pinch"===e.core.touchAction&&(e.$LG(n.target).hasClass("lg-item")||a.get().contains(n.target))){n.preventDefault();var r=e.getTouchDistance(n),l=t-r;if(!o&&Math.abs(l)>5&&(o=!0),o){s=e.scale;var c=Math.max(1,i+.02*-l);e.scale=Math.round(100*(c+Number.EPSILON))/100;var g=e.scale-s;e.zoomImage(e.scale,Math.round(100*(g+Number.EPSILON))/100,!1,!1)}}})),this.core.$inner.on("touchend.lg",(function(i){if("pinch"===e.core.touchAction&&(e.$LG(i.target).hasClass("lg-item")||a.get().contains(i.target))){if(o=!1,t=0,e.scale<=1)e.resetZoom();else{var s=e.getCurrentImageActualSizeScale();if(e.scale>=s){var n=s-e.scale;0===n&&(n=.01),e.zoomImage(s,n,!1,!0)}e.manageActualPixelClassNames(),e.core.outer.addClass("lg-zoomed")}e.core.touchAction=void 0}}))},h.prototype.touchendZoom=function(e,t,o,i,s){var a=t.x-e.x,n=t.y-e.y,r=Math.abs(a)/s+1,l=Math.abs(n)/s+1;r>2&&(r+=1),l>2&&(l+=1),a*=r,n*=l;var c=this.core.getSlideItem(this.core.index).find(".lg-img-wrap").first(),g={};g.x=this.left+a,g.y=this.top+n;var h=this.getPossibleSwipeDragCords();(Math.abs(a)>15||Math.abs(n)>15)&&(i&&(this.isBeyondPossibleTop(g.y,h.minY)?g.y=h.minY:this.isBeyondPossibleBottom(g.y,h.maxY)&&(g.y=h.maxY)),o&&(this.isBeyondPossibleLeft(g.x,h.minX)?g.x=h.minX:this.isBeyondPossibleRight(g.x,h.maxX)&&(g.x=h.maxX)),i?this.top=g.y:g.y=this.top,o?this.left=g.x:g.x=this.left,this.setZoomSwipeStyles(c,g),this.positionChanged=!0)},h.prototype.getZoomSwipeCords=function(e,t,o,i,s){var a={};if(i){if(a.y=this.top+(t.y-e.y),this.isBeyondPossibleTop(a.y,s.minY)){var n=s.minY-a.y;a.y=s.minY-n/6}else if(this.isBeyondPossibleBottom(a.y,s.maxY)){var r=a.y-s.maxY;a.y=s.maxY+r/6}}else a.y=this.top;if(o){if(a.x=this.left+(t.x-e.x),this.isBeyondPossibleLeft(a.x,s.minX)){var l=s.minX-a.x;a.x=s.minX-l/6}else if(this.isBeyondPossibleRight(a.x,s.maxX)){var c=a.x-s.maxX;a.x=s.maxX+c/6}}else a.x=this.left;return a},h.prototype.isBeyondPossibleLeft=function(e,t){return e>=t},h.prototype.isBeyondPossibleRight=function(e,t){return e<=t},h.prototype.isBeyondPossibleTop=function(e,t){return e>=t},h.prototype.isBeyondPossibleBottom=function(e,t){return e<=t},h.prototype.isImageSlide=function(e){var t=this.core.galleryItems[e];return"image"===this.core.getSlideType(t)},h.prototype.getPossibleSwipeDragCords=function(e){var t=this.core.getSlideItem(this.core.index).find(".lg-image").first(),o=this.core.mediaContainerPosition.bottom,i=t.get().getBoundingClientRect(),s=i.height,a=i.width;return e&&(s+=e*s,a+=e*a),{minY:(s-this.containerRect.height)/2,maxY:(this.containerRect.height-s)/2+o,minX:(a-this.containerRect.width)/2,maxX:(this.containerRect.width-a)/2}},h.prototype.setZoomSwipeStyles=function(e,t){e.css("transform","translate3d("+t.x+"px, "+t.y+"px, 0)")},h.prototype.zoomSwipe=function(){var e,t,o=this,i={},s={},a=!1,n=!1,r=!1,l=new Date,c=(new Date,this.core.getSlideItem(this.core.index));this.core.$inner.on("touchstart.lg",(function(s){if(o.isImageSlide(o.core.index)&&(c=o.core.getSlideItem(o.core.index),(o.$LG(s.target).hasClass("lg-item")||c.get().contains(s.target))&&1===s.touches.length&&o.core.outer.hasClass("lg-zoomed"))){s.preventDefault(),l=new Date,o.core.touchAction="zoomSwipe",t=o.core.getSlideItem(o.core.index).find(".lg-img-wrap").first();var a=o.getDragAllowedAxises(0);r=a.allowY,((n=a.allowX)||r)&&(i=o.getSwipeCords(s)),e=o.getPossibleSwipeDragCords(),o.core.outer.addClass("lg-zoom-dragging lg-zoom-drag-transition")}})),this.core.$inner.on("touchmove.lg",(function(l){if(1===l.touches.length&&"zoomSwipe"===o.core.touchAction&&(o.$LG(l.target).hasClass("lg-item")||c.get().contains(l.target))){l.preventDefault(),o.core.touchAction="zoomSwipe",s=o.getSwipeCords(l);var g=o.getZoomSwipeCords(i,s,n,r,e);(Math.abs(s.x-i.x)>15||Math.abs(s.y-i.y)>15)&&(a=!0,o.setZoomSwipeStyles(t,g))}})),this.core.$inner.on("touchend.lg",(function(e){if("zoomSwipe"===o.core.touchAction&&(o.$LG(e.target).hasClass("lg-item")||c.get().contains(e.target))){if(e.preventDefault(),o.core.touchAction=void 0,o.core.outer.removeClass("lg-zoom-dragging"),!a)return;a=!1;var t=(new Date).valueOf()-l.valueOf();o.touchendZoom(i,s,n,r,t)}}))},h.prototype.zoomDrag=function(){var e,t,o,i,s=this,a={},n={},r=!1,l=!1,c=!1,g=!1;this.core.outer.on("mousedown.lg.zoom",(function(t){if(s.isImageSlide(s.core.index)){var n=s.core.getSlideItem(s.core.index);if(s.$LG(t.target).hasClass("lg-item")||n.get().contains(t.target)){e=new Date,i=s.core.getSlideItem(s.core.index).find(".lg-img-wrap").first();var l=s.getDragAllowedAxises(0);g=l.allowY,c=l.allowX,s.core.outer.hasClass("lg-zoomed")&&s.$LG(t.target).hasClass("lg-object")&&(c||g)&&(t.preventDefault(),a=s.getDragCords(t),o=s.getPossibleSwipeDragCords(),r=!0,s.core.outer.removeClass("lg-grab").addClass("lg-grabbing lg-zoom-drag-transition lg-zoom-dragging"))}}})),this.$LG(window).on("mousemove.lg.zoom.global"+this.core.lgId,(function(e){if(r){l=!0,n=s.getDragCords(e);var t=s.getZoomSwipeCords(a,n,c,g,o);s.setZoomSwipeStyles(i,t)}})),this.$LG(window).on("mouseup.lg.zoom.global"+this.core.lgId,(function(o){if(r){if(t=new Date,r=!1,s.core.outer.removeClass("lg-zoom-dragging"),l&&(a.x!==n.x||a.y!==n.y)){n=s.getDragCords(o);var i=t.valueOf()-e.valueOf();s.touchendZoom(a,n,c,g,i)}l=!1}s.core.outer.removeClass("lg-grabbing").addClass("lg-grab")}))},h.prototype.closeGallery=function(){this.resetZoom(),this.zoomInProgress=!1},h.prototype.destroy=function(){this.$LG(window).off(".lg.zoom.global"+this.core.lgId),this.core.LGel.off(".lg.zoom"),this.core.LGel.off(".zoom"),clearTimeout(this.zoomableTimeout),this.zoomableTimeout=!1},h}()}));
diff --git a/app/public/lg/lightgallery-bundle.min.css b/app/public/lg/lightgallery-bundle.min.css
deleted file mode 100644
index da7c3ce..0000000
--- a/app/public/lg/lightgallery-bundle.min.css
+++ /dev/null
@@ -1 +0,0 @@
-@font-face{font-family:lg;src:url(../fonts/lg.woff2?io9a6k) format("woff2"),url(../fonts/lg.ttf?io9a6k) format("truetype"),url(../fonts/lg.woff?io9a6k) format("woff"),url(../fonts/lg.svg?io9a6k#lg) format("svg");font-weight:400;font-style:normal;font-display:block}.lg-icon{font-family:lg!important;speak:never;font-style:normal;font-weight:400;font-variant:normal;text-transform:none;line-height:1;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale}.lg-container{font-family:system-ui,-apple-system,"Segoe UI",Roboto,"Helvetica Neue",Arial,"Noto Sans","Liberation Sans",sans-serif,"Apple Color Emoji","Segoe UI Emoji","Segoe UI Symbol","Noto Color Emoji"}.lg-next,.lg-prev{background-color:rgba(0,0,0,.45);border-radius:2px;color:#999;cursor:pointer;display:block;font-size:22px;margin-top:-10px;padding:8px 10px 9px;position:absolute;top:50%;z-index:1084;outline:0;border:none}.lg-next.disabled,.lg-prev.disabled{opacity:0!important;cursor:default}.lg-next:hover:not(.disabled),.lg-prev:hover:not(.disabled){color:#fff}.lg-single-item .lg-next,.lg-single-item .lg-prev{display:none}.lg-next{right:20px}.lg-next:before{content:"\e095"}.lg-prev{left:20px}.lg-prev:after{content:"\e094"}@-webkit-keyframes lg-right-end{0%{left:0}50%{left:-30px}100%{left:0}}@-moz-keyframes lg-right-end{0%{left:0}50%{left:-30px}100%{left:0}}@-ms-keyframes lg-right-end{0%{left:0}50%{left:-30px}100%{left:0}}@keyframes lg-right-end{0%{left:0}50%{left:-30px}100%{left:0}}@-webkit-keyframes lg-left-end{0%{left:0}50%{left:30px}100%{left:0}}@-moz-keyframes lg-left-end{0%{left:0}50%{left:30px}100%{left:0}}@-ms-keyframes lg-left-end{0%{left:0}50%{left:30px}100%{left:0}}@keyframes lg-left-end{0%{left:0}50%{left:30px}100%{left:0}}.lg-outer.lg-right-end .lg-object{-webkit-animation:lg-right-end .3s;-o-animation:lg-right-end .3s;animation:lg-right-end .3s;position:relative}.lg-outer.lg-left-end .lg-object{-webkit-animation:lg-left-end .3s;-o-animation:lg-left-end .3s;animation:lg-left-end .3s;position:relative}.lg-toolbar{z-index:1082;left:0;position:absolute;top:0;width:100%}.lg-media-overlap .lg-toolbar{background-image:linear-gradient(0deg,rgba(0,0,0,0),rgba(0,0,0,.4))}.lg-toolbar .lg-icon{color:#999;cursor:pointer;float:right;font-size:24px;height:47px;line-height:27px;padding:10px 0;text-align:center;width:50px;text-decoration:none!important;outline:medium none;will-change:color;-webkit-transition:color .2s linear;-o-transition:color .2s linear;transition:color .2s linear;background:0 0;border:none;box-shadow:none}.lg-toolbar .lg-icon.lg-icon-18{font-size:18px}.lg-toolbar .lg-icon:hover{color:#fff}.lg-toolbar .lg-close:after{content:"\e070"}.lg-toolbar .lg-maximize{font-size:22px}.lg-toolbar .lg-maximize:after{content:"\e90a"}.lg-toolbar .lg-download:after{content:"\e0f2"}.lg-sub-html{color:#eee;font-size:16px;padding:10px 40px;text-align:center;z-index:1080;opacity:0;-webkit-transition:opacity .2s ease-out 0s;-o-transition:opacity .2s ease-out 0s;transition:opacity .2s ease-out 0s}.lg-sub-html h4{margin:0;font-size:13px;font-weight:700}.lg-sub-html p{font-size:12px;margin:5px 0 0}.lg-sub-html a{color:inherit}.lg-sub-html a:hover{text-decoration:underline}.lg-media-overlap .lg-sub-html{background-image:linear-gradient(180deg,rgba(0,0,0,0),rgba(0,0,0,.6))}.lg-item .lg-sub-html{position:absolute;bottom:0;right:0;left:0}.lg-error-msg{font-size:14px;color:#999}.lg-counter{color:#999;display:inline-block;font-size:16px;padding-left:20px;padding-top:12px;height:47px;vertical-align:middle}.lg-closing .lg-next,.lg-closing .lg-prev,.lg-closing .lg-sub-html,.lg-closing .lg-toolbar{opacity:0;-webkit-transition:-webkit-transform .08 cubic-bezier(0,0,.25,1) 0s,opacity .08 cubic-bezier(0,0,.25,1) 0s,color .08 linear;-moz-transition:-moz-transform .08 cubic-bezier(0,0,.25,1) 0s,opacity .08 cubic-bezier(0,0,.25,1) 0s,color .08 linear;-o-transition:-o-transform .08 cubic-bezier(0,0,.25,1) 0s,opacity .08 cubic-bezier(0,0,.25,1) 0s,color .08 linear;transition:transform .08 cubic-bezier(0,0,.25,1) 0s,opacity .08 cubic-bezier(0,0,.25,1) 0s,color .08 linear}body:not(.lg-from-hash) .lg-outer.lg-start-zoom .lg-item:not(.lg-zoomable) .lg-img-wrap,body:not(.lg-from-hash) .lg-outer.lg-start-zoom .lg-item:not(.lg-zoomable) .lg-media-cont,body:not(.lg-from-hash) .lg-outer.lg-start-zoom .lg-item:not(.lg-zoomable) .lg-video-cont{opacity:0;-moz-transform:scale3d(.5,.5,.5);-o-transform:scale3d(.5,.5,.5);-ms-transform:scale3d(.5,.5,.5);-webkit-transform:scale3d(.5,.5,.5);transform:scale3d(.5,.5,.5);will-change:transform,opacity;-webkit-transition:-webkit-transform 250ms cubic-bezier(0,0,.25,1) 0s,opacity 250ms cubic-bezier(0,0,.25,1)!important;-moz-transition:-moz-transform 250ms cubic-bezier(0,0,.25,1) 0s,opacity 250ms cubic-bezier(0,0,.25,1)!important;-o-transition:-o-transform 250ms cubic-bezier(0,0,.25,1) 0s,opacity 250ms cubic-bezier(0,0,.25,1)!important;transition:transform 250ms cubic-bezier(0,0,.25,1) 0s,opacity 250ms cubic-bezier(0,0,.25,1)!important}body:not(.lg-from-hash) .lg-outer.lg-start-zoom .lg-item:not(.lg-zoomable).lg-complete .lg-img-wrap,body:not(.lg-from-hash) .lg-outer.lg-start-zoom .lg-item:not(.lg-zoomable).lg-complete .lg-media-cont,body:not(.lg-from-hash) .lg-outer.lg-start-zoom .lg-item:not(.lg-zoomable).lg-complete .lg-video-cont{opacity:1;-moz-transform:scale3d(1,1,1);-o-transform:scale3d(1,1,1);-ms-transform:scale3d(1,1,1);-webkit-transform:scale3d(1,1,1);transform:scale3d(1,1,1)}.lg-icon:focus-visible{color:#fff;border-radius:3px;outline:1px dashed rgba(255,255,255,.6)}.lg-toolbar .lg-icon:focus-visible{border-radius:8px;outline-offset:-5px}.lg-outer .lg-thumb-outer{background-color:#0d0a0a;width:100%;max-height:350px;overflow:hidden;float:left}.lg-outer .lg-thumb-outer.lg-grab .lg-thumb-item{cursor:-webkit-grab;cursor:-moz-grab;cursor:-o-grab;cursor:-ms-grab;cursor:grab}.lg-outer .lg-thumb-outer.lg-grabbing .lg-thumb-item{cursor:move;cursor:-webkit-grabbing;cursor:-moz-grabbing;cursor:-o-grabbing;cursor:-ms-grabbing;cursor:grabbing}.lg-outer .lg-thumb-outer.lg-dragging .lg-thumb{-webkit-transition-duration:0s!important;transition-duration:0s!important}.lg-outer .lg-thumb-outer.lg-rebuilding-thumbnails .lg-thumb{-webkit-transition-duration:0s!important;transition-duration:0s!important}.lg-outer .lg-thumb-outer.lg-thumb-align-middle{text-align:center}.lg-outer .lg-thumb-outer.lg-thumb-align-left{text-align:left}.lg-outer .lg-thumb-outer.lg-thumb-align-right{text-align:right}.lg-outer.lg-single-item .lg-thumb-outer{display:none}.lg-outer .lg-thumb{padding:5px 0;height:100%;margin-bottom:-5px;display:inline-block;vertical-align:middle}@media (min-width:768px){.lg-outer .lg-thumb{padding:10px 0}}.lg-outer .lg-thumb-item{cursor:pointer;float:left;overflow:hidden;height:100%;border-radius:2px;margin-bottom:5px;will-change:border-color}@media (min-width:768px){.lg-outer .lg-thumb-item{border-radius:4px;border:2px solid #fff;-webkit-transition:border-color .25s ease;-o-transition:border-color .25s ease;transition:border-color .25s ease}}.lg-outer .lg-thumb-item.active,.lg-outer .lg-thumb-item:hover{border-color:#a90707}.lg-outer .lg-thumb-item img{width:100%;height:100%;object-fit:cover;display:block}.lg-outer.lg-can-toggle .lg-item{padding-bottom:0}.lg-outer .lg-toggle-thumb:after{content:"\e1ff"}.lg-outer.lg-animate-thumb .lg-thumb{-webkit-transition-timing-function:cubic-bezier(.215,.61,.355,1);transition-timing-function:cubic-bezier(.215,.61,.355,1)}.lg-outer .lg-video-cont{text-align:center;display:inline-block;vertical-align:middle;position:relative}.lg-outer .lg-video-cont .lg-object{width:100%!important;height:100%!important}.lg-outer .lg-has-iframe .lg-video-cont{-webkit-overflow-scrolling:touch;overflow:auto}.lg-outer .lg-video-object{position:absolute;left:0;right:0;width:100%;height:100%;top:0;bottom:0;z-index:3}.lg-outer .lg-video-poster{z-index:1}.lg-outer .lg-has-video .lg-video-object{opacity:0;will-change:opacity;-webkit-transition:opacity .3s ease-in;-o-transition:opacity .3s ease-in;transition:opacity .3s ease-in}.lg-outer .lg-has-video.lg-video-loaded .lg-video-play-button,.lg-outer .lg-has-video.lg-video-loaded .lg-video-poster{opacity:0!important}.lg-outer .lg-has-video.lg-video-loaded .lg-video-object{opacity:1}@keyframes lg-play-stroke{0%{stroke-dasharray:1,200;stroke-dashoffset:0}50%{stroke-dasharray:89,200;stroke-dashoffset:-35px}100%{stroke-dasharray:89,200;stroke-dashoffset:-124px}}@keyframes lg-play-rotate{100%{-webkit-transform:rotate(360deg);transform:rotate(360deg)}}.lg-video-play-button{width:18%;max-width:140px;position:absolute;top:50%;left:50%;z-index:2;cursor:pointer;transform:translate(-50%,-50%) scale(1);will-change:opacity,transform;-webkit-transition:-webkit-transform .25s cubic-bezier(.17,.88,.32,1.28),opacity .1s;-moz-transition:-moz-transform .25s cubic-bezier(.17,.88,.32,1.28),opacity .1s;-o-transition:-o-transform .25s cubic-bezier(.17,.88,.32,1.28),opacity .1s;transition:transform .25s cubic-bezier(.17,.88,.32,1.28),opacity .1s}.lg-video-play-button:hover .lg-video-play-icon,.lg-video-play-button:hover .lg-video-play-icon-bg{opacity:1}.lg-video-play-icon-bg{fill:none;stroke-width:3%;stroke:#fcfcfc;opacity:.6;will-change:opacity;-webkit-transition:opacity .12s ease-in;-o-transition:opacity .12s ease-in;transition:opacity .12s ease-in}.lg-video-play-icon-circle{position:absolute;top:0;left:0;bottom:0;right:0;fill:none;stroke-width:3%;stroke:rgba(30,30,30,.9);stroke-opacity:1;stroke-linecap:round;stroke-dasharray:200;stroke-dashoffset:200}.lg-video-play-icon{position:absolute;width:25%;max-width:120px;left:50%;top:50%;transform:translate3d(-50%,-50%,0);opacity:.6;will-change:opacity;-webkit-transition:opacity .12s ease-in;-o-transition:opacity .12s ease-in;transition:opacity .12s ease-in}.lg-video-play-icon .lg-video-play-icon-inner{fill:#fcfcfc}.lg-video-loading .lg-video-play-icon-circle{animation:lg-play-rotate 2s linear .25s infinite,lg-play-stroke 1.5s ease-in-out .25s infinite}.lg-video-loaded .lg-video-play-button{opacity:0;transform:translate(-50%,-50%) scale(.7)}.lg-progress-bar{background-color:#333;height:5px;left:0;position:absolute;top:0;width:100%;z-index:1083;opacity:0;will-change:opacity;-webkit-transition:opacity 80ms ease 0s;-moz-transition:opacity 80ms ease 0s;-o-transition:opacity 80ms ease 0s;transition:opacity 80ms ease 0s}.lg-progress-bar .lg-progress{background-color:#a90707;height:5px;width:0}.lg-progress-bar.lg-start .lg-progress{width:100%}.lg-show-autoplay .lg-progress-bar{opacity:1}.lg-autoplay-button:after{content:"\e01d"}.lg-show-autoplay .lg-autoplay-button:after{content:"\e01a"}.lg-single-item .lg-autoplay-button{opacity:.75;pointer-events:none}.lg-outer.lg-css3.lg-zoom-dragging .lg-item.lg-complete.lg-zoomable .lg-image,.lg-outer.lg-css3.lg-zoom-dragging .lg-item.lg-complete.lg-zoomable .lg-img-wrap{-webkit-transition-duration:0s!important;transition-duration:0s!important}.lg-outer.lg-use-transition-for-zoom .lg-item.lg-complete.lg-zoomable .lg-img-wrap{will-change:transform;-webkit-transition:-webkit-transform .5s cubic-bezier(.12,.415,.01,1.19) 0s;-moz-transition:-moz-transform .5s cubic-bezier(.12,.415,.01,1.19) 0s;-o-transition:-o-transform .5s cubic-bezier(.12,.415,.01,1.19) 0s;transition:transform .5s cubic-bezier(.12,.415,.01,1.19) 0s}.lg-outer.lg-use-transition-for-zoom.lg-zoom-drag-transition .lg-item.lg-complete.lg-zoomable .lg-img-wrap{will-change:transform;-webkit-transition:-webkit-transform .8s cubic-bezier(0,0,.25,1) 0s;-moz-transition:-moz-transform .8s cubic-bezier(0,0,.25,1) 0s;-o-transition:-o-transform .8s cubic-bezier(0,0,.25,1) 0s;transition:transform .8s cubic-bezier(0,0,.25,1) 0s}.lg-outer .lg-item.lg-complete.lg-zoomable .lg-img-wrap{-webkit-transform:translate3d(0,0,0);transform:translate3d(0,0,0);-webkit-backface-visibility:hidden;-moz-backface-visibility:hidden;backface-visibility:hidden}.lg-outer .lg-item.lg-complete.lg-zoomable .lg-dummy-img,.lg-outer .lg-item.lg-complete.lg-zoomable .lg-image{-webkit-transform:scale3d(1,1,1);transform:scale3d(1,1,1);-webkit-transition:-webkit-transform .5s cubic-bezier(.12,.415,.01,1.19) 0s,opacity .15s!important;-moz-transition:-moz-transform .5s cubic-bezier(.12,.415,.01,1.19) 0s,opacity .15s!important;-o-transition:-o-transform .5s cubic-bezier(.12,.415,.01,1.19) 0s,opacity .15s!important;transition:transform .5s cubic-bezier(.12,.415,.01,1.19) 0s,opacity .15s!important;-webkit-backface-visibility:hidden;-moz-backface-visibility:hidden;backface-visibility:hidden}.lg-outer .lg-item.lg-complete.lg-zoomable .lg-dummy-img.no-transition,.lg-outer .lg-item.lg-complete.lg-zoomable .lg-image.no-transition{transition:none!important}.lg-outer .lg-item.lg-complete.lg-zoomable .lg-dummy-img.reset-transition,.lg-outer .lg-item.lg-complete.lg-zoomable .lg-image.reset-transition{transform:scale3d(1,1,1) translate3d(-50%,-50%,0)!important;max-width:none!important;max-height:none!important;top:50%!important;left:50%!important}.lg-outer .lg-item.lg-complete.lg-zoomable .lg-dummy-img.reset-transition-x,.lg-outer .lg-item.lg-complete.lg-zoomable .lg-image.reset-transition-x{transform:scale3d(1,1,1) translate3d(-50%,0,0)!important;top:0!important;left:50%!important;max-width:none!important;max-height:none!important}.lg-outer .lg-item.lg-complete.lg-zoomable .lg-dummy-img.reset-transition-y,.lg-outer .lg-item.lg-complete.lg-zoomable .lg-image.reset-transition-y{transform:scale3d(1,1,1) translate3d(0,-50%,0)!important;top:50%!important;left:0!important;max-width:none!important;max-height:none!important}.lg-icon.lg-zoom-in:after{content:"\e311"}.lg-actual-size .lg-icon.lg-zoom-in{opacity:1;pointer-events:auto}.lg-icon.lg-actual-size{font-size:20px}.lg-icon.lg-actual-size:after{content:"\e033"}.lg-icon.lg-zoom-out{opacity:.5;pointer-events:none}.lg-icon.lg-zoom-out:after{content:"\e312"}.lg-zoomed .lg-icon.lg-zoom-out{opacity:1;pointer-events:auto}.lg-outer.lg-first-slide-loading .lg-actual-size,.lg-outer.lg-first-slide-loading .lg-zoom-in,.lg-outer.lg-first-slide-loading .lg-zoom-out,.lg-outer[data-lg-slide-type=iframe] .lg-actual-size,.lg-outer[data-lg-slide-type=iframe] .lg-zoom-in,.lg-outer[data-lg-slide-type=iframe] .lg-zoom-out,.lg-outer[data-lg-slide-type=video] .lg-actual-size,.lg-outer[data-lg-slide-type=video] .lg-zoom-in,.lg-outer[data-lg-slide-type=video] .lg-zoom-out{opacity:.75;pointer-events:none}.lg-outer .lg-pager-outer{text-align:center;z-index:1080;height:10px;margin-bottom:10px}.lg-outer .lg-pager-outer.lg-pager-hover .lg-pager-cont{overflow:visible}.lg-outer.lg-single-item .lg-pager-outer{display:none}.lg-outer .lg-pager-cont{cursor:pointer;display:inline-block;overflow:hidden;position:relative;vertical-align:top;margin:0 5px}.lg-outer .lg-pager-cont:hover .lg-pager-thumb-cont{opacity:1;-webkit-transform:translate3d(0,0,0);transform:translate3d(0,0,0)}.lg-outer .lg-pager-cont.lg-pager-active .lg-pager{box-shadow:0 0 0 2px #fff inset}.lg-outer .lg-pager-thumb-cont{background-color:#fff;color:#fff;bottom:100%;height:83px;left:0;margin-bottom:20px;margin-left:-60px;opacity:0;padding:5px;position:absolute;width:120px;border-radius:3px;will-change:transform,opacity;-webkit-transition:opacity .15s ease 0s,-webkit-transform .15s ease 0s;-moz-transition:opacity .15s ease 0s,-moz-transform .15s ease 0s;-o-transition:opacity .15s ease 0s,-o-transform .15s ease 0s;transition:opacity .15s ease 0s,transform .15s ease 0s;-webkit-transform:translate3d(0,5px,0);transform:translate3d(0,5px,0)}.lg-outer .lg-pager-thumb-cont img{width:100%;height:100%}.lg-outer .lg-pager{background-color:rgba(255,255,255,.5);border-radius:50%;box-shadow:0 0 0 8px rgba(255,255,255,.7) inset;display:block;height:12px;-webkit-transition:box-shadow .3s ease 0s;-o-transition:box-shadow .3s ease 0s;transition:box-shadow .3s ease 0s;width:12px}.lg-outer .lg-pager:focus,.lg-outer .lg-pager:hover{box-shadow:0 0 0 8px #fff inset}.lg-outer .lg-caret{border-left:10px solid transparent;border-right:10px solid transparent;border-top:10px dashed;bottom:-10px;display:inline-block;height:0;left:50%;margin-left:-5px;position:absolute;vertical-align:middle;width:0}.lg-fullscreen:after{content:"\e20c"}.lg-fullscreen-on .lg-fullscreen:after{content:"\e20d"}.lg-outer .lg-dropdown-overlay{background-color:rgba(0,0,0,.25);bottom:0;cursor:default;left:0;position:absolute;right:0;top:0;z-index:1081;opacity:0;visibility:hidden;will-change:visibility,opacity;-webkit-transition:visibility 0s linear .18s,opacity .18s linear 0s;-o-transition:visibility 0s linear .18s,opacity .18s linear 0s;transition:visibility 0s linear .18s,opacity .18s linear 0s}.lg-outer.lg-dropdown-active .lg-dropdown,.lg-outer.lg-dropdown-active .lg-dropdown-overlay{-webkit-transition-delay:0s;transition-delay:0s;-moz-transform:translate3d(0,0,0);-o-transform:translate3d(0,0,0);-ms-transform:translate3d(0,0,0);-webkit-transform:translate3d(0,0,0);transform:translate3d(0,0,0);opacity:1;visibility:visible}.lg-outer.lg-dropdown-active .lg-share{color:#fff}.lg-outer .lg-dropdown{background-color:#fff;border-radius:2px;font-size:14px;list-style-type:none;margin:0;padding:10px 0;position:absolute;right:0;text-align:left;top:50px;opacity:0;visibility:hidden;-moz-transform:translate3d(0,5px,0);-o-transform:translate3d(0,5px,0);-ms-transform:translate3d(0,5px,0);-webkit-transform:translate3d(0,5px,0);transform:translate3d(0,5px,0);will-change:visibility,opacity,transform;-webkit-transition:-webkit-transform .18s linear 0s,visibility 0s linear .5s,opacity .18s linear 0s;-moz-transition:-moz-transform .18s linear 0s,visibility 0s linear .5s,opacity .18s linear 0s;-o-transition:-o-transform .18s linear 0s,visibility 0s linear .5s,opacity .18s linear 0s;transition:transform .18s linear 0s,visibility 0s linear .5s,opacity .18s linear 0s}.lg-outer .lg-dropdown:after{content:"";display:block;height:0;width:0;position:absolute;border:8px solid transparent;border-bottom-color:#fff;right:16px;top:-16px}.lg-outer .lg-dropdown>li:last-child{margin-bottom:0}.lg-outer .lg-dropdown>li:hover a{color:#333}.lg-outer .lg-dropdown a{color:#333;display:block;white-space:pre;padding:4px 12px;font-family:"Open Sans","Helvetica Neue",Helvetica,Arial,sans-serif;font-size:12px}.lg-outer .lg-dropdown a:hover{background-color:rgba(0,0,0,.07)}.lg-outer .lg-dropdown .lg-dropdown-text{display:inline-block;line-height:1;margin-top:-3px;vertical-align:middle}.lg-outer .lg-dropdown .lg-icon{color:#333;display:inline-block;float:none;font-size:20px;height:auto;line-height:1;margin-right:8px;padding:0;vertical-align:middle;width:auto}.lg-outer .lg-share{position:relative}.lg-outer .lg-share:after{content:"\e80d"}.lg-outer .lg-share-facebook .lg-icon{color:#3b5998}.lg-outer .lg-share-facebook .lg-icon:after{content:"\e904"}.lg-outer .lg-share-twitter .lg-icon{color:#00aced}.lg-outer .lg-share-twitter .lg-icon:after{content:"\e907"}.lg-outer .lg-share-pinterest .lg-icon{color:#cb2027}.lg-outer .lg-share-pinterest .lg-icon:after{content:"\e906"}.lg-comment-box{width:420px;max-width:100%;position:absolute;right:0;top:0;bottom:0;z-index:9999;background-color:#fff;will-change:transform;-moz-transform:translate3d(100%,0,0);-o-transform:translate3d(100%,0,0);-ms-transform:translate3d(100%,0,0);-webkit-transform:translate3d(100%,0,0);transform:translate3d(100%,0,0);-webkit-transition:-webkit-transform .4s cubic-bezier(0,0,.25,1) 0s;-moz-transition:-moz-transform .4s cubic-bezier(0,0,.25,1) 0s;-o-transition:-o-transform .4s cubic-bezier(0,0,.25,1) 0s;transition:transform .4s cubic-bezier(0,0,.25,1) 0s}.lg-comment-box .lg-comment-title{margin:0;color:#fff;font-size:18px}.lg-comment-box .lg-comment-header{background-color:#000;padding:12px 20px;position:absolute;left:0;right:0;top:0}.lg-comment-box .lg-comment-body{height:100%!important;padding-top:43px!important;width:100%!important}.lg-comment-box .fb-comments{height:100%;width:100%;background:url(../images/loading.gif) no-repeat scroll center center #fff;overflow-y:auto;display:inline-block}.lg-comment-box .fb-comments[fb-xfbml-state=rendered]{background-image:none}.lg-comment-box .fb-comments>span{max-width:100%}.lg-comment-box .lg-comment-close{position:absolute;right:5px;top:12px;cursor:pointer;font-size:20px;color:#999;will-change:color;-webkit-transition:color .2s linear;-o-transition:color .2s linear;transition:color .2s linear}.lg-comment-box .lg-comment-close:hover{color:#fff}.lg-comment-box .lg-comment-close:after{content:"\e070"}.lg-comment-box iframe{max-width:100%!important;width:100%!important}.lg-comment-box #disqus_thread{padding:0 20px}.lg-outer .lg-comment-overlay{background-color:rgba(0,0,0,.25);bottom:0;cursor:default;left:0;position:fixed;right:0;top:0;z-index:1081;opacity:0;visibility:hidden;will-change:visibility,opacity;-webkit-transition:visibility 0s linear .18s,opacity .18s linear 0s;-o-transition:visibility 0s linear .18s,opacity .18s linear 0s;transition:visibility 0s linear .18s,opacity .18s linear 0s}.lg-outer .lg-comment-toggle:after{content:"\e908"}.lg-outer.lg-comment-active .lg-comment-overlay{-webkit-transition-delay:0s;transition-delay:0s;-moz-transform:translate3d(0,0,0);-o-transform:translate3d(0,0,0);-ms-transform:translate3d(0,0,0);-webkit-transform:translate3d(0,0,0);transform:translate3d(0,0,0);opacity:1;visibility:visible}.lg-outer.lg-comment-active .lg-comment-toggle{color:#fff}.lg-outer.lg-comment-active .lg-comment-box{-moz-transform:translate3d(0,0,0);-o-transform:translate3d(0,0,0);-ms-transform:translate3d(0,0,0);-webkit-transform:translate3d(0,0,0);transform:translate3d(0,0,0)}.lg-outer .lg-img-rotate{position:absolute;left:0;right:0;top:0;bottom:0;-webkit-transition:-webkit-transform .4s cubic-bezier(0,0,.25,1) 0s;-moz-transition:-moz-transform .4s cubic-bezier(0,0,.25,1) 0s;-o-transition:-o-transform .4s cubic-bezier(0,0,.25,1) 0s;transition:transform .4s cubic-bezier(0,0,.25,1) 0s}.lg-outer[data-lg-slide-type=iframe] .lg-flip-hor,.lg-outer[data-lg-slide-type=iframe] .lg-flip-ver,.lg-outer[data-lg-slide-type=iframe] .lg-rotate-left,.lg-outer[data-lg-slide-type=iframe] .lg-rotate-right,.lg-outer[data-lg-slide-type=video] .lg-flip-hor,.lg-outer[data-lg-slide-type=video] .lg-flip-ver,.lg-outer[data-lg-slide-type=video] .lg-rotate-left,.lg-outer[data-lg-slide-type=video] .lg-rotate-right{opacity:.75;pointer-events:none}.lg-outer .lg-img-rotate:before{content:"";display:inline-block;height:100%;vertical-align:middle}.lg-rotate-left:after{content:"\e900"}.lg-rotate-right:after{content:"\e901"}.lg-icon.lg-flip-hor,.lg-icon.lg-flip-ver{font-size:26px}.lg-flip-ver:after{content:"\e903"}.lg-flip-hor:after{content:"\e902"}.lg-medium-zoom-item{cursor:zoom-in}.lg-medium-zoom .lg-outer{cursor:zoom-out}.lg-medium-zoom .lg-outer.lg-grab img.lg-object{cursor:zoom-out}.lg-medium-zoom .lg-outer.lg-grabbing img.lg-object{cursor:zoom-out}.lg-relative-caption .lg-outer .lg-sub-html{white-space:normal;bottom:auto;padding:0;background-image:none}.lg-relative-caption .lg-outer .lg-relative-caption-item{opacity:0;padding:16px 0;transition:.5s opacity ease}.lg-relative-caption .lg-outer .lg-show-caption .lg-relative-caption-item{opacity:1}.lg-group:after{content:"";display:table;clear:both}.lg-container{display:none;outline:0}.lg-container.lg-show{display:block}.lg-on{scroll-behavior:unset}.lg-overlay-open{overflow:hidden}.lg-hide-sub-html .lg-sub-html,.lg-next,.lg-pager-outer,.lg-prev,.lg-toolbar{opacity:0;will-change:transform,opacity;-webkit-transition:-webkit-transform .25s cubic-bezier(0,0,.25,1) 0s,opacity .25s cubic-bezier(0,0,.25,1) 0s;-moz-transition:-moz-transform .25s cubic-bezier(0,0,.25,1) 0s,opacity .25s cubic-bezier(0,0,.25,1) 0s;-o-transition:-o-transform .25s cubic-bezier(0,0,.25,1) 0s,opacity .25s cubic-bezier(0,0,.25,1) 0s;transition:transform .25s cubic-bezier(0,0,.25,1) 0s,opacity .25s cubic-bezier(0,0,.25,1) 0s}.lg-show-in .lg-next,.lg-show-in .lg-pager-outer,.lg-show-in .lg-prev,.lg-show-in .lg-toolbar{opacity:1}.lg-show-in.lg-hide-sub-html .lg-sub-html{opacity:1}.lg-show-in .lg-hide-items .lg-prev{opacity:0;-webkit-transform:translate3d(-10px,0,0);transform:translate3d(-10px,0,0)}.lg-show-in .lg-hide-items .lg-next{opacity:0;-webkit-transform:translate3d(10px,0,0);transform:translate3d(10px,0,0)}.lg-show-in .lg-hide-items .lg-toolbar{opacity:0;-webkit-transform:translate3d(0,-10px,0);transform:translate3d(0,-10px,0)}.lg-show-in .lg-hide-items.lg-hide-sub-html .lg-sub-html{opacity:0;-webkit-transform:translate3d(0,20px,0);transform:translate3d(0,20px,0)}.lg-outer{width:100%;height:100%;position:fixed;top:0;left:0;z-index:1050;text-align:left;opacity:.001;outline:0;will-change:auto;overflow:hidden;-webkit-transition:opacity .15s ease 0s;-o-transition:opacity .15s ease 0s;transition:opacity .15s ease 0s}.lg-outer *{-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}.lg-outer.lg-zoom-from-image{opacity:1}.lg-outer.lg-visible{opacity:1}.lg-outer.lg-css3 .lg-item:not(.lg-start-end-progress).lg-current,.lg-outer.lg-css3 .lg-item:not(.lg-start-end-progress).lg-next-slide,.lg-outer.lg-css3 .lg-item:not(.lg-start-end-progress).lg-prev-slide{-webkit-transition-duration:inherit!important;transition-duration:inherit!important;-webkit-transition-timing-function:inherit!important;transition-timing-function:inherit!important}.lg-outer.lg-css3.lg-dragging .lg-item.lg-current,.lg-outer.lg-css3.lg-dragging .lg-item.lg-next-slide,.lg-outer.lg-css3.lg-dragging .lg-item.lg-prev-slide{-webkit-transition-duration:0s!important;transition-duration:0s!important;opacity:1}.lg-outer.lg-grab img.lg-object{cursor:-webkit-grab;cursor:-moz-grab;cursor:-o-grab;cursor:-ms-grab;cursor:grab}.lg-outer.lg-grabbing img.lg-object{cursor:move;cursor:-webkit-grabbing;cursor:-moz-grabbing;cursor:-o-grabbing;cursor:-ms-grabbing;cursor:grabbing}.lg-outer .lg-content{position:absolute;top:0;left:0;right:0;bottom:0}.lg-outer .lg-inner{width:100%;position:absolute;left:0;top:0;bottom:0;-webkit-transition:opacity 0s;-o-transition:opacity 0s;transition:opacity 0s;white-space:nowrap}.lg-outer .lg-item{display:none!important}.lg-outer .lg-item:not(.lg-start-end-progress){background:url(../images/loading.gif) no-repeat scroll center center transparent}.lg-outer.lg-css3 .lg-current,.lg-outer.lg-css3 .lg-next-slide,.lg-outer.lg-css3 .lg-prev-slide{display:inline-block!important}.lg-outer.lg-css .lg-current{display:inline-block!important}.lg-outer .lg-img-wrap,.lg-outer .lg-item{display:inline-block;text-align:center;position:absolute;width:100%;height:100%}.lg-outer .lg-img-wrap:before,.lg-outer .lg-item:before{content:"";display:inline-block;height:100%;vertical-align:middle}.lg-outer .lg-img-wrap{position:absolute;left:0;right:0;top:0;bottom:0;white-space:nowrap;font-size:0}.lg-outer .lg-item.lg-complete{background-image:none}.lg-outer .lg-item.lg-current{z-index:1060}.lg-outer .lg-object{display:inline-block;vertical-align:middle;max-width:100%;max-height:100%;width:auto;height:auto;position:relative}.lg-outer .lg-empty-html .lg-sub-html,.lg-outer .lg-empty-html.lg-sub-html{display:none}.lg-outer.lg-hide-download .lg-download{opacity:.75;pointer-events:none}.lg-outer .lg-first-slide .lg-dummy-img{position:absolute;top:50%;left:50%}.lg-outer.lg-components-open:not(.lg-zoomed) .lg-components{-webkit-transform:translate3d(0,0,0);transform:translate3d(0,0,0);opacity:1}.lg-outer.lg-components-open:not(.lg-zoomed) .lg-sub-html{opacity:1;transition:opacity .2s ease-out .15s}.lg-outer .lg-media-cont{text-align:center;display:inline-block;vertical-align:middle;position:relative}.lg-outer .lg-media-cont .lg-object{width:100%!important;height:100%!important}.lg-outer .lg-has-iframe .lg-media-cont{-webkit-overflow-scrolling:touch;overflow:auto}.lg-backdrop{position:fixed;top:0;left:0;right:0;bottom:0;z-index:1040;background-color:#000;opacity:0;will-change:auto;-webkit-transition:opacity 333ms ease-in 0s;-o-transition:opacity 333ms ease-in 0s;transition:opacity 333ms ease-in 0s}.lg-backdrop.in{opacity:1}.lg-css3.lg-no-trans .lg-current,.lg-css3.lg-no-trans .lg-next-slide,.lg-css3.lg-no-trans .lg-prev-slide{-webkit-transition:none 0s ease 0s!important;-moz-transition:none 0s ease 0s!important;-o-transition:none 0s ease 0s!important;transition:none 0s ease 0s!important}.lg-css3.lg-use-css3 .lg-item{-webkit-backface-visibility:hidden;-moz-backface-visibility:hidden;backface-visibility:hidden}.lg-css3.lg-fade .lg-item{opacity:0}.lg-css3.lg-fade .lg-item.lg-current{opacity:1}.lg-css3.lg-fade .lg-item.lg-current,.lg-css3.lg-fade .lg-item.lg-next-slide,.lg-css3.lg-fade .lg-item.lg-prev-slide{-webkit-transition:opacity .1s ease 0s;-moz-transition:opacity .1s ease 0s;-o-transition:opacity .1s ease 0s;transition:opacity .1s ease 0s}.lg-css3.lg-use-css3 .lg-item.lg-start-progress{-webkit-transition:-webkit-transform 1s cubic-bezier(.175,.885,.32,1.275) 0s;-moz-transition:-moz-transform 1s cubic-bezier(.175,.885,.32,1.275) 0s;-o-transition:-o-transform 1s cubic-bezier(.175,.885,.32,1.275) 0s;transition:transform 1s cubic-bezier(.175,.885,.32,1.275) 0s}.lg-css3.lg-use-css3 .lg-item.lg-start-end-progress{-webkit-transition:-webkit-transform 1s cubic-bezier(0,0,.25,1) 0s;-moz-transition:-moz-transform 1s cubic-bezier(0,0,.25,1) 0s;-o-transition:-o-transform 1s cubic-bezier(0,0,.25,1) 0s;transition:transform 1s cubic-bezier(0,0,.25,1) 0s}.lg-css3.lg-slide.lg-use-css3 .lg-item{opacity:0}.lg-css3.lg-slide.lg-use-css3 .lg-item.lg-prev-slide{-webkit-transform:translate3d(-100%,0,0);transform:translate3d(-100%,0,0)}.lg-css3.lg-slide.lg-use-css3 .lg-item.lg-next-slide{-webkit-transform:translate3d(100%,0,0);transform:translate3d(100%,0,0)}.lg-css3.lg-slide.lg-use-css3 .lg-item.lg-current{-webkit-transform:translate3d(0,0,0);transform:translate3d(0,0,0);opacity:1}.lg-css3.lg-slide.lg-use-css3 .lg-item.lg-current,.lg-css3.lg-slide.lg-use-css3 .lg-item.lg-next-slide,.lg-css3.lg-slide.lg-use-css3 .lg-item.lg-prev-slide{-webkit-transition:-webkit-transform 1s cubic-bezier(0,0,.25,1) 0s,opacity .1s ease 0s;-moz-transition:-moz-transform 1s cubic-bezier(0,0,.25,1) 0s,opacity .1s ease 0s;-o-transition:-o-transform 1s cubic-bezier(0,0,.25,1) 0s,opacity .1s ease 0s;transition:transform 1s cubic-bezier(0,0,.25,1) 0s,opacity .1s ease 0s}.lg-container{display:none}.lg-container.lg-show{display:block}.lg-container.lg-dragging-vertical .lg-backdrop{-webkit-transition-duration:0s!important;transition-duration:0s!important}.lg-container.lg-dragging-vertical .lg-css3 .lg-item.lg-current{-webkit-transition-duration:0s!important;transition-duration:0s!important;opacity:1}.lg-inline .lg-backdrop,.lg-inline .lg-outer{position:absolute}.lg-inline .lg-backdrop{z-index:1}.lg-inline .lg-outer{z-index:2}.lg-inline .lg-maximize:after{content:"\e909"}.lg-components{-webkit-transform:translate3d(0,100%,0);transform:translate3d(0,100%,0);will-change:transform;-webkit-transition:-webkit-transform .35s ease-out 0s;-moz-transition:-moz-transform .35s ease-out 0s;-o-transition:-o-transform .35s ease-out 0s;transition:transform .35s ease-out 0s;z-index:1080;position:absolute;bottom:0;right:0;left:0}
\ No newline at end of file
diff --git a/app/public/lg/lightgallery.min.js b/app/public/lg/lightgallery.min.js
deleted file mode 100644
index 16c4a50..0000000
--- a/app/public/lg/lightgallery.min.js
+++ /dev/null
@@ -1,8 +0,0 @@
-/**
- * lightgallery | 2.9.0 | October 1st 2025
- * http://www.lightgalleryjs.com/
- * Copyright (c) 2020 Sachin Neravath;
- * @license GPLv3
- */
-
-!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e():"function"==typeof define&&define.amd?define(e):(t="undefined"!=typeof globalThis?globalThis:t||self).lightGallery=e()}(this,(function(){"use strict";var t=function(){return(t=Object.assign||function(t){for(var e,i=1,s=arguments.length;i";e.append(s)}else e.html(t)}))},E=function(t,e,i,s){void 0===i&&(i=0);var n=x(t).attr("data-lg-size")||s;if(n){var o=n.split(",");if(o[1])for(var r=window.innerWidth,l=0;lr){n=a;break}l===o.length-1&&(n=a)}var d=n.split("-"),g=parseInt(d[0],10),h=parseInt(d[1],10),c=e.width(),u=e.height()-i,m=Math.min(c,g),p=Math.min(u,h),f=Math.min(m/g,p/h);return{width:g*f,height:h*f}}},O=function(t,e,i,s,n){if(n){var o=x(t).find("img").first();if(o.get()){var r=e.get().getBoundingClientRect(),l=r.width,a=e.height()-(i+s),d=o.width(),g=o.height(),h=o.style(),c=(l-d)/2-o.offset().left+(parseFloat(h.paddingLeft)||0)+(parseFloat(h.borderLeft)||0)+x(window).scrollLeft()+r.left,u=(a-g)/2-o.offset().top+(parseFloat(h.paddingTop)||0)+(parseFloat(h.borderTop)||0)+x(window).scrollTop()+i;return"translate3d("+(c*=-1)+"px, "+(u*=-1)+"px, 0) scale3d("+d/n.width+", "+g/n.height+", 1)"}}},L=function(t,e,i,s,n,o){return'\n \n
'},D=function(t,e,i,s,n,o){var r=" ',l="";o&&(l=("string"==typeof o?JSON.parse(o):o).map((function(t){var e="";return Object.keys(t).forEach((function(i){e+=" "+i+'="'+t[i]+'"'}))," "})));return""+l+r},z=function(t){for(var e=[],i=[],s="",n=0;nr){s=i[l];break}return s},M=function(t){return!!t&&(!!t.complete&&0!==t.naturalWidth)},G=function(t,e,i,s,n){var o="";o=n&&n.youtube?"lg-has-youtube":n&&n.vimeo?"lg-has-vimeo":"lg-has-html5";var r=e;return"string"!=typeof e&&(r=e.outerHTML),'\n
\n '+r+'\n
\n
'},k=function(t){var e=t.querySelectorAll('a[href]:not([disabled]), button:not([disabled]), textarea:not([disabled]), input[type="text"]:not([disabled]), input[type="radio"]:not([disabled]), input[type="checkbox"]:not([disabled]), select:not([disabled])');return[].filter.call(e,(function(t){var e=window.getComputedStyle(t);return"none"!==e.display&&"hidden"!==e.visibility}))},A=function(t,e,i,s){var n=[],o=function(){for(var t=0,e=0,i=arguments.length;e-1&&(d=a),d&&(e[d]=l.value)}}var g=x(t),h=g.find("img").first().attr("alt"),c=g.attr("title"),u=s?g.attr(s):g.find("img").first().attr("src");e.thumb=u,i&&!e.subHtml&&(e.subHtml=c||h||""),e.alt=h||c||"",n.push(e)})),n},B=function(){return/iPhone|iPad|iPod|Android/i.test(navigator.userAgent)},P=function(t,e,i){if(!t)return e?{html5:!0}:void console.error("lightGallery :- data-src is not provided on slide item "+(i+1)+". Please make sure the selector property is properly configured. More info - https://www.lightgalleryjs.com/demos/html-markup/");var s=t.match(/\/\/(?:www\.)?youtu(?:\.be|be\.com|be-nocookie\.com)\/(?:watch\?v=|embed\/)?([a-z0-9\-\_\%]+)([\&|?][\S]*)*/i),n=t.match(/\/\/(?:www\.)?(?:player\.)?vimeo.com\/(?:video\/)?([0-9a-z\-_]+)(.*)?/i),o=t.match(/https?:\/\/(.+)?(wistia\.com|wi\.st)\/(medias|embed)\/([0-9a-z\-_]+)(.*)/);return s?{youtube:s}:n?{vimeo:n}:o?{wistia:o}:void 0},F=0,H=function(){function w(t,e){if(this.lgOpened=!1,this.index=0,this.plugins=[],this.lGalleryOn=!1,this.lgBusy=!1,this.currentItemsInDom=[],this.prevScrollTop=0,this.bodyPaddingRight=0,this.isDummyImageRemoved=!1,this.dragOrSwipeEnabled=!1,this.mediaContainerPosition={top:0,bottom:0},!t)return this;if(F++,this.lgId=F,this.el=t,this.LGel=x(t),this.generateSettings(e),this.buildModules(),this.settings.dynamic&&void 0!==this.settings.dynamicEl&&!Array.isArray(this.settings.dynamicEl))throw"When using dynamic mode, you must also define dynamicEl as an Array.";return this.galleryItems=this.getItems(),this.normalizeSettings(),this.init(),this.validateLicense(),this}return w.prototype.generateSettings=function(e){if(this.settings=t(t({},C),e),this.settings.isMobile&&"function"==typeof this.settings.isMobile?this.settings.isMobile():B()){var i=t(t({},this.settings.mobileSettings),this.settings.mobileSettings);this.settings=t(t({},this.settings),i)}},w.prototype.normalizeSettings=function(){if(this.settings.slideEndAnimation&&(this.settings.hideControlOnEnd=!1),this.settings.closable||(this.settings.swipeToClose=!1),this.zoomFromOrigin=this.settings.zoomFromOrigin,this.settings.dynamic&&(this.zoomFromOrigin=!1),this.settings.container){var t=this.settings.container;if("function"==typeof t)this.settings.container=t();else if("string"==typeof t){var e=document.querySelector(t);this.settings.container=null!=e?e:document.body}}else this.settings.container=document.body;this.settings.preload=Math.min(this.settings.preload,this.galleryItems.length)},w.prototype.init=function(){var t=this;this.addSlideVideoInfo(this.galleryItems),this.buildStructure(),this.LGel.trigger(i,{instance:this}),this.settings.keyPress&&this.keyPress(),setTimeout((function(){t.enableDrag(),t.enableSwipe(),t.triggerPosterClick()}),50),this.arrow(),this.settings.mousewheel&&this.mousewheel(),this.settings.dynamic||this.openGalleryOnItemClick()},w.prototype.openGalleryOnItemClick=function(){for(var t=this,e=function(e){var s=i.items[e],n=x(s),o=I.generateUUID();n.attr("data-lg-id",o).on("click.lgcustom-item-"+o,(function(i){i.preventDefault();var n=t.settings.index||e;t.openGallery(n,s)}))},i=this,s=0;s '+this.settings.prevHtml+' \n '+this.settings.nextHtml+" "),".lg-item"!==this.settings.appendSubHtmlTo&&(i='
');var s="";this.settings.allowMediaOverlap&&(s+="lg-media-overlap ");var n=this.settings.ariaLabelledby?'aria-labelledby="'+this.settings.ariaLabelledby+'"':"",o=this.settings.ariaDescribedby?'aria-describedby="'+this.settings.ariaDescribedby+'"':"",r="lg-container "+this.settings.addClass+" "+(document.body!==this.settings.container?"lg-inline":""),l=this.settings.closable&&this.settings.showCloseIcon?' ':"",a=this.settings.showMaximizeIcon?' ':"",d='\n \n
\n\n
\n\n
\n
\n '+a+"\n "+l+"\n
\n "+(".lg-outer"===this.settings.appendSubHtmlTo?i:"")+'\n
\n '+(".lg-sub-html"===this.settings.appendSubHtmlTo?i:"")+"\n
\n
\n
\n ";x(this.settings.container).append(d),document.body!==this.settings.container&&x(this.settings.container).css("position","relative"),this.outer=this.getElementById("lg-outer"),this.$lgComponents=this.getElementById("lg-components"),this.$backdrop=this.getElementById("lg-backdrop"),this.$container=this.getElementById("lg-container"),this.$inner=this.getElementById("lg-inner"),this.$content=this.getElementById("lg-content"),this.$toolbar=this.getElementById("lg-toolbar"),this.$backdrop.css("transition-duration",this.settings.backdropDuration+"ms");var g=this.settings.mode+" ";this.manageSingleSlideClassName(),this.settings.enableDrag&&(g+="lg-grab "),this.outer.addClass(g),this.$inner.css("transition-timing-function",this.settings.easing),this.$inner.css("transition-duration",this.settings.speed+"ms"),this.settings.download&&this.$toolbar.append(' '),this.counter(),x(window).on("resize.lg.global"+this.lgId+" orientationchange.lg.global"+this.lgId,(function(){t.refreshOnResize()})),this.hideBars(),this.manageCloseGallery(),this.toggleMaximize(),this.initModules()}},w.prototype.refreshOnResize=function(){if(this.lgOpened){var t=this.galleryItems[this.index].__slideVideoInfo;this.mediaContainerPosition=this.getMediaContainerPosition();var e=this.mediaContainerPosition,i=e.top,s=e.bottom;if(this.currentImageSize=E(this.items[this.index],this.outer,i+s,t&&this.settings.videoMaxSize),t&&this.resizeVideoSlide(this.index,this.currentImageSize),this.zoomFromOrigin&&!this.isDummyImageRemoved){var o=this.getDummyImgStyles(this.currentImageSize);this.outer.find(".lg-current .lg-dummy-img").first().attr("style",o)}this.LGel.trigger(n)}},w.prototype.resizeVideoSlide=function(t,e){var i=this.getVideoContStyle(e);this.getSlideItem(t).find(".lg-video-cont").attr("style",i)},w.prototype.updateSlides=function(t,e){if(this.index>t.length-1&&(this.index=t.length-1),1===t.length&&(this.index=0),t.length){var i=this.galleryItems[e].src;this.galleryItems=t,this.updateControls(),this.$inner.empty(),this.currentItemsInDom=[];var s=0;this.galleryItems.some((function(t,e){return t.src===i&&(s=e,!0)})),this.currentItemsInDom=this.organizeSlideItems(s,-1),this.loadContent(s,!0),this.getSlideItem(s).addClass("lg-current"),this.index=s,this.updateCurrentCounter(s),this.LGel.trigger(o)}else this.closeGallery()},w.prototype.getItems=function(){if(this.items=[],this.settings.dynamic)return this.settings.dynamicEl||[];if("this"===this.settings.selector)this.items.push(this.el);else if(this.settings.selector)if("string"==typeof this.settings.selector)if(this.settings.selectWithin){var t=x(this.settings.selectWithin);this.items=t.find(this.settings.selector).get()}else this.items=this.el.querySelectorAll(this.settings.selector);else this.items=this.settings.selector;else this.items=this.el.children;return A(this.items,this.settings.extraProps,this.settings.getCaptionFromTitleOrAlt,this.settings.exThumbImage)},w.prototype.shouldHideScrollbar=function(){return this.settings.hideScrollbar&&document.body===this.settings.container},w.prototype.hideScrollbar=function(){if(this.shouldHideScrollbar()){this.bodyPaddingRight=parseFloat(x("body").style().paddingRight);var t=document.documentElement.getBoundingClientRect(),e=window.innerWidth-t.width;x(document.body).css("padding-right",e+this.bodyPaddingRight+"px"),x(document.body).addClass("lg-overlay-open")}},w.prototype.resetScrollBar=function(){this.shouldHideScrollbar()&&(x(document.body).css("padding-right",this.bodyPaddingRight+"px"),x(document.body).removeClass("lg-overlay-open"))},w.prototype.openGallery=function(t,e){var i=this;if(void 0===t&&(t=this.settings.index),!this.lgOpened){this.lgOpened=!0,this.outer.removeClass("lg-hide-items"),this.hideScrollbar(),this.$container.addClass("lg-show");var s=this.getItemsToBeInsertedToDom(t,t);this.currentItemsInDom=s;var n="";s.forEach((function(t){n=n+'
'})),this.$inner.append(n),this.addHtml(t);var o="";this.mediaContainerPosition=this.getMediaContainerPosition();var r=this.mediaContainerPosition,d=r.top,g=r.bottom;this.settings.allowMediaOverlap||this.setMediaContainerPosition(d,g);var h=this.galleryItems[t].__slideVideoInfo;this.zoomFromOrigin&&e&&(this.currentImageSize=E(e,this.outer,d+g,h&&this.settings.videoMaxSize),o=O(e,this.outer,d,g,this.currentImageSize)),this.zoomFromOrigin&&o||(this.outer.addClass(this.settings.startClass),this.getSlideItem(t).removeClass("lg-complete"));var c=this.settings.zoomFromOrigin?100:this.settings.backdropDuration;setTimeout((function(){i.outer.addClass("lg-components-open")}),c),this.index=t,this.LGel.trigger(l),this.getSlideItem(t).addClass("lg-current"),this.lGalleryOn=!1,this.prevScrollTop=x(window).scrollTop(),setTimeout((function(){if(i.zoomFromOrigin&&o){var e=i.getSlideItem(t);e.css("transform",o),setTimeout((function(){e.addClass("lg-start-progress lg-start-end-progress").css("transition-duration",i.settings.startAnimationDuration+"ms"),i.outer.addClass("lg-zoom-from-image")})),setTimeout((function(){e.css("transform","translate3d(0, 0, 0)")}),100)}setTimeout((function(){i.$backdrop.addClass("in"),i.$container.addClass("lg-show-in")}),10),setTimeout((function(){i.settings.trapFocus&&document.body===i.settings.container&&i.trapFocus()}),i.settings.backdropDuration+50),i.zoomFromOrigin&&o||setTimeout((function(){i.outer.addClass("lg-visible")}),i.settings.backdropDuration),i.slide(t,!1,!1,!1),i.LGel.trigger(a)})),document.body===this.settings.container&&x("html").addClass("lg-on")}},w.prototype.getMediaContainerPosition=function(){if(this.settings.allowMediaOverlap)return{top:0,bottom:0};var t=this.$toolbar.get().clientHeight||0,e=this.outer.find(".lg-components .lg-sub-html").get(),i=this.settings.defaultCaptionHeight||e&&e.clientHeight||0,s=this.outer.find(".lg-thumb-outer").get();return{top:t,bottom:(s?s.clientHeight:0)+i}},w.prototype.setMediaContainerPosition=function(t,e){void 0===t&&(t=0),void 0===e&&(e=0),this.$content.css("top",t+"px").css("bottom",e+"px")},w.prototype.hideBars=function(){var t=this;setTimeout((function(){t.outer.removeClass("lg-hide-items"),t.settings.hideBarsDelay>0&&(t.outer.on("mousemove.lg click.lg touchstart.lg",(function(){t.outer.removeClass("lg-hide-items"),clearTimeout(t.hideBarTimeout),t.hideBarTimeout=setTimeout((function(){t.outer.addClass("lg-hide-items")}),t.settings.hideBarsDelay)})),t.outer.trigger("mousemove.lg"))}),this.settings.showBarsAfter)},w.prototype.initPictureFill=function(t){if(this.settings.supportLegacyBrowser)try{picturefill({elements:[t.get()]})}catch(t){console.warn("lightGallery :- If you want srcset or picture tag to be supported for older browser please include picturefil javascript library in your document.")}},w.prototype.counter=function(){if(this.settings.counter){var t='\n '+(this.index+1)+' /\n '+this.galleryItems.length+"
";this.outer.find(this.settings.appendCounterTo).append(t)}},w.prototype.addHtml=function(t){var e,i;if(this.galleryItems[t].subHtmlUrl?i=this.galleryItems[t].subHtmlUrl:e=this.galleryItems[t].subHtml,!i)if(e){var s=e.substring(0,1);if("."===s||"#"===s)try{e=this.settings.subHtmlSelectorRelative&&!this.settings.dynamic?x(this.items).eq(t).find(e).first().html():x(e).first().html()}catch(t){console.warn('Error processing subHtml selector "'+e+'"'),e=""}}else e="";if(".lg-item"!==this.settings.appendSubHtmlTo)i?T(i,this.outer.find(".lg-sub-html"),"replace"):this.outer.find(".lg-sub-html").html(e);else{var n=x(this.getSlideItemId(t));i?T(i,n,"append"):n.append(''+e+"
")}null!=e&&(""===e?this.outer.find(this.settings.appendSubHtmlTo).addClass("lg-empty-html"):this.outer.find(this.settings.appendSubHtmlTo).removeClass("lg-empty-html")),this.LGel.trigger(r,{index:t})},w.prototype.preload=function(t){for(var e=1;e<=this.settings.preload&&!(e>=this.galleryItems.length-t);e++)this.loadContent(t+e,!1);for(var i=1;i<=this.settings.preload&&!(t-i<0);i++)this.loadContent(t-i,!1)},w.prototype.getDummyImgStyles=function(t){return t?"width:"+t.width+"px;\n margin-left: -"+t.width/2+"px;\n margin-top: -"+t.height/2+"px;\n height:"+t.height+"px":""},w.prototype.getVideoContStyle=function(t){return t?"width:"+t.width+"px;\n height:"+t.height+"px":""},w.prototype.getDummyImageContent=function(t,e,i){var s;if(this.settings.dynamic||(s=x(this.items).eq(e)),s){var n=void 0;if(!(n=this.settings.exThumbImage?s.attr(this.settings.exThumbImage):s.find("img").first().attr("src")))return"";var o=this.getDummyImgStyles(this.currentImageSize),r=document.createElement("img");return r.alt=i||"",r.src=n,r.className="lg-dummy-img",r.style.cssText=o,t.addClass("lg-first-slide"),this.outer.addClass("lg-first-slide-loading"),r}return""},w.prototype.setImgMarkup=function(t,e,i){var s=this.galleryItems[i],n=s.alt,o=s.srcset,r=s.sizes,l=s.sources,a="",d=n?'alt="'+n+'"':"";a=this.isFirstSlideWithZoomAnimation()?this.getDummyImageContent(e,i,d):D(i,t,d,o,r,l);var g=document.createElement("picture");g.className="lg-img-wrap",x(g).append(a),e.prepend(g)},w.prototype.onSlideObjectLoad=function(t,e,i,s){var n=t.find(".lg-object").first();M(n.get())||e?i():(n.on("load.lg error.lg",(function(){i&&i()})),n.on("error.lg",(function(){s&&s()})))},w.prototype.onLgObjectLoad=function(t,e,i,s,n,o){var r=this;this.onSlideObjectLoad(t,o,(function(){r.triggerSlideItemLoad(t,e,i,s,n)}),(function(){t.addClass("lg-complete lg-complete_"),t.html(''+r.settings.strings.mediaLoadingFailed+" ")}))},w.prototype.triggerSlideItemLoad=function(t,e,i,s,n){var o=this,r=this.galleryItems[e],l=n&&"video"===this.getSlideType(r)&&!r.poster?s:0;setTimeout((function(){t.addClass("lg-complete lg-complete_"),o.LGel.trigger(d,{index:e,delay:i||0,isFirstSlide:n})}),l)},w.prototype.isFirstSlideWithZoomAnimation=function(){return!(this.lGalleryOn||!this.zoomFromOrigin||!this.currentImageSize)},w.prototype.addSlideVideoInfo=function(t){var e=this;t.forEach((function(t,i){t.__slideVideoInfo=P(t.src,!!t.video,i),t.__slideVideoInfo&&e.settings.loadYouTubePoster&&!t.poster&&t.__slideVideoInfo.youtube&&(t.poster="//img.youtube.com/vi/"+t.__slideVideoInfo.youtube[1]+"/maxresdefault.jpg")}))},w.prototype.loadContent=function(t,i){var n=this,o=this.galleryItems[t],r=x(this.getSlideItemId(t)),l=o.poster,a=o.srcset,d=o.sizes,g=o.sources,h=o.src,c=o.video,u=c&&"string"==typeof c?JSON.parse(c):c;if(o.responsive){var m=o.responsive.split(",");h=z(m)||h}var p=o.__slideVideoInfo,f="",y=!!o.iframe,v=!this.lGalleryOn,b=0;if(v&&(b=this.zoomFromOrigin&&this.currentImageSize?this.settings.startAnimationDuration+10:this.settings.backdropDuration+10),!r.hasClass("lg-loaded")){if(p){var C=this.mediaContainerPosition,I=C.top,w=C.bottom,S=E(this.items[t],this.outer,I+w,p&&this.settings.videoMaxSize);f=this.getVideoContStyle(S)}if(y){var T=L(this.settings.iframeWidth,this.settings.iframeHeight,this.settings.iframeMaxWidth,this.settings.iframeMaxHeight,h,o.iframeTitle);r.prepend(T)}else if(l){var O="";v&&this.zoomFromOrigin&&this.currentImageSize&&(O=this.getDummyImageContent(r,t,""));T=G(l,O||"",f,this.settings.strings.playVideo,p);r.prepend(T)}else if(p){T='
';r.prepend(T)}else if(this.setImgMarkup(h,r,t),a||g){var M=r.find(".lg-object");this.initPictureFill(M)}(l||p)&&this.LGel.trigger(s,{index:t,src:h,html5Video:u,hasPoster:!!l}),this.LGel.trigger(e,{index:t}),this.lGalleryOn&&".lg-item"===this.settings.appendSubHtmlTo&&this.addHtml(t)}var k=0;b&&!x(document.body).hasClass("lg-from-hash")&&(k=b),this.isFirstSlideWithZoomAnimation()&&(setTimeout((function(){r.removeClass("lg-start-end-progress lg-start-progress").removeAttr("style")}),this.settings.startAnimationDuration+100),r.hasClass("lg-loaded")||setTimeout((function(){if("image"===n.getSlideType(o)){var e=o.alt,i=e?'alt="'+e+'"':"";if(r.find(".lg-img-wrap").append(D(t,h,i,a,d,o.sources)),a||g){var s=r.find(".lg-object");n.initPictureFill(s)}}("image"===n.getSlideType(o)||"video"===n.getSlideType(o)&&l)&&(n.onLgObjectLoad(r,t,b,k,!0,!1),n.onSlideObjectLoad(r,!(!p||!p.html5||l),(function(){n.loadContentOnFirstSlideLoad(t,r,k)}),(function(){n.loadContentOnFirstSlideLoad(t,r,k)})))}),this.settings.startAnimationDuration+100)),r.addClass("lg-loaded"),this.isFirstSlideWithZoomAnimation()&&("video"!==this.getSlideType(o)||l)||this.onLgObjectLoad(r,t,b,k,v,!(!p||!p.html5||l)),this.zoomFromOrigin&&this.currentImageSize||!r.hasClass("lg-complete_")||this.lGalleryOn||setTimeout((function(){r.addClass("lg-complete")}),this.settings.backdropDuration),this.lGalleryOn=!0,!0===i&&(r.hasClass("lg-complete_")?this.preload(t):r.find(".lg-object").first().on("load.lg error.lg",(function(){n.preload(t)})))},w.prototype.loadContentOnFirstSlideLoad=function(t,e,i){var s=this;setTimeout((function(){e.find(".lg-dummy-img").remove(),e.removeClass("lg-first-slide"),s.outer.removeClass("lg-first-slide-loading"),s.isDummyImageRemoved=!0,s.preload(t)}),i+300)},w.prototype.getItemsToBeInsertedToDom=function(t,e,i){var s=this;void 0===i&&(i=0);var n=[],o=Math.max(i,3);o=Math.min(o,this.galleryItems.length);var r="lg-item-"+this.lgId+"-"+e;if(this.galleryItems.length<=3)return this.galleryItems.forEach((function(t,e){n.push("lg-item-"+s.lgId+"-"+e)})),n;if(t<(this.galleryItems.length-1)/2){for(var l=t;l>t-o/2&&l>=0;l--)n.push("lg-item-"+this.lgId+"-"+l);var a=n.length;for(l=0;l')})),this.currentItemsInDom.forEach((function(t){-1===s.indexOf(t)&&x("#"+t).remove()})),s},w.prototype.getPreviousSlideIndex=function(){var t=0;try{var e=this.outer.find(".lg-current").first().attr("id");t=parseInt(e.split("-")[3])||0}catch(e){t=0}return t},w.prototype.setDownloadValue=function(t){if(this.settings.download){var e=this.galleryItems[t];if(!1===e.downloadUrl||"false"===e.downloadUrl)this.outer.addClass("lg-hide-download");else{var i=this.getElementById("lg-download");this.outer.removeClass("lg-hide-download"),i.attr("href",e.downloadUrl||e.src),e.download&&i.attr("download",e.download)}}},w.prototype.makeSlideAnimation=function(t,e,i){var s=this;this.lGalleryOn&&i.addClass("lg-slide-progress"),setTimeout((function(){s.outer.addClass("lg-no-trans"),s.outer.find(".lg-item").removeClass("lg-prev-slide lg-next-slide"),"prev"===t?(e.addClass("lg-prev-slide"),i.addClass("lg-next-slide")):(e.addClass("lg-next-slide"),i.addClass("lg-prev-slide")),setTimeout((function(){s.outer.find(".lg-item").removeClass("lg-current"),e.addClass("lg-current"),s.outer.removeClass("lg-no-trans")}),50)}),this.lGalleryOn?this.settings.slideDelay:0)},w.prototype.slide=function(t,e,i,s){var n=this,o=this.getPreviousSlideIndex();if(this.currentItemsInDom=this.organizeSlideItems(t,o),!this.lGalleryOn||o!==t){var r=this.galleryItems.length;if(!this.lgBusy){this.settings.counter&&this.updateCurrentCounter(t);var l=this.getSlideItem(t),a=this.getSlideItem(o),d=this.galleryItems[t],c=d.__slideVideoInfo;if(this.outer.attr("data-lg-slide-type",this.getSlideType(d)),this.setDownloadValue(t),c){var u=this.mediaContainerPosition,m=u.top,p=u.bottom,f=E(this.items[t],this.outer,m+p,c&&this.settings.videoMaxSize);this.resizeVideoSlide(t,f)}if(this.LGel.trigger(g,{prevIndex:o,index:t,fromTouch:!!e,fromThumb:!!i}),this.lgBusy=!0,clearTimeout(this.hideBarTimeout),this.arrowDisable(t),s||(to&&(s="next")),e){this.outer.find(".lg-item").removeClass("lg-prev-slide lg-current lg-next-slide");var y=void 0,v=void 0;r>2?(y=t-1,v=t+1,(0===t&&o===r-1||t===r-1&&0===o)&&(v=0,y=r-1)):(y=0,v=1),"prev"===s?this.getSlideItem(v).addClass("lg-next-slide"):this.getSlideItem(y).addClass("lg-prev-slide"),l.addClass("lg-current")}else this.makeSlideAnimation(s,l,a);this.lGalleryOn?setTimeout((function(){n.loadContent(t,!0),".lg-item"!==n.settings.appendSubHtmlTo&&n.addHtml(t)}),this.settings.speed+50+(e?0:this.settings.slideDelay)):this.loadContent(t,!0),setTimeout((function(){n.lgBusy=!1,a.removeClass("lg-slide-progress"),n.LGel.trigger(h,{prevIndex:o,index:t,fromTouch:e,fromThumb:i})}),(this.lGalleryOn?this.settings.speed+100:100)+(e?0:this.settings.slideDelay))}this.index=t}},w.prototype.updateCurrentCounter=function(t){this.getElementById("lg-counter-current").html(t+1+"")},w.prototype.updateCounterTotal=function(){this.getElementById("lg-counter-all").html(this.galleryItems.length+"")},w.prototype.getSlideType=function(t){return t.__slideVideoInfo?"video":t.iframe?"iframe":"image"},w.prototype.touchMove=function(t,e,i){var s=e.pageX-t.pageX,n=e.pageY-t.pageY,o=!1;if(this.swipeDirection?o=!0:Math.abs(s)>15?(this.swipeDirection="horizontal",o=!0):Math.abs(n)>15&&(this.swipeDirection="vertical",o=!0),o){var r=this.getSlideItem(this.index);if("horizontal"===this.swipeDirection){null==i||i.preventDefault(),this.outer.addClass("lg-dragging"),this.setTranslate(r,s,0);var l=r.get().offsetWidth,a=15*l/100-Math.abs(10*s/100);this.setTranslate(this.outer.find(".lg-prev-slide").first(),-l+s-a,0),this.setTranslate(this.outer.find(".lg-next-slide").first(),l+s+a,0)}else if("vertical"===this.swipeDirection&&this.settings.swipeToClose){null==i||i.preventDefault(),this.$container.addClass("lg-dragging-vertical");var d=1-Math.abs(n)/window.innerHeight;this.$backdrop.css("opacity",d);var g=1-Math.abs(n)/(2*window.innerWidth);this.setTranslate(r,0,n,g,g),Math.abs(n)>100&&this.outer.addClass("lg-hide-items").removeClass("lg-components-open")}}},w.prototype.touchEnd=function(t,e,i){var s,n=this;"lg-slide"!==this.settings.mode&&this.outer.addClass("lg-slide"),setTimeout((function(){n.$container.removeClass("lg-dragging-vertical"),n.outer.removeClass("lg-dragging lg-hide-items").addClass("lg-components-open");var o=!0;if("horizontal"===n.swipeDirection){s=t.pageX-e.pageX;var r=Math.abs(t.pageX-e.pageX);s<0&&r>n.settings.swipeThreshold?(n.goToNextSlide(!0),o=!1):s>0&&r>n.settings.swipeThreshold&&(n.goToPrevSlide(!0),o=!1)}else if("vertical"===n.swipeDirection){if(s=Math.abs(t.pageY-e.pageY),n.settings.closable&&n.settings.swipeToClose&&s>100)return void n.closeGallery();n.$backdrop.css("opacity",1)}if(n.outer.find(".lg-item").removeAttr("style"),o&&Math.abs(t.pageX-e.pageX)<5){var l=x(i.target);n.isPosterElement(l)&&n.LGel.trigger(c)}n.swipeDirection=void 0})),setTimeout((function(){n.outer.hasClass("lg-dragging")||"lg-slide"===n.settings.mode||n.outer.removeClass("lg-slide")}),this.settings.speed+100)},w.prototype.enableSwipe=function(){var t=this,e={},i={},s=!1,n=!1;this.settings.enableSwipe&&(this.$inner.on("touchstart.lg",(function(i){t.dragOrSwipeEnabled=!0;var s=t.getSlideItem(t.index);!x(i.target).hasClass("lg-item")&&!s.get().contains(i.target)||t.outer.hasClass("lg-zoomed")||t.lgBusy||1!==i.touches.length||(n=!0,t.touchAction="swipe",t.manageSwipeClass(),e={pageX:i.touches[0].pageX,pageY:i.touches[0].pageY})})),this.$inner.on("touchmove.lg",(function(o){n&&"swipe"===t.touchAction&&1===o.touches.length&&(i={pageX:o.touches[0].pageX,pageY:o.touches[0].pageY},t.touchMove(e,i,o),s=!0)})),this.$inner.on("touchend.lg",(function(o){if("swipe"===t.touchAction){if(s)s=!1,t.touchEnd(i,e,o);else if(n){var r=x(o.target);t.isPosterElement(r)&&t.LGel.trigger(c)}t.touchAction=void 0,n=!1}})))},w.prototype.enableDrag=function(){var t=this,e={},i={},s=!1,n=!1;this.settings.enableDrag&&(this.outer.on("mousedown.lg",(function(i){t.dragOrSwipeEnabled=!0;var n=t.getSlideItem(t.index);(x(i.target).hasClass("lg-item")||n.get().contains(i.target))&&(t.outer.hasClass("lg-zoomed")||t.lgBusy||(i.preventDefault(),t.lgBusy||(t.manageSwipeClass(),e={pageX:i.pageX,pageY:i.pageY},s=!0,t.outer.get().scrollLeft+=1,t.outer.get().scrollLeft-=1,t.outer.removeClass("lg-grab").addClass("lg-grabbing"),t.LGel.trigger(u))))})),x(window).on("mousemove.lg.global"+this.lgId,(function(o){s&&t.lgOpened&&(n=!0,i={pageX:o.pageX,pageY:o.pageY},t.touchMove(e,i),t.LGel.trigger(m))})),x(window).on("mouseup.lg.global"+this.lgId,(function(o){if(t.lgOpened){var r=x(o.target);n?(n=!1,t.touchEnd(i,e,o),t.LGel.trigger(p)):t.isPosterElement(r)&&t.LGel.trigger(c),s&&(s=!1,t.outer.removeClass("lg-grabbing").addClass("lg-grab"))}})))},w.prototype.triggerPosterClick=function(){var t=this;this.$inner.on("click.lg",(function(e){!t.dragOrSwipeEnabled&&t.isPosterElement(x(e.target))&&t.LGel.trigger(c)}))},w.prototype.manageSwipeClass=function(){var t=this.index+1,e=this.index-1;this.settings.loop&&this.galleryItems.length>2&&(0===this.index?e=this.galleryItems.length-1:this.index===this.galleryItems.length-1&&(t=0)),this.outer.find(".lg-item").removeClass("lg-next-slide lg-prev-slide"),e>-1&&this.getSlideItem(e).addClass("lg-prev-slide"),this.getSlideItem(t).addClass("lg-next-slide")},w.prototype.goToNextSlide=function(t){var e=this,i=this.settings.loop;t&&this.galleryItems.length<3&&(i=!1),this.lgBusy||(this.index+10?(this.index--,this.LGel.trigger(y,{index:this.index,fromTouch:t}),this.slide(this.index,!!t,!1,"prev")):i?(this.index=this.galleryItems.length-1,this.LGel.trigger(y,{index:this.index,fromTouch:t}),this.slide(this.index,!!t,!1,"prev")):this.settings.slideEndAnimation&&!t&&(this.outer.addClass("lg-left-end"),setTimeout((function(){e.outer.removeClass("lg-left-end")}),400)))},w.prototype.keyPress=function(){var t=this;x(window).on("keydown.lg.global"+this.lgId,(function(e){t.lgOpened&&!0===t.settings.escKey&&27===e.keyCode&&(e.preventDefault(),t.settings.allowMediaOverlap&&t.outer.hasClass("lg-can-toggle")&&t.outer.hasClass("lg-components-open")?t.outer.removeClass("lg-components-open"):t.closeGallery()),t.lgOpened&&t.galleryItems.length>1&&(37===e.keyCode&&(e.preventDefault(),t.goToPrevSlide()),39===e.keyCode&&(e.preventDefault(),t.goToNextSlide()))}))},w.prototype.arrow=function(){var t=this;this.getElementById("lg-prev").on("click.lg",(function(){t.goToPrevSlide()})),this.getElementById("lg-next").on("click.lg",(function(){t.goToNextSlide()}))},w.prototype.arrowDisable=function(t){if(!this.settings.loop&&this.settings.hideControlOnEnd){var e=this.getElementById("lg-prev"),i=this.getElementById("lg-next");t+1===this.galleryItems.length?i.attr("disabled","disabled").addClass("disabled"):i.removeAttr("disabled").removeClass("disabled"),0===t?e.attr("disabled","disabled").addClass("disabled"):e.removeAttr("disabled").removeClass("disabled")}},w.prototype.setTranslate=function(t,e,i,s,n){void 0===s&&(s=1),void 0===n&&(n=1),t.css("transform","translate3d("+e+"px, "+i+"px, 0px) scale3d("+s+", "+n+", 1)")},w.prototype.mousewheel=function(){var t=this,e=0;this.outer.on("wheel.lg",(function(i){if(i.deltaY&&!(t.galleryItems.length<2)){i.preventDefault();var s=(new Date).getTime();s-e<1e3||(e=s,i.deltaY>0?t.goToNextSlide():i.deltaY<0&&t.goToPrevSlide())}}))},w.prototype.isSlideElement=function(t){return t.hasClass("lg-outer")||t.hasClass("lg-item")||t.hasClass("lg-img-wrap")||t.hasClass("lg-img-rotate")},w.prototype.isPosterElement=function(t){var e=this.getSlideItem(this.index).find(".lg-video-play-button").get();return t.hasClass("lg-video-poster")||t.hasClass("lg-video-play-button")||e&&e.contains(t.get())},w.prototype.toggleMaximize=function(){var t=this;this.getElementById("lg-maximize").on("click.lg",(function(){t.$container.toggleClass("lg-inline"),t.refreshOnResize()}))},w.prototype.invalidateItems=function(){for(var t=0;t} Content
+ */
+
+/** @typedef {{ x?: number; y?: number }} Point */
+
+/**
+ * @typedef {Object} PhotoSwipeEventsMap https://photoswipe.com/events/
+ *
+ *
+ * https://photoswipe.com/adding-ui-elements/
+ *
+ * @prop {undefined} uiRegister
+ * @prop {{ data: UIElementData }} uiElementCreate
+ *
+ *
+ * https://photoswipe.com/events/#initialization-events
+ *
+ * @prop {undefined} beforeOpen
+ * @prop {undefined} firstUpdate
+ * @prop {undefined} initialLayout
+ * @prop {undefined} change
+ * @prop {undefined} afterInit
+ * @prop {undefined} bindEvents
+ *
+ *
+ * https://photoswipe.com/events/#opening-or-closing-transition-events
+ *
+ * @prop {undefined} openingAnimationStart
+ * @prop {undefined} openingAnimationEnd
+ * @prop {undefined} closingAnimationStart
+ * @prop {undefined} closingAnimationEnd
+ *
+ *
+ * https://photoswipe.com/events/#closing-events
+ *
+ * @prop {undefined} close
+ * @prop {undefined} destroy
+ *
+ *
+ * https://photoswipe.com/events/#pointer-and-gesture-events
+ *
+ * @prop {{ originalEvent: PointerEvent }} pointerDown
+ * @prop {{ originalEvent: PointerEvent }} pointerMove
+ * @prop {{ originalEvent: PointerEvent }} pointerUp
+ * @prop {{ bgOpacity: number }} pinchClose can be default prevented
+ * @prop {{ panY: number }} verticalDrag can be default prevented
+ *
+ *
+ * https://photoswipe.com/events/#slide-content-events
+ *
+ * @prop {{ content: Content }} contentInit
+ * @prop {{ content: Content; isLazy: boolean }} contentLoad can be default prevented
+ * @prop {{ content: Content; isLazy: boolean }} contentLoadImage can be default prevented
+ * @prop {{ content: Content; slide: Slide; isError?: boolean }} loadComplete
+ * @prop {{ content: Content; slide: Slide }} loadError
+ * @prop {{ content: Content; width: number; height: number }} contentResize can be default prevented
+ * @prop {{ content: Content; width: number; height: number; slide: Slide }} imageSizeChange
+ * @prop {{ content: Content }} contentLazyLoad can be default prevented
+ * @prop {{ content: Content }} contentAppend can be default prevented
+ * @prop {{ content: Content }} contentActivate can be default prevented
+ * @prop {{ content: Content }} contentDeactivate can be default prevented
+ * @prop {{ content: Content }} contentRemove can be default prevented
+ * @prop {{ content: Content }} contentDestroy can be default prevented
+ *
+ *
+ * undocumented
+ *
+ * @prop {{ point: Point; originalEvent: PointerEvent }} imageClickAction can be default prevented
+ * @prop {{ point: Point; originalEvent: PointerEvent }} bgClickAction can be default prevented
+ * @prop {{ point: Point; originalEvent: PointerEvent }} tapAction can be default prevented
+ * @prop {{ point: Point; originalEvent: PointerEvent }} doubleTapAction can be default prevented
+ *
+ * @prop {{ originalEvent: KeyboardEvent }} keydown can be default prevented
+ * @prop {{ x: number; dragging: boolean }} moveMainScroll
+ * @prop {{ slide: Slide }} firstZoomPan
+ * @prop {{ slide: Slide | undefined, data: SlideData, index: number }} gettingData
+ * @prop {undefined} beforeResize
+ * @prop {undefined} resize
+ * @prop {undefined} viewportSize
+ * @prop {undefined} updateScrollOffset
+ * @prop {{ slide: Slide }} slideInit
+ * @prop {{ slide: Slide }} afterSetContent
+ * @prop {{ slide: Slide }} slideLoad
+ * @prop {{ slide: Slide }} appendHeavy can be default prevented
+ * @prop {{ slide: Slide }} appendHeavyContent
+ * @prop {{ slide: Slide }} slideActivate
+ * @prop {{ slide: Slide }} slideDeactivate
+ * @prop {{ slide: Slide }} slideDestroy
+ * @prop {{ destZoomLevel: number, centerPoint: Point | undefined, transitionDuration: number | false | undefined }} beforeZoomTo
+ * @prop {{ slide: Slide }} zoomPanUpdate
+ * @prop {{ slide: Slide }} initialZoomPan
+ * @prop {{ slide: Slide }} calcSlideSize
+ * @prop {undefined} resolutionChanged
+ * @prop {{ originalEvent: WheelEvent }} wheel can be default prevented
+ * @prop {{ content: Content }} contentAppendImage can be default prevented
+ * @prop {{ index: number; itemData: SlideData }} lazyLoadSlide can be default prevented
+ * @prop {undefined} lazyLoad
+ * @prop {{ slide: Slide }} calcBounds
+ * @prop {{ zoomLevels: ZoomLevel, slideData: SlideData }} zoomLevelsUpdate
+ *
+ *
+ * legacy
+ *
+ * @prop {undefined} init
+ * @prop {undefined} initialZoomIn
+ * @prop {undefined} initialZoomOut
+ * @prop {undefined} initialZoomInEnd
+ * @prop {undefined} initialZoomOutEnd
+ * @prop {{ dataSource: DataSource | undefined, numItems: number }} numItems
+ * @prop {{ itemData: SlideData; index: number }} itemData
+ * @prop {{ index: number, itemData: SlideData, instance: PhotoSwipe }} thumbBounds
+ */
+
+/**
+ * @typedef {Object} PhotoSwipeFiltersMap https://photoswipe.com/filters/
+ *
+ * @prop {(numItems: number, dataSource: DataSource | undefined) => number} numItems
+ * Modify the total amount of slides. Example on Data sources page.
+ * https://photoswipe.com/filters/#numitems
+ *
+ * @prop {(itemData: SlideData, index: number) => SlideData} itemData
+ * Modify slide item data. Example on Data sources page.
+ * https://photoswipe.com/filters/#itemdata
+ *
+ * @prop {(itemData: SlideData, element: HTMLElement, linkEl: HTMLAnchorElement) => SlideData} domItemData
+ * Modify item data when it's parsed from DOM element. Example on Data sources page.
+ * https://photoswipe.com/filters/#domitemdata
+ *
+ * @prop {(clickedIndex: number, e: MouseEvent, instance: PhotoSwipeLightbox) => number} clickedIndex
+ * Modify clicked gallery item index.
+ * https://photoswipe.com/filters/#clickedindex
+ *
+ * @prop {(placeholderSrc: string | false, content: Content) => string | false} placeholderSrc
+ * Modify placeholder image source.
+ * https://photoswipe.com/filters/#placeholdersrc
+ *
+ * @prop {(isContentLoading: boolean, content: Content) => boolean} isContentLoading
+ * Modify if the content is currently loading.
+ * https://photoswipe.com/filters/#iscontentloading
+ *
+ * @prop {(isContentZoomable: boolean, content: Content) => boolean} isContentZoomable
+ * Modify if the content can be zoomed.
+ * https://photoswipe.com/filters/#iscontentzoomable
+ *
+ * @prop {(useContentPlaceholder: boolean, content: Content) => boolean} useContentPlaceholder
+ * Modify if the placeholder should be used for the content.
+ * https://photoswipe.com/filters/#usecontentplaceholder
+ *
+ * @prop {(isKeepingPlaceholder: boolean, content: Content) => boolean} isKeepingPlaceholder
+ * Modify if the placeholder should be kept after the content is loaded.
+ * https://photoswipe.com/filters/#iskeepingplaceholder
+ *
+ *
+ * @prop {(contentErrorElement: HTMLElement, content: Content) => HTMLElement} contentErrorElement
+ * Modify an element when the content has error state (for example, if image cannot be loaded).
+ * https://photoswipe.com/filters/#contenterrorelement
+ *
+ * @prop {(element: HTMLElement, data: UIElementData) => HTMLElement} uiElement
+ * Modify a UI element that's being created.
+ * https://photoswipe.com/filters/#uielement
+ *
+ * @prop {(thumbnail: HTMLElement | null | undefined, itemData: SlideData, index: number) => HTMLElement} thumbEl
+ * Modify the thumbnail element from which opening zoom animation starts or ends.
+ * https://photoswipe.com/filters/#thumbel
+ *
+ * @prop {(thumbBounds: Bounds | undefined, itemData: SlideData, index: number) => Bounds} thumbBounds
+ * Modify the thumbnail bounds from which opening zoom animation starts or ends.
+ * https://photoswipe.com/filters/#thumbbounds
+ *
+ * @prop {(srcsetSizesWidth: number, content: Content) => number} srcsetSizesWidth
+ *
+ * @prop {(preventPointerEvent: boolean, event: PointerEvent, pointerType: string) => boolean} preventPointerEvent
+ *
+ */
+
+/**
+ * @template {keyof PhotoSwipeFiltersMap} T
+ * @typedef {{ fn: PhotoSwipeFiltersMap[T], priority: number }} Filter
+ */
+
+/**
+ * @template {keyof PhotoSwipeEventsMap} T
+ * @typedef {PhotoSwipeEventsMap[T] extends undefined ? PhotoSwipeEvent : PhotoSwipeEvent & PhotoSwipeEventsMap[T]} AugmentedEvent
+ */
+
+/**
+ * @template {keyof PhotoSwipeEventsMap} T
+ * @typedef {(event: AugmentedEvent) => void} EventCallback
+ */
+
+/**
+ * Base PhotoSwipe event object
+ *
+ * @template {keyof PhotoSwipeEventsMap} T
+ */
+class PhotoSwipeEvent {
+ /**
+ * @param {T} type
+ * @param {PhotoSwipeEventsMap[T]} [details]
+ */
+ constructor(type, details) {
+ this.type = type;
+ this.defaultPrevented = false;
+
+ if (details) {
+ Object.assign(this, details);
+ }
+ }
+
+ preventDefault() {
+ this.defaultPrevented = true;
+ }
+
+}
+/**
+ * PhotoSwipe base class that can listen and dispatch for events.
+ * Shared by PhotoSwipe Core and PhotoSwipe Lightbox, extended by base.js
+ */
+
+
+class Eventable {
+ constructor() {
+ /**
+ * @type {{ [T in keyof PhotoSwipeEventsMap]?: ((event: AugmentedEvent) => void)[] }}
+ */
+ this._listeners = {};
+ /**
+ * @type {{ [T in keyof PhotoSwipeFiltersMap]?: Filter[] }}
+ */
+
+ this._filters = {};
+ /** @type {PhotoSwipe | undefined} */
+
+ this.pswp = undefined;
+ /** @type {PhotoSwipeOptions | undefined} */
+
+ this.options = undefined;
+ }
+ /**
+ * @template {keyof PhotoSwipeFiltersMap} T
+ * @param {T} name
+ * @param {PhotoSwipeFiltersMap[T]} fn
+ * @param {number} priority
+ */
+
+
+ addFilter(name, fn, priority = 100) {
+ var _this$_filters$name, _this$_filters$name2, _this$pswp;
+
+ if (!this._filters[name]) {
+ this._filters[name] = [];
+ }
+
+ (_this$_filters$name = this._filters[name]) === null || _this$_filters$name === void 0 || _this$_filters$name.push({
+ fn,
+ priority
+ });
+ (_this$_filters$name2 = this._filters[name]) === null || _this$_filters$name2 === void 0 || _this$_filters$name2.sort((f1, f2) => f1.priority - f2.priority);
+ (_this$pswp = this.pswp) === null || _this$pswp === void 0 || _this$pswp.addFilter(name, fn, priority);
+ }
+ /**
+ * @template {keyof PhotoSwipeFiltersMap} T
+ * @param {T} name
+ * @param {PhotoSwipeFiltersMap[T]} fn
+ */
+
+
+ removeFilter(name, fn) {
+ if (this._filters[name]) {
+ // @ts-expect-error
+ this._filters[name] = this._filters[name].filter(filter => filter.fn !== fn);
+ }
+
+ if (this.pswp) {
+ this.pswp.removeFilter(name, fn);
+ }
+ }
+ /**
+ * @template {keyof PhotoSwipeFiltersMap} T
+ * @param {T} name
+ * @param {Parameters} args
+ * @returns {Parameters[0]}
+ */
+
+
+ applyFilters(name, ...args) {
+ var _this$_filters$name3;
+
+ (_this$_filters$name3 = this._filters[name]) === null || _this$_filters$name3 === void 0 || _this$_filters$name3.forEach(filter => {
+ // @ts-expect-error
+ args[0] = filter.fn.apply(this, args);
+ });
+ return args[0];
+ }
+ /**
+ * @template {keyof PhotoSwipeEventsMap} T
+ * @param {T} name
+ * @param {EventCallback} fn
+ */
+
+
+ on(name, fn) {
+ var _this$_listeners$name, _this$pswp2;
+
+ if (!this._listeners[name]) {
+ this._listeners[name] = [];
+ }
+
+ (_this$_listeners$name = this._listeners[name]) === null || _this$_listeners$name === void 0 || _this$_listeners$name.push(fn); // When binding events to lightbox,
+ // also bind events to PhotoSwipe Core,
+ // if it's open.
+
+ (_this$pswp2 = this.pswp) === null || _this$pswp2 === void 0 || _this$pswp2.on(name, fn);
+ }
+ /**
+ * @template {keyof PhotoSwipeEventsMap} T
+ * @param {T} name
+ * @param {EventCallback} fn
+ */
+
+
+ off(name, fn) {
+ var _this$pswp3;
+
+ if (this._listeners[name]) {
+ // @ts-expect-error
+ this._listeners[name] = this._listeners[name].filter(listener => fn !== listener);
+ }
+
+ (_this$pswp3 = this.pswp) === null || _this$pswp3 === void 0 || _this$pswp3.off(name, fn);
+ }
+ /**
+ * @template {keyof PhotoSwipeEventsMap} T
+ * @param {T} name
+ * @param {PhotoSwipeEventsMap[T]} [details]
+ * @returns {AugmentedEvent}
+ */
+
+
+ dispatch(name, details) {
+ var _this$_listeners$name2;
+
+ if (this.pswp) {
+ return this.pswp.dispatch(name, details);
+ }
+
+ const event =
+ /** @type {AugmentedEvent} */
+ new PhotoSwipeEvent(name, details);
+ (_this$_listeners$name2 = this._listeners[name]) === null || _this$_listeners$name2 === void 0 || _this$_listeners$name2.forEach(listener => {
+ listener.call(this, event);
+ });
+ return event;
+ }
+
+}
+
+class Placeholder {
+ /**
+ * @param {string | false} imageSrc
+ * @param {HTMLElement} container
+ */
+ constructor(imageSrc, container) {
+ // Create placeholder
+ // (stretched thumbnail or simple div behind the main image)
+
+ /** @type {HTMLImageElement | HTMLDivElement | null} */
+ this.element = createElement('pswp__img pswp__img--placeholder', imageSrc ? 'img' : 'div', container);
+
+ if (imageSrc) {
+ const imgEl =
+ /** @type {HTMLImageElement} */
+ this.element;
+ imgEl.decoding = 'async';
+ imgEl.alt = '';
+ imgEl.src = imageSrc;
+ imgEl.setAttribute('role', 'presentation');
+ }
+
+ this.element.setAttribute('aria-hidden', 'true');
+ }
+ /**
+ * @param {number} width
+ * @param {number} height
+ */
+
+
+ setDisplayedSize(width, height) {
+ if (!this.element) {
+ return;
+ }
+
+ if (this.element.tagName === 'IMG') {
+ // Use transform scale() to modify img placeholder size
+ // (instead of changing width/height directly).
+ // This helps with performance, specifically in iOS15 Safari.
+ setWidthHeight(this.element, 250, 'auto');
+ this.element.style.transformOrigin = '0 0';
+ this.element.style.transform = toTransformString(0, 0, width / 250);
+ } else {
+ setWidthHeight(this.element, width, height);
+ }
+ }
+
+ destroy() {
+ var _this$element;
+
+ if ((_this$element = this.element) !== null && _this$element !== void 0 && _this$element.parentNode) {
+ this.element.remove();
+ }
+
+ this.element = null;
+ }
+
+}
+
+/** @typedef {import('./slide.js').default} Slide */
+
+/** @typedef {import('./slide.js').SlideData} SlideData */
+
+/** @typedef {import('../core/base.js').default} PhotoSwipeBase */
+
+/** @typedef {import('../util/util.js').LoadState} LoadState */
+
+class Content {
+ /**
+ * @param {SlideData} itemData Slide data
+ * @param {PhotoSwipeBase} instance PhotoSwipe or PhotoSwipeLightbox instance
+ * @param {number} index
+ */
+ constructor(itemData, instance, index) {
+ this.instance = instance;
+ this.data = itemData;
+ this.index = index;
+ /** @type {HTMLImageElement | HTMLDivElement | undefined} */
+
+ this.element = undefined;
+ /** @type {Placeholder | undefined} */
+
+ this.placeholder = undefined;
+ /** @type {Slide | undefined} */
+
+ this.slide = undefined;
+ this.displayedImageWidth = 0;
+ this.displayedImageHeight = 0;
+ this.width = Number(this.data.w) || Number(this.data.width) || 0;
+ this.height = Number(this.data.h) || Number(this.data.height) || 0;
+ this.isAttached = false;
+ this.hasSlide = false;
+ this.isDecoding = false;
+ /** @type {LoadState} */
+
+ this.state = LOAD_STATE.IDLE;
+
+ if (this.data.type) {
+ this.type = this.data.type;
+ } else if (this.data.src) {
+ this.type = 'image';
+ } else {
+ this.type = 'html';
+ }
+
+ this.instance.dispatch('contentInit', {
+ content: this
+ });
+ }
+
+ removePlaceholder() {
+ if (this.placeholder && !this.keepPlaceholder()) {
+ // With delay, as image might be loaded, but not rendered
+ setTimeout(() => {
+ if (this.placeholder) {
+ this.placeholder.destroy();
+ this.placeholder = undefined;
+ }
+ }, 1000);
+ }
+ }
+ /**
+ * Preload content
+ *
+ * @param {boolean} isLazy
+ * @param {boolean} [reload]
+ */
+
+
+ load(isLazy, reload) {
+ if (this.slide && this.usePlaceholder()) {
+ if (!this.placeholder) {
+ const placeholderSrc = this.instance.applyFilters('placeholderSrc', // use image-based placeholder only for the first slide,
+ // as rendering (even small stretched thumbnail) is an expensive operation
+ this.data.msrc && this.slide.isFirstSlide ? this.data.msrc : false, this);
+ this.placeholder = new Placeholder(placeholderSrc, this.slide.container);
+ } else {
+ const placeholderEl = this.placeholder.element; // Add placeholder to DOM if it was already created
+
+ if (placeholderEl && !placeholderEl.parentElement) {
+ this.slide.container.prepend(placeholderEl);
+ }
+ }
+ }
+
+ if (this.element && !reload) {
+ return;
+ }
+
+ if (this.instance.dispatch('contentLoad', {
+ content: this,
+ isLazy
+ }).defaultPrevented) {
+ return;
+ }
+
+ if (this.isImageContent()) {
+ this.element = createElement('pswp__img', 'img'); // Start loading only after width is defined, as sizes might depend on it.
+ // Due to Safari feature, we must define sizes before srcset.
+
+ if (this.displayedImageWidth) {
+ this.loadImage(isLazy);
+ }
+ } else {
+ this.element = createElement('pswp__content', 'div');
+ this.element.innerHTML = this.data.html || '';
+ }
+
+ if (reload && this.slide) {
+ this.slide.updateContentSize(true);
+ }
+ }
+ /**
+ * Preload image
+ *
+ * @param {boolean} isLazy
+ */
+
+
+ loadImage(isLazy) {
+ var _this$data$src, _this$data$alt;
+
+ if (!this.isImageContent() || !this.element || this.instance.dispatch('contentLoadImage', {
+ content: this,
+ isLazy
+ }).defaultPrevented) {
+ return;
+ }
+
+ const imageElement =
+ /** @type HTMLImageElement */
+ this.element;
+ this.updateSrcsetSizes();
+
+ if (this.data.srcset) {
+ imageElement.srcset = this.data.srcset;
+ }
+
+ imageElement.src = (_this$data$src = this.data.src) !== null && _this$data$src !== void 0 ? _this$data$src : '';
+ imageElement.alt = (_this$data$alt = this.data.alt) !== null && _this$data$alt !== void 0 ? _this$data$alt : '';
+ this.state = LOAD_STATE.LOADING;
+
+ if (imageElement.complete) {
+ this.onLoaded();
+ } else {
+ imageElement.onload = () => {
+ this.onLoaded();
+ };
+
+ imageElement.onerror = () => {
+ this.onError();
+ };
+ }
+ }
+ /**
+ * Assign slide to content
+ *
+ * @param {Slide} slide
+ */
+
+
+ setSlide(slide) {
+ this.slide = slide;
+ this.hasSlide = true;
+ this.instance = slide.pswp; // todo: do we need to unset slide?
+ }
+ /**
+ * Content load success handler
+ */
+
+
+ onLoaded() {
+ this.state = LOAD_STATE.LOADED;
+
+ if (this.slide && this.element) {
+ this.instance.dispatch('loadComplete', {
+ slide: this.slide,
+ content: this
+ }); // if content is reloaded
+
+ if (this.slide.isActive && this.slide.heavyAppended && !this.element.parentNode) {
+ this.append();
+ this.slide.updateContentSize(true);
+ }
+
+ if (this.state === LOAD_STATE.LOADED || this.state === LOAD_STATE.ERROR) {
+ this.removePlaceholder();
+ }
+ }
+ }
+ /**
+ * Content load error handler
+ */
+
+
+ onError() {
+ this.state = LOAD_STATE.ERROR;
+
+ if (this.slide) {
+ this.displayError();
+ this.instance.dispatch('loadComplete', {
+ slide: this.slide,
+ isError: true,
+ content: this
+ });
+ this.instance.dispatch('loadError', {
+ slide: this.slide,
+ content: this
+ });
+ }
+ }
+ /**
+ * @returns {Boolean} If the content is currently loading
+ */
+
+
+ isLoading() {
+ return this.instance.applyFilters('isContentLoading', this.state === LOAD_STATE.LOADING, this);
+ }
+ /**
+ * @returns {Boolean} If the content is in error state
+ */
+
+
+ isError() {
+ return this.state === LOAD_STATE.ERROR;
+ }
+ /**
+ * @returns {boolean} If the content is image
+ */
+
+
+ isImageContent() {
+ return this.type === 'image';
+ }
+ /**
+ * Update content size
+ *
+ * @param {Number} width
+ * @param {Number} height
+ */
+
+
+ setDisplayedSize(width, height) {
+ if (!this.element) {
+ return;
+ }
+
+ if (this.placeholder) {
+ this.placeholder.setDisplayedSize(width, height);
+ }
+
+ if (this.instance.dispatch('contentResize', {
+ content: this,
+ width,
+ height
+ }).defaultPrevented) {
+ return;
+ }
+
+ setWidthHeight(this.element, width, height);
+
+ if (this.isImageContent() && !this.isError()) {
+ const isInitialSizeUpdate = !this.displayedImageWidth && width;
+ this.displayedImageWidth = width;
+ this.displayedImageHeight = height;
+
+ if (isInitialSizeUpdate) {
+ this.loadImage(false);
+ } else {
+ this.updateSrcsetSizes();
+ }
+
+ if (this.slide) {
+ this.instance.dispatch('imageSizeChange', {
+ slide: this.slide,
+ width,
+ height,
+ content: this
+ });
+ }
+ }
+ }
+ /**
+ * @returns {boolean} If the content can be zoomed
+ */
+
+
+ isZoomable() {
+ return this.instance.applyFilters('isContentZoomable', this.isImageContent() && this.state !== LOAD_STATE.ERROR, this);
+ }
+ /**
+ * Update image srcset sizes attribute based on width and height
+ */
+
+
+ updateSrcsetSizes() {
+ // Handle srcset sizes attribute.
+ //
+ // Never lower quality, if it was increased previously.
+ // Chrome does this automatically, Firefox and Safari do not,
+ // so we store largest used size in dataset.
+ if (!this.isImageContent() || !this.element || !this.data.srcset) {
+ return;
+ }
+
+ const image =
+ /** @type HTMLImageElement */
+ this.element;
+ const sizesWidth = this.instance.applyFilters('srcsetSizesWidth', this.displayedImageWidth, this);
+
+ if (!image.dataset.largestUsedSize || sizesWidth > parseInt(image.dataset.largestUsedSize, 10)) {
+ image.sizes = sizesWidth + 'px';
+ image.dataset.largestUsedSize = String(sizesWidth);
+ }
+ }
+ /**
+ * @returns {boolean} If content should use a placeholder (from msrc by default)
+ */
+
+
+ usePlaceholder() {
+ return this.instance.applyFilters('useContentPlaceholder', this.isImageContent(), this);
+ }
+ /**
+ * Preload content with lazy-loading param
+ */
+
+
+ lazyLoad() {
+ if (this.instance.dispatch('contentLazyLoad', {
+ content: this
+ }).defaultPrevented) {
+ return;
+ }
+
+ this.load(true);
+ }
+ /**
+ * @returns {boolean} If placeholder should be kept after content is loaded
+ */
+
+
+ keepPlaceholder() {
+ return this.instance.applyFilters('isKeepingPlaceholder', this.isLoading(), this);
+ }
+ /**
+ * Destroy the content
+ */
+
+
+ destroy() {
+ this.hasSlide = false;
+ this.slide = undefined;
+
+ if (this.instance.dispatch('contentDestroy', {
+ content: this
+ }).defaultPrevented) {
+ return;
+ }
+
+ this.remove();
+
+ if (this.placeholder) {
+ this.placeholder.destroy();
+ this.placeholder = undefined;
+ }
+
+ if (this.isImageContent() && this.element) {
+ this.element.onload = null;
+ this.element.onerror = null;
+ this.element = undefined;
+ }
+ }
+ /**
+ * Display error message
+ */
+
+
+ displayError() {
+ if (this.slide) {
+ var _this$instance$option, _this$instance$option2;
+
+ let errorMsgEl = createElement('pswp__error-msg', 'div');
+ errorMsgEl.innerText = (_this$instance$option = (_this$instance$option2 = this.instance.options) === null || _this$instance$option2 === void 0 ? void 0 : _this$instance$option2.errorMsg) !== null && _this$instance$option !== void 0 ? _this$instance$option : '';
+ errorMsgEl =
+ /** @type {HTMLDivElement} */
+ this.instance.applyFilters('contentErrorElement', errorMsgEl, this);
+ this.element = createElement('pswp__content pswp__error-msg-container', 'div');
+ this.element.appendChild(errorMsgEl);
+ this.slide.container.innerText = '';
+ this.slide.container.appendChild(this.element);
+ this.slide.updateContentSize(true);
+ this.removePlaceholder();
+ }
+ }
+ /**
+ * Append the content
+ */
+
+
+ append() {
+ if (this.isAttached || !this.element) {
+ return;
+ }
+
+ this.isAttached = true;
+
+ if (this.state === LOAD_STATE.ERROR) {
+ this.displayError();
+ return;
+ }
+
+ if (this.instance.dispatch('contentAppend', {
+ content: this
+ }).defaultPrevented) {
+ return;
+ }
+
+ const supportsDecode = ('decode' in this.element);
+
+ if (this.isImageContent()) {
+ // Use decode() on nearby slides
+ //
+ // Nearby slide images are in DOM and not hidden via display:none.
+ // However, they are placed offscreen (to the left and right side).
+ //
+ // Some browsers do not composite the image until it's actually visible,
+ // using decode() helps.
+ //
+ // You might ask "why dont you just decode() and then append all images",
+ // that's because I want to show image before it's fully loaded,
+ // as browser can render parts of image while it is loading.
+ // We do not do this in Safari due to partial loading bug.
+ if (supportsDecode && this.slide && (!this.slide.isActive || isSafari())) {
+ this.isDecoding = true; // purposefully using finally instead of then,
+ // as if srcset sizes changes dynamically - it may cause decode error
+
+ /** @type {HTMLImageElement} */
+
+ this.element.decode().catch(() => {}).finally(() => {
+ this.isDecoding = false;
+ this.appendImage();
+ });
+ } else {
+ this.appendImage();
+ }
+ } else if (this.slide && !this.element.parentNode) {
+ this.slide.container.appendChild(this.element);
+ }
+ }
+ /**
+ * Activate the slide,
+ * active slide is generally the current one,
+ * meaning the user can see it.
+ */
+
+
+ activate() {
+ if (this.instance.dispatch('contentActivate', {
+ content: this
+ }).defaultPrevented || !this.slide) {
+ return;
+ }
+
+ if (this.isImageContent() && this.isDecoding && !isSafari()) {
+ // add image to slide when it becomes active,
+ // even if it's not finished decoding
+ this.appendImage();
+ } else if (this.isError()) {
+ this.load(false, true); // try to reload
+ }
+
+ if (this.slide.holderElement) {
+ this.slide.holderElement.setAttribute('aria-hidden', 'false');
+ }
+ }
+ /**
+ * Deactivate the content
+ */
+
+
+ deactivate() {
+ this.instance.dispatch('contentDeactivate', {
+ content: this
+ });
+
+ if (this.slide && this.slide.holderElement) {
+ this.slide.holderElement.setAttribute('aria-hidden', 'true');
+ }
+ }
+ /**
+ * Remove the content from DOM
+ */
+
+
+ remove() {
+ this.isAttached = false;
+
+ if (this.instance.dispatch('contentRemove', {
+ content: this
+ }).defaultPrevented) {
+ return;
+ }
+
+ if (this.element && this.element.parentNode) {
+ this.element.remove();
+ }
+
+ if (this.placeholder && this.placeholder.element) {
+ this.placeholder.element.remove();
+ }
+ }
+ /**
+ * Append the image content to slide container
+ */
+
+
+ appendImage() {
+ if (!this.isAttached) {
+ return;
+ }
+
+ if (this.instance.dispatch('contentAppendImage', {
+ content: this
+ }).defaultPrevented) {
+ return;
+ } // ensure that element exists and is not already appended
+
+
+ if (this.slide && this.element && !this.element.parentNode) {
+ this.slide.container.appendChild(this.element);
+ }
+
+ if (this.state === LOAD_STATE.LOADED || this.state === LOAD_STATE.ERROR) {
+ this.removePlaceholder();
+ }
+ }
+
+}
+
+/** @typedef {import('../photoswipe.js').PhotoSwipeOptions} PhotoSwipeOptions */
+
+/** @typedef {import('../core/base.js').default} PhotoSwipeBase */
+
+/** @typedef {import('../photoswipe.js').Point} Point */
+
+/** @typedef {import('../slide/slide.js').SlideData} SlideData */
+
+/**
+ * @param {PhotoSwipeOptions} options
+ * @param {PhotoSwipeBase} pswp
+ * @returns {Point}
+ */
+function getViewportSize(options, pswp) {
+ if (options.getViewportSizeFn) {
+ const newViewportSize = options.getViewportSizeFn(options, pswp);
+
+ if (newViewportSize) {
+ return newViewportSize;
+ }
+ }
+
+ return {
+ x: document.documentElement.clientWidth,
+ // TODO: height on mobile is very incosistent due to toolbar
+ // find a way to improve this
+ //
+ // document.documentElement.clientHeight - doesn't seem to work well
+ y: window.innerHeight
+ };
+}
+/**
+ * Parses padding option.
+ * Supported formats:
+ *
+ * // Object
+ * padding: {
+ * top: 0,
+ * bottom: 0,
+ * left: 0,
+ * right: 0
+ * }
+ *
+ * // A function that returns the object
+ * paddingFn: (viewportSize, itemData, index) => {
+ * return {
+ * top: 0,
+ * bottom: 0,
+ * left: 0,
+ * right: 0
+ * };
+ * }
+ *
+ * // Legacy variant
+ * paddingLeft: 0,
+ * paddingRight: 0,
+ * paddingTop: 0,
+ * paddingBottom: 0,
+ *
+ * @param {'left' | 'top' | 'bottom' | 'right'} prop
+ * @param {PhotoSwipeOptions} options PhotoSwipe options
+ * @param {Point} viewportSize PhotoSwipe viewport size, for example: { x:800, y:600 }
+ * @param {SlideData} itemData Data about the slide
+ * @param {number} index Slide index
+ * @returns {number}
+ */
+
+function parsePaddingOption(prop, options, viewportSize, itemData, index) {
+ let paddingValue = 0;
+
+ if (options.paddingFn) {
+ paddingValue = options.paddingFn(viewportSize, itemData, index)[prop];
+ } else if (options.padding) {
+ paddingValue = options.padding[prop];
+ } else {
+ const legacyPropName = 'padding' + prop[0].toUpperCase() + prop.slice(1); // @ts-expect-error
+
+ if (options[legacyPropName]) {
+ // @ts-expect-error
+ paddingValue = options[legacyPropName];
+ }
+ }
+
+ return Number(paddingValue) || 0;
+}
+/**
+ * @param {PhotoSwipeOptions} options
+ * @param {Point} viewportSize
+ * @param {SlideData} itemData
+ * @param {number} index
+ * @returns {Point}
+ */
+
+function getPanAreaSize(options, viewportSize, itemData, index) {
+ return {
+ x: viewportSize.x - parsePaddingOption('left', options, viewportSize, itemData, index) - parsePaddingOption('right', options, viewportSize, itemData, index),
+ y: viewportSize.y - parsePaddingOption('top', options, viewportSize, itemData, index) - parsePaddingOption('bottom', options, viewportSize, itemData, index)
+ };
+}
+
+const MAX_IMAGE_WIDTH = 4000;
+/** @typedef {import('../photoswipe.js').default} PhotoSwipe */
+
+/** @typedef {import('../photoswipe.js').PhotoSwipeOptions} PhotoSwipeOptions */
+
+/** @typedef {import('../photoswipe.js').Point} Point */
+
+/** @typedef {import('../slide/slide.js').SlideData} SlideData */
+
+/** @typedef {'fit' | 'fill' | number | ((zoomLevelObject: ZoomLevel) => number)} ZoomLevelOption */
+
+/**
+ * Calculates zoom levels for specific slide.
+ * Depends on viewport size and image size.
+ */
+
+class ZoomLevel {
+ /**
+ * @param {PhotoSwipeOptions} options PhotoSwipe options
+ * @param {SlideData} itemData Slide data
+ * @param {number} index Slide index
+ * @param {PhotoSwipe} [pswp] PhotoSwipe instance, can be undefined if not initialized yet
+ */
+ constructor(options, itemData, index, pswp) {
+ this.pswp = pswp;
+ this.options = options;
+ this.itemData = itemData;
+ this.index = index;
+ /** @type { Point | null } */
+
+ this.panAreaSize = null;
+ /** @type { Point | null } */
+
+ this.elementSize = null;
+ this.fit = 1;
+ this.fill = 1;
+ this.vFill = 1;
+ this.initial = 1;
+ this.secondary = 1;
+ this.max = 1;
+ this.min = 1;
+ }
+ /**
+ * Calculate initial, secondary and maximum zoom level for the specified slide.
+ *
+ * It should be called when either image or viewport size changes.
+ *
+ * @param {number} maxWidth
+ * @param {number} maxHeight
+ * @param {Point} panAreaSize
+ */
+
+
+ update(maxWidth, maxHeight, panAreaSize) {
+ /** @type {Point} */
+ const elementSize = {
+ x: maxWidth,
+ y: maxHeight
+ };
+ this.elementSize = elementSize;
+ this.panAreaSize = panAreaSize;
+ const hRatio = panAreaSize.x / elementSize.x;
+ const vRatio = panAreaSize.y / elementSize.y;
+ this.fit = Math.min(1, hRatio < vRatio ? hRatio : vRatio);
+ this.fill = Math.min(1, hRatio > vRatio ? hRatio : vRatio); // zoom.vFill defines zoom level of the image
+ // when it has 100% of viewport vertical space (height)
+
+ this.vFill = Math.min(1, vRatio);
+ this.initial = this._getInitial();
+ this.secondary = this._getSecondary();
+ this.max = Math.max(this.initial, this.secondary, this._getMax());
+ this.min = Math.min(this.fit, this.initial, this.secondary);
+
+ if (this.pswp) {
+ this.pswp.dispatch('zoomLevelsUpdate', {
+ zoomLevels: this,
+ slideData: this.itemData
+ });
+ }
+ }
+ /**
+ * Parses user-defined zoom option.
+ *
+ * @private
+ * @param {'initial' | 'secondary' | 'max'} optionPrefix Zoom level option prefix (initial, secondary, max)
+ * @returns { number | undefined }
+ */
+
+
+ _parseZoomLevelOption(optionPrefix) {
+ const optionName =
+ /** @type {'initialZoomLevel' | 'secondaryZoomLevel' | 'maxZoomLevel'} */
+ optionPrefix + 'ZoomLevel';
+ const optionValue = this.options[optionName];
+
+ if (!optionValue) {
+ return;
+ }
+
+ if (typeof optionValue === 'function') {
+ return optionValue(this);
+ }
+
+ if (optionValue === 'fill') {
+ return this.fill;
+ }
+
+ if (optionValue === 'fit') {
+ return this.fit;
+ }
+
+ return Number(optionValue);
+ }
+ /**
+ * Get zoom level to which image will be zoomed after double-tap gesture,
+ * or when user clicks on zoom icon,
+ * or mouse-click on image itself.
+ * If you return 1 image will be zoomed to its original size.
+ *
+ * @private
+ * @return {number}
+ */
+
+
+ _getSecondary() {
+ let currZoomLevel = this._parseZoomLevelOption('secondary');
+
+ if (currZoomLevel) {
+ return currZoomLevel;
+ } // 3x of "fit" state, but not larger than original
+
+
+ currZoomLevel = Math.min(1, this.fit * 3);
+
+ if (this.elementSize && currZoomLevel * this.elementSize.x > MAX_IMAGE_WIDTH) {
+ currZoomLevel = MAX_IMAGE_WIDTH / this.elementSize.x;
+ }
+
+ return currZoomLevel;
+ }
+ /**
+ * Get initial image zoom level.
+ *
+ * @private
+ * @return {number}
+ */
+
+
+ _getInitial() {
+ return this._parseZoomLevelOption('initial') || this.fit;
+ }
+ /**
+ * Maximum zoom level when user zooms
+ * via zoom/pinch gesture,
+ * via cmd/ctrl-wheel or via trackpad.
+ *
+ * @private
+ * @return {number}
+ */
+
+
+ _getMax() {
+ // max zoom level is x4 from "fit state",
+ // used for zoom gesture and ctrl/trackpad zoom
+ return this._parseZoomLevelOption('max') || Math.max(1, this.fit * 4);
+ }
+
+}
+
+/**
+ * Lazy-load an image
+ * This function is used both by Lightbox and PhotoSwipe core,
+ * thus it can be called before dialog is opened.
+ *
+ * @param {SlideData} itemData Data about the slide
+ * @param {PhotoSwipeBase} instance PhotoSwipe or PhotoSwipeLightbox instance
+ * @param {number} index
+ * @returns {Content} Image that is being decoded or false.
+ */
+
+function lazyLoadData(itemData, instance, index) {
+ const content = instance.createContentFromData(itemData, index);
+ /** @type {ZoomLevel | undefined} */
+
+ let zoomLevel;
+ const {
+ options
+ } = instance; // We need to know dimensions of the image to preload it,
+ // as it might use srcset, and we need to define sizes
+
+ if (options) {
+ zoomLevel = new ZoomLevel(options, itemData, -1);
+ let viewportSize;
+
+ if (instance.pswp) {
+ viewportSize = instance.pswp.viewportSize;
+ } else {
+ viewportSize = getViewportSize(options, instance);
+ }
+
+ const panAreaSize = getPanAreaSize(options, viewportSize, itemData, index);
+ zoomLevel.update(content.width, content.height, panAreaSize);
+ }
+
+ content.lazyLoad();
+
+ if (zoomLevel) {
+ content.setDisplayedSize(Math.ceil(content.width * zoomLevel.initial), Math.ceil(content.height * zoomLevel.initial));
+ }
+
+ return content;
+}
+/**
+ * Lazy-loads specific slide.
+ * This function is used both by Lightbox and PhotoSwipe core,
+ * thus it can be called before dialog is opened.
+ *
+ * By default, it loads image based on viewport size and initial zoom level.
+ *
+ * @param {number} index Slide index
+ * @param {PhotoSwipeBase} instance PhotoSwipe or PhotoSwipeLightbox eventable instance
+ * @returns {Content | undefined}
+ */
+
+function lazyLoadSlide(index, instance) {
+ const itemData = instance.getItemData(index);
+
+ if (instance.dispatch('lazyLoadSlide', {
+ index,
+ itemData
+ }).defaultPrevented) {
+ return;
+ }
+
+ return lazyLoadData(itemData, instance, index);
+}
+
+/** @typedef {import("../photoswipe.js").default} PhotoSwipe */
+
+/** @typedef {import("../slide/slide.js").SlideData} SlideData */
+
+/**
+ * PhotoSwipe base class that can retrieve data about every slide.
+ * Shared by PhotoSwipe Core and PhotoSwipe Lightbox
+ */
+
+class PhotoSwipeBase extends Eventable {
+ /**
+ * Get total number of slides
+ *
+ * @returns {number}
+ */
+ getNumItems() {
+ var _this$options;
+
+ let numItems = 0;
+ const dataSource = (_this$options = this.options) === null || _this$options === void 0 ? void 0 : _this$options.dataSource;
+
+ if (dataSource && 'length' in dataSource) {
+ // may be an array or just object with length property
+ numItems = dataSource.length;
+ } else if (dataSource && 'gallery' in dataSource) {
+ // query DOM elements
+ if (!dataSource.items) {
+ dataSource.items = this._getGalleryDOMElements(dataSource.gallery);
+ }
+
+ if (dataSource.items) {
+ numItems = dataSource.items.length;
+ }
+ } // legacy event, before filters were introduced
+
+
+ const event = this.dispatch('numItems', {
+ dataSource,
+ numItems
+ });
+ return this.applyFilters('numItems', event.numItems, dataSource);
+ }
+ /**
+ * @param {SlideData} slideData
+ * @param {number} index
+ * @returns {Content}
+ */
+
+
+ createContentFromData(slideData, index) {
+ return new Content(slideData, this, index);
+ }
+ /**
+ * Get item data by index.
+ *
+ * "item data" should contain normalized information that PhotoSwipe needs to generate a slide.
+ * For example, it may contain properties like
+ * `src`, `srcset`, `w`, `h`, which will be used to generate a slide with image.
+ *
+ * @param {number} index
+ * @returns {SlideData}
+ */
+
+
+ getItemData(index) {
+ var _this$options2;
+
+ const dataSource = (_this$options2 = this.options) === null || _this$options2 === void 0 ? void 0 : _this$options2.dataSource;
+ /** @type {SlideData | HTMLElement} */
+
+ let dataSourceItem = {};
+
+ if (Array.isArray(dataSource)) {
+ // Datasource is an array of elements
+ dataSourceItem = dataSource[index];
+ } else if (dataSource && 'gallery' in dataSource) {
+ // dataSource has gallery property,
+ // thus it was created by Lightbox, based on
+ // gallery and children options
+ // query DOM elements
+ if (!dataSource.items) {
+ dataSource.items = this._getGalleryDOMElements(dataSource.gallery);
+ }
+
+ dataSourceItem = dataSource.items[index];
+ }
+
+ let itemData = dataSourceItem;
+
+ if (itemData instanceof Element) {
+ itemData = this._domElementToItemData(itemData);
+ } // Dispatching the itemData event,
+ // it's a legacy verion before filters were introduced
+
+
+ const event = this.dispatch('itemData', {
+ itemData: itemData || {},
+ index
+ });
+ return this.applyFilters('itemData', event.itemData, index);
+ }
+ /**
+ * Get array of gallery DOM elements,
+ * based on childSelector and gallery element.
+ *
+ * @param {HTMLElement} galleryElement
+ * @returns {HTMLElement[]}
+ */
+
+
+ _getGalleryDOMElements(galleryElement) {
+ var _this$options3, _this$options4;
+
+ if ((_this$options3 = this.options) !== null && _this$options3 !== void 0 && _this$options3.children || (_this$options4 = this.options) !== null && _this$options4 !== void 0 && _this$options4.childSelector) {
+ return getElementsFromOption(this.options.children, this.options.childSelector, galleryElement) || [];
+ }
+
+ return [galleryElement];
+ }
+ /**
+ * Converts DOM element to item data object.
+ *
+ * @param {HTMLElement} element DOM element
+ * @returns {SlideData}
+ */
+
+
+ _domElementToItemData(element) {
+ /** @type {SlideData} */
+ const itemData = {
+ element
+ };
+ const linkEl =
+ /** @type {HTMLAnchorElement} */
+ element.tagName === 'A' ? element : element.querySelector('a');
+
+ if (linkEl) {
+ // src comes from data-pswp-src attribute,
+ // if it's empty link href is used
+ itemData.src = linkEl.dataset.pswpSrc || linkEl.href;
+
+ if (linkEl.dataset.pswpSrcset) {
+ itemData.srcset = linkEl.dataset.pswpSrcset;
+ }
+
+ itemData.width = linkEl.dataset.pswpWidth ? parseInt(linkEl.dataset.pswpWidth, 10) : 0;
+ itemData.height = linkEl.dataset.pswpHeight ? parseInt(linkEl.dataset.pswpHeight, 10) : 0; // support legacy w & h properties
+
+ itemData.w = itemData.width;
+ itemData.h = itemData.height;
+
+ if (linkEl.dataset.pswpType) {
+ itemData.type = linkEl.dataset.pswpType;
+ }
+
+ const thumbnailEl = element.querySelector('img');
+
+ if (thumbnailEl) {
+ var _thumbnailEl$getAttri;
+
+ // msrc is URL to placeholder image that's displayed before large image is loaded
+ // by default it's displayed only for the first slide
+ itemData.msrc = thumbnailEl.currentSrc || thumbnailEl.src;
+ itemData.alt = (_thumbnailEl$getAttri = thumbnailEl.getAttribute('alt')) !== null && _thumbnailEl$getAttri !== void 0 ? _thumbnailEl$getAttri : '';
+ }
+
+ if (linkEl.dataset.pswpCropped || linkEl.dataset.cropped) {
+ itemData.thumbCropped = true;
+ }
+ }
+
+ return this.applyFilters('domItemData', itemData, element, linkEl);
+ }
+ /**
+ * Lazy-load by slide data
+ *
+ * @param {SlideData} itemData Data about the slide
+ * @param {number} index
+ * @returns {Content} Image that is being decoded or false.
+ */
+
+
+ lazyLoadData(itemData, index) {
+ return lazyLoadData(itemData, this, index);
+ }
+
+}
+
+/**
+ * @template T
+ * @typedef {import('../types.js').Type} Type
+ */
+
+/** @typedef {import('../photoswipe.js').default} PhotoSwipe */
+
+/** @typedef {import('../photoswipe.js').PhotoSwipeOptions} PhotoSwipeOptions */
+
+/** @typedef {import('../photoswipe.js').DataSource} DataSource */
+
+/** @typedef {import('../photoswipe.js').Point} Point */
+
+/** @typedef {import('../slide/content.js').default} Content */
+
+/** @typedef {import('../core/eventable.js').PhotoSwipeEventsMap} PhotoSwipeEventsMap */
+
+/** @typedef {import('../core/eventable.js').PhotoSwipeFiltersMap} PhotoSwipeFiltersMap */
+
+/**
+ * @template {keyof PhotoSwipeEventsMap} T
+ * @typedef {import('../core/eventable.js').EventCallback} EventCallback
+ */
+
+/**
+ * PhotoSwipe Lightbox
+ *
+ * - If user has unsupported browser it falls back to default browser action (just opens URL)
+ * - Binds click event to links that should open PhotoSwipe
+ * - parses DOM strcture for PhotoSwipe (retrieves large image URLs and sizes)
+ * - Initializes PhotoSwipe
+ *
+ *
+ * Loader options use the same object as PhotoSwipe, and supports such options:
+ *
+ * gallery - Element | Element[] | NodeList | string selector for the gallery element
+ * children - Element | Element[] | NodeList | string selector for the gallery children
+ *
+ */
+
+class PhotoSwipeLightbox extends PhotoSwipeBase {
+ /**
+ * @param {PhotoSwipeOptions} [options]
+ */
+ constructor(options) {
+ super();
+ /** @type {PhotoSwipeOptions} */
+
+ this.options = options || {};
+ this._uid = 0;
+ this.shouldOpen = false;
+ /**
+ * @private
+ * @type {Content | undefined}
+ */
+
+ this._preloadedContent = undefined;
+ this.onThumbnailsClick = this.onThumbnailsClick.bind(this);
+ }
+ /**
+ * Initialize lightbox, should be called only once.
+ * It's not included in the main constructor, so you may bind events before it.
+ */
+
+
+ init() {
+ // Bind click events to each gallery
+ getElementsFromOption(this.options.gallery, this.options.gallerySelector).forEach(galleryElement => {
+ galleryElement.addEventListener('click', this.onThumbnailsClick, false);
+ });
+ }
+ /**
+ * @param {MouseEvent} e
+ */
+
+
+ onThumbnailsClick(e) {
+ // Exit and allow default browser action if:
+ if (specialKeyUsed(e) // ... if clicked with a special key (ctrl/cmd...)
+ || window.pswp) {
+ // ... if PhotoSwipe is already open
+ return;
+ } // If both clientX and clientY are 0 or not defined,
+ // the event is likely triggered by keyboard,
+ // so we do not pass the initialPoint
+ //
+ // Note that some screen readers emulate the mouse position,
+ // so it's not the ideal way to detect them.
+ //
+
+ /** @type {Point | null} */
+
+
+ let initialPoint = {
+ x: e.clientX,
+ y: e.clientY
+ };
+
+ if (!initialPoint.x && !initialPoint.y) {
+ initialPoint = null;
+ }
+
+ let clickedIndex = this.getClickedIndex(e);
+ clickedIndex = this.applyFilters('clickedIndex', clickedIndex, e, this);
+ /** @type {DataSource} */
+
+ const dataSource = {
+ gallery:
+ /** @type {HTMLElement} */
+ e.currentTarget
+ };
+
+ if (clickedIndex >= 0) {
+ e.preventDefault();
+ this.loadAndOpen(clickedIndex, dataSource, initialPoint);
+ }
+ }
+ /**
+ * Get index of gallery item that was clicked.
+ *
+ * @param {MouseEvent} e click event
+ * @returns {number}
+ */
+
+
+ getClickedIndex(e) {
+ // legacy option
+ if (this.options.getClickedIndexFn) {
+ return this.options.getClickedIndexFn.call(this, e);
+ }
+
+ const clickedTarget =
+ /** @type {HTMLElement} */
+ e.target;
+ const childElements = getElementsFromOption(this.options.children, this.options.childSelector,
+ /** @type {HTMLElement} */
+ e.currentTarget);
+ const clickedChildIndex = childElements.findIndex(child => child === clickedTarget || child.contains(clickedTarget));
+
+ if (clickedChildIndex !== -1) {
+ return clickedChildIndex;
+ } else if (this.options.children || this.options.childSelector) {
+ // click wasn't on a child element
+ return -1;
+ } // There is only one item (which is the gallery)
+
+
+ return 0;
+ }
+ /**
+ * Load and open PhotoSwipe
+ *
+ * @param {number} index
+ * @param {DataSource} [dataSource]
+ * @param {Point | null} [initialPoint]
+ * @returns {boolean}
+ */
+
+
+ loadAndOpen(index, dataSource, initialPoint) {
+ // Check if the gallery is already open
+ if (window.pswp || !this.options) {
+ return false;
+ } // Use the first gallery element if dataSource is not provided
+
+
+ if (!dataSource && this.options.gallery && this.options.children) {
+ const galleryElements = getElementsFromOption(this.options.gallery);
+
+ if (galleryElements[0]) {
+ dataSource = {
+ gallery: galleryElements[0]
+ };
+ }
+ } // set initial index
+
+
+ this.options.index = index; // define options for PhotoSwipe constructor
+
+ this.options.initialPointerPos = initialPoint;
+ this.shouldOpen = true;
+ this.preload(index, dataSource);
+ return true;
+ }
+ /**
+ * Load the main module and the slide content by index
+ *
+ * @param {number} index
+ * @param {DataSource} [dataSource]
+ */
+
+
+ preload(index, dataSource) {
+ const {
+ options
+ } = this;
+
+ if (dataSource) {
+ options.dataSource = dataSource;
+ } // Add the main module
+
+ /** @type {Promise>[]} */
+
+
+ const promiseArray = [];
+ const pswpModuleType = typeof options.pswpModule;
+
+ if (isPswpClass(options.pswpModule)) {
+ promiseArray.push(Promise.resolve(
+ /** @type {Type} */
+ options.pswpModule));
+ } else if (pswpModuleType === 'string') {
+ throw new Error('pswpModule as string is no longer supported');
+ } else if (pswpModuleType === 'function') {
+ promiseArray.push(
+ /** @type {() => Promise>} */
+ options.pswpModule());
+ } else {
+ throw new Error('pswpModule is not valid');
+ } // Add custom-defined promise, if any
+
+
+ if (typeof options.openPromise === 'function') {
+ // allow developers to perform some task before opening
+ promiseArray.push(options.openPromise());
+ }
+
+ if (options.preloadFirstSlide !== false && index >= 0) {
+ this._preloadedContent = lazyLoadSlide(index, this);
+ } // Wait till all promises resolve and open PhotoSwipe
+
+
+ const uid = ++this._uid;
+ Promise.all(promiseArray).then(iterableModules => {
+ if (this.shouldOpen) {
+ const mainModule = iterableModules[0];
+
+ this._openPhotoswipe(mainModule, uid);
+ }
+ });
+ }
+ /**
+ * @private
+ * @param {Type | { default: Type }} module
+ * @param {number} uid
+ */
+
+
+ _openPhotoswipe(module, uid) {
+ // Cancel opening if UID doesn't match the current one
+ // (if user clicked on another gallery item before current was loaded).
+ //
+ // Or if shouldOpen flag is set to false
+ // (developer may modify it via public API)
+ if (uid !== this._uid && this.shouldOpen) {
+ return;
+ }
+
+ this.shouldOpen = false; // PhotoSwipe is already open
+
+ if (window.pswp) {
+ return;
+ }
+ /**
+ * Pass data to PhotoSwipe and open init
+ *
+ * @type {PhotoSwipe}
+ */
+
+
+ const pswp = typeof module === 'object' ? new module.default(this.options) // eslint-disable-line
+ : new module(this.options); // eslint-disable-line
+
+ this.pswp = pswp;
+ window.pswp = pswp; // map listeners from Lightbox to PhotoSwipe Core
+
+ /** @type {(keyof PhotoSwipeEventsMap)[]} */
+
+ Object.keys(this._listeners).forEach(name => {
+ var _this$_listeners$name;
+
+ (_this$_listeners$name = this._listeners[name]) === null || _this$_listeners$name === void 0 || _this$_listeners$name.forEach(fn => {
+ pswp.on(name,
+ /** @type {EventCallback} */
+ fn);
+ });
+ }); // same with filters
+
+ /** @type {(keyof PhotoSwipeFiltersMap)[]} */
+
+ Object.keys(this._filters).forEach(name => {
+ var _this$_filters$name;
+
+ (_this$_filters$name = this._filters[name]) === null || _this$_filters$name === void 0 || _this$_filters$name.forEach(filter => {
+ pswp.addFilter(name, filter.fn, filter.priority);
+ });
+ });
+
+ if (this._preloadedContent) {
+ pswp.contentLoader.addToCache(this._preloadedContent);
+ this._preloadedContent = undefined;
+ }
+
+ pswp.on('destroy', () => {
+ // clean up public variables
+ this.pswp = undefined;
+ delete window.pswp;
+ });
+ pswp.init();
+ }
+ /**
+ * Unbinds all events, closes PhotoSwipe if it's open.
+ */
+
+
+ destroy() {
+ var _this$pswp;
+
+ (_this$pswp = this.pswp) === null || _this$pswp === void 0 || _this$pswp.destroy();
+ this.shouldOpen = false;
+ this._listeners = {};
+ getElementsFromOption(this.options.gallery, this.options.gallerySelector).forEach(galleryElement => {
+ galleryElement.removeEventListener('click', this.onThumbnailsClick, false);
+ });
+ }
+
+}
+
+export { PhotoSwipeLightbox as default };
+//# sourceMappingURL=photoswipe-lightbox.esm.js.map
diff --git a/app/public/photoswipe/photoswipe.css b/app/public/photoswipe/photoswipe.css
new file mode 100644
index 0000000..553038b
--- /dev/null
+++ b/app/public/photoswipe/photoswipe.css
@@ -0,0 +1,420 @@
+/*! PhotoSwipe main CSS by Dmytro Semenov | photoswipe.com */
+
+.pswp {
+ --pswp-bg: #000;
+ --pswp-placeholder-bg: #222;
+
+
+ --pswp-root-z-index: 100000;
+
+ --pswp-preloader-color: rgba(79, 79, 79, 0.4);
+ --pswp-preloader-color-secondary: rgba(255, 255, 255, 0.9);
+
+ /* defined via js:
+ --pswp-transition-duration: 333ms; */
+
+ --pswp-icon-color: #fff;
+ --pswp-icon-color-secondary: #4f4f4f;
+ --pswp-icon-stroke-color: #4f4f4f;
+ --pswp-icon-stroke-width: 2px;
+
+ --pswp-error-text-color: var(--pswp-icon-color);
+}
+
+
+/*
+ Styles for basic PhotoSwipe (pswp) functionality (sliding area, open/close transitions)
+*/
+
+.pswp {
+ position: fixed;
+ top: 0;
+ left: 0;
+ width: 100%;
+ height: 100%;
+ z-index: var(--pswp-root-z-index);
+ display: none;
+ touch-action: none;
+ outline: 0;
+ opacity: 0.003;
+ contain: layout style size;
+ -webkit-tap-highlight-color: rgba(0, 0, 0, 0);
+}
+
+/* Prevents focus outline on the root element,
+ (it may be focused initially) */
+.pswp:focus {
+ outline: 0;
+}
+
+.pswp * {
+ box-sizing: border-box;
+}
+
+.pswp img {
+ max-width: none;
+}
+
+.pswp--open {
+ display: block;
+}
+
+.pswp,
+.pswp__bg {
+ transform: translateZ(0);
+ will-change: opacity;
+}
+
+.pswp__bg {
+ opacity: 0.005;
+ background: var(--pswp-bg);
+}
+
+.pswp,
+.pswp__scroll-wrap {
+ overflow: hidden;
+}
+
+.pswp__scroll-wrap,
+.pswp__bg,
+.pswp__container,
+.pswp__item,
+.pswp__content,
+.pswp__img,
+.pswp__zoom-wrap {
+ position: absolute;
+ top: 0;
+ left: 0;
+ width: 100%;
+ height: 100%;
+}
+
+.pswp__img,
+.pswp__zoom-wrap {
+ width: auto;
+ height: auto;
+}
+
+.pswp--click-to-zoom.pswp--zoom-allowed .pswp__img {
+ cursor: -webkit-zoom-in;
+ cursor: -moz-zoom-in;
+ cursor: zoom-in;
+}
+
+.pswp--click-to-zoom.pswp--zoomed-in .pswp__img {
+ cursor: move;
+ cursor: -webkit-grab;
+ cursor: -moz-grab;
+ cursor: grab;
+}
+
+.pswp--click-to-zoom.pswp--zoomed-in .pswp__img:active {
+ cursor: -webkit-grabbing;
+ cursor: -moz-grabbing;
+ cursor: grabbing;
+}
+
+/* :active to override grabbing cursor */
+.pswp--no-mouse-drag.pswp--zoomed-in .pswp__img,
+.pswp--no-mouse-drag.pswp--zoomed-in .pswp__img:active,
+.pswp__img {
+ cursor: -webkit-zoom-out;
+ cursor: -moz-zoom-out;
+ cursor: zoom-out;
+}
+
+
+/* Prevent selection and tap highlights */
+.pswp__container,
+.pswp__img,
+.pswp__button,
+.pswp__counter {
+ -webkit-user-select: none;
+ -moz-user-select: none;
+ -ms-user-select: none;
+ user-select: none;
+}
+
+.pswp__item {
+ /* z-index for fade transition */
+ z-index: 1;
+ overflow: hidden;
+}
+
+.pswp__hidden {
+ display: none !important;
+}
+
+/* Allow to click through pswp__content element, but not its children */
+.pswp__content {
+ pointer-events: none;
+}
+.pswp__content > * {
+ pointer-events: auto;
+}
+
+
+/*
+
+ PhotoSwipe UI
+
+*/
+
+/*
+ Error message appears when image is not loaded
+ (JS option errorMsg controls markup)
+*/
+.pswp__error-msg-container {
+ display: grid;
+}
+.pswp__error-msg {
+ margin: auto;
+ font-size: 1em;
+ line-height: 1;
+ color: var(--pswp-error-text-color);
+}
+
+/*
+class pswp__hide-on-close is applied to elements that
+should hide (for example fade out) when PhotoSwipe is closed
+and show (for example fade in) when PhotoSwipe is opened
+ */
+.pswp .pswp__hide-on-close {
+ opacity: 0.005;
+ will-change: opacity;
+ transition: opacity var(--pswp-transition-duration) cubic-bezier(0.4, 0, 0.22, 1);
+ z-index: 10; /* always overlap slide content */
+ pointer-events: none; /* hidden elements should not be clickable */
+}
+
+/* class pswp--ui-visible is added when opening or closing transition starts */
+.pswp--ui-visible .pswp__hide-on-close {
+ opacity: 1;
+ pointer-events: auto;
+}
+
+/* styles, including css reset */
+.pswp__button {
+ position: relative;
+ display: block;
+ width: 50px;
+ height: 60px;
+ padding: 0;
+ margin: 0;
+ overflow: hidden;
+ cursor: pointer;
+ background: none;
+ border: 0;
+ box-shadow: none;
+ opacity: 0.85;
+ -webkit-appearance: none;
+ -webkit-touch-callout: none;
+}
+
+.pswp__button:hover,
+.pswp__button:active,
+.pswp__button:focus {
+ transition: none;
+ padding: 0;
+ background: none;
+ border: 0;
+ box-shadow: none;
+ opacity: 1;
+}
+
+.pswp__button:disabled {
+ opacity: 0.3;
+ cursor: auto;
+}
+
+.pswp__icn {
+ fill: var(--pswp-icon-color);
+ color: var(--pswp-icon-color-secondary);
+}
+
+.pswp__icn {
+ position: absolute;
+ top: 14px;
+ left: 9px;
+ width: 32px;
+ height: 32px;
+ overflow: hidden;
+ pointer-events: none;
+}
+
+.pswp__icn-shadow {
+ stroke: var(--pswp-icon-stroke-color);
+ stroke-width: var(--pswp-icon-stroke-width);
+ fill: none;
+}
+
+.pswp__icn:focus {
+ outline: 0;
+}
+
+/*
+ div element that matches size of large image,
+ large image loads on top of it,
+ used when msrc is not provided
+*/
+div.pswp__img--placeholder,
+.pswp__img--with-bg {
+ background: var(--pswp-placeholder-bg);
+}
+
+.pswp__top-bar {
+ position: absolute;
+ left: 0;
+ top: 0;
+ width: 100%;
+ height: 60px;
+ display: flex;
+ flex-direction: row;
+ justify-content: flex-end;
+ z-index: 10;
+
+ /* allow events to pass through top bar itself */
+ pointer-events: none !important;
+}
+.pswp__top-bar > * {
+ pointer-events: auto;
+ /* this makes transition significantly more smooth,
+ even though inner elements are not animated */
+ will-change: opacity;
+}
+
+
+/*
+
+ Close button
+
+*/
+.pswp__button--close {
+ margin-right: 6px;
+}
+
+
+/*
+
+ Arrow buttons
+
+*/
+.pswp__button--arrow {
+ position: absolute;
+ top: 0;
+ width: 75px;
+ height: 100px;
+ top: 50%;
+ margin-top: -50px;
+}
+
+.pswp__button--arrow:disabled {
+ display: none;
+ cursor: default;
+}
+
+.pswp__button--arrow .pswp__icn {
+ top: 50%;
+ margin-top: -30px;
+ width: 60px;
+ height: 60px;
+ background: none;
+ border-radius: 0;
+}
+
+.pswp--one-slide .pswp__button--arrow {
+ display: none;
+}
+
+/* hide arrows on touch screens */
+.pswp--touch .pswp__button--arrow {
+ visibility: hidden;
+}
+
+/* show arrows only after mouse was used */
+.pswp--has_mouse .pswp__button--arrow {
+ visibility: visible;
+}
+
+.pswp__button--arrow--prev {
+ right: auto;
+ left: 0px;
+}
+
+.pswp__button--arrow--next {
+ right: 0px;
+}
+.pswp__button--arrow--next .pswp__icn {
+ left: auto;
+ right: 14px;
+ /* flip horizontally */
+ transform: scale(-1, 1);
+}
+
+/*
+
+ Zoom button
+
+*/
+.pswp__button--zoom {
+ display: none;
+}
+
+.pswp--zoom-allowed .pswp__button--zoom {
+ display: block;
+}
+
+/* "+" => "-" */
+.pswp--zoomed-in .pswp__zoom-icn-bar-v {
+ display: none;
+}
+
+
+/*
+
+ Loading indicator
+
+*/
+.pswp__preloader {
+ position: relative;
+ overflow: hidden;
+ width: 50px;
+ height: 60px;
+ margin-right: auto;
+}
+
+.pswp__preloader .pswp__icn {
+ opacity: 0;
+ transition: opacity 0.2s linear;
+ animation: pswp-clockwise 600ms linear infinite;
+}
+
+.pswp__preloader--active .pswp__icn {
+ opacity: 0.85;
+}
+
+@keyframes pswp-clockwise {
+ 0% { transform: rotate(0deg); }
+ 100% { transform: rotate(360deg); }
+}
+
+
+/*
+
+ "1 of 10" counter
+
+*/
+.pswp__counter {
+ height: 30px;
+ margin-top: 15px;
+ margin-inline-start: 20px;
+ font-size: 14px;
+ line-height: 30px;
+ color: var(--pswp-icon-color);
+ text-shadow: 1px 1px 3px var(--pswp-icon-color-secondary);
+ opacity: 0.85;
+}
+
+.pswp--one-slide .pswp__counter {
+ display: none;
+}
diff --git a/app/public/photoswipe/photoswipe.esm.js b/app/public/photoswipe/photoswipe.esm.js
new file mode 100644
index 0000000..0b278f6
--- /dev/null
+++ b/app/public/photoswipe/photoswipe.esm.js
@@ -0,0 +1,7081 @@
+/*!
+ * PhotoSwipe 5.4.4 - https://photoswipe.com
+ * (c) 2024 Dmytro Semenov
+ */
+/** @typedef {import('../photoswipe.js').Point} Point */
+
+/**
+ * @template {keyof HTMLElementTagNameMap} T
+ * @param {string} className
+ * @param {T} tagName
+ * @param {Node} [appendToEl]
+ * @returns {HTMLElementTagNameMap[T]}
+ */
+function createElement(className, tagName, appendToEl) {
+ const el = document.createElement(tagName);
+
+ if (className) {
+ el.className = className;
+ }
+
+ if (appendToEl) {
+ appendToEl.appendChild(el);
+ }
+
+ return el;
+}
+/**
+ * @param {Point} p1
+ * @param {Point} p2
+ * @returns {Point}
+ */
+
+function equalizePoints(p1, p2) {
+ p1.x = p2.x;
+ p1.y = p2.y;
+
+ if (p2.id !== undefined) {
+ p1.id = p2.id;
+ }
+
+ return p1;
+}
+/**
+ * @param {Point} p
+ */
+
+function roundPoint(p) {
+ p.x = Math.round(p.x);
+ p.y = Math.round(p.y);
+}
+/**
+ * Returns distance between two points.
+ *
+ * @param {Point} p1
+ * @param {Point} p2
+ * @returns {number}
+ */
+
+function getDistanceBetween(p1, p2) {
+ const x = Math.abs(p1.x - p2.x);
+ const y = Math.abs(p1.y - p2.y);
+ return Math.sqrt(x * x + y * y);
+}
+/**
+ * Whether X and Y positions of points are equal
+ *
+ * @param {Point} p1
+ * @param {Point} p2
+ * @returns {boolean}
+ */
+
+function pointsEqual(p1, p2) {
+ return p1.x === p2.x && p1.y === p2.y;
+}
+/**
+ * The float result between the min and max values.
+ *
+ * @param {number} val
+ * @param {number} min
+ * @param {number} max
+ * @returns {number}
+ */
+
+function clamp(val, min, max) {
+ return Math.min(Math.max(val, min), max);
+}
+/**
+ * Get transform string
+ *
+ * @param {number} x
+ * @param {number} [y]
+ * @param {number} [scale]
+ * @returns {string}
+ */
+
+function toTransformString(x, y, scale) {
+ let propValue = `translate3d(${x}px,${y || 0}px,0)`;
+
+ if (scale !== undefined) {
+ propValue += ` scale3d(${scale},${scale},1)`;
+ }
+
+ return propValue;
+}
+/**
+ * Apply transform:translate(x, y) scale(scale) to element
+ *
+ * @param {HTMLElement} el
+ * @param {number} x
+ * @param {number} [y]
+ * @param {number} [scale]
+ */
+
+function setTransform(el, x, y, scale) {
+ el.style.transform = toTransformString(x, y, scale);
+}
+const defaultCSSEasing = 'cubic-bezier(.4,0,.22,1)';
+/**
+ * Apply CSS transition to element
+ *
+ * @param {HTMLElement} el
+ * @param {string} [prop] CSS property to animate
+ * @param {number} [duration] in ms
+ * @param {string} [ease] CSS easing function
+ */
+
+function setTransitionStyle(el, prop, duration, ease) {
+ // inOut: 'cubic-bezier(.4, 0, .22, 1)', // for "toggle state" transitions
+ // out: 'cubic-bezier(0, 0, .22, 1)', // for "show" transitions
+ // in: 'cubic-bezier(.4, 0, 1, 1)'// for "hide" transitions
+ el.style.transition = prop ? `${prop} ${duration}ms ${ease || defaultCSSEasing}` : 'none';
+}
+/**
+ * Apply width and height CSS properties to element
+ *
+ * @param {HTMLElement} el
+ * @param {string | number} w
+ * @param {string | number} h
+ */
+
+function setWidthHeight(el, w, h) {
+ el.style.width = typeof w === 'number' ? `${w}px` : w;
+ el.style.height = typeof h === 'number' ? `${h}px` : h;
+}
+/**
+ * @param {HTMLElement} el
+ */
+
+function removeTransitionStyle(el) {
+ setTransitionStyle(el);
+}
+/**
+ * @param {HTMLImageElement} img
+ * @returns {Promise}
+ */
+
+function decodeImage(img) {
+ if ('decode' in img) {
+ return img.decode().catch(() => {});
+ }
+
+ if (img.complete) {
+ return Promise.resolve(img);
+ }
+
+ return new Promise((resolve, reject) => {
+ img.onload = () => resolve(img);
+
+ img.onerror = reject;
+ });
+}
+/** @typedef {LOAD_STATE[keyof LOAD_STATE]} LoadState */
+
+/** @type {{ IDLE: 'idle'; LOADING: 'loading'; LOADED: 'loaded'; ERROR: 'error' }} */
+
+const LOAD_STATE = {
+ IDLE: 'idle',
+ LOADING: 'loading',
+ LOADED: 'loaded',
+ ERROR: 'error'
+};
+/**
+ * Check if click or keydown event was dispatched
+ * with a special key or via mouse wheel.
+ *
+ * @param {MouseEvent | KeyboardEvent} e
+ * @returns {boolean}
+ */
+
+function specialKeyUsed(e) {
+ return 'button' in e && e.button === 1 || e.ctrlKey || e.metaKey || e.altKey || e.shiftKey;
+}
+/**
+ * Parse `gallery` or `children` options.
+ *
+ * @param {import('../photoswipe.js').ElementProvider} [option]
+ * @param {string} [legacySelector]
+ * @param {HTMLElement | Document} [parent]
+ * @returns HTMLElement[]
+ */
+
+function getElementsFromOption(option, legacySelector, parent = document) {
+ /** @type {HTMLElement[]} */
+ let elements = [];
+
+ if (option instanceof Element) {
+ elements = [option];
+ } else if (option instanceof NodeList || Array.isArray(option)) {
+ elements = Array.from(option);
+ } else {
+ const selector = typeof option === 'string' ? option : legacySelector;
+
+ if (selector) {
+ elements = Array.from(parent.querySelectorAll(selector));
+ }
+ }
+
+ return elements;
+}
+/**
+ * Check if browser is Safari
+ *
+ * @returns {boolean}
+ */
+
+function isSafari() {
+ return !!(navigator.vendor && navigator.vendor.match(/apple/i));
+}
+
+// Detect passive event listener support
+let supportsPassive = false;
+/* eslint-disable */
+
+try {
+ /* @ts-ignore */
+ window.addEventListener('test', null, Object.defineProperty({}, 'passive', {
+ get: () => {
+ supportsPassive = true;
+ }
+ }));
+} catch (e) {}
+/* eslint-enable */
+
+/**
+ * @typedef {Object} PoolItem
+ * @prop {HTMLElement | Window | Document | undefined | null} target
+ * @prop {string} type
+ * @prop {EventListenerOrEventListenerObject} listener
+ * @prop {boolean} [passive]
+ */
+
+
+class DOMEvents {
+ constructor() {
+ /**
+ * @type {PoolItem[]}
+ * @private
+ */
+ this._pool = [];
+ }
+ /**
+ * Adds event listeners
+ *
+ * @param {PoolItem['target']} target
+ * @param {PoolItem['type']} type Can be multiple, separated by space.
+ * @param {PoolItem['listener']} listener
+ * @param {PoolItem['passive']} [passive]
+ */
+
+
+ add(target, type, listener, passive) {
+ this._toggleListener(target, type, listener, passive);
+ }
+ /**
+ * Removes event listeners
+ *
+ * @param {PoolItem['target']} target
+ * @param {PoolItem['type']} type
+ * @param {PoolItem['listener']} listener
+ * @param {PoolItem['passive']} [passive]
+ */
+
+
+ remove(target, type, listener, passive) {
+ this._toggleListener(target, type, listener, passive, true);
+ }
+ /**
+ * Removes all bound events
+ */
+
+
+ removeAll() {
+ this._pool.forEach(poolItem => {
+ this._toggleListener(poolItem.target, poolItem.type, poolItem.listener, poolItem.passive, true, true);
+ });
+
+ this._pool = [];
+ }
+ /**
+ * Adds or removes event
+ *
+ * @private
+ * @param {PoolItem['target']} target
+ * @param {PoolItem['type']} type
+ * @param {PoolItem['listener']} listener
+ * @param {PoolItem['passive']} [passive]
+ * @param {boolean} [unbind] Whether the event should be added or removed
+ * @param {boolean} [skipPool] Whether events pool should be skipped
+ */
+
+
+ _toggleListener(target, type, listener, passive, unbind, skipPool) {
+ if (!target) {
+ return;
+ }
+
+ const methodName = unbind ? 'removeEventListener' : 'addEventListener';
+ const types = type.split(' ');
+ types.forEach(eType => {
+ if (eType) {
+ // Events pool is used to easily unbind all events when PhotoSwipe is closed,
+ // so developer doesn't need to do this manually
+ if (!skipPool) {
+ if (unbind) {
+ // Remove from the events pool
+ this._pool = this._pool.filter(poolItem => {
+ return poolItem.type !== eType || poolItem.listener !== listener || poolItem.target !== target;
+ });
+ } else {
+ // Add to the events pool
+ this._pool.push({
+ target,
+ type: eType,
+ listener,
+ passive
+ });
+ }
+ } // most PhotoSwipe events call preventDefault,
+ // and we do not need browser to scroll the page
+
+
+ const eventOptions = supportsPassive ? {
+ passive: passive || false
+ } : false;
+ target[methodName](eType, listener, eventOptions);
+ }
+ });
+ }
+
+}
+
+/** @typedef {import('../photoswipe.js').PhotoSwipeOptions} PhotoSwipeOptions */
+
+/** @typedef {import('../core/base.js').default} PhotoSwipeBase */
+
+/** @typedef {import('../photoswipe.js').Point} Point */
+
+/** @typedef {import('../slide/slide.js').SlideData} SlideData */
+
+/**
+ * @param {PhotoSwipeOptions} options
+ * @param {PhotoSwipeBase} pswp
+ * @returns {Point}
+ */
+function getViewportSize(options, pswp) {
+ if (options.getViewportSizeFn) {
+ const newViewportSize = options.getViewportSizeFn(options, pswp);
+
+ if (newViewportSize) {
+ return newViewportSize;
+ }
+ }
+
+ return {
+ x: document.documentElement.clientWidth,
+ // TODO: height on mobile is very incosistent due to toolbar
+ // find a way to improve this
+ //
+ // document.documentElement.clientHeight - doesn't seem to work well
+ y: window.innerHeight
+ };
+}
+/**
+ * Parses padding option.
+ * Supported formats:
+ *
+ * // Object
+ * padding: {
+ * top: 0,
+ * bottom: 0,
+ * left: 0,
+ * right: 0
+ * }
+ *
+ * // A function that returns the object
+ * paddingFn: (viewportSize, itemData, index) => {
+ * return {
+ * top: 0,
+ * bottom: 0,
+ * left: 0,
+ * right: 0
+ * };
+ * }
+ *
+ * // Legacy variant
+ * paddingLeft: 0,
+ * paddingRight: 0,
+ * paddingTop: 0,
+ * paddingBottom: 0,
+ *
+ * @param {'left' | 'top' | 'bottom' | 'right'} prop
+ * @param {PhotoSwipeOptions} options PhotoSwipe options
+ * @param {Point} viewportSize PhotoSwipe viewport size, for example: { x:800, y:600 }
+ * @param {SlideData} itemData Data about the slide
+ * @param {number} index Slide index
+ * @returns {number}
+ */
+
+function parsePaddingOption(prop, options, viewportSize, itemData, index) {
+ let paddingValue = 0;
+
+ if (options.paddingFn) {
+ paddingValue = options.paddingFn(viewportSize, itemData, index)[prop];
+ } else if (options.padding) {
+ paddingValue = options.padding[prop];
+ } else {
+ const legacyPropName = 'padding' + prop[0].toUpperCase() + prop.slice(1); // @ts-expect-error
+
+ if (options[legacyPropName]) {
+ // @ts-expect-error
+ paddingValue = options[legacyPropName];
+ }
+ }
+
+ return Number(paddingValue) || 0;
+}
+/**
+ * @param {PhotoSwipeOptions} options
+ * @param {Point} viewportSize
+ * @param {SlideData} itemData
+ * @param {number} index
+ * @returns {Point}
+ */
+
+function getPanAreaSize(options, viewportSize, itemData, index) {
+ return {
+ x: viewportSize.x - parsePaddingOption('left', options, viewportSize, itemData, index) - parsePaddingOption('right', options, viewportSize, itemData, index),
+ y: viewportSize.y - parsePaddingOption('top', options, viewportSize, itemData, index) - parsePaddingOption('bottom', options, viewportSize, itemData, index)
+ };
+}
+
+/** @typedef {import('./slide.js').default} Slide */
+
+/** @typedef {Record} Point */
+
+/** @typedef {'x' | 'y'} Axis */
+
+/**
+ * Calculates minimum, maximum and initial (center) bounds of a slide
+ */
+
+class PanBounds {
+ /**
+ * @param {Slide} slide
+ */
+ constructor(slide) {
+ this.slide = slide;
+ this.currZoomLevel = 1;
+ this.center =
+ /** @type {Point} */
+ {
+ x: 0,
+ y: 0
+ };
+ this.max =
+ /** @type {Point} */
+ {
+ x: 0,
+ y: 0
+ };
+ this.min =
+ /** @type {Point} */
+ {
+ x: 0,
+ y: 0
+ };
+ }
+ /**
+ * _getItemBounds
+ *
+ * @param {number} currZoomLevel
+ */
+
+
+ update(currZoomLevel) {
+ this.currZoomLevel = currZoomLevel;
+
+ if (!this.slide.width) {
+ this.reset();
+ } else {
+ this._updateAxis('x');
+
+ this._updateAxis('y');
+
+ this.slide.pswp.dispatch('calcBounds', {
+ slide: this.slide
+ });
+ }
+ }
+ /**
+ * _calculateItemBoundsForAxis
+ *
+ * @param {Axis} axis
+ */
+
+
+ _updateAxis(axis) {
+ const {
+ pswp
+ } = this.slide;
+ const elSize = this.slide[axis === 'x' ? 'width' : 'height'] * this.currZoomLevel;
+ const paddingProp = axis === 'x' ? 'left' : 'top';
+ const padding = parsePaddingOption(paddingProp, pswp.options, pswp.viewportSize, this.slide.data, this.slide.index);
+ const panAreaSize = this.slide.panAreaSize[axis]; // Default position of element.
+ // By default, it is center of viewport:
+
+ this.center[axis] = Math.round((panAreaSize - elSize) / 2) + padding; // maximum pan position
+
+ this.max[axis] = elSize > panAreaSize ? Math.round(panAreaSize - elSize) + padding : this.center[axis]; // minimum pan position
+
+ this.min[axis] = elSize > panAreaSize ? padding : this.center[axis];
+ } // _getZeroBounds
+
+
+ reset() {
+ this.center.x = 0;
+ this.center.y = 0;
+ this.max.x = 0;
+ this.max.y = 0;
+ this.min.x = 0;
+ this.min.y = 0;
+ }
+ /**
+ * Correct pan position if it's beyond the bounds
+ *
+ * @param {Axis} axis x or y
+ * @param {number} panOffset
+ * @returns {number}
+ */
+
+
+ correctPan(axis, panOffset) {
+ // checkPanBounds
+ return clamp(panOffset, this.max[axis], this.min[axis]);
+ }
+
+}
+
+const MAX_IMAGE_WIDTH = 4000;
+/** @typedef {import('../photoswipe.js').default} PhotoSwipe */
+
+/** @typedef {import('../photoswipe.js').PhotoSwipeOptions} PhotoSwipeOptions */
+
+/** @typedef {import('../photoswipe.js').Point} Point */
+
+/** @typedef {import('../slide/slide.js').SlideData} SlideData */
+
+/** @typedef {'fit' | 'fill' | number | ((zoomLevelObject: ZoomLevel) => number)} ZoomLevelOption */
+
+/**
+ * Calculates zoom levels for specific slide.
+ * Depends on viewport size and image size.
+ */
+
+class ZoomLevel {
+ /**
+ * @param {PhotoSwipeOptions} options PhotoSwipe options
+ * @param {SlideData} itemData Slide data
+ * @param {number} index Slide index
+ * @param {PhotoSwipe} [pswp] PhotoSwipe instance, can be undefined if not initialized yet
+ */
+ constructor(options, itemData, index, pswp) {
+ this.pswp = pswp;
+ this.options = options;
+ this.itemData = itemData;
+ this.index = index;
+ /** @type { Point | null } */
+
+ this.panAreaSize = null;
+ /** @type { Point | null } */
+
+ this.elementSize = null;
+ this.fit = 1;
+ this.fill = 1;
+ this.vFill = 1;
+ this.initial = 1;
+ this.secondary = 1;
+ this.max = 1;
+ this.min = 1;
+ }
+ /**
+ * Calculate initial, secondary and maximum zoom level for the specified slide.
+ *
+ * It should be called when either image or viewport size changes.
+ *
+ * @param {number} maxWidth
+ * @param {number} maxHeight
+ * @param {Point} panAreaSize
+ */
+
+
+ update(maxWidth, maxHeight, panAreaSize) {
+ /** @type {Point} */
+ const elementSize = {
+ x: maxWidth,
+ y: maxHeight
+ };
+ this.elementSize = elementSize;
+ this.panAreaSize = panAreaSize;
+ const hRatio = panAreaSize.x / elementSize.x;
+ const vRatio = panAreaSize.y / elementSize.y;
+ this.fit = Math.min(1, hRatio < vRatio ? hRatio : vRatio);
+ this.fill = Math.min(1, hRatio > vRatio ? hRatio : vRatio); // zoom.vFill defines zoom level of the image
+ // when it has 100% of viewport vertical space (height)
+
+ this.vFill = Math.min(1, vRatio);
+ this.initial = this._getInitial();
+ this.secondary = this._getSecondary();
+ this.max = Math.max(this.initial, this.secondary, this._getMax());
+ this.min = Math.min(this.fit, this.initial, this.secondary);
+
+ if (this.pswp) {
+ this.pswp.dispatch('zoomLevelsUpdate', {
+ zoomLevels: this,
+ slideData: this.itemData
+ });
+ }
+ }
+ /**
+ * Parses user-defined zoom option.
+ *
+ * @private
+ * @param {'initial' | 'secondary' | 'max'} optionPrefix Zoom level option prefix (initial, secondary, max)
+ * @returns { number | undefined }
+ */
+
+
+ _parseZoomLevelOption(optionPrefix) {
+ const optionName =
+ /** @type {'initialZoomLevel' | 'secondaryZoomLevel' | 'maxZoomLevel'} */
+ optionPrefix + 'ZoomLevel';
+ const optionValue = this.options[optionName];
+
+ if (!optionValue) {
+ return;
+ }
+
+ if (typeof optionValue === 'function') {
+ return optionValue(this);
+ }
+
+ if (optionValue === 'fill') {
+ return this.fill;
+ }
+
+ if (optionValue === 'fit') {
+ return this.fit;
+ }
+
+ return Number(optionValue);
+ }
+ /**
+ * Get zoom level to which image will be zoomed after double-tap gesture,
+ * or when user clicks on zoom icon,
+ * or mouse-click on image itself.
+ * If you return 1 image will be zoomed to its original size.
+ *
+ * @private
+ * @return {number}
+ */
+
+
+ _getSecondary() {
+ let currZoomLevel = this._parseZoomLevelOption('secondary');
+
+ if (currZoomLevel) {
+ return currZoomLevel;
+ } // 3x of "fit" state, but not larger than original
+
+
+ currZoomLevel = Math.min(1, this.fit * 3);
+
+ if (this.elementSize && currZoomLevel * this.elementSize.x > MAX_IMAGE_WIDTH) {
+ currZoomLevel = MAX_IMAGE_WIDTH / this.elementSize.x;
+ }
+
+ return currZoomLevel;
+ }
+ /**
+ * Get initial image zoom level.
+ *
+ * @private
+ * @return {number}
+ */
+
+
+ _getInitial() {
+ return this._parseZoomLevelOption('initial') || this.fit;
+ }
+ /**
+ * Maximum zoom level when user zooms
+ * via zoom/pinch gesture,
+ * via cmd/ctrl-wheel or via trackpad.
+ *
+ * @private
+ * @return {number}
+ */
+
+
+ _getMax() {
+ // max zoom level is x4 from "fit state",
+ // used for zoom gesture and ctrl/trackpad zoom
+ return this._parseZoomLevelOption('max') || Math.max(1, this.fit * 4);
+ }
+
+}
+
+/** @typedef {import('../photoswipe.js').default} PhotoSwipe */
+/**
+ * Renders and allows to control a single slide
+ */
+
+class Slide {
+ /**
+ * @param {SlideData} data
+ * @param {number} index
+ * @param {PhotoSwipe} pswp
+ */
+ constructor(data, index, pswp) {
+ this.data = data;
+ this.index = index;
+ this.pswp = pswp;
+ this.isActive = index === pswp.currIndex;
+ this.currentResolution = 0;
+ /** @type {Point} */
+
+ this.panAreaSize = {
+ x: 0,
+ y: 0
+ };
+ /** @type {Point} */
+
+ this.pan = {
+ x: 0,
+ y: 0
+ };
+ this.isFirstSlide = this.isActive && !pswp.opener.isOpen;
+ this.zoomLevels = new ZoomLevel(pswp.options, data, index, pswp);
+ this.pswp.dispatch('gettingData', {
+ slide: this,
+ data: this.data,
+ index
+ });
+ this.content = this.pswp.contentLoader.getContentBySlide(this);
+ this.container = createElement('pswp__zoom-wrap', 'div');
+ /** @type {HTMLElement | null} */
+
+ this.holderElement = null;
+ this.currZoomLevel = 1;
+ /** @type {number} */
+
+ this.width = this.content.width;
+ /** @type {number} */
+
+ this.height = this.content.height;
+ this.heavyAppended = false;
+ this.bounds = new PanBounds(this);
+ this.prevDisplayedWidth = -1;
+ this.prevDisplayedHeight = -1;
+ this.pswp.dispatch('slideInit', {
+ slide: this
+ });
+ }
+ /**
+ * If this slide is active/current/visible
+ *
+ * @param {boolean} isActive
+ */
+
+
+ setIsActive(isActive) {
+ if (isActive && !this.isActive) {
+ // slide just became active
+ this.activate();
+ } else if (!isActive && this.isActive) {
+ // slide just became non-active
+ this.deactivate();
+ }
+ }
+ /**
+ * Appends slide content to DOM
+ *
+ * @param {HTMLElement} holderElement
+ */
+
+
+ append(holderElement) {
+ this.holderElement = holderElement;
+ this.container.style.transformOrigin = '0 0'; // Slide appended to DOM
+
+ if (!this.data) {
+ return;
+ }
+
+ this.calculateSize();
+ this.load();
+ this.updateContentSize();
+ this.appendHeavy();
+ this.holderElement.appendChild(this.container);
+ this.zoomAndPanToInitial();
+ this.pswp.dispatch('firstZoomPan', {
+ slide: this
+ });
+ this.applyCurrentZoomPan();
+ this.pswp.dispatch('afterSetContent', {
+ slide: this
+ });
+
+ if (this.isActive) {
+ this.activate();
+ }
+ }
+
+ load() {
+ this.content.load(false);
+ this.pswp.dispatch('slideLoad', {
+ slide: this
+ });
+ }
+ /**
+ * Append "heavy" DOM elements
+ *
+ * This may depend on a type of slide,
+ * but generally these are large images.
+ */
+
+
+ appendHeavy() {
+ const {
+ pswp
+ } = this;
+ const appendHeavyNearby = true; // todo
+ // Avoid appending heavy elements during animations
+
+ if (this.heavyAppended || !pswp.opener.isOpen || pswp.mainScroll.isShifted() || !this.isActive && !appendHeavyNearby) {
+ return;
+ }
+
+ if (this.pswp.dispatch('appendHeavy', {
+ slide: this
+ }).defaultPrevented) {
+ return;
+ }
+
+ this.heavyAppended = true;
+ this.content.append();
+ this.pswp.dispatch('appendHeavyContent', {
+ slide: this
+ });
+ }
+ /**
+ * Triggered when this slide is active (selected).
+ *
+ * If it's part of opening/closing transition -
+ * activate() will trigger after the transition is ended.
+ */
+
+
+ activate() {
+ this.isActive = true;
+ this.appendHeavy();
+ this.content.activate();
+ this.pswp.dispatch('slideActivate', {
+ slide: this
+ });
+ }
+ /**
+ * Triggered when this slide becomes inactive.
+ *
+ * Slide can become inactive only after it was active.
+ */
+
+
+ deactivate() {
+ this.isActive = false;
+ this.content.deactivate();
+
+ if (this.currZoomLevel !== this.zoomLevels.initial) {
+ // allow filtering
+ this.calculateSize();
+ } // reset zoom level
+
+
+ this.currentResolution = 0;
+ this.zoomAndPanToInitial();
+ this.applyCurrentZoomPan();
+ this.updateContentSize();
+ this.pswp.dispatch('slideDeactivate', {
+ slide: this
+ });
+ }
+ /**
+ * The slide should destroy itself, it will never be used again.
+ * (unbind all events and destroy internal components)
+ */
+
+
+ destroy() {
+ this.content.hasSlide = false;
+ this.content.remove();
+ this.container.remove();
+ this.pswp.dispatch('slideDestroy', {
+ slide: this
+ });
+ }
+
+ resize() {
+ if (this.currZoomLevel === this.zoomLevels.initial || !this.isActive) {
+ // Keep initial zoom level if it was before the resize,
+ // as well as when this slide is not active
+ // Reset position and scale to original state
+ this.calculateSize();
+ this.currentResolution = 0;
+ this.zoomAndPanToInitial();
+ this.applyCurrentZoomPan();
+ this.updateContentSize();
+ } else {
+ // readjust pan position if it's beyond the bounds
+ this.calculateSize();
+ this.bounds.update(this.currZoomLevel);
+ this.panTo(this.pan.x, this.pan.y);
+ }
+ }
+ /**
+ * Apply size to current slide content,
+ * based on the current resolution and scale.
+ *
+ * @param {boolean} [force] if size should be updated even if dimensions weren't changed
+ */
+
+
+ updateContentSize(force) {
+ // Use initial zoom level
+ // if resolution is not defined (user didn't zoom yet)
+ const scaleMultiplier = this.currentResolution || this.zoomLevels.initial;
+
+ if (!scaleMultiplier) {
+ return;
+ }
+
+ const width = Math.round(this.width * scaleMultiplier) || this.pswp.viewportSize.x;
+ const height = Math.round(this.height * scaleMultiplier) || this.pswp.viewportSize.y;
+
+ if (!this.sizeChanged(width, height) && !force) {
+ return;
+ }
+
+ this.content.setDisplayedSize(width, height);
+ }
+ /**
+ * @param {number} width
+ * @param {number} height
+ */
+
+
+ sizeChanged(width, height) {
+ if (width !== this.prevDisplayedWidth || height !== this.prevDisplayedHeight) {
+ this.prevDisplayedWidth = width;
+ this.prevDisplayedHeight = height;
+ return true;
+ }
+
+ return false;
+ }
+ /** @returns {HTMLImageElement | HTMLDivElement | null | undefined} */
+
+
+ getPlaceholderElement() {
+ var _this$content$placeho;
+
+ return (_this$content$placeho = this.content.placeholder) === null || _this$content$placeho === void 0 ? void 0 : _this$content$placeho.element;
+ }
+ /**
+ * Zoom current slide image to...
+ *
+ * @param {number} destZoomLevel Destination zoom level.
+ * @param {Point} [centerPoint]
+ * Transform origin center point, or false if viewport center should be used.
+ * @param {number | false} [transitionDuration] Transition duration, may be set to 0.
+ * @param {boolean} [ignoreBounds] Minimum and maximum zoom levels will be ignored.
+ */
+
+
+ zoomTo(destZoomLevel, centerPoint, transitionDuration, ignoreBounds) {
+ const {
+ pswp
+ } = this;
+
+ if (!this.isZoomable() || pswp.mainScroll.isShifted()) {
+ return;
+ }
+
+ pswp.dispatch('beforeZoomTo', {
+ destZoomLevel,
+ centerPoint,
+ transitionDuration
+ }); // stop all pan and zoom transitions
+
+ pswp.animations.stopAllPan(); // if (!centerPoint) {
+ // centerPoint = pswp.getViewportCenterPoint();
+ // }
+
+ const prevZoomLevel = this.currZoomLevel;
+
+ if (!ignoreBounds) {
+ destZoomLevel = clamp(destZoomLevel, this.zoomLevels.min, this.zoomLevels.max);
+ } // if (transitionDuration === undefined) {
+ // transitionDuration = this.pswp.options.zoomAnimationDuration;
+ // }
+
+
+ this.setZoomLevel(destZoomLevel);
+ this.pan.x = this.calculateZoomToPanOffset('x', centerPoint, prevZoomLevel);
+ this.pan.y = this.calculateZoomToPanOffset('y', centerPoint, prevZoomLevel);
+ roundPoint(this.pan);
+
+ const finishTransition = () => {
+ this._setResolution(destZoomLevel);
+
+ this.applyCurrentZoomPan();
+ };
+
+ if (!transitionDuration) {
+ finishTransition();
+ } else {
+ pswp.animations.startTransition({
+ isPan: true,
+ name: 'zoomTo',
+ target: this.container,
+ transform: this.getCurrentTransform(),
+ onComplete: finishTransition,
+ duration: transitionDuration,
+ easing: pswp.options.easing
+ });
+ }
+ }
+ /**
+ * @param {Point} [centerPoint]
+ */
+
+
+ toggleZoom(centerPoint) {
+ this.zoomTo(this.currZoomLevel === this.zoomLevels.initial ? this.zoomLevels.secondary : this.zoomLevels.initial, centerPoint, this.pswp.options.zoomAnimationDuration);
+ }
+ /**
+ * Updates zoom level property and recalculates new pan bounds,
+ * unlike zoomTo it does not apply transform (use applyCurrentZoomPan)
+ *
+ * @param {number} currZoomLevel
+ */
+
+
+ setZoomLevel(currZoomLevel) {
+ this.currZoomLevel = currZoomLevel;
+ this.bounds.update(this.currZoomLevel);
+ }
+ /**
+ * Get pan position after zoom at a given `point`.
+ *
+ * Always call setZoomLevel(newZoomLevel) beforehand to recalculate
+ * pan bounds according to the new zoom level.
+ *
+ * @param {'x' | 'y'} axis
+ * @param {Point} [point]
+ * point based on which zoom is performed, usually refers to the current mouse position,
+ * if false - viewport center will be used.
+ * @param {number} [prevZoomLevel] Zoom level before new zoom was applied.
+ * @returns {number}
+ */
+
+
+ calculateZoomToPanOffset(axis, point, prevZoomLevel) {
+ const totalPanDistance = this.bounds.max[axis] - this.bounds.min[axis];
+
+ if (totalPanDistance === 0) {
+ return this.bounds.center[axis];
+ }
+
+ if (!point) {
+ point = this.pswp.getViewportCenterPoint();
+ }
+
+ if (!prevZoomLevel) {
+ prevZoomLevel = this.zoomLevels.initial;
+ }
+
+ const zoomFactor = this.currZoomLevel / prevZoomLevel;
+ return this.bounds.correctPan(axis, (this.pan[axis] - point[axis]) * zoomFactor + point[axis]);
+ }
+ /**
+ * Apply pan and keep it within bounds.
+ *
+ * @param {number} panX
+ * @param {number} panY
+ */
+
+
+ panTo(panX, panY) {
+ this.pan.x = this.bounds.correctPan('x', panX);
+ this.pan.y = this.bounds.correctPan('y', panY);
+ this.applyCurrentZoomPan();
+ }
+ /**
+ * If the slide in the current state can be panned by the user
+ * @returns {boolean}
+ */
+
+
+ isPannable() {
+ return Boolean(this.width) && this.currZoomLevel > this.zoomLevels.fit;
+ }
+ /**
+ * If the slide can be zoomed
+ * @returns {boolean}
+ */
+
+
+ isZoomable() {
+ return Boolean(this.width) && this.content.isZoomable();
+ }
+ /**
+ * Apply transform and scale based on
+ * the current pan position (this.pan) and zoom level (this.currZoomLevel)
+ */
+
+
+ applyCurrentZoomPan() {
+ this._applyZoomTransform(this.pan.x, this.pan.y, this.currZoomLevel);
+
+ if (this === this.pswp.currSlide) {
+ this.pswp.dispatch('zoomPanUpdate', {
+ slide: this
+ });
+ }
+ }
+
+ zoomAndPanToInitial() {
+ this.currZoomLevel = this.zoomLevels.initial; // pan according to the zoom level
+
+ this.bounds.update(this.currZoomLevel);
+ equalizePoints(this.pan, this.bounds.center);
+ this.pswp.dispatch('initialZoomPan', {
+ slide: this
+ });
+ }
+ /**
+ * Set translate and scale based on current resolution
+ *
+ * @param {number} x
+ * @param {number} y
+ * @param {number} zoom
+ * @private
+ */
+
+
+ _applyZoomTransform(x, y, zoom) {
+ zoom /= this.currentResolution || this.zoomLevels.initial;
+ setTransform(this.container, x, y, zoom);
+ }
+
+ calculateSize() {
+ const {
+ pswp
+ } = this;
+ equalizePoints(this.panAreaSize, getPanAreaSize(pswp.options, pswp.viewportSize, this.data, this.index));
+ this.zoomLevels.update(this.width, this.height, this.panAreaSize);
+ pswp.dispatch('calcSlideSize', {
+ slide: this
+ });
+ }
+ /** @returns {string} */
+
+
+ getCurrentTransform() {
+ const scale = this.currZoomLevel / (this.currentResolution || this.zoomLevels.initial);
+ return toTransformString(this.pan.x, this.pan.y, scale);
+ }
+ /**
+ * Set resolution and re-render the image.
+ *
+ * For example, if the real image size is 2000x1500,
+ * and resolution is 0.5 - it will be rendered as 1000x750.
+ *
+ * Image with zoom level 2 and resolution 0.5 is
+ * the same as image with zoom level 1 and resolution 1.
+ *
+ * Used to optimize animations and make
+ * sure that browser renders image in the highest quality.
+ * Also used by responsive images to load the correct one.
+ *
+ * @param {number} newResolution
+ */
+
+
+ _setResolution(newResolution) {
+ if (newResolution === this.currentResolution) {
+ return;
+ }
+
+ this.currentResolution = newResolution;
+ this.updateContentSize();
+ this.pswp.dispatch('resolutionChanged');
+ }
+
+}
+
+/** @typedef {import('../photoswipe.js').Point} Point */
+
+/** @typedef {import('./gestures.js').default} Gestures */
+
+const PAN_END_FRICTION = 0.35;
+const VERTICAL_DRAG_FRICTION = 0.6; // 1 corresponds to the third of viewport height
+
+const MIN_RATIO_TO_CLOSE = 0.4; // Minimum speed required to navigate
+// to next or previous slide
+
+const MIN_NEXT_SLIDE_SPEED = 0.5;
+/**
+ * @param {number} initialVelocity
+ * @param {number} decelerationRate
+ * @returns {number}
+ */
+
+function project(initialVelocity, decelerationRate) {
+ return initialVelocity * decelerationRate / (1 - decelerationRate);
+}
+/**
+ * Handles single pointer dragging
+ */
+
+
+class DragHandler {
+ /**
+ * @param {Gestures} gestures
+ */
+ constructor(gestures) {
+ this.gestures = gestures;
+ this.pswp = gestures.pswp;
+ /** @type {Point} */
+
+ this.startPan = {
+ x: 0,
+ y: 0
+ };
+ }
+
+ start() {
+ if (this.pswp.currSlide) {
+ equalizePoints(this.startPan, this.pswp.currSlide.pan);
+ }
+
+ this.pswp.animations.stopAll();
+ }
+
+ change() {
+ const {
+ p1,
+ prevP1,
+ dragAxis
+ } = this.gestures;
+ const {
+ currSlide
+ } = this.pswp;
+
+ if (dragAxis === 'y' && this.pswp.options.closeOnVerticalDrag && currSlide && currSlide.currZoomLevel <= currSlide.zoomLevels.fit && !this.gestures.isMultitouch) {
+ // Handle vertical drag to close
+ const panY = currSlide.pan.y + (p1.y - prevP1.y);
+
+ if (!this.pswp.dispatch('verticalDrag', {
+ panY
+ }).defaultPrevented) {
+ this._setPanWithFriction('y', panY, VERTICAL_DRAG_FRICTION);
+
+ const bgOpacity = 1 - Math.abs(this._getVerticalDragRatio(currSlide.pan.y));
+ this.pswp.applyBgOpacity(bgOpacity);
+ currSlide.applyCurrentZoomPan();
+ }
+ } else {
+ const mainScrollChanged = this._panOrMoveMainScroll('x');
+
+ if (!mainScrollChanged) {
+ this._panOrMoveMainScroll('y');
+
+ if (currSlide) {
+ roundPoint(currSlide.pan);
+ currSlide.applyCurrentZoomPan();
+ }
+ }
+ }
+ }
+
+ end() {
+ const {
+ velocity
+ } = this.gestures;
+ const {
+ mainScroll,
+ currSlide
+ } = this.pswp;
+ let indexDiff = 0;
+ this.pswp.animations.stopAll(); // Handle main scroll if it's shifted
+
+ if (mainScroll.isShifted()) {
+ // Position of the main scroll relative to the viewport
+ const mainScrollShiftDiff = mainScroll.x - mainScroll.getCurrSlideX(); // Ratio between 0 and 1:
+ // 0 - slide is not visible at all,
+ // 0.5 - half of the slide is visible
+ // 1 - slide is fully visible
+
+ const currentSlideVisibilityRatio = mainScrollShiftDiff / this.pswp.viewportSize.x; // Go next slide.
+ //
+ // - if velocity and its direction is matched,
+ // and we see at least tiny part of the next slide
+ //
+ // - or if we see less than 50% of the current slide
+ // and velocity is close to 0
+ //
+
+ if (velocity.x < -MIN_NEXT_SLIDE_SPEED && currentSlideVisibilityRatio < 0 || velocity.x < 0.1 && currentSlideVisibilityRatio < -0.5) {
+ // Go to next slide
+ indexDiff = 1;
+ velocity.x = Math.min(velocity.x, 0);
+ } else if (velocity.x > MIN_NEXT_SLIDE_SPEED && currentSlideVisibilityRatio > 0 || velocity.x > -0.1 && currentSlideVisibilityRatio > 0.5) {
+ // Go to prev slide
+ indexDiff = -1;
+ velocity.x = Math.max(velocity.x, 0);
+ }
+
+ mainScroll.moveIndexBy(indexDiff, true, velocity.x);
+ } // Restore zoom level
+
+
+ if (currSlide && currSlide.currZoomLevel > currSlide.zoomLevels.max || this.gestures.isMultitouch) {
+ this.gestures.zoomLevels.correctZoomPan(true);
+ } else {
+ // we run two animations instead of one,
+ // as each axis has own pan boundaries and thus different spring function
+ // (correctZoomPan does not have this functionality,
+ // it animates all properties with single timing function)
+ this._finishPanGestureForAxis('x');
+
+ this._finishPanGestureForAxis('y');
+ }
+ }
+ /**
+ * @private
+ * @param {'x' | 'y'} axis
+ */
+
+
+ _finishPanGestureForAxis(axis) {
+ const {
+ velocity
+ } = this.gestures;
+ const {
+ currSlide
+ } = this.pswp;
+
+ if (!currSlide) {
+ return;
+ }
+
+ const {
+ pan,
+ bounds
+ } = currSlide;
+ const panPos = pan[axis];
+ const restoreBgOpacity = this.pswp.bgOpacity < 1 && axis === 'y'; // 0.995 means - scroll view loses 0.5% of its velocity per millisecond
+ // Increasing this number will reduce travel distance
+
+ const decelerationRate = 0.995; // 0.99
+ // Pan position if there is no bounds
+
+ const projectedPosition = panPos + project(velocity[axis], decelerationRate);
+
+ if (restoreBgOpacity) {
+ const vDragRatio = this._getVerticalDragRatio(panPos);
+
+ const projectedVDragRatio = this._getVerticalDragRatio(projectedPosition); // If we are above and moving upwards,
+ // or if we are below and moving downwards
+
+
+ if (vDragRatio < 0 && projectedVDragRatio < -MIN_RATIO_TO_CLOSE || vDragRatio > 0 && projectedVDragRatio > MIN_RATIO_TO_CLOSE) {
+ this.pswp.close();
+ return;
+ }
+ } // Pan position with corrected bounds
+
+
+ const correctedPanPosition = bounds.correctPan(axis, projectedPosition); // Exit if pan position should not be changed
+ // or if speed it too low
+
+ if (panPos === correctedPanPosition) {
+ return;
+ } // Overshoot if the final position is out of pan bounds
+
+
+ const dampingRatio = correctedPanPosition === projectedPosition ? 1 : 0.82;
+ const initialBgOpacity = this.pswp.bgOpacity;
+ const totalPanDist = correctedPanPosition - panPos;
+ this.pswp.animations.startSpring({
+ name: 'panGesture' + axis,
+ isPan: true,
+ start: panPos,
+ end: correctedPanPosition,
+ velocity: velocity[axis],
+ dampingRatio,
+ onUpdate: pos => {
+ // Animate opacity of background relative to Y pan position of an image
+ if (restoreBgOpacity && this.pswp.bgOpacity < 1) {
+ // 0 - start of animation, 1 - end of animation
+ const animationProgressRatio = 1 - (correctedPanPosition - pos) / totalPanDist; // We clamp opacity to keep it between 0 and 1.
+ // As progress ratio can be larger than 1 due to overshoot,
+ // and we do not want to bounce opacity.
+
+ this.pswp.applyBgOpacity(clamp(initialBgOpacity + (1 - initialBgOpacity) * animationProgressRatio, 0, 1));
+ }
+
+ pan[axis] = Math.floor(pos);
+ currSlide.applyCurrentZoomPan();
+ }
+ });
+ }
+ /**
+ * Update position of the main scroll,
+ * or/and update pan position of the current slide.
+ *
+ * Should return true if it changes (or can change) main scroll.
+ *
+ * @private
+ * @param {'x' | 'y'} axis
+ * @returns {boolean}
+ */
+
+
+ _panOrMoveMainScroll(axis) {
+ const {
+ p1,
+ dragAxis,
+ prevP1,
+ isMultitouch
+ } = this.gestures;
+ const {
+ currSlide,
+ mainScroll
+ } = this.pswp;
+ const delta = p1[axis] - prevP1[axis];
+ const newMainScrollX = mainScroll.x + delta;
+
+ if (!delta || !currSlide) {
+ return false;
+ } // Always move main scroll if image can not be panned
+
+
+ if (axis === 'x' && !currSlide.isPannable() && !isMultitouch) {
+ mainScroll.moveTo(newMainScrollX, true);
+ return true; // changed main scroll
+ }
+
+ const {
+ bounds
+ } = currSlide;
+ const newPan = currSlide.pan[axis] + delta;
+
+ if (this.pswp.options.allowPanToNext && dragAxis === 'x' && axis === 'x' && !isMultitouch) {
+ const currSlideMainScrollX = mainScroll.getCurrSlideX(); // Position of the main scroll relative to the viewport
+
+ const mainScrollShiftDiff = mainScroll.x - currSlideMainScrollX;
+ const isLeftToRight = delta > 0;
+ const isRightToLeft = !isLeftToRight;
+
+ if (newPan > bounds.min[axis] && isLeftToRight) {
+ // Panning from left to right, beyond the left edge
+ // Wether the image was at minimum pan position (or less)
+ // when this drag gesture started.
+ // Minimum pan position refers to the left edge of the image.
+ const wasAtMinPanPosition = bounds.min[axis] <= this.startPan[axis];
+
+ if (wasAtMinPanPosition) {
+ mainScroll.moveTo(newMainScrollX, true);
+ return true;
+ } else {
+ this._setPanWithFriction(axis, newPan); //currSlide.pan[axis] = newPan;
+
+ }
+ } else if (newPan < bounds.max[axis] && isRightToLeft) {
+ // Paning from right to left, beyond the right edge
+ // Maximum pan position refers to the right edge of the image.
+ const wasAtMaxPanPosition = this.startPan[axis] <= bounds.max[axis];
+
+ if (wasAtMaxPanPosition) {
+ mainScroll.moveTo(newMainScrollX, true);
+ return true;
+ } else {
+ this._setPanWithFriction(axis, newPan); //currSlide.pan[axis] = newPan;
+
+ }
+ } else {
+ // If main scroll is shifted
+ if (mainScrollShiftDiff !== 0) {
+ // If main scroll is shifted right
+ if (mainScrollShiftDiff > 0
+ /*&& isRightToLeft*/
+ ) {
+ mainScroll.moveTo(Math.max(newMainScrollX, currSlideMainScrollX), true);
+ return true;
+ } else if (mainScrollShiftDiff < 0
+ /*&& isLeftToRight*/
+ ) {
+ // Main scroll is shifted left (Position is less than 0 comparing to the viewport 0)
+ mainScroll.moveTo(Math.min(newMainScrollX, currSlideMainScrollX), true);
+ return true;
+ }
+ } else {
+ // We are within pan bounds, so just pan
+ this._setPanWithFriction(axis, newPan);
+ }
+ }
+ } else {
+ if (axis === 'y') {
+ // Do not pan vertically if main scroll is shifted o
+ if (!mainScroll.isShifted() && bounds.min.y !== bounds.max.y) {
+ this._setPanWithFriction(axis, newPan);
+ }
+ } else {
+ this._setPanWithFriction(axis, newPan);
+ }
+ }
+
+ return false;
+ } // If we move above - the ratio is negative
+ // If we move below the ratio is positive
+
+ /**
+ * Relation between pan Y position and third of viewport height.
+ *
+ * When we are at initial position (center bounds) - the ratio is 0,
+ * if position is shifted upwards - the ratio is negative,
+ * if position is shifted downwards - the ratio is positive.
+ *
+ * @private
+ * @param {number} panY The current pan Y position.
+ * @returns {number}
+ */
+
+
+ _getVerticalDragRatio(panY) {
+ var _this$pswp$currSlide$, _this$pswp$currSlide;
+
+ return (panY - ((_this$pswp$currSlide$ = (_this$pswp$currSlide = this.pswp.currSlide) === null || _this$pswp$currSlide === void 0 ? void 0 : _this$pswp$currSlide.bounds.center.y) !== null && _this$pswp$currSlide$ !== void 0 ? _this$pswp$currSlide$ : 0)) / (this.pswp.viewportSize.y / 3);
+ }
+ /**
+ * Set pan position of the current slide.
+ * Apply friction if the position is beyond the pan bounds,
+ * or if custom friction is defined.
+ *
+ * @private
+ * @param {'x' | 'y'} axis
+ * @param {number} potentialPan
+ * @param {number} [customFriction] (0.1 - 1)
+ */
+
+
+ _setPanWithFriction(axis, potentialPan, customFriction) {
+ const {
+ currSlide
+ } = this.pswp;
+
+ if (!currSlide) {
+ return;
+ }
+
+ const {
+ pan,
+ bounds
+ } = currSlide;
+ const correctedPan = bounds.correctPan(axis, potentialPan); // If we are out of pan bounds
+
+ if (correctedPan !== potentialPan || customFriction) {
+ const delta = Math.round(potentialPan - pan[axis]);
+ pan[axis] += delta * (customFriction || PAN_END_FRICTION);
+ } else {
+ pan[axis] = potentialPan;
+ }
+ }
+
+}
+
+/** @typedef {import('../photoswipe.js').Point} Point */
+
+/** @typedef {import('./gestures.js').default} Gestures */
+
+const UPPER_ZOOM_FRICTION = 0.05;
+const LOWER_ZOOM_FRICTION = 0.15;
+/**
+ * Get center point between two points
+ *
+ * @param {Point} p
+ * @param {Point} p1
+ * @param {Point} p2
+ * @returns {Point}
+ */
+
+function getZoomPointsCenter(p, p1, p2) {
+ p.x = (p1.x + p2.x) / 2;
+ p.y = (p1.y + p2.y) / 2;
+ return p;
+}
+
+class ZoomHandler {
+ /**
+ * @param {Gestures} gestures
+ */
+ constructor(gestures) {
+ this.gestures = gestures;
+ /**
+ * @private
+ * @type {Point}
+ */
+
+ this._startPan = {
+ x: 0,
+ y: 0
+ };
+ /**
+ * @private
+ * @type {Point}
+ */
+
+ this._startZoomPoint = {
+ x: 0,
+ y: 0
+ };
+ /**
+ * @private
+ * @type {Point}
+ */
+
+ this._zoomPoint = {
+ x: 0,
+ y: 0
+ };
+ /** @private */
+
+ this._wasOverFitZoomLevel = false;
+ /** @private */
+
+ this._startZoomLevel = 1;
+ }
+
+ start() {
+ const {
+ currSlide
+ } = this.gestures.pswp;
+
+ if (currSlide) {
+ this._startZoomLevel = currSlide.currZoomLevel;
+ equalizePoints(this._startPan, currSlide.pan);
+ }
+
+ this.gestures.pswp.animations.stopAllPan();
+ this._wasOverFitZoomLevel = false;
+ }
+
+ change() {
+ const {
+ p1,
+ startP1,
+ p2,
+ startP2,
+ pswp
+ } = this.gestures;
+ const {
+ currSlide
+ } = pswp;
+
+ if (!currSlide) {
+ return;
+ }
+
+ const minZoomLevel = currSlide.zoomLevels.min;
+ const maxZoomLevel = currSlide.zoomLevels.max;
+
+ if (!currSlide.isZoomable() || pswp.mainScroll.isShifted()) {
+ return;
+ }
+
+ getZoomPointsCenter(this._startZoomPoint, startP1, startP2);
+ getZoomPointsCenter(this._zoomPoint, p1, p2);
+
+ let currZoomLevel = 1 / getDistanceBetween(startP1, startP2) * getDistanceBetween(p1, p2) * this._startZoomLevel; // slightly over the zoom.fit
+
+
+ if (currZoomLevel > currSlide.zoomLevels.initial + currSlide.zoomLevels.initial / 15) {
+ this._wasOverFitZoomLevel = true;
+ }
+
+ if (currZoomLevel < minZoomLevel) {
+ if (pswp.options.pinchToClose && !this._wasOverFitZoomLevel && this._startZoomLevel <= currSlide.zoomLevels.initial) {
+ // fade out background if zooming out
+ const bgOpacity = 1 - (minZoomLevel - currZoomLevel) / (minZoomLevel / 1.2);
+
+ if (!pswp.dispatch('pinchClose', {
+ bgOpacity
+ }).defaultPrevented) {
+ pswp.applyBgOpacity(bgOpacity);
+ }
+ } else {
+ // Apply the friction if zoom level is below the min
+ currZoomLevel = minZoomLevel - (minZoomLevel - currZoomLevel) * LOWER_ZOOM_FRICTION;
+ }
+ } else if (currZoomLevel > maxZoomLevel) {
+ // Apply the friction if zoom level is above the max
+ currZoomLevel = maxZoomLevel + (currZoomLevel - maxZoomLevel) * UPPER_ZOOM_FRICTION;
+ }
+
+ currSlide.pan.x = this._calculatePanForZoomLevel('x', currZoomLevel);
+ currSlide.pan.y = this._calculatePanForZoomLevel('y', currZoomLevel);
+ currSlide.setZoomLevel(currZoomLevel);
+ currSlide.applyCurrentZoomPan();
+ }
+
+ end() {
+ const {
+ pswp
+ } = this.gestures;
+ const {
+ currSlide
+ } = pswp;
+
+ if ((!currSlide || currSlide.currZoomLevel < currSlide.zoomLevels.initial) && !this._wasOverFitZoomLevel && pswp.options.pinchToClose) {
+ pswp.close();
+ } else {
+ this.correctZoomPan();
+ }
+ }
+ /**
+ * @private
+ * @param {'x' | 'y'} axis
+ * @param {number} currZoomLevel
+ * @returns {number}
+ */
+
+
+ _calculatePanForZoomLevel(axis, currZoomLevel) {
+ const zoomFactor = currZoomLevel / this._startZoomLevel;
+ return this._zoomPoint[axis] - (this._startZoomPoint[axis] - this._startPan[axis]) * zoomFactor;
+ }
+ /**
+ * Correct currZoomLevel and pan if they are
+ * beyond minimum or maximum values.
+ * With animation.
+ *
+ * @param {boolean} [ignoreGesture]
+ * Wether gesture coordinates should be ignored when calculating destination pan position.
+ */
+
+
+ correctZoomPan(ignoreGesture) {
+ const {
+ pswp
+ } = this.gestures;
+ const {
+ currSlide
+ } = pswp;
+
+ if (!(currSlide !== null && currSlide !== void 0 && currSlide.isZoomable())) {
+ return;
+ }
+
+ if (this._zoomPoint.x === 0) {
+ ignoreGesture = true;
+ }
+
+ const prevZoomLevel = currSlide.currZoomLevel;
+ /** @type {number} */
+
+ let destinationZoomLevel;
+ let currZoomLevelNeedsChange = true;
+
+ if (prevZoomLevel < currSlide.zoomLevels.initial) {
+ destinationZoomLevel = currSlide.zoomLevels.initial; // zoom to min
+ } else if (prevZoomLevel > currSlide.zoomLevels.max) {
+ destinationZoomLevel = currSlide.zoomLevels.max; // zoom to max
+ } else {
+ currZoomLevelNeedsChange = false;
+ destinationZoomLevel = prevZoomLevel;
+ }
+
+ const initialBgOpacity = pswp.bgOpacity;
+ const restoreBgOpacity = pswp.bgOpacity < 1;
+ const initialPan = equalizePoints({
+ x: 0,
+ y: 0
+ }, currSlide.pan);
+ let destinationPan = equalizePoints({
+ x: 0,
+ y: 0
+ }, initialPan);
+
+ if (ignoreGesture) {
+ this._zoomPoint.x = 0;
+ this._zoomPoint.y = 0;
+ this._startZoomPoint.x = 0;
+ this._startZoomPoint.y = 0;
+ this._startZoomLevel = prevZoomLevel;
+ equalizePoints(this._startPan, initialPan);
+ }
+
+ if (currZoomLevelNeedsChange) {
+ destinationPan = {
+ x: this._calculatePanForZoomLevel('x', destinationZoomLevel),
+ y: this._calculatePanForZoomLevel('y', destinationZoomLevel)
+ };
+ } // set zoom level, so pan bounds are updated according to it
+
+
+ currSlide.setZoomLevel(destinationZoomLevel);
+ destinationPan = {
+ x: currSlide.bounds.correctPan('x', destinationPan.x),
+ y: currSlide.bounds.correctPan('y', destinationPan.y)
+ }; // return zoom level and its bounds to initial
+
+ currSlide.setZoomLevel(prevZoomLevel);
+ const panNeedsChange = !pointsEqual(destinationPan, initialPan);
+
+ if (!panNeedsChange && !currZoomLevelNeedsChange && !restoreBgOpacity) {
+ // update resolution after gesture
+ currSlide._setResolution(destinationZoomLevel);
+
+ currSlide.applyCurrentZoomPan(); // nothing to animate
+
+ return;
+ }
+
+ pswp.animations.stopAllPan();
+ pswp.animations.startSpring({
+ isPan: true,
+ start: 0,
+ end: 1000,
+ velocity: 0,
+ dampingRatio: 1,
+ naturalFrequency: 40,
+ onUpdate: now => {
+ now /= 1000; // 0 - start, 1 - end
+
+ if (panNeedsChange || currZoomLevelNeedsChange) {
+ if (panNeedsChange) {
+ currSlide.pan.x = initialPan.x + (destinationPan.x - initialPan.x) * now;
+ currSlide.pan.y = initialPan.y + (destinationPan.y - initialPan.y) * now;
+ }
+
+ if (currZoomLevelNeedsChange) {
+ const newZoomLevel = prevZoomLevel + (destinationZoomLevel - prevZoomLevel) * now;
+ currSlide.setZoomLevel(newZoomLevel);
+ }
+
+ currSlide.applyCurrentZoomPan();
+ } // Restore background opacity
+
+
+ if (restoreBgOpacity && pswp.bgOpacity < 1) {
+ // We clamp opacity to keep it between 0 and 1.
+ // As progress ratio can be larger than 1 due to overshoot,
+ // and we do not want to bounce opacity.
+ pswp.applyBgOpacity(clamp(initialBgOpacity + (1 - initialBgOpacity) * now, 0, 1));
+ }
+ },
+ onComplete: () => {
+ // update resolution after transition ends
+ currSlide._setResolution(destinationZoomLevel);
+
+ currSlide.applyCurrentZoomPan();
+ }
+ });
+ }
+
+}
+
+/**
+ * @template {string} T
+ * @template {string} P
+ * @typedef {import('../types.js').AddPostfix} AddPostfix
+ */
+
+/** @typedef {import('./gestures.js').default} Gestures */
+
+/** @typedef {import('../photoswipe.js').Point} Point */
+
+/** @typedef {'imageClick' | 'bgClick' | 'tap' | 'doubleTap'} Actions */
+
+/**
+ * Whether the tap was performed on the main slide
+ * (rather than controls or caption).
+ *
+ * @param {PointerEvent} event
+ * @returns {boolean}
+ */
+function didTapOnMainContent(event) {
+ return !!
+ /** @type {HTMLElement} */
+ event.target.closest('.pswp__container');
+}
+/**
+ * Tap, double-tap handler.
+ */
+
+
+class TapHandler {
+ /**
+ * @param {Gestures} gestures
+ */
+ constructor(gestures) {
+ this.gestures = gestures;
+ }
+ /**
+ * @param {Point} point
+ * @param {PointerEvent} originalEvent
+ */
+
+
+ click(point, originalEvent) {
+ const targetClassList =
+ /** @type {HTMLElement} */
+ originalEvent.target.classList;
+ const isImageClick = targetClassList.contains('pswp__img');
+ const isBackgroundClick = targetClassList.contains('pswp__item') || targetClassList.contains('pswp__zoom-wrap');
+
+ if (isImageClick) {
+ this._doClickOrTapAction('imageClick', point, originalEvent);
+ } else if (isBackgroundClick) {
+ this._doClickOrTapAction('bgClick', point, originalEvent);
+ }
+ }
+ /**
+ * @param {Point} point
+ * @param {PointerEvent} originalEvent
+ */
+
+
+ tap(point, originalEvent) {
+ if (didTapOnMainContent(originalEvent)) {
+ this._doClickOrTapAction('tap', point, originalEvent);
+ }
+ }
+ /**
+ * @param {Point} point
+ * @param {PointerEvent} originalEvent
+ */
+
+
+ doubleTap(point, originalEvent) {
+ if (didTapOnMainContent(originalEvent)) {
+ this._doClickOrTapAction('doubleTap', point, originalEvent);
+ }
+ }
+ /**
+ * @private
+ * @param {Actions} actionName
+ * @param {Point} point
+ * @param {PointerEvent} originalEvent
+ */
+
+
+ _doClickOrTapAction(actionName, point, originalEvent) {
+ var _this$gestures$pswp$e;
+
+ const {
+ pswp
+ } = this.gestures;
+ const {
+ currSlide
+ } = pswp;
+ const actionFullName =
+ /** @type {AddPostfix} */
+ actionName + 'Action';
+ const optionValue = pswp.options[actionFullName];
+
+ if (pswp.dispatch(actionFullName, {
+ point,
+ originalEvent
+ }).defaultPrevented) {
+ return;
+ }
+
+ if (typeof optionValue === 'function') {
+ optionValue.call(pswp, point, originalEvent);
+ return;
+ }
+
+ switch (optionValue) {
+ case 'close':
+ case 'next':
+ pswp[optionValue]();
+ break;
+
+ case 'zoom':
+ currSlide === null || currSlide === void 0 || currSlide.toggleZoom(point);
+ break;
+
+ case 'zoom-or-close':
+ // by default click zooms current image,
+ // if it can not be zoomed - gallery will be closed
+ if (currSlide !== null && currSlide !== void 0 && currSlide.isZoomable() && currSlide.zoomLevels.secondary !== currSlide.zoomLevels.initial) {
+ currSlide.toggleZoom(point);
+ } else if (pswp.options.clickToCloseNonZoomable) {
+ pswp.close();
+ }
+
+ break;
+
+ case 'toggle-controls':
+ (_this$gestures$pswp$e = this.gestures.pswp.element) === null || _this$gestures$pswp$e === void 0 || _this$gestures$pswp$e.classList.toggle('pswp--ui-visible'); // if (_controlsVisible) {
+ // _ui.hideControls();
+ // } else {
+ // _ui.showControls();
+ // }
+
+ break;
+ }
+ }
+
+}
+
+/** @typedef {import('../photoswipe.js').default} PhotoSwipe */
+
+/** @typedef {import('../photoswipe.js').Point} Point */
+// How far should user should drag
+// until we can determine that the gesture is swipe and its direction
+
+const AXIS_SWIPE_HYSTERISIS = 10; //const PAN_END_FRICTION = 0.35;
+
+const DOUBLE_TAP_DELAY = 300; // ms
+
+const MIN_TAP_DISTANCE = 25; // px
+
+/**
+ * Gestures class bind touch, pointer or mouse events
+ * and emits drag to drag-handler and zoom events zoom-handler.
+ *
+ * Drag and zoom events are emited in requestAnimationFrame,
+ * and only when one of pointers was actually changed.
+ */
+
+class Gestures {
+ /**
+ * @param {PhotoSwipe} pswp
+ */
+ constructor(pswp) {
+ this.pswp = pswp;
+ /** @type {'x' | 'y' | null} */
+
+ this.dragAxis = null; // point objects are defined once and reused
+ // PhotoSwipe keeps track only of two pointers, others are ignored
+
+ /** @type {Point} */
+
+ this.p1 = {
+ x: 0,
+ y: 0
+ }; // the first pressed pointer
+
+ /** @type {Point} */
+
+ this.p2 = {
+ x: 0,
+ y: 0
+ }; // the second pressed pointer
+
+ /** @type {Point} */
+
+ this.prevP1 = {
+ x: 0,
+ y: 0
+ };
+ /** @type {Point} */
+
+ this.prevP2 = {
+ x: 0,
+ y: 0
+ };
+ /** @type {Point} */
+
+ this.startP1 = {
+ x: 0,
+ y: 0
+ };
+ /** @type {Point} */
+
+ this.startP2 = {
+ x: 0,
+ y: 0
+ };
+ /** @type {Point} */
+
+ this.velocity = {
+ x: 0,
+ y: 0
+ };
+ /** @type {Point}
+ * @private
+ */
+
+ this._lastStartP1 = {
+ x: 0,
+ y: 0
+ };
+ /** @type {Point}
+ * @private
+ */
+
+ this._intervalP1 = {
+ x: 0,
+ y: 0
+ };
+ /** @private */
+
+ this._numActivePoints = 0;
+ /** @type {Point[]}
+ * @private
+ */
+
+ this._ongoingPointers = [];
+ /** @private */
+
+ this._touchEventEnabled = 'ontouchstart' in window;
+ /** @private */
+
+ this._pointerEventEnabled = !!window.PointerEvent;
+ this.supportsTouch = this._touchEventEnabled || this._pointerEventEnabled && navigator.maxTouchPoints > 1;
+ /** @private */
+
+ this._numActivePoints = 0;
+ /** @private */
+
+ this._intervalTime = 0;
+ /** @private */
+
+ this._velocityCalculated = false;
+ this.isMultitouch = false;
+ this.isDragging = false;
+ this.isZooming = false;
+ /** @type {number | null} */
+
+ this.raf = null;
+ /** @type {NodeJS.Timeout | null}
+ * @private
+ */
+
+ this._tapTimer = null;
+
+ if (!this.supportsTouch) {
+ // disable pan to next slide for non-touch devices
+ pswp.options.allowPanToNext = false;
+ }
+
+ this.drag = new DragHandler(this);
+ this.zoomLevels = new ZoomHandler(this);
+ this.tapHandler = new TapHandler(this);
+ pswp.on('bindEvents', () => {
+ pswp.events.add(pswp.scrollWrap, 'click',
+ /** @type EventListener */
+ this._onClick.bind(this));
+
+ if (this._pointerEventEnabled) {
+ this._bindEvents('pointer', 'down', 'up', 'cancel');
+ } else if (this._touchEventEnabled) {
+ this._bindEvents('touch', 'start', 'end', 'cancel'); // In previous versions we also bound mouse event here,
+ // in case device supports both touch and mouse events,
+ // but newer versions of browsers now support PointerEvent.
+ // on iOS10 if you bind touchmove/end after touchstart,
+ // and you don't preventDefault touchstart (which PhotoSwipe does),
+ // preventDefault will have no effect on touchmove and touchend.
+ // Unless you bind it previously.
+
+
+ if (pswp.scrollWrap) {
+ pswp.scrollWrap.ontouchmove = () => {};
+
+ pswp.scrollWrap.ontouchend = () => {};
+ }
+ } else {
+ this._bindEvents('mouse', 'down', 'up');
+ }
+ });
+ }
+ /**
+ * @private
+ * @param {'mouse' | 'touch' | 'pointer'} pref
+ * @param {'down' | 'start'} down
+ * @param {'up' | 'end'} up
+ * @param {'cancel'} [cancel]
+ */
+
+
+ _bindEvents(pref, down, up, cancel) {
+ const {
+ pswp
+ } = this;
+ const {
+ events
+ } = pswp;
+ const cancelEvent = cancel ? pref + cancel : '';
+ events.add(pswp.scrollWrap, pref + down,
+ /** @type EventListener */
+ this.onPointerDown.bind(this));
+ events.add(window, pref + 'move',
+ /** @type EventListener */
+ this.onPointerMove.bind(this));
+ events.add(window, pref + up,
+ /** @type EventListener */
+ this.onPointerUp.bind(this));
+
+ if (cancelEvent) {
+ events.add(pswp.scrollWrap, cancelEvent,
+ /** @type EventListener */
+ this.onPointerUp.bind(this));
+ }
+ }
+ /**
+ * @param {PointerEvent} e
+ */
+
+
+ onPointerDown(e) {
+ // We do not call preventDefault for touch events
+ // to allow browser to show native dialog on longpress
+ // (the one that allows to save image or open it in new tab).
+ //
+ // Desktop Safari allows to drag images when preventDefault isn't called on mousedown,
+ // even though preventDefault IS called on mousemove. That's why we preventDefault mousedown.
+ const isMousePointer = e.type === 'mousedown' || e.pointerType === 'mouse'; // Allow dragging only via left mouse button.
+ // http://www.quirksmode.org/js/events_properties.html
+ // https://developer.mozilla.org/en-US/docs/Web/API/event.button
+
+ if (isMousePointer && e.button > 0) {
+ return;
+ }
+
+ const {
+ pswp
+ } = this; // if PhotoSwipe is opening or closing
+
+ if (!pswp.opener.isOpen) {
+ e.preventDefault();
+ return;
+ }
+
+ if (pswp.dispatch('pointerDown', {
+ originalEvent: e
+ }).defaultPrevented) {
+ return;
+ }
+
+ if (isMousePointer) {
+ pswp.mouseDetected(); // preventDefault mouse event to prevent
+ // browser image drag feature
+
+ this._preventPointerEventBehaviour(e, 'down');
+ }
+
+ pswp.animations.stopAll();
+
+ this._updatePoints(e, 'down');
+
+ if (this._numActivePoints === 1) {
+ this.dragAxis = null; // we need to store initial point to determine the main axis,
+ // drag is activated only after the axis is determined
+
+ equalizePoints(this.startP1, this.p1);
+ }
+
+ if (this._numActivePoints > 1) {
+ // Tap or double tap should not trigger if more than one pointer
+ this._clearTapTimer();
+
+ this.isMultitouch = true;
+ } else {
+ this.isMultitouch = false;
+ }
+ }
+ /**
+ * @param {PointerEvent} e
+ */
+
+
+ onPointerMove(e) {
+ this._preventPointerEventBehaviour(e, 'move');
+
+ if (!this._numActivePoints) {
+ return;
+ }
+
+ this._updatePoints(e, 'move');
+
+ if (this.pswp.dispatch('pointerMove', {
+ originalEvent: e
+ }).defaultPrevented) {
+ return;
+ }
+
+ if (this._numActivePoints === 1 && !this.isDragging) {
+ if (!this.dragAxis) {
+ this._calculateDragDirection();
+ } // Drag axis was detected, emit drag.start
+
+
+ if (this.dragAxis && !this.isDragging) {
+ if (this.isZooming) {
+ this.isZooming = false;
+ this.zoomLevels.end();
+ }
+
+ this.isDragging = true;
+
+ this._clearTapTimer(); // Tap can not trigger after drag
+ // Adjust starting point
+
+
+ this._updateStartPoints();
+
+ this._intervalTime = Date.now(); //this._startTime = this._intervalTime;
+
+ this._velocityCalculated = false;
+ equalizePoints(this._intervalP1, this.p1);
+ this.velocity.x = 0;
+ this.velocity.y = 0;
+ this.drag.start();
+
+ this._rafStopLoop();
+
+ this._rafRenderLoop();
+ }
+ } else if (this._numActivePoints > 1 && !this.isZooming) {
+ this._finishDrag();
+
+ this.isZooming = true; // Adjust starting points
+
+ this._updateStartPoints();
+
+ this.zoomLevels.start();
+
+ this._rafStopLoop();
+
+ this._rafRenderLoop();
+ }
+ }
+ /**
+ * @private
+ */
+
+
+ _finishDrag() {
+ if (this.isDragging) {
+ this.isDragging = false; // Try to calculate velocity,
+ // if it wasn't calculated yet in drag.change
+
+ if (!this._velocityCalculated) {
+ this._updateVelocity(true);
+ }
+
+ this.drag.end();
+ this.dragAxis = null;
+ }
+ }
+ /**
+ * @param {PointerEvent} e
+ */
+
+
+ onPointerUp(e) {
+ if (!this._numActivePoints) {
+ return;
+ }
+
+ this._updatePoints(e, 'up');
+
+ if (this.pswp.dispatch('pointerUp', {
+ originalEvent: e
+ }).defaultPrevented) {
+ return;
+ }
+
+ if (this._numActivePoints === 0) {
+ this._rafStopLoop();
+
+ if (this.isDragging) {
+ this._finishDrag();
+ } else if (!this.isZooming && !this.isMultitouch) {
+ //this.zoomLevels.correctZoomPan();
+ this._finishTap(e);
+ }
+ }
+
+ if (this._numActivePoints < 2 && this.isZooming) {
+ this.isZooming = false;
+ this.zoomLevels.end();
+
+ if (this._numActivePoints === 1) {
+ // Since we have 1 point left, we need to reinitiate drag
+ this.dragAxis = null;
+
+ this._updateStartPoints();
+ }
+ }
+ }
+ /**
+ * @private
+ */
+
+
+ _rafRenderLoop() {
+ if (this.isDragging || this.isZooming) {
+ this._updateVelocity();
+
+ if (this.isDragging) {
+ // make sure that pointer moved since the last update
+ if (!pointsEqual(this.p1, this.prevP1)) {
+ this.drag.change();
+ }
+ } else
+ /* if (this.isZooming) */
+ {
+ if (!pointsEqual(this.p1, this.prevP1) || !pointsEqual(this.p2, this.prevP2)) {
+ this.zoomLevels.change();
+ }
+ }
+
+ this._updatePrevPoints();
+
+ this.raf = requestAnimationFrame(this._rafRenderLoop.bind(this));
+ }
+ }
+ /**
+ * Update velocity at 50ms interval
+ *
+ * @private
+ * @param {boolean} [force]
+ */
+
+
+ _updateVelocity(force) {
+ const time = Date.now();
+ const duration = time - this._intervalTime;
+
+ if (duration < 50 && !force) {
+ return;
+ }
+
+ this.velocity.x = this._getVelocity('x', duration);
+ this.velocity.y = this._getVelocity('y', duration);
+ this._intervalTime = time;
+ equalizePoints(this._intervalP1, this.p1);
+ this._velocityCalculated = true;
+ }
+ /**
+ * @private
+ * @param {PointerEvent} e
+ */
+
+
+ _finishTap(e) {
+ const {
+ mainScroll
+ } = this.pswp; // Do not trigger tap events if main scroll is shifted
+
+ if (mainScroll.isShifted()) {
+ // restore main scroll position
+ // (usually happens if stopped in the middle of animation)
+ mainScroll.moveIndexBy(0, true);
+ return;
+ } // Do not trigger tap for touchcancel or pointercancel
+
+
+ if (e.type.indexOf('cancel') > 0) {
+ return;
+ } // Trigger click instead of tap for mouse events
+
+
+ if (e.type === 'mouseup' || e.pointerType === 'mouse') {
+ this.tapHandler.click(this.startP1, e);
+ return;
+ } // Disable delay if there is no doubleTapAction
+
+
+ const tapDelay = this.pswp.options.doubleTapAction ? DOUBLE_TAP_DELAY : 0; // If tapTimer is defined - we tapped recently,
+ // check if the current tap is close to the previous one,
+ // if yes - trigger double tap
+
+ if (this._tapTimer) {
+ this._clearTapTimer(); // Check if two taps were more or less on the same place
+
+
+ if (getDistanceBetween(this._lastStartP1, this.startP1) < MIN_TAP_DISTANCE) {
+ this.tapHandler.doubleTap(this.startP1, e);
+ }
+ } else {
+ equalizePoints(this._lastStartP1, this.startP1);
+ this._tapTimer = setTimeout(() => {
+ this.tapHandler.tap(this.startP1, e);
+
+ this._clearTapTimer();
+ }, tapDelay);
+ }
+ }
+ /**
+ * @private
+ */
+
+
+ _clearTapTimer() {
+ if (this._tapTimer) {
+ clearTimeout(this._tapTimer);
+ this._tapTimer = null;
+ }
+ }
+ /**
+ * Get velocity for axis
+ *
+ * @private
+ * @param {'x' | 'y'} axis
+ * @param {number} duration
+ * @returns {number}
+ */
+
+
+ _getVelocity(axis, duration) {
+ // displacement is like distance, but can be negative.
+ const displacement = this.p1[axis] - this._intervalP1[axis];
+
+ if (Math.abs(displacement) > 1 && duration > 5) {
+ return displacement / duration;
+ }
+
+ return 0;
+ }
+ /**
+ * @private
+ */
+
+
+ _rafStopLoop() {
+ if (this.raf) {
+ cancelAnimationFrame(this.raf);
+ this.raf = null;
+ }
+ }
+ /**
+ * @private
+ * @param {PointerEvent} e
+ * @param {'up' | 'down' | 'move'} pointerType Normalized pointer type
+ */
+
+
+ _preventPointerEventBehaviour(e, pointerType) {
+ const preventPointerEvent = this.pswp.applyFilters('preventPointerEvent', true, e, pointerType);
+
+ if (preventPointerEvent) {
+ e.preventDefault();
+ }
+ }
+ /**
+ * Parses and normalizes points from the touch, mouse or pointer event.
+ * Updates p1 and p2.
+ *
+ * @private
+ * @param {PointerEvent | TouchEvent} e
+ * @param {'up' | 'down' | 'move'} pointerType Normalized pointer type
+ */
+
+
+ _updatePoints(e, pointerType) {
+ if (this._pointerEventEnabled) {
+ const pointerEvent =
+ /** @type {PointerEvent} */
+ e; // Try to find the current pointer in ongoing pointers by its ID
+
+ const pointerIndex = this._ongoingPointers.findIndex(ongoingPointer => {
+ return ongoingPointer.id === pointerEvent.pointerId;
+ });
+
+ if (pointerType === 'up' && pointerIndex > -1) {
+ // release the pointer - remove it from ongoing
+ this._ongoingPointers.splice(pointerIndex, 1);
+ } else if (pointerType === 'down' && pointerIndex === -1) {
+ // add new pointer
+ this._ongoingPointers.push(this._convertEventPosToPoint(pointerEvent, {
+ x: 0,
+ y: 0
+ }));
+ } else if (pointerIndex > -1) {
+ // update existing pointer
+ this._convertEventPosToPoint(pointerEvent, this._ongoingPointers[pointerIndex]);
+ }
+
+ this._numActivePoints = this._ongoingPointers.length; // update points that PhotoSwipe uses
+ // to calculate position and scale
+
+ if (this._numActivePoints > 0) {
+ equalizePoints(this.p1, this._ongoingPointers[0]);
+ }
+
+ if (this._numActivePoints > 1) {
+ equalizePoints(this.p2, this._ongoingPointers[1]);
+ }
+ } else {
+ const touchEvent =
+ /** @type {TouchEvent} */
+ e;
+ this._numActivePoints = 0;
+
+ if (touchEvent.type.indexOf('touch') > -1) {
+ // Touch Event
+ // https://developer.mozilla.org/en-US/docs/Web/API/TouchEvent
+ if (touchEvent.touches && touchEvent.touches.length > 0) {
+ this._convertEventPosToPoint(touchEvent.touches[0], this.p1);
+
+ this._numActivePoints++;
+
+ if (touchEvent.touches.length > 1) {
+ this._convertEventPosToPoint(touchEvent.touches[1], this.p2);
+
+ this._numActivePoints++;
+ }
+ }
+ } else {
+ // Mouse Event
+ this._convertEventPosToPoint(
+ /** @type {PointerEvent} */
+ e, this.p1);
+
+ if (pointerType === 'up') {
+ // clear all points on mouseup
+ this._numActivePoints = 0;
+ } else {
+ this._numActivePoints++;
+ }
+ }
+ }
+ }
+ /** update points that were used during previous rAF tick
+ * @private
+ */
+
+
+ _updatePrevPoints() {
+ equalizePoints(this.prevP1, this.p1);
+ equalizePoints(this.prevP2, this.p2);
+ }
+ /** update points at the start of gesture
+ * @private
+ */
+
+
+ _updateStartPoints() {
+ equalizePoints(this.startP1, this.p1);
+ equalizePoints(this.startP2, this.p2);
+
+ this._updatePrevPoints();
+ }
+ /** @private */
+
+
+ _calculateDragDirection() {
+ if (this.pswp.mainScroll.isShifted()) {
+ // if main scroll position is shifted – direction is always horizontal
+ this.dragAxis = 'x';
+ } else {
+ // calculate delta of the last touchmove tick
+ const diff = Math.abs(this.p1.x - this.startP1.x) - Math.abs(this.p1.y - this.startP1.y);
+
+ if (diff !== 0) {
+ // check if pointer was shifted horizontally or vertically
+ const axisToCheck = diff > 0 ? 'x' : 'y';
+
+ if (Math.abs(this.p1[axisToCheck] - this.startP1[axisToCheck]) >= AXIS_SWIPE_HYSTERISIS) {
+ this.dragAxis = axisToCheck;
+ }
+ }
+ }
+ }
+ /**
+ * Converts touch, pointer or mouse event
+ * to PhotoSwipe point.
+ *
+ * @private
+ * @param {Touch | PointerEvent} e
+ * @param {Point} p
+ * @returns {Point}
+ */
+
+
+ _convertEventPosToPoint(e, p) {
+ p.x = e.pageX - this.pswp.offset.x;
+ p.y = e.pageY - this.pswp.offset.y;
+
+ if ('pointerId' in e) {
+ p.id = e.pointerId;
+ } else if (e.identifier !== undefined) {
+ p.id = e.identifier;
+ }
+
+ return p;
+ }
+ /**
+ * @private
+ * @param {PointerEvent} e
+ */
+
+
+ _onClick(e) {
+ // Do not allow click event to pass through after drag
+ if (this.pswp.mainScroll.isShifted()) {
+ e.preventDefault();
+ e.stopPropagation();
+ }
+ }
+
+}
+
+/** @typedef {import('./photoswipe.js').default} PhotoSwipe */
+
+/** @typedef {import('./slide/slide.js').default} Slide */
+
+/** @typedef {{ el: HTMLDivElement; slide?: Slide }} ItemHolder */
+
+const MAIN_SCROLL_END_FRICTION = 0.35; // const MIN_SWIPE_TRANSITION_DURATION = 250;
+// const MAX_SWIPE_TRABSITION_DURATION = 500;
+// const DEFAULT_SWIPE_TRANSITION_DURATION = 333;
+
+/**
+ * Handles movement of the main scrolling container
+ * (for example, it repositions when user swipes left or right).
+ *
+ * Also stores its state.
+ */
+
+class MainScroll {
+ /**
+ * @param {PhotoSwipe} pswp
+ */
+ constructor(pswp) {
+ this.pswp = pswp;
+ this.x = 0;
+ this.slideWidth = 0;
+ /** @private */
+
+ this._currPositionIndex = 0;
+ /** @private */
+
+ this._prevPositionIndex = 0;
+ /** @private */
+
+ this._containerShiftIndex = -1;
+ /** @type {ItemHolder[]} */
+
+ this.itemHolders = [];
+ }
+ /**
+ * Position the scroller and slide containers
+ * according to viewport size.
+ *
+ * @param {boolean} [resizeSlides] Whether slides content should resized
+ */
+
+
+ resize(resizeSlides) {
+ const {
+ pswp
+ } = this;
+ const newSlideWidth = Math.round(pswp.viewportSize.x + pswp.viewportSize.x * pswp.options.spacing); // Mobile browsers might trigger a resize event during a gesture.
+ // (due to toolbar appearing or hiding).
+ // Avoid re-adjusting main scroll position if width wasn't changed
+
+ const slideWidthChanged = newSlideWidth !== this.slideWidth;
+
+ if (slideWidthChanged) {
+ this.slideWidth = newSlideWidth;
+ this.moveTo(this.getCurrSlideX());
+ }
+
+ this.itemHolders.forEach((itemHolder, index) => {
+ if (slideWidthChanged) {
+ setTransform(itemHolder.el, (index + this._containerShiftIndex) * this.slideWidth);
+ }
+
+ if (resizeSlides && itemHolder.slide) {
+ itemHolder.slide.resize();
+ }
+ });
+ }
+ /**
+ * Reset X position of the main scroller to zero
+ */
+
+
+ resetPosition() {
+ // Position on the main scroller (offset)
+ // it is independent from slide index
+ this._currPositionIndex = 0;
+ this._prevPositionIndex = 0; // This will force recalculation of size on next resize()
+
+ this.slideWidth = 0; // _containerShiftIndex*viewportSize will give you amount of transform of the current slide
+
+ this._containerShiftIndex = -1;
+ }
+ /**
+ * Create and append array of three items
+ * that hold data about slides in DOM
+ */
+
+
+ appendHolders() {
+ this.itemHolders = []; // append our three slide holders -
+ // previous, current, and next
+
+ for (let i = 0; i < 3; i++) {
+ const el = createElement('pswp__item', 'div', this.pswp.container);
+ el.setAttribute('role', 'group');
+ el.setAttribute('aria-roledescription', 'slide');
+ el.setAttribute('aria-hidden', 'true'); // hide nearby item holders until initial zoom animation finishes (to avoid extra Paints)
+
+ el.style.display = i === 1 ? 'block' : 'none';
+ this.itemHolders.push({
+ el //index: -1
+
+ });
+ }
+ }
+ /**
+ * Whether the main scroll can be horizontally swiped to the next or previous slide.
+ * @returns {boolean}
+ */
+
+
+ canBeSwiped() {
+ return this.pswp.getNumItems() > 1;
+ }
+ /**
+ * Move main scroll by X amount of slides.
+ * For example:
+ * `-1` will move to the previous slide,
+ * `0` will reset the scroll position of the current slide,
+ * `3` will move three slides forward
+ *
+ * If loop option is enabled - index will be automatically looped too,
+ * (for example `-1` will move to the last slide of the gallery).
+ *
+ * @param {number} diff
+ * @param {boolean} [animate]
+ * @param {number} [velocityX]
+ * @returns {boolean} whether index was changed or not
+ */
+
+
+ moveIndexBy(diff, animate, velocityX) {
+ const {
+ pswp
+ } = this;
+ let newIndex = pswp.potentialIndex + diff;
+ const numSlides = pswp.getNumItems();
+
+ if (pswp.canLoop()) {
+ newIndex = pswp.getLoopedIndex(newIndex);
+ const distance = (diff + numSlides) % numSlides;
+
+ if (distance <= numSlides / 2) {
+ // go forward
+ diff = distance;
+ } else {
+ // go backwards
+ diff = distance - numSlides;
+ }
+ } else {
+ if (newIndex < 0) {
+ newIndex = 0;
+ } else if (newIndex >= numSlides) {
+ newIndex = numSlides - 1;
+ }
+
+ diff = newIndex - pswp.potentialIndex;
+ }
+
+ pswp.potentialIndex = newIndex;
+ this._currPositionIndex -= diff;
+ pswp.animations.stopMainScroll();
+ const destinationX = this.getCurrSlideX();
+
+ if (!animate) {
+ this.moveTo(destinationX);
+ this.updateCurrItem();
+ } else {
+ pswp.animations.startSpring({
+ isMainScroll: true,
+ start: this.x,
+ end: destinationX,
+ velocity: velocityX || 0,
+ naturalFrequency: 30,
+ dampingRatio: 1,
+ //0.7,
+ onUpdate: x => {
+ this.moveTo(x);
+ },
+ onComplete: () => {
+ this.updateCurrItem();
+ pswp.appendHeavy();
+ }
+ });
+ let currDiff = pswp.potentialIndex - pswp.currIndex;
+
+ if (pswp.canLoop()) {
+ const currDistance = (currDiff + numSlides) % numSlides;
+
+ if (currDistance <= numSlides / 2) {
+ // go forward
+ currDiff = currDistance;
+ } else {
+ // go backwards
+ currDiff = currDistance - numSlides;
+ }
+ } // Force-append new slides during transition
+ // if difference between slides is more than 1
+
+
+ if (Math.abs(currDiff) > 1) {
+ this.updateCurrItem();
+ }
+ }
+
+ return Boolean(diff);
+ }
+ /**
+ * X position of the main scroll for the current slide
+ * (ignores position during dragging)
+ * @returns {number}
+ */
+
+
+ getCurrSlideX() {
+ return this.slideWidth * this._currPositionIndex;
+ }
+ /**
+ * Whether scroll position is shifted.
+ * For example, it will return true if the scroll is being dragged or animated.
+ * @returns {boolean}
+ */
+
+
+ isShifted() {
+ return this.x !== this.getCurrSlideX();
+ }
+ /**
+ * Update slides X positions and set their content
+ */
+
+
+ updateCurrItem() {
+ var _this$itemHolders$;
+
+ const {
+ pswp
+ } = this;
+ const positionDifference = this._prevPositionIndex - this._currPositionIndex;
+
+ if (!positionDifference) {
+ return;
+ }
+
+ this._prevPositionIndex = this._currPositionIndex;
+ pswp.currIndex = pswp.potentialIndex;
+ let diffAbs = Math.abs(positionDifference);
+ /** @type {ItemHolder | undefined} */
+
+ let tempHolder;
+
+ if (diffAbs >= 3) {
+ this._containerShiftIndex += positionDifference + (positionDifference > 0 ? -3 : 3);
+ diffAbs = 3; // If slides are changed by 3 screens or more - clean up previous slides
+
+ this.itemHolders.forEach(itemHolder => {
+ var _itemHolder$slide;
+
+ (_itemHolder$slide = itemHolder.slide) === null || _itemHolder$slide === void 0 || _itemHolder$slide.destroy();
+ itemHolder.slide = undefined;
+ });
+ }
+
+ for (let i = 0; i < diffAbs; i++) {
+ if (positionDifference > 0) {
+ tempHolder = this.itemHolders.shift();
+
+ if (tempHolder) {
+ this.itemHolders[2] = tempHolder; // move first to last
+
+ this._containerShiftIndex++;
+ setTransform(tempHolder.el, (this._containerShiftIndex + 2) * this.slideWidth);
+ pswp.setContent(tempHolder, pswp.currIndex - diffAbs + i + 2);
+ }
+ } else {
+ tempHolder = this.itemHolders.pop();
+
+ if (tempHolder) {
+ this.itemHolders.unshift(tempHolder); // move last to first
+
+ this._containerShiftIndex--;
+ setTransform(tempHolder.el, this._containerShiftIndex * this.slideWidth);
+ pswp.setContent(tempHolder, pswp.currIndex + diffAbs - i - 2);
+ }
+ }
+ } // Reset transfrom every 50ish navigations in one direction.
+ //
+ // Otherwise transform will keep growing indefinitely,
+ // which might cause issues as browsers have a maximum transform limit.
+ // I wasn't able to reach it, but just to be safe.
+ // This should not cause noticable lag.
+
+
+ if (Math.abs(this._containerShiftIndex) > 50 && !this.isShifted()) {
+ this.resetPosition();
+ this.resize();
+ } // Pan transition might be running (and consntantly updating pan position)
+
+
+ pswp.animations.stopAllPan();
+ this.itemHolders.forEach((itemHolder, i) => {
+ if (itemHolder.slide) {
+ // Slide in the 2nd holder is always active
+ itemHolder.slide.setIsActive(i === 1);
+ }
+ });
+ pswp.currSlide = (_this$itemHolders$ = this.itemHolders[1]) === null || _this$itemHolders$ === void 0 ? void 0 : _this$itemHolders$.slide;
+ pswp.contentLoader.updateLazy(positionDifference);
+
+ if (pswp.currSlide) {
+ pswp.currSlide.applyCurrentZoomPan();
+ }
+
+ pswp.dispatch('change');
+ }
+ /**
+ * Move the X position of the main scroll container
+ *
+ * @param {number} x
+ * @param {boolean} [dragging]
+ */
+
+
+ moveTo(x, dragging) {
+ if (!this.pswp.canLoop() && dragging) {
+ // Apply friction
+ let newSlideIndexOffset = (this.slideWidth * this._currPositionIndex - x) / this.slideWidth;
+ newSlideIndexOffset += this.pswp.currIndex;
+ const delta = Math.round(x - this.x);
+
+ if (newSlideIndexOffset < 0 && delta > 0 || newSlideIndexOffset >= this.pswp.getNumItems() - 1 && delta < 0) {
+ x = this.x + delta * MAIN_SCROLL_END_FRICTION;
+ }
+ }
+
+ this.x = x;
+
+ if (this.pswp.container) {
+ setTransform(this.pswp.container, x);
+ }
+
+ this.pswp.dispatch('moveMainScroll', {
+ x,
+ dragging: dragging !== null && dragging !== void 0 ? dragging : false
+ });
+ }
+
+}
+
+/** @typedef {import('./photoswipe.js').default} PhotoSwipe */
+
+/**
+ * @template T
+ * @typedef {import('./types.js').Methods} Methods
+ */
+
+const KeyboardKeyCodesMap = {
+ Escape: 27,
+ z: 90,
+ ArrowLeft: 37,
+ ArrowUp: 38,
+ ArrowRight: 39,
+ ArrowDown: 40,
+ Tab: 9
+};
+/**
+ * @template {keyof KeyboardKeyCodesMap} T
+ * @param {T} key
+ * @param {boolean} isKeySupported
+ * @returns {T | number | undefined}
+ */
+
+const getKeyboardEventKey = (key, isKeySupported) => {
+ return isKeySupported ? key : KeyboardKeyCodesMap[key];
+};
+/**
+ * - Manages keyboard shortcuts.
+ * - Helps trap focus within photoswipe.
+ */
+
+
+class Keyboard {
+ /**
+ * @param {PhotoSwipe} pswp
+ */
+ constructor(pswp) {
+ this.pswp = pswp;
+ /** @private */
+
+ this._wasFocused = false;
+ pswp.on('bindEvents', () => {
+ if (pswp.options.trapFocus) {
+ // Dialog was likely opened by keyboard if initial point is not defined
+ if (!pswp.options.initialPointerPos) {
+ // focus causes layout,
+ // which causes lag during the animation,
+ // that's why we delay it until the opener transition ends
+ this._focusRoot();
+ }
+
+ pswp.events.add(document, 'focusin',
+ /** @type EventListener */
+ this._onFocusIn.bind(this));
+ }
+
+ pswp.events.add(document, 'keydown',
+ /** @type EventListener */
+ this._onKeyDown.bind(this));
+ });
+ const lastActiveElement =
+ /** @type {HTMLElement} */
+ document.activeElement;
+ pswp.on('destroy', () => {
+ if (pswp.options.returnFocus && lastActiveElement && this._wasFocused) {
+ lastActiveElement.focus();
+ }
+ });
+ }
+ /** @private */
+
+
+ _focusRoot() {
+ if (!this._wasFocused && this.pswp.element) {
+ this.pswp.element.focus();
+ this._wasFocused = true;
+ }
+ }
+ /**
+ * @private
+ * @param {KeyboardEvent} e
+ */
+
+
+ _onKeyDown(e) {
+ const {
+ pswp
+ } = this;
+
+ if (pswp.dispatch('keydown', {
+ originalEvent: e
+ }).defaultPrevented) {
+ return;
+ }
+
+ if (specialKeyUsed(e)) {
+ // don't do anything if special key pressed
+ // to prevent from overriding default browser actions
+ // for example, in Chrome on Mac cmd+arrow-left returns to previous page
+ return;
+ }
+ /** @type {Methods | undefined} */
+
+
+ let keydownAction;
+ /** @type {'x' | 'y' | undefined} */
+
+ let axis;
+ let isForward = false;
+ const isKeySupported = ('key' in e);
+
+ switch (isKeySupported ? e.key : e.keyCode) {
+ case getKeyboardEventKey('Escape', isKeySupported):
+ if (pswp.options.escKey) {
+ keydownAction = 'close';
+ }
+
+ break;
+
+ case getKeyboardEventKey('z', isKeySupported):
+ keydownAction = 'toggleZoom';
+ break;
+
+ case getKeyboardEventKey('ArrowLeft', isKeySupported):
+ axis = 'x';
+ break;
+
+ case getKeyboardEventKey('ArrowUp', isKeySupported):
+ axis = 'y';
+ break;
+
+ case getKeyboardEventKey('ArrowRight', isKeySupported):
+ axis = 'x';
+ isForward = true;
+ break;
+
+ case getKeyboardEventKey('ArrowDown', isKeySupported):
+ isForward = true;
+ axis = 'y';
+ break;
+
+ case getKeyboardEventKey('Tab', isKeySupported):
+ this._focusRoot();
+
+ break;
+ } // if left/right/top/bottom key
+
+
+ if (axis) {
+ // prevent page scroll
+ e.preventDefault();
+ const {
+ currSlide
+ } = pswp;
+
+ if (pswp.options.arrowKeys && axis === 'x' && pswp.getNumItems() > 1) {
+ keydownAction = isForward ? 'next' : 'prev';
+ } else if (currSlide && currSlide.currZoomLevel > currSlide.zoomLevels.fit) {
+ // up/down arrow keys pan the image vertically
+ // left/right arrow keys pan horizontally.
+ // Unless there is only one image,
+ // or arrowKeys option is disabled
+ currSlide.pan[axis] += isForward ? -80 : 80;
+ currSlide.panTo(currSlide.pan.x, currSlide.pan.y);
+ }
+ }
+
+ if (keydownAction) {
+ e.preventDefault(); // @ts-ignore
+
+ pswp[keydownAction]();
+ }
+ }
+ /**
+ * Trap focus inside photoswipe
+ *
+ * @private
+ * @param {FocusEvent} e
+ */
+
+
+ _onFocusIn(e) {
+ const {
+ template
+ } = this.pswp;
+
+ if (template && document !== e.target && template !== e.target && !template.contains(
+ /** @type {Node} */
+ e.target)) {
+ // focus root element
+ template.focus();
+ }
+ }
+
+}
+
+const DEFAULT_EASING = 'cubic-bezier(.4,0,.22,1)';
+/** @typedef {import('./animations.js').SharedAnimationProps} SharedAnimationProps */
+
+/** @typedef {Object} DefaultCssAnimationProps
+ *
+ * @prop {HTMLElement} target
+ * @prop {number} [duration]
+ * @prop {string} [easing]
+ * @prop {string} [transform]
+ * @prop {string} [opacity]
+ * */
+
+/** @typedef {SharedAnimationProps & DefaultCssAnimationProps} CssAnimationProps */
+
+/**
+ * Runs CSS transition.
+ */
+
+class CSSAnimation {
+ /**
+ * onComplete can be unpredictable, be careful about current state
+ *
+ * @param {CssAnimationProps} props
+ */
+ constructor(props) {
+ var _props$prop;
+
+ this.props = props;
+ const {
+ target,
+ onComplete,
+ transform,
+ onFinish = () => {},
+ duration = 333,
+ easing = DEFAULT_EASING
+ } = props;
+ this.onFinish = onFinish; // support only transform and opacity
+
+ const prop = transform ? 'transform' : 'opacity';
+ const propValue = (_props$prop = props[prop]) !== null && _props$prop !== void 0 ? _props$prop : '';
+ /** @private */
+
+ this._target = target;
+ /** @private */
+
+ this._onComplete = onComplete;
+ /** @private */
+
+ this._finished = false;
+ /** @private */
+
+ this._onTransitionEnd = this._onTransitionEnd.bind(this); // Using timeout hack to make sure that animation
+ // starts even if the animated property was changed recently,
+ // otherwise transitionend might not fire or transition won't start.
+ // https://drafts.csswg.org/css-transitions/#starting
+ //
+ // ¯\_(ツ)_/¯
+
+ /** @private */
+
+ this._helperTimeout = setTimeout(() => {
+ setTransitionStyle(target, prop, duration, easing);
+ this._helperTimeout = setTimeout(() => {
+ target.addEventListener('transitionend', this._onTransitionEnd, false);
+ target.addEventListener('transitioncancel', this._onTransitionEnd, false); // Safari occasionally does not emit transitionend event
+ // if element property was modified during the transition,
+ // which may be caused by resize or third party component,
+ // using timeout as a safety fallback
+
+ this._helperTimeout = setTimeout(() => {
+ this._finalizeAnimation();
+ }, duration + 500);
+ target.style[prop] = propValue;
+ }, 30); // Do not reduce this number
+ }, 0);
+ }
+ /**
+ * @private
+ * @param {TransitionEvent} e
+ */
+
+
+ _onTransitionEnd(e) {
+ if (e.target === this._target) {
+ this._finalizeAnimation();
+ }
+ }
+ /**
+ * @private
+ */
+
+
+ _finalizeAnimation() {
+ if (!this._finished) {
+ this._finished = true;
+ this.onFinish();
+
+ if (this._onComplete) {
+ this._onComplete();
+ }
+ }
+ } // Destroy is called automatically onFinish
+
+
+ destroy() {
+ if (this._helperTimeout) {
+ clearTimeout(this._helperTimeout);
+ }
+
+ removeTransitionStyle(this._target);
+
+ this._target.removeEventListener('transitionend', this._onTransitionEnd, false);
+
+ this._target.removeEventListener('transitioncancel', this._onTransitionEnd, false);
+
+ if (!this._finished) {
+ this._finalizeAnimation();
+ }
+ }
+
+}
+
+const DEFAULT_NATURAL_FREQUENCY = 12;
+const DEFAULT_DAMPING_RATIO = 0.75;
+/**
+ * Spring easing helper
+ */
+
+class SpringEaser {
+ /**
+ * @param {number} initialVelocity Initial velocity, px per ms.
+ *
+ * @param {number} [dampingRatio]
+ * Determines how bouncy animation will be.
+ * From 0 to 1, 0 - always overshoot, 1 - do not overshoot.
+ * "overshoot" refers to part of animation that
+ * goes beyond the final value.
+ *
+ * @param {number} [naturalFrequency]
+ * Determines how fast animation will slow down.
+ * The higher value - the stiffer the transition will be,
+ * and the faster it will slow down.
+ * Recommended value from 10 to 50
+ */
+ constructor(initialVelocity, dampingRatio, naturalFrequency) {
+ this.velocity = initialVelocity * 1000; // convert to "pixels per second"
+ // https://en.wikipedia.org/wiki/Damping_ratio
+
+ this._dampingRatio = dampingRatio || DEFAULT_DAMPING_RATIO; // https://en.wikipedia.org/wiki/Natural_frequency
+
+ this._naturalFrequency = naturalFrequency || DEFAULT_NATURAL_FREQUENCY;
+ this._dampedFrequency = this._naturalFrequency;
+
+ if (this._dampingRatio < 1) {
+ this._dampedFrequency *= Math.sqrt(1 - this._dampingRatio * this._dampingRatio);
+ }
+ }
+ /**
+ * @param {number} deltaPosition Difference between current and end position of the animation
+ * @param {number} deltaTime Frame duration in milliseconds
+ *
+ * @returns {number} Displacement, relative to the end position.
+ */
+
+
+ easeFrame(deltaPosition, deltaTime) {
+ // Inspired by Apple Webkit and Android spring function implementation
+ // https://en.wikipedia.org/wiki/Oscillation
+ // https://en.wikipedia.org/wiki/Damping_ratio
+ // we ignore mass (assume that it's 1kg)
+ let displacement = 0;
+ let coeff;
+ deltaTime /= 1000;
+ const naturalDumpingPow = Math.E ** (-this._dampingRatio * this._naturalFrequency * deltaTime);
+
+ if (this._dampingRatio === 1) {
+ coeff = this.velocity + this._naturalFrequency * deltaPosition;
+ displacement = (deltaPosition + coeff * deltaTime) * naturalDumpingPow;
+ this.velocity = displacement * -this._naturalFrequency + coeff * naturalDumpingPow;
+ } else if (this._dampingRatio < 1) {
+ coeff = 1 / this._dampedFrequency * (this._dampingRatio * this._naturalFrequency * deltaPosition + this.velocity);
+ const dumpedFCos = Math.cos(this._dampedFrequency * deltaTime);
+ const dumpedFSin = Math.sin(this._dampedFrequency * deltaTime);
+ displacement = naturalDumpingPow * (deltaPosition * dumpedFCos + coeff * dumpedFSin);
+ this.velocity = displacement * -this._naturalFrequency * this._dampingRatio + naturalDumpingPow * (-this._dampedFrequency * deltaPosition * dumpedFSin + this._dampedFrequency * coeff * dumpedFCos);
+ } // Overdamped (>1) damping ratio is not supported
+
+
+ return displacement;
+ }
+
+}
+
+/** @typedef {import('./animations.js').SharedAnimationProps} SharedAnimationProps */
+
+/**
+ * @typedef {Object} DefaultSpringAnimationProps
+ *
+ * @prop {number} start
+ * @prop {number} end
+ * @prop {number} velocity
+ * @prop {number} [dampingRatio]
+ * @prop {number} [naturalFrequency]
+ * @prop {(end: number) => void} onUpdate
+ */
+
+/** @typedef {SharedAnimationProps & DefaultSpringAnimationProps} SpringAnimationProps */
+
+class SpringAnimation {
+ /**
+ * @param {SpringAnimationProps} props
+ */
+ constructor(props) {
+ this.props = props;
+ this._raf = 0;
+ const {
+ start,
+ end,
+ velocity,
+ onUpdate,
+ onComplete,
+ onFinish = () => {},
+ dampingRatio,
+ naturalFrequency
+ } = props;
+ this.onFinish = onFinish;
+ const easer = new SpringEaser(velocity, dampingRatio, naturalFrequency);
+ let prevTime = Date.now();
+ let deltaPosition = start - end;
+
+ const animationLoop = () => {
+ if (this._raf) {
+ deltaPosition = easer.easeFrame(deltaPosition, Date.now() - prevTime); // Stop the animation if velocity is low and position is close to end
+
+ if (Math.abs(deltaPosition) < 1 && Math.abs(easer.velocity) < 50) {
+ // Finalize the animation
+ onUpdate(end);
+
+ if (onComplete) {
+ onComplete();
+ }
+
+ this.onFinish();
+ } else {
+ prevTime = Date.now();
+ onUpdate(deltaPosition + end);
+ this._raf = requestAnimationFrame(animationLoop);
+ }
+ }
+ };
+
+ this._raf = requestAnimationFrame(animationLoop);
+ } // Destroy is called automatically onFinish
+
+
+ destroy() {
+ if (this._raf >= 0) {
+ cancelAnimationFrame(this._raf);
+ }
+
+ this._raf = 0;
+ }
+
+}
+
+/** @typedef {import('./css-animation.js').CssAnimationProps} CssAnimationProps */
+
+/** @typedef {import('./spring-animation.js').SpringAnimationProps} SpringAnimationProps */
+
+/** @typedef {Object} SharedAnimationProps
+ * @prop {string} [name]
+ * @prop {boolean} [isPan]
+ * @prop {boolean} [isMainScroll]
+ * @prop {VoidFunction} [onComplete]
+ * @prop {VoidFunction} [onFinish]
+ */
+
+/** @typedef {SpringAnimation | CSSAnimation} Animation */
+
+/** @typedef {SpringAnimationProps | CssAnimationProps} AnimationProps */
+
+/**
+ * Manages animations
+ */
+
+class Animations {
+ constructor() {
+ /** @type {Animation[]} */
+ this.activeAnimations = [];
+ }
+ /**
+ * @param {SpringAnimationProps} props
+ */
+
+
+ startSpring(props) {
+ this._start(props, true);
+ }
+ /**
+ * @param {CssAnimationProps} props
+ */
+
+
+ startTransition(props) {
+ this._start(props);
+ }
+ /**
+ * @private
+ * @param {AnimationProps} props
+ * @param {boolean} [isSpring]
+ * @returns {Animation}
+ */
+
+
+ _start(props, isSpring) {
+ const animation = isSpring ? new SpringAnimation(
+ /** @type SpringAnimationProps */
+ props) : new CSSAnimation(
+ /** @type CssAnimationProps */
+ props);
+ this.activeAnimations.push(animation);
+
+ animation.onFinish = () => this.stop(animation);
+
+ return animation;
+ }
+ /**
+ * @param {Animation} animation
+ */
+
+
+ stop(animation) {
+ animation.destroy();
+ const index = this.activeAnimations.indexOf(animation);
+
+ if (index > -1) {
+ this.activeAnimations.splice(index, 1);
+ }
+ }
+
+ stopAll() {
+ // _stopAllAnimations
+ this.activeAnimations.forEach(animation => {
+ animation.destroy();
+ });
+ this.activeAnimations = [];
+ }
+ /**
+ * Stop all pan or zoom transitions
+ */
+
+
+ stopAllPan() {
+ this.activeAnimations = this.activeAnimations.filter(animation => {
+ if (animation.props.isPan) {
+ animation.destroy();
+ return false;
+ }
+
+ return true;
+ });
+ }
+
+ stopMainScroll() {
+ this.activeAnimations = this.activeAnimations.filter(animation => {
+ if (animation.props.isMainScroll) {
+ animation.destroy();
+ return false;
+ }
+
+ return true;
+ });
+ }
+ /**
+ * Returns true if main scroll transition is running
+ */
+ // isMainScrollRunning() {
+ // return this.activeAnimations.some((animation) => {
+ // return animation.props.isMainScroll;
+ // });
+ // }
+
+ /**
+ * Returns true if any pan or zoom transition is running
+ */
+
+
+ isPanRunning() {
+ return this.activeAnimations.some(animation => {
+ return animation.props.isPan;
+ });
+ }
+
+}
+
+/** @typedef {import('./photoswipe.js').default} PhotoSwipe */
+
+/**
+ * Handles scroll wheel.
+ * Can pan and zoom current slide image.
+ */
+class ScrollWheel {
+ /**
+ * @param {PhotoSwipe} pswp
+ */
+ constructor(pswp) {
+ this.pswp = pswp;
+ pswp.events.add(pswp.element, 'wheel',
+ /** @type EventListener */
+ this._onWheel.bind(this));
+ }
+ /**
+ * @private
+ * @param {WheelEvent} e
+ */
+
+
+ _onWheel(e) {
+ e.preventDefault();
+ const {
+ currSlide
+ } = this.pswp;
+ let {
+ deltaX,
+ deltaY
+ } = e;
+
+ if (!currSlide) {
+ return;
+ }
+
+ if (this.pswp.dispatch('wheel', {
+ originalEvent: e
+ }).defaultPrevented) {
+ return;
+ }
+
+ if (e.ctrlKey || this.pswp.options.wheelToZoom) {
+ // zoom
+ if (currSlide.isZoomable()) {
+ let zoomFactor = -deltaY;
+
+ if (e.deltaMode === 1
+ /* DOM_DELTA_LINE */
+ ) {
+ zoomFactor *= 0.05;
+ } else {
+ zoomFactor *= e.deltaMode ? 1 : 0.002;
+ }
+
+ zoomFactor = 2 ** zoomFactor;
+ const destZoomLevel = currSlide.currZoomLevel * zoomFactor;
+ currSlide.zoomTo(destZoomLevel, {
+ x: e.clientX,
+ y: e.clientY
+ });
+ }
+ } else {
+ // pan
+ if (currSlide.isPannable()) {
+ if (e.deltaMode === 1
+ /* DOM_DELTA_LINE */
+ ) {
+ // 18 - average line height
+ deltaX *= 18;
+ deltaY *= 18;
+ }
+
+ currSlide.panTo(currSlide.pan.x - deltaX, currSlide.pan.y - deltaY);
+ }
+ }
+ }
+
+}
+
+/** @typedef {import('../photoswipe.js').default} PhotoSwipe */
+
+/**
+ * @template T
+ * @typedef {import('../types.js').Methods} Methods
+ */
+
+/**
+ * @typedef {Object} UIElementMarkupProps
+ * @prop {boolean} [isCustomSVG]
+ * @prop {string} inner
+ * @prop {string} [outlineID]
+ * @prop {number | string} [size]
+ */
+
+/**
+ * @typedef {Object} UIElementData
+ * @prop {DefaultUIElements | string} [name]
+ * @prop {string} [className]
+ * @prop {UIElementMarkup} [html]
+ * @prop {boolean} [isButton]
+ * @prop {keyof HTMLElementTagNameMap} [tagName]
+ * @prop {string} [title]
+ * @prop {string} [ariaLabel]
+ * @prop {(element: HTMLElement, pswp: PhotoSwipe) => void} [onInit]
+ * @prop {Methods | ((e: MouseEvent, element: HTMLElement, pswp: PhotoSwipe) => void)} [onClick]
+ * @prop {'bar' | 'wrapper' | 'root'} [appendTo]
+ * @prop {number} [order]
+ */
+
+/** @typedef {'arrowPrev' | 'arrowNext' | 'close' | 'zoom' | 'counter'} DefaultUIElements */
+
+/** @typedef {string | UIElementMarkupProps} UIElementMarkup */
+
+/**
+ * @param {UIElementMarkup} [htmlData]
+ * @returns {string}
+ */
+
+function addElementHTML(htmlData) {
+ if (typeof htmlData === 'string') {
+ // Allow developers to provide full svg,
+ // For example:
+ //
+ //
+ //
+ //
+ // Can also be any HTML string.
+ return htmlData;
+ }
+
+ if (!htmlData || !htmlData.isCustomSVG) {
+ return '';
+ }
+
+ const svgData = htmlData;
+ let out = ''; // replace all %d with size
+
+ out = out.split('%d').join(
+ /** @type {string} */
+ svgData.size || 32); // Icons may contain outline/shadow,
+ // to make it we "clone" base icon shape and add border to it.
+ // Icon itself and border are styled via CSS.
+ //
+ // Property shadowID defines ID of element that should be cloned.
+
+ if (svgData.outlineID) {
+ out += ' ';
+ }
+
+ out += svgData.inner;
+ out += ' ';
+ return out;
+}
+
+class UIElement {
+ /**
+ * @param {PhotoSwipe} pswp
+ * @param {UIElementData} data
+ */
+ constructor(pswp, data) {
+ var _container;
+
+ const name = data.name || data.className;
+ let elementHTML = data.html; // @ts-expect-error lookup only by `data.name` maybe?
+
+ if (pswp.options[name] === false) {
+ // exit if element is disabled from options
+ return;
+ } // Allow to override SVG icons from options
+ // @ts-expect-error lookup only by `data.name` maybe?
+
+
+ if (typeof pswp.options[name + 'SVG'] === 'string') {
+ // arrowPrevSVG
+ // arrowNextSVG
+ // closeSVG
+ // zoomSVG
+ // @ts-expect-error lookup only by `data.name` maybe?
+ elementHTML = pswp.options[name + 'SVG'];
+ }
+
+ pswp.dispatch('uiElementCreate', {
+ data
+ });
+ let className = '';
+
+ if (data.isButton) {
+ className += 'pswp__button ';
+ className += data.className || `pswp__button--${data.name}`;
+ } else {
+ className += data.className || `pswp__${data.name}`;
+ }
+
+ let tagName = data.isButton ? data.tagName || 'button' : data.tagName || 'div';
+ tagName =
+ /** @type {keyof HTMLElementTagNameMap} */
+ tagName.toLowerCase();
+ /** @type {HTMLElement} */
+
+ const element = createElement(className, tagName);
+
+ if (data.isButton) {
+ if (tagName === 'button') {
+ /** @type {HTMLButtonElement} */
+ element.type = 'button';
+ }
+
+ let {
+ title
+ } = data;
+ const {
+ ariaLabel
+ } = data; // @ts-expect-error lookup only by `data.name` maybe?
+
+ if (typeof pswp.options[name + 'Title'] === 'string') {
+ // @ts-expect-error lookup only by `data.name` maybe?
+ title = pswp.options[name + 'Title'];
+ }
+
+ if (title) {
+ element.title = title;
+ }
+
+ const ariaText = ariaLabel || title;
+
+ if (ariaText) {
+ element.setAttribute('aria-label', ariaText);
+ }
+ }
+
+ element.innerHTML = addElementHTML(elementHTML);
+
+ if (data.onInit) {
+ data.onInit(element, pswp);
+ }
+
+ if (data.onClick) {
+ element.onclick = e => {
+ if (typeof data.onClick === 'string') {
+ // @ts-ignore
+ pswp[data.onClick]();
+ } else if (typeof data.onClick === 'function') {
+ data.onClick(e, element, pswp);
+ }
+ };
+ } // Top bar is default position
+
+
+ const appendTo = data.appendTo || 'bar';
+ /** @type {HTMLElement | undefined} root element by default */
+
+ let container = pswp.element;
+
+ if (appendTo === 'bar') {
+ if (!pswp.topBar) {
+ pswp.topBar = createElement('pswp__top-bar pswp__hide-on-close', 'div', pswp.scrollWrap);
+ }
+
+ container = pswp.topBar;
+ } else {
+ // element outside of top bar gets a secondary class
+ // that makes element fade out on close
+ element.classList.add('pswp__hide-on-close');
+
+ if (appendTo === 'wrapper') {
+ container = pswp.scrollWrap;
+ }
+ }
+
+ (_container = container) === null || _container === void 0 || _container.appendChild(pswp.applyFilters('uiElement', element, data));
+ }
+
+}
+
+/*
+ Backward and forward arrow buttons
+ */
+
+/** @typedef {import('./ui-element.js').UIElementData} UIElementData */
+
+/** @typedef {import('../photoswipe.js').default} PhotoSwipe */
+
+/**
+ *
+ * @param {HTMLElement} element
+ * @param {PhotoSwipe} pswp
+ * @param {boolean} [isNextButton]
+ */
+function initArrowButton(element, pswp, isNextButton) {
+ element.classList.add('pswp__button--arrow'); // TODO: this should point to a unique id for this instance
+
+ element.setAttribute('aria-controls', 'pswp__items');
+ pswp.on('change', () => {
+ if (!pswp.options.loop) {
+ if (isNextButton) {
+ /** @type {HTMLButtonElement} */
+ element.disabled = !(pswp.currIndex < pswp.getNumItems() - 1);
+ } else {
+ /** @type {HTMLButtonElement} */
+ element.disabled = !(pswp.currIndex > 0);
+ }
+ }
+ });
+}
+/** @type {UIElementData} */
+
+
+const arrowPrev = {
+ name: 'arrowPrev',
+ className: 'pswp__button--arrow--prev',
+ title: 'Previous',
+ order: 10,
+ isButton: true,
+ appendTo: 'wrapper',
+ html: {
+ isCustomSVG: true,
+ size: 60,
+ inner: ' ',
+ outlineID: 'pswp__icn-arrow'
+ },
+ onClick: 'prev',
+ onInit: initArrowButton
+};
+/** @type {UIElementData} */
+
+const arrowNext = {
+ name: 'arrowNext',
+ className: 'pswp__button--arrow--next',
+ title: 'Next',
+ order: 11,
+ isButton: true,
+ appendTo: 'wrapper',
+ html: {
+ isCustomSVG: true,
+ size: 60,
+ inner: ' ',
+ outlineID: 'pswp__icn-arrow'
+ },
+ onClick: 'next',
+ onInit: (el, pswp) => {
+ initArrowButton(el, pswp, true);
+ }
+};
+
+/** @type {import('./ui-element.js').UIElementData} UIElementData */
+const closeButton = {
+ name: 'close',
+ title: 'Close',
+ order: 20,
+ isButton: true,
+ html: {
+ isCustomSVG: true,
+ inner: ' ',
+ outlineID: 'pswp__icn-close'
+ },
+ onClick: 'close'
+};
+
+/** @type {import('./ui-element.js').UIElementData} UIElementData */
+const zoomButton = {
+ name: 'zoom',
+ title: 'Zoom',
+ order: 10,
+ isButton: true,
+ html: {
+ isCustomSVG: true,
+ // eslint-disable-next-line max-len
+ inner: ' ' + ' ' + ' ',
+ outlineID: 'pswp__icn-zoom'
+ },
+ onClick: 'toggleZoom'
+};
+
+/** @type {import('./ui-element.js').UIElementData} UIElementData */
+const loadingIndicator = {
+ name: 'preloader',
+ appendTo: 'bar',
+ order: 7,
+ html: {
+ isCustomSVG: true,
+ // eslint-disable-next-line max-len
+ inner: ' ',
+ outlineID: 'pswp__icn-loading'
+ },
+ onInit: (indicatorElement, pswp) => {
+ /** @type {boolean | undefined} */
+ let isVisible;
+ /** @type {NodeJS.Timeout | null} */
+
+ let delayTimeout = null;
+ /**
+ * @param {string} className
+ * @param {boolean} add
+ */
+
+ const toggleIndicatorClass = (className, add) => {
+ indicatorElement.classList.toggle('pswp__preloader--' + className, add);
+ };
+ /**
+ * @param {boolean} visible
+ */
+
+
+ const setIndicatorVisibility = visible => {
+ if (isVisible !== visible) {
+ isVisible = visible;
+ toggleIndicatorClass('active', visible);
+ }
+ };
+
+ const updatePreloaderVisibility = () => {
+ var _pswp$currSlide;
+
+ if (!((_pswp$currSlide = pswp.currSlide) !== null && _pswp$currSlide !== void 0 && _pswp$currSlide.content.isLoading())) {
+ setIndicatorVisibility(false);
+
+ if (delayTimeout) {
+ clearTimeout(delayTimeout);
+ delayTimeout = null;
+ }
+
+ return;
+ }
+
+ if (!delayTimeout) {
+ // display loading indicator with delay
+ delayTimeout = setTimeout(() => {
+ var _pswp$currSlide2;
+
+ setIndicatorVisibility(Boolean((_pswp$currSlide2 = pswp.currSlide) === null || _pswp$currSlide2 === void 0 ? void 0 : _pswp$currSlide2.content.isLoading()));
+ delayTimeout = null;
+ }, pswp.options.preloaderDelay);
+ }
+ };
+
+ pswp.on('change', updatePreloaderVisibility);
+ pswp.on('loadComplete', e => {
+ if (pswp.currSlide === e.slide) {
+ updatePreloaderVisibility();
+ }
+ }); // expose the method
+
+ if (pswp.ui) {
+ pswp.ui.updatePreloaderVisibility = updatePreloaderVisibility;
+ }
+ }
+};
+
+/** @type {import('./ui-element.js').UIElementData} UIElementData */
+const counterIndicator = {
+ name: 'counter',
+ order: 5,
+ onInit: (counterElement, pswp) => {
+ pswp.on('change', () => {
+ counterElement.innerText = pswp.currIndex + 1 + pswp.options.indexIndicatorSep + pswp.getNumItems();
+ });
+ }
+};
+
+/** @typedef {import('../photoswipe.js').default} PhotoSwipe */
+
+/** @typedef {import('./ui-element.js').UIElementData} UIElementData */
+
+/**
+ * Set special class on element when image is zoomed.
+ *
+ * By default, it is used to adjust
+ * zoom icon and zoom cursor via CSS.
+ *
+ * @param {HTMLElement} el
+ * @param {boolean} isZoomedIn
+ */
+
+function setZoomedIn(el, isZoomedIn) {
+ el.classList.toggle('pswp--zoomed-in', isZoomedIn);
+}
+
+class UI {
+ /**
+ * @param {PhotoSwipe} pswp
+ */
+ constructor(pswp) {
+ this.pswp = pswp;
+ this.isRegistered = false;
+ /** @type {UIElementData[]} */
+
+ this.uiElementsData = [];
+ /** @type {(UIElement | UIElementData)[]} */
+
+ this.items = [];
+ /** @type {() => void} */
+
+ this.updatePreloaderVisibility = () => {};
+ /**
+ * @private
+ * @type {number | undefined}
+ */
+
+
+ this._lastUpdatedZoomLevel = undefined;
+ }
+
+ init() {
+ const {
+ pswp
+ } = this;
+ this.isRegistered = false;
+ this.uiElementsData = [closeButton, arrowPrev, arrowNext, zoomButton, loadingIndicator, counterIndicator];
+ pswp.dispatch('uiRegister'); // sort by order
+
+ this.uiElementsData.sort((a, b) => {
+ // default order is 0
+ return (a.order || 0) - (b.order || 0);
+ });
+ this.items = [];
+ this.isRegistered = true;
+ this.uiElementsData.forEach(uiElementData => {
+ this.registerElement(uiElementData);
+ });
+ pswp.on('change', () => {
+ var _pswp$element;
+
+ (_pswp$element = pswp.element) === null || _pswp$element === void 0 || _pswp$element.classList.toggle('pswp--one-slide', pswp.getNumItems() === 1);
+ });
+ pswp.on('zoomPanUpdate', () => this._onZoomPanUpdate());
+ }
+ /**
+ * @param {UIElementData} elementData
+ */
+
+
+ registerElement(elementData) {
+ if (this.isRegistered) {
+ this.items.push(new UIElement(this.pswp, elementData));
+ } else {
+ this.uiElementsData.push(elementData);
+ }
+ }
+ /**
+ * Fired each time zoom or pan position is changed.
+ * Update classes that control visibility of zoom button and cursor icon.
+ *
+ * @private
+ */
+
+
+ _onZoomPanUpdate() {
+ const {
+ template,
+ currSlide,
+ options
+ } = this.pswp;
+
+ if (this.pswp.opener.isClosing || !template || !currSlide) {
+ return;
+ }
+
+ let {
+ currZoomLevel
+ } = currSlide; // if not open yet - check against initial zoom level
+
+ if (!this.pswp.opener.isOpen) {
+ currZoomLevel = currSlide.zoomLevels.initial;
+ }
+
+ if (currZoomLevel === this._lastUpdatedZoomLevel) {
+ return;
+ }
+
+ this._lastUpdatedZoomLevel = currZoomLevel;
+ const currZoomLevelDiff = currSlide.zoomLevels.initial - currSlide.zoomLevels.secondary; // Initial and secondary zoom levels are almost equal
+
+ if (Math.abs(currZoomLevelDiff) < 0.01 || !currSlide.isZoomable()) {
+ // disable zoom
+ setZoomedIn(template, false);
+ template.classList.remove('pswp--zoom-allowed');
+ return;
+ }
+
+ template.classList.add('pswp--zoom-allowed');
+ const potentialZoomLevel = currZoomLevel === currSlide.zoomLevels.initial ? currSlide.zoomLevels.secondary : currSlide.zoomLevels.initial;
+ setZoomedIn(template, potentialZoomLevel <= currZoomLevel);
+
+ if (options.imageClickAction === 'zoom' || options.imageClickAction === 'zoom-or-close') {
+ template.classList.add('pswp--click-to-zoom');
+ }
+ }
+
+}
+
+/** @typedef {import('./slide.js').SlideData} SlideData */
+
+/** @typedef {import('../photoswipe.js').default} PhotoSwipe */
+
+/** @typedef {{ x: number; y: number; w: number; innerRect?: { w: number; h: number; x: number; y: number } }} Bounds */
+
+/**
+ * @param {HTMLElement} el
+ * @returns Bounds
+ */
+function getBoundsByElement(el) {
+ const thumbAreaRect = el.getBoundingClientRect();
+ return {
+ x: thumbAreaRect.left,
+ y: thumbAreaRect.top,
+ w: thumbAreaRect.width
+ };
+}
+/**
+ * @param {HTMLElement} el
+ * @param {number} imageWidth
+ * @param {number} imageHeight
+ * @returns Bounds
+ */
+
+
+function getCroppedBoundsByElement(el, imageWidth, imageHeight) {
+ const thumbAreaRect = el.getBoundingClientRect(); // fill image into the area
+ // (do they same as object-fit:cover does to retrieve coordinates)
+
+ const hRatio = thumbAreaRect.width / imageWidth;
+ const vRatio = thumbAreaRect.height / imageHeight;
+ const fillZoomLevel = hRatio > vRatio ? hRatio : vRatio;
+ const offsetX = (thumbAreaRect.width - imageWidth * fillZoomLevel) / 2;
+ const offsetY = (thumbAreaRect.height - imageHeight * fillZoomLevel) / 2;
+ /**
+ * Coordinates of the image,
+ * as if it was not cropped,
+ * height is calculated automatically
+ *
+ * @type {Bounds}
+ */
+
+ const bounds = {
+ x: thumbAreaRect.left + offsetX,
+ y: thumbAreaRect.top + offsetY,
+ w: imageWidth * fillZoomLevel
+ }; // Coordinates of inner crop area
+ // relative to the image
+
+ bounds.innerRect = {
+ w: thumbAreaRect.width,
+ h: thumbAreaRect.height,
+ x: offsetX,
+ y: offsetY
+ };
+ return bounds;
+}
+/**
+ * Get dimensions of thumbnail image
+ * (click on which opens photoswipe or closes photoswipe to)
+ *
+ * @param {number} index
+ * @param {SlideData} itemData
+ * @param {PhotoSwipe} instance PhotoSwipe instance
+ * @returns {Bounds | undefined}
+ */
+
+
+function getThumbBounds(index, itemData, instance) {
+ // legacy event, before filters were introduced
+ const event = instance.dispatch('thumbBounds', {
+ index,
+ itemData,
+ instance
+ }); // @ts-expect-error
+
+ if (event.thumbBounds) {
+ // @ts-expect-error
+ return event.thumbBounds;
+ }
+
+ const {
+ element
+ } = itemData;
+ /** @type {Bounds | undefined} */
+
+ let thumbBounds;
+ /** @type {HTMLElement | null | undefined} */
+
+ let thumbnail;
+
+ if (element && instance.options.thumbSelector !== false) {
+ const thumbSelector = instance.options.thumbSelector || 'img';
+ thumbnail = element.matches(thumbSelector) ? element :
+ /** @type {HTMLElement | null} */
+ element.querySelector(thumbSelector);
+ }
+
+ thumbnail = instance.applyFilters('thumbEl', thumbnail, itemData, index);
+
+ if (thumbnail) {
+ if (!itemData.thumbCropped) {
+ thumbBounds = getBoundsByElement(thumbnail);
+ } else {
+ thumbBounds = getCroppedBoundsByElement(thumbnail, itemData.width || itemData.w || 0, itemData.height || itemData.h || 0);
+ }
+ }
+
+ return instance.applyFilters('thumbBounds', thumbBounds, itemData, index);
+}
+
+/** @typedef {import('../lightbox/lightbox.js').default} PhotoSwipeLightbox */
+
+/** @typedef {import('../photoswipe.js').default} PhotoSwipe */
+
+/** @typedef {import('../photoswipe.js').PhotoSwipeOptions} PhotoSwipeOptions */
+
+/** @typedef {import('../photoswipe.js').DataSource} DataSource */
+
+/** @typedef {import('../ui/ui-element.js').UIElementData} UIElementData */
+
+/** @typedef {import('../slide/content.js').default} ContentDefault */
+
+/** @typedef {import('../slide/slide.js').default} Slide */
+
+/** @typedef {import('../slide/slide.js').SlideData} SlideData */
+
+/** @typedef {import('../slide/zoom-level.js').default} ZoomLevel */
+
+/** @typedef {import('../slide/get-thumb-bounds.js').Bounds} Bounds */
+
+/**
+ * Allow adding an arbitrary props to the Content
+ * https://photoswipe.com/custom-content/#using-webp-image-format
+ * @typedef {ContentDefault & Record} Content
+ */
+
+/** @typedef {{ x?: number; y?: number }} Point */
+
+/**
+ * @typedef {Object} PhotoSwipeEventsMap https://photoswipe.com/events/
+ *
+ *
+ * https://photoswipe.com/adding-ui-elements/
+ *
+ * @prop {undefined} uiRegister
+ * @prop {{ data: UIElementData }} uiElementCreate
+ *
+ *
+ * https://photoswipe.com/events/#initialization-events
+ *
+ * @prop {undefined} beforeOpen
+ * @prop {undefined} firstUpdate
+ * @prop {undefined} initialLayout
+ * @prop {undefined} change
+ * @prop {undefined} afterInit
+ * @prop {undefined} bindEvents
+ *
+ *
+ * https://photoswipe.com/events/#opening-or-closing-transition-events
+ *
+ * @prop {undefined} openingAnimationStart
+ * @prop {undefined} openingAnimationEnd
+ * @prop {undefined} closingAnimationStart
+ * @prop {undefined} closingAnimationEnd
+ *
+ *
+ * https://photoswipe.com/events/#closing-events
+ *
+ * @prop {undefined} close
+ * @prop {undefined} destroy
+ *
+ *
+ * https://photoswipe.com/events/#pointer-and-gesture-events
+ *
+ * @prop {{ originalEvent: PointerEvent }} pointerDown
+ * @prop {{ originalEvent: PointerEvent }} pointerMove
+ * @prop {{ originalEvent: PointerEvent }} pointerUp
+ * @prop {{ bgOpacity: number }} pinchClose can be default prevented
+ * @prop {{ panY: number }} verticalDrag can be default prevented
+ *
+ *
+ * https://photoswipe.com/events/#slide-content-events
+ *
+ * @prop {{ content: Content }} contentInit
+ * @prop {{ content: Content; isLazy: boolean }} contentLoad can be default prevented
+ * @prop {{ content: Content; isLazy: boolean }} contentLoadImage can be default prevented
+ * @prop {{ content: Content; slide: Slide; isError?: boolean }} loadComplete
+ * @prop {{ content: Content; slide: Slide }} loadError
+ * @prop {{ content: Content; width: number; height: number }} contentResize can be default prevented
+ * @prop {{ content: Content; width: number; height: number; slide: Slide }} imageSizeChange
+ * @prop {{ content: Content }} contentLazyLoad can be default prevented
+ * @prop {{ content: Content }} contentAppend can be default prevented
+ * @prop {{ content: Content }} contentActivate can be default prevented
+ * @prop {{ content: Content }} contentDeactivate can be default prevented
+ * @prop {{ content: Content }} contentRemove can be default prevented
+ * @prop {{ content: Content }} contentDestroy can be default prevented
+ *
+ *
+ * undocumented
+ *
+ * @prop {{ point: Point; originalEvent: PointerEvent }} imageClickAction can be default prevented
+ * @prop {{ point: Point; originalEvent: PointerEvent }} bgClickAction can be default prevented
+ * @prop {{ point: Point; originalEvent: PointerEvent }} tapAction can be default prevented
+ * @prop {{ point: Point; originalEvent: PointerEvent }} doubleTapAction can be default prevented
+ *
+ * @prop {{ originalEvent: KeyboardEvent }} keydown can be default prevented
+ * @prop {{ x: number; dragging: boolean }} moveMainScroll
+ * @prop {{ slide: Slide }} firstZoomPan
+ * @prop {{ slide: Slide | undefined, data: SlideData, index: number }} gettingData
+ * @prop {undefined} beforeResize
+ * @prop {undefined} resize
+ * @prop {undefined} viewportSize
+ * @prop {undefined} updateScrollOffset
+ * @prop {{ slide: Slide }} slideInit
+ * @prop {{ slide: Slide }} afterSetContent
+ * @prop {{ slide: Slide }} slideLoad
+ * @prop {{ slide: Slide }} appendHeavy can be default prevented
+ * @prop {{ slide: Slide }} appendHeavyContent
+ * @prop {{ slide: Slide }} slideActivate
+ * @prop {{ slide: Slide }} slideDeactivate
+ * @prop {{ slide: Slide }} slideDestroy
+ * @prop {{ destZoomLevel: number, centerPoint: Point | undefined, transitionDuration: number | false | undefined }} beforeZoomTo
+ * @prop {{ slide: Slide }} zoomPanUpdate
+ * @prop {{ slide: Slide }} initialZoomPan
+ * @prop {{ slide: Slide }} calcSlideSize
+ * @prop {undefined} resolutionChanged
+ * @prop {{ originalEvent: WheelEvent }} wheel can be default prevented
+ * @prop {{ content: Content }} contentAppendImage can be default prevented
+ * @prop {{ index: number; itemData: SlideData }} lazyLoadSlide can be default prevented
+ * @prop {undefined} lazyLoad
+ * @prop {{ slide: Slide }} calcBounds
+ * @prop {{ zoomLevels: ZoomLevel, slideData: SlideData }} zoomLevelsUpdate
+ *
+ *
+ * legacy
+ *
+ * @prop {undefined} init
+ * @prop {undefined} initialZoomIn
+ * @prop {undefined} initialZoomOut
+ * @prop {undefined} initialZoomInEnd
+ * @prop {undefined} initialZoomOutEnd
+ * @prop {{ dataSource: DataSource | undefined, numItems: number }} numItems
+ * @prop {{ itemData: SlideData; index: number }} itemData
+ * @prop {{ index: number, itemData: SlideData, instance: PhotoSwipe }} thumbBounds
+ */
+
+/**
+ * @typedef {Object} PhotoSwipeFiltersMap https://photoswipe.com/filters/
+ *
+ * @prop {(numItems: number, dataSource: DataSource | undefined) => number} numItems
+ * Modify the total amount of slides. Example on Data sources page.
+ * https://photoswipe.com/filters/#numitems
+ *
+ * @prop {(itemData: SlideData, index: number) => SlideData} itemData
+ * Modify slide item data. Example on Data sources page.
+ * https://photoswipe.com/filters/#itemdata
+ *
+ * @prop {(itemData: SlideData, element: HTMLElement, linkEl: HTMLAnchorElement) => SlideData} domItemData
+ * Modify item data when it's parsed from DOM element. Example on Data sources page.
+ * https://photoswipe.com/filters/#domitemdata
+ *
+ * @prop {(clickedIndex: number, e: MouseEvent, instance: PhotoSwipeLightbox) => number} clickedIndex
+ * Modify clicked gallery item index.
+ * https://photoswipe.com/filters/#clickedindex
+ *
+ * @prop {(placeholderSrc: string | false, content: Content) => string | false} placeholderSrc
+ * Modify placeholder image source.
+ * https://photoswipe.com/filters/#placeholdersrc
+ *
+ * @prop {(isContentLoading: boolean, content: Content) => boolean} isContentLoading
+ * Modify if the content is currently loading.
+ * https://photoswipe.com/filters/#iscontentloading
+ *
+ * @prop {(isContentZoomable: boolean, content: Content) => boolean} isContentZoomable
+ * Modify if the content can be zoomed.
+ * https://photoswipe.com/filters/#iscontentzoomable
+ *
+ * @prop {(useContentPlaceholder: boolean, content: Content) => boolean} useContentPlaceholder
+ * Modify if the placeholder should be used for the content.
+ * https://photoswipe.com/filters/#usecontentplaceholder
+ *
+ * @prop {(isKeepingPlaceholder: boolean, content: Content) => boolean} isKeepingPlaceholder
+ * Modify if the placeholder should be kept after the content is loaded.
+ * https://photoswipe.com/filters/#iskeepingplaceholder
+ *
+ *
+ * @prop {(contentErrorElement: HTMLElement, content: Content) => HTMLElement} contentErrorElement
+ * Modify an element when the content has error state (for example, if image cannot be loaded).
+ * https://photoswipe.com/filters/#contenterrorelement
+ *
+ * @prop {(element: HTMLElement, data: UIElementData) => HTMLElement} uiElement
+ * Modify a UI element that's being created.
+ * https://photoswipe.com/filters/#uielement
+ *
+ * @prop {(thumbnail: HTMLElement | null | undefined, itemData: SlideData, index: number) => HTMLElement} thumbEl
+ * Modify the thumbnail element from which opening zoom animation starts or ends.
+ * https://photoswipe.com/filters/#thumbel
+ *
+ * @prop {(thumbBounds: Bounds | undefined, itemData: SlideData, index: number) => Bounds} thumbBounds
+ * Modify the thumbnail bounds from which opening zoom animation starts or ends.
+ * https://photoswipe.com/filters/#thumbbounds
+ *
+ * @prop {(srcsetSizesWidth: number, content: Content) => number} srcsetSizesWidth
+ *
+ * @prop {(preventPointerEvent: boolean, event: PointerEvent, pointerType: string) => boolean} preventPointerEvent
+ *
+ */
+
+/**
+ * @template {keyof PhotoSwipeFiltersMap} T
+ * @typedef {{ fn: PhotoSwipeFiltersMap[T], priority: number }} Filter
+ */
+
+/**
+ * @template {keyof PhotoSwipeEventsMap} T
+ * @typedef {PhotoSwipeEventsMap[T] extends undefined ? PhotoSwipeEvent : PhotoSwipeEvent & PhotoSwipeEventsMap[T]} AugmentedEvent
+ */
+
+/**
+ * @template {keyof PhotoSwipeEventsMap} T
+ * @typedef {(event: AugmentedEvent) => void} EventCallback
+ */
+
+/**
+ * Base PhotoSwipe event object
+ *
+ * @template {keyof PhotoSwipeEventsMap} T
+ */
+class PhotoSwipeEvent {
+ /**
+ * @param {T} type
+ * @param {PhotoSwipeEventsMap[T]} [details]
+ */
+ constructor(type, details) {
+ this.type = type;
+ this.defaultPrevented = false;
+
+ if (details) {
+ Object.assign(this, details);
+ }
+ }
+
+ preventDefault() {
+ this.defaultPrevented = true;
+ }
+
+}
+/**
+ * PhotoSwipe base class that can listen and dispatch for events.
+ * Shared by PhotoSwipe Core and PhotoSwipe Lightbox, extended by base.js
+ */
+
+
+class Eventable {
+ constructor() {
+ /**
+ * @type {{ [T in keyof PhotoSwipeEventsMap]?: ((event: AugmentedEvent) => void)[] }}
+ */
+ this._listeners = {};
+ /**
+ * @type {{ [T in keyof PhotoSwipeFiltersMap]?: Filter[] }}
+ */
+
+ this._filters = {};
+ /** @type {PhotoSwipe | undefined} */
+
+ this.pswp = undefined;
+ /** @type {PhotoSwipeOptions | undefined} */
+
+ this.options = undefined;
+ }
+ /**
+ * @template {keyof PhotoSwipeFiltersMap} T
+ * @param {T} name
+ * @param {PhotoSwipeFiltersMap[T]} fn
+ * @param {number} priority
+ */
+
+
+ addFilter(name, fn, priority = 100) {
+ var _this$_filters$name, _this$_filters$name2, _this$pswp;
+
+ if (!this._filters[name]) {
+ this._filters[name] = [];
+ }
+
+ (_this$_filters$name = this._filters[name]) === null || _this$_filters$name === void 0 || _this$_filters$name.push({
+ fn,
+ priority
+ });
+ (_this$_filters$name2 = this._filters[name]) === null || _this$_filters$name2 === void 0 || _this$_filters$name2.sort((f1, f2) => f1.priority - f2.priority);
+ (_this$pswp = this.pswp) === null || _this$pswp === void 0 || _this$pswp.addFilter(name, fn, priority);
+ }
+ /**
+ * @template {keyof PhotoSwipeFiltersMap} T
+ * @param {T} name
+ * @param {PhotoSwipeFiltersMap[T]} fn
+ */
+
+
+ removeFilter(name, fn) {
+ if (this._filters[name]) {
+ // @ts-expect-error
+ this._filters[name] = this._filters[name].filter(filter => filter.fn !== fn);
+ }
+
+ if (this.pswp) {
+ this.pswp.removeFilter(name, fn);
+ }
+ }
+ /**
+ * @template {keyof PhotoSwipeFiltersMap} T
+ * @param {T} name
+ * @param {Parameters} args
+ * @returns {Parameters[0]}
+ */
+
+
+ applyFilters(name, ...args) {
+ var _this$_filters$name3;
+
+ (_this$_filters$name3 = this._filters[name]) === null || _this$_filters$name3 === void 0 || _this$_filters$name3.forEach(filter => {
+ // @ts-expect-error
+ args[0] = filter.fn.apply(this, args);
+ });
+ return args[0];
+ }
+ /**
+ * @template {keyof PhotoSwipeEventsMap} T
+ * @param {T} name
+ * @param {EventCallback} fn
+ */
+
+
+ on(name, fn) {
+ var _this$_listeners$name, _this$pswp2;
+
+ if (!this._listeners[name]) {
+ this._listeners[name] = [];
+ }
+
+ (_this$_listeners$name = this._listeners[name]) === null || _this$_listeners$name === void 0 || _this$_listeners$name.push(fn); // When binding events to lightbox,
+ // also bind events to PhotoSwipe Core,
+ // if it's open.
+
+ (_this$pswp2 = this.pswp) === null || _this$pswp2 === void 0 || _this$pswp2.on(name, fn);
+ }
+ /**
+ * @template {keyof PhotoSwipeEventsMap} T
+ * @param {T} name
+ * @param {EventCallback} fn
+ */
+
+
+ off(name, fn) {
+ var _this$pswp3;
+
+ if (this._listeners[name]) {
+ // @ts-expect-error
+ this._listeners[name] = this._listeners[name].filter(listener => fn !== listener);
+ }
+
+ (_this$pswp3 = this.pswp) === null || _this$pswp3 === void 0 || _this$pswp3.off(name, fn);
+ }
+ /**
+ * @template {keyof PhotoSwipeEventsMap} T
+ * @param {T} name
+ * @param {PhotoSwipeEventsMap[T]} [details]
+ * @returns {AugmentedEvent}
+ */
+
+
+ dispatch(name, details) {
+ var _this$_listeners$name2;
+
+ if (this.pswp) {
+ return this.pswp.dispatch(name, details);
+ }
+
+ const event =
+ /** @type {AugmentedEvent} */
+ new PhotoSwipeEvent(name, details);
+ (_this$_listeners$name2 = this._listeners[name]) === null || _this$_listeners$name2 === void 0 || _this$_listeners$name2.forEach(listener => {
+ listener.call(this, event);
+ });
+ return event;
+ }
+
+}
+
+class Placeholder {
+ /**
+ * @param {string | false} imageSrc
+ * @param {HTMLElement} container
+ */
+ constructor(imageSrc, container) {
+ // Create placeholder
+ // (stretched thumbnail or simple div behind the main image)
+
+ /** @type {HTMLImageElement | HTMLDivElement | null} */
+ this.element = createElement('pswp__img pswp__img--placeholder', imageSrc ? 'img' : 'div', container);
+
+ if (imageSrc) {
+ const imgEl =
+ /** @type {HTMLImageElement} */
+ this.element;
+ imgEl.decoding = 'async';
+ imgEl.alt = '';
+ imgEl.src = imageSrc;
+ imgEl.setAttribute('role', 'presentation');
+ }
+
+ this.element.setAttribute('aria-hidden', 'true');
+ }
+ /**
+ * @param {number} width
+ * @param {number} height
+ */
+
+
+ setDisplayedSize(width, height) {
+ if (!this.element) {
+ return;
+ }
+
+ if (this.element.tagName === 'IMG') {
+ // Use transform scale() to modify img placeholder size
+ // (instead of changing width/height directly).
+ // This helps with performance, specifically in iOS15 Safari.
+ setWidthHeight(this.element, 250, 'auto');
+ this.element.style.transformOrigin = '0 0';
+ this.element.style.transform = toTransformString(0, 0, width / 250);
+ } else {
+ setWidthHeight(this.element, width, height);
+ }
+ }
+
+ destroy() {
+ var _this$element;
+
+ if ((_this$element = this.element) !== null && _this$element !== void 0 && _this$element.parentNode) {
+ this.element.remove();
+ }
+
+ this.element = null;
+ }
+
+}
+
+/** @typedef {import('./slide.js').default} Slide */
+
+/** @typedef {import('./slide.js').SlideData} SlideData */
+
+/** @typedef {import('../core/base.js').default} PhotoSwipeBase */
+
+/** @typedef {import('../util/util.js').LoadState} LoadState */
+
+class Content {
+ /**
+ * @param {SlideData} itemData Slide data
+ * @param {PhotoSwipeBase} instance PhotoSwipe or PhotoSwipeLightbox instance
+ * @param {number} index
+ */
+ constructor(itemData, instance, index) {
+ this.instance = instance;
+ this.data = itemData;
+ this.index = index;
+ /** @type {HTMLImageElement | HTMLDivElement | undefined} */
+
+ this.element = undefined;
+ /** @type {Placeholder | undefined} */
+
+ this.placeholder = undefined;
+ /** @type {Slide | undefined} */
+
+ this.slide = undefined;
+ this.displayedImageWidth = 0;
+ this.displayedImageHeight = 0;
+ this.width = Number(this.data.w) || Number(this.data.width) || 0;
+ this.height = Number(this.data.h) || Number(this.data.height) || 0;
+ this.isAttached = false;
+ this.hasSlide = false;
+ this.isDecoding = false;
+ /** @type {LoadState} */
+
+ this.state = LOAD_STATE.IDLE;
+
+ if (this.data.type) {
+ this.type = this.data.type;
+ } else if (this.data.src) {
+ this.type = 'image';
+ } else {
+ this.type = 'html';
+ }
+
+ this.instance.dispatch('contentInit', {
+ content: this
+ });
+ }
+
+ removePlaceholder() {
+ if (this.placeholder && !this.keepPlaceholder()) {
+ // With delay, as image might be loaded, but not rendered
+ setTimeout(() => {
+ if (this.placeholder) {
+ this.placeholder.destroy();
+ this.placeholder = undefined;
+ }
+ }, 1000);
+ }
+ }
+ /**
+ * Preload content
+ *
+ * @param {boolean} isLazy
+ * @param {boolean} [reload]
+ */
+
+
+ load(isLazy, reload) {
+ if (this.slide && this.usePlaceholder()) {
+ if (!this.placeholder) {
+ const placeholderSrc = this.instance.applyFilters('placeholderSrc', // use image-based placeholder only for the first slide,
+ // as rendering (even small stretched thumbnail) is an expensive operation
+ this.data.msrc && this.slide.isFirstSlide ? this.data.msrc : false, this);
+ this.placeholder = new Placeholder(placeholderSrc, this.slide.container);
+ } else {
+ const placeholderEl = this.placeholder.element; // Add placeholder to DOM if it was already created
+
+ if (placeholderEl && !placeholderEl.parentElement) {
+ this.slide.container.prepend(placeholderEl);
+ }
+ }
+ }
+
+ if (this.element && !reload) {
+ return;
+ }
+
+ if (this.instance.dispatch('contentLoad', {
+ content: this,
+ isLazy
+ }).defaultPrevented) {
+ return;
+ }
+
+ if (this.isImageContent()) {
+ this.element = createElement('pswp__img', 'img'); // Start loading only after width is defined, as sizes might depend on it.
+ // Due to Safari feature, we must define sizes before srcset.
+
+ if (this.displayedImageWidth) {
+ this.loadImage(isLazy);
+ }
+ } else {
+ this.element = createElement('pswp__content', 'div');
+ this.element.innerHTML = this.data.html || '';
+ }
+
+ if (reload && this.slide) {
+ this.slide.updateContentSize(true);
+ }
+ }
+ /**
+ * Preload image
+ *
+ * @param {boolean} isLazy
+ */
+
+
+ loadImage(isLazy) {
+ var _this$data$src, _this$data$alt;
+
+ if (!this.isImageContent() || !this.element || this.instance.dispatch('contentLoadImage', {
+ content: this,
+ isLazy
+ }).defaultPrevented) {
+ return;
+ }
+
+ const imageElement =
+ /** @type HTMLImageElement */
+ this.element;
+ this.updateSrcsetSizes();
+
+ if (this.data.srcset) {
+ imageElement.srcset = this.data.srcset;
+ }
+
+ imageElement.src = (_this$data$src = this.data.src) !== null && _this$data$src !== void 0 ? _this$data$src : '';
+ imageElement.alt = (_this$data$alt = this.data.alt) !== null && _this$data$alt !== void 0 ? _this$data$alt : '';
+ this.state = LOAD_STATE.LOADING;
+
+ if (imageElement.complete) {
+ this.onLoaded();
+ } else {
+ imageElement.onload = () => {
+ this.onLoaded();
+ };
+
+ imageElement.onerror = () => {
+ this.onError();
+ };
+ }
+ }
+ /**
+ * Assign slide to content
+ *
+ * @param {Slide} slide
+ */
+
+
+ setSlide(slide) {
+ this.slide = slide;
+ this.hasSlide = true;
+ this.instance = slide.pswp; // todo: do we need to unset slide?
+ }
+ /**
+ * Content load success handler
+ */
+
+
+ onLoaded() {
+ this.state = LOAD_STATE.LOADED;
+
+ if (this.slide && this.element) {
+ this.instance.dispatch('loadComplete', {
+ slide: this.slide,
+ content: this
+ }); // if content is reloaded
+
+ if (this.slide.isActive && this.slide.heavyAppended && !this.element.parentNode) {
+ this.append();
+ this.slide.updateContentSize(true);
+ }
+
+ if (this.state === LOAD_STATE.LOADED || this.state === LOAD_STATE.ERROR) {
+ this.removePlaceholder();
+ }
+ }
+ }
+ /**
+ * Content load error handler
+ */
+
+
+ onError() {
+ this.state = LOAD_STATE.ERROR;
+
+ if (this.slide) {
+ this.displayError();
+ this.instance.dispatch('loadComplete', {
+ slide: this.slide,
+ isError: true,
+ content: this
+ });
+ this.instance.dispatch('loadError', {
+ slide: this.slide,
+ content: this
+ });
+ }
+ }
+ /**
+ * @returns {Boolean} If the content is currently loading
+ */
+
+
+ isLoading() {
+ return this.instance.applyFilters('isContentLoading', this.state === LOAD_STATE.LOADING, this);
+ }
+ /**
+ * @returns {Boolean} If the content is in error state
+ */
+
+
+ isError() {
+ return this.state === LOAD_STATE.ERROR;
+ }
+ /**
+ * @returns {boolean} If the content is image
+ */
+
+
+ isImageContent() {
+ return this.type === 'image';
+ }
+ /**
+ * Update content size
+ *
+ * @param {Number} width
+ * @param {Number} height
+ */
+
+
+ setDisplayedSize(width, height) {
+ if (!this.element) {
+ return;
+ }
+
+ if (this.placeholder) {
+ this.placeholder.setDisplayedSize(width, height);
+ }
+
+ if (this.instance.dispatch('contentResize', {
+ content: this,
+ width,
+ height
+ }).defaultPrevented) {
+ return;
+ }
+
+ setWidthHeight(this.element, width, height);
+
+ if (this.isImageContent() && !this.isError()) {
+ const isInitialSizeUpdate = !this.displayedImageWidth && width;
+ this.displayedImageWidth = width;
+ this.displayedImageHeight = height;
+
+ if (isInitialSizeUpdate) {
+ this.loadImage(false);
+ } else {
+ this.updateSrcsetSizes();
+ }
+
+ if (this.slide) {
+ this.instance.dispatch('imageSizeChange', {
+ slide: this.slide,
+ width,
+ height,
+ content: this
+ });
+ }
+ }
+ }
+ /**
+ * @returns {boolean} If the content can be zoomed
+ */
+
+
+ isZoomable() {
+ return this.instance.applyFilters('isContentZoomable', this.isImageContent() && this.state !== LOAD_STATE.ERROR, this);
+ }
+ /**
+ * Update image srcset sizes attribute based on width and height
+ */
+
+
+ updateSrcsetSizes() {
+ // Handle srcset sizes attribute.
+ //
+ // Never lower quality, if it was increased previously.
+ // Chrome does this automatically, Firefox and Safari do not,
+ // so we store largest used size in dataset.
+ if (!this.isImageContent() || !this.element || !this.data.srcset) {
+ return;
+ }
+
+ const image =
+ /** @type HTMLImageElement */
+ this.element;
+ const sizesWidth = this.instance.applyFilters('srcsetSizesWidth', this.displayedImageWidth, this);
+
+ if (!image.dataset.largestUsedSize || sizesWidth > parseInt(image.dataset.largestUsedSize, 10)) {
+ image.sizes = sizesWidth + 'px';
+ image.dataset.largestUsedSize = String(sizesWidth);
+ }
+ }
+ /**
+ * @returns {boolean} If content should use a placeholder (from msrc by default)
+ */
+
+
+ usePlaceholder() {
+ return this.instance.applyFilters('useContentPlaceholder', this.isImageContent(), this);
+ }
+ /**
+ * Preload content with lazy-loading param
+ */
+
+
+ lazyLoad() {
+ if (this.instance.dispatch('contentLazyLoad', {
+ content: this
+ }).defaultPrevented) {
+ return;
+ }
+
+ this.load(true);
+ }
+ /**
+ * @returns {boolean} If placeholder should be kept after content is loaded
+ */
+
+
+ keepPlaceholder() {
+ return this.instance.applyFilters('isKeepingPlaceholder', this.isLoading(), this);
+ }
+ /**
+ * Destroy the content
+ */
+
+
+ destroy() {
+ this.hasSlide = false;
+ this.slide = undefined;
+
+ if (this.instance.dispatch('contentDestroy', {
+ content: this
+ }).defaultPrevented) {
+ return;
+ }
+
+ this.remove();
+
+ if (this.placeholder) {
+ this.placeholder.destroy();
+ this.placeholder = undefined;
+ }
+
+ if (this.isImageContent() && this.element) {
+ this.element.onload = null;
+ this.element.onerror = null;
+ this.element = undefined;
+ }
+ }
+ /**
+ * Display error message
+ */
+
+
+ displayError() {
+ if (this.slide) {
+ var _this$instance$option, _this$instance$option2;
+
+ let errorMsgEl = createElement('pswp__error-msg', 'div');
+ errorMsgEl.innerText = (_this$instance$option = (_this$instance$option2 = this.instance.options) === null || _this$instance$option2 === void 0 ? void 0 : _this$instance$option2.errorMsg) !== null && _this$instance$option !== void 0 ? _this$instance$option : '';
+ errorMsgEl =
+ /** @type {HTMLDivElement} */
+ this.instance.applyFilters('contentErrorElement', errorMsgEl, this);
+ this.element = createElement('pswp__content pswp__error-msg-container', 'div');
+ this.element.appendChild(errorMsgEl);
+ this.slide.container.innerText = '';
+ this.slide.container.appendChild(this.element);
+ this.slide.updateContentSize(true);
+ this.removePlaceholder();
+ }
+ }
+ /**
+ * Append the content
+ */
+
+
+ append() {
+ if (this.isAttached || !this.element) {
+ return;
+ }
+
+ this.isAttached = true;
+
+ if (this.state === LOAD_STATE.ERROR) {
+ this.displayError();
+ return;
+ }
+
+ if (this.instance.dispatch('contentAppend', {
+ content: this
+ }).defaultPrevented) {
+ return;
+ }
+
+ const supportsDecode = ('decode' in this.element);
+
+ if (this.isImageContent()) {
+ // Use decode() on nearby slides
+ //
+ // Nearby slide images are in DOM and not hidden via display:none.
+ // However, they are placed offscreen (to the left and right side).
+ //
+ // Some browsers do not composite the image until it's actually visible,
+ // using decode() helps.
+ //
+ // You might ask "why dont you just decode() and then append all images",
+ // that's because I want to show image before it's fully loaded,
+ // as browser can render parts of image while it is loading.
+ // We do not do this in Safari due to partial loading bug.
+ if (supportsDecode && this.slide && (!this.slide.isActive || isSafari())) {
+ this.isDecoding = true; // purposefully using finally instead of then,
+ // as if srcset sizes changes dynamically - it may cause decode error
+
+ /** @type {HTMLImageElement} */
+
+ this.element.decode().catch(() => {}).finally(() => {
+ this.isDecoding = false;
+ this.appendImage();
+ });
+ } else {
+ this.appendImage();
+ }
+ } else if (this.slide && !this.element.parentNode) {
+ this.slide.container.appendChild(this.element);
+ }
+ }
+ /**
+ * Activate the slide,
+ * active slide is generally the current one,
+ * meaning the user can see it.
+ */
+
+
+ activate() {
+ if (this.instance.dispatch('contentActivate', {
+ content: this
+ }).defaultPrevented || !this.slide) {
+ return;
+ }
+
+ if (this.isImageContent() && this.isDecoding && !isSafari()) {
+ // add image to slide when it becomes active,
+ // even if it's not finished decoding
+ this.appendImage();
+ } else if (this.isError()) {
+ this.load(false, true); // try to reload
+ }
+
+ if (this.slide.holderElement) {
+ this.slide.holderElement.setAttribute('aria-hidden', 'false');
+ }
+ }
+ /**
+ * Deactivate the content
+ */
+
+
+ deactivate() {
+ this.instance.dispatch('contentDeactivate', {
+ content: this
+ });
+
+ if (this.slide && this.slide.holderElement) {
+ this.slide.holderElement.setAttribute('aria-hidden', 'true');
+ }
+ }
+ /**
+ * Remove the content from DOM
+ */
+
+
+ remove() {
+ this.isAttached = false;
+
+ if (this.instance.dispatch('contentRemove', {
+ content: this
+ }).defaultPrevented) {
+ return;
+ }
+
+ if (this.element && this.element.parentNode) {
+ this.element.remove();
+ }
+
+ if (this.placeholder && this.placeholder.element) {
+ this.placeholder.element.remove();
+ }
+ }
+ /**
+ * Append the image content to slide container
+ */
+
+
+ appendImage() {
+ if (!this.isAttached) {
+ return;
+ }
+
+ if (this.instance.dispatch('contentAppendImage', {
+ content: this
+ }).defaultPrevented) {
+ return;
+ } // ensure that element exists and is not already appended
+
+
+ if (this.slide && this.element && !this.element.parentNode) {
+ this.slide.container.appendChild(this.element);
+ }
+
+ if (this.state === LOAD_STATE.LOADED || this.state === LOAD_STATE.ERROR) {
+ this.removePlaceholder();
+ }
+ }
+
+}
+
+/** @typedef {import('./content.js').default} Content */
+
+/** @typedef {import('./slide.js').default} Slide */
+
+/** @typedef {import('./slide.js').SlideData} SlideData */
+
+/** @typedef {import('../core/base.js').default} PhotoSwipeBase */
+
+/** @typedef {import('../photoswipe.js').default} PhotoSwipe */
+
+const MIN_SLIDES_TO_CACHE = 5;
+/**
+ * Lazy-load an image
+ * This function is used both by Lightbox and PhotoSwipe core,
+ * thus it can be called before dialog is opened.
+ *
+ * @param {SlideData} itemData Data about the slide
+ * @param {PhotoSwipeBase} instance PhotoSwipe or PhotoSwipeLightbox instance
+ * @param {number} index
+ * @returns {Content} Image that is being decoded or false.
+ */
+
+function lazyLoadData(itemData, instance, index) {
+ const content = instance.createContentFromData(itemData, index);
+ /** @type {ZoomLevel | undefined} */
+
+ let zoomLevel;
+ const {
+ options
+ } = instance; // We need to know dimensions of the image to preload it,
+ // as it might use srcset, and we need to define sizes
+
+ if (options) {
+ zoomLevel = new ZoomLevel(options, itemData, -1);
+ let viewportSize;
+
+ if (instance.pswp) {
+ viewportSize = instance.pswp.viewportSize;
+ } else {
+ viewportSize = getViewportSize(options, instance);
+ }
+
+ const panAreaSize = getPanAreaSize(options, viewportSize, itemData, index);
+ zoomLevel.update(content.width, content.height, panAreaSize);
+ }
+
+ content.lazyLoad();
+
+ if (zoomLevel) {
+ content.setDisplayedSize(Math.ceil(content.width * zoomLevel.initial), Math.ceil(content.height * zoomLevel.initial));
+ }
+
+ return content;
+}
+/**
+ * Lazy-loads specific slide.
+ * This function is used both by Lightbox and PhotoSwipe core,
+ * thus it can be called before dialog is opened.
+ *
+ * By default, it loads image based on viewport size and initial zoom level.
+ *
+ * @param {number} index Slide index
+ * @param {PhotoSwipeBase} instance PhotoSwipe or PhotoSwipeLightbox eventable instance
+ * @returns {Content | undefined}
+ */
+
+function lazyLoadSlide(index, instance) {
+ const itemData = instance.getItemData(index);
+
+ if (instance.dispatch('lazyLoadSlide', {
+ index,
+ itemData
+ }).defaultPrevented) {
+ return;
+ }
+
+ return lazyLoadData(itemData, instance, index);
+}
+
+class ContentLoader {
+ /**
+ * @param {PhotoSwipe} pswp
+ */
+ constructor(pswp) {
+ this.pswp = pswp; // Total amount of cached images
+
+ this.limit = Math.max(pswp.options.preload[0] + pswp.options.preload[1] + 1, MIN_SLIDES_TO_CACHE);
+ /** @type {Content[]} */
+
+ this._cachedItems = [];
+ }
+ /**
+ * Lazy load nearby slides based on `preload` option.
+ *
+ * @param {number} [diff] Difference between slide indexes that was changed recently, or 0.
+ */
+
+
+ updateLazy(diff) {
+ const {
+ pswp
+ } = this;
+
+ if (pswp.dispatch('lazyLoad').defaultPrevented) {
+ return;
+ }
+
+ const {
+ preload
+ } = pswp.options;
+ const isForward = diff === undefined ? true : diff >= 0;
+ let i; // preload[1] - num items to preload in forward direction
+
+ for (i = 0; i <= preload[1]; i++) {
+ this.loadSlideByIndex(pswp.currIndex + (isForward ? i : -i));
+ } // preload[0] - num items to preload in backward direction
+
+
+ for (i = 1; i <= preload[0]; i++) {
+ this.loadSlideByIndex(pswp.currIndex + (isForward ? -i : i));
+ }
+ }
+ /**
+ * @param {number} initialIndex
+ */
+
+
+ loadSlideByIndex(initialIndex) {
+ const index = this.pswp.getLoopedIndex(initialIndex); // try to get cached content
+
+ let content = this.getContentByIndex(index);
+
+ if (!content) {
+ // no cached content, so try to load from scratch:
+ content = lazyLoadSlide(index, this.pswp); // if content can be loaded, add it to cache:
+
+ if (content) {
+ this.addToCache(content);
+ }
+ }
+ }
+ /**
+ * @param {Slide} slide
+ * @returns {Content}
+ */
+
+
+ getContentBySlide(slide) {
+ let content = this.getContentByIndex(slide.index);
+
+ if (!content) {
+ // create content if not found in cache
+ content = this.pswp.createContentFromData(slide.data, slide.index);
+ this.addToCache(content);
+ } // assign slide to content
+
+
+ content.setSlide(slide);
+ return content;
+ }
+ /**
+ * @param {Content} content
+ */
+
+
+ addToCache(content) {
+ // move to the end of array
+ this.removeByIndex(content.index);
+
+ this._cachedItems.push(content);
+
+ if (this._cachedItems.length > this.limit) {
+ // Destroy the first content that's not attached
+ const indexToRemove = this._cachedItems.findIndex(item => {
+ return !item.isAttached && !item.hasSlide;
+ });
+
+ if (indexToRemove !== -1) {
+ const removedItem = this._cachedItems.splice(indexToRemove, 1)[0];
+
+ removedItem.destroy();
+ }
+ }
+ }
+ /**
+ * Removes an image from cache, does not destroy() it, just removes.
+ *
+ * @param {number} index
+ */
+
+
+ removeByIndex(index) {
+ const indexToRemove = this._cachedItems.findIndex(item => item.index === index);
+
+ if (indexToRemove !== -1) {
+ this._cachedItems.splice(indexToRemove, 1);
+ }
+ }
+ /**
+ * @param {number} index
+ * @returns {Content | undefined}
+ */
+
+
+ getContentByIndex(index) {
+ return this._cachedItems.find(content => content.index === index);
+ }
+
+ destroy() {
+ this._cachedItems.forEach(content => content.destroy());
+
+ this._cachedItems = [];
+ }
+
+}
+
+/** @typedef {import("../photoswipe.js").default} PhotoSwipe */
+
+/** @typedef {import("../slide/slide.js").SlideData} SlideData */
+
+/**
+ * PhotoSwipe base class that can retrieve data about every slide.
+ * Shared by PhotoSwipe Core and PhotoSwipe Lightbox
+ */
+
+class PhotoSwipeBase extends Eventable {
+ /**
+ * Get total number of slides
+ *
+ * @returns {number}
+ */
+ getNumItems() {
+ var _this$options;
+
+ let numItems = 0;
+ const dataSource = (_this$options = this.options) === null || _this$options === void 0 ? void 0 : _this$options.dataSource;
+
+ if (dataSource && 'length' in dataSource) {
+ // may be an array or just object with length property
+ numItems = dataSource.length;
+ } else if (dataSource && 'gallery' in dataSource) {
+ // query DOM elements
+ if (!dataSource.items) {
+ dataSource.items = this._getGalleryDOMElements(dataSource.gallery);
+ }
+
+ if (dataSource.items) {
+ numItems = dataSource.items.length;
+ }
+ } // legacy event, before filters were introduced
+
+
+ const event = this.dispatch('numItems', {
+ dataSource,
+ numItems
+ });
+ return this.applyFilters('numItems', event.numItems, dataSource);
+ }
+ /**
+ * @param {SlideData} slideData
+ * @param {number} index
+ * @returns {Content}
+ */
+
+
+ createContentFromData(slideData, index) {
+ return new Content(slideData, this, index);
+ }
+ /**
+ * Get item data by index.
+ *
+ * "item data" should contain normalized information that PhotoSwipe needs to generate a slide.
+ * For example, it may contain properties like
+ * `src`, `srcset`, `w`, `h`, which will be used to generate a slide with image.
+ *
+ * @param {number} index
+ * @returns {SlideData}
+ */
+
+
+ getItemData(index) {
+ var _this$options2;
+
+ const dataSource = (_this$options2 = this.options) === null || _this$options2 === void 0 ? void 0 : _this$options2.dataSource;
+ /** @type {SlideData | HTMLElement} */
+
+ let dataSourceItem = {};
+
+ if (Array.isArray(dataSource)) {
+ // Datasource is an array of elements
+ dataSourceItem = dataSource[index];
+ } else if (dataSource && 'gallery' in dataSource) {
+ // dataSource has gallery property,
+ // thus it was created by Lightbox, based on
+ // gallery and children options
+ // query DOM elements
+ if (!dataSource.items) {
+ dataSource.items = this._getGalleryDOMElements(dataSource.gallery);
+ }
+
+ dataSourceItem = dataSource.items[index];
+ }
+
+ let itemData = dataSourceItem;
+
+ if (itemData instanceof Element) {
+ itemData = this._domElementToItemData(itemData);
+ } // Dispatching the itemData event,
+ // it's a legacy verion before filters were introduced
+
+
+ const event = this.dispatch('itemData', {
+ itemData: itemData || {},
+ index
+ });
+ return this.applyFilters('itemData', event.itemData, index);
+ }
+ /**
+ * Get array of gallery DOM elements,
+ * based on childSelector and gallery element.
+ *
+ * @param {HTMLElement} galleryElement
+ * @returns {HTMLElement[]}
+ */
+
+
+ _getGalleryDOMElements(galleryElement) {
+ var _this$options3, _this$options4;
+
+ if ((_this$options3 = this.options) !== null && _this$options3 !== void 0 && _this$options3.children || (_this$options4 = this.options) !== null && _this$options4 !== void 0 && _this$options4.childSelector) {
+ return getElementsFromOption(this.options.children, this.options.childSelector, galleryElement) || [];
+ }
+
+ return [galleryElement];
+ }
+ /**
+ * Converts DOM element to item data object.
+ *
+ * @param {HTMLElement} element DOM element
+ * @returns {SlideData}
+ */
+
+
+ _domElementToItemData(element) {
+ /** @type {SlideData} */
+ const itemData = {
+ element
+ };
+ const linkEl =
+ /** @type {HTMLAnchorElement} */
+ element.tagName === 'A' ? element : element.querySelector('a');
+
+ if (linkEl) {
+ // src comes from data-pswp-src attribute,
+ // if it's empty link href is used
+ itemData.src = linkEl.dataset.pswpSrc || linkEl.href;
+
+ if (linkEl.dataset.pswpSrcset) {
+ itemData.srcset = linkEl.dataset.pswpSrcset;
+ }
+
+ itemData.width = linkEl.dataset.pswpWidth ? parseInt(linkEl.dataset.pswpWidth, 10) : 0;
+ itemData.height = linkEl.dataset.pswpHeight ? parseInt(linkEl.dataset.pswpHeight, 10) : 0; // support legacy w & h properties
+
+ itemData.w = itemData.width;
+ itemData.h = itemData.height;
+
+ if (linkEl.dataset.pswpType) {
+ itemData.type = linkEl.dataset.pswpType;
+ }
+
+ const thumbnailEl = element.querySelector('img');
+
+ if (thumbnailEl) {
+ var _thumbnailEl$getAttri;
+
+ // msrc is URL to placeholder image that's displayed before large image is loaded
+ // by default it's displayed only for the first slide
+ itemData.msrc = thumbnailEl.currentSrc || thumbnailEl.src;
+ itemData.alt = (_thumbnailEl$getAttri = thumbnailEl.getAttribute('alt')) !== null && _thumbnailEl$getAttri !== void 0 ? _thumbnailEl$getAttri : '';
+ }
+
+ if (linkEl.dataset.pswpCropped || linkEl.dataset.cropped) {
+ itemData.thumbCropped = true;
+ }
+ }
+
+ return this.applyFilters('domItemData', itemData, element, linkEl);
+ }
+ /**
+ * Lazy-load by slide data
+ *
+ * @param {SlideData} itemData Data about the slide
+ * @param {number} index
+ * @returns {Content} Image that is being decoded or false.
+ */
+
+
+ lazyLoadData(itemData, index) {
+ return lazyLoadData(itemData, this, index);
+ }
+
+}
+
+/** @typedef {import('./photoswipe.js').default} PhotoSwipe */
+
+/** @typedef {import('./slide/get-thumb-bounds.js').Bounds} Bounds */
+
+/** @typedef {import('./util/animations.js').AnimationProps} AnimationProps */
+// some browsers do not paint
+// elements which opacity is set to 0,
+// since we need to pre-render elements for the animation -
+// we set it to the minimum amount
+
+const MIN_OPACITY = 0.003;
+/**
+ * Manages opening and closing transitions of the PhotoSwipe.
+ *
+ * It can perform zoom, fade or no transition.
+ */
+
+class Opener {
+ /**
+ * @param {PhotoSwipe} pswp
+ */
+ constructor(pswp) {
+ this.pswp = pswp;
+ this.isClosed = true;
+ this.isOpen = false;
+ this.isClosing = false;
+ this.isOpening = false;
+ /**
+ * @private
+ * @type {number | false | undefined}
+ */
+
+ this._duration = undefined;
+ /** @private */
+
+ this._useAnimation = false;
+ /** @private */
+
+ this._croppedZoom = false;
+ /** @private */
+
+ this._animateRootOpacity = false;
+ /** @private */
+
+ this._animateBgOpacity = false;
+ /**
+ * @private
+ * @type { HTMLDivElement | HTMLImageElement | null | undefined }
+ */
+
+ this._placeholder = undefined;
+ /**
+ * @private
+ * @type { HTMLDivElement | undefined }
+ */
+
+ this._opacityElement = undefined;
+ /**
+ * @private
+ * @type { HTMLDivElement | undefined }
+ */
+
+ this._cropContainer1 = undefined;
+ /**
+ * @private
+ * @type { HTMLElement | null | undefined }
+ */
+
+ this._cropContainer2 = undefined;
+ /**
+ * @private
+ * @type {Bounds | undefined}
+ */
+
+ this._thumbBounds = undefined;
+ this._prepareOpen = this._prepareOpen.bind(this); // Override initial zoom and pan position
+
+ pswp.on('firstZoomPan', this._prepareOpen);
+ }
+
+ open() {
+ this._prepareOpen();
+
+ this._start();
+ }
+
+ close() {
+ if (this.isClosed || this.isClosing || this.isOpening) {
+ // if we close during opening animation
+ // for now do nothing,
+ // browsers aren't good at changing the direction of the CSS transition
+ return;
+ }
+
+ const slide = this.pswp.currSlide;
+ this.isOpen = false;
+ this.isOpening = false;
+ this.isClosing = true;
+ this._duration = this.pswp.options.hideAnimationDuration;
+
+ if (slide && slide.currZoomLevel * slide.width >= this.pswp.options.maxWidthToAnimate) {
+ this._duration = 0;
+ }
+
+ this._applyStartProps();
+
+ setTimeout(() => {
+ this._start();
+ }, this._croppedZoom ? 30 : 0);
+ }
+ /** @private */
+
+
+ _prepareOpen() {
+ this.pswp.off('firstZoomPan', this._prepareOpen);
+
+ if (!this.isOpening) {
+ const slide = this.pswp.currSlide;
+ this.isOpening = true;
+ this.isClosing = false;
+ this._duration = this.pswp.options.showAnimationDuration;
+
+ if (slide && slide.zoomLevels.initial * slide.width >= this.pswp.options.maxWidthToAnimate) {
+ this._duration = 0;
+ }
+
+ this._applyStartProps();
+ }
+ }
+ /** @private */
+
+
+ _applyStartProps() {
+ const {
+ pswp
+ } = this;
+ const slide = this.pswp.currSlide;
+ const {
+ options
+ } = pswp;
+
+ if (options.showHideAnimationType === 'fade') {
+ options.showHideOpacity = true;
+ this._thumbBounds = undefined;
+ } else if (options.showHideAnimationType === 'none') {
+ options.showHideOpacity = false;
+ this._duration = 0;
+ this._thumbBounds = undefined;
+ } else if (this.isOpening && pswp._initialThumbBounds) {
+ // Use initial bounds if defined
+ this._thumbBounds = pswp._initialThumbBounds;
+ } else {
+ this._thumbBounds = this.pswp.getThumbBounds();
+ }
+
+ this._placeholder = slide === null || slide === void 0 ? void 0 : slide.getPlaceholderElement();
+ pswp.animations.stopAll(); // Discard animations when duration is less than 50ms
+
+ this._useAnimation = Boolean(this._duration && this._duration > 50);
+ this._animateZoom = Boolean(this._thumbBounds) && (slide === null || slide === void 0 ? void 0 : slide.content.usePlaceholder()) && (!this.isClosing || !pswp.mainScroll.isShifted());
+
+ if (!this._animateZoom) {
+ this._animateRootOpacity = true;
+
+ if (this.isOpening && slide) {
+ slide.zoomAndPanToInitial();
+ slide.applyCurrentZoomPan();
+ }
+ } else {
+ var _options$showHideOpac;
+
+ this._animateRootOpacity = (_options$showHideOpac = options.showHideOpacity) !== null && _options$showHideOpac !== void 0 ? _options$showHideOpac : false;
+ }
+
+ this._animateBgOpacity = !this._animateRootOpacity && this.pswp.options.bgOpacity > MIN_OPACITY;
+ this._opacityElement = this._animateRootOpacity ? pswp.element : pswp.bg;
+
+ if (!this._useAnimation) {
+ this._duration = 0;
+ this._animateZoom = false;
+ this._animateBgOpacity = false;
+ this._animateRootOpacity = true;
+
+ if (this.isOpening) {
+ if (pswp.element) {
+ pswp.element.style.opacity = String(MIN_OPACITY);
+ }
+
+ pswp.applyBgOpacity(1);
+ }
+
+ return;
+ }
+
+ if (this._animateZoom && this._thumbBounds && this._thumbBounds.innerRect) {
+ var _this$pswp$currSlide;
+
+ // Properties are used when animation from cropped thumbnail
+ this._croppedZoom = true;
+ this._cropContainer1 = this.pswp.container;
+ this._cropContainer2 = (_this$pswp$currSlide = this.pswp.currSlide) === null || _this$pswp$currSlide === void 0 ? void 0 : _this$pswp$currSlide.holderElement;
+
+ if (pswp.container) {
+ pswp.container.style.overflow = 'hidden';
+ pswp.container.style.width = pswp.viewportSize.x + 'px';
+ }
+ } else {
+ this._croppedZoom = false;
+ }
+
+ if (this.isOpening) {
+ // Apply styles before opening transition
+ if (this._animateRootOpacity) {
+ if (pswp.element) {
+ pswp.element.style.opacity = String(MIN_OPACITY);
+ }
+
+ pswp.applyBgOpacity(1);
+ } else {
+ if (this._animateBgOpacity && pswp.bg) {
+ pswp.bg.style.opacity = String(MIN_OPACITY);
+ }
+
+ if (pswp.element) {
+ pswp.element.style.opacity = '1';
+ }
+ }
+
+ if (this._animateZoom) {
+ this._setClosedStateZoomPan();
+
+ if (this._placeholder) {
+ // tell browser that we plan to animate the placeholder
+ this._placeholder.style.willChange = 'transform'; // hide placeholder to allow hiding of
+ // elements that overlap it (such as icons over the thumbnail)
+
+ this._placeholder.style.opacity = String(MIN_OPACITY);
+ }
+ }
+ } else if (this.isClosing) {
+ // hide nearby slides to make sure that
+ // they are not painted during the transition
+ if (pswp.mainScroll.itemHolders[0]) {
+ pswp.mainScroll.itemHolders[0].el.style.display = 'none';
+ }
+
+ if (pswp.mainScroll.itemHolders[2]) {
+ pswp.mainScroll.itemHolders[2].el.style.display = 'none';
+ }
+
+ if (this._croppedZoom) {
+ if (pswp.mainScroll.x !== 0) {
+ // shift the main scroller to zero position
+ pswp.mainScroll.resetPosition();
+ pswp.mainScroll.resize();
+ }
+ }
+ }
+ }
+ /** @private */
+
+
+ _start() {
+ if (this.isOpening && this._useAnimation && this._placeholder && this._placeholder.tagName === 'IMG') {
+ // To ensure smooth animation
+ // we wait till the current slide image placeholder is decoded,
+ // but no longer than 250ms,
+ // and no shorter than 50ms
+ // (just using requestanimationframe is not enough in Firefox,
+ // for some reason)
+ new Promise(resolve => {
+ let decoded = false;
+ let isDelaying = true;
+ decodeImage(
+ /** @type {HTMLImageElement} */
+ this._placeholder).finally(() => {
+ decoded = true;
+
+ if (!isDelaying) {
+ resolve(true);
+ }
+ });
+ setTimeout(() => {
+ isDelaying = false;
+
+ if (decoded) {
+ resolve(true);
+ }
+ }, 50);
+ setTimeout(resolve, 250);
+ }).finally(() => this._initiate());
+ } else {
+ this._initiate();
+ }
+ }
+ /** @private */
+
+
+ _initiate() {
+ var _this$pswp$element, _this$pswp$element2;
+
+ (_this$pswp$element = this.pswp.element) === null || _this$pswp$element === void 0 || _this$pswp$element.style.setProperty('--pswp-transition-duration', this._duration + 'ms');
+ this.pswp.dispatch(this.isOpening ? 'openingAnimationStart' : 'closingAnimationStart'); // legacy event
+
+ this.pswp.dispatch(
+ /** @type {'initialZoomIn' | 'initialZoomOut'} */
+ 'initialZoom' + (this.isOpening ? 'In' : 'Out'));
+ (_this$pswp$element2 = this.pswp.element) === null || _this$pswp$element2 === void 0 || _this$pswp$element2.classList.toggle('pswp--ui-visible', this.isOpening);
+
+ if (this.isOpening) {
+ if (this._placeholder) {
+ // unhide the placeholder
+ this._placeholder.style.opacity = '1';
+ }
+
+ this._animateToOpenState();
+ } else if (this.isClosing) {
+ this._animateToClosedState();
+ }
+
+ if (!this._useAnimation) {
+ this._onAnimationComplete();
+ }
+ }
+ /** @private */
+
+
+ _onAnimationComplete() {
+ const {
+ pswp
+ } = this;
+ this.isOpen = this.isOpening;
+ this.isClosed = this.isClosing;
+ this.isOpening = false;
+ this.isClosing = false;
+ pswp.dispatch(this.isOpen ? 'openingAnimationEnd' : 'closingAnimationEnd'); // legacy event
+
+ pswp.dispatch(
+ /** @type {'initialZoomInEnd' | 'initialZoomOutEnd'} */
+ 'initialZoom' + (this.isOpen ? 'InEnd' : 'OutEnd'));
+
+ if (this.isClosed) {
+ pswp.destroy();
+ } else if (this.isOpen) {
+ var _pswp$currSlide;
+
+ if (this._animateZoom && pswp.container) {
+ pswp.container.style.overflow = 'visible';
+ pswp.container.style.width = '100%';
+ }
+
+ (_pswp$currSlide = pswp.currSlide) === null || _pswp$currSlide === void 0 || _pswp$currSlide.applyCurrentZoomPan();
+ }
+ }
+ /** @private */
+
+
+ _animateToOpenState() {
+ const {
+ pswp
+ } = this;
+
+ if (this._animateZoom) {
+ if (this._croppedZoom && this._cropContainer1 && this._cropContainer2) {
+ this._animateTo(this._cropContainer1, 'transform', 'translate3d(0,0,0)');
+
+ this._animateTo(this._cropContainer2, 'transform', 'none');
+ }
+
+ if (pswp.currSlide) {
+ pswp.currSlide.zoomAndPanToInitial();
+
+ this._animateTo(pswp.currSlide.container, 'transform', pswp.currSlide.getCurrentTransform());
+ }
+ }
+
+ if (this._animateBgOpacity && pswp.bg) {
+ this._animateTo(pswp.bg, 'opacity', String(pswp.options.bgOpacity));
+ }
+
+ if (this._animateRootOpacity && pswp.element) {
+ this._animateTo(pswp.element, 'opacity', '1');
+ }
+ }
+ /** @private */
+
+
+ _animateToClosedState() {
+ const {
+ pswp
+ } = this;
+
+ if (this._animateZoom) {
+ this._setClosedStateZoomPan(true);
+ } // do not animate opacity if it's already at 0
+
+
+ if (this._animateBgOpacity && pswp.bgOpacity > 0.01 && pswp.bg) {
+ this._animateTo(pswp.bg, 'opacity', '0');
+ }
+
+ if (this._animateRootOpacity && pswp.element) {
+ this._animateTo(pswp.element, 'opacity', '0');
+ }
+ }
+ /**
+ * @private
+ * @param {boolean} [animate]
+ */
+
+
+ _setClosedStateZoomPan(animate) {
+ if (!this._thumbBounds) return;
+ const {
+ pswp
+ } = this;
+ const {
+ innerRect
+ } = this._thumbBounds;
+ const {
+ currSlide,
+ viewportSize
+ } = pswp;
+
+ if (this._croppedZoom && innerRect && this._cropContainer1 && this._cropContainer2) {
+ const containerOnePanX = -viewportSize.x + (this._thumbBounds.x - innerRect.x) + innerRect.w;
+ const containerOnePanY = -viewportSize.y + (this._thumbBounds.y - innerRect.y) + innerRect.h;
+ const containerTwoPanX = viewportSize.x - innerRect.w;
+ const containerTwoPanY = viewportSize.y - innerRect.h;
+
+ if (animate) {
+ this._animateTo(this._cropContainer1, 'transform', toTransformString(containerOnePanX, containerOnePanY));
+
+ this._animateTo(this._cropContainer2, 'transform', toTransformString(containerTwoPanX, containerTwoPanY));
+ } else {
+ setTransform(this._cropContainer1, containerOnePanX, containerOnePanY);
+ setTransform(this._cropContainer2, containerTwoPanX, containerTwoPanY);
+ }
+ }
+
+ if (currSlide) {
+ equalizePoints(currSlide.pan, innerRect || this._thumbBounds);
+ currSlide.currZoomLevel = this._thumbBounds.w / currSlide.width;
+
+ if (animate) {
+ this._animateTo(currSlide.container, 'transform', currSlide.getCurrentTransform());
+ } else {
+ currSlide.applyCurrentZoomPan();
+ }
+ }
+ }
+ /**
+ * @private
+ * @param {HTMLElement} target
+ * @param {'transform' | 'opacity'} prop
+ * @param {string} propValue
+ */
+
+
+ _animateTo(target, prop, propValue) {
+ if (!this._duration) {
+ target.style[prop] = propValue;
+ return;
+ }
+
+ const {
+ animations
+ } = this.pswp;
+ /** @type {AnimationProps} */
+
+ const animProps = {
+ duration: this._duration,
+ easing: this.pswp.options.easing,
+ onComplete: () => {
+ if (!animations.activeAnimations.length) {
+ this._onAnimationComplete();
+ }
+ },
+ target
+ };
+ animProps[prop] = propValue;
+ animations.startTransition(animProps);
+ }
+
+}
+
+/**
+ * @template T
+ * @typedef {import('./types.js').Type} Type
+ */
+
+/** @typedef {import('./slide/slide.js').SlideData} SlideData */
+
+/** @typedef {import('./slide/zoom-level.js').ZoomLevelOption} ZoomLevelOption */
+
+/** @typedef {import('./ui/ui-element.js').UIElementData} UIElementData */
+
+/** @typedef {import('./main-scroll.js').ItemHolder} ItemHolder */
+
+/** @typedef {import('./core/eventable.js').PhotoSwipeEventsMap} PhotoSwipeEventsMap */
+
+/** @typedef {import('./core/eventable.js').PhotoSwipeFiltersMap} PhotoSwipeFiltersMap */
+
+/** @typedef {import('./slide/get-thumb-bounds').Bounds} Bounds */
+
+/**
+ * @template {keyof PhotoSwipeEventsMap} T
+ * @typedef {import('./core/eventable.js').EventCallback} EventCallback
+ */
+
+/**
+ * @template {keyof PhotoSwipeEventsMap} T
+ * @typedef {import('./core/eventable.js').AugmentedEvent} AugmentedEvent
+ */
+
+/** @typedef {{ x: number; y: number; id?: string | number }} Point */
+
+/** @typedef {{ top: number; bottom: number; left: number; right: number }} Padding */
+
+/** @typedef {SlideData[]} DataSourceArray */
+
+/** @typedef {{ gallery: HTMLElement; items?: HTMLElement[] }} DataSourceObject */
+
+/** @typedef {DataSourceArray | DataSourceObject} DataSource */
+
+/** @typedef {(point: Point, originalEvent: PointerEvent) => void} ActionFn */
+
+/** @typedef {'close' | 'next' | 'zoom' | 'zoom-or-close' | 'toggle-controls'} ActionType */
+
+/** @typedef {Type | { default: Type }} PhotoSwipeModule */
+
+/** @typedef {PhotoSwipeModule | Promise | (() => Promise)} PhotoSwipeModuleOption */
+
+/**
+ * @typedef {string | NodeListOf | HTMLElement[] | HTMLElement} ElementProvider
+ */
+
+/** @typedef {Partial} PhotoSwipeOptions https://photoswipe.com/options/ */
+
+/**
+ * @typedef {Object} PreparedPhotoSwipeOptions
+ *
+ * @prop {DataSource} [dataSource]
+ * Pass an array of any items via dataSource option. Its length will determine amount of slides
+ * (which may be modified further from numItems event).
+ *
+ * Each item should contain data that you need to generate slide
+ * (for image slide it would be src (image URL), width (image width), height, srcset, alt).
+ *
+ * If these properties are not present in your initial array, you may "pre-parse" each item from itemData filter.
+ *
+ * @prop {number} bgOpacity
+ * Background backdrop opacity, always define it via this option and not via CSS rgba color.
+ *
+ * @prop {number} spacing
+ * Spacing between slides. Defined as ratio relative to the viewport width (0.1 = 10% of viewport).
+ *
+ * @prop {boolean} allowPanToNext
+ * Allow swipe navigation to the next slide when the current slide is zoomed. Does not apply to mouse events.
+ *
+ * @prop {boolean} loop
+ * If set to true you'll be able to swipe from the last to the first image.
+ * Option is always false when there are less than 3 slides.
+ *
+ * @prop {boolean} [wheelToZoom]
+ * By default PhotoSwipe zooms image with ctrl-wheel, if you enable this option - image will zoom just via wheel.
+ *
+ * @prop {boolean} pinchToClose
+ * Pinch touch gesture to close the gallery.
+ *
+ * @prop {boolean} closeOnVerticalDrag
+ * Vertical drag gesture to close the PhotoSwipe.
+ *
+ * @prop {Padding} [padding]
+ * Slide area padding (in pixels).
+ *
+ * @prop {(viewportSize: Point, itemData: SlideData, index: number) => Padding} [paddingFn]
+ * The option is checked frequently, so make sure it's performant. Overrides padding option if defined. For example:
+ *
+ * @prop {number | false} hideAnimationDuration
+ * Transition duration in milliseconds, can be 0.
+ *
+ * @prop {number | false} showAnimationDuration
+ * Transition duration in milliseconds, can be 0.
+ *
+ * @prop {number | false} zoomAnimationDuration
+ * Transition duration in milliseconds, can be 0.
+ *
+ * @prop {string} easing
+ * String, 'cubic-bezier(.4,0,.22,1)'. CSS easing function for open/close/zoom transitions.
+ *
+ * @prop {boolean} escKey
+ * Esc key to close.
+ *
+ * @prop {boolean} arrowKeys
+ * Left/right arrow keys for navigation.
+ *
+ * @prop {boolean} trapFocus
+ * Trap focus within PhotoSwipe element while it's open.
+ *
+ * @prop {boolean} returnFocus
+ * Restore focus the last active element after PhotoSwipe is closed.
+ *
+ * @prop {boolean} clickToCloseNonZoomable
+ * If image is not zoomable (for example, smaller than viewport) it can be closed by clicking on it.
+ *
+ * @prop {ActionType | ActionFn | false} imageClickAction
+ * Refer to click and tap actions page.
+ *
+ * @prop {ActionType | ActionFn | false} bgClickAction
+ * Refer to click and tap actions page.
+ *
+ * @prop {ActionType | ActionFn | false} tapAction
+ * Refer to click and tap actions page.
+ *
+ * @prop {ActionType | ActionFn | false} doubleTapAction
+ * Refer to click and tap actions page.
+ *
+ * @prop {number} preloaderDelay
+ * Delay before the loading indicator will be displayed,
+ * if image is loaded during it - the indicator will not be displayed at all. Can be zero.
+ *
+ * @prop {string} indexIndicatorSep
+ * Used for slide count indicator ("1 of 10 ").
+ *
+ * @prop {(options: PhotoSwipeOptions, pswp: PhotoSwipeBase) => Point} [getViewportSizeFn]
+ * A function that should return slide viewport width and height, in format {x: 100, y: 100}.
+ *
+ * @prop {string} errorMsg
+ * Message to display when the image wasn't able to load. If you need to display HTML - use contentErrorElement filter.
+ *
+ * @prop {[number, number]} preload
+ * Lazy loading of nearby slides based on direction of movement. Should be an array with two integers,
+ * first one - number of items to preload before the current image, second one - after the current image.
+ * Two nearby images are always loaded.
+ *
+ * @prop {string} [mainClass]
+ * Class that will be added to the root element of PhotoSwipe, may contain multiple separated by space.
+ * Example on Styling page.
+ *
+ * @prop {HTMLElement} [appendToEl]
+ * Element to which PhotoSwipe dialog will be appended when it opens.
+ *
+ * @prop {number} maxWidthToAnimate
+ * Maximum width of image to animate, if initial rendered image width
+ * is larger than this value - the opening/closing transition will be automatically disabled.
+ *
+ * @prop {string} [closeTitle]
+ * Translating
+ *
+ * @prop {string} [zoomTitle]
+ * Translating
+ *
+ * @prop {string} [arrowPrevTitle]
+ * Translating
+ *
+ * @prop {string} [arrowNextTitle]
+ * Translating
+ *
+ * @prop {'zoom' | 'fade' | 'none'} [showHideAnimationType]
+ * To adjust opening or closing transition type use lightbox option `showHideAnimationType` (`String`).
+ * It supports three values - `zoom` (default), `fade` (default if there is no thumbnail) and `none`.
+ *
+ * Animations are automatically disabled if user `(prefers-reduced-motion: reduce)`.
+ *
+ * @prop {number} index
+ * Defines start slide index.
+ *
+ * @prop {(e: MouseEvent) => number} [getClickedIndexFn]
+ *
+ * @prop {boolean} [arrowPrev]
+ * @prop {boolean} [arrowNext]
+ * @prop {boolean} [zoom]
+ * @prop {boolean} [close]
+ * @prop {boolean} [counter]
+ *
+ * @prop {string} [arrowPrevSVG]
+ * @prop {string} [arrowNextSVG]
+ * @prop {string} [zoomSVG]
+ * @prop {string} [closeSVG]
+ * @prop {string} [counterSVG]
+ *
+ * @prop {string} [arrowPrevTitle]
+ * @prop {string} [arrowNextTitle]
+ * @prop {string} [zoomTitle]
+ * @prop {string} [closeTitle]
+ * @prop {string} [counterTitle]
+ *
+ * @prop {ZoomLevelOption} [initialZoomLevel]
+ * @prop {ZoomLevelOption} [secondaryZoomLevel]
+ * @prop {ZoomLevelOption} [maxZoomLevel]
+ *
+ * @prop {boolean} [mouseMovePan]
+ * @prop {Point | null} [initialPointerPos]
+ * @prop {boolean} [showHideOpacity]
+ *
+ * @prop {PhotoSwipeModuleOption} [pswpModule]
+ * @prop {() => Promise} [openPromise]
+ * @prop {boolean} [preloadFirstSlide]
+ * @prop {ElementProvider} [gallery]
+ * @prop {string} [gallerySelector]
+ * @prop {ElementProvider} [children]
+ * @prop {string} [childSelector]
+ * @prop {string | false} [thumbSelector]
+ */
+
+/** @type {PreparedPhotoSwipeOptions} */
+
+const defaultOptions = {
+ allowPanToNext: true,
+ spacing: 0.1,
+ loop: true,
+ pinchToClose: true,
+ closeOnVerticalDrag: true,
+ hideAnimationDuration: 333,
+ showAnimationDuration: 333,
+ zoomAnimationDuration: 333,
+ escKey: true,
+ arrowKeys: true,
+ trapFocus: true,
+ returnFocus: true,
+ maxWidthToAnimate: 4000,
+ clickToCloseNonZoomable: true,
+ imageClickAction: 'zoom-or-close',
+ bgClickAction: 'close',
+ tapAction: 'toggle-controls',
+ doubleTapAction: 'zoom',
+ indexIndicatorSep: ' / ',
+ preloaderDelay: 2000,
+ bgOpacity: 0.8,
+ index: 0,
+ errorMsg: 'The image cannot be loaded',
+ preload: [1, 2],
+ easing: 'cubic-bezier(.4,0,.22,1)'
+};
+/**
+ * PhotoSwipe Core
+ */
+
+class PhotoSwipe extends PhotoSwipeBase {
+ /**
+ * @param {PhotoSwipeOptions} [options]
+ */
+ constructor(options) {
+ super();
+ this.options = this._prepareOptions(options || {});
+ /**
+ * offset of viewport relative to document
+ *
+ * @type {Point}
+ */
+
+ this.offset = {
+ x: 0,
+ y: 0
+ };
+ /**
+ * @type {Point}
+ * @private
+ */
+
+ this._prevViewportSize = {
+ x: 0,
+ y: 0
+ };
+ /**
+ * Size of scrollable PhotoSwipe viewport
+ *
+ * @type {Point}
+ */
+
+ this.viewportSize = {
+ x: 0,
+ y: 0
+ };
+ /**
+ * background (backdrop) opacity
+ */
+
+ this.bgOpacity = 1;
+ this.currIndex = 0;
+ this.potentialIndex = 0;
+ this.isOpen = false;
+ this.isDestroying = false;
+ this.hasMouse = false;
+ /**
+ * @private
+ * @type {SlideData}
+ */
+
+ this._initialItemData = {};
+ /** @type {Bounds | undefined} */
+
+ this._initialThumbBounds = undefined;
+ /** @type {HTMLDivElement | undefined} */
+
+ this.topBar = undefined;
+ /** @type {HTMLDivElement | undefined} */
+
+ this.element = undefined;
+ /** @type {HTMLDivElement | undefined} */
+
+ this.template = undefined;
+ /** @type {HTMLDivElement | undefined} */
+
+ this.container = undefined;
+ /** @type {HTMLElement | undefined} */
+
+ this.scrollWrap = undefined;
+ /** @type {Slide | undefined} */
+
+ this.currSlide = undefined;
+ this.events = new DOMEvents();
+ this.animations = new Animations();
+ this.mainScroll = new MainScroll(this);
+ this.gestures = new Gestures(this);
+ this.opener = new Opener(this);
+ this.keyboard = new Keyboard(this);
+ this.contentLoader = new ContentLoader(this);
+ }
+ /** @returns {boolean} */
+
+
+ init() {
+ if (this.isOpen || this.isDestroying) {
+ return false;
+ }
+
+ this.isOpen = true;
+ this.dispatch('init'); // legacy
+
+ this.dispatch('beforeOpen');
+
+ this._createMainStructure(); // add classes to the root element of PhotoSwipe
+
+
+ let rootClasses = 'pswp--open';
+
+ if (this.gestures.supportsTouch) {
+ rootClasses += ' pswp--touch';
+ }
+
+ if (this.options.mainClass) {
+ rootClasses += ' ' + this.options.mainClass;
+ }
+
+ if (this.element) {
+ this.element.className += ' ' + rootClasses;
+ }
+
+ this.currIndex = this.options.index || 0;
+ this.potentialIndex = this.currIndex;
+ this.dispatch('firstUpdate'); // starting index can be modified here
+ // initialize scroll wheel handler to block the scroll
+
+ this.scrollWheel = new ScrollWheel(this); // sanitize index
+
+ if (Number.isNaN(this.currIndex) || this.currIndex < 0 || this.currIndex >= this.getNumItems()) {
+ this.currIndex = 0;
+ }
+
+ if (!this.gestures.supportsTouch) {
+ // enable mouse features if no touch support detected
+ this.mouseDetected();
+ } // causes forced synchronous layout
+
+
+ this.updateSize();
+ this.offset.y = window.pageYOffset;
+ this._initialItemData = this.getItemData(this.currIndex);
+ this.dispatch('gettingData', {
+ index: this.currIndex,
+ data: this._initialItemData,
+ slide: undefined
+ }); // *Layout* - calculate size and position of elements here
+
+ this._initialThumbBounds = this.getThumbBounds();
+ this.dispatch('initialLayout');
+ this.on('openingAnimationEnd', () => {
+ const {
+ itemHolders
+ } = this.mainScroll; // Add content to the previous and next slide
+
+ if (itemHolders[0]) {
+ itemHolders[0].el.style.display = 'block';
+ this.setContent(itemHolders[0], this.currIndex - 1);
+ }
+
+ if (itemHolders[2]) {
+ itemHolders[2].el.style.display = 'block';
+ this.setContent(itemHolders[2], this.currIndex + 1);
+ }
+
+ this.appendHeavy();
+ this.contentLoader.updateLazy();
+ this.events.add(window, 'resize', this._handlePageResize.bind(this));
+ this.events.add(window, 'scroll', this._updatePageScrollOffset.bind(this));
+ this.dispatch('bindEvents');
+ }); // set content for center slide (first time)
+
+ if (this.mainScroll.itemHolders[1]) {
+ this.setContent(this.mainScroll.itemHolders[1], this.currIndex);
+ }
+
+ this.dispatch('change');
+ this.opener.open();
+ this.dispatch('afterInit');
+ return true;
+ }
+ /**
+ * Get looped slide index
+ * (for example, -1 will return the last slide)
+ *
+ * @param {number} index
+ * @returns {number}
+ */
+
+
+ getLoopedIndex(index) {
+ const numSlides = this.getNumItems();
+
+ if (this.options.loop) {
+ if (index > numSlides - 1) {
+ index -= numSlides;
+ }
+
+ if (index < 0) {
+ index += numSlides;
+ }
+ }
+
+ return clamp(index, 0, numSlides - 1);
+ }
+
+ appendHeavy() {
+ this.mainScroll.itemHolders.forEach(itemHolder => {
+ var _itemHolder$slide;
+
+ (_itemHolder$slide = itemHolder.slide) === null || _itemHolder$slide === void 0 || _itemHolder$slide.appendHeavy();
+ });
+ }
+ /**
+ * Change the slide
+ * @param {number} index New index
+ */
+
+
+ goTo(index) {
+ this.mainScroll.moveIndexBy(this.getLoopedIndex(index) - this.potentialIndex);
+ }
+ /**
+ * Go to the next slide.
+ */
+
+
+ next() {
+ this.goTo(this.potentialIndex + 1);
+ }
+ /**
+ * Go to the previous slide.
+ */
+
+
+ prev() {
+ this.goTo(this.potentialIndex - 1);
+ }
+ /**
+ * @see slide/slide.js zoomTo
+ *
+ * @param {Parameters} args
+ */
+
+
+ zoomTo(...args) {
+ var _this$currSlide;
+
+ (_this$currSlide = this.currSlide) === null || _this$currSlide === void 0 || _this$currSlide.zoomTo(...args);
+ }
+ /**
+ * @see slide/slide.js toggleZoom
+ */
+
+
+ toggleZoom() {
+ var _this$currSlide2;
+
+ (_this$currSlide2 = this.currSlide) === null || _this$currSlide2 === void 0 || _this$currSlide2.toggleZoom();
+ }
+ /**
+ * Close the gallery.
+ * After closing transition ends - destroy it
+ */
+
+
+ close() {
+ if (!this.opener.isOpen || this.isDestroying) {
+ return;
+ }
+
+ this.isDestroying = true;
+ this.dispatch('close');
+ this.events.removeAll();
+ this.opener.close();
+ }
+ /**
+ * Destroys the gallery:
+ * - instantly closes the gallery
+ * - unbinds events,
+ * - cleans intervals and timeouts
+ * - removes elements from DOM
+ */
+
+
+ destroy() {
+ var _this$element;
+
+ if (!this.isDestroying) {
+ this.options.showHideAnimationType = 'none';
+ this.close();
+ return;
+ }
+
+ this.dispatch('destroy');
+ this._listeners = {};
+
+ if (this.scrollWrap) {
+ this.scrollWrap.ontouchmove = null;
+ this.scrollWrap.ontouchend = null;
+ }
+
+ (_this$element = this.element) === null || _this$element === void 0 || _this$element.remove();
+ this.mainScroll.itemHolders.forEach(itemHolder => {
+ var _itemHolder$slide2;
+
+ (_itemHolder$slide2 = itemHolder.slide) === null || _itemHolder$slide2 === void 0 || _itemHolder$slide2.destroy();
+ });
+ this.contentLoader.destroy();
+ this.events.removeAll();
+ }
+ /**
+ * Refresh/reload content of a slide by its index
+ *
+ * @param {number} slideIndex
+ */
+
+
+ refreshSlideContent(slideIndex) {
+ this.contentLoader.removeByIndex(slideIndex);
+ this.mainScroll.itemHolders.forEach((itemHolder, i) => {
+ var _this$currSlide$index, _this$currSlide3;
+
+ let potentialHolderIndex = ((_this$currSlide$index = (_this$currSlide3 = this.currSlide) === null || _this$currSlide3 === void 0 ? void 0 : _this$currSlide3.index) !== null && _this$currSlide$index !== void 0 ? _this$currSlide$index : 0) - 1 + i;
+
+ if (this.canLoop()) {
+ potentialHolderIndex = this.getLoopedIndex(potentialHolderIndex);
+ }
+
+ if (potentialHolderIndex === slideIndex) {
+ // set the new slide content
+ this.setContent(itemHolder, slideIndex, true); // activate the new slide if it's current
+
+ if (i === 1) {
+ var _itemHolder$slide3;
+
+ this.currSlide = itemHolder.slide;
+ (_itemHolder$slide3 = itemHolder.slide) === null || _itemHolder$slide3 === void 0 || _itemHolder$slide3.setIsActive(true);
+ }
+ }
+ });
+ this.dispatch('change');
+ }
+ /**
+ * Set slide content
+ *
+ * @param {ItemHolder} holder mainScroll.itemHolders array item
+ * @param {number} index Slide index
+ * @param {boolean} [force] If content should be set even if index wasn't changed
+ */
+
+
+ setContent(holder, index, force) {
+ if (this.canLoop()) {
+ index = this.getLoopedIndex(index);
+ }
+
+ if (holder.slide) {
+ if (holder.slide.index === index && !force) {
+ // exit if holder already contains this slide
+ // this could be common when just three slides are used
+ return;
+ } // destroy previous slide
+
+
+ holder.slide.destroy();
+ holder.slide = undefined;
+ } // exit if no loop and index is out of bounds
+
+
+ if (!this.canLoop() && (index < 0 || index >= this.getNumItems())) {
+ return;
+ }
+
+ const itemData = this.getItemData(index);
+ holder.slide = new Slide(itemData, index, this); // set current slide
+
+ if (index === this.currIndex) {
+ this.currSlide = holder.slide;
+ }
+
+ holder.slide.append(holder.el);
+ }
+ /** @returns {Point} */
+
+
+ getViewportCenterPoint() {
+ return {
+ x: this.viewportSize.x / 2,
+ y: this.viewportSize.y / 2
+ };
+ }
+ /**
+ * Update size of all elements.
+ * Executed on init and on page resize.
+ *
+ * @param {boolean} [force] Update size even if size of viewport was not changed.
+ */
+
+
+ updateSize(force) {
+ // let item;
+ // let itemIndex;
+ if (this.isDestroying) {
+ // exit if PhotoSwipe is closed or closing
+ // (to avoid errors, as resize event might be delayed)
+ return;
+ } //const newWidth = this.scrollWrap.clientWidth;
+ //const newHeight = this.scrollWrap.clientHeight;
+
+
+ const newViewportSize = getViewportSize(this.options, this);
+
+ if (!force && pointsEqual(newViewportSize, this._prevViewportSize)) {
+ // Exit if dimensions were not changed
+ return;
+ } //this._prevViewportSize.x = newWidth;
+ //this._prevViewportSize.y = newHeight;
+
+
+ equalizePoints(this._prevViewportSize, newViewportSize);
+ this.dispatch('beforeResize');
+ equalizePoints(this.viewportSize, this._prevViewportSize);
+
+ this._updatePageScrollOffset();
+
+ this.dispatch('viewportSize'); // Resize slides only after opener animation is finished
+ // and don't re-calculate size on inital size update
+
+ this.mainScroll.resize(this.opener.isOpen);
+
+ if (!this.hasMouse && window.matchMedia('(any-hover: hover)').matches) {
+ this.mouseDetected();
+ }
+
+ this.dispatch('resize');
+ }
+ /**
+ * @param {number} opacity
+ */
+
+
+ applyBgOpacity(opacity) {
+ this.bgOpacity = Math.max(opacity, 0);
+
+ if (this.bg) {
+ this.bg.style.opacity = String(this.bgOpacity * this.options.bgOpacity);
+ }
+ }
+ /**
+ * Whether mouse is detected
+ */
+
+
+ mouseDetected() {
+ if (!this.hasMouse) {
+ var _this$element2;
+
+ this.hasMouse = true;
+ (_this$element2 = this.element) === null || _this$element2 === void 0 || _this$element2.classList.add('pswp--has_mouse');
+ }
+ }
+ /**
+ * Page resize event handler
+ *
+ * @private
+ */
+
+
+ _handlePageResize() {
+ this.updateSize(); // In iOS webview, if element size depends on document size,
+ // it'll be measured incorrectly in resize event
+ //
+ // https://bugs.webkit.org/show_bug.cgi?id=170595
+ // https://hackernoon.com/onresize-event-broken-in-mobile-safari-d8469027bf4d
+
+ if (/iPhone|iPad|iPod/i.test(window.navigator.userAgent)) {
+ setTimeout(() => {
+ this.updateSize();
+ }, 500);
+ }
+ }
+ /**
+ * Page scroll offset is used
+ * to get correct coordinates
+ * relative to PhotoSwipe viewport.
+ *
+ * @private
+ */
+
+
+ _updatePageScrollOffset() {
+ this.setScrollOffset(0, window.pageYOffset);
+ }
+ /**
+ * @param {number} x
+ * @param {number} y
+ */
+
+
+ setScrollOffset(x, y) {
+ this.offset.x = x;
+ this.offset.y = y;
+ this.dispatch('updateScrollOffset');
+ }
+ /**
+ * Create main HTML structure of PhotoSwipe,
+ * and add it to DOM
+ *
+ * @private
+ */
+
+
+ _createMainStructure() {
+ // root DOM element of PhotoSwipe (.pswp)
+ this.element = createElement('pswp', 'div');
+ this.element.setAttribute('tabindex', '-1');
+ this.element.setAttribute('role', 'dialog'); // template is legacy prop
+
+ this.template = this.element; // Background is added as a separate element,
+ // as animating opacity is faster than animating rgba()
+
+ this.bg = createElement('pswp__bg', 'div', this.element);
+ this.scrollWrap = createElement('pswp__scroll-wrap', 'section', this.element);
+ this.container = createElement('pswp__container', 'div', this.scrollWrap); // aria pattern: carousel
+
+ this.scrollWrap.setAttribute('aria-roledescription', 'carousel');
+ this.container.setAttribute('aria-live', 'off');
+ this.container.setAttribute('id', 'pswp__items');
+ this.mainScroll.appendHolders();
+ this.ui = new UI(this);
+ this.ui.init(); // append to DOM
+
+ (this.options.appendToEl || document.body).appendChild(this.element);
+ }
+ /**
+ * Get position and dimensions of small thumbnail
+ * {x:,y:,w:}
+ *
+ * Height is optional (calculated based on the large image)
+ *
+ * @returns {Bounds | undefined}
+ */
+
+
+ getThumbBounds() {
+ return getThumbBounds(this.currIndex, this.currSlide ? this.currSlide.data : this._initialItemData, this);
+ }
+ /**
+ * If the PhotoSwipe can have continuous loop
+ * @returns Boolean
+ */
+
+
+ canLoop() {
+ return this.options.loop && this.getNumItems() > 2;
+ }
+ /**
+ * @private
+ * @param {PhotoSwipeOptions} options
+ * @returns {PreparedPhotoSwipeOptions}
+ */
+
+
+ _prepareOptions(options) {
+ if (window.matchMedia('(prefers-reduced-motion), (update: slow)').matches) {
+ options.showHideAnimationType = 'none';
+ options.zoomAnimationDuration = 0;
+ }
+ /** @type {PreparedPhotoSwipeOptions} */
+
+
+ return { ...defaultOptions,
+ ...options
+ };
+ }
+
+}
+
+export { PhotoSwipe as default };
+//# sourceMappingURL=photoswipe.esm.js.map
diff --git a/app/public/style.css b/app/public/style.css
index c1f80d8..d563fed 100644
--- a/app/public/style.css
+++ b/app/public/style.css
@@ -1,118 +1,384 @@
-html {
- background: #191919;
+/*
+ Tokens ported from immich-app/immich v2.7.5 (web/src/app.css, 2026-05-23).
+ Re-check approximately once a year for visual drift.
+
+ Font note: Immich uses "GoogleSans" (Google's proprietary font, not freely
+ distributed). We use a system font stack with Inter from Google Fonts as a
+ visually-close substitute. Same approach Immich's open-source consumers use.
+*/
+
+/* Inter (OFL-1.1, see fonts/Inter-LICENSE.txt). Single variable WOFF2 covers
+ all weights from 100-900, so we can use any weight in CSS without an extra
+ network request. Vendored locally so IPP runs cleanly air-gapped. */
+@font-face {
+ font-family: 'Inter';
+ src: url('/share/static/fonts/inter-latin-wght-normal.woff2') format('woff2-variations');
+ font-weight: 100 900;
+ font-style: normal;
+ font-display: swap;
}
-#lightgallery a {
- position: relative;
- display: inline-block;
- text-decoration: none;
+:root {
+ /* Immich light-mode tokens (RGB triplets so they compose via rgb(var(...))) */
+ --immich-primary: 66 80 175;
+ --immich-bg: 255 255 255;
+ --immich-fg: 0 0 0;
+ --immich-gray: 235 235 235;
+
+ /* Immich dark-mode tokens */
+ --immich-dark-primary: 172 203 250;
+ --immich-dark-bg: 10 10 10;
+ --immich-dark-fg: 229 231 235;
+ --immich-dark-gray: 33 33 33;
+
+ /* Active palette - light by default; html.dark overrides below */
+ --color-bg: rgb(var(--immich-bg));
+ --color-fg: rgb(var(--immich-fg));
+ --color-primary: rgb(var(--immich-primary));
+ --color-gray: rgb(var(--immich-gray));
+
+ --font-sans: 'Inter', system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
+
+ /* Horizontal inset for textual page content (title, description, group
+ headers). The grid itself goes edge-to-edge on mobile so it doesn't use
+ this value. */
+ --gutter: 32px;
+
+ color-scheme: light;
+}
+
+@media (max-width: 640px) {
+ :root {
+ --gutter: 8px;
+ }
+}
+
+html.dark {
+ --color-bg: rgb(var(--immich-dark-bg));
+ --color-fg: rgb(var(--immich-dark-fg));
+ --color-primary: rgb(var(--immich-dark-primary));
+ --color-gray: rgb(var(--immich-dark-gray));
+
+ color-scheme: dark;
+}
+
+* { box-sizing: border-box; }
+
+html, body {
+ margin: 0;
+ height: 100%;
+ background: var(--color-bg);
+ color: var(--color-fg);
+ font-family: var(--font-sans);
+}
+
+/* ===== Justified-rows / square-grid gallery (tiles are absolute-positioned by JS) ===== */
+
+#gallery {
+ /* Container is a positioned box; tiles are absolute-positioned by JS.
+ Container height is set explicitly so the scrollbar reflects the full
+ virtualized layout. */
+ position: relative;
+ margin: 0 var(--gutter) var(--gutter);
+}
+
+@media (max-width: 640px) {
+ /* Tiles go edge-to-edge on mobile, so the gallery doesn't use --gutter */
+ #gallery {
margin: 0;
- padding: 0;
- cursor: pointer;
+ }
}
-#lightgallery img {
- max-height: 250px;
- margin: 4px;
+#gallery a {
+ position: absolute;
+ display: block;
+ overflow: hidden;
+ text-decoration: none;
+ cursor: pointer;
+ background-color: var(--color-gray);
+ background-size: cover;
+ background-position: center;
+ background-repeat: no-repeat;
+ /* left / top / width / height set per-tile by layoutGrid() in web.js;
+ background-image is the decoded thumbhash placeholder, set by web.js. */
}
-@media (max-width: 800px) {
- #lightgallery a {
- width: calc(100vw / 3 - 10px);
- height: calc(100vw / 3 - 10px);
- overflow: hidden;
- }
-
- #lightgallery img {
- width: 100%;
- height: 100%;
- object-fit: cover;
- object-position: center;
- }
-}
-@media (min-width: 801px) {
- #lightgallery a.thumb-error {
- width: 250px;
- height: 250px;
- margin: 4px;
- }
+#gallery img {
+ display: block;
+ width: 100%;
+ height: 100%;
+ object-fit: cover;
}
-#lightgallery a.thumb-error {
- background: #2a2a2a;
+/* Hide the until JS sets its src - otherwise Chrome renders its default
+ broken-image glyph for img elements with explicit dimensions but no src
+ (e.g. tiles awaiting load, or tiles whose in-flight fetch was cancelled
+ when the user scrolled past). The 's gray background shows through. */
+#gallery img:not([src]) {
+ visibility: hidden;
}
-#lightgallery a.thumb-error img {
- display: none;
+
+#gallery a.thumb-error img {
+ display: none;
+}
+
+/* ===== Group headers (visible when ipp.groupGalleryByDate is enabled) ===== */
+
+.group-header {
+ position: absolute;
+ left: 0;
+ right: 0;
+ margin: 0;
+ padding: 16px 0 8px;
+ font-size: 18px;
+ font-weight: 500;
+ line-height: 1.2;
+ letter-spacing: -0.01em;
+ color: var(--color-fg);
+ white-space: nowrap;
+}
+
+@media (max-width: 640px) {
+ /* On mobile the gallery itself goes edge-to-edge, so the headers need
+ their own left padding to keep the text away from the screen edge. */
+ .group-header {
+ padding-left: var(--gutter);
+ }
+}
+
+/* ===== Selection mode (checkmark + selected state) ===== */
+
+.tile-check {
+ position: absolute;
+ top: 10px;
+ left: 10px;
+ width: 24px;
+ height: 24px;
+ border-radius: 50%;
+ border: 2px solid rgba(255, 255, 255, 0.9);
+ background-color: rgba(0, 0, 0, 0.25);
+ opacity: 0;
+ transition: opacity 0.15s, background-color 0.15s, border-color 0.15s;
+ z-index: 2;
+ cursor: pointer;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+}
+
+#gallery a:hover .tile-check,
+#gallery.select-mode .tile-check {
+ opacity: 1;
+}
+
+.tile-check svg {
+ width: 16px;
+ height: 16px;
+ color: #fff;
+ display: none;
+}
+
+#gallery a.selected .tile-check {
+ background-color: var(--color-primary);
+ border-color: var(--color-primary);
+ opacity: 1;
+}
+
+#gallery a.selected .tile-check svg {
+ display: block;
+}
+
+#gallery a.selected {
+ outline: 3px solid var(--color-primary);
+ outline-offset: -3px;
}
.play-icon {
- position: absolute;
- top: 50%;
- left: 50%;
- transform: translate(-50%, -50%);
- width: 50px;
- height: 50px;
- background-image: url('/share/static/images/play.png');
- background-size: contain;
- background-repeat: no-repeat;
- opacity: 0.5;
+ position: absolute;
+ top: 50%;
+ left: 50%;
+ transform: translate(-50%, -50%);
+ width: 50px;
+ height: 50px;
+ background-image: url('/share/static/images/play.png');
+ background-size: contain;
+ background-repeat: no-repeat;
+ opacity: 0.5;
}
-#lightgallery a:has(.play-icon):hover .play-icon {
- opacity: 1;
+#gallery a:has(.play-icon):hover .play-icon {
+ opacity: 1;
}
-#password {
- color: white;
-}
-
-#header, #album-description {
- font-family: system-ui, "Segoe UI", Roboto, Oxygen, Ubuntu, Cantarell, Helvetica, Arial, "Helvetica Neue", sans-serif;
- color: white;
-}
+/* ===== Header (title + asset count + download action) ===== */
#header {
- width: 100%;
- display: flex;
+ display: flex;
+ align-items: flex-start;
+ justify-content: space-between;
+ gap: 16px;
+ padding: 28px var(--gutter) 12px;
+ color: var(--color-fg);
+}
+
+.header-text {
+ flex: 1 1 auto;
+ min-width: 0;
}
#header h1 {
- font-size: 18pt;
- font-weight: bold;
- margin: 4px;
+ margin: 0;
+ font-size: 28px;
+ font-weight: 500;
+ line-height: 1.2;
+ letter-spacing: -0.01em;
+ overflow-wrap: break-word;
}
-#album-description h2 {
- font-size: 12pt;
- font-weight: normal;
- font-style: italic;
- margin: 4px;
- white-space: pre-wrap;
+#header .subtitle {
+ margin: 4px 0 0;
+ font-size: 14px;
+ font-weight: 400;
+ opacity: 0.55;
}
#download-all {
- margin: auto 4px auto auto;
+ flex: 0 0 auto;
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ width: 44px;
+ height: 44px;
+ border-radius: 50%;
+ text-decoration: none;
+ color: var(--color-fg);
+ transition: background-color 0.15s;
}
-#loading-spinner {
- text-align: center;
- margin: 75px 0;
+#download-all:hover,
+#download-all:focus-visible {
+ background-color: color-mix(in srgb, var(--color-fg) 10%, transparent);
+ outline: none;
}
-.loader {
- width: 48px;
+
+#download-all svg {
+ width: 22px;
+ height: 22px;
+}
+
+#album-description {
+ margin: 0;
+ padding: 0 var(--gutter) 16px;
+ color: var(--color-fg);
+ opacity: 0.7;
+ font-size: 15px;
+ line-height: 1.5;
+ white-space: pre-wrap;
+}
+
+@media (max-width: 640px) {
+ #header {
+ padding-top: 16px;
+ padding-bottom: 8px;
+ }
+ #header h1 {
+ font-size: 22px;
+ }
+ #album-description {
+ padding-bottom: 12px;
+ font-size: 14px;
+ }
+}
+
+/* ===== Selection toolbar (fixed at top while select-mode is active) ===== */
+
+#select-toolbar {
+ position: fixed;
+ top: 0;
+ left: 0;
+ right: 0;
+ height: 56px;
+ background: var(--color-bg);
+ border-bottom: 1px solid color-mix(in srgb, var(--color-fg) 10%, transparent);
+ display: flex;
+ align-items: center;
+ gap: 4px;
+ padding: 0 8px;
+ z-index: 100;
+ box-shadow: 0 1px 6px color-mix(in srgb, var(--color-fg) 6%, transparent);
+}
+
+/* The display rule above is more specific than the browser's default
+ [hidden] { display: none } - explicitly override so the toolbar honors
+ the hidden attribute. */
+#select-toolbar[hidden] {
+ display: none;
+}
+
+.toolbar-btn {
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ width: 44px;
+ height: 44px;
+ padding: 0;
+ border-radius: 50%;
+ background: transparent;
+ border: none;
+ color: var(--color-fg);
+ cursor: pointer;
+ transition: background-color 0.15s;
+}
+
+.toolbar-btn:hover,
+.toolbar-btn:focus-visible {
+ background-color: color-mix(in srgb, var(--color-fg) 10%, transparent);
+ outline: none;
+}
+
+.toolbar-btn svg {
+ width: 22px;
+ height: 22px;
+}
+
+#select-count {
+ flex: 1 1 auto;
+ min-width: 0;
+ padding: 0 12px;
+ font-size: 16px;
+ font-weight: 500;
+ color: var(--color-fg);
+}
+
+.toolbar-btn-text {
+ flex: 0 0 auto;
+ padding: 8px 16px;
+ background: transparent;
+ border: none;
+ color: var(--color-fg);
+ cursor: pointer;
+ border-radius: 20px;
+ font-size: 14px;
+ font-weight: 500;
+ transition: background-color 0.15s;
+}
+
+.toolbar-btn-text:hover,
+.toolbar-btn-text:focus-visible {
+ background-color: color-mix(in srgb, var(--color-fg) 10%, transparent);
+ outline: none;
+}
+
+@media (max-width: 640px) {
+ #select-toolbar {
height: 48px;
- border: 5px solid #888;
- border-bottom-color: transparent;
- border-radius: 50%;
- display: inline-block;
- box-sizing: border-box;
- animation: rotation 1s linear infinite;
-}
-@keyframes rotation {
- 0% {
- transform: rotate(0deg);
- }
- 100% {
- transform: rotate(360deg);
- }
+ }
+ #select-count {
+ font-size: 15px;
+ padding: 0 8px;
+ }
+ .toolbar-btn-text {
+ padding: 6px 12px;
+ font-size: 13px;
+ }
}
diff --git a/app/public/thumbhash/thumbhash.js b/app/public/thumbhash/thumbhash.js
new file mode 100644
index 0000000..369b118
--- /dev/null
+++ b/app/public/thumbhash/thumbhash.js
@@ -0,0 +1,288 @@
+/**
+ * Encodes an RGBA image to a ThumbHash. RGB should not be premultiplied by A.
+ *
+ * @param w The width of the input image. Must be ≤100px.
+ * @param h The height of the input image. Must be ≤100px.
+ * @param rgba The pixels in the input image, row-by-row. Must have w*h*4 elements.
+ * @returns The ThumbHash as a Uint8Array.
+ */
+export function rgbaToThumbHash(w, h, rgba) {
+ // Encoding an image larger than 100x100 is slow with no benefit
+ if (w > 100 || h > 100) throw new Error(`${w}x${h} doesn't fit in 100x100`)
+ let { PI, round, max, cos, abs } = Math
+
+ // Determine the average color
+ let avg_r = 0, avg_g = 0, avg_b = 0, avg_a = 0
+ for (let i = 0, j = 0; i < w * h; i++, j += 4) {
+ let alpha = rgba[j + 3] / 255
+ avg_r += alpha / 255 * rgba[j]
+ avg_g += alpha / 255 * rgba[j + 1]
+ avg_b += alpha / 255 * rgba[j + 2]
+ avg_a += alpha
+ }
+ if (avg_a) {
+ avg_r /= avg_a
+ avg_g /= avg_a
+ avg_b /= avg_a
+ }
+
+ let hasAlpha = avg_a < w * h
+ let l_limit = hasAlpha ? 5 : 7 // Use fewer luminance bits if there's alpha
+ let lx = max(1, round(l_limit * w / max(w, h)))
+ let ly = max(1, round(l_limit * h / max(w, h)))
+ let l = [] // luminance
+ let p = [] // yellow - blue
+ let q = [] // red - green
+ let a = [] // alpha
+
+ // Convert the image from RGBA to LPQA (composite atop the average color)
+ for (let i = 0, j = 0; i < w * h; i++, j += 4) {
+ let alpha = rgba[j + 3] / 255
+ let r = avg_r * (1 - alpha) + alpha / 255 * rgba[j]
+ let g = avg_g * (1 - alpha) + alpha / 255 * rgba[j + 1]
+ let b = avg_b * (1 - alpha) + alpha / 255 * rgba[j + 2]
+ l[i] = (r + g + b) / 3
+ p[i] = (r + g) / 2 - b
+ q[i] = r - g
+ a[i] = alpha
+ }
+
+ // Encode using the DCT into DC (constant) and normalized AC (varying) terms
+ let encodeChannel = (channel, nx, ny) => {
+ let dc = 0, ac = [], scale = 0, fx = []
+ for (let cy = 0; cy < ny; cy++) {
+ for (let cx = 0; cx * ny < nx * (ny - cy); cx++) {
+ let f = 0
+ for (let x = 0; x < w; x++)
+ fx[x] = cos(PI / w * cx * (x + 0.5))
+ for (let y = 0; y < h; y++)
+ for (let x = 0, fy = cos(PI / h * cy * (y + 0.5)); x < w; x++)
+ f += channel[x + y * w] * fx[x] * fy
+ f /= w * h
+ if (cx || cy) {
+ ac.push(f)
+ scale = max(scale, abs(f))
+ } else {
+ dc = f
+ }
+ }
+ }
+ if (scale)
+ for (let i = 0; i < ac.length; i++)
+ ac[i] = 0.5 + 0.5 / scale * ac[i]
+ return [dc, ac, scale]
+ }
+ let [l_dc, l_ac, l_scale] = encodeChannel(l, max(3, lx), max(3, ly))
+ let [p_dc, p_ac, p_scale] = encodeChannel(p, 3, 3)
+ let [q_dc, q_ac, q_scale] = encodeChannel(q, 3, 3)
+ let [a_dc, a_ac, a_scale] = hasAlpha ? encodeChannel(a, 5, 5) : []
+
+ // Write the constants
+ let isLandscape = w > h
+ let header24 = round(63 * l_dc) | (round(31.5 + 31.5 * p_dc) << 6) | (round(31.5 + 31.5 * q_dc) << 12) | (round(31 * l_scale) << 18) | (hasAlpha << 23)
+ let header16 = (isLandscape ? ly : lx) | (round(63 * p_scale) << 3) | (round(63 * q_scale) << 9) | (isLandscape << 15)
+ let hash = [header24 & 255, (header24 >> 8) & 255, header24 >> 16, header16 & 255, header16 >> 8]
+ let ac_start = hasAlpha ? 6 : 5
+ let ac_index = 0
+ if (hasAlpha) hash.push(round(15 * a_dc) | (round(15 * a_scale) << 4))
+
+ // Write the varying factors
+ for (let ac of hasAlpha ? [l_ac, p_ac, q_ac, a_ac] : [l_ac, p_ac, q_ac])
+ for (let f of ac)
+ hash[ac_start + (ac_index >> 1)] |= round(15 * f) << ((ac_index++ & 1) << 2)
+ return new Uint8Array(hash)
+}
+
+/**
+ * Decodes a ThumbHash to an RGBA image. RGB is not be premultiplied by A.
+ *
+ * @param hash The bytes of the ThumbHash.
+ * @returns The width, height, and pixels of the rendered placeholder image.
+ */
+export function thumbHashToRGBA(hash) {
+ let { PI, min, max, cos, round } = Math
+
+ // Read the constants
+ let header24 = hash[0] | (hash[1] << 8) | (hash[2] << 16)
+ let header16 = hash[3] | (hash[4] << 8)
+ let l_dc = (header24 & 63) / 63
+ let p_dc = ((header24 >> 6) & 63) / 31.5 - 1
+ let q_dc = ((header24 >> 12) & 63) / 31.5 - 1
+ let l_scale = ((header24 >> 18) & 31) / 31
+ let hasAlpha = header24 >> 23
+ let p_scale = ((header16 >> 3) & 63) / 63
+ let q_scale = ((header16 >> 9) & 63) / 63
+ let isLandscape = header16 >> 15
+ let lx = max(3, isLandscape ? hasAlpha ? 5 : 7 : header16 & 7)
+ let ly = max(3, isLandscape ? header16 & 7 : hasAlpha ? 5 : 7)
+ let a_dc = hasAlpha ? (hash[5] & 15) / 15 : 1
+ let a_scale = (hash[5] >> 4) / 15
+
+ // Read the varying factors (boost saturation by 1.25x to compensate for quantization)
+ let ac_start = hasAlpha ? 6 : 5
+ let ac_index = 0
+ let decodeChannel = (nx, ny, scale) => {
+ let ac = []
+ for (let cy = 0; cy < ny; cy++)
+ for (let cx = cy ? 0 : 1; cx * ny < nx * (ny - cy); cx++)
+ ac.push((((hash[ac_start + (ac_index >> 1)] >> ((ac_index++ & 1) << 2)) & 15) / 7.5 - 1) * scale)
+ return ac
+ }
+ let l_ac = decodeChannel(lx, ly, l_scale)
+ let p_ac = decodeChannel(3, 3, p_scale * 1.25)
+ let q_ac = decodeChannel(3, 3, q_scale * 1.25)
+ let a_ac = hasAlpha && decodeChannel(5, 5, a_scale)
+
+ // Decode using the DCT into RGB
+ let ratio = thumbHashToApproximateAspectRatio(hash)
+ let w = round(ratio > 1 ? 32 : 32 * ratio)
+ let h = round(ratio > 1 ? 32 / ratio : 32)
+ let rgba = new Uint8Array(w * h * 4), fx = [], fy = []
+ for (let y = 0, i = 0; y < h; y++) {
+ for (let x = 0; x < w; x++, i += 4) {
+ let l = l_dc, p = p_dc, q = q_dc, a = a_dc
+
+ // Precompute the coefficients
+ for (let cx = 0, n = max(lx, hasAlpha ? 5 : 3); cx < n; cx++)
+ fx[cx] = cos(PI / w * (x + 0.5) * cx)
+ for (let cy = 0, n = max(ly, hasAlpha ? 5 : 3); cy < n; cy++)
+ fy[cy] = cos(PI / h * (y + 0.5) * cy)
+
+ // Decode L
+ for (let cy = 0, j = 0; cy < ly; cy++)
+ for (let cx = cy ? 0 : 1, fy2 = fy[cy] * 2; cx * ly < lx * (ly - cy); cx++, j++)
+ l += l_ac[j] * fx[cx] * fy2
+
+ // Decode P and Q
+ for (let cy = 0, j = 0; cy < 3; cy++) {
+ for (let cx = cy ? 0 : 1, fy2 = fy[cy] * 2; cx < 3 - cy; cx++, j++) {
+ let f = fx[cx] * fy2
+ p += p_ac[j] * f
+ q += q_ac[j] * f
+ }
+ }
+
+ // Decode A
+ if (hasAlpha)
+ for (let cy = 0, j = 0; cy < 5; cy++)
+ for (let cx = cy ? 0 : 1, fy2 = fy[cy] * 2; cx < 5 - cy; cx++, j++)
+ a += a_ac[j] * fx[cx] * fy2
+
+ // Convert to RGB
+ let b = l - 2 / 3 * p
+ let r = (3 * l - b + q) / 2
+ let g = r - q
+ rgba[i] = max(0, 255 * min(1, r))
+ rgba[i + 1] = max(0, 255 * min(1, g))
+ rgba[i + 2] = max(0, 255 * min(1, b))
+ rgba[i + 3] = max(0, 255 * min(1, a))
+ }
+ }
+ return { w, h, rgba }
+}
+
+/**
+ * Extracts the average color from a ThumbHash. RGB is not be premultiplied by A.
+ *
+ * @param hash The bytes of the ThumbHash.
+ * @returns The RGBA values for the average color. Each value ranges from 0 to 1.
+ */
+export function thumbHashToAverageRGBA(hash) {
+ let { min, max } = Math
+ let header = hash[0] | (hash[1] << 8) | (hash[2] << 16)
+ let l = (header & 63) / 63
+ let p = ((header >> 6) & 63) / 31.5 - 1
+ let q = ((header >> 12) & 63) / 31.5 - 1
+ let hasAlpha = header >> 23
+ let a = hasAlpha ? (hash[5] & 15) / 15 : 1
+ let b = l - 2 / 3 * p
+ let r = (3 * l - b + q) / 2
+ let g = r - q
+ return {
+ r: max(0, min(1, r)),
+ g: max(0, min(1, g)),
+ b: max(0, min(1, b)),
+ a
+ }
+}
+
+/**
+ * Extracts the approximate aspect ratio of the original image.
+ *
+ * @param hash The bytes of the ThumbHash.
+ * @returns The approximate aspect ratio (i.e. width / height).
+ */
+export function thumbHashToApproximateAspectRatio(hash) {
+ let header = hash[3]
+ let hasAlpha = hash[2] & 0x80
+ let isLandscape = hash[4] & 0x80
+ let lx = isLandscape ? hasAlpha ? 5 : 7 : header & 7
+ let ly = isLandscape ? header & 7 : hasAlpha ? 5 : 7
+ return lx / ly
+}
+
+/**
+ * Encodes an RGBA image to a PNG data URL. RGB should not be premultiplied by
+ * A. This is optimized for speed and simplicity and does not optimize for size
+ * at all. This doesn't do any compression (all values are stored uncompressed).
+ *
+ * @param w The width of the input image. Must be ≤100px.
+ * @param h The height of the input image. Must be ≤100px.
+ * @param rgba The pixels in the input image, row-by-row. Must have w*h*4 elements.
+ * @returns A data URL containing a PNG for the input image.
+ */
+export function rgbaToDataURL(w, h, rgba) {
+ let row = w * 4 + 1
+ let idat = 6 + h * (5 + row)
+ let bytes = [
+ 137, 80, 78, 71, 13, 10, 26, 10, 0, 0, 0, 13, 73, 72, 68, 82, 0, 0,
+ w >> 8, w & 255, 0, 0, h >> 8, h & 255, 8, 6, 0, 0, 0, 0, 0, 0, 0,
+ idat >>> 24, (idat >> 16) & 255, (idat >> 8) & 255, idat & 255,
+ 73, 68, 65, 84, 120, 1
+ ]
+ let table = [
+ 0, 498536548, 997073096, 651767980, 1994146192, 1802195444, 1303535960,
+ 1342533948, -306674912, -267414716, -690576408, -882789492, -1687895376,
+ -2032938284, -1609899400, -1111625188
+ ]
+ let a = 1, b = 0
+ for (let y = 0, i = 0, end = row - 1; y < h; y++, end += row - 1) {
+ bytes.push(y + 1 < h ? 0 : 1, row & 255, row >> 8, ~row & 255, (row >> 8) ^ 255, 0)
+ for (b = (b + a) % 65521; i < end; i++) {
+ let u = rgba[i] & 255
+ bytes.push(u)
+ a = (a + u) % 65521
+ b = (b + a) % 65521
+ }
+ }
+ bytes.push(
+ b >> 8, b & 255, a >> 8, a & 255, 0, 0, 0, 0,
+ 0, 0, 0, 0, 73, 69, 78, 68, 174, 66, 96, 130
+ )
+ for (let [start, end] of [[12, 29], [37, 41 + idat]]) {
+ let c = ~0
+ for (let i = start; i < end; i++) {
+ c ^= bytes[i]
+ c = (c >>> 4) ^ table[c & 15]
+ c = (c >>> 4) ^ table[c & 15]
+ }
+ c = ~c
+ bytes[end++] = c >>> 24
+ bytes[end++] = (c >> 16) & 255
+ bytes[end++] = (c >> 8) & 255
+ bytes[end++] = c & 255
+ }
+ return 'data:image/png;base64,' + btoa(String.fromCharCode(...bytes))
+}
+
+/**
+ * Decodes a ThumbHash to a PNG data URL. This is a convenience function that
+ * just calls "thumbHashToRGBA" followed by "rgbaToDataURL".
+ *
+ * @param hash The bytes of the ThumbHash.
+ * @returns A data URL containing a PNG for the rendered ThumbHash.
+ */
+export function thumbHashToDataURL(hash) {
+ let image = thumbHashToRGBA(hash)
+ return rgbaToDataURL(image.w, image.h, image.rgba)
+}
diff --git a/app/public/web.js b/app/public/web.js
index 04f7129..4d992e2 100644
--- a/app/public/web.js
+++ b/app/public/web.js
@@ -1,78 +1,886 @@
-// How many thumbnails to load per "page" fetched from Immich
-const PER_PAGE = 50
+// @ts-check
+// ============================================================================
+// Gallery client - virtualized justified/square grid, PhotoSwipe v5 lightbox
+//
+// Layout is pre-computed for all items based on container width. Only tiles
+// within viewport ± 1 viewport-height buffer exist in the DOM at any moment.
+// PhotoSwipe runs with a full dataSource array so the lightbox navigates
+// across all items regardless of which tiles are currently rendered.
+// ============================================================================
-class LGallery {
- items
- lightGallery
- element
- index = PER_PAGE
+// Runtime URLs served by Express, not filesystem paths. TypeScript's resolver
+// can't follow them, so we silence its module-not-found errors here. The
+// imports themselves work fine at runtime.
+// @ts-ignore
+import PhotoSwipeLightbox from '/share/static/photoswipe/photoswipe-lightbox.esm.js'
+// @ts-ignore
+import { thumbHashToDataURL } from '/share/static/thumbhash/thumbhash.js'
- /**
- * Create a lightGallery instance and populate it with the first page of gallery items
- */
- init (params = {}) {
- // Create the lightGallery instance
- this.element = document.getElementById('lightgallery')
- this.lightGallery = lightGallery(this.element, Object.assign({
- plugins: [lgZoom, lgThumbnail, lgVideo, lgFullscreen, lgHash],
- speed: 500,
- loop: params.items.length <= PER_PAGE,
- /*
- This license key was graciously provided by LightGallery under their
- GPLv3 open-source project license:
- */
- licenseKey: '8FFA6495-676C4D30-8BFC54B6-4D0A6CEC'
- /*
- Please do not take it and use it for other projects, as it was provided
- specifically for Immich Public Proxy.
+/**
+ * @typedef {Object} GalleryItem
+ * @property {string} id
+ * @property {'IMAGE'|'VIDEO'} type
+ * @property {string} previewUrl
+ * @property {string} thumbnailUrl
+ * @property {string} [downloadUrl]
+ * @property {string} [videoData] JSON-stringified video source info
+ * @property {string} [description] Escaped HTML fragment for the lightbox caption
+ * @property {string} downloadFilename
+ * @property {number} [width]
+ * @property {number} [height]
+ * @property {string} [thumbhash]
+ * @property {string} [fileCreatedAt] ISO date
+ */
- For your own projects you can use the default license key of
- 0000-0000-000-0000 as per their docs:
+/**
+ * @typedef {Object} LightboxConfig
+ * @property {boolean} [showArrows]
+ * @property {boolean} [showDownload]
+ * @property {boolean} [mobileArrows]
+ */
- https://www.lightgalleryjs.com/docs/settings/#licenseKey
- */
- }, params.lgConfig))
- this.items = params.items
+/**
+ * @typedef {Object} InitParams
+ * @property {GalleryItem[]} [items]
+ * @property {number} [openItem] 1-based; opens lightbox on the Nth item
+ * @property {LightboxConfig} [lightboxConfig]
+ * @property {boolean} [groupByDate]
+ */
- const spinner = document.getElementById('loading-spinner')
- let observer = null
+/**
+ * @typedef {Object} LayoutEntry
+ * @property {number} index
+ * @property {number} left
+ * @property {number} top
+ * @property {number} width
+ * @property {number} height
+ */
- if (spinner) {
- observer = new IntersectionObserver((entries) => {
- if (entries[0].isIntersecting) {
- lgallery.loadMoreItems(observer, spinner)
- }
- }, { rootMargin: '200px' })
- observer.observe(spinner)
+/**
+ * @typedef {Object} HeaderEntry
+ * @property {string} label
+ * @property {number} top
+ * @property {number} height
+ */
+
+/**
+ * @typedef {Object} GroupSpec
+ * @property {string | null} label
+ * @property {number[]} indices
+ */
+
+// Justified-rows target row height (matches Immich's main view)
+const TARGET_ROW_HEIGHT = 235
+const GAP = 4
+const MOBILE_BREAKPOINT = 640
+const MOBILE_COLS = 3
+const IMAGE_LOAD_MARGIN_PX = 300
+const SCROLL_SETTLE_MS = 100
+const BUFFER_VIEWPORTS = 1
+// Height reserved for each month header (must agree with .group-header CSS)
+const HEADER_HEIGHT = 48
+// Vertical gap between groups
+const GROUP_GAP = 16
+
+// MDI icons (Apache 2.0). Same icon set Immich uses for its viewer.
+const ICON_DOWNLOAD = ' '
+const ICON_FULLSCREEN = ' '
+const ICON_FULLSCREEN_EXIT = ' '
+
+// ----- module state ---------------------------------------------------------
+
+/** @type {GalleryItem[]} */
+let items = []
+/** @type {LayoutEntry[]} - sparse, indexed by GalleryItem index */
+let layout = []
+/** @type {HeaderEntry[]} - empty when groupByDate is off */
+let headers = []
+let groupByDate = false
+/** @type {HTMLElement | null} */
+let container = null
+/** @type {any} - PhotoSwipeLightbox instance; external module, leave untyped */
+let lightbox = null
+/** @type {LightboxConfig} */
+let lightboxConfig = {}
+/** @type {boolean} - true while our pushed history entry is live */
+let lightboxPushedHistory = false
+/** @type {boolean} - guards against re-entering the popstate handler during our own history.back() */
+let closingFromHistory = false
+/** @type {Map} */
+const renderedTiles = new Map()
+/** @type {Map} */
+const renderedHeaders = new Map()
+let lastContainerW = 0
+
+// Selection mode (mode-toggle UX: hidden checkmarks until activated)
+let selectMode = false
+/** @type {Set} - set of asset IDs */
+const selected = new Set()
+/** @type {HTMLElement | null} */
+let toolbarEl = null
+/** @type {HTMLElement | null} */
+let countEl = null
+/** @type {HTMLButtonElement | null} */
+let selectAllBtn = null
+/** @type {HTMLButtonElement | null} */
+let cancelBtn = null
+/** @type {HTMLButtonElement | null} */
+let downloadBtn = null
+
+// Inline SVG for the check icon shown inside selected tiles' checkmark circle
+const CHECK_SVG = ' '
+
+// Long-press threshold for entering select mode via touch/mouse
+const LONG_PRESS_MS = 500
+
+// ----- layout computation ---------------------------------------------------
+
+function computeLayout (containerW) {
+ const tileLayout = new Array(items.length)
+ const newHeaders = []
+ const groups = groupByDate ? groupItemsByMonth() : [{ label: null, indices: itemIndices() }]
+ const isMobile = containerW < MOBILE_BREAKPOINT
+ let y = 0
+ for (let g = 0; g < groups.length; g++) {
+ const group = groups[g]
+ if (group.label) {
+ newHeaders.push({ label: group.label, top: y, height: HEADER_HEIGHT })
+ y += HEADER_HEIGHT
}
+ y = isMobile
+ ? layoutSquareGroup(containerW, group.indices, y, tileLayout)
+ : layoutJustifiedGroup(containerW, group.indices, y, tileLayout)
+ if (g < groups.length - 1) y += GROUP_GAP
+ }
+ return {
+ layout: tileLayout,
+ headers: newHeaders,
+ totalHeight: Math.max(0, y)
+ }
+}
- const preloadThreshold = 8
- this.element.addEventListener('lgAfterSlide', (event) => {
- if (event.detail.index >= this.index - preloadThreshold) {
- lgallery.loadMoreItems(observer, spinner)
- }
+function itemIndices () {
+ const out = new Array(items.length)
+ for (let i = 0; i < items.length; i++) out[i] = i
+ return out
+}
+
+/** @returns {GroupSpec[]} */
+function groupItemsByMonth () {
+ // Preserve item order (already sorted desc by render.ts when grouping is on)
+ /** @type {Map} */
+ const map = new Map()
+ for (let i = 0; i < items.length; i++) {
+ const key = (items[i].fileCreatedAt || '').slice(0, 7) || 'undated'
+ let g = map.get(key)
+ if (!g) {
+ g = { label: monthLabel(key), indices: [] }
+ map.set(key, g)
+ }
+ g.indices.push(i)
+ }
+ return Array.from(map.values())
+}
+
+/** @param {string} key @returns {string} */
+function monthLabel (key) {
+ if (key === 'undated') return 'Undated'
+ const parts = key.split('-')
+ const y = Number(parts[0])
+ const m = Number(parts[1])
+ if (!y || !m) return key
+ // Intl.DateTimeFormat picks up the browser's locale; UTC timeZone keeps
+ // the displayed month consistent with the UTC YYYY-MM bucket key.
+ return new Intl.DateTimeFormat(undefined, {
+ year: 'numeric',
+ month: 'long',
+ timeZone: 'UTC'
+ }).format(new Date(Date.UTC(y, m - 1, 1)))
+}
+
+/**
+ * @param {number} containerW
+ * @param {number[]} indices
+ * @param {number} startY
+ * @param {LayoutEntry[]} tileLayout
+ * @returns {number} The y position past the last tile (no trailing gap)
+ */
+function layoutSquareGroup (containerW, indices, startY, tileLayout) {
+ const tileSize = Math.floor((containerW - (MOBILE_COLS - 1) * GAP) / MOBILE_COLS)
+ let col = 0
+ let x = 0
+ let y = startY
+ for (const idx of indices) {
+ tileLayout[idx] = { index: idx, left: x, top: y, width: tileSize, height: tileSize }
+ col++
+ if (col === MOBILE_COLS) {
+ col = 0
+ x = 0
+ y += tileSize + GAP
+ } else {
+ x += tileSize + GAP
+ }
+ }
+ // If the last row was partial, advance y to past it
+ if (col > 0) y += tileSize
+ // Otherwise back off the trailing inter-row gap
+ else if (y > startY) y -= GAP
+ return y
+}
+
+function layoutJustifiedGroup (containerW, indices, startY, tileLayout) {
+ let rowItems = []
+ let aspectSum = 0
+ let y = startY
+
+ const applyRow = (rowItems, height, isLastRow) => {
+ const intHeight = Math.floor(height)
+ let x = 0
+ rowItems.forEach(({ idx, aspect }, i) => {
+ const isFinalInRow = i === rowItems.length - 1
+ const w = (!isLastRow && isFinalInRow)
+ ? containerW - x
+ : Math.floor(aspect * height)
+ tileLayout[idx] = { index: idx, left: x, top: y, width: w, height: intHeight }
+ x += w + GAP
})
+ y += intHeight + GAP
}
- /**
- * Load more gallery items as per lightGallery docs
- * https://www.lightgalleryjs.com/demos/infinite-scrolling/
- */
- loadMoreItems (observer, spinner) {
- if (this.index < this.items.length) {
- // Append new thumbnails
- this.items
- .slice(this.index, this.index + PER_PAGE)
- .forEach(item => {
- this.element.insertAdjacentHTML('beforeend', item.html + '\n')
- })
- this.index += PER_PAGE
- this.lightGallery.refresh()
+ for (const idx of indices) {
+ const item = items[idx]
+ const w = item.width || 1
+ const h = item.height || 1
+ const aspect = w / h
+ rowItems.push({ idx, aspect })
+ aspectSum += aspect
+ const projectedH = (containerW - (rowItems.length - 1) * GAP) / aspectSum
+ if (projectedH <= TARGET_ROW_HEIGHT) {
+ applyRow(rowItems, projectedH, false)
+ rowItems = []
+ aspectSum = 0
+ }
+ }
+ if (rowItems.length) applyRow(rowItems, TARGET_ROW_HEIGHT, true)
+
+ // y advanced past the last row's trailing gap; back off
+ return y > startY ? y - GAP : y
+}
+
+// ----- tile DOM construction ------------------------------------------------
+
+function onThumbError () {
+ this.closest('a').classList.add('thumb-error')
+}
+
+// Cache of decoded thumbhash → PNG data URL. Same thumbhash on multiple
+// tile-creations (revisits during virtualization) reuses the same URL.
+const thumbhashCache = new Map()
+
+function decodeThumbhash (base64) {
+ const cached = thumbhashCache.get(base64)
+ if (cached) return cached
+ try {
+ const binary = atob(base64)
+ const bytes = new Uint8Array(binary.length)
+ for (let i = 0; i < bytes.length; i++) bytes[i] = binary.charCodeAt(i)
+ const url = thumbHashToDataURL(bytes)
+ thumbhashCache.set(base64, url)
+ return url
+ } catch (e) {
+ return null
+ }
+}
+
+function createTile (index) {
+ const item = items[index]
+ const l = layout[index]
+ const a = document.createElement('a')
+ a.dataset.index = index
+ if (item.type !== 'VIDEO') a.href = item.previewUrl
+ a.style.left = l.left + 'px'
+ a.style.top = l.top + 'px'
+ a.style.width = l.width + 'px'
+ a.style.height = l.height + 'px'
+
+ if (item.thumbhash) {
+ const url = decodeThumbhash(item.thumbhash)
+ if (url) a.style.backgroundImage = 'url(' + url + ')'
+ }
+
+ const img = document.createElement('img')
+ // alt left empty: browsers paint alt text over the thumbhash background
+ // while the thumbnail downloads. Description (if any) is shown in the
+ // lightbox caption instead.
+ img.alt = ''
+ img.dataset.src = item.thumbnailUrl
+ img.onerror = onThumbError
+ a.appendChild(img)
+
+ if (item.type === 'VIDEO') {
+ const playIcon = document.createElement('div')
+ playIcon.className = 'play-icon'
+ a.appendChild(playIcon)
+ }
+
+ // Selection checkmark (rendered only when select mode is even possible -
+ // i.e. when the page included the toolbar element)
+ if (toolbarEl) {
+ const check = document.createElement('div')
+ check.className = 'tile-check'
+ check.innerHTML = CHECK_SVG
+ check.addEventListener('click', (e) => {
+ e.preventDefault()
+ e.stopPropagation()
+ if (!selectMode) enterSelectMode()
+ toggleSelection(item.id)
+ })
+ a.appendChild(check)
+ if (selected.has(item.id)) a.classList.add('selected')
+ attachLongPress(a, item.id)
+ }
+
+ a.addEventListener('click', (e) => {
+ e.preventDefault()
+ if (selectMode) {
+ toggleSelection(item.id)
} else {
- // Remove the loading spinner and stop observing once all items are loaded
- if (observer) observer.disconnect()
- if (spinner) spinner.remove()
+ openLightbox(index)
+ }
+ })
+
+ return a
+}
+
+// ----- long-press (enter select mode) --------------------------------------
+
+function attachLongPress (tile, id) {
+ let timer = null
+ let pressed = false
+ const cancel = () => {
+ if (timer) { clearTimeout(timer); timer = null }
+ }
+ tile.addEventListener('pointerdown', (e) => {
+ // Ignore right/middle clicks
+ if (e.button !== undefined && e.button !== 0) return
+ pressed = false
+ timer = setTimeout(() => {
+ timer = null
+ pressed = true
+ if (!selectMode) enterSelectMode()
+ toggleSelection(id)
+ }, LONG_PRESS_MS)
+ })
+ tile.addEventListener('pointerup', cancel)
+ tile.addEventListener('pointercancel', cancel)
+ tile.addEventListener('pointerleave', cancel)
+ tile.addEventListener('pointermove', (e) => {
+ // Cancel long-press if pointer moves significantly (scroll, drag)
+ if (Math.abs(e.movementX) + Math.abs(e.movementY) > 6) cancel()
+ })
+ // Swallow the synthetic click that follows a successful long-press so it
+ // doesn't open the lightbox.
+ tile.addEventListener('click', (e) => {
+ if (pressed) {
+ pressed = false
+ e.preventDefault()
+ e.stopImmediatePropagation()
+ }
+ }, true)
+}
+
+// ----- selection state -----------------------------------------------------
+
+function enterSelectMode () {
+ if (selectMode) return
+ selectMode = true
+ if (container) container.classList.add('select-mode')
+ if (toolbarEl) toolbarEl.hidden = false
+}
+
+function exitSelectMode () {
+ if (!selectMode) return
+ selectMode = false
+ // Clear DOM markers on the tiles currently in the DOM
+ for (const a of renderedTiles.values()) a.classList.remove('selected')
+ selected.clear()
+ if (container) container.classList.remove('select-mode')
+ if (toolbarEl) toolbarEl.hidden = true
+ updateSelectionUI()
+}
+
+function toggleSelection (id) {
+ if (selected.has(id)) selected.delete(id)
+ else selected.add(id)
+ const idx = items.findIndex(it => it.id === id)
+ const tile = idx >= 0 ? renderedTiles.get(idx) : null
+ if (tile) tile.classList.toggle('selected', selected.has(id))
+ // Auto-exit if user deselected the last item
+ if (selected.size === 0 && selectMode) exitSelectMode()
+ else updateSelectionUI()
+}
+
+function updateSelectionUI () {
+ if (countEl) {
+ countEl.textContent = selected.size + ' selected'
+ }
+ if (downloadBtn) downloadBtn.disabled = selected.size === 0
+ if (selectAllBtn) {
+ selectAllBtn.textContent =
+ selected.size === items.length ? 'Deselect all' : 'Select all'
+ }
+}
+
+function selectAllOrNone () {
+ if (selected.size === items.length) {
+ // Deselect all but keep select mode active
+ for (const a of renderedTiles.values()) a.classList.remove('selected')
+ selected.clear()
+ updateSelectionUI()
+ } else {
+ if (!selectMode) enterSelectMode()
+ for (const item of items) selected.add(item.id)
+ for (const a of renderedTiles.values()) a.classList.add('selected')
+ updateSelectionUI()
+ }
+}
+
+function downloadSelected () {
+ if (selected.size === 0) return
+ // Single selection: download the file directly so the user gets the image
+ // (or video) instead of a one-entry zip.
+ if (selected.size === 1) {
+ const id = selected.values().next().value
+ const item = items.find(it => it.id === id)
+ if (item && item.downloadUrl) {
+ const a = document.createElement('a')
+ a.href = item.downloadUrl
+ a.download = item.downloadFilename || ''
+ document.body.appendChild(a)
+ a.click()
+ a.remove()
+ return
+ }
+ }
+ // Form POST so the browser handles streaming the zip directly to disk.
+ const form = document.createElement('form')
+ form.method = 'POST'
+ form.action = window.location.pathname + '/download'
+ const input = document.createElement('input')
+ input.type = 'hidden'
+ input.name = 'assets'
+ input.value = JSON.stringify(Array.from(selected))
+ form.appendChild(input)
+ document.body.appendChild(form)
+ form.submit()
+ form.remove()
+}
+
+function setupToolbar () {
+ toolbarEl = document.getElementById('select-toolbar')
+ // No toolbar means downloads aren't allowed for this share; nothing to wire
+ if (!toolbarEl) return
+ countEl = document.getElementById('select-count')
+ selectAllBtn = /** @type {HTMLButtonElement | null} */ (document.getElementById('select-all'))
+ cancelBtn = /** @type {HTMLButtonElement | null} */ (document.getElementById('select-cancel'))
+ downloadBtn = /** @type {HTMLButtonElement | null} */ (document.getElementById('select-download'))
+ if (cancelBtn) cancelBtn.addEventListener('click', exitSelectMode)
+ if (selectAllBtn) selectAllBtn.addEventListener('click', selectAllOrNone)
+ if (downloadBtn) downloadBtn.addEventListener('click', downloadSelected)
+ updateSelectionUI()
+}
+
+// ----- virtualization -------------------------------------------------------
+
+function getVisibleRange () {
+ const containerTop = container.getBoundingClientRect().top
+ const viewportTopInContainer = -containerTop
+ const viewportBottomInContainer = viewportTopInContainer + window.innerHeight
+ const buffer = window.innerHeight * BUFFER_VIEWPORTS
+ return {
+ top: viewportTopInContainer - buffer,
+ bottom: viewportBottomInContainer + buffer
+ }
+}
+
+function createHeader (header) {
+ const el = document.createElement('h2')
+ el.className = 'group-header'
+ el.style.top = header.top + 'px'
+ el.textContent = header.label
+ return el
+}
+
+function virtualize () {
+ if (!container || !layout.length) return
+ const { top, bottom } = getVisibleRange()
+
+ // Tiles
+ const neededTiles = new Set()
+ for (const l of layout) {
+ if (!l) continue
+ if (l.top + l.height < top) continue
+ if (l.top > bottom) break
+ neededTiles.add(l.index)
+ }
+ for (const [index, el] of renderedTiles) {
+ if (!neededTiles.has(index)) {
+ el.remove()
+ renderedTiles.delete(index)
+ }
+ }
+ for (const index of neededTiles) {
+ if (renderedTiles.has(index)) continue
+ const tile = createTile(index)
+ container.appendChild(tile)
+ renderedTiles.set(index, tile)
+ }
+
+ // Group headers (when grouping is enabled; headers is empty otherwise)
+ const neededHeaders = new Set()
+ for (const h of headers) {
+ if (h.top + h.height < top) continue
+ if (h.top > bottom) break
+ neededHeaders.add(h.label)
+ }
+ for (const [label, el] of renderedHeaders) {
+ if (!neededHeaders.has(label)) {
+ el.remove()
+ renderedHeaders.delete(label)
+ }
+ }
+ for (const label of neededHeaders) {
+ if (renderedHeaders.has(label)) continue
+ const h = headers.find(x => x.label === label)
+ if (!h) continue
+ const el = createHeader(h)
+ container.appendChild(el)
+ renderedHeaders.set(label, el)
+ }
+}
+
+function computeLayoutAndRender () {
+ if (!container) return
+ const containerW = container.clientWidth
+ if (containerW <= 0) return
+ if (containerW === lastContainerW) {
+ virtualize()
+ return
+ }
+ lastContainerW = containerW
+
+ const result = computeLayout(containerW)
+ layout = result.layout
+ headers = result.headers
+ container.style.height = result.totalHeight + 'px'
+
+ for (const [, el] of renderedTiles) el.remove()
+ renderedTiles.clear()
+ for (const [, el] of renderedHeaders) el.remove()
+ renderedHeaders.clear()
+
+ virtualize()
+ loadVisibleTiles()
+}
+
+// ----- image src lifecycle --------------------------------------------------
+
+function loadVisibleTiles () {
+ if (!container) return
+ const vpHeight = window.innerHeight
+ const containerTop = container.getBoundingClientRect().top
+ for (const a of renderedTiles.values()) {
+ const img = a.firstElementChild
+ if (!(img instanceof HTMLImageElement)) continue
+ const aTopInVp = containerTop + parseFloat(a.style.top || '0')
+ const aHeight = parseFloat(a.style.height || '0')
+ const isFar = aTopInVp + aHeight < -IMAGE_LOAD_MARGIN_PX ||
+ aTopInVp > vpHeight + IMAGE_LOAD_MARGIN_PX
+ if (isFar) {
+ if (img.src && !img.complete) {
+ img.dataset.src = img.src
+ img.removeAttribute('src')
+ }
+ } else if (img.dataset.src) {
+ img.src = img.dataset.src
+ img.removeAttribute('data-src')
}
}
}
-const lgallery = new LGallery()
\ No newline at end of file
+
+// ----- scroll handling ------------------------------------------------------
+
+let scrollFrame = null
+let loadTimer = null
+
+function onScroll () {
+ if (scrollFrame == null) {
+ scrollFrame = requestAnimationFrame(() => {
+ scrollFrame = null
+ virtualize()
+ })
+ }
+ if (loadTimer) clearTimeout(loadTimer)
+ loadTimer = setTimeout(() => {
+ loadTimer = null
+ loadVisibleTiles()
+ }, SCROLL_SETTLE_MS)
+}
+
+// ----- PhotoSwipe -----------------------------------------------------------
+
+function parseVideoData (item) {
+ try {
+ const data = JSON.parse(item.videoData || '{}')
+ const source = (data.source && data.source[0]) || {}
+ return { src: source.src || '', type: source.type || 'video/mp4' }
+ } catch (e) {
+ return { src: '', type: 'video/mp4' }
+ }
+}
+
+function escapeAttr (s) {
+ return String(s).replace(/&/g, '&').replace(/"/g, '"').replace(//g, '>')
+}
+
+function buildDataSource () {
+ return items.map(item => {
+ if (item.type === 'VIDEO') {
+ const v = parseVideoData(item)
+ return {
+ html:
+ '' +
+ '' +
+ '' +
+ ' ' +
+ '
'
+ }
+ }
+ return {
+ src: item.previewUrl,
+ width: item.width || 1600,
+ height: item.height || 1200,
+ msrc: item.thumbnailUrl,
+ alt: item.description || ''
+ }
+ })
+}
+
+function initLightbox () {
+ lightbox = new PhotoSwipeLightbox({
+ dataSource: buildDataSource(),
+ pswpModule: () => import('/share/static/photoswipe/photoswipe.esm.js'),
+ bgOpacity: 1,
+ showHideAnimationType: 'fade',
+ closeOnVerticalDrag: true,
+ arrowKeys: true,
+ loop: false,
+ padding: { top: 56, bottom: 56, left: 16, right: 16 }
+ })
+
+ // Download button (only registered if config enables it)
+ if (lightboxConfig.showDownload) {
+ lightbox.on('uiRegister', () => {
+ lightbox.pswp.ui.registerElement({
+ name: 'download-button',
+ order: 8,
+ isButton: true,
+ tagName: 'a',
+ ariaLabel: 'Download',
+ html: ICON_DOWNLOAD,
+ onInit: (el, pswp) => {
+ el.setAttribute('target', '_blank')
+ el.setAttribute('rel', 'noopener')
+ const update = () => {
+ const item = items[pswp.currIndex]
+ if (item && item.downloadUrl) {
+ el.href = item.downloadUrl
+ el.setAttribute('download', item.downloadFilename || '')
+ } else {
+ el.removeAttribute('href')
+ }
+ }
+ update()
+ pswp.on('change', update)
+ }
+ })
+ })
+ }
+
+ // Fullscreen toggle. Skipped on browsers without Fullscreen API support
+ // for arbitrary elements (notably iOS Safari on iPhone).
+ if (document.fullscreenEnabled) {
+ lightbox.on('uiRegister', () => {
+ lightbox.pswp.ui.registerElement({
+ name: 'fullscreen-button',
+ order: 9,
+ isButton: true,
+ html: ICON_FULLSCREEN,
+ onInit: (el, pswp) => {
+ const update = () => {
+ const active = document.fullscreenElement === pswp.element
+ el.innerHTML = active ? ICON_FULLSCREEN_EXIT : ICON_FULLSCREEN
+ el.setAttribute('aria-label', active ? 'Exit fullscreen' : 'Fullscreen')
+ el.setAttribute('title', active ? 'Exit fullscreen' : 'Fullscreen')
+ }
+ update()
+ el.addEventListener('click', () => {
+ if (document.fullscreenElement) {
+ document.exitFullscreen().catch(() => {})
+ } else {
+ pswp.element.requestFullscreen().catch(() => {})
+ }
+ })
+ document.addEventListener('fullscreenchange', update)
+ pswp.on('destroy', () => {
+ document.removeEventListener('fullscreenchange', update)
+ if (document.fullscreenElement === pswp.element) {
+ document.exitFullscreen().catch(() => {})
+ }
+ })
+ }
+ })
+ })
+ }
+
+ // Caption from EXIF description (only present when item.description is set;
+ // server-side gated on ipp.showMetadata.description). Content is already
+ // HTML-escaped in render.ts, so innerHTML assignment is safe.
+ lightbox.on('uiRegister', () => {
+ lightbox.pswp.ui.registerElement({
+ name: 'caption',
+ order: 9,
+ isButton: false,
+ appendTo: 'root',
+ onInit: (el, pswp) => {
+ el.classList.add('pswp__caption')
+ const render = () => {
+ const item = items[pswp.currIndex]
+ const text = (item && item.description) || ''
+ el.innerHTML = text
+ el.hidden = !text
+ }
+ render()
+ pswp.on('change', render)
+ }
+ })
+ })
+
+ // Hash navigation + back-button handling: push a history entry on open so
+ // the mobile back gesture closes the lightbox; sync the hash with the
+ // current slide as the user pages through.
+ lightbox.on('uiRegister', () => {
+ const pswp = lightbox.pswp
+ const item = items[pswp.currIndex]
+ if (item) {
+ history.pushState({ pswp: true }, '', '#' + item.id)
+ lightboxPushedHistory = true
+ }
+ pswp.on('change', () => {
+ const it = items[pswp.currIndex]
+ if (it) history.replaceState({ pswp: lightboxPushedHistory }, '', '#' + it.id)
+ })
+ pswp.on('close', () => {
+ scrollToCurrentSlide(pswp.currIndex)
+ const wasFromHistory = closingFromHistory
+ closingFromHistory = false
+ if (wasFromHistory) {
+ // popstate already moved us back; nothing more to do
+ lightboxPushedHistory = false
+ } else if (lightboxPushedHistory) {
+ // UI close (button / Esc / swipe-down): consume our pushed entry
+ closingFromHistory = true
+ lightboxPushedHistory = false
+ history.back()
+ } else {
+ history.replaceState(null, '', window.location.pathname + window.location.search)
+ }
+ })
+ })
+
+ window.addEventListener('popstate', () => {
+ if (closingFromHistory) {
+ // Our own history.back() during a UI-driven close
+ closingFromHistory = false
+ return
+ }
+ if (lightbox && lightbox.pswp && lightboxPushedHistory) {
+ closingFromHistory = true
+ lightbox.pswp.close()
+ }
+ })
+
+ // Optional control hiding (defaults match Immich's behavior)
+ const docEl = document.documentElement
+ if (!lightboxConfig.showArrows) docEl.classList.add('pswp-no-arrows')
+ if (!lightboxConfig.mobileArrows) docEl.classList.add('pswp-no-mobile-arrows')
+
+ lightbox.init()
+}
+
+function openLightbox (index) {
+ if (lightbox) lightbox.loadAndOpen(index)
+}
+
+/**
+ * Scroll the page so the tile for the given item is comfortably in view.
+ * Called from the lightbox close handler - if the user navigated prev/next
+ * inside the lightbox, or arrived via a #asset-id deep link, the tile they
+ * end on may be far from the original scroll position. We only scroll when
+ * the tile is genuinely off-screen, so closing on a still-visible tile
+ * doesn't jiggle the page.
+ */
+function scrollToCurrentSlide (index) {
+ if (!container || index == null || !layout[index]) return
+ const entry = layout[index]
+ const containerTop = container.getBoundingClientRect().top + window.scrollY
+ const tileTop = containerTop + entry.top
+ const tileBottom = tileTop + entry.height
+ const viewportTop = window.scrollY
+ const viewportBottom = viewportTop + window.innerHeight
+ // Already mostly visible - leave the scroll alone
+ if (tileTop >= viewportTop && tileBottom <= viewportBottom) return
+ // Center the tile vertically in the viewport
+ const targetScroll = tileTop - (window.innerHeight - entry.height) / 2
+ window.scrollTo({ top: Math.max(0, targetScroll), behavior: 'instant' })
+}
+
+// ----- entry point ----------------------------------------------------------
+
+function readInitParams () {
+ const el = document.getElementById('ipp-init')
+ if (!el) return {}
+ try { return JSON.parse(el.textContent || '{}') } catch (e) { return {} }
+}
+
+function init () {
+ const params = readInitParams()
+ items = params.items || []
+ lightboxConfig = params.lightboxConfig || {}
+ groupByDate = !!params.groupByDate
+ container = document.getElementById('gallery')
+ if (!container) return
+
+ setupToolbar()
+ initLightbox()
+
+ let resizeFrame
+ const resizeObserver = new ResizeObserver(() => {
+ if (resizeFrame) cancelAnimationFrame(resizeFrame)
+ resizeFrame = requestAnimationFrame(computeLayoutAndRender)
+ })
+ resizeObserver.observe(container)
+
+ window.addEventListener('scroll', onScroll, { passive: true })
+
+ // Deep-link: prefer #asset-id in the URL hash, fall back to ?openItem
+ const hash = window.location.hash.slice(1)
+ if (hash) {
+ const idx = items.findIndex(it => it.id === hash)
+ if (idx >= 0) openLightbox(idx)
+ } else if (params.openItem && params.openItem > 0 && params.openItem <= items.length) {
+ openLightbox(params.openItem - 1)
+ }
+}
+
+init()
diff --git a/app/src/functions.ts b/app/src/functions.ts
index 6f71f86..a40ef51 100644
--- a/app/src/functions.ts
+++ b/app/src/functions.ts
@@ -2,7 +2,7 @@ import dayjs from 'dayjs'
import { Response } from 'express-serve-static-core'
import { DownloadAll, SharedLink } from './types'
-let config = {}
+let config: { [key: string]: unknown } = {}
try {
if (process.env.CONFIG) {
// Attempt to parse docker-compose config string into JSON (if specified)
@@ -15,6 +15,56 @@ try {
console.log(e)
}
+// Backward-compatability shim for 1.x users with a legacy `lightGallery.*` config section
+if (config.lightGallery && typeof config.lightGallery === 'object') {
+ const lg = config.lightGallery as Record
+ const mobile = (lg.mobileSettings || {}) as Record
+ const ipp = (config.ipp || (config.ipp = {})) as Record
+ const lightbox = (ipp.lightbox || (ipp.lightbox = {})) as Record
+ // Only fill in fields the user hasn't already set on ipp.lightbox.
+ if (lightbox.showArrows === undefined && lg.controls !== undefined) {
+ lightbox.showArrows = !!lg.controls
+ }
+ if (lightbox.showDownload === undefined && lg.download !== undefined) {
+ lightbox.showDownload = !!lg.download
+ }
+ if (lightbox.mobileArrows === undefined && mobile.controls !== undefined) {
+ lightbox.mobileArrows = !!mobile.controls
+ }
+ console.log(
+ '[IPP] The `lightGallery` config section is deprecated; relevant keys ' +
+ 'have been mapped to `ipp.lightbox.*`. See README for the current options.'
+ )
+}
+
+// Backward-compat shim: gallery-related keys that used to live directly on
+// `ipp` now live under `ipp.gallery`. Map legacy keys forward, only filling
+// in fields the user hasn't already set on the new path.
+{
+ const ipp = (config.ipp || (config.ipp = {})) as Record
+ const galleryKeyMigrations: Array<[string, string]> = [
+ ['singleImageGallery', 'singleImage'],
+ ['singleItemAutoOpen', 'singleItemAutoOpen'],
+ ['showGalleryTitle', 'showTitle'],
+ ['showGalleryDescription', 'showDescription'],
+ ['groupGalleryByDate', 'groupByDate']
+ ]
+ const legacyPresent = galleryKeyMigrations.some(([oldKey]) => ipp[oldKey] !== undefined)
+ if (legacyPresent) {
+ const gallery = (ipp.gallery || (ipp.gallery = {})) as Record
+ for (const [oldKey, newKey] of galleryKeyMigrations) {
+ if (ipp[oldKey] !== undefined && gallery[newKey] === undefined) {
+ gallery[newKey] = ipp[oldKey]
+ }
+ }
+ console.log(
+ '[IPP] Top-level gallery keys (singleImageGallery, singleItemAutoOpen, ' +
+ 'showGalleryTitle, showGalleryDescription, groupGalleryByDate) are ' +
+ 'deprecated; please move them under `ipp.gallery.*`. See README.'
+ )
+ }
+}
+
/**
* Get a configuration option fron config.json using dotted notation.
*
@@ -22,7 +72,7 @@ try {
* @param [defaultOption] - Specify a default option to return if no configuation value is found
*
* @example
- * getConfigOption('ipp.singleImageGallery')
+ * getConfigOption('ipp.gallery.singleImage')
*/
export const getConfigOption = (path: string, defaultOption?: unknown) => {
const value = path.split('.').reduce((obj: { [key: string]: unknown }, key) => (obj || {})[key], config)
diff --git a/app/src/immich.ts b/app/src/immich.ts
index 7932671..52af23e 100644
--- a/app/src/immich.ts
+++ b/app/src/immich.ts
@@ -13,9 +13,38 @@ import dayjs from 'dayjs'
import { addResponseHeaders, canDownload, getConfigOption, log } from './functions'
import render from './render'
import { Response } from 'express-serve-static-core'
+import { h } from 'preact'
+import { renderPage } from './views/_render'
+import { Password } from './views/password'
import { respondToInvalidRequest } from './invalidRequestHandler'
import { encrypt } from './encrypt'
+/*
+ In-process cache for share-link lookups. Each direct-asset request (e.g.
+ `/share/photo/:key/:id/thumbnail`) re-validates the share by calling
+ getShareByKey, which for album shares also pulls the entire album asset
+ list from Immich. Without this cache, a gallery view of N tiles fans out
+ into N concurrent full-album fetches against Immich and serializes there,
+ pushing per-thumbnail latency into seconds. The cache holds Promises
+ (not resolved values) so concurrent cold misses coalesce into one upstream
+ call instead of stampeding.
+
+ CAUTION: a cache hit returns the SAME SharedLinkResult reference across
+ requests. Callers MUST treat the result (and its `link.assets`) as
+ read-only. In-place mutation persists for the cache lifetime and leaks
+ across concurrent requests. Current callers (notably the in-place
+ `share.assets.sort(...)` in render.ts) happen to be idempotent so this is
+ safe today, but new callers should clone before mutating.
+
+ Eviction is LRU: each cache hit moves the entry to the end of the Map's
+ insertion order, and overflow drops the oldest (least-recently-used)
+ entry. TTL handles freshness; size cap handles memory.
+*/
+type ShareCacheEntry = { promise: Promise; expiresAt: number }
+const shareCache = new Map()
+const shareCacheTtlMs = 120_000
+const shareCacheMax = 100
+
class Immich {
/**
* Make a request to Immich API. We're not using the SDK to limit
@@ -90,12 +119,11 @@ class Immich {
// Password required - show the visitor the password page
if (sharedLinkRes.passwordRequired) {
// `request.key` is already sanitised at this point, but it never hurts to be explicit
- const key = request.key.replace(/[^\w-]/g, '')
- res.render('password', {
- key,
- lgConfig: render.lgConfig,
+ const shareKey = request.key.replace(/[^\w-]/g, '')
+ res.send(renderPage(h(Password, {
+ shareKey,
notifyInvalidPassword: !!request.password
- })
+ })))
return
}
@@ -122,13 +150,13 @@ class Immich {
// This is an individual item (not a gallery)
log('Serving link ' + request.key)
const asset = link.assets[0]
- if (asset.type === AssetType.image && !getConfigOption('ipp.singleImageGallery') && !request.password) {
+ if (asset.type === AssetType.image && !getConfigOption('ipp.gallery.singleImage') && !request.password) {
// For photos, output the image directly unless configured to show a gallery,
// or unless it's a password-protected link
await render.assetBuffer(request, res, link.assets[0], ImageSize.preview)
} else {
// Show a gallery page
- const openItem = getConfigOption('ipp.singleItemAutoOpen', true) ? 1 : 0
+ const openItem = getConfigOption('ipp.gallery.singleItemAutoOpen', true) ? 1 : 0
await render.gallery(res, link, openItem)
}
} else {
@@ -139,10 +167,49 @@ class Immich {
}
/**
- * Query Immich for the SharedLink metadata for a given key.
- * The key is what is returned in the URL when you create a share in Immich.
+ * Query Immich for the SharedLink metadata for a given key, with a short
+ * in-process cache + in-flight de-duplication. See the cache notes at the
+ * top of this file for the why.
+ *
+ * The cache holds the full post-album-population SharedLinkResult, so warm
+ * hits skip both the `/shared-links/me` and `/albums/:id` round trips.
+ * Negative results (`valid: false`) and rejections are dropped from the
+ * cache immediately so a transient Immich blip doesn't poison the cache.
*/
async getShareByKey (key: string, password?: string, keyType: KeyType = KeyType.key): Promise {
+ const cacheKey = `${keyType}:${key}:${password ?? ''}`
+ const now = Date.now()
+ const cached = shareCache.get(cacheKey)
+ if (cached && cached.expiresAt > now) {
+ // Move-to-end to mark this entry as most-recently-used for LRU eviction
+ shareCache.delete(cacheKey)
+ shareCache.set(cacheKey, cached)
+ return cached.promise
+ }
+
+ const promise = this.fetchShareByKey(key, password, keyType)
+ shareCache.set(cacheKey, {
+ promise,
+ expiresAt: now + shareCacheTtlMs
+ })
+ if (shareCache.size > shareCacheMax) {
+ const oldest = shareCache.keys().next().value
+ if (oldest !== undefined && oldest !== cacheKey) shareCache.delete(oldest)
+ }
+ promise.then(
+ (result) => { if (!result?.valid) shareCache.delete(cacheKey) },
+ () => { shareCache.delete(cacheKey) }
+ )
+ return promise
+ }
+
+ /**
+ * Underlying fetch for getShareByKey. Always hits Immich; the public
+ * getShareByKey wraps this with the cache. Don't call this directly from
+ * outside the class — going through getShareByKey is what gives us the
+ * coalescing on cold misses.
+ */
+ private async fetchShareByKey (key: string, password?: string, keyType: KeyType = KeyType.key): Promise {
let link
const url = this.buildUrl(this.apiUrl() + '/shared-links/me', {
[keyType]: key,
@@ -235,7 +302,7 @@ class Immich {
}
/**
- * Get the content-type of a video, for passing back to lightGallery
+ * Get the content-type of a video, for the lightbox element
*/
async getVideoContentType (asset: Asset) {
const data = await this.request(this.buildUrl('/assets/' + encodeURIComponent(asset.id) + '/video/playback', {
diff --git a/app/src/index.ts b/app/src/index.ts
index 3ad7da6..ee8414e 100644
--- a/app/src/index.ts
+++ b/app/src/index.ts
@@ -8,9 +8,12 @@ import render from './render'
import dayjs from 'dayjs'
import { NextFunction, Request, Response } from 'express-serve-static-core'
import { Asset, AssetType, ImageSize, KeyType } from './types'
-import { addResponseHeaders, getConfigOption, toString } from './functions'
+import { addResponseHeaders, canDownload, getConfigOption, toString } from './functions'
import { decrypt, encrypt } from './encrypt'
import { respondToInvalidRequest } from './invalidRequestHandler'
+import { h } from 'preact'
+import { renderPage } from './views/_render'
+import { Home } from './views/home'
// Extend the Request type with a `password` property
declare module 'express-serve-static-core' {
@@ -28,10 +31,10 @@ app.use(cookieSession({
sameSite: 'strict',
secret: crypto.randomBytes(32).toString('base64url')
}))
-// Add the EJS view engine, to render the gallery page
-app.set('view engine', 'ejs')
-// For parsing the password unlock form
+// For parsing the password unlock form and POSTed JSON payloads
app.use(express.json())
+// For parsing the selective-download form POST (form-encoded body)
+app.use(express.urlencoded({ extended: false, limit: '1mb' }))
// Serve static assets from the 'public' folder as /share/static
app.use('/share/static', express.static('public', { setHeaders: addResponseHeaders }))
// Serve the same assets on /, to allow for /robots.txt and /favicon.ico
@@ -111,7 +114,51 @@ app.post('/share/unlock', async (req, res) => {
})
/*
- * [ROUTE] Catch accidental POST requests to share URLs (e.g. from browser history
+ * [ROUTE] Selective download - POST a list of asset IDs, get a zip of just those.
+ * The list arrives as a single "assets" form field containing a JSON array.
+ * Validates each ID against share.assets so the request can't pull anything
+ * outside the share.
+ */
+app.post('/:shareType(share|s)/:key/download', decodeCookie, async (req, res) => {
+ const keyType = immich.getKeyTypeFromShare(req.params.shareType)
+ let requestedIds: unknown
+ try {
+ requestedIds = JSON.parse(String(req.body?.assets ?? '[]'))
+ } catch (e) {
+ respondToInvalidRequest(res, 400, 'Malformed assets list')
+ return
+ }
+ if (!Array.isArray(requestedIds) || requestedIds.length === 0) {
+ respondToInvalidRequest(res, 400, 'No assets selected')
+ return
+ }
+
+ const result = await immich.getShareByKey(req.params.key, req.password, keyType)
+ if (!result?.valid || !result.link) {
+ respondToInvalidRequest(res, 404, 'Invalid share link')
+ return
+ }
+ if (result.passwordRequired) {
+ respondToInvalidRequest(res, 401, 'Password required')
+ return
+ }
+ if (!canDownload(result.link)) {
+ respondToInvalidRequest(res, 403, 'Downloads disabled for this share')
+ return
+ }
+
+ const requested = new Set(requestedIds.map(String))
+ const validAssets = result.link.assets.filter(a => requested.has(a.id))
+ if (validAssets.length === 0) {
+ respondToInvalidRequest(res, 400, 'No valid assets in selection')
+ return
+ }
+
+ await render.downloadAssets(res, result.link, validAssets)
+})
+
+/*
+ * [ROUTE] Catch accidental POST requests to share URLs (e.g. from browser history
* state issues) and force a clean GET redirect.
* See https://github.com/alangrainger/immich-public-proxy/pull/205
*/
@@ -185,7 +232,7 @@ app.get('/share/:type(photo|video)/:key/:id/:size?', decodeCookie, async (req, r
if (getConfigOption('ipp.showHomePage', true)) {
app.get(/^\/(|share)\/*$/, (_req, res) => {
addResponseHeaders(res)
- res.render('home')
+ res.send(renderPage(h(Home, {})))
})
}
diff --git a/app/src/render.ts b/app/src/render.ts
index f730465..a22af72 100644
--- a/app/src/render.ts
+++ b/app/src/render.ts
@@ -1,120 +1,124 @@
import immich from './immich'
import { Response } from 'express-serve-static-core'
import { Asset, AssetType, ImageSize, IncomingShareRequest, SharedLink } from './types'
-import { canDownload, escapeHtml, getConfigOption } from './functions'
+import { canDownload, escapeHtml, getConfigOption, log, toString } from './functions'
import archiver from 'archiver'
import { respondToInvalidRequest } from './invalidRequestHandler'
import { sanitize } from './includes/sanitize'
+import { h } from 'preact'
+import { renderPage } from './views/_render'
+import { Gallery, GalleryItem, GalleryProps } from './views/gallery'
class Render {
- lgConfig
-
- constructor () {
- this.lgConfig = getConfigOption('lightGallery', {})
- }
-
/**
- * Stream data from Immich back to the client
+ * Stream an asset from Immich back to the client.
+ *
+ * Errors from Immich are always reported to the client as 404 — see
+ * invalidRequestHandler. Upstream status codes are never surfaced. Trashed
+ * or locked assets are handled implicitly: Immich's own endpoints refuse
+ * to serve them, and the upstream failure surfaces as a client 404.
*/
async assetBuffer (req: IncomingShareRequest, res: Response, asset: Asset, size?: ImageSize | string) {
- // Get meta info regarding the asset
- const metaRes = await fetch(immich.buildUrl(immich.apiUrl() + '/assets/' + encodeURIComponent(asset.id), {
- key: asset.key
- }))
- const meta = await metaRes.json()
-
- // Make sure we should display this asset
- if (meta.isTrashed || meta.visibility === 'locked') {
- respondToInvalidRequest(res, 404, `Asset ${asset.id} is trashed or locked`)
- return
- }
-
- // Prepare the request
const headerList = ['content-type', 'content-length', 'last-modified', 'etag']
- size = immich.validateImageSize(size)
- let subpath, sizeQueryParam
+ const fetchHeaders: Record = {}
+ let subpath: string
+ let sizeQueryParam: string | undefined
+ let attachment = false
+
if (asset.type === AssetType.video) {
subpath = '/video/playback'
- } else if (asset.type === AssetType.image) {
- // For images, there are three combinations of path + query string, depending on image size
- if (size === ImageSize.original && getConfigOption('ipp.downloadOriginalPhoto', true)) {
- subpath = '/original'
- } else if (size === ImageSize.preview || size === ImageSize.original) {
- // IPP is configured in config.json to send the preview size instead of the original size
- subpath = '/thumbnail'
- sizeQueryParam = 'preview'
- } else {
- subpath = '/' + size
- }
- }
- const headers = { range: '' }
-
- // For videos, request them in 2.5MB chunks rather than the entire video
- if (asset.type === AssetType.video) {
+ // Stream videos in 2.5 MB chunks rather than the entire file
const range = (req.range || '').replace(/bytes=/, '').split('-')
const start = parseInt(range[0], 10) || 0
const end = parseInt(range[1], 10) || start + 2499999
- headers.range = `bytes=${start}-${end}`
+ fetchHeaders.range = `bytes=${start}-${end}`
headerList.push('cache-control', 'content-range')
res.setHeader('accept-ranges', 'bytes')
res.status(206) // Partial Content
+ } else {
+ const endpoint = this.resolveImageEndpoint(immich.validateImageSize(size))
+ subpath = endpoint.subpath
+ sizeQueryParam = endpoint.sizeQueryParam
+ attachment = endpoint.attachment
}
- // Request data from Immich
const url = immich.buildUrl(immich.apiUrl() + '/assets/' + encodeURIComponent(asset.id) + subpath, {
[asset.keyType || 'key']: asset.key,
size: sizeQueryParam,
password: asset.password
})
- const data = await fetch(url, { headers })
+ const data = await fetch(url, { headers: fetchHeaders })
- // Add the filename for downloaded assets
- if (size === ImageSize.original && asset.originalFileName && getConfigOption('ipp.downloadOriginalPhoto', true)) {
- res.setHeader('Content-Disposition', `attachment; filename="${this.getFilename(asset)}"`)
- }
-
- // Return the response to the client
- if (data.status >= 200 && data.status < 300) {
- // Populate the whitelisted response headers
- headerList.forEach(header => {
- const value = data.headers.get(header)
- if (value) res.setHeader(header, value)
- })
- // Return the Immich asset binary data
- await data.body?.pipeTo(
- new WritableStream({
- write (chunk) { res.write(chunk) }
- })
- )
- res.end()
- } else {
+ if (data.status < 200 || data.status >= 300) {
let immichMessage = ''
try {
const json = await data.json()
if (json.message) immichMessage = '\nResponse from Immich: ' + json.message
} catch (e) { }
respondToInvalidRequest(res, 404, 'Failed response from Immich for asset ' + asset.id + ' on this URL:\n' + url + immichMessage)
+ return
}
+
+ if (attachment && asset.originalFileName) {
+ res.setHeader('Content-Disposition', `attachment; filename="${this.getFilename(asset)}"`)
+ }
+ headerList.forEach(header => {
+ const value = data.headers.get(header)
+ if (value) res.setHeader(header, value)
+ })
+ await data.body?.pipeTo(
+ new WritableStream({
+ write (chunk) { res.write(chunk) }
+ })
+ )
+ res.end()
}
/**
- * Render a gallery page for a given SharedLink, using EJS and lightGallery.
+ * Map an ImageSize to the Immich endpoint that serves it.
+ *
+ * Policy: when `ipp.downloadOriginalPhoto` is off, requests for the original
+ * image are silently downgraded to preview — the operator has opted out of
+ * serving full-resolution files. (The original may also be a RAW/HEIC file
+ * the browser can't render.)
+ */
+ private resolveImageEndpoint (size: ImageSize): { subpath: string; sizeQueryParam?: string; attachment: boolean } {
+ const allowOriginal = getConfigOption('ipp.downloadOriginalPhoto', true)
+ if (size === ImageSize.original && allowOriginal) {
+ return { subpath: '/original', attachment: true }
+ }
+ if (size === ImageSize.thumbnail) {
+ return { subpath: '/thumbnail', attachment: false }
+ }
+ // preview, or original downgraded because downloadOriginalPhoto is off
+ return { subpath: '/thumbnail', sizeQueryParam: 'preview', attachment: false }
+ }
+
+ /**
+ * Render a gallery page for a given SharedLink.
*
* @param res - ExpressJS Response
* @param share - Immich `shared-link` containing the assets to show in the gallery
- * @param [openItem] - Immediately open a lightbox to the Nth item when the gallery loads
+ * @param [openItem] - Immediately open the lightbox to the Nth item when the gallery loads
*/
async gallery (res: Response, share: SharedLink, openItem?: number) {
// publicBaseUrl is used for the og:image, which requires a fully qualified URL.
// You can specify this in your docker-compose file, or send it dynamically as a `publicBaseUrl` header
const publicBaseUrl = process.env.PUBLIC_BASE_URL || res.req.headers.publicBaseUrl || (res.req.protocol + '://' + res.req.headers.host)
- // Use .map to generate an array of promises, then await them all to load in parallel.
- const items = await Promise.all(share.assets.map(async (asset) => {
- let video, downloadUrl
+ // Date grouping needs chronological order; sort newest-first when enabled
+ // (overrides any album.order the upstream applied).
+ const groupByDate = !!getConfigOption('ipp.gallery.groupByDate', false)
+ if (groupByDate) {
+ share.assets.sort((a, b) => (b.fileCreatedAt || '').localeCompare(a.fileCreatedAt || ''))
+ }
+
+ // Build structured items in parallel
+ const items: GalleryItem[] = await Promise.all(share.assets.map(async (asset): Promise => {
+ let videoData: string | undefined
+ let downloadUrl: string | undefined
if (asset.type === AssetType.video) {
- // Populate the data-video property
- video = JSON.stringify({
+ videoData = JSON.stringify({
source: [
{
src: immich.videoUrl(share.key, asset.id),
@@ -129,42 +133,58 @@ class Render {
downloadUrl = immich.videoUrl(share.key, asset.id)
}
if (getConfigOption('ipp.downloadOriginalPhoto', true)) {
- // Add a download link for the original-size image, if configured in config.json
downloadUrl = immich.photoUrl(share.key, asset.id, ImageSize.original)
}
const thumbnailUrl = immich.photoUrl(share.key, asset.id, ImageSize.thumbnail)
const previewUrl = immich.photoUrl(share.key, asset.id, immich.getPreviewImageSize(asset))
- const description = getConfigOption('ipp.showMetadata.description', false) && typeof asset?.exifInfo?.description === 'string' ? escapeHtml(asset.exifInfo.description) : ''
+ const description = getConfigOption('ipp.showMetadata.description', false) && typeof asset?.exifInfo?.description === 'string'
+ ? escapeHtml(asset.exifInfo.description)
+ : ''
- // Create the full HTML element source to pass to the gallery view
- const itemHtml = [
- video ? ` `,
- video ? '
' : '',
- ' '
- ].join('')
+ let width = asset.exifInfo?.exifImageWidth
+ let height = asset.exifInfo?.exifImageHeight
+ const orientation = asset.exifInfo?.orientation
+ if (orientation && ['5', '6', '7', '8'].includes(orientation) && width && height) {
+ [width, height] = [height, width]
+ }
return {
- html: itemHtml,
+ id: asset.id,
+ type: asset.type,
+ previewUrl,
thumbnailUrl,
- previewUrl
+ downloadUrl,
+ videoData,
+ description: description || undefined,
+ downloadFilename: this.getFilename(asset),
+ width,
+ height,
+ thumbhash: asset.thumbhash,
+ fileCreatedAt: asset.fileCreatedAt
}
}))
- res.render('gallery', {
+ const downloadAllowed = canDownload(share)
+ const props: GalleryProps = {
items,
- openItem,
title: this.title(share),
- description: getConfigOption('ipp.showGalleryDescription', false) ? this.description(share) : '',
- publicBaseUrl,
+ description: getConfigOption('ipp.gallery.showDescription', false) ? this.description(share) : '',
+ publicBaseUrl: toString(publicBaseUrl),
path: '/share/' + share.key,
- showDownload: canDownload(share),
- showTitle: getConfigOption('ipp.showGalleryTitle', false),
- lgConfig: getConfigOption('lightGallery', {})
- })
+ showDownload: downloadAllowed,
+ showTitle: !!getConfigOption('ipp.gallery.showTitle', true),
+ openItem,
+ lightboxConfig: {
+ // Show download button only if downloading is allowed AND configured.
+ showDownload: downloadAllowed && !!getConfigOption('ipp.lightbox.showDownload', true),
+ showArrows: !!getConfigOption('ipp.lightbox.showArrows', true),
+ mobileArrows: !!getConfigOption('ipp.lightbox.mobileArrows', false)
+ },
+ groupByDate
+ }
+
+ res.send(renderPage(h(Gallery, props)))
}
/**
@@ -182,33 +202,110 @@ class Render {
}
/**
- * Download all assets as a zip file
+ * Download all assets in a share as a zip file.
*/
async downloadAll (res: Response, share: SharedLink) {
- const downloadOriginalAsset = getConfigOption('ipp.downloadOriginalPhoto', true)
+ await this.downloadAssets(res, share, share.assets)
+ }
+
+ /**
+ * Stream the given assets back as a zip file.
+ *
+ * Assets are fetched from Immich with a bounded concurrency (configurable via
+ * `ipp.downloadFromImmichConcurrencyLimit`, default 8) rather than all at once.
+ * Fetching every asset in parallel overwhelms the Immich server on large albums
+ * and causes the client download to time out before the first bytes are sent.
+ *
+ * Each asset is retried up to 3 times with linear backoff. If any asset still
+ * fails after retries, the in-flight download is aborted mid-stream: the
+ * archive is aborted, the HTTP response socket is destroyed, and the failure
+ * is logged. We do this (rather than silently omitting the asset) because by
+ * the time we know the asset failed we've already sent a 200 response to the
+ * client, so the only way to signal "your zip is incomplete" is to terminate
+ * the response — leaving the user with a visibly broken/truncated download
+ * instead of a zip that's quietly missing files.
+ */
+ async downloadAssets (res: Response, share: SharedLink, assets: Asset[]) {
+ const concurrency = Math.max(1, getConfigOption('ipp.downloadFromImmichConcurrencyLimit', 8) as number)
+ const endpoint = this.resolveImageEndpoint(ImageSize.original)
res.setHeader('Content-Type', 'application/zip')
let filename = (sanitize(this.title(share)) || 'photos') + '.zip'
filename = encodeURI(filename)
res.setHeader('Content-Disposition', `attachment; filename*=UTF-8''${filename}`)
const archive = archiver('zip', { zlib: { level: 6 } })
archive.pipe(res)
- await Promise.all(share.assets.map(async (asset) => {
- const endpoint = downloadOriginalAsset ? 'original' : 'thumbnail'
- const url = immich.buildUrl(immich.apiUrl() + '/assets/' + encodeURIComponent(asset.id) + '/' + endpoint, {
- key: asset.key,
- password: asset.password,
- size: downloadOriginalAsset ? '' : 'preview'
- })
- const data = await fetch(url)
- // Check the response for validity
- if (!data.ok) {
- console.warn(`Failed to fetch asset: ${asset.id}`)
- return
+
+ let aborted = false
+ let failure: { asset: Asset, url: string, status?: number, error?: unknown } | null = null
+ const fail = (info: { asset: Asset, url: string, status?: number, error?: unknown }) => {
+ if (!aborted) {
+ aborted = true
+ failure = info
}
- archive.append(Buffer.from(await data.arrayBuffer()), { name: this.getFilename(asset) })
- }))
+ }
+
+ const maxAttempts = 3
+ const queue = assets.slice()
+ const worker = async () => {
+ while (queue.length > 0) {
+ if (aborted) return
+ const asset = queue.shift()
+ if (!asset) return
+ const url = immich.buildUrl(immich.apiUrl() + '/assets/' + encodeURIComponent(asset.id) + endpoint.subpath, {
+ key: asset.key,
+ password: asset.password,
+ size: endpoint.sizeQueryParam
+ })
+
+ let buffer: Buffer | undefined
+ let lastStatus: number | undefined
+ let lastError: unknown
+ for (let attempt = 1; attempt <= maxAttempts; attempt++) {
+ if (aborted) return
+ try {
+ const data = await fetch(url, { signal: AbortSignal.timeout(20_000) })
+ if (data.ok) {
+ buffer = Buffer.from(await data.arrayBuffer())
+ break
+ }
+ lastStatus = data.status
+ lastError = undefined
+ } catch (e) {
+ lastError = e
+ lastStatus = undefined
+ }
+ if (attempt < maxAttempts) {
+ const reason = lastStatus !== undefined
+ ? `HTTP ${lastStatus}`
+ : (lastError instanceof Error ? lastError.message : String(lastError))
+ log(`Retrying asset ${asset.id} (attempt ${attempt + 1}/${maxAttempts}) after ${reason}`)
+ // Linear backoff between attempts to avoid hammering a struggling server.
+ await new Promise(resolve => setTimeout(resolve, 500 * attempt))
+ }
+ }
+
+ if (!buffer) {
+ fail({ asset, url, status: lastStatus, error: lastError })
+ return
+ }
+ if (aborted) return
+ archive.append(buffer, { name: this.getFilename(asset) })
+ }
+ }
+ await Promise.all(Array.from({ length: concurrency }, () => worker()))
+
+ if (aborted && failure) {
+ const f = failure as { asset: Asset, url: string, status?: number, error?: unknown }
+ const detail = f.status !== undefined
+ ? `HTTP ${f.status}`
+ : (f.error instanceof Error ? f.error.message : String(f.error))
+ log(`Aborting zip download for share ${share.key}: failed to fetch asset ${f.asset.id} from ${f.url} (${detail})`)
+ archive.abort()
+ res.destroy()
+ return
+ }
+
await archive.finalize()
- archive.on('end', () => res.end())
}
/**
diff --git a/app/src/types.ts b/app/src/types.ts
index 7a95367..18e4a2c 100644
--- a/app/src/types.ts
+++ b/app/src/types.ts
@@ -12,6 +12,11 @@ export enum KeyType {
export interface ExifInfo {
description?: string;
+ exifImageWidth?: number;
+ exifImageHeight?: number;
+ // EXIF orientation string ("1".."8") or null. Values 5-8 indicate the image
+ // is rotated 90°/270°, so the displayed aspect ratio swaps width/height.
+ orientation?: string | null;
}
export enum AlbumType {
@@ -30,6 +35,8 @@ export interface Asset {
type: AssetType;
isTrashed: boolean;
exifInfo?: ExifInfo;
+ // Base64-encoded thumbhash for tasteful blur placeholders during lazy-load
+ thumbhash?: string;
}
export interface Album {
diff --git a/app/src/views/_render.ts b/app/src/views/_render.ts
new file mode 100644
index 0000000..9cb82f5
--- /dev/null
+++ b/app/src/views/_render.ts
@@ -0,0 +1,10 @@
+import { renderToString } from 'preact-render-to-string'
+import { VNode } from 'preact'
+
+/**
+ * Render a JSX component to a complete HTML response string.
+ * Prepends the doctype so the result is a valid HTML5 document.
+ */
+export function renderPage (component: VNode): string {
+ return '' + renderToString(component)
+}
diff --git a/app/src/views/_theme.tsx b/app/src/views/_theme.tsx
new file mode 100644
index 0000000..5017c3f
--- /dev/null
+++ b/app/src/views/_theme.tsx
@@ -0,0 +1,25 @@
+// Mirrors Immich's FOUC-prevention pattern: read color-theme from localStorage
+// (or fall back to OS preference), then add/remove .dark on before paint.
+// Source: immich-app/immich v2.7.5 web/src/app.html (2026-05-23).
+const themeScript = `
+ const key = 'color-theme';
+ let theme = localStorage.getItem(key);
+ if (!theme) {
+ theme = { value: 'light', system: true };
+ } else if (theme === 'dark' || theme === 'light') {
+ theme = { value: theme, system: false };
+ localStorage.setItem(key, JSON.stringify(theme));
+ } else {
+ theme = JSON.parse(theme);
+ }
+ let v = theme.value;
+ if (theme.system) {
+ v = window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
+ }
+ if (v === 'dark') document.documentElement.classList.add('dark');
+ else document.documentElement.classList.remove('dark');
+`
+
+export function ThemeScript () {
+ return
+}
diff --git a/app/src/views/gallery.tsx b/app/src/views/gallery.tsx
new file mode 100644
index 0000000..b52d9e4
--- /dev/null
+++ b/app/src/views/gallery.tsx
@@ -0,0 +1,133 @@
+import { AssetType } from '../types'
+import { ThemeScript } from './_theme'
+
+export interface GalleryItem {
+ id: string
+ type: AssetType
+ previewUrl: string
+ thumbnailUrl: string
+ downloadUrl?: string
+ // pre-stringified JSON describing the video source (used to build a
+ // element for video slides in the PhotoSwipe lightbox)
+ videoData?: string
+ // already-escaped HTML fragment used as a caption in the lightbox
+ description?: string
+ downloadFilename: string
+ // Display dimensions after EXIF orientation correction; needed for the
+ // pre-computed justified-rows layout that virtualization depends on.
+ width?: number
+ height?: number
+ // Base64-encoded thumbhash for an optional blur placeholder behind each tile
+ thumbhash?: string
+ // ISO date string from Immich; used to group tiles by month when enabled.
+ fileCreatedAt?: string
+}
+
+export interface LightboxConfig {
+ showArrows: boolean
+ showDownload: boolean
+ mobileArrows: boolean
+}
+
+export interface GalleryProps {
+ items: GalleryItem[]
+ title: string
+ description: string
+ publicBaseUrl: string
+ path: string
+ showDownload: boolean
+ showTitle: boolean
+ openItem?: number
+ lightboxConfig: LightboxConfig
+ groupByDate: boolean
+}
+
+export function Gallery (props: GalleryProps) {
+ const initJson = JSON.stringify({
+ items: props.items,
+ openItem: props.openItem,
+ lightboxConfig: props.lightboxConfig,
+ groupByDate: props.groupByDate
+ })
+ const firstItem = props.items[0]
+ const ogImageUrl = firstItem ? props.publicBaseUrl + firstItem.previewUrl : ''
+
+ return (
+
+
+
+
+ {props.title}
+
+
+ {props.description && <>
+
+
+
+ >}
+ {firstItem && <>
+
+
+
+ >}
+
+
+
+
+
+
+ {(props.showTitle || props.showDownload) && (
+
+ )}
+ {props.description && (
+ {props.description}
+ )}
+{/* Container is intentionally empty - web.js's virtualization manager
+ populates it with only the tiles within the viewport buffer. */}
+
+ {props.showDownload && (
+
+ )}
+ {/* Init params for web.js (read at module load). Using a JSON script
+ block avoids the cross-script-type coordination problems that come
+ with mixing classic and module scripts. */}
+
+
+
+
+ )
+}
diff --git a/app/src/views/home.tsx b/app/src/views/home.tsx
new file mode 100644
index 0000000..8edc9e9
--- /dev/null
+++ b/app/src/views/home.tsx
@@ -0,0 +1,37 @@
+export function Home () {
+ return (
+
+
+
+
+
+
+
+
+
+
+
+ )
+}
diff --git a/app/src/views/password.tsx b/app/src/views/password.tsx
new file mode 100644
index 0000000..75f76e9
--- /dev/null
+++ b/app/src/views/password.tsx
@@ -0,0 +1,72 @@
+interface PasswordProps {
+ shareKey: string
+ notifyInvalidPassword: boolean
+}
+
+const submitScript = `
+ async function submitForm (formElement) {
+ const formData = new FormData(formElement)
+ try {
+ const res = await fetch('/share/unlock', {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify(Object.fromEntries(formData.entries()))
+ })
+ if (res.status === 200) {
+ window.location.reload()
+ }
+ } catch (e) { }
+ }
+
+ document.getElementById('unlock')
+ .addEventListener('submit', function (e) {
+ e.preventDefault()
+ submitForm(this)
+ })
+`
+
+export function Password ({ shareKey, notifyInvalidPassword }: PasswordProps) {
+ return (
+
+
+
+ Password required
+
+
+
+
+
+
+
+
+
+
+
+ )
+}
diff --git a/app/tsconfig.json b/app/tsconfig.json
index b6b280e..789304d 100644
--- a/app/tsconfig.json
+++ b/app/tsconfig.json
@@ -19,9 +19,12 @@
"ES6",
"ES7"
],
- "allowSyntheticDefaultImports": true
+ "allowSyntheticDefaultImports": true,
+ "jsx": "react-jsx",
+ "jsxImportSource": "preact"
},
"include": [
- "**/*.ts"
+ "**/*.ts",
+ "**/*.tsx"
]
}
diff --git a/app/views/gallery.ejs b/app/views/gallery.ejs
deleted file mode 100644
index 6391614..0000000
--- a/app/views/gallery.ejs
+++ /dev/null
@@ -1,76 +0,0 @@
-
-
-
-
- <%# Meta tags for link previews (title, optionally description and thumbnail) %>
- <%= title %>
-
-
- <% if (description) { %>
-
-
-
- <% } %>
- <%
- // Add an og-image using the first image's thumbnail
- if (items?.[0]?.previewUrl) {
- %>
-
-
-
- <% } %>
-
-
-
-
-
-
-<% if (description) { %>
-
-
<%= description %>
-
-<% } %>
-
- <%
- // Load the first 50 thumbnails, then load more as the user scrolls. See web.js
- items.slice(0, 50).forEach(item => {
- %><%- item.html %>
- <% }) %>
-
-<% if (items.length > 50) { %>
<% } %>
-
-
-
-
-
-
-
-
-
-
diff --git a/app/views/home.ejs b/app/views/home.ejs
deleted file mode 100644
index cdc7eb9..0000000
--- a/app/views/home.ejs
+++ /dev/null
@@ -1,30 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/app/views/password.ejs b/app/views/password.ejs
deleted file mode 100644
index 4ac5d42..0000000
--- a/app/views/password.ejs
+++ /dev/null
@@ -1,78 +0,0 @@
-
-
-
-
- Password required
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/docs/screenshot.webp b/docs/screenshot.webp
index f107fa0..1b5091e 100644
Binary files a/docs/screenshot.webp and b/docs/screenshot.webp differ