commit 38cf95d55fb7b63aeffb8724907f7f0a8ee1a083 Author: Rui Carmo Date: Sat Dec 13 10:19:52 2025 +0000 initial import diff --git a/.github/copilot-instructions.md b/.github/copilot-instructions.md new file mode 100644 index 0000000..ed04b3e --- /dev/null +++ b/.github/copilot-instructions.md @@ -0,0 +1,22 @@ +# TRMNL Server + +This project is an e-ink device server that allows a client to connect to it and generates images and data for display on TRMNL e-ink devices. + +## Coding Style Guidelines + +When contributing to this project, please adhere to the following coding style guidelines: + +* DO NOT CREATE NEW CODE FILES unless explicitly told to. +* SPACES, not TABS, for indentation. Use 4 spaces per indentation level. +* Code in a functional style, with concise functions that do one thing only. +* NEVER duplicate code. Always re-use existing code or create new helper functions. If they are reusable, add them to `utils.py` or `models.py` as appropriate. +* When importing, prefer explicit imports (`from sys import stderr`) rather than just importing the module. A critical example is doing `from os.path import join, dirname, abspath` instead of `import os` and then using `os.path.join()`, etc. Never mind how many imports this creates; explicit imports are preferred for clarity. +* Inside a package, prefer package-relative imports (`from .utils import helper_function`) rather than absolute imports (`from trmnl_server.utils import helper_function`). +* When creating new functions, include type hints for all parameters and return values. +* Do not create one-liner wrappers around existing/internal module functions unless absolutely necessary. Use the public ones instead. +* When considering creating utility functions, try not to create one or two-liners. Inline the logic instead if they are that simple. +* Add utility functions to `utils.py` and constants to `config.py`, making sure to import them where needed and that any major configuration parameters are handled in a consistent way. +* NEVER add import statements inside functions or methods. Add any and all imports at the top of the file. +* Only perform database operations in `models.py`. Create or re-use new helpers there as needed. +* Before writing new helpers or adding inline logic for things that might be reusable, check if there are existing ones that can be re-used or adapted in `utils.py` or `models.py`. + diff --git a/.github/workflows/pylint.yml b/.github/workflows/pylint.yml new file mode 100644 index 0000000..00bc32f --- /dev/null +++ b/.github/workflows/pylint.yml @@ -0,0 +1,33 @@ +name: Pylint + +on: [push] + +jobs: + build: + runs-on: ubuntu-latest + strategy: + matrix: + python-version: ["3.9", "3.10"] + steps: + - uses: actions/checkout@v4 + - name: Set up Python ${{ matrix.python-version }} + uses: actions/setup-python@v3 + with: + python-version: ${{ matrix.python-version }} + - name: Install dependencies + run: | + python -m pip install --upgrade pip + pip install pylint astroid + pip install -r requirements.txt + - name: Analysing the code with pylint + run: | + pylint_output=$(pylint $(git ls-files '*.py') --output-format=parseable | tee pylint.log) + echo "$pylint_output" + SCORE=$(echo "$pylint_output" | awk -F ' ' '/Your code has been rated at/ {print $7}' | cut -d'/' -f1) + if (( $(echo "$SCORE >= 9.0" | bc -l) )); then + echo "Pylint score ($SCORE) is acceptable." + exit 0 + else + echo "Pylint score ($SCORE) is too low." + exit 1 + fi diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..28d9750 --- /dev/null +++ b/.gitignore @@ -0,0 +1,15 @@ +.DS_Store +trmnl_log.json +db/clientData.txt +logs/server.log +ssl/cert.pem +config.yaml +ssl/key.pem +db/clientLog.txt +trmnl.db +venv/* +__pycache__/* +web/*.bmp +web/*.png +*.pyc +var/ diff --git a/.vscode/settings.json b/.vscode/settings.json new file mode 100644 index 0000000..9b38853 --- /dev/null +++ b/.vscode/settings.json @@ -0,0 +1,7 @@ +{ + "python.testing.pytestArgs": [ + "tests" + ], + "python.testing.unittestEnabled": false, + "python.testing.pytestEnabled": true +} \ No newline at end of file diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..027c6c6 --- /dev/null +++ b/LICENSE @@ -0,0 +1,23 @@ +MIT License + +Based on previous work by the original project owner: https://github.com/ohAnd/trmnlServer + +Copyright (c) 2025 Rui Carmo + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. \ No newline at end of file diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..f5a5754 --- /dev/null +++ b/Makefile @@ -0,0 +1,18 @@ +PYTHON ?= python3 +MODULE ?= trmnl_server +ARGS ?= +export SERVER_PORT ?= 4567 + +.PHONY: serve test clean +serve: + $(PYTHON) -m $(MODULE) $(ARGS) + +test: + $(PYTHON) -m pytest -q tests + +clean: + find . -name '__pycache__' -type d -prune -exec rm -rf {} + + find . -name '*.pyc' -delete + rm -rf .pytest_cache .coverage + rm -rf var/generated + rm -rf var/db diff --git a/OFL.txt b/OFL.txt new file mode 100644 index 0000000..cb512b9 --- /dev/null +++ b/OFL.txt @@ -0,0 +1,93 @@ +Copyright 2020 The Space Grotesk Project Authors (https://github.com/floriankarsten/space-grotesk) + +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 & 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/README.md b/README.md new file mode 100644 index 0000000..1db4b10 --- /dev/null +++ b/README.md @@ -0,0 +1,97 @@ +# TRMNL Local Server + +This is a self-hosted FastAPI backend that emulates the TRMNL cloud so e-paper devices can fetch fresh images and metadata from your local network. + +![Obligatory screenshot](docs/playlist.png) + +It is loosely based on a Flask implementation by [@ohAnd](https://github.com/ohAnd/trmnlServer), rewritten (nearly) from scratch to use FastAPI, async I/O, and a plugin-driven architecture for rendering various charts and images, prioritizing greyscale output suitable for later firmware versions but allowing you to force 1-bit BMP for legacy devices on a per-item basis + +The server maintains device/playlists in SQLite, renders plugin-driven charts/photos into BMP/PNG assets, and exposes `/api/display` plus legacy-compatible endpoints expected by the firmware. + +## Non-Goals + +- **Full feature parity with the official TRMNL cloud** – this is a lightweight server for personal use, not a 1:1 clone of the official backend. +- **Advanced security features** – while SSL is supported (but disabled by default to save battery), user authentication, multi-user support, and other advanced features are out of scope. +- **Extensive plugin library** – only a few example plugins are provided; users are encouraged to write their own. +- **Web dashboard for management** – a minimal static UI is included for previewing plugin outputs, but no full-featured admin panel. +- **Browser-based rendering** – all image generation is done server-side using Python libraries to minimize system requirements. + +## Highlights + +- **FastAPI core** – `trmnl_server/main.py` hosts the HTTP API, static assets under `/web`, and middleware-level request logging. +- **Plugin rendering pipeline** – classes in `plugins/` generate images (BMP for the panel, grayscale PNG previews) using Pillow, httpx, pandas, etc. +- **Device + playlist persistence** – SQLAlchemy models in `models.py` keep per-device rotation state, playlists, logs, and battery samples in `var/db/trmnl.db`. +- **Autodiscovered plugin scheduler** – background workers keep assets fresh; see **Plugins & registry** for discovery rules and toggles. +- **Firmware compatibility** – `/api/display` always returns a single `image_url` plus a changing `filename` token so ESP32-based firmware knows when to refresh. +- **Batteries-included tooling** – `Makefile` wraps `make serve` (launch FastAPI via `python -m trmnl_server`) and `make test` (pytest). Plugins can be previewed via helper scripts under the repo root. +- **Color grading + dithering** – "color" grading and multiple dithering algorithms are available to improve image quality on e-ink panels. + +## Deployment + +I am deploying this with `kata`, a Docker-based service manager I wrote, but any method that can run a FastAPI app will work. + +## Running Locally + +```bash +git clone https://github.com/rcarmo/trmnlServer.git +cd trmnlServer +python3 -m venv .venv && source .venv/bin/activate +pip install -r requirements.txt +make serve +``` + +The server logs which port it binds to (default `SERVER_PORT=4567`). Point your TRMNL device at `http://:`. + +Useful commands: + +- `make serve` – start FastAPI using the current working directory as the runtime root. +- `SERVER_PORT=8081 make serve` – override port for quick tests. +- `make serve ARGS=/path/to/workdir` – run the server against a different working directory (`var/` contents plus SSL/generated assets) without touching your source tree. +- `python -m trmnl_server --list-plugins` – print the plugin registry (names + defaults) and exit. +- `python -m trmnl_server --run-plugin WeatherPlugin --plugin-output /tmp --plugin-arg image_root=/path` – run a single plugin once for debugging with optional keyword arguments. +- `make test` – run `pytest` (`tests/test_rotation.py`, `tests/test_plugins.py`, `tests/test_weather.py`). + +## Configuration + +All settings come from environment variables: + +- `SERVER_PORT`, `ENABLE_SSL` – networking defaults (4567/False out of the box, set `ENABLE_SSL=true` when you need TLS). +- `IMAGE_PATH`, `REFRESH_TIME`, `DITHERING_MODE` – rendering and dithering behaviour. +- `PHOTO_GRADING_ENABLED` – enable/disable photographic grading for image-heavy plugins (default: true). +- `EINK_TONE_POINTS`, `EINK_TONE_GAMMA` – optional grayscale response compensation points/gamma for panel-space quantization. +- `BATTERY_MAX_VOLTAGE`, `BATTERY_MIN_VOLTAGE`, `TIME_ZONE` – telemetry scaling. +- `SETUP_API_KEY`, `SETUP_FRIENDLY_ID`, `SETUP_MESSAGE` – `/api/setup` payload fields. +- `ASSETS_ROOT`, `STATIC_ROOT`, `GENERATED_ROOT` – relative directories (inside the working dir) for dashboard assets and generated BMP/PNG output (defaults: `web`, `web`, and `var/generated`). +- `CALIBRATION_PLUGIN_ENABLED` – set to `false` to remove calibration plugins from the registry and skip generating calibration assets. + +Whenever a setting is changed via the `/settings/*` endpoints, the new value is written to SQLite (table `config_entries`). On startup, `config.py` loads environment variables first (highest precedence) and then applies any persisted entries that are not overridden by the environment, so API-driven tweaks survive restarts without fighting `SERVER_PORT=...` overrides in your shell. + +Runtime artefacts now consolidate under `var/` inside your chosen working directory: + +- `var/db/trmnl.db` – SQLite database plus future state. +- `var/logs/` – reserved for future log sinks. +- `var/generated/` – plugin BMP/PNG output served via `/generated/*`. +- `var/ssl/` – self-signed certs generated automatically if SSL is enabled. + +FastAPI creates these directories during startup if they are missing, and `.gitignore` keeps `var/` out of version control. + +## Plugins & registry + +- Plugins are auto-discovered from `trmnl_server/plugins/` by the scheduler; any class inheriting `PluginBase` with `AUTO_REGISTER=True` is registered. +- Set `AUTO_REGISTER = False` on a plugin class to opt it out of the registry. +- Set `CALIBRATION_PLUGIN_ENABLED=false` (ENV or `/settings`) to remove all calibration plugins from the registry and skip generating calibration assets. +- `python -m trmnl_server --list-plugins` shows the active registry; `--run-plugin ` respects these toggles. + +## API + Static Surface + +| Path | Description | +| --------------------------------------------- | ---------------------------------------------------------------------------------------------- | +| `GET /api/display` | Main firmware endpoint: returns `image_url`, `filename`, refresh hints, and playlist metadata. | +| `POST /api/log` | Device log ingestion recorded via SQLAlchemy. | +| `POST /api/battery` | Battery + RSSI samples persisted to `BatteryStatus`. | +| `GET /image/screen.bmp` / `screen1.bmp` | Alternating BMP endpoints to break caches. | +| `GET /image/grayscale.png` / `grayscale1.png` | Optional grayscale preview for firmware that supports it. | +| `GET /web/*` | Static dashboard assets (HTML/JS/CSS/fonts and fallback imagery). | +| `GET /generated/*` | Runtime plugin output (BMP/PNG) served as-is. | + +The UI under `web/` shows plugin output previews and rotation metadata; templates in `templates/` are used by specific plugins (e.g., weather renderer). diff --git a/docs/playlist.png b/docs/playlist.png new file mode 100644 index 0000000..212ef9d Binary files /dev/null and b/docs/playlist.png differ diff --git a/kata-compose.yaml b/kata-compose.yaml new file mode 100644 index 0000000..ebd463b --- /dev/null +++ b/kata-compose.yaml @@ -0,0 +1,25 @@ +version: "3.9" + +services: + trmnl-server: + container_name: trmnl-server + runtime: python + ports: + - "4567:4567" + environment: + # Override as needed (examples): + SERVER_PORT: "4567" + ENABLE_SSL: false + PYTHONIOENCODING: "UTF_8:replace" + PYTHONUNBUFFERED: 1 + PYTHONPATH: "/app" + LANG: "en_US.UTF-8" + LC_ALL: "en_US.UTF-8" + TZ: "Europe/Lisbon" + # CALIBRATION_PLUGIN_ENABLED: "true" + # PHOTO_GRADING_ENABLED: "true" + # ASSETS_ROOT: "web" + # STATIC_ROOT: "web" + # GENERATED_ROOT: "var/generated" + command: python3 -u -m trmnl_server + restart: unless-stopped diff --git a/pytest.ini b/pytest.ini new file mode 100644 index 0000000..a635c5c --- /dev/null +++ b/pytest.ini @@ -0,0 +1,2 @@ +[pytest] +pythonpath = . diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..512b619 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,13 @@ +pillow>=10.3.0 +fastapi>=0.109.0 +uvicorn>=0.27.0 +python-multipart>=0.0.9 +psutil>=5.9.4 +PyYAML>=6.0 +httpx>=0.27.0 +sqlalchemy>=2.0.0 +d3blocks>=1.0.0 +html2image>=2.0.0 +pandas>=2.0.0 +feedparser>=6.0.10 +pytest>=8.2.0 \ No newline at end of file diff --git a/tests/test_plugins.py b/tests/test_plugins.py new file mode 100644 index 0000000..ce42771 --- /dev/null +++ b/tests/test_plugins.py @@ -0,0 +1,214 @@ +from io import BytesIO +from pathlib import Path +from typing import Any, Dict, List, Tuple +from unittest.mock import AsyncMock, patch + +import pytest +from PIL import Image + +from trmnl_server.plugins.base import PluginOutput +from trmnl_server.plugins.bing import BingWallpaperPlugin +from trmnl_server.plugins.hn import HNPlugin +from trmnl_server.plugins.random_image import RandomImagePlugin +try: + from trmnl_server.plugins.charts import PageviewsPlugin, VisitorsPlugin # type: ignore[attr-defined] +except ModuleNotFoundError: + PageviewsPlugin = None + VisitorsPlugin = None +from trmnl_server.plugins.xkcd import XKCDPlugin +from trmnl_server.plugins.weather import WeatherPlugin +from trmnl_server.services import plugins as plugin_service +from trmnl_server import config + +pytestmark = pytest.mark.asyncio + +def _make_image_bytes(size: Tuple[int, int] = (32, 32), color: Tuple[int, int, int] = (255, 0, 0)) -> bytes: + img = Image.new('RGB', size, color=color) + buffer = BytesIO() + img.save(buffer, format='PNG') + return buffer.getvalue() + + +def _make_image(size: Tuple[int, int] = (32, 32), color: Tuple[int, int, int] = (0, 255, 0)) -> Image.Image: + return Image.open(BytesIO(_make_image_bytes(size=size, color=color))).convert('RGB') + + +def _plugin_available(plugin_name: str) -> bool: + available = {name.lower() for name in plugin_service.list_available_plugins()} + return plugin_name.lower() in available + + +def _assert_output_assets(output: PluginOutput) -> None: + mono = Path(output.monochrome_path) + gray = Path(output.grayscale_path) + assert mono.is_file() and mono.stat().st_size > 0 + assert gray.is_file() and gray.stat().st_size > 0 + + +async def test_bing_plugin_generates_assets(tmp_path: Path) -> None: + if not _plugin_available(BingWallpaperPlugin.__name__): + pytest.skip('BingWallpaperPlugin not available') + plugin_cls = plugin_service.get_plugin_schedule(BingWallpaperPlugin.__name__).plugin_cls + plugin = plugin_cls() + fake_metadata = {"url": "http://example.com/test_wallpaper.png"} + + with patch.object(plugin, '_fetch_metadata', new=AsyncMock(return_value=fake_metadata)), \ + patch.object(plugin, '_download_image', new=AsyncMock(return_value=_make_image_bytes())): + output = await plugin.run(output_dir=str(tmp_path)) + + assert isinstance(output, PluginOutput) + _assert_output_assets(output) + + +async def test_xkcd_plugin_generates_assets(tmp_path: Path) -> None: + if not _plugin_available(XKCDPlugin.__name__): + pytest.skip('XKCDPlugin not available') + plugin_cls = plugin_service.get_plugin_schedule(XKCDPlugin.__name__).plugin_cls + plugin = plugin_cls() + fake_metadata = { + "img": "http://example.com/comic.png", + "safe_title": "Test XKCD", + "alt": "Alt text", + "transcript": "Transcript text" + } + + with patch.object(plugin, '_fetch_metadata', new=AsyncMock(return_value=fake_metadata)), \ + patch.object(plugin, '_download_image', new=AsyncMock(return_value=_make_image_bytes())), \ + patch.object(plugin, '_load_image', return_value=_make_image()): + output = await plugin.run(output_dir=str(tmp_path)) + + assert isinstance(output, PluginOutput) + _assert_output_assets(output) + + +async def test_hn_plugin_generates_assets(tmp_path: Path) -> None: + if not _plugin_available(HNPlugin.__name__): + pytest.skip('HNPlugin not available') + plugin_cls = plugin_service.get_plugin_schedule(HNPlugin.__name__).plugin_cls + plugin = plugin_cls() + fake_entries: List[Dict[str, Any]] = [ + {"title": "Test headline", "points": 123, "comments": 45}, + {"title": "Another headline", "points": 456, "comments": 78} + ] + + with patch.object(plugin, '_fetch_entries', new=AsyncMock(return_value=fake_entries)): + output = await plugin.run(output_dir=str(tmp_path)) + + assert isinstance(output, PluginOutput) + _assert_output_assets(output) + + +def _fake_stats_data() -> List[Tuple[str, int]]: + return [("00", 0), ("01", 10), ("02", 20), ("03", 5)] + + +async def test_pageviews_plugin_generates_assets(tmp_path: Path) -> None: + if PageviewsPlugin is None or not _plugin_available('PageviewsPlugin'): + pytest.skip('PageviewsPlugin not available') + plugin_cls = plugin_service.get_plugin_schedule('PageviewsPlugin').plugin_cls + plugin = plugin_cls() + fake_data = _fake_stats_data() + + with patch.object(plugin, '_fetch_series', new=AsyncMock(return_value=fake_data)): + output = await plugin.run(output_dir=str(tmp_path)) + + assert isinstance(output, PluginOutput) + _assert_output_assets(output) + + +async def test_visitors_plugin_generates_assets(tmp_path: Path) -> None: + if VisitorsPlugin is None or not _plugin_available('VisitorsPlugin'): + pytest.skip('VisitorsPlugin not available') + plugin_cls = plugin_service.get_plugin_schedule('VisitorsPlugin').plugin_cls + plugin = plugin_cls() + fake_data = _fake_stats_data() + + with patch.object(plugin, '_fetch_series', new=AsyncMock(return_value=fake_data)): + output = await plugin.run(output_dir=str(tmp_path)) + + assert isinstance(output, PluginOutput) + _assert_output_assets(output) + + +async def test_random_image_plugin_generates_assets(tmp_path: Path) -> None: + image_root = tmp_path / "images" + image_root.mkdir() + img_path = image_root / "sample.png" + img = Image.new('RGB', (64, 64), color=(0, 0, 255)) + img.save(img_path) + + if not _plugin_available(RandomImagePlugin.__name__): + pytest.skip('RandomImagePlugin not available') + plugin_cls = plugin_service.get_plugin_schedule(RandomImagePlugin.__name__).plugin_cls + plugin = plugin_cls() + output = await plugin.run(output_dir=str(tmp_path), image_root=str(image_root)) + + assert isinstance(output, PluginOutput) + _assert_output_assets(output) + + +async def test_photo_grading_toggle_changes_prepare_image() -> None: + if not _plugin_available(BingWallpaperPlugin.__name__): + pytest.skip('BingWallpaperPlugin not available') + plugin_cls = plugin_service.get_plugin_schedule(BingWallpaperPlugin.__name__).plugin_cls + plugin = plugin_cls() + + gradient = Image.linear_gradient('L').resize((64, 64)) + rgb = gradient.convert('RGB') + + original = config.PHOTO_GRADING_ENABLED + try: + config.PHOTO_GRADING_ENABLED = False + disabled = plugin.prepare_image(rgb) + assert disabled.mode == 'L' + assert disabled.tobytes() == rgb.convert('L').tobytes() + + config.PHOTO_GRADING_ENABLED = True + enabled = plugin.prepare_image(rgb) + assert enabled.mode == 'L' + assert enabled.tobytes() != rgb.convert('L').tobytes() + finally: + config.PHOTO_GRADING_ENABLED = original + + +async def test_plugin_runner_passes_extra_kwargs(monkeypatch, tmp_path: Path) -> None: + bmp = tmp_path / 'weather.bmp' + png = tmp_path / 'weather.png' + bmp.write_bytes(b'0') + png.write_bytes(b'0') + + async def fake_run(self, **kwargs): # type: ignore[override] + assert kwargs['output_dir'] == str(tmp_path) + assert kwargs['extra'] == 'value' + return PluginOutput(monochrome_path=str(bmp), grayscale_path=str(png)) + + if not _plugin_available(WeatherPlugin.__name__): + pytest.skip('WeatherPlugin not available') + + monkeypatch.setattr(WeatherPlugin, 'run', fake_run) + + result = await plugin_service.run_single_plugin_by_name( + 'WeatherPlugin', + output_dir=str(tmp_path), + plugin_kwargs={'extra': 'value'} + ) + + assert result.monochrome_path == str(bmp) + assert result.grayscale_path == str(png) + + +async def test_plugin_runner_errors_on_unknown_plugin(tmp_path: Path) -> None: + with pytest.raises(ValueError): + await plugin_service.run_single_plugin_by_name('NotAPlugin', output_dir=str(tmp_path)) + + +async def test_calibration_plugins_can_be_disabled(monkeypatch) -> None: + original = config.CALIBRATION_PLUGIN_ENABLED + try: + monkeypatch.setattr(config, 'CALIBRATION_PLUGIN_ENABLED', False) + names = plugin_service.list_available_plugins() + assert all('calibration' not in name.lower() for name in names) + with pytest.raises(ValueError): + plugin_service.get_plugin_schedule('CalibrationPlugin') + finally: + monkeypatch.setattr(config, 'CALIBRATION_PLUGIN_ENABLED', original) diff --git a/tests/test_rotation.py b/tests/test_rotation.py new file mode 100644 index 0000000..8216056 --- /dev/null +++ b/tests/test_rotation.py @@ -0,0 +1,444 @@ +from typing import Dict, List + +from fastapi.testclient import TestClient + +from trmnl_server import main, models +from trmnl_server.services import state +from trmnl_server import utils +from io import BytesIO +from urllib.parse import urlparse + + +def _prime_rotation_master() -> Dict: + master = state.global_state['rotation_master'] + master.clear() + master.update({ + 'bmp_entries': [b'A', b'B'], + 'png_entries': [b'A', b'B'], + 'hashes': ['hashA', 'hashB'], + 'meta': [ + { + 'id': 'hashA', + 'hash': 'hashA', + 'plugin': 'TestPlugin', + 'label': 'Entry A', + 'url_png': '/web/a.png', + 'url_bmp': '/web/a.bmp' + }, + { + 'id': 'hashB', + 'hash': 'hashB', + 'plugin': 'TestPlugin', + 'label': 'Entry B', + 'url_png': '/web/b.png', + 'url_bmp': '/web/b.bmp' + } + ], + 'selected_ids': [], + 'version': 0 + }) + return master + + +def _prime_rotation_with_dummy_frames() -> Dict: + """Populate rotation master with a real BMP and PNG so preview conversion succeeds.""" + master = state.global_state['rotation_master'] + master.clear() + dummy_path = utils.asset_path('img', 'dummy.bmp') + with open(dummy_path, 'rb') as handle: + bmp_bytes = handle.read() + png_bytes = utils.convert_bmp_bytes_to_png(BytesIO(bmp_bytes)).getvalue() + master.update({ + 'bmp_entries': [bmp_bytes], + 'png_entries': [png_bytes], + 'hashes': ['hashA'], + 'meta': [ + { + 'id': 'hashA', + 'hash': 'hashA', + 'plugin': 'TestPlugin', + 'label': 'Entry A', + 'url_png': '/web/a.png', + 'url_bmp': '/web/a.bmp' + } + ], + 'selected_ids': ['hashA'], + 'version': 0 + }) + return master + + +def _prime_rotation_with_two_frames() -> Dict: + """Populate rotation with two distinct frames so we can verify preview updates.""" + master = state.global_state['rotation_master'] + master.clear() + dummy_path = utils.asset_path('img', 'dummy.bmp') + with open(dummy_path, 'rb') as handle: + bmp_bytes1 = handle.read() + # Create a second BMP by toggling one pixel via PIL to ensure valid encoding + img = utils.load_image(str(dummy_path)) + img = utils.ensure_image_mode(img, '1') + img_copy = img.copy() + img_copy.putpixel((0, 0), 0 if img_copy.getpixel((0, 0)) == 255 else 255) + bmp_buffer = BytesIO() + img_copy.save(bmp_buffer, format='BMP') + bmp_bytes2 = bmp_buffer.getvalue() + png_bytes1 = utils.convert_bmp_bytes_to_png(BytesIO(bmp_bytes1)).getvalue() + png_bytes2 = utils.convert_bmp_bytes_to_png(BytesIO(bmp_bytes2)).getvalue() + master.update({ + 'bmp_entries': [bytes(bmp_bytes1), bytes(bmp_bytes2)], + 'png_entries': [png_bytes1, png_bytes2], + 'hashes': ['hashA', 'hashB'], + 'meta': [ + { + 'id': 'hashA', + 'hash': 'hashA', + 'plugin': 'TestPlugin', + 'label': 'Entry A', + 'url_png': '/web/a.png', + 'url_bmp': '/web/a.bmp' + }, + { + 'id': 'hashB', + 'hash': 'hashB', + 'plugin': 'TestPlugin', + 'label': 'Entry B', + 'url_png': '/web/b.png', + 'url_bmp': '/web/b.bmp' + } + ], + 'selected_ids': ['hashA', 'hashB'], + 'version': 0 + }) + return master + + +def _reset_device_context(*device_ids: str) -> None: + for device_id in device_ids: + for key in ('devices', 'device_playlists', 'client_metrics', 'device_profiles'): + state.global_state.setdefault(key, {}).pop(device_id, None) + models.delete_device_state(device_id) + models.delete_rotation_playlist(device_id) + models.delete_device_playlist_binding(device_id) + + +def test_save_playlist_updates_rotation_and_order(): + client = TestClient(main.app) + master = _prime_rotation_master() + device_id = 'test-device' + _reset_device_context(device_id) + + try: + # Initial GET + resp = client.get('/rotation') + assert resp.status_code == 200 + data = resp.json() + assert data['entries'][0]['id'] == 'hashA' + assert data['entries'][1]['id'] == 'hashB' + + # Post new playlist selecting only hashB + resp = client.post('/rotation', json={'playlist': ['hashB']}) + assert resp.status_code == 200 + payload = resp.json() + assert payload['playlists']['default'] == ['hashB'] + assert master['selected_ids'] == ['hashB'] + # Version should bump + assert master['version'] == 1 + + # Trigger display request so device records the new playlist state + resp_display = client.get('/api/display', headers={'X-Device-Id': device_id}) + assert resp_display.status_code == 200 + device_state = state.get_device_state(device_id) + with state.STATE_LOCK: + assert device_state['playlist_indexes'] == [1] + assert device_state['playlist_ids'] == ['hashB'] + assert device_state['request_count'] == 1 + assert device_state['last_entry_hash'] == 'hashB' + finally: + _reset_device_context(device_id) + + +def test_device_specific_playlist_update(): + client = TestClient(main.app) + _prime_rotation_master() + device_id = 'device-specific' + _reset_device_context(device_id) + + try: + resp = client.post('/rotation', json={'playlist': ['hashA'], 'device_id': device_id}) + assert resp.status_code == 200 + payload = resp.json() + device_playlists: Dict[str, List[str]] = payload['playlists'].get('devices') or {} + assert device_playlists.get(device_id) == ['hashA'] + assert state.get_playlist_selection(device_id) == ['hashA'] + finally: + _reset_device_context(device_id) + + +def test_devices_endpoint_lists_known_devices(): + client = TestClient(main.app) + _prime_rotation_master() + device_id = 'metrics-device' + _reset_device_context(device_id) + try: + state.get_device_state(device_id) + state.update_client_metrics(device_id, refresh_rate=90, battery_voltage=3.8, rssi=-55) + + resp = client.get('/devices', params={'include_default': 'false'}) + assert resp.status_code == 200 + payload = resp.json() + devices = payload['devices'] + assert all(entry['device_id'] != state.DEFAULT_DEVICE_ID for entry in devices) + assert any(entry['device_id'] == device_id for entry in devices) + finally: + _reset_device_context(device_id) + + +def test_device_profile_update_endpoint(): + client = TestClient(main.app) + _prime_rotation_master() + device_id = 'kitchen-panel' + _reset_device_context(device_id) + try: + state.get_device_state(device_id) + + resp = client.patch( + f'/devices/{device_id}', + json={ + 'friendly_name': 'Kitchen Display', + 'refresh_interval': 180, + 'playlist': ['hashB'] + } + ) + assert resp.status_code == 200 + payload = resp.json() + assert payload['device_id'] == device_id + assert payload['friendly_name'] == 'Kitchen Display' + assert payload['refresh_interval'] == 180 + assert payload['playlist'] == ['hashB'] + + profile = state.ensure_device_profile(device_id) + assert profile['friendly_name'] == 'Kitchen Display' + + finally: + _reset_device_context(device_id) + +def test_image_token_resolves_device_without_headers(): + client = TestClient(main.app) + _prime_rotation_master() + device_id = 'token-device' + _reset_device_context(device_id) + + try: + # Bind a named playlist so we can verify the resolved frame index. + state.set_named_playlist('Charts', ['hashB']) + state.set_device_playlist_binding(device_id, 'Charts') + + resp_display = client.get('/api/display', headers={'X-Device-Id': device_id, 'fw-version': '1.6.9'}) + assert resp_display.status_code == 200 + image_url = resp_display.json().get('image_url') + assert isinstance(image_url, str) and 'token=' in image_url + token = image_url.split('token=')[-1] + assert token + + device_state = state.get_device_state(device_id) + with state.STATE_LOCK: + pending_idx = device_state.get('pending_entry_index') + assert pending_idx == 1 + + resp_image = client.get(f'/image/grayscale.png?token={token}') + assert resp_image.status_code == 200 + assert resp_image.content == state.get_rotation_png_bytes(pending_idx) + finally: + _reset_device_context(device_id) + + +def test_playlist_entry_forces_bmp_even_when_grayscale_supported(): + client = TestClient(main.app) + _prime_rotation_master() + device_id = 'force-bmp-device' + _reset_device_context(device_id) + + try: + resp = client.post('/rotation', json={'playlist': ['hashB@bmp'], 'device_id': device_id}) + assert resp.status_code == 200 + + resp_display = client.get('/api/display', headers={'X-Device-Id': device_id, 'fw-version': '1.6.9'}) + assert resp_display.status_code == 200 + image_url = resp_display.json().get('image_url') + assert isinstance(image_url, str) + assert '/image/screen' in image_url + + parsed = urlparse(image_url) + resp_image = client.get(f"{parsed.path}?{parsed.query}") + assert resp_image.status_code == 200 + assert resp_image.content == state.get_rotation_bmp_bytes(1) + finally: + _reset_device_context(device_id) + + +def test_playlist_entry_forces_png_when_grayscale_supported(): + client = TestClient(main.app) + _prime_rotation_master() + device_id = 'force-png-device' + _reset_device_context(device_id) + + try: + resp = client.post('/rotation', json={'playlist': ['hashB@png'], 'device_id': device_id}) + assert resp.status_code == 200 + + resp_display = client.get('/api/display', headers={'X-Device-Id': device_id, 'fw-version': '1.6.9'}) + assert resp_display.status_code == 200 + image_url = resp_display.json().get('image_url') + assert isinstance(image_url, str) + assert '/image/grayscale' in image_url + + parsed = urlparse(image_url) + resp_image = client.get(f"{parsed.path}?{parsed.query}") + assert resp_image.status_code == 200 + assert resp_image.content == state.get_rotation_png_bytes(1) + finally: + _reset_device_context(device_id) + + +def test_preview_endpoint_persists_last_frame(): + client = TestClient(main.app) + _prime_rotation_with_dummy_frames() + device_id = 'preview-device' + _reset_device_context(device_id) + + try: + # Trigger a display fetch which should capture the preview + resp = client.get('/api/display', headers={'X-Device-Id': device_id}) + assert resp.status_code == 200 + + device_state = state.get_device_state(device_id) + with state.STATE_LOCK: + preview_index = device_state.get('current_preview_entry_index') + preview_url = device_state.get('current_preview_url') + preview_token = device_state.get('current_preview_token') + + assert preview_index is not None, 'preview index should be cached after display fetch' + assert preview_url and preview_url.startswith(f'/preview/{device_id}') + assert preview_token, 'preview token should be set' + + # Preview endpoint should return the cached PNG + resp_preview = client.get(f'/preview/{device_id}') + assert resp_preview.status_code == 200 + assert resp_preview.headers.get('content-type') == 'image/png' + expected_bytes = state.get_rotation_png_bytes(preview_index) + assert resp_preview.content == expected_bytes + + # A different device with no preview should 404 + resp_missing = client.get('/preview/unknown-device') + assert resp_missing.status_code == 404 + finally: + _reset_device_context(device_id) + + +def test_named_playlist_binding_affects_rotation_and_deletion_unbinds(): + client = TestClient(main.app) + _prime_rotation_master() + device_id = 'bound-device' + _reset_device_context(device_id) + + try: + resp = client.post('/playlists', json={'name': 'morning', 'playlist': ['hashA']}) + assert resp.status_code == 200 + + resp = client.patch(f'/devices/{device_id}', json={'playlist_name': 'morning'}) + assert resp.status_code == 200 + + resp_display = client.get('/api/display', headers={'X-Device-Id': device_id}) + assert resp_display.status_code == 200 + device_state = state.get_device_state(device_id) + with state.STATE_LOCK: + assert device_state['playlist_ids'] == ['hashA'] + + resp_delete = client.delete('/playlists/morning') + assert resp_delete.status_code == 200 + + device_state = state.get_device_state(device_id) + with state.STATE_LOCK: + assert device_state.get('request_count') == 0 + + resp_display = client.get('/api/display', headers={'X-Device-Id': device_id}) + assert resp_display.status_code == 200 + device_state = state.get_device_state(device_id) + with state.STATE_LOCK: + assert device_state['playlist_ids'] == ['hashA', 'hashB'] + finally: + _reset_device_context(device_id) + + +def test_named_playlist_requires_at_least_one_entry(): + client = TestClient(main.app) + _prime_rotation_master() + + resp = client.post('/playlists', json={'name': 'empty', 'playlist': []}) + assert resp.status_code == 400 + + +def test_preview_updates_on_subsequent_frames(): + client = TestClient(main.app) + _prime_rotation_with_two_frames() + device_id = 'preview-advancing' + _reset_device_context(device_id) + + try: + # First frame + resp1 = client.get('/api/display', headers={'X-Device-Id': device_id}) + assert resp1.status_code == 200 + state_after_first = state.get_device_state(device_id) + with state.STATE_LOCK: + first_token = state_after_first.get('current_preview_token') + first_index = state_after_first.get('current_preview_entry_index') + assert first_index is not None + assert first_token + resp_preview_first = client.get(f'/preview/{device_id}') + assert resp_preview_first.status_code == 200 + first_bytes = resp_preview_first.content + + # Second frame (rotation advances) + resp2 = client.get('/api/display', headers={'X-Device-Id': device_id}) + assert resp2.status_code == 200 + state_after_second = state.get_device_state(device_id) + with state.STATE_LOCK: + second_token = state_after_second.get('current_preview_token') + second_index = state_after_second.get('current_preview_entry_index') + assert second_index is not None + assert second_token + resp_preview_second = client.get(f'/preview/{device_id}') + assert resp_preview_second.status_code == 200 + second_bytes = resp_preview_second.content + assert second_bytes + assert second_bytes != first_bytes, 'Preview bytes should update to the next rotation frame' + assert second_token != first_token, 'Preview token should change when preview bytes change' + finally: + _reset_device_context(device_id) + + +def test_preview_sequence_stores_each_frame(): + client = TestClient(main.app) + master = _prime_rotation_with_two_frames() + device_id = 'preview-sequence' + _reset_device_context(device_id) + + try: + expected_sequence = master['png_entries'] + for idx in range(3): + resp = client.get('/api/display', headers={'X-Device-Id': device_id}) + assert resp.status_code == 200 + device_state = state.get_device_state(device_id) + with state.STATE_LOCK: + preview_token = device_state.get('current_preview_token') + preview_index = device_state.get('current_preview_entry_index') + assert preview_index is not None + assert preview_token + expected_bytes = expected_sequence[idx % len(expected_sequence)] + + resp_preview = client.get(f'/preview/{device_id}') + assert resp_preview.status_code == 200 + assert resp_preview.content == expected_bytes + finally: + _reset_device_context(device_id) diff --git a/tests/test_weather.py b/tests/test_weather.py new file mode 100644 index 0000000..f6a7812 --- /dev/null +++ b/tests/test_weather.py @@ -0,0 +1,44 @@ +from pathlib import Path +from typing import Any, Dict +from unittest.mock import AsyncMock, patch + +import pytest + +from trmnl_server.plugins.base import PluginOutput +from trmnl_server.plugins.weather import WeatherPlugin + + +def _sample_weather_payload() -> Dict[str, Any]: + # Minimal structure consumed by WeatherPlugin + times = [f"2025-12-10T{str(h).zfill(2)}:00" for h in range(24)] + temps = [10 + (h % 5) for h in range(24)] + precip = [0.1 * (h % 3) for h in range(24)] + return { + "current_weather": { + "temperature": 21.5, + "windspeed": 12.3 + }, + "hourly": { + "time": times, + "temperature_2m": temps, + "precipitation": precip + } + } + + +@pytest.mark.asyncio +async def test_weather_plugin_generates_assets(tmp_path: Path): + payload = _sample_weather_payload() + with patch.object( + WeatherPlugin, + '_fetch_weather_data', + new=AsyncMock(return_value=payload) + ): + plugin = WeatherPlugin() + output = await plugin.run(output_dir=str(tmp_path)) + + assert isinstance(output, PluginOutput) + mono = Path(output.monochrome_path) + gray = Path(output.grayscale_path) + assert mono.is_file() and mono.stat().st_size > 0 + assert gray.is_file() and gray.stat().st_size > 0 diff --git a/trmnl_server/__init__.py b/trmnl_server/__init__.py new file mode 100644 index 0000000..3ca3a76 --- /dev/null +++ b/trmnl_server/__init__.py @@ -0,0 +1,5 @@ +"""TRMNL local server package.""" + +from . import config # re-export for convenience + +__all__ = ['config'] diff --git a/trmnl_server/__main__.py b/trmnl_server/__main__.py new file mode 100644 index 0000000..0e9d004 --- /dev/null +++ b/trmnl_server/__main__.py @@ -0,0 +1,6 @@ +"""Module entry point for ``python -m trmnl_server``.""" + +from .main import run + +if __name__ == '__main__': + run() diff --git a/trmnl_server/config.py b/trmnl_server/config.py new file mode 100644 index 0000000..d8c71a0 --- /dev/null +++ b/trmnl_server/config.py @@ -0,0 +1,263 @@ +from __future__ import annotations + +import logging +from os import environ, getcwd +from os.path import abspath, isdir, join +from sys import stdout + +# Logging Configuration +LOG_LEVEL = environ.get('LOG_LEVEL', 'DEBUG').upper() +logging.basicConfig( + level=getattr(logging, LOG_LEVEL, logging.DEBUG), + format="%(asctime)s %(levelname)s %(message)s", + datefmt="%Y-%m-%d %H:%M:%S", + stream=stdout +) +logger = logging.getLogger('trmnlServer') + +# Pillow emits very noisy DEBUG logs (PNG chunk dumps). Keep them at INFO+. +logging.getLogger('PIL').setLevel(logging.INFO) +logging.getLogger('PIL.PngImagePlugin').setLevel(logging.INFO) +logging.getLogger('httpx').setLevel(logging.WARNING) +logging.getLogger('httpcore').setLevel(logging.WARNING) + +logger.info('[Config] loading module') + +_TRUE_VALUES = {'true', '1', 't', 'yes', 'on'} + +IMAGE_PATH = 'images/screen.bmp' +REFRESH_TIME = 900 +BATTERY_MAX_VOLTAGE = 4.1 +BATTERY_MIN_VOLTAGE = 2.3 +TIME_ZONE = 'UTC' +SERVER_PORT = 4567 +ENABLE_SSL = False +SERVER_SCHEME = 'http' +SETUP_API_KEY = '' +SETUP_FRIENDLY_ID = 'trmnl-byod' +SETUP_MESSAGE = 'Configured' +DITHERING_MODE = 'none' +ASSETS_ROOT = 'web' +STATIC_ROOT = 'web' +GENERATED_ROOT = 'var/generated' + +# Photographic plugin grading +# +# When enabled, photographic plugins apply additional histogram and shadow grading +# prior to tone-curve-aware quantization/dithering. +# When disabled, photographic plugins output raw grayscale (no extra grading), +# which makes it easier to reason about the tone curve/LUT calibration. +PHOTO_GRADING_ENABLED = True + +# Calibration plugin control +# +# When disabled, calibration plugins are excluded from the plugin registry and +# no calibration assets are generated. +CALIBRATION_PLUGIN_ENABLED = False + +# E-ink grayscale response compensation +# +# These settings allow quantization and dithering to operate in a non-linear +# "panel space" so the resulting grays are closer to perceptually uniform on +# real e-ink panels. +# +# - EINK_TONE_POINTS: optional anchor list "in:out" in 0-255, comma-separated +# e.g. "0:0,32:40,128:160,255:255" (digital input -> observed panel output). +# - EINK_TONE_GAMMA: fallback forward gamma (digital -> panel) when points unset. +EINK_TONE_POINTS = '0:0,32:6,64:18,85:32,128:95,170:155,192:190,224:225,255:250' +EINK_TONE_GAMMA = 1.0 + +CONFIG_DIR = getcwd() +VAR_ROOT = join(CONFIG_DIR, 'var') +DATABASE_PATH = join(VAR_ROOT, 'db', 'trmnl.db') +LOGS_DIR = join(VAR_ROOT, 'logs') +SSL_DIR = join(VAR_ROOT, 'ssl') +WEB_ROOT_DIR = join(CONFIG_DIR, ASSETS_ROOT) +WEB_STATIC_DIR = join(CONFIG_DIR, STATIC_ROOT) +WEB_GENERATED_DIR = join(CONFIG_DIR, GENERATED_ROOT) + +_ENV_OVERRIDES: set[str] = set() + + +def _env_str(name: str, default: str, config_key: str) -> str: + value = environ.get(name) + if value is None: + return default + _ENV_OVERRIDES.add(config_key) + return value + + +def _env_bool(name: str, default: bool, config_key: str) -> bool: + value = environ.get(name) + if value is None: + return default + _ENV_OVERRIDES.add(config_key) + return value.strip().lower() in _TRUE_VALUES + + +def _env_int(name: str, default: int, config_key: str) -> int: + value = environ.get(name) + if value is None: + return default + try: + number = int(value) + _ENV_OVERRIDES.add(config_key) + return number + except ValueError: + logger.warning('[Config] Invalid int for %s: %s', name, value) + return default + + +def _env_float(name: str, default: float, config_key: str) -> float: + value = environ.get(name) + if value is None: + return default + try: + number = float(value) + _ENV_OVERRIDES.add(config_key) + return number + except ValueError: + logger.warning('[Config] Invalid float for %s: %s', name, value) + return default + + +def _apply_environment_overrides() -> None: + global IMAGE_PATH, REFRESH_TIME + global BATTERY_MAX_VOLTAGE, BATTERY_MIN_VOLTAGE, TIME_ZONE + global SERVER_PORT, ENABLE_SSL, SERVER_SCHEME + global SETUP_API_KEY, SETUP_FRIENDLY_ID, SETUP_MESSAGE + global DITHERING_MODE, ASSETS_ROOT, STATIC_ROOT, GENERATED_ROOT + global EINK_TONE_POINTS, EINK_TONE_GAMMA + global PHOTO_GRADING_ENABLED, CALIBRATION_PLUGIN_ENABLED + _ENV_OVERRIDES.clear() + + default_eink_tone_points = EINK_TONE_POINTS + default_eink_tone_gamma = EINK_TONE_GAMMA + + IMAGE_PATH = _env_str('IMAGE_PATH', 'images/screen.bmp', 'image_path') + REFRESH_TIME = _env_int('REFRESH_TIME', 900, 'refresh_time') + BATTERY_MAX_VOLTAGE = _env_float('BATTERY_MAX_VOLTAGE', 4.1, 'battery_max_voltage') + BATTERY_MIN_VOLTAGE = _env_float('BATTERY_MIN_VOLTAGE', 2.3, 'battery_min_voltage') + TIME_ZONE = _env_str('TIME_ZONE', 'UTC', 'time_zone') + SERVER_PORT = _env_int('SERVER_PORT', 4567, 'server_port') + ENABLE_SSL = _env_bool('ENABLE_SSL', False, 'enable_ssl') + SETUP_API_KEY = _env_str('SETUP_API_KEY', '', 'setup_api_key') + SETUP_FRIENDLY_ID = _env_str('SETUP_FRIENDLY_ID', 'trmnl-byod', 'setup_friendly_id') + SETUP_MESSAGE = _env_str('SETUP_MESSAGE', 'Configured', 'setup_message') + DITHERING_MODE = _env_str('DITHERING_MODE', 'none', 'dithering_mode') + ASSETS_ROOT = _env_str('ASSETS_ROOT', 'web', 'assets_root') + STATIC_ROOT = _env_str('STATIC_ROOT', 'web', 'static_root') + GENERATED_ROOT = _env_str('GENERATED_ROOT', 'var/generated', 'generated_root') + EINK_TONE_POINTS = _env_str('EINK_TONE_POINTS', default_eink_tone_points, 'eink_tone_points') + EINK_TONE_GAMMA = _env_float('EINK_TONE_GAMMA', default_eink_tone_gamma, 'eink_tone_gamma') + PHOTO_GRADING_ENABLED = _env_bool('PHOTO_GRADING_ENABLED', PHOTO_GRADING_ENABLED, 'photo_grading_enabled') + CALIBRATION_PLUGIN_ENABLED = _env_bool('CALIBRATION_PLUGIN_ENABLED', CALIBRATION_PLUGIN_ENABLED, 'calibration_plugin_enabled') + _refresh_server_scheme() + + +def _refresh_server_scheme() -> None: + global SERVER_SCHEME + SERVER_SCHEME = 'https' if ENABLE_SSL else 'http' + + +def _refresh_path_constants() -> None: + global VAR_ROOT, DATABASE_PATH, LOGS_DIR, SSL_DIR + global WEB_ROOT_DIR, WEB_STATIC_DIR, WEB_GENERATED_DIR + VAR_ROOT = join(CONFIG_DIR, 'var') + DATABASE_PATH = join(VAR_ROOT, 'db', 'trmnl.db') + LOGS_DIR = join(VAR_ROOT, 'logs') + SSL_DIR = join(VAR_ROOT, 'ssl') + WEB_ROOT_DIR = join(CONFIG_DIR, ASSETS_ROOT) + WEB_STATIC_DIR = join(CONFIG_DIR, STATIC_ROOT) + WEB_GENERATED_DIR = join(CONFIG_DIR, GENERATED_ROOT) + + +def load_config(base_dir: str | None = None) -> None: + """Apply environment overrides and update path constants for the provided base directory.""" + global CONFIG_DIR + _apply_environment_overrides() + if base_dir: + candidate = abspath(base_dir) + if not isdir(candidate): + logger.warning('[Config] Provided base_dir %s is not a directory; using current working directory', base_dir) + candidate = getcwd() + CONFIG_DIR = candidate + else: + CONFIG_DIR = getcwd() + _refresh_path_constants() + + +def _coerce_bool(value) -> bool: + if isinstance(value, bool): + return value + if isinstance(value, str): + return value.strip().lower() in _TRUE_VALUES + return bool(value) + + +def update_config(key: str, value) -> None: + """Update an in-memory configuration value.""" + global IMAGE_PATH, REFRESH_TIME + global BATTERY_MAX_VOLTAGE, BATTERY_MIN_VOLTAGE, TIME_ZONE + global SERVER_PORT, ENABLE_SSL, SETUP_API_KEY + global SETUP_FRIENDLY_ID, SETUP_MESSAGE, DITHERING_MODE + global ASSETS_ROOT, STATIC_ROOT, GENERATED_ROOT + global EINK_TONE_POINTS, EINK_TONE_GAMMA + global PHOTO_GRADING_ENABLED, CALIBRATION_PLUGIN_ENABLED + + logger.info('[Config] Updating %s to %s', key, value) + + if key == 'image_path': + IMAGE_PATH = str(value) + elif key == 'refresh_time': + REFRESH_TIME = int(value) + elif key == 'battery_max_voltage': + BATTERY_MAX_VOLTAGE = float(value) + elif key == 'battery_min_voltage': + BATTERY_MIN_VOLTAGE = float(value) + elif key == 'time_zone': + TIME_ZONE = str(value) + elif key == 'server_port': + SERVER_PORT = int(value) + elif key == 'enable_ssl': + ENABLE_SSL = _coerce_bool(value) + _refresh_server_scheme() + elif key == 'setup_api_key': + SETUP_API_KEY = str(value) + elif key == 'setup_friendly_id': + SETUP_FRIENDLY_ID = str(value) + elif key == 'setup_message': + SETUP_MESSAGE = str(value) + elif key == 'dithering_mode': + DITHERING_MODE = str(value) + elif key == 'assets_root': + ASSETS_ROOT = str(value) + _refresh_path_constants() + elif key == 'static_root': + STATIC_ROOT = str(value) + _refresh_path_constants() + elif key == 'generated_root': + GENERATED_ROOT = str(value) + _refresh_path_constants() + elif key == 'eink_tone_points': + EINK_TONE_POINTS = str(value) + elif key == 'eink_tone_gamma': + EINK_TONE_GAMMA = float(value) + elif key == 'photo_grading_enabled': + PHOTO_GRADING_ENABLED = _coerce_bool(value) + elif key == 'calibration_plugin_enabled': + CALIBRATION_PLUGIN_ENABLED = _coerce_bool(value) + else: + logger.warning('[Config] Unknown config key: %s', key) + + +def apply_persisted_config(entries: dict[str, str]) -> None: + """Apply database-backed configuration entries unless overridden by env vars.""" + for key, raw_value in entries.items(): + if key in _ENV_OVERRIDES: + continue + update_config(key, raw_value) + + +_apply_environment_overrides() +_refresh_path_constants() diff --git a/trmnl_server/main.py b/trmnl_server/main.py new file mode 100644 index 0000000..a66eafa --- /dev/null +++ b/trmnl_server/main.py @@ -0,0 +1,341 @@ +#! /usr/bin/env python +"""FastAPI entrypoint and CLI tooling for the TRMNL local server.""" + +from __future__ import annotations + +import argparse +import asyncio +import os +import sys +from contextlib import asynccontextmanager +from typing import Awaitable, Callable, Dict, List, Optional, Tuple + +import uvicorn +from fastapi import FastAPI, Request, Response +from fastapi.staticfiles import StaticFiles + +from . import config, models, utils +from .routes import api_router, image_router, page_router +from .services import plugins, state + +################################################################################################### + +logger = config.logger +logger.info('[Main] Starting trmnlServer') + +API_LOG_PATH_PREFIXES = ('/api',) +MAX_REQUEST_LOG_BODY = 2048 +MAX_RESPONSE_LOG_BODY = 2048 +BINARY_CONTENT_PREFIXES = ( + 'application/octet-stream', + 'application/pdf', + 'application/zip', + 'image/', + 'audio/', + 'video/' +) + +BASE_PATH = os.path.abspath(os.path.join(os.path.dirname(os.path.abspath(__file__)), os.pardir)) +STATIC_MOUNT_PATHS: Optional[Tuple[str, str]] = None + + +def should_log_request(path: str) -> bool: + return any(path.startswith(prefix) for prefix in API_LOG_PATH_PREFIXES) + + +def format_request_body(body: bytes, limit: int = MAX_REQUEST_LOG_BODY) -> str: + if not body: + return '' + body_text = body.decode('utf-8', errors='replace') + if len(body_text) > limit: + return f"{body_text[:limit]}..." + return body_text + + +def is_binary_content_type(content_type: str) -> bool: + lowered = (content_type or '').lower() + return any(lowered.startswith(prefix) for prefix in BINARY_CONTENT_PREFIXES) + + +def format_response_body(body: bytes, limit: int = MAX_RESPONSE_LOG_BODY) -> str: + if not body: + return '' + text = body.decode('utf-8', errors='replace') + if len(text) > limit: + return f"{text[:limit]}..." + return text + + +@asynccontextmanager +async def lifespan(app: FastAPI): # noqa: ARG001 + logger.info('Running initial plugin refresh') + await plugins.refresh_plugin_assets() + logger.info('Starting plugin refresh workers') + await plugins.start_plugin_refreshers() + yield + logger.info('Stopping plugin refresh workers') + await plugins.stop_plugin_refreshers() + + +app = FastAPI(lifespan=lifespan) + + +@app.middleware('http') +async def log_api_request( + request: Request, + call_next: Callable[[Request], Awaitable[Response]] +) -> Response: + log_this_request = should_log_request(request.url.path) + if log_this_request: + body_bytes = await request.body() + logger.info( + '[RequestDump] method=%s path=%s query=%s headers=%s body=%s', + request.method, + request.url.path, + dict(request.query_params), + dict(request.headers), + format_request_body(body_bytes) + ) + response = await call_next(request) + if log_this_request: + content_type = response.headers.get('content-type', '') + if not is_binary_content_type(content_type): + response_body_chunks = [chunk async for chunk in response.body_iterator] + response_body = b''.join(response_body_chunks) + logger.info( + '[ResponseDump] path=%s status=%s content_type=%s headers=%s body=%s', + request.url.path, + response.status_code, + content_type, + dict(response.headers), + format_response_body(response_body) + ) + return Response( + content=response_body, + status_code=response.status_code, + headers=dict(response.headers), + media_type=response.media_type, + background=response.background + ) + return response +app.include_router(image_router) +app.include_router(api_router) +app.include_router(page_router) + + +def _parse_cli_args(argv: Optional[List[str]] = None) -> argparse.Namespace: + parser = argparse.ArgumentParser(description='TRMNL local server') + parser.add_argument('workdir', nargs='?', help='Runtime working directory', default=None) + parser.add_argument('--list-plugins', action='store_true', help='List registered plugins and exit') + parser.add_argument('--run-plugin', metavar='PLUGIN', help='Run a single plugin and exit') + parser.add_argument('--plugin-output', metavar='DIR', help='Override output directory when running a plugin') + parser.add_argument( + '--plugin-arg', + action='append', + default=[], + metavar='KEY=VALUE', + help='Additional keyword arguments for --run-plugin' + ) + return parser.parse_args(argv) + + +def _parse_plugin_kwargs(pairs: List[str]) -> Dict[str, str]: + kwargs: Dict[str, str] = {} + for entry in pairs: + if '=' not in entry: + raise ValueError(f"Invalid plugin arg '{entry}'. Expected KEY=VALUE") + key, value = entry.split('=', 1) + kwargs[key] = value + return kwargs + + +def _resolve_workdir(candidate: Optional[str]) -> str: + if not candidate: + return BASE_PATH + if not os.path.isdir(candidate): + print(f"Path {candidate} is not a directory. Using default path {BASE_PATH}.") + return BASE_PATH + return candidate + + +def _ensure_static_mounts() -> None: + global STATIC_MOUNT_PATHS + desired = (config.WEB_STATIC_DIR, config.WEB_GENERATED_DIR) + if STATIC_MOUNT_PATHS == desired: + return + # Remove existing mounts if present so new directories are reflected + app.router.routes = [ + route for route in app.router.routes + if getattr(route, 'name', None) not in {'web-static', 'web-generated', 'generated-static'} + ] + app.mount('/web', StaticFiles(directory=config.WEB_STATIC_DIR), name='web-static') + # Serve generated, volatile plugin outputs directly under /generated + app.mount('/generated', StaticFiles(directory=config.WEB_GENERATED_DIR), name='generated-static') + STATIC_MOUNT_PATHS = desired + + +def _enforce_runtime_directory_defaults(entries: Optional[Dict[str, str]] = None) -> None: + desired_static = 'web' + desired_assets = 'web' + desired_generated = 'var/generated' + if entries is None: + entries = {} + + persisted_static = entries.get('static_root') + if persisted_static and persisted_static != desired_static: + logger.info( + 'Migrating static_root from %s to %s to align with reorganized web assets', + persisted_static, + desired_static + ) + config.update_config('static_root', desired_static) + models.save_config_entry('static_root', desired_static) + + persisted_assets = entries.get('assets_root') + if persisted_assets and persisted_assets != desired_assets: + logger.info( + 'Migrating assets_root from %s to %s to align with reorganized web assets', + persisted_assets, + desired_assets + ) + config.update_config('assets_root', desired_assets) + models.save_config_entry('assets_root', desired_assets) + + persisted_generated = entries.get('generated_root') + if persisted_generated and persisted_generated != desired_generated: + logger.info( + 'Migrating generated_root from %s to %s to keep volatile assets under var/', + persisted_generated, + desired_generated + ) + config.update_config('generated_root', desired_generated) + models.save_config_entry('generated_root', desired_generated) + + +def _prepare_runtime(current_dir: str) -> str: + config.load_config(current_dir) + os.makedirs(config.VAR_ROOT, exist_ok=True) + os.makedirs(os.path.dirname(config.DATABASE_PATH), exist_ok=True) + models.init_db() + persisted_entries = models.load_config_entries() + config.apply_persisted_config(persisted_entries) + _enforce_runtime_directory_defaults(persisted_entries) + state.initialize_rotation_playlists_from_storage() + + runtime_paths = { + config.VAR_ROOT, + os.path.dirname(config.DATABASE_PATH), + config.LOGS_DIR, + config.SSL_DIR, + config.WEB_STATIC_DIR, + config.WEB_GENERATED_DIR + } + for path in runtime_paths: + os.makedirs(path, exist_ok=True) + + server_ip = utils.get_ip_address() + server_scheme = config.SERVER_SCHEME + server_base_url = f"{server_scheme}://{server_ip}:{config.SERVER_PORT}" + state.set_server_base_url(server_base_url) + logger.info( + 'Server will be running on IP: %s and port: %s (scheme: %s)', + server_ip, + config.SERVER_PORT, + server_scheme + ) + + for path in (config.WEB_ROOT_DIR, config.WEB_STATIC_DIR, config.WEB_GENERATED_DIR, config.SSL_DIR): + os.makedirs(path, exist_ok=True) + _ensure_static_mounts() + return server_ip + + +def _print_available_plugins() -> None: + print('Registered plugins:') + for name in plugins.list_available_plugins(): + print(f' - {name}') + + +def _run_plugin_command(plugin_name: str, output_dir: Optional[str], plugin_kwargs: Dict[str, str]) -> None: + try: + result = asyncio.run( + plugins.run_single_plugin_by_name( + plugin_name, + output_dir=output_dir, + plugin_kwargs=plugin_kwargs + ) + ) + except ValueError as exc: + logger.error('%s', exc) + sys.exit(2) + except RuntimeError as exc: + logger.error('%s', exc) + sys.exit(1) + logger.info( + 'Plugin %s assets saved to %s and %s', + plugin_name, + result.monochrome_path, + result.grayscale_path + ) + + +def _start_http_server(server_ip: str) -> None: + with state.STATE_LOCK: + state.get_device_state(state.DEFAULT_DEVICE_ID)['bmp_send_switch'] = True + if config.ENABLE_SSL: + cert_file = os.path.join(config.SSL_DIR, 'cert.pem') + key_file = os.path.join(config.SSL_DIR, 'key.pem') + + if not os.path.exists(cert_file) or not os.path.exists(key_file): + logger.debug('[Main] cert.pem and key.pem not found, generating new ones') + os.system( + f'openssl req -x509 -newkey rsa:4096 -keyout {key_file} -out {cert_file} ' + f'-days 365 -nodes ' + f'-subj "/C=US/ST=Georgia/L=Atlanta/O=trmnlServer/OU=webapp/CN={server_ip}"' + ) + + logger.debug('[Main] Starting the server with uvicorn and SSL') + uvicorn.run( + app, + host='0.0.0.0', + port=config.SERVER_PORT, + ssl_keyfile=key_file, + ssl_certfile=cert_file, + log_level='info' + ) + else: + logger.debug('[Main] Starting the server without SSL') + uvicorn.run( + app, + host='0.0.0.0', + port=config.SERVER_PORT, + log_level='info' + ) + + +_prepare_runtime(BASE_PATH) + + +def run() -> None: + args = _parse_cli_args(sys.argv[1:]) + current_dir = _resolve_workdir(args.workdir) + server_ip = _prepare_runtime(current_dir) + + if args.list_plugins: + _print_available_plugins() + return + + if args.run_plugin: + try: + plugin_kwargs = _parse_plugin_kwargs(args.plugin_arg) + except ValueError as exc: + logger.error('%s', exc) + sys.exit(2) + _run_plugin_command(args.run_plugin, args.plugin_output, plugin_kwargs) + return + + _start_http_server(server_ip) + + +if __name__ == '__main__': + run() diff --git a/trmnl_server/models.py b/trmnl_server/models.py new file mode 100644 index 0000000..970d2a4 --- /dev/null +++ b/trmnl_server/models.py @@ -0,0 +1,519 @@ +import datetime +import json +from typing import Dict, List, Optional, Tuple + +from sqlalchemy import DateTime, Float, Integer, String, Text, UniqueConstraint, create_engine, inspect, select, text +from sqlalchemy.orm import DeclarativeBase, Mapped, Session, mapped_column, sessionmaker + +from . import config + +logger = config.logger + + +def _utcnow() -> datetime.datetime: + """Return a timezone-aware UTC timestamp for SQLAlchemy defaults.""" + return datetime.datetime.now(datetime.timezone.utc) + + +def _database_url() -> str: + return f"sqlite:///{config.DATABASE_PATH}" + + +engine = create_engine(_database_url(), connect_args={"check_same_thread": False}) +SessionLocal = sessionmaker(autocommit=False, autoflush=False) +SessionLocal.configure(bind=engine) + + +class Base(DeclarativeBase): + pass + + +class BatteryStatus(Base): + __tablename__ = "battery_status" + + id: Mapped[int] = mapped_column(Integer, primary_key=True, index=True) + timestamp: Mapped[datetime.datetime] = mapped_column(DateTime, default=_utcnow) + voltage: Mapped[float] = mapped_column(Float) + rssi: Mapped[int] = mapped_column(Integer) + + def __repr__(self) -> str: + return f"" + + +class LogEntry(Base): + __tablename__ = "logs" + + id: Mapped[int] = mapped_column(Integer, primary_key=True, index=True) + timestamp: Mapped[datetime.datetime] = mapped_column(DateTime, default=_utcnow) + context: Mapped[str] = mapped_column(String) + info: Mapped[str] = mapped_column(String) + + def __repr__(self) -> str: + return f"" + + +class RotationPlaylist(Base): + __tablename__ = "rotation_playlists" + __table_args__ = ( + UniqueConstraint("name", "device_id", name="uq_rotation_playlists_name_device"), + ) + + id: Mapped[int] = mapped_column(Integer, primary_key=True, index=True) + name: Mapped[str] = mapped_column(String, default="default") + device_id: Mapped[Optional[str]] = mapped_column(String, nullable=True) + selected_ids: Mapped[str] = mapped_column(Text, default="[]") + updated_at: Mapped[datetime.datetime] = mapped_column(DateTime, default=_utcnow) + + def __repr__(self) -> str: + return f"" + + +class DevicePlaylistBinding(Base): + __tablename__ = "device_playlist_bindings" + + device_id: Mapped[str] = mapped_column(String, primary_key=True, index=True) + playlist_name: Mapped[str] = mapped_column(String, default="default") + updated_at: Mapped[datetime.datetime] = mapped_column(DateTime, default=_utcnow, onupdate=_utcnow) + + def __repr__(self) -> str: + return f"" + + +class DeviceState(Base): + __tablename__ = "device_states" + + device_id: Mapped[str] = mapped_column(String, primary_key=True, index=True) + rotation_version: Mapped[int] = mapped_column(Integer, default=0) + rotation_index: Mapped[int] = mapped_column(Integer, default=-1) + last_entry_hash: Mapped[Optional[str]] = mapped_column(String, nullable=True) + rotation_hash_order: Mapped[str] = mapped_column(Text, default="[]") + current_plugin_id: Mapped[Optional[str]] = mapped_column(String, nullable=True) + updated_at: Mapped[datetime.datetime] = mapped_column(DateTime, default=_utcnow, onupdate=_utcnow) + + def __repr__(self) -> str: + return ( + f"" + ) + + +class ConfigEntry(Base): + __tablename__ = "config_entries" + + key: Mapped[str] = mapped_column(String, primary_key=True, index=True) + value: Mapped[str] = mapped_column(String) + + def __repr__(self) -> str: + return f"" + + +class DeviceProfile(Base): + __tablename__ = "device_profiles" + + device_id: Mapped[str] = mapped_column(String, primary_key=True, index=True) + friendly_name: Mapped[str] = mapped_column(String, default="") + refresh_interval: Mapped[Optional[int]] = mapped_column(Integer, nullable=True) + time_zone: Mapped[Optional[str]] = mapped_column(String, nullable=True) + created_at: Mapped[datetime.datetime] = mapped_column(DateTime, default=_utcnow) + updated_at: Mapped[datetime.datetime] = mapped_column(DateTime, default=_utcnow, onupdate=_utcnow) + last_seen: Mapped[datetime.datetime] = mapped_column(DateTime, default=_utcnow) + + def __repr__(self) -> str: + return f"" + + +def reconfigure_engine() -> None: + """Recreate the SQLite engine to follow the current config path.""" + global engine + new_engine = create_engine(_database_url(), connect_args={"check_same_thread": False}) + if engine: + engine.dispose() + engine = new_engine + SessionLocal.configure(bind=engine) + + +def init_db() -> None: + """Initialize the database by creating all tables.""" + reconfigure_engine() + Base.metadata.create_all(bind=engine) + _ensure_device_state_schema() + + +def _ensure_device_state_schema() -> None: + try: + inspector = inspect(engine) + columns = {column['name'] for column in inspector.get_columns('device_states')} + except Exception as exc: # noqa: BLE001 + logger.warning("Failed to inspect device_states schema: %s", exc) + return + if 'current_plugin_id' in columns: + return + try: + with engine.begin() as connection: + connection.execute(text('ALTER TABLE device_states ADD COLUMN current_plugin_id VARCHAR')) + except Exception as exc: # noqa: BLE001 + logger.warning("Failed to add current_plugin_id column: %s", exc) + + +def get_db(): + """Dependency to get a database session.""" + db = SessionLocal() + try: + yield db + finally: + db.close() + + +def add_battery_status(voltage: float, rssi: int) -> BatteryStatus: + """Add a new battery status entry.""" + with SessionLocal() as db: + status = BatteryStatus(voltage=voltage, rssi=rssi) + db.add(status) + db.commit() + db.refresh(status) + return status + + +def get_battery_history( + limit: int = 30, + from_date: Optional[datetime.datetime] = None, + to_date: Optional[datetime.datetime] = None +) -> List[BatteryStatus]: + """Get battery history with optional filtering.""" + with SessionLocal() as db: + query = select(BatteryStatus).order_by(BatteryStatus.timestamp.desc()) + + if from_date and to_date: + query = query.where(BatteryStatus.timestamp >= from_date, BatteryStatus.timestamp <= to_date) + + if limit: + query = query.limit(limit) + + result = db.execute(query) + return list(result.scalars().all()) + + +def add_log_entry(context: str, info: str) -> LogEntry: + """Add a new log entry.""" + with SessionLocal() as db: + log = LogEntry(context=context, info=info) + db.add(log) + db.commit() + db.refresh(log) + return log + + +def get_logs(limit: int = 20) -> List[LogEntry]: + """Get the latest log entries ordered oldest-to-newest.""" + with SessionLocal() as db: + query = select(LogEntry).order_by(LogEntry.timestamp.desc()).limit(limit) + result = db.execute(query) + logs = list(result.scalars().all()) + return sorted(logs, key=lambda entry: entry.timestamp) + + +def get_logs_after(last_id: int, limit: int = 50) -> List[LogEntry]: + """Get log entries with an ID greater than the provided cursor.""" + with SessionLocal() as db: + query = ( + select(LogEntry) + .where(LogEntry.id > last_id) + .order_by(LogEntry.timestamp.asc()) + ) + result = db.execute(query) + return list(result.scalars().all()) + + +def _serialize_list(values: Optional[List[str]]) -> str: + return json.dumps(values or []) + + +def _deserialize_list(payload: Optional[str]) -> List[str]: + if not payload: + return [] + try: + data = json.loads(payload) + except json.JSONDecodeError: + return [] + if isinstance(data, list): + return [str(item) for item in data] + return [] + + +def get_rotation_playlist(device_id: Optional[str] = None, name: str = "default") -> Optional[List[str]]: + with SessionLocal() as db: + stmt = ( + select(RotationPlaylist) + .where(RotationPlaylist.name == name) + .where(RotationPlaylist.device_id == device_id) + ) + result = db.execute(stmt).scalars().first() + if result is None: + return None + return _deserialize_list(result.selected_ids) + + +def save_rotation_playlist( + selected_ids: List[str], + device_id: Optional[str] = None, + name: str = "default" +) -> None: + payload = _serialize_list(selected_ids) + timestamp = _utcnow() + with SessionLocal() as db: + stmt = ( + select(RotationPlaylist) + .where(RotationPlaylist.name == name) + .where(RotationPlaylist.device_id == device_id) + ) + row = db.execute(stmt).scalars().first() + if row is None: + row = RotationPlaylist(name=name, device_id=device_id, selected_ids=payload, updated_at=timestamp) + db.add(row) + else: + row.selected_ids = payload + row.updated_at = timestamp + db.commit() + + +def list_device_playlists(name: str = "default") -> List[Tuple[str, List[str]]]: + with SessionLocal() as db: + stmt = ( + select(RotationPlaylist) + .where(RotationPlaylist.name == name) + .where(RotationPlaylist.device_id.isnot(None)) + ) + rows = db.execute(stmt).scalars().all() + return [ + (row.device_id, _deserialize_list(row.selected_ids)) + for row in rows + ] + + +def delete_rotation_playlist(device_id: str, name: str = "default") -> None: + with SessionLocal() as db: + stmt = ( + select(RotationPlaylist) + .where(RotationPlaylist.name == name) + .where(RotationPlaylist.device_id == device_id) + ) + row = db.execute(stmt).scalars().first() + if row is None: + return + db.delete(row) + db.commit() + + +def list_named_rotation_playlists() -> List[Tuple[str, List[str]]]: + with SessionLocal() as db: + stmt = ( + select(RotationPlaylist) + .where(RotationPlaylist.device_id.is_(None)) + .where(RotationPlaylist.name != 'default') + ) + rows = db.execute(stmt).scalars().all() + return [(row.name, _deserialize_list(row.selected_ids)) for row in rows] + + +def delete_named_rotation_playlist(name: str) -> None: + with SessionLocal() as db: + stmt = ( + select(RotationPlaylist) + .where(RotationPlaylist.name == name) + .where(RotationPlaylist.device_id.is_(None)) + ) + row = db.execute(stmt).scalars().first() + if row is None: + return + db.delete(row) + db.commit() + + +def list_device_playlist_bindings() -> List[Tuple[str, str]]: + with SessionLocal() as db: + stmt = select(DevicePlaylistBinding) + rows = db.execute(stmt).scalars().all() + return [(row.device_id, row.playlist_name) for row in rows] + + +def get_device_playlist_binding(device_id: str) -> Optional[str]: + with SessionLocal() as db: + row = db.get(DevicePlaylistBinding, device_id) + if row is None: + return None + return row.playlist_name + + +def set_device_playlist_binding(device_id: str, playlist_name: str) -> None: + timestamp = _utcnow() + with SessionLocal() as db: + row = db.get(DevicePlaylistBinding, device_id) + if row is None: + row = DevicePlaylistBinding(device_id=device_id, playlist_name=playlist_name, updated_at=timestamp) + db.add(row) + else: + row.playlist_name = playlist_name + row.updated_at = timestamp + db.commit() + + +def delete_device_playlist_binding(device_id: str) -> None: + with SessionLocal() as db: + row = db.get(DevicePlaylistBinding, device_id) + if row is None: + return + db.delete(row) + db.commit() + + +def get_device_state(device_id: str) -> Optional[Dict[str, object]]: + with SessionLocal() as db: + row = db.get(DeviceState, device_id) + if row is None: + return None + return { + 'rotation_version': row.rotation_version, + 'rotation_index': row.rotation_index, + 'last_entry_hash': row.last_entry_hash, + 'rotation_hash_order': _deserialize_list(row.rotation_hash_order), + 'current_plugin_id': row.current_plugin_id + } + + +def save_device_state( + device_id: str, + rotation_version: int, + rotation_index: int, + rotation_hash_order: List[str], + last_entry_hash: Optional[str], + current_plugin_id: Optional[str] +) -> None: + timestamp = _utcnow() + payload = _serialize_list(rotation_hash_order) + with SessionLocal() as db: + row = db.get(DeviceState, device_id) + if row is None: + row = DeviceState( + device_id=device_id, + rotation_version=rotation_version, + rotation_index=rotation_index, + last_entry_hash=last_entry_hash, + rotation_hash_order=payload, + current_plugin_id=current_plugin_id, + updated_at=timestamp + ) + db.add(row) + else: + row.rotation_version = rotation_version + row.rotation_index = rotation_index + row.last_entry_hash = last_entry_hash + row.rotation_hash_order = payload + row.current_plugin_id = current_plugin_id + row.updated_at = timestamp + db.commit() + + +def delete_device_state(device_id: str) -> None: + with SessionLocal() as db: + row = db.get(DeviceState, device_id) + if row is None: + return + db.delete(row) + db.commit() + + +def _profile_to_dict(profile: DeviceProfile) -> Dict[str, Optional[str]]: + return { + 'device_id': profile.device_id, + 'friendly_name': profile.friendly_name, + 'refresh_interval': profile.refresh_interval, + 'time_zone': profile.time_zone, + 'last_seen': profile.last_seen + } + + +def get_device_profile(device_id: str) -> Optional[Dict[str, Optional[str]]]: + with SessionLocal() as db: + profile = db.get(DeviceProfile, device_id) + if profile is None: + return None + return _profile_to_dict(profile) + + +def ensure_device_profile(device_id: str) -> Dict[str, Optional[str]]: + timestamp = _utcnow() + with SessionLocal() as db: + profile = db.get(DeviceProfile, device_id) + if profile is None: + profile = DeviceProfile( + device_id=device_id, + created_at=timestamp, + updated_at=timestamp, + last_seen=timestamp + ) + db.add(profile) + db.commit() + db.refresh(profile) + return _profile_to_dict(profile) + + +def update_device_profile( + device_id: str, + *, + friendly_name: Optional[str] = None, + refresh_interval: Optional[int] = None, + time_zone: Optional[str] = None +) -> Dict[str, Optional[str]]: + timestamp = _utcnow() + with SessionLocal() as db: + profile = db.get(DeviceProfile, device_id) + if profile is None: + profile = DeviceProfile(device_id=device_id, created_at=timestamp) + db.add(profile) + if friendly_name is not None: + profile.friendly_name = friendly_name + if refresh_interval is not None: + profile.refresh_interval = refresh_interval + if time_zone is not None: + profile.time_zone = time_zone + profile.updated_at = timestamp + db.commit() + db.refresh(profile) + return _profile_to_dict(profile) + + +def touch_device_last_seen(device_id: str) -> None: + timestamp = _utcnow() + with SessionLocal() as db: + profile = db.get(DeviceProfile, device_id) + if profile is None: + profile = DeviceProfile(device_id=device_id, created_at=timestamp) + db.add(profile) + profile.last_seen = timestamp + db.commit() + + +def list_device_profiles() -> List[Dict[str, Optional[str]]]: + with SessionLocal() as db: + rows = db.execute(select(DeviceProfile).order_by(DeviceProfile.device_id)).scalars().all() + return [_profile_to_dict(row) for row in rows] + + +def save_config_entry(key: str, value: str) -> None: + """Persist a configuration key/value pair for future restarts.""" + with SessionLocal() as db: + entry = db.get(ConfigEntry, key) + if entry is None: + entry = ConfigEntry(key=key, value=str(value)) + db.add(entry) + else: + entry.value = str(value) + db.commit() + + +def load_config_entries() -> Dict[str, str]: + """Return all persisted configuration entries as a key/value mapping.""" + with SessionLocal() as db: + stmt = select(ConfigEntry) + rows = db.execute(stmt).scalars().all() + return {row.key: row.value for row in rows} diff --git a/trmnl_server/plugins/__init__.py b/trmnl_server/plugins/__init__.py new file mode 100644 index 0000000..91d38b0 --- /dev/null +++ b/trmnl_server/plugins/__init__.py @@ -0,0 +1,3 @@ +""" +Plugins package for trmnlServer. +""" diff --git a/trmnl_server/plugins/base.py b/trmnl_server/plugins/base.py new file mode 100644 index 0000000..edec7bd --- /dev/null +++ b/trmnl_server/plugins/base.py @@ -0,0 +1,631 @@ +from abc import ABC, abstractmethod +import asyncio +import logging +import math +import os +from dataclasses import dataclass +from typing import Optional, Tuple, List, Sequence + +from PIL import Image, ImageOps, ImageEnhance, ImageFont, ImageDraw + +from .. import config +from ..utils import save_display_assets, load_font as utils_load_font + +logger = logging.getLogger(__name__) + + +@dataclass(frozen=True) +class PluginOutput: + """Paths to the generated monochrome BMP and grayscale PNG assets.""" + + monochrome_path: str + grayscale_path: str + + +@dataclass(frozen=True) +class ChartBounds: + """Normalized rectangle describing the drawable chart area.""" + + x0: float + y0: float + x1: float + y1: float + + @property + def width(self) -> float: + return self.x1 - self.x0 + + @property + def height(self) -> float: + return self.y1 - self.y0 + + +@dataclass(frozen=True) +class AxisScale: + """Normalized Y-axis scaling parameters.""" + + axis_min: float + axis_max: float + step: float + + @property + def span(self) -> float: + return max(self.axis_max - self.axis_min, 1.0) + + +class PluginBase(ABC): + """Abstract base class for image-producing plugins with optional adjustments.""" + + BASENAME: str = 'plugin' + OUTPUT_SUBDIR: Optional[str] = None + SET_PRIMARY: bool = False + AUTO_REGISTER: bool = True + REFRESH_INTERVAL: Optional[int] = None + REGISTRY_ORDER: int = 100 + + def __init__(self): + self.name = self.__class__.__name__ + + def get_display_name(self) -> str: + display_attr = getattr(self, 'DISPLAY_NAME', None) + return str(display_attr) if display_attr else self.name + + @abstractmethod + async def run(self, **kwargs) -> Optional[PluginOutput]: + """Execute the plugin logic asynchronously.""" + raise NotImplementedError + + def get_adjustment_settings(self) -> Tuple[bool, float, float]: + """Return (apply_contrast, gamma_value, contrast_cutoff).""" + return (False, 1.0, 0.0) + + def get_content_ttl(self) -> int: + """Number of seconds this plugin's output remains fresh.""" + return 900 + + def apply_adjustments(self, image: Image.Image) -> Image.Image: + """Apply optional contrast and gamma adjustments according to plugin settings.""" + apply_contrast, gamma_value, contrast_cutoff = self.get_adjustment_settings() + adjusted = image + + if apply_contrast: + adjusted = ImageOps.autocontrast(adjusted, cutoff=contrast_cutoff) + + if gamma_value and gamma_value != 1.0: + inv_gamma = 1.0 / gamma_value + adjusted = adjusted.point( + lambda value: max(0, min(255, int(round((value / 255.0) ** inv_gamma * 255)))) + ) + + return adjusted + + @staticmethod + def lift_black_point(image: Image.Image, offset: int = 16) -> Image.Image: + """Raise the black point to recover detail in deep shadows.""" + offset = max(0, min(offset, 64)) + lut = [min(255, value + offset) for value in range(256)] + return image.point(lut) + + @staticmethod + def boost_shadows(image: Image.Image, pivot: int = 180, shadow_gamma: float = 0.7) -> Image.Image: + """Brighten tonal values below the pivot using a gamma curve.""" + pivot = max(1, min(pivot, 254)) + pivot_norm = pivot / 255.0 + lut = [] + for value in range(256): + normalized = value / 255.0 + if normalized < pivot_norm: + ratio = normalized / pivot_norm + remapped = (ratio ** shadow_gamma) * pivot_norm + else: + remapped = normalized + lut.append(int(round(remapped * 255))) + return image.point(lut) + + def apply_eink_grading( + self, + image: Image.Image, + *, + shadow_pivot: int = 180, + shadow_gamma: float = 0.65, + brightness: float = 1.1, + contrast_cutoff: float = 0.05 + ) -> Image.Image: + """Apply a shadow lift, brightness tweak, and autocontrast pass.""" + lifted = self.boost_shadows(image, pivot=shadow_pivot, shadow_gamma=shadow_gamma) + brightened = ImageEnhance.Brightness(lifted).enhance(brightness) + return ImageOps.autocontrast(brightened, cutoff=contrast_cutoff) + + def prepare_image(self, image: Image.Image) -> Image.Image: + """Convert plugin output to grayscale and apply the configured adjustments.""" + grayscale = image.convert('L') if image.mode != 'L' else image + return self.apply_adjustments(grayscale) + + def save_assets( + self, + image: Image.Image, + output_dir: str, + basename: str, + dither_mode: Optional[str] = None + ) -> PluginOutput: + """Apply uniform processing and persist BMP/PNG outputs for the plugin.""" + prepared = self.prepare_image(image) + bmp_path, png_path = save_display_assets( + prepared, + output_dir, + basename, + dither_mode=dither_mode + ) + return PluginOutput(monochrome_path=bmp_path, grayscale_path=png_path) + + @staticmethod + def load_font(size: int, fallback_paths: Optional[Tuple[str, ...]] = None) -> ImageFont.ImageFont: + """Attempt to load a font from several candidate paths, falling back gracefully.""" + return utils_load_font(size, fallback_paths) + + +class ChartPlugin(PluginBase): + """Base class for numeric time-series charts with smooth curves and shared styling.""" + + SERIES_LABEL: str = "Series" + BASENAME: str = "chart" + CANVAS_SIZE: Tuple[int, int] = (800, 480) + MARGIN_X: int = 70 + MARGIN_Y: int = 80 + GRID_Y_STEPS: int = 5 + GRID_X_LABELS: int = 8 + CURVE_SAMPLES: int = 12 + CURVE_SMOOTHING: float = 2.5 + TITLE_FONT_SIZE: int = 32 + AXIS_FONT_SIZE: int = 16 + VALUE_FONT_SIZE: int = 20 + CAPTION_FONT_SIZE: int = 14 + GRID_COLOR: int = 210 + AXIS_COLOR: int = 120 + CURVE_COLOR: int = 0 + MAX_MARKER_RADIUS: int = 8 + CHART_STYLE: str = "area" + AREA_GRADIENT_TOP: int = 170 + AREA_GRADIENT_BOTTOM: int = 255 + DITHER_MODE: Optional[str] = 'floyd-steinberg' + CAPTION_TEXT: Optional[str] = None + + def get_content_ttl(self) -> int: + return 1800 # default 30 minutes + + async def run(self, **kwargs) -> Optional[PluginOutput]: + output_dir = kwargs.get('output_dir', 'web') + os.makedirs(output_dir, exist_ok=True) + + dataset = await self._fetch_series() + if not dataset: + logger.warning("%s feed returned no datapoints", self.__class__.__name__) + return None + + chart = await asyncio.to_thread(self._render_chart, dataset) + output = await asyncio.to_thread( + self.save_assets, + chart, + output_dir, + self.BASENAME, + dither_mode=self.DITHER_MODE + ) + logger.info( + "%s assets saved to %s and %s", + self.__class__.__name__, + output.monochrome_path, + output.grayscale_path + ) + return output + + @abstractmethod + async def _fetch_series(self) -> Sequence[Tuple[str, int]]: + ... + + def _render_chart(self, dataset: Sequence[Tuple[str, int]]) -> Image.Image: + image, draw = self._create_canvas() + bounds = self._chart_bounds() + fonts = { + 'title': self.load_font(self.TITLE_FONT_SIZE), + 'axis': self.load_font(self.AXIS_FONT_SIZE), + 'value': self.load_font(self.VALUE_FONT_SIZE), + 'caption': self.load_font(self.CAPTION_FONT_SIZE) + } + + labels: List[str] = [name for name, _ in dataset] + values: List[int] = [int(value) for _, value in dataset] + if not values: + return image + + stats = self._compute_value_stats(values) + axis_scale = self._calculate_axis_scale(stats[0], stats[1]) + points = self._map_points(values, bounds, axis_scale) + smooth_points = self._smooth_points(points) + + self._draw_title(draw, fonts['title']) + self._draw_axes(draw, bounds) + self._draw_grid(draw, bounds, axis_scale) + self._draw_max_band(draw, bounds, axis_scale, stats[1]) + self._draw_area_fill(image, smooth_points, bounds) + self._draw_curve(draw, smooth_points) + self._draw_y_labels(draw, bounds, fonts['axis'], axis_scale) + self._draw_x_labels(draw, bounds, fonts['axis'], labels) + self._draw_max_marker(draw, points, values, fonts['value']) + self._draw_legend(draw, bounds, fonts['axis'], stats, sum(values)) + self._draw_caption(draw, bounds, fonts['caption']) + + return image + + def _create_canvas(self) -> Tuple[Image.Image, ImageDraw.ImageDraw]: + image = Image.new('L', self.CANVAS_SIZE, color=255) + return image, ImageDraw.Draw(image) + + def _chart_bounds(self) -> ChartBounds: + width, height = self.CANVAS_SIZE + return ChartBounds(self.MARGIN_X, self.MARGIN_Y, width - self.MARGIN_X, height - 60) + + def _draw_title(self, draw: ImageDraw.ImageDraw, font: ImageFont.ImageFont) -> None: + title = self.SERIES_LABEL + bbox = draw.textbbox((0, 0), title, font=font) + width, _ = self.CANVAS_SIZE + draw.text(((width - (bbox[2] - bbox[0])) / 2, 20), title, fill=0, font=font) + + def _draw_axes(self, draw: ImageDraw.ImageDraw, bounds: ChartBounds) -> None: + draw.line([(bounds.x0, bounds.y0), (bounds.x0, bounds.y1)], fill=self.AXIS_COLOR, width=2) + draw.line([(bounds.x0, bounds.y1), (bounds.x1, bounds.y1)], fill=self.AXIS_COLOR, width=2) + + def _draw_grid(self, draw: ImageDraw.ImageDraw, bounds: ChartBounds, axis_scale: AxisScale) -> None: + tick_values = self._generate_tick_values(axis_scale) + for value in tick_values: + if value in (axis_scale.axis_min, axis_scale.axis_max): + continue + ratio = (axis_scale.axis_max - value) / axis_scale.span + gy = bounds.y0 + ratio * bounds.height + draw.line([(bounds.x0, gy), (bounds.x1, gy)], fill=self.GRID_COLOR, width=1) + for step in range(1, self.GRID_X_LABELS): + gx = bounds.x0 + (step * bounds.width / self.GRID_X_LABELS) + draw.line([(gx, bounds.y0), (gx, bounds.y1)], fill=self.GRID_COLOR, width=1) + + @staticmethod + def _compute_value_stats(values: Sequence[int]) -> Tuple[int, int, float]: + if not values: + return (0, 1, 1.0) + min_val = min(values) + max_val = max(values) + if min_val == max_val: + max_val += 1 + span = float(max_val - min_val) + return (min_val, max_val, span) + + def _map_points( + self, + values: Sequence[int], + bounds: ChartBounds, + axis_scale: AxisScale + ) -> List[Tuple[float, float]]: + sample_count = max(1, len(values) - 1) + points: List[Tuple[float, float]] = [] + for idx, value in enumerate(values): + px = bounds.x0 + (idx / sample_count) * bounds.width if sample_count else bounds.x0 + normalized = (value - axis_scale.axis_min) / axis_scale.span if axis_scale.span else 0.0 + py = bounds.y1 - normalized * bounds.height + points.append((px, py)) + return points + + def _smooth_points(self, points: Sequence[Tuple[float, float]]) -> List[Tuple[float, float]]: + if len(points) < 2 or self.CURVE_SAMPLES <= 0: + return list(points) + + xs = [px for px, _ in points] + ys = [py for _, py in points] + deltas: List[float] = [] + for idx in range(len(points) - 1): + dx = xs[idx + 1] - xs[idx] + if dx <= 0: + return list(points) + deltas.append((ys[idx + 1] - ys[idx]) / dx) + + slopes = self._compute_monotone_slopes(xs, deltas) + smooth: List[Tuple[float, float]] = [points[0]] + for idx in range(len(points) - 1): + smooth.extend( + self._hermite_segment_samples( + xs[idx], + ys[idx], + xs[idx + 1], + ys[idx + 1], + slopes[idx], + slopes[idx + 1] + ) + ) + smooth.append(points[idx + 1]) + return smooth + + def _compute_monotone_slopes(self, xs: Sequence[float], deltas: Sequence[float]) -> List[float]: + count = len(xs) + slopes = [0.0] * count + if count < 2: + return slopes + + slopes[0] = self._scale_and_clamp_slope(None, deltas[0], deltas[0]) + slopes[-1] = self._scale_and_clamp_slope(deltas[-1], None, deltas[-1]) + for idx in range(1, count - 1): + prev = deltas[idx - 1] + curr = deltas[idx] + if prev == 0 or curr == 0 or prev * curr < 0: + slopes[idx] = 0.0 + continue + dx_prev = xs[idx] - xs[idx - 1] + dx_next = xs[idx + 1] - xs[idx] + w1 = 2 * dx_next + dx_prev + w2 = dx_next + 2 * dx_prev + raw_slope = (w1 + w2) / (w1 / prev + w2 / curr) + slopes[idx] = self._scale_and_clamp_slope(prev, curr, raw_slope) + return slopes + + def _scale_and_clamp_slope( + self, + prev_delta: Optional[float], + next_delta: Optional[float], + slope: float + ) -> float: + if slope == 0.0: + return 0.0 + scaled = slope * self.CURVE_SMOOTHING + limits: List[float] = [] + if prev_delta not in (None, 0.0): + limits.append(3.0 * abs(prev_delta)) + if next_delta not in (None, 0.0): + limits.append(3.0 * abs(next_delta)) + if not limits: + return 0.0 + limit = min(limits) + magnitude = min(abs(scaled), limit) + return math.copysign(magnitude, scaled) + + def _hermite_segment_samples( + self, + x0: float, + y0: float, + x1: float, + y1: float, + m0: float, + m1: float + ) -> List[Tuple[float, float]]: + segment_points: List[Tuple[float, float]] = [] + span = x1 - x0 + if span <= 0: + return segment_points + + for step in range(1, self.CURVE_SAMPLES + 1): + t = step / (self.CURVE_SAMPLES + 1) + t2 = t * t + t3 = t2 * t + h00 = 2 * t3 - 3 * t2 + 1 + h10 = t3 - 2 * t2 + t + h01 = -2 * t3 + 3 * t2 + h11 = t3 - t2 + x = x0 + t * span + y = ( + h00 * y0 + + h10 * span * m0 + + h01 * y1 + + h11 * span * m1 + ) + segment_points.append((x, y)) + + return segment_points + + def _is_area_chart(self) -> bool: + return self.CHART_STYLE.lower() == 'area' + + def _draw_area_fill( + self, + image: Image.Image, + points: Sequence[Tuple[float, float]], + bounds: ChartBounds + ) -> None: + if not self._is_area_chart() or len(points) < 2: + return + polygon = self._build_area_polygon(points, bounds) + area_layer = Image.new('L', self.CANVAS_SIZE, color=self.AREA_GRADIENT_TOP) + gradient_patch = self._build_area_gradient(bounds) + area_layer.paste( + gradient_patch, + (int(round(bounds.x0)), int(round(bounds.y0))) + ) + mask = Image.new('L', self.CANVAS_SIZE, 0) + mask_draw = ImageDraw.Draw(mask) + mask_draw.polygon(self._round_points(polygon), fill=255) + image.paste(area_layer, mask=mask) + + def _build_area_gradient(self, bounds: ChartBounds) -> Image.Image: + width = max(1, int(math.ceil(bounds.width))) + height = max(1, int(math.ceil(bounds.height))) + top = max(0, min(255, self.AREA_GRADIENT_TOP)) + bottom = max(0, min(255, self.AREA_GRADIENT_BOTTOM)) + column = Image.new('L', (1, height), color=top) + for y in range(height): + ratio = y / max(1, height - 1) + value = int(round(top + (bottom - top) * ratio)) + column.putpixel((0, y), value) + return column.resize((width, height)) + + @staticmethod + def _build_area_polygon( + points: Sequence[Tuple[float, float]], + bounds: ChartBounds + ) -> List[Tuple[float, float]]: + polygon: List[Tuple[float, float]] = [(bounds.x0, bounds.y1)] + polygon.extend(points) + polygon.append((points[-1][0], bounds.y1)) + return polygon + + @staticmethod + def _round_points(points: Sequence[Tuple[float, float]]) -> List[Tuple[int, int]]: + return [(int(round(px)), int(round(py))) for px, py in points] + + def _draw_curve(self, draw: ImageDraw.ImageDraw, points: Sequence[Tuple[float, float]]) -> None: + if len(points) < 2: + return + draw.line(points, fill=self.CURVE_COLOR, width=3) + + def _draw_y_labels( + self, + draw: ImageDraw.ImageDraw, + bounds: ChartBounds, + font: ImageFont.ImageFont, + axis_scale: AxisScale + ) -> None: + for value in self._generate_tick_values(axis_scale): + ratio = (axis_scale.axis_max - value) / axis_scale.span + yy = bounds.y0 + ratio * bounds.height + label = f"{int(round(value)):,}" + bbox = draw.textbbox((0, 0), label, font=font) + draw.line([(bounds.x0 - 6, yy), (bounds.x0, yy)], fill=self.AXIS_COLOR, width=1) + draw.text((bounds.x0 - bbox[2] - 12, yy - (bbox[3] - bbox[1]) / 2), label, fill=self.AXIS_COLOR, font=font) + + def _draw_x_labels( + self, + draw: ImageDraw.ImageDraw, + bounds: ChartBounds, + font: ImageFont.ImageFont, + labels: Sequence[str] + ) -> None: + if not labels: + return + step = max(1, len(labels) // self.GRID_X_LABELS) + for idx in range(0, len(labels), step): + label = labels[idx] + bbox = draw.textbbox((0, 0), label, font=font) + px = bounds.x0 + (idx / max(1, len(labels) - 1)) * bounds.width + draw.text((px - (bbox[2] - bbox[0]) / 2, bounds.y1 + 8), label, fill=0, font=font) + + def _draw_max_band( + self, + draw: ImageDraw.ImageDraw, + bounds: ChartBounds, + axis_scale: AxisScale, + max_value: int + ) -> None: + if not axis_scale.span: + return + ratio = (axis_scale.axis_max - max_value) / axis_scale.span + yy = bounds.y0 + ratio * bounds.height + draw.line([(bounds.x0, yy), (bounds.x1, yy)], fill=self.AXIS_COLOR, width=1) + + def _draw_max_marker( + self, + draw: ImageDraw.ImageDraw, + points: Sequence[Tuple[float, float]], + values: Sequence[int], + font: ImageFont.ImageFont + ) -> None: + if not points or not values: + return + max_idx = max(range(len(values)), key=lambda idx: values[idx]) + px, py = points[max_idx] + draw.ellipse( + ( + px - self.MAX_MARKER_RADIUS, + py - self.MAX_MARKER_RADIUS, + px + self.MAX_MARKER_RADIUS, + py + self.MAX_MARKER_RADIUS + ), + outline=self.AXIS_COLOR, + width=2, + fill=255 + ) + inner_radius = max(2, self.MAX_MARKER_RADIUS // 3) + draw.ellipse( + (px - inner_radius, py - inner_radius, px + inner_radius, py + inner_radius), + fill=self.CURVE_COLOR + ) + label = f"{values[max_idx]:,}" + bbox = draw.textbbox((0, 0), label, font=font) + text_width = bbox[2] - bbox[0] + offset = 12 if px < (self.CANVAS_SIZE[0] - 120) else -text_width - 12 + draw.text((px + offset, py - (bbox[3] - bbox[1]) / 2), label, fill=0, font=font) + + def _draw_legend( + self, + draw: ImageDraw.ImageDraw, + bounds: ChartBounds, + font: ImageFont.ImageFont, + stats: Tuple[int, int, float], + total: int + ) -> None: + min_val, max_val, _ = stats + legend = f"min {min_val:,} · max {max_val:,} · total {total:,}" + draw.text((bounds.x0, bounds.y1 + 40), legend, fill=self.AXIS_COLOR, font=font) + + def _draw_caption( + self, + draw: ImageDraw.ImageDraw, + bounds: ChartBounds, + font: ImageFont.ImageFont + ) -> None: + caption = getattr(self, 'CAPTION_TEXT', None) + if not caption: + return + bbox = draw.textbbox((0, 0), caption, font=font) + width = bbox[2] - bbox[0] + x = bounds.x1 - width + y = bounds.y1 + 40 + draw.text((x, y), caption, fill=self.AXIS_COLOR, font=font) + + def _calculate_axis_scale(self, min_value: int, max_value: int, ticks: int = 5) -> AxisScale: + if max_value == min_value: + max_value += 1 + span = max_value - min_value + nice_steps = (1, 2, 2.5, 5, 10) + base_power = max(math.floor(math.log10(max(max_value, 1))) - 1, 0) + base_unit = max(10 ** base_power, 1) + step = nice_steps[-1] * base_unit + desired_ticks = max(ticks, self.GRID_Y_STEPS) + span = span if span > 0 else step + + for candidate in nice_steps: + candidate_step = int(math.ceil(candidate * base_unit)) + ticks_needed = math.ceil(span / candidate_step) + if ticks_needed <= desired_ticks + 2: + step = candidate_step + break + + axis_min = math.floor(min_value / step) * step + axis_max = math.ceil(max_value / step) * step + if axis_max == axis_min: + axis_max = axis_min + step + return AxisScale(axis_min, axis_max, step) + + def _generate_tick_values(self, axis_scale: AxisScale) -> List[float]: + if axis_scale.step <= 0: + return [axis_scale.axis_min, axis_scale.axis_max] + ticks: List[float] = [] + current = axis_scale.axis_min + while current <= axis_scale.axis_max + 1e-6: + ticks.append(current) + current += axis_scale.step + if ticks[-1] != axis_scale.axis_max: + ticks.append(axis_scale.axis_max) + return ticks + + +class PhotographicPlugin(PluginBase): + """Base class for photograph-oriented plugins with enhanced grading.""" + + def get_adjustment_settings(self) -> Tuple[bool, float, float]: + return (True, 1.2, 0.05) + + def apply_adjustments(self, image: Image.Image) -> Image.Image: + if not bool(getattr(config, 'PHOTO_GRADING_ENABLED', True)): + return image + + adjusted = super().apply_adjustments(image) + return self.apply_eink_grading( + adjusted, + shadow_pivot=180, + shadow_gamma=0.65, + brightness=1.1, + contrast_cutoff=0.05 + ) diff --git a/trmnl_server/plugins/bing.py b/trmnl_server/plugins/bing.py new file mode 100644 index 0000000..2f60d45 --- /dev/null +++ b/trmnl_server/plugins/bing.py @@ -0,0 +1,106 @@ +import asyncio +import logging +import os +from io import BytesIO +from typing import Tuple + +import httpx +from PIL import Image, ImageOps + +from .base import PhotographicPlugin, PluginOutput + +logger = logging.getLogger(__name__) + + +class BingWallpaperPlugin(PhotographicPlugin): + """Download the latest Bing wallpaper and adapt it for TRMNL displays.""" + + BASENAME = "bing_wallpaper" + OUTPUT_SUBDIR = "bing" + REGISTRY_ORDER = 20 + REFRESH_INTERVAL = 3600 + DISPLAY_NAME = "Bing Wallpaper" + + API_URL = "https://www.bing.com/HPImageArchive.aspx" + BASE_URL = "https://www.bing.com" + + def __init__(self, market: str = "en-US"): + super().__init__() + self.market = market + + async def run(self, **kwargs): + """Fetch, process, and persist the latest Bing wallpaper image.""" + market = kwargs.get("market", self.market) + target_size: Tuple[int, int] = kwargs.get("target_size", (800, 480)) + output_dir = kwargs.get("output_dir", "web") + os.makedirs(output_dir, exist_ok=True) + + try: + async with httpx.AsyncClient(timeout=20) as client: + metadata = await self._fetch_metadata(client, market) + if not metadata: + logger.warning("No Bing metadata returned") + return None + + image_url = metadata.get("url") or metadata.get("urlbase") + if not image_url: + logger.warning("Bing metadata missing URL") + return None + + full_url = image_url + if not full_url.startswith("http"): + full_url = f"{self.BASE_URL}{image_url}" + + logger.info("Downloading Bing wallpaper from %s", full_url) + image_bytes = await self._download_image(client, full_url) + processed = await asyncio.to_thread(self._prepare_image, image_bytes, target_size) + + output = await asyncio.to_thread( + self.save_assets, + processed, + output_dir, + 'bing_wallpaper', + dither_mode='floyd-steinberg' + ) + logger.info( + "Saved Bing wallpaper assets to %s and %s", + output.monochrome_path, + output.grayscale_path + ) + return output + except Exception as exc: + logger.error("Failed to fetch Bing wallpaper: %s", exc) + raise + + def get_content_ttl(self) -> int: + return 43200 # 12 hours + + async def _fetch_metadata(self, client: httpx.AsyncClient, market: str) -> dict: + params = { + "format": "js", + "idx": 0, + "n": 1, + "mkt": market + } + response = await client.get(self.API_URL, params=params) + response.raise_for_status() + data = response.json() + images = data.get("images", []) + return images[0] if images else {} + + async def _download_image(self, client: httpx.AsyncClient, url: str) -> bytes: + response = await client.get(url) + response.raise_for_status() + return response.content + + def _prepare_image(self, data: bytes, target_size: Tuple[int, int]) -> Image.Image: + with Image.open(BytesIO(data)) as img: + rgb_image = img.convert("RGB") + fitted = ImageOps.fit( + rgb_image, + target_size, + method=Image.Resampling.LANCZOS, + bleed=0.0, + centering=(0.5, 0.5) + ) + return fitted.convert("L") diff --git a/trmnl_server/plugins/calibration.py b/trmnl_server/plugins/calibration.py new file mode 100644 index 0000000..792c5cb --- /dev/null +++ b/trmnl_server/plugins/calibration.py @@ -0,0 +1,241 @@ +from __future__ import annotations + +from os import makedirs +from typing import Optional, Sequence, Tuple + +from PIL import Image, ImageDraw + +from .base import PluginBase, PluginOutput +from .. import config +from ..utils import get_available_dither_modes, get_effective_grayscale_palette_levels, save_display_assets + + +def _draw_labeled_patch( + draw: ImageDraw.ImageDraw, + *, + box: Tuple[int, int, int, int], + fill: Tuple[int, int, int], + label: str, + font +) -> None: + draw.rectangle(box, fill=fill) + x0, y0, x1, _y1 = box + draw.rectangle((x0, y0, x1, y0 + 20), fill=(255, 255, 255)) + draw.text((x0 + 4, y0 + 2), label, fill=(0, 0, 0), font=font) + + +def _render_calibration_canvas( + size: Tuple[int, int], + *, + title: str, + font_title, + font_small, + strip_panel_levels: Optional[Sequence[int]] = None, + strip_digital_levels: Optional[Sequence[int]] = None +) -> Image.Image: + width, _height = size + image = Image.new('RGB', size, color=(255, 255, 255)) + draw = ImageDraw.Draw(image) + + draw.text((18, 14), title, fill=(0, 0, 0), font=font_title) + + # Grayscale gradient ramp + ramp_top = 60 + ramp_height = 40 + for x in range(width): + v = int(round((x / max(width - 1, 1)) * 255)) + draw.line((x, ramp_top, x, ramp_top + ramp_height), fill=(v, v, v)) + draw.rectangle((0, ramp_top, width - 1, ramp_top + ramp_height), outline=(0, 0, 0)) + + # Tick marks every 32 values + for v in range(0, 256, 32): + x = int(round((v / 255.0) * (width - 1))) + draw.line((x, ramp_top + ramp_height + 2, x, ramp_top + ramp_height + 12), fill=(0, 0, 0)) + draw.text((x + 2, ramp_top + ramp_height + 10), str(v), fill=(0, 0, 0), font=font_small) + + # Solid reference strip using the *effective* palette levels. + # This makes it easy to see what the server is actually sending after tone-curve + # compensation (often not 0/85/170/255 in digital space). + strip_top = 122 + strip_height = 20 + strip_x0 = 18 + strip_x1 = width - 18 + strip_gap = 8 + block_w = int((strip_x1 - strip_x0 - (3 * strip_gap)) / 4) + + if strip_panel_levels is None or strip_digital_levels is None: + panel_levels, digital_levels = get_effective_grayscale_palette_levels(4) + else: + panel_levels = list(strip_panel_levels) + digital_levels = list(strip_digital_levels) + + for idx, value in enumerate(digital_levels[:4]): + x0 = strip_x0 + idx * (block_w + strip_gap) + x1 = x0 + block_w + box = (x0, strip_top, x1, strip_top + strip_height) + draw.rectangle(box, fill=(value, value, value), outline=(0, 0, 0)) + text_color = (255, 255, 255) if value < 96 else (0, 0, 0) + panel_value = panel_levels[idx] if idx < len(panel_levels) else value + draw.text((x0 + 4, strip_top + 2), f"{value}/{panel_value}", fill=text_color, font=font_small) + + # Color patches (helps visualize how RGB collapses to grayscale) + patches_top = 150 + patch_w = 190 + patch_h = 78 + gap = 10 + colors: Sequence[Tuple[str, Tuple[int, int, int]]] = ( + ("RED", (255, 0, 0)), + ("GREEN", (0, 255, 0)), + ("BLUE", (0, 0, 255)), + ("CYAN", (0, 255, 255)), + ("MAGENTA", (255, 0, 255)), + ("YELLOW", (255, 255, 0)), + ("ORANGE", (255, 165, 0)), + ("PURPLE", (128, 0, 128)), + ) + + for idx, (label, color) in enumerate(colors): + col = idx % 4 + row = idx // 4 + x0 = 18 + col * (patch_w + gap) + y0 = patches_top + row * (patch_h + gap) + x1 = x0 + patch_w + y1 = y0 + patch_h + _draw_labeled_patch(draw, box=(x0, y0, x1, y1), fill=color, label=label, font=font_small) + draw.rectangle((x0, y0, x1, y1), outline=(0, 0, 0)) + + # Fine detail patterns + patterns_top = 330 + pattern_h = 140 + pattern_w = 250 + + def box_at(index: int) -> Tuple[int, int, int, int]: + x0 = 18 + index * (pattern_w + 10) + y0 = patterns_top + return (x0, y0, x0 + pattern_w, y0 + pattern_h) + + # 1px vertical lines + x0, y0, x1, y1 = box_at(0) + draw.rectangle((x0, y0, x1, y1), fill=(255, 255, 255), outline=(0, 0, 0)) + draw.text((x0 + 4, y0 + 2), "1px vertical", fill=(0, 0, 0), font=font_small) + for x in range(x0 + 8, x1 - 8): + if (x - (x0 + 8)) % 2 == 0: + draw.line((x, y0 + 24, x, y1 - 8), fill=(0, 0, 0)) + + # 1px diagonal + x0, y0, x1, y1 = box_at(1) + draw.rectangle((x0, y0, x1, y1), fill=(255, 255, 255), outline=(0, 0, 0)) + draw.text((x0 + 4, y0 + 2), "diagonal", fill=(0, 0, 0), font=font_small) + for i in range(0, min(x1 - x0, y1 - y0) - 40): + if i % 2 == 0: + draw.point((x0 + 20 + i, y0 + 30 + i), fill=(0, 0, 0)) + + # Checkerboard 2x2 + x0, y0, x1, y1 = box_at(2) + draw.rectangle((x0, y0, x1, y1), fill=(255, 255, 255), outline=(0, 0, 0)) + draw.text((x0 + 4, y0 + 2), "checker 2x2", fill=(0, 0, 0), font=font_small) + cell = 6 + for yy in range(y0 + 26, y1 - 8, cell): + for xx in range(x0 + 8, x1 - 8, cell): + if (((xx - (x0 + 8)) // cell) + ((yy - (y0 + 26)) // cell)) % 2 == 0: + draw.rectangle((xx, yy, xx + cell - 1, yy + cell - 1), fill=(0, 0, 0)) + + return image + + +class CalibrationPlugin(PluginBase): + AUTO_REGISTER: bool = config.CALIBRATION_PLUGIN_ENABLED + DISPLAY_NAME: str = 'Calibration' + BASENAME: str = 'calibration' + OUTPUT_SUBDIR: Optional[str] = 'calibration' + REGISTRY_ORDER: int = 5 + VARIANT_ROOT_NAME: str = 'calibration' + PRIMARY_DITHER_MODE: str = 'floyd-steinberg' + PRIMARY_VARIANT: str = '' + + def prepare_image(self, image: Image.Image) -> Image.Image: + """Calibration output must bypass any plugin-specific grading/tweaks.""" + return image.convert('L') if image.mode != 'L' else image + + def apply_adjustments(self, image: Image.Image) -> Image.Image: + """No-op: calibration images should remain ungraded.""" + return image + + async def run(self, **kwargs) -> Optional[PluginOutput]: + output_dir = str(kwargs.get('output_dir') or '').strip() or 'web' + makedirs(output_dir, exist_ok=True) + + font_title = self.load_font(34) + font_small = self.load_font(14) + + primary_variant = (self.PRIMARY_VARIANT or '').strip().lower() or self.PRIMARY_DITHER_MODE + + plugin_label = self.get_display_name() + title_prefix = f"TRMNL {plugin_label}" if plugin_label else "TRMNL Calibration" + + if primary_variant == 'unquantized': + title = f"{title_prefix} — unquantized (raw, no tone curve/dither)" + elif primary_variant == 'none': + title = f"{title_prefix} — none (tone curve, no dithering)" + else: + title = f"{title_prefix} — {primary_variant} (tone curve + dithering)" + + base = _render_calibration_canvas( + (800, 480), + title=title, + font_title=font_title, + font_small=font_small, + strip_panel_levels=[0, 85, 170, 255] if primary_variant == 'unquantized' else None, + strip_digital_levels=[0, 85, 170, 255] if primary_variant == 'unquantized' else None + ) + + if primary_variant == 'unquantized': + basename = f"{self.VARIANT_ROOT_NAME}_unquantized" + bmp_path, png_path = save_display_assets( + base, + output_dir, + basename, + dither_mode='none', + grayscale_levels=None + ) + return PluginOutput(monochrome_path=bmp_path, grayscale_path=png_path) + + basename = f"{self.VARIANT_ROOT_NAME}_{primary_variant}".replace('-', '_') + bmp_path, png_path = save_display_assets( + base, + output_dir, + basename, + dither_mode=primary_variant + ) + return PluginOutput(monochrome_path=bmp_path, grayscale_path=png_path) + + +class CalibrationNonePlugin(CalibrationPlugin): + """Calibration plugin variant that returns the non-dithered image for rotation.""" + + DISPLAY_NAME: str = 'Calibration (No Dither)' + BASENAME: str = 'calibration_none' + OUTPUT_SUBDIR: Optional[str] = 'calibration' + REGISTRY_ORDER: int = 6 + PRIMARY_DITHER_MODE: str = 'none' + + +class CalibrationUnquantizedPlugin(CalibrationPlugin): + """Calibration plugin variant that returns the unquantized (8-bit) image for rotation.""" + + DISPLAY_NAME: str = 'Calibration (Unquantized)' + BASENAME: str = 'calibration_unquantized' + OUTPUT_SUBDIR: Optional[str] = 'calibration' + REGISTRY_ORDER: int = 7 + PRIMARY_VARIANT: str = 'unquantized' + + +class CalibrationPerceptualPlugin(CalibrationPlugin): + """Calibration plugin variant that returns the unquantized (8-bit) image for rotation.""" + + DISPLAY_NAME: str = 'Calibration (Perceptual)' + BASENAME: str = 'calibration_perceptual' + OUTPUT_SUBDIR: Optional[str] = 'calibration' + REGISTRY_ORDER: int = 7 + PRIMARY_VARIANT: str = 'perceptual' + PRIMARY_DITHER_MODE: str = 'perceptual' diff --git a/trmnl_server/plugins/charts.py b/trmnl_server/plugins/charts.py new file mode 100644 index 0000000..47a6de8 --- /dev/null +++ b/trmnl_server/plugins/charts.py @@ -0,0 +1,80 @@ +import logging +from typing import List, Sequence, Tuple + +import httpx + +from .base import ChartPlugin + +logger = logging.getLogger(__name__) + +# Node-RED API endpoints for local web stats +PAGEVIEWS_URL = "http://192.168.1.100:1880/api/site/pageviews" +VISITORS_URL = "http://192.168.1.100:1880/api/site/visitors" + +# Node-RED API endpoint for total power consumption +TOTAL_POWER_URL = "http://192.168.1.100:1880/api/power/all" + + +async def _fetch_series(url: str) -> List[Tuple[str, int]]: + async with httpx.AsyncClient(timeout=10) as client: + response = await client.get(url) + response.raise_for_status() + payload = response.json() + entries = payload.get('data', []) + parsed: List[Tuple[str, int]] = [] + for entry in entries: + name = str(entry.get('name', '')).zfill(2) + try: + value = int(entry.get('value', 0)) + except (TypeError, ValueError): + value = 0 + parsed.append((name, value)) + return parsed + + +class PageviewsPlugin(ChartPlugin): + """Render hourly pageviews chart.""" + + DISPLAY_NAME = "Web Stats - Pageviews" + SERIES_LABEL = "Pageviews" + BASENAME = "webstats_pageviews" + OUTPUT_SUBDIR = "webstats" + REGISTRY_ORDER = 60 + REFRESH_INTERVAL = 1800 + CHART_STYLE = "area" + CAPTION_TEXT = "Estimated pageviews - last 24h" + + async def _fetch_series(self) -> Sequence[Tuple[str, int]]: + return await _fetch_series(PAGEVIEWS_URL) + + +class VisitorsPlugin(ChartPlugin): + """Render hourly visitors chart.""" + + DISPLAY_NAME = "Web Stats - Visitors" + SERIES_LABEL = "Visitors" + BASENAME = "webstats_visitors" + OUTPUT_SUBDIR = "webstats" + REGISTRY_ORDER = 70 + REFRESH_INTERVAL = 1800 + CHART_STYLE = "area" + CAPTION_TEXT = "Estimated unique visitors - last 24h" + + async def _fetch_series(self) -> Sequence[Tuple[str, int]]: + return await _fetch_series(VISITORS_URL) + + +class TotalPowerPlugin(ChartPlugin): + """Render the total power chart from the local power feed.""" + + DISPLAY_NAME = "Power - Total" + SERIES_LABEL = "Total Power (W)" + BASENAME = "power_total" + OUTPUT_SUBDIR = "power" + REGISTRY_ORDER = 80 + REFRESH_INTERVAL = 1800 + CHART_STYLE = "area" + CAPTION_TEXT = "All smart outlets combined - last 24h" + + async def _fetch_series(self) -> Sequence[Tuple[str, int]]: + return await _fetch_series(TOTAL_POWER_URL) diff --git a/trmnl_server/plugins/hn.py b/trmnl_server/plugins/hn.py new file mode 100644 index 0000000..08d9a0b --- /dev/null +++ b/trmnl_server/plugins/hn.py @@ -0,0 +1,147 @@ +import asyncio +import logging +import os +import re +from html import unescape +from html.parser import HTMLParser +from typing import List, Optional, Tuple + +import feedparser +import httpx +from PIL import Image, ImageDraw, ImageFont + +from .base import PluginBase, PluginOutput + +logger = logging.getLogger(__name__) + + +class HNPlugin(PluginBase): + """Render an e-ink friendly snapshot of Hacker News front page headlines.""" + + BASENAME = "hackernews" + OUTPUT_SUBDIR = "news" + REGISTRY_ORDER = 40 + REFRESH_INTERVAL = 600 + DISPLAY_NAME = "Hacker News" + + FEED_URL = "https://hnrss.org/frontpage" + + def get_content_ttl(self) -> int: + return 1800 # 30 minutes + + async def run(self, **kwargs) -> Optional[PluginOutput]: + target_size = kwargs.get("target_size", (800, 480)) + max_items = kwargs.get("max_items", 10) + output_dir = kwargs.get("output_dir", "web") + os.makedirs(output_dir, exist_ok=True) + + try: + entries = await self._fetch_entries(max_items) + if not entries: + logger.warning("HN feed returned no entries") + return None + + rendered = await asyncio.to_thread(self._render_entries, entries, target_size) + output = await asyncio.to_thread(self.save_assets, rendered, output_dir, 'hackernews') + logger.info( + "Saved Hacker News assets to %s and %s", + output.monochrome_path, + output.grayscale_path + ) + return output + except Exception as exc: + logger.error("Failed to render HN feed: %s", exc) + raise + + async def _fetch_entries(self, max_items: int) -> List[dict]: + async with httpx.AsyncClient(timeout=10) as client: + response = await client.get(self.FEED_URL) + response.raise_for_status() + payload = response.content + feed = feedparser.parse(payload) + entries = [] + for entry in feed.entries[:max_items]: + points, comments = self._parse_metadata(entry) + entries.append({ + 'title': entry.get('title', 'Untitled'), + 'points': points, + 'comments': comments + }) + return entries + + def _parse_metadata(self, entry) -> Tuple[int, int]: + points = 0 + comments = 0 + summary = entry.get('summary', '') + text = self._strip_html(summary) + points_match = re.search(r'Points:\s*(\d+)', text) + comments_match = re.search(r'#\s*Comments:\s*(\d+)', text) + if points_match: + points = int(points_match.group(1)) + if comments_match: + comments = int(comments_match.group(1)) + return points, comments + + def _strip_html(self, html: str) -> str: + parser = _HTMLStripper() + parser.feed(html or '') + return unescape(parser.get_text()) + + def _render_entries(self, entries: List[dict], target_size) -> Image.Image: + canvas = Image.new('L', target_size, color=255) + draw = ImageDraw.Draw(canvas) + + title_font = self.load_font(28) + item_font = self.load_font(20) + meta_font = self.load_font(16) + + draw.text((30, 20), "Hacker News", fill=0, font=title_font) + draw.line([(30, 60), (target_size[0] - 30, 60)], fill=0, width=1) + + y = 80 + line_height = item_font.size + 10 + + for idx, entry in enumerate(entries, start=1): + title = f"{entry['title']}" + wrapped = self._wrap_text(title, item_font, target_size[0] - 60) + for line in wrapped: + draw.text((40, y), line, fill=0, font=item_font) + y += line_height + + meta = f"{entry['points']} points | {entry['comments']} comments" + draw.text((40, y), meta, fill=80, font=meta_font) + y += meta_font.size + 12 + + if y > target_size[1] - line_height: + break + + return canvas + + def _wrap_text(self, text: str, font: ImageFont.ImageFont, max_width: int) -> List[str]: + words = text.split() + lines: List[str] = [] + current: List[str] = [] + + for word in words: + test_line = " ".join(current + [word]).strip() + if font.getlength(test_line) <= max_width: + current.append(word) + else: + if current: + lines.append(" ".join(current)) + current = [word] + if current: + lines.append(" ".join(current)) + return lines + + +class _HTMLStripper(HTMLParser): + def __init__(self): + super().__init__() + self.parts: List[str] = [] + + def handle_data(self, data: str) -> None: + self.parts.append(data) + + def get_text(self) -> str: + return "\n".join(self.parts) \ No newline at end of file diff --git a/trmnl_server/plugins/random_image.py b/trmnl_server/plugins/random_image.py new file mode 100644 index 0000000..bab146d --- /dev/null +++ b/trmnl_server/plugins/random_image.py @@ -0,0 +1,91 @@ +import asyncio +import logging +import os +import random +from pathlib import Path +from typing import Optional, Sequence, Tuple + +from PIL import Image, ImageOps + +from .base import PhotographicPlugin, PluginOutput + +logger = logging.getLogger(__name__) + +DEFAULT_IMAGE_ROOT = Path(os.environ.get('HOME', '~')).expanduser() / 'Pictures' / 'Samurai Jack' +SUPPORTED_EXTENSIONS = {'.jpg', '.jpeg', '.png', '.bmp', '.gif'} + + +class RandomImagePlugin(PhotographicPlugin): + """Select a random image from disk, adapt it, and add it to the rotation.""" + + BASENAME = "random_image" + OUTPUT_SUBDIR = "random" + REGISTRY_ORDER = 50 + REFRESH_INTERVAL = 1800 + DISPLAY_NAME = "Random Image" + + def get_content_ttl(self) -> int: + return 3600 # 60 minutes + + async def run(self, **kwargs) -> Optional[PluginOutput]: + target_size = kwargs.get('target_size', (800, 480)) + output_dir = kwargs.get('output_dir', 'web') + source_root = Path(kwargs.get('image_root', DEFAULT_IMAGE_ROOT)) + return await asyncio.to_thread( + self._run_sync, + target_size, + output_dir, + source_root + ) + + def _run_sync( + self, + target_size: Sequence[int], + output_dir: str, + source_root: Path + ) -> Optional[PluginOutput]: + os.makedirs(output_dir, exist_ok=True) + + if not source_root.exists(): + logger.warning("Random image root %s does not exist", source_root) + return None + + image_path = self._pick_random_image(source_root) + if not image_path: + logger.warning("No images found under %s", source_root) + return None + + adapted = self._prepare_image(image_path, target_size) + output = self.save_assets( + adapted, + output_dir, + 'random_image', + dither_mode='floyd-steinberg' + ) + logger.info( + "Random image assets saved to %s and %s", + output.monochrome_path, + output.grayscale_path + ) + return output + + def _pick_random_image(self, root: Path) -> Optional[Path]: + candidates = [ + path for path in root.rglob('*') + if path.is_file() and path.suffix.lower() in SUPPORTED_EXTENSIONS + ] + if not candidates: + return None + return random.choice(candidates) + + def _prepare_image(self, image_path: Path, target_size: Sequence[int]) -> Image.Image: + with Image.open(image_path) as img: + rgb_image = img.convert('RGB') + fitted = ImageOps.fit( + rgb_image, + target_size, + method=Image.Resampling.LANCZOS, + bleed=0.0, + centering=(0.5, 0.5) + ) + return fitted.convert('L') diff --git a/trmnl_server/plugins/weather.py b/trmnl_server/plugins/weather.py new file mode 100644 index 0000000..ef31c0b --- /dev/null +++ b/trmnl_server/plugins/weather.py @@ -0,0 +1,234 @@ +import asyncio +from typing import Any, Dict, List + +import httpx +from PIL import Image, ImageDraw + +from .base import PluginBase, PluginOutput +import logging +from .. import config + +logger = logging.getLogger(__name__) + +class WeatherPlugin(PluginBase): + """ + Plugin to fetch weather data and generate a Braun-inspired minimalist visualization. + Uses only black and white with clean lines and excellent typography. + """ + + BASENAME = "weather" + OUTPUT_SUBDIR = "weather" + SET_PRIMARY = True + REGISTRY_ORDER = 10 + DISPLAY_NAME = "Weather" + + def __init__(self): + super().__init__() + # Glyphs temporarily disabled — keep keys for compatibility + self.icons = { + 'sun': '', + 'cloud': '', + 'rain': '', + 'wind': '', + 'thermometer': '', + 'droplet': '', + } + + async def run(self, **kwargs): + """ + Fetch weather and generate Braun-inspired black and white image. + kwargs can contain 'latitude' and 'longitude'. + """ + lat = kwargs.get('latitude', 38.7223) # Default: Lisbon, Portugal + lon = kwargs.get('longitude', -9.1393) + output_dir = kwargs.get('output_dir', config.ASSETS_ROOT) + + logger.info(f"Running WeatherPlugin for lat={lat}, lon={lon}") + + try: + data = await self._fetch_weather_data(lat, lon) + + current_weather = data.get('current_weather', {}) + current_temp = current_weather.get('temperature', 'N/A') + current_windspeed = current_weather.get('windspeed', 'N/A') + + hourly = data.get('hourly', {}) + times = hourly.get('time', [])[:24] # Next 24 hours + temps = hourly.get('temperature_2m', [])[:24] + precip = hourly.get('precipitation', [])[:24] + + if not times or not temps: + logger.error("No weather data found") + return + + # Calculate temperature range + min_temp = min(temps) + max_temp = max(temps) + temp_range = max_temp - min_temp if max_temp != min_temp else 1 + + # Calculate precipitation range + max_precip = max(precip) if precip else 0 + + image = await asyncio.to_thread( + self._render_weather_panel, + current_temp, + current_windspeed, + times, + temps, + precip, + min_temp, + max_temp, + max_precip + ) + output = await asyncio.to_thread(self.save_assets, image, output_dir, 'weather') + logger.info( + "Weather plugin execution complete. Assets saved to %s and %s", + output.monochrome_path, + output.grayscale_path + ) + return output + + except Exception as e: + logger.error(f"Error running WeatherPlugin: {e}") + raise + + async def _fetch_weather_data(self, lat: float, lon: float) -> Dict[str, Any]: + url = ( + "https://api.open-meteo.com/v1/forecast" + f"?latitude={lat}&longitude={lon}&hourly=temperature_2m,precipitation¤t_weather=true" + ) + async with httpx.AsyncClient(timeout=10) as client: + response = await client.get(url) + response.raise_for_status() + return response.json() + + def _render_weather_panel( + self, + current_temp: Any, + current_windspeed: Any, + times: List[str], + temps: List[float], + precip: List[float], + min_temp: float, + max_temp: float, + max_precip: float + ) -> Image.Image: + img = Image.new('RGB', (800, 480), color='white') + draw = ImageDraw.Draw(img) + + title_font = self.load_font(32) + temp_font = self.load_font(96) + label_font = self.load_font(18) + small_font = self.load_font(14) + tick_font = self.load_font(11) + # Use the project's default font for icons (Space Grotesk) + icon_font = self.load_font(24) + + margin = 30 + y_pos = margin + + # Title (glyphs removed) — align at left margin + draw.text((margin, y_pos), "WEATHER", fill='black', font=title_font) + y_pos += 50 + + draw.line([(margin, y_pos), (800 - margin, y_pos)], fill='black', width=1) + y_pos += 25 + + draw.text((margin, y_pos), f"{current_temp}°", fill='black', font=temp_font) + + wind_icon_x = margin + 180 + # Wind glyph removed; draw only the text aligned where the icon used to be + draw.text((wind_icon_x, y_pos + 73), f"{current_windspeed} km/h", + fill='black', font=small_font) + y_pos += 120 + + draw.line([(margin, y_pos), (800 - margin, y_pos)], fill='black', width=1) + y_pos += 25 + + chart_y = y_pos + chart_height = 200 + chart_width = 350 + + chart1_x = margin + draw.text((chart1_x, chart_y - 20), "TEMPERATURE", fill='black', font=label_font) + self._draw_braun_bar_chart( + draw, chart1_x, chart_y, chart_width, chart_height, + temps[::2], times[::2], min_temp, max_temp, + tick_font + ) + + chart2_x = margin + chart_width + 40 + # Droplet glyph removed; align label at chart start + draw.text((chart2_x, chart_y - 20), "PRECIPITATION", fill='black', font=label_font) + self._draw_braun_bar_chart( + draw, chart2_x, chart_y, chart_width, chart_height, + precip[::2], times[::2], 0, max_precip if max_precip > 0 else 1, + tick_font + ) + + return img + + def _draw_braun_bar_chart(self, draw, x, y, width, height, values, labels, min_val, max_val, font): + """ + Draw a Braun-inspired minimalist bar chart. + - Thin, clean lines + - No fills, only outlines + - Minimal labels + - Grid lines for readability + """ + # Draw thin axes + draw.line([(x, y + height), (x + width, y + height)], fill='black', width=1) + draw.line([(x, y), (x, y + height)], fill='black', width=1) + + # Draw subtle horizontal grid lines (Braun style) + for i in range(1, 4): + grid_y = y + (i * height / 4) + draw.line([(x, grid_y), (x + width, grid_y)], fill='#CCCCCC', width=1) + + # Calculate bar width + num_bars = len(values) + if num_bars == 0: + return + + bar_spacing = 3 + bar_width = (width - (num_bars + 1) * bar_spacing) / num_bars + + # Draw bars - Braun style: outlined rectangles, no fill + val_range = max_val - min_val if max_val != min_val else 1 + for i, val in enumerate(values): + bar_x = x + bar_spacing + i * (bar_width + bar_spacing) + bar_height = ((val - min_val) / val_range) * height + bar_y = y + height - bar_height + + # Draw outlined bar (no fill for Braun aesthetic) + if bar_height > 2: # Only draw if visible + draw.rectangle( + [(bar_x, bar_y), (bar_x + bar_width, y + height)], + fill='black', # Solid black bars for contrast + outline='black', + width=1 + ) + + # Draw minimal x-axis labels (every 4th) + for i in range(0, len(labels), 4): + if i < len(labels): + label_x = x + bar_spacing + i * (bar_width + bar_spacing) + time_str = labels[i].split('T')[1][:2] # Just hour + bbox = draw.textbbox((0, 0), time_str, font=font) + text_width = bbox[2] - bbox[0] + draw.text((label_x - text_width/2 + bar_width/2, y + height + 5), + time_str, fill='black', font=font) + + # Draw minimal y-axis scale (3 ticks) - closer to axis + for i in range(3): + tick_val = min_val + (val_range * i / 2) + tick_y = y + height - (i / 2) * height + # Small tick mark + draw.line([(x - 3, tick_y), (x, tick_y)], fill='black', width=1) + # Value label - positioned closer to axis + label_text = f"{tick_val:.0f}" + bbox = draw.textbbox((0, 0), label_text, font=font) + text_width = bbox[2] - bbox[0] + draw.text((x - text_width - 8, tick_y - 6), label_text, fill='black', font=font) + + diff --git a/trmnl_server/plugins/xkcd.py b/trmnl_server/plugins/xkcd.py new file mode 100644 index 0000000..fdae32b --- /dev/null +++ b/trmnl_server/plugins/xkcd.py @@ -0,0 +1,118 @@ +import asyncio +import logging +import os +from io import BytesIO +from typing import Optional + +import httpx +from PIL import Image, ImageDraw, ImageFont, ImageOps + +from .base import PluginBase, PluginOutput + +logger = logging.getLogger(__name__) + + +class XKCDPlugin(PluginBase): + """Fetch the current XKCD comic and render a summary panel.""" + + BASENAME = "xkcd" + OUTPUT_SUBDIR = "xkcd" + REGISTRY_ORDER = 30 + REFRESH_INTERVAL = 3600 + DISPLAY_NAME = "XKCD" + + INFO_URL = "https://xkcd.com/info.0.json" + + async def run(self, **kwargs) -> Optional[PluginOutput]: + """Download the comic of the day, render metadata, and store it as BMP.""" + target_size = kwargs.get("target_size", (800, 480)) + output_dir = kwargs.get("output_dir", "web") + os.makedirs(output_dir, exist_ok=True) + + try: + async with httpx.AsyncClient(timeout=15) as client: + metadata = await self._fetch_metadata(client) + if not metadata: + logger.warning("No XKCD metadata available") + return None + image_bytes = await self._download_image(client, metadata.get("img")) + comic_image = await asyncio.to_thread(self._load_image, image_bytes) + rendered = await asyncio.to_thread(self._render_panel, comic_image, metadata, target_size) + output = await asyncio.to_thread(self.save_assets, rendered, output_dir, 'xkcd') + logger.info( + "Saved XKCD assets to %s and %s", + output.monochrome_path, + output.grayscale_path + ) + return output + except Exception as exc: + logger.error("Failed to fetch XKCD comic: %s", exc) + raise + + def get_content_ttl(self) -> int: + return 43200 # 12 hours; comics update daily + + async def _fetch_metadata(self, client: httpx.AsyncClient) -> dict: + response = await client.get(self.INFO_URL) + response.raise_for_status() + return response.json() + + async def _download_image(self, client: httpx.AsyncClient, url: Optional[str]) -> bytes: + if not url: + raise ValueError("XKCD metadata missing image URL") + response = await client.get(url) + response.raise_for_status() + return response.content + + def _load_image(self, data: bytes) -> Image.Image: + return Image.open(BytesIO(data)).convert("RGB") + + def _render_panel(self, comic: Image.Image, metadata: dict, target_size) -> Image.Image: + base_canvas = Image.new("L", target_size, color=255) + base_draw = ImageDraw.Draw(base_canvas) + + title = metadata.get("safe_title") or metadata.get("title", "XKCD") + alt_text = metadata.get("alt", "") + transcript = metadata.get("transcript", "") + + title_font = self.load_font(32) + body_font = self.load_font(18) + + max_comic_height = 280 + max_comic_width = target_size[0] - 60 + fitted = ImageOps.contain(comic, (max_comic_width, max_comic_height)) + fitted = fitted.convert("L") + + top_margin = 30 + comic_x = max(0, (target_size[0] - fitted.width) // 2) + base_canvas.paste(fitted, (comic_x, top_margin)) + draw = ImageDraw.Draw(base_canvas) + + text_y = top_margin + fitted.height + 20 + draw.text((30, text_y), title, fill=0, font=title_font) + text_y += title_font.size + 10 + + wrapped_alt = self._wrap_text(alt_text or transcript, body_font, target_size[0] - 60) + for line in wrapped_alt: + draw.text((30, text_y), line, fill=0, font=body_font) + text_y += body_font.size + 4 + + return base_canvas + + def _wrap_text(self, text: str, font: ImageFont.ImageFont, max_width: int): + words = text.split() + lines = [] + current = [] + + for word in words: + test_line = " ".join(current + [word]).strip() + width = font.getlength(test_line) + if width <= max_width: + current.append(word) + else: + if current: + lines.append(" ".join(current)) + current = [word] + if current: + lines.append(" ".join(current)) + return lines \ No newline at end of file diff --git a/trmnl_server/routes/__init__.py b/trmnl_server/routes/__init__.py new file mode 100644 index 0000000..a7b969a --- /dev/null +++ b/trmnl_server/routes/__init__.py @@ -0,0 +1,7 @@ +"""FastAPI routers for the TRMNL local server.""" + +from .api import router as api_router +from .images import router as image_router +from .pages import router as page_router + +__all__ = ['api_router', 'image_router', 'page_router'] diff --git a/trmnl_server/routes/api.py b/trmnl_server/routes/api.py new file mode 100644 index 0000000..555c7cf --- /dev/null +++ b/trmnl_server/routes/api.py @@ -0,0 +1,557 @@ +"""API routes for TRMNL local server.""" + +from __future__ import annotations + +from datetime import datetime, timedelta, timezone +from typing import Any, Dict, List, Optional +from urllib.parse import quote + +from hashlib import sha256 +from time import time +import psutil +from fastapi import APIRouter, Body, Header, Query, Request +from fastapi.responses import JSONResponse, Response + +from .. import config, models, utils +from ..services import plugins, state + +router = APIRouter() +logger = config.logger + + +def _serialize_device_payload(device_id: str) -> Dict[str, Any]: + profile = state.ensure_device_profile(device_id) + metrics = state.get_client_metrics(device_id) + device_state = state.get_device_state(device_id) + playlist = state.get_playlist_selection(device_id) + binding_name = state.get_device_playlist_binding_name(device_id) or state.DEFAULT_DEVICE_ID + current_entry_hash = device_state.get('last_entry_hash') + preview_url = device_state.get('current_preview_url') or f"/preview/{quote(device_id)}" + preview_token = device_state.get('current_preview_token') + return { + 'device_id': device_id, + 'friendly_name': profile.get('friendly_name') or device_id, + 'refresh_interval': state.get_refresh_interval(device_id), + 'playlist_name': binding_name, + 'playlist': playlist, + 'metrics': { + 'refresh_rate': metrics.get('refresh_rate'), + 'battery_voltage': metrics.get('battery_voltage'), + 'battery_state': utils.get_battery_state(metrics.get('battery_voltage')), + 'rssi': metrics.get('rssi'), + 'last_contact': utils.to_iso_timestamp(metrics.get('last_contact')) + }, + 'profile': { + 'refresh_interval': profile.get('refresh_interval'), + 'time_zone': profile.get('time_zone'), + 'last_seen': utils.to_iso_datetime(profile.get('last_seen')) if profile.get('last_seen') else None + }, + 'state': { + 'supports_grayscale': device_state.get('supports_grayscale'), + 'current_entry_hash': current_entry_hash, + 'current_plugin_id': device_state.get('last_entry_plugin'), + 'current_preview_url': preview_url, + 'current_preview_token': preview_token + } + } + + +@router.get('/api/display') +@router.get('/api/display/') +async def display( + request: Request, + refresh_rate: Optional[str] = Header(None, alias='Refresh-Rate'), + battery_voltage: Optional[str] = Header(None, alias='Battery-Voltage'), + rssi: Optional[str] = Header(None, alias='RSSI') +) -> JSONResponse: + """Main firmware endpoint returning the next image URL and metadata.""" + device_id, device_state = state.get_device_state_from_request(request) + state.ensure_device_profile(device_id) + models.add_log_entry( + 'Request received at /api/display', + f'Headers: {request.headers},URL: {request.url}, device: {device_id}' + ) + logger.info('[API] /api/display - URL: %s device: %s', request.url, device_id) + + fw_version = request.headers.get('fw-version') + grayscale_ready = utils.firmware_supports_grayscale(fw_version) + with state.STATE_LOCK: + device_state['supports_grayscale'] = grayscale_ready + + update_kwargs = { + 'refresh_rate': int(refresh_rate) if refresh_rate is not None else None, + 'battery_voltage': float(battery_voltage) if battery_voltage is not None else None, + 'rssi': int(rssi) if rssi is not None else None + } + state.update_client_metrics(device_id, **update_kwargs) + models.touch_device_last_seen(device_id) + if battery_voltage is not None and rssi is not None: + models.add_battery_status(float(battery_voltage), int(rssi)) + + base_url = state.request_base_url(request) + + grayscale_path: Optional[str] = None + sequence = 0 + with state.STATE_LOCK: + send_switch = device_state['bmp_send_switch'] + adapted_url = base_url + ('/image/screen.bmp' if send_switch else '/image/screen1.bmp') + device_state['bmp_send_switch'] = not send_switch + if grayscale_ready: + grayscale_switch = device_state.get('grayscale_send_switch', True) + grayscale_path = '/image/grayscale.png' if grayscale_switch else '/image/grayscale1.png' + device_state['grayscale_send_switch'] = not grayscale_switch + sequence = device_state.get('token_sequence', 0) + 1 + device_state['token_sequence'] = sequence + + entry_idx: Optional[int] = None + try: + entry_idx = state.schedule_next_rotation_entry(device_id, device_state) + except state.RotationUnavailableError as exc: + logger.warning('[API] rotation unavailable for %s: %s; attempting plugin refresh', device_id, exc) + await plugins.refresh_plugin_assets() + try: + entry_idx = state.schedule_next_rotation_entry(device_id, device_state) + except state.RotationUnavailableError as exc2: + logger.error('[API] rotation still unavailable for %s after refresh: %s', device_id, exc2) + entry_idx = None + + if entry_idx is None: + base_url = state.request_base_url(request) + sequence = 0 + with state.STATE_LOCK: + send_switch = device_state['bmp_send_switch'] + device_state['bmp_send_switch'] = not send_switch + if grayscale_ready: + grayscale_switch = device_state.get('grayscale_send_switch', True) + device_state['grayscale_send_switch'] = not grayscale_switch + sequence = device_state.get('token_sequence', 0) + 1 + device_state['token_sequence'] = sequence + + request_version = device_state.get('request_count', 0) + salt = f"{device_id}-{sequence}-{request_version}-dummy" + token = sha256(salt.encode('utf-8')).hexdigest()[:16] + state.register_image_token(device_id, token) + + separator = '&' if '?' in base_url else '?' + image_url = f"{base_url}/image/dummy.bmp{separator}token={token}" + response = { + 'status': 0, + 'image_url': image_url, + 'filename': token, + 'update_firmware': False, + 'firmware_url': base_url + '/fw/update', + 'refresh_rate': state.get_refresh_interval(device_id), + 'reset_firmware': False, + 'special_function': '', + 'action': '' + } + models.add_log_entry('send json /api/display', f'response: {response}') + return JSONResponse(response) + + state.update_device_preview(device_id, device_state, entry_idx) + + entry_hash = device_state.get('last_entry_hash') or str(entry_idx) + request_version = device_state.get('request_count', 0) + salt = f"{device_id}-{sequence}-{request_version}-{entry_hash}" + token = sha256(salt.encode('utf-8')).hexdigest()[:16] + + state.register_image_token(device_id, token) + + separator = '&' if '?' in adapted_url else '?' + image_url = f"{adapted_url}{separator}token={token}" + pending_media = None + with state.STATE_LOCK: + pending_media = device_state.get('pending_entry_media') + + if grayscale_ready and grayscale_path and pending_media != 'bmp': + image_url = f"{base_url}{grayscale_path}?token={token}" + + response = { + 'status': 0, + 'image_url': image_url, + 'filename': token, + 'update_firmware': False, + 'firmware_url': base_url + '/fw/update', + 'refresh_rate': state.get_refresh_interval(device_id), + 'reset_firmware': False, + 'special_function': '', + 'action': '' + } + + models.add_log_entry('send json /api/display', f'response: {response}') + return JSONResponse(response) + + +@router.get('/api/setup') +@router.get('/api/setup/') +def api_setup(request: Request) -> JSONResponse: + """Provide setup metadata expected by TRMNL clients.""" + base_url = state.request_base_url(request) + payload = { + 'status': 200, + 'api_key': config.SETUP_API_KEY, + 'friendly_id': config.SETUP_FRIENDLY_ID, + 'image_url': base_url + '/image/screen.bmp', + 'message': config.SETUP_MESSAGE + } + models.add_log_entry('send json /api/setup', f'response: {payload}') + return JSONResponse(payload) + + +@router.get('/settings') +def get_settings() -> JSONResponse: + """Retrieve the current settings for the terminal server.""" + return JSONResponse({ + 'config_image_path': config.IMAGE_PATH, + 'config_refresh_time': config.REFRESH_TIME + }) + + +@router.post('/settings/refreshtime') +def update_refresh_time(data: Dict[str, Any] = Body(...)) -> JSONResponse: + """Update the refresh time in the configuration.""" + new_refresh_time = data.get('refresh_rate') + if new_refresh_time is None: + return JSONResponse({'status': 'error', 'message': 'Invalid refresh rate'}, status_code=400) + + config.update_config('refresh_time', new_refresh_time) + models.save_config_entry('refresh_time', str(config.REFRESH_TIME)) + return JSONResponse({'status': 'success', 'new_refresh_time': config.REFRESH_TIME}, status_code=200) + + +@router.post('/settings/imagepath') +def update_image_path(data: Dict[str, Any] = Body(...)) -> JSONResponse: + """Update the fallback image path in the configuration.""" + new_image_path = data.get('bmp_path') + if new_image_path is None: + return JSONResponse({'status': 'error', 'message': 'Invalid new_image_path'}, status_code=400) + + config.update_config('image_path', new_image_path) + models.save_config_entry('image_path', config.IMAGE_PATH) + return JSONResponse({'status': 'success', 'new_image_path': config.IMAGE_PATH}, status_code=200) + + +@router.post('/api/log') +@router.post('/api/log/') +async def api_log(request: Request) -> JSONResponse: + """Capture and persist client log payloads while echoing them to stdout.""" + raw_body = await request.body() + body_text = raw_body.decode('utf-8', errors='replace') if raw_body else '' + + logger.info('[API] /api/log - payload: %s', body_text) + print(body_text) + models.add_log_entry('Request received at /api/log', body_text) + + parsed_content: Dict[str, Any] = {} + try: + parsed_content = await request.json() + except ValueError: + pass + + logs_array: List[Any] = [] + if isinstance(parsed_content, dict): + log_block = parsed_content.get('log') + if isinstance(log_block, dict): + logs_array = log_block.get('logs_array') or [] + + for log_entry in logs_array: + models.add_log_entry('Client Log', str(log_entry)) + print(str(log_entry)) + + return JSONResponse({'status': 'logged'}, status_code=200) + + +@router.get('/rotation') +def get_rotation_playlist() -> JSONResponse: + """Expose the current rotation entries and default playlist selection.""" + snapshot = state.build_rotation_snapshot() + return JSONResponse(snapshot) + + +@router.post('/rotation') +def update_rotation_playlist(data: Dict[str, Any] = Body(...)) -> JSONResponse: + """Update the default or per-device rotation playlist using entry IDs.""" + playlist_ids = data.get('playlist') + device_id = data.get('device_id') + + if not isinstance(playlist_ids, list) or not all(isinstance(pid, str) for pid in playlist_ids): + return JSONResponse({'status': 'error', 'message': 'playlist must be a list of IDs'}, status_code=400) + + try: + if device_id: + state.set_device_playlist(device_id, playlist_ids) + else: + state.set_default_playlist(playlist_ids) + except ValueError as exc: + return JSONResponse({'status': 'error', 'message': str(exc)}, status_code=400) + + snapshot = state.build_rotation_snapshot() + return JSONResponse(snapshot) + + +@router.post('/playlists') +def upsert_named_playlist(data: Dict[str, Any] = Body(...)) -> JSONResponse: + """Create or update a named rotation playlist entity.""" + name = data.get('name') + playlist_ids = data.get('playlist') + + if not isinstance(name, str) or not name.strip() or name.strip() == state.DEFAULT_DEVICE_ID: + return JSONResponse({'status': 'error', 'message': 'name must be a non-default string'}, status_code=400) + if not isinstance(playlist_ids, list) or not all(isinstance(pid, str) for pid in playlist_ids): + return JSONResponse({'status': 'error', 'message': 'playlist must be a list of IDs'}, status_code=400) + + try: + state.set_named_playlist(name.strip(), playlist_ids) + except ValueError as exc: + return JSONResponse({'status': 'error', 'message': str(exc)}, status_code=400) + + snapshot = state.build_rotation_snapshot() + return JSONResponse(snapshot) + + +@router.delete('/playlists/{name}') +def delete_named_playlist(name: str) -> JSONResponse: + """Delete a named playlist and unbind any devices using it.""" + if not name or name.strip() == state.DEFAULT_DEVICE_ID: + return JSONResponse({'status': 'error', 'message': 'default playlist cannot be deleted'}, status_code=400) + try: + state.delete_named_playlist(name.strip()) + except ValueError as exc: + return JSONResponse({'status': 'error', 'message': str(exc)}, status_code=400) + snapshot = state.build_rotation_snapshot() + return JSONResponse(snapshot) + + +@router.delete('/rotation/{device_id}') +def delete_rotation_playlist(device_id: str) -> JSONResponse: + """Remove a per-device playlist override and fall back to the default selection.""" + normalized = (device_id or '').strip() or state.DEFAULT_DEVICE_ID + if normalized == state.DEFAULT_DEVICE_ID: + return JSONResponse({'status': 'error', 'message': 'default playlist cannot be deleted'}, status_code=400) + + state.clear_device_playlist(normalized) + snapshot = state.build_rotation_snapshot() + return JSONResponse(snapshot) + + +@router.get('/devices') +def list_devices(include_default: bool = Query(True, alias='include_default')) -> JSONResponse: + """List known devices along with their profiles, metrics, and playlists.""" + device_ids = state.known_device_ids(include_default=include_default) + devices = [_serialize_device_payload(device_id) for device_id in device_ids] + return JSONResponse({'devices': devices}) + + +@router.get('/devices/{device_id}') +def get_device(device_id: str) -> JSONResponse: + """Return metadata and metrics for a specific device.""" + normalized_id = device_id.strip() or state.DEFAULT_DEVICE_ID + payload = _serialize_device_payload(normalized_id) + return JSONResponse(payload) + + +@router.patch('/devices/{device_id}') +def update_device( + device_id: str, + data: Dict[str, Any] = Body(...) +) -> JSONResponse: + """Update device profile fields and optionally override its playlist.""" + normalized_id = device_id.strip() or state.DEFAULT_DEVICE_ID + friendly_name = data.get('friendly_name') + refresh_interval = data.get('refresh_interval') + time_zone = data.get('time_zone') + playlist_ids = data.get('playlist') + has_playlist_name = 'playlist_name' in data + playlist_name = data.get('playlist_name') + + refresh_override: Optional[int] = None + if refresh_interval is not None: + if not isinstance(refresh_interval, int) or refresh_interval <= 0: + return JSONResponse({'status': 'error', 'message': 'refresh_interval must be a positive integer'}, status_code=400) + refresh_override = refresh_interval + + if playlist_ids is not None: + if not isinstance(playlist_ids, list) or not all(isinstance(pid, str) for pid in playlist_ids): + return JSONResponse({'status': 'error', 'message': 'playlist must be a list of IDs'}, status_code=400) + + state.update_device_profile( + normalized_id, + friendly_name=friendly_name, + refresh_interval=refresh_override, + time_zone=time_zone + ) + + if playlist_ids is not None: + try: + state.set_device_playlist(normalized_id, playlist_ids) + except ValueError as exc: + return JSONResponse({'status': 'error', 'message': str(exc)}, status_code=400) + + if has_playlist_name: + if playlist_name is not None and not isinstance(playlist_name, str): + return JSONResponse({'status': 'error', 'message': 'playlist_name must be a string or null'}, status_code=400) + try: + state.set_device_playlist_binding(normalized_id, playlist_name) + except ValueError as exc: + return JSONResponse({'status': 'error', 'message': str(exc)}, status_code=400) + + payload = _serialize_device_payload(normalized_id) + return JSONResponse(payload) + + +@router.get('/server/log') +def log_view( + request: Request, + limit: int = Query(30, ge=1, le=200), + after: Optional[int] = Query(None), + response_format: str = Query('text', alias='format') +) -> Response: + """Return recent logs with optional cursor-based pagination.""" + logs = models.get_logs_after(after, limit) if after is not None else models.get_logs(limit=limit) + + wants_json = 'application/json' in (request.headers.get('accept') or '').lower() or response_format.lower() == 'json' + if wants_json: + payload = [ + { + 'id': log.id, + 'timestamp': utils.to_iso_datetime(log.timestamp), + 'context': log.context, + 'info': log.info + } + for log in logs + ] + return JSONResponse(payload) + + formatted_logs = '\n'.join([f"{log.timestamp} -- [{log.context}] -- {log.info}" for log in logs]) + response = Response(content=formatted_logs, media_type='text/plain') + if logs: + response.headers['X-Log-Last-Id'] = str(logs[-1].id) + return response + + +@router.get('/server/battery') +def battery_view( + all_data: Optional[str] = Query(None, alias='all'), + from_date: Optional[str] = Query(None, alias='from'), + to_date: Optional[str] = Query(None, alias='to') +) -> JSONResponse: + """Fetch battery data from the client database and return it in JSON format.""" + from_dt = None + to_dt = None + if from_date: + try: + from_dt = datetime.strptime(from_date, '%Y-%m-%d') + except ValueError: + pass + if to_date: + try: + to_dt = datetime.strptime(to_date, '%Y-%m-%d') + except ValueError: + pass + + if not all_data and not from_dt and not to_dt: + today = datetime.now().replace(hour=0, minute=0, second=0, microsecond=0) + from_dt = today + to_dt = today + timedelta(days=1) + + limit = None if all_data else 1000 + history = models.get_battery_history(limit=limit, from_date=from_dt, to_date=to_dt) + + response_data = [ + { + 'timestamp': utils.to_iso_datetime(entry.timestamp), + 'battery_voltage': entry.voltage, + 'rssi': entry.rssi + } + for entry in history + ] + response_data.sort(key=lambda x: x['timestamp']) + + return JSONResponse(response_data) + + +@router.get('/status') +def status_view(device_id: Optional[str] = Query(None, alias='device_id')) -> JSONResponse: + """Retrieve the current status of the server and connected devices.""" + selected_device_id = device_id or state.DEFAULT_DEVICE_ID + uptime_seconds = int(time() - state.start_time) + uptime = str(timedelta(seconds=uptime_seconds)) + + cpu_load = psutil.cpu_percent(interval=None) + current_time = utils.to_iso_datetime(datetime.now(timezone.utc)) + + metrics = state.get_client_metrics(selected_device_id) + profile = state.ensure_device_profile(selected_device_id) + refresh_interval = state.get_refresh_interval(selected_device_id) + battery_voltage = metrics['battery_voltage'] + battery_state = utils.get_battery_state(battery_voltage) + wifi_signal = metrics['rssi'] + wifi_signal_strength = utils.get_wifi_signal_strength(wifi_signal) + + battery_history = models.get_battery_history(limit=30) + client_data_db = [ + { + 'timestamp': utils.to_iso_datetime(entry.timestamp), + 'battery_voltage': entry.voltage, + 'rssi': entry.rssi + } + for entry in battery_history + ] + client_data_db.sort(key=lambda x: x['timestamp']) + + device_state = state.get_device_state(selected_device_id) + current_entry_hash = device_state.get('last_entry_hash') + current_preview_url = device_state.get('current_preview_url') or f"/preview/{quote(selected_device_id)}" + current_preview_token = device_state.get('current_preview_token') + + metrics_store = state.get_all_client_metrics() + + def _has_contact(device_id: str) -> bool: + metrics_record = metrics_store.get(device_id) or {} + last_contact = metrics_record.get('last_contact') + return isinstance(last_contact, (int, float)) and last_contact > 0 + + filtered_ids = [] + seen_ids = set() + for known_id in state.known_device_ids(include_default=False): + if _has_contact(known_id): + filtered_ids.append(known_id) + seen_ids.add(known_id) + if selected_device_id and selected_device_id != state.DEFAULT_DEVICE_ID and selected_device_id not in seen_ids: + filtered_ids.append(selected_device_id) + devices_summary = [_serialize_device_payload(known_id) for known_id in filtered_ids] + playlists_summary = state.list_playlist_targets() + + status_data = { + 'server': { + 'uptime': uptime, + 'cpu_load': cpu_load, + 'current_time': current_time + }, + 'client': { + 'device_id': selected_device_id, + 'friendly_name': profile.get('friendly_name') or selected_device_id, + 'battery_voltage': battery_voltage, + 'battery_voltage_max': config.BATTERY_MAX_VOLTAGE, + 'battery_voltage_min': config.BATTERY_MIN_VOLTAGE, + 'battery_state': battery_state, + 'wifi_signal': wifi_signal, + 'wifi_signal_strength': wifi_signal_strength, + 'refresh_time': refresh_interval, + 'last_contact': utils.to_iso_timestamp(metrics['last_contact']), + 'profile': { + 'refresh_interval': profile.get('refresh_interval'), + 'time_zone': profile.get('time_zone'), + 'last_seen': utils.to_iso_datetime(profile.get('last_seen')) if profile.get('last_seen') else None + }, + 'supports_grayscale': device_state.get('supports_grayscale'), + 'current_entry_hash': current_entry_hash, + 'current_plugin_id': device_state.get('last_entry_plugin'), + 'current_preview_url': current_preview_url, + 'current_preview_token': current_preview_token + }, + 'devices': devices_summary, + 'playlists': playlists_summary, + 'client_data_db': client_data_db + } + return JSONResponse(status_data) diff --git a/trmnl_server/routes/images.py b/trmnl_server/routes/images.py new file mode 100644 index 0000000..5f11a79 --- /dev/null +++ b/trmnl_server/routes/images.py @@ -0,0 +1,111 @@ +"""Image-serving routes for TRMNL local server.""" + +from __future__ import annotations + +from io import BytesIO + +from fastapi import APIRouter, HTTPException, Request +from fastapi.responses import FileResponse, Response + +from .. import config, models, utils +from ..services import state + +router = APIRouter() +logger = config.logger + +SCREEN_VARIANTS = {'screen.bmp', 'screen1.bmp'} +ORIGINAL_VARIANTS = {'original.bmp', 'original1.bmp'} +GRAYSCALE_VARIANTS = {'grayscale.png', 'grayscale1.png'} + + +def _device_context_for_image_request(request: Request) -> tuple[str, dict]: + token = request.query_params.get('token') + resolved = state.resolve_device_id_from_token(token) + if resolved: + return resolved, state.get_device_state(resolved) + return state.get_device_state_from_request(request) + + +def _binary_response(image_blob: BytesIO, media_type: str) -> Response: + payload = image_blob.getvalue() + headers = {'Content-Length': str(len(payload))} + return Response(content=payload, media_type=media_type, headers=headers) + + +def _client_host(request: Request) -> str: + client = request.client + return client.host if client else 'unknown' + + +def _serve_bmp_frame(request: Request, route: str) -> Response: + device_id, device_state = _device_context_for_image_request(request) + try: + frame = state.get_next_bmp_frame(device_id, device_state) + except state.RotationUnavailableError as exc: + raise HTTPException(status_code=503, detail=str(exc)) from exc + client_host = _client_host(request) + models.add_log_entry( + f'Request received at {route}', + f'serving image for IP: {client_host} device: {device_id}' + ) + logger.info('[API] %s - serving image for IP: %s device: %s', route, client_host, device_id) + return _binary_response(frame, 'image/bmp') + + +def _serve_original_image(request: Request) -> Response: + _, device_state = _device_context_for_image_request(request) + entry_idx = state.current_frame_entry_index(device_state) + if entry_idx is None: + raise HTTPException(status_code=404, detail='No original image available') + png_bytes = state.get_rotation_png_bytes(entry_idx) + return _binary_response(BytesIO(png_bytes), 'image/png') + + +def _serve_grayscale_frame(request: Request) -> Response: + device_id, device_state = _device_context_for_image_request(request) + try: + png_blob = state.get_next_png_frame(device_id, device_state) + except state.RotationUnavailableError as exc: + raise HTTPException(status_code=503, detail=str(exc)) from exc + return _binary_response(png_blob, 'image/png') + + +@router.get('/image/{image_name}') +def serve_image_variant(request: Request, image_name: str) -> Response: + """Serve BMP, PNG, or placeholder assets behind /image/* routes.""" + route = f'/image/{image_name}' + if image_name in SCREEN_VARIANTS: + return _serve_bmp_frame(request, route) + if image_name in ORIGINAL_VARIANTS: + return _serve_original_image(request) + if image_name in GRAYSCALE_VARIANTS: + return _serve_grayscale_frame(request) + if image_name == 'dummy.bmp': + return FileResponse(utils.asset_path('img', 'dummy.bmp'), media_type='image/bmp') + raise HTTPException(status_code=404, detail='Unknown image path') + + +@router.get('/images/current.png') +def serve_current_png(request: Request) -> Response: + """Convert the current BMP frame to PNG for browser viewing.""" + _, device_state = _device_context_for_image_request(request) + entry_idx = state.current_frame_entry_index(device_state) + if entry_idx is None: + raise HTTPException(status_code=404, detail='No current image available') + bmp_blob = BytesIO(state.get_rotation_bmp_bytes(entry_idx)) + png_bytes = utils.convert_bmp_bytes_to_png(bmp_blob) + return _binary_response(png_bytes, 'image/png') + + +@router.get('/preview/{device_id}') +def serve_preview(device_id: str) -> Response: + """Serve the last rotation PNG fetched by a device.""" + device_state = state.get_device_state(device_id or state.DEFAULT_DEVICE_ID) + entry_idx = state.preview_frame_entry_index(device_state) + if entry_idx is None: + raise HTTPException(status_code=404, detail='No preview available') + payload = state.get_rotation_png_bytes(entry_idx) + response = _binary_response(BytesIO(payload), 'image/png') + response.headers['Cache-Control'] = 'no-store, no-cache, must-revalidate, max-age=0' + response.headers['Pragma'] = 'no-cache' + return response diff --git a/trmnl_server/routes/pages.py b/trmnl_server/routes/pages.py new file mode 100644 index 0000000..c2b91bf --- /dev/null +++ b/trmnl_server/routes/pages.py @@ -0,0 +1,18 @@ +"""Page routes for TRMNL local server.""" + +from __future__ import annotations + +from fastapi import APIRouter +from fastapi.responses import HTMLResponse + +from .. import utils + +router = APIRouter() + + +@router.get('/') +def index() -> HTMLResponse: + """Serve the main HTML dashboard.""" + index_path = utils.asset_path('index.html') + with open(index_path, 'r', encoding='utf-8') as file: + return HTMLResponse(file.read()) diff --git a/trmnl_server/services/__init__.py b/trmnl_server/services/__init__.py new file mode 100644 index 0000000..50c8a69 --- /dev/null +++ b/trmnl_server/services/__init__.py @@ -0,0 +1 @@ +"""Service modules for rotation, device state, and plugin scheduling.""" diff --git a/trmnl_server/services/plugins.py b/trmnl_server/services/plugins.py new file mode 100644 index 0000000..2f98080 --- /dev/null +++ b/trmnl_server/services/plugins.py @@ -0,0 +1,297 @@ +"""Plugin refresh scheduling, orchestration, and CLI helpers.""" + +from __future__ import annotations + +import inspect +from asyncio import CancelledError, Task, create_task, gather, sleep +from dataclasses import dataclass +from importlib import import_module +from os.path import exists +from pkgutil import walk_packages +from time import time +from typing import Any, Dict, List, Optional, Tuple, Type + +from .. import config, plugins as plugins_pkg +from ..utils import asset_path, get_generated_assets_root +from ..plugins.base import PluginBase, PluginOutput + +from . import state + +logger = config.logger + +PLUGIN_REFRESH_RETRY = 300 +plugin_tasks: Dict[str, Task] = {} +_ttl_cache: Dict[str, int] = {} + + +@dataclass(frozen=True) +class PluginSchedule: + """Typed plugin configuration entry used by the scheduler and CLI.""" + + plugin_cls: Type[PluginBase] + basename: str + set_primary: bool = False + refresh_interval: Optional[int] = None + output_subdir: Optional[str] = None + + @property + def name(self) -> str: + return self.plugin_cls.__name__ + + def fallback_assets(self) -> Tuple[str, str]: + return _asset_paths(self.basename) + + def resolved_refresh_interval(self) -> int: + if self.refresh_interval: + return self.refresh_interval + return _default_plugin_ttl(self.plugin_cls) + + def resolved_output_directory(self) -> str: + root = get_generated_assets_root() + target = root / self.output_subdir if self.output_subdir else root + target.mkdir(parents=True, exist_ok=True) + return target.as_posix() + + @classmethod + def from_plugin(cls, plugin_cls: Type[PluginBase]) -> PluginSchedule: + basename = getattr(plugin_cls, 'BASENAME', plugin_cls.__name__.lower()) + output_subdir = getattr(plugin_cls, 'OUTPUT_SUBDIR', None) or basename + return cls( + plugin_cls=plugin_cls, + basename=basename, + set_primary=bool(getattr(plugin_cls, 'SET_PRIMARY', False)), + refresh_interval=getattr(plugin_cls, 'REFRESH_INTERVAL', None), + output_subdir=output_subdir + ) + + +def _discover_plugin_classes() -> List[Type[PluginBase]]: + classes: List[Type[PluginBase]] = [] + prefix = f"{plugins_pkg.__name__}." + for _, module_name, _ in walk_packages(plugins_pkg.__path__, prefix): + if module_name.endswith('.base'): + continue + if (not config.CALIBRATION_PLUGIN_ENABLED) and module_name.endswith('.calibration'): + continue + try: + module = import_module(module_name) + except Exception as exc: # noqa: BLE001 + logger.warning("Failed to import plugin module %s: %s", module_name, exc) + continue + for attribute in vars(module).values(): + if not inspect.isclass(attribute): + continue + if not issubclass(attribute, PluginBase): + continue + if attribute is PluginBase: + continue + if attribute.__module__ != module.__name__: + continue + if inspect.isabstract(attribute): + continue + if not getattr(attribute, 'AUTO_REGISTER', True): + continue + classes.append(attribute) + classes.sort(key=lambda cls: (getattr(cls, 'REGISTRY_ORDER', 100), cls.__name__)) + return classes + + +def _is_calibration_plugin_class(plugin_cls: Type[PluginBase]) -> bool: + return plugin_cls.__module__.endswith('.calibration') or getattr(plugin_cls, 'BASENAME', '').startswith('calibration') + + +def _build_plugin_registry() -> List[PluginSchedule]: + return [PluginSchedule.from_plugin(plugin_cls) for plugin_cls in _discover_plugin_classes()] + + +PLUGIN_REGISTRY: List[PluginSchedule] = _build_plugin_registry() + + +def _asset_paths(basename: str) -> Tuple[str, str]: + bmp_path = asset_path(f'{basename}.bmp') + png_path = asset_path(f'{basename}.png') + return (bmp_path.as_posix(), png_path.as_posix()) + + +def _default_plugin_ttl(plugin_cls: Type[PluginBase]) -> int: + cached = _ttl_cache.get(plugin_cls.__name__) + if cached: + return cached + try: + instance = plugin_cls() + ttl_default = max(60, int(instance.get_content_ttl())) + except Exception: # noqa: BLE001 + ttl_default = 900 + _ttl_cache[plugin_cls.__name__] = ttl_default + return ttl_default + + +def plugin_schedules() -> List[PluginSchedule]: + """Return a shallow copy of the plugin registry for iteration.""" + schedules = list(PLUGIN_REGISTRY) + if not config.CALIBRATION_PLUGIN_ENABLED: + schedules = [schedule for schedule in schedules if not _is_calibration_plugin_class(schedule.plugin_cls)] + return schedules + + +def list_available_plugins() -> List[str]: + return [schedule.name for schedule in plugin_schedules()] + + +def get_plugin_schedule(plugin_name: str) -> PluginSchedule: + normalized = plugin_name.lower() + for schedule in plugin_schedules(): + if schedule.name.lower() == normalized: + return schedule + raise ValueError(f"Unknown plugin '{plugin_name}'. Available: {', '.join(list_available_plugins())}") + + +async def run_single_plugin_by_name( + plugin_name: str, + *, + output_dir: Optional[str] = None, + plugin_kwargs: Optional[Dict[str, Any]] = None +) -> PluginOutput: + schedule = get_plugin_schedule(plugin_name) + plugin_instance = schedule.plugin_cls() + kwargs: Dict[str, Any] = dict(plugin_kwargs or {}) + kwargs.setdefault('output_dir', output_dir or schedule.resolved_output_directory()) + result = await plugin_instance.run(**kwargs) + if not result or not _assets_exist(result): + raise RuntimeError(f"Plugin {plugin_name} produced no output") + return result + + +def _assets_exist(assets: Optional[PluginOutput]) -> bool: + if not assets: + return False + return exists(assets.monochrome_path) and exists(assets.grayscale_path) + + +def _seconds_until_plugin_refresh( + plugin_name: str, + default_interval: int = 900, + min_interval: int = 60 +) -> int: + with state.STATE_LOCK: + cache_entry = state.global_state.get('plugins', {}).get(plugin_name, {}) + expires_at = cache_entry.get('expires_at') + if expires_at: + delay = max(0, expires_at - time()) + return max(min_interval, int(delay)) + return default_interval + + +async def process_plugin_output(schedule: PluginSchedule) -> None: + plugin_cls = schedule.plugin_cls + plugin_name = plugin_cls.__name__ + fallback_assets = schedule.fallback_assets() + with state.STATE_LOCK: + cache_entry = state.global_state['plugins'].setdefault(plugin_name, {}) + cached_assets: Optional[PluginOutput] = cache_entry.get('assets') + expires_at = cache_entry.get('expires_at', 0) + display_name: Optional[str] = cache_entry.get('display_name') or getattr(plugin_cls, 'DISPLAY_NAME', None) + now = time() + + assets_valid = _assets_exist(cached_assets) + needs_refresh = (not assets_valid) or (expires_at <= now) + assets = cached_assets if assets_valid else None + + if needs_refresh: + plugin_instance = plugin_cls() + output_dir = schedule.resolved_output_directory() + try: + refreshed_assets = await plugin_instance.run(output_dir=output_dir) + if _assets_exist(refreshed_assets): + ttl_seconds = max(1, plugin_instance.get_content_ttl()) + try: + display_name = plugin_instance.get_display_name() + except Exception: # noqa: BLE001 + display_name = getattr(plugin_cls, 'DISPLAY_NAME', None) or plugin_name + with state.STATE_LOCK: + cache_entry = state.global_state['plugins'].setdefault(plugin_name, cache_entry) + cache_entry['expires_at'] = time() + ttl_seconds + cache_entry['assets'] = refreshed_assets + cache_entry['display_name'] = display_name + assets = refreshed_assets + logger.info("%s refreshed; next refresh in %.0f seconds", plugin_name, ttl_seconds) + else: + logger.warning("%s produced no output; attempting fallback", plugin_name) + with state.STATE_LOCK: + cache_entry = state.global_state['plugins'].setdefault(plugin_name, cache_entry) + cache_entry['expires_at'] = time() + PLUGIN_REFRESH_RETRY + except Exception as exc: # noqa: BLE001 + logger.error("Failed to run %s: %s", plugin_name, exc) + with state.STATE_LOCK: + cache_entry = state.global_state['plugins'].setdefault(plugin_name, cache_entry) + cache_entry['expires_at'] = time() + PLUGIN_REFRESH_RETRY + + if (not assets) and fallback_assets: + bmp_path, png_path = fallback_assets + if exists(bmp_path) and exists(png_path): + assets = PluginOutput(monochrome_path=bmp_path, grayscale_path=png_path) + with state.STATE_LOCK: + cache_entry = state.global_state['plugins'].setdefault(plugin_name, cache_entry) + cache_entry['assets'] = assets + + if not assets: + logger.warning("No valid asset available for %s", plugin_name) + return + + if schedule.set_primary: + state.set_primary_rotation_assets(plugin_name, assets, display_name) + else: + state.append_rotation_assets(plugin_name, assets, display_name) + + +async def refresh_plugin_assets() -> None: + """Run all plugin refresh operations concurrently off the event loop.""" + schedules = plugin_schedules() + tasks = [process_plugin_output(schedule) for schedule in schedules] + if not tasks: + return + results = await gather(*tasks, return_exceptions=True) + for schedule, result in zip(schedules, results): + if isinstance(result, Exception): + logger.error("Plugin refresh task failed for %s: %s", schedule.name, result) + + +async def _plugin_refresh_worker( + schedule: PluginSchedule +) -> None: + plugin_name = schedule.name + logger.info("Starting refresh worker for %s", plugin_name) + try: + while True: + try: + await process_plugin_output(schedule) + except Exception as exc: # noqa: BLE001 + logger.error("Plugin refresh task failed for %s: %s", plugin_name, exc) + delay = _seconds_until_plugin_refresh(plugin_name, schedule.resolved_refresh_interval(), 60) + try: + await sleep(delay) + except CancelledError: + logger.info("Plugin refresh worker cancelled for %s", plugin_name) + raise + except CancelledError: + pass + + +async def start_plugin_refreshers() -> None: + """Launch background tasks to refresh each plugin independently.""" + if plugin_tasks: + return + for schedule in plugin_schedules(): + plugin_name = schedule.name + task = create_task(_plugin_refresh_worker(schedule)) + plugin_tasks[plugin_name] = task + + +async def stop_plugin_refreshers() -> None: + """Cancel all plugin refresh tasks and wait for them to stop.""" + if not plugin_tasks: + return + for task in plugin_tasks.values(): + task.cancel() + await gather(*plugin_tasks.values(), return_exceptions=True) + plugin_tasks.clear() \ No newline at end of file diff --git a/trmnl_server/services/state.py b/trmnl_server/services/state.py new file mode 100644 index 0000000..b4a95de --- /dev/null +++ b/trmnl_server/services/state.py @@ -0,0 +1,1200 @@ +"""Shared device, rotation, and state management utilities.""" + +from __future__ import annotations + +from hashlib import sha1 +from os.path import abspath +from time import time +from io import BytesIO +from threading import RLock +from typing import Any, Dict, List, Optional, Tuple +from urllib.parse import quote + +from fastapi import Request + +from .. import config, models, utils +from ..plugins.base import PluginOutput + +logger = config.logger + +DEFAULT_DEVICE_ID = 'default' +STATE_LOCK = RLock() +start_time = time() + +_IMAGE_TOKEN_TTL_SECONDS = 600.0 + +_server_base_url = '' + + +class RotationUnavailableError(RuntimeError): + """Raised when no rotation entries are available for a device.""" + pass + + +def set_server_base_url(base_url: str) -> None: + """Persist the server base URL so freshly created device states have a default.""" + global _server_base_url + _server_base_url = base_url.rstrip('/') if base_url else '' + + +def get_server_base_url() -> str: + return _server_base_url or f"{config.SERVER_SCHEME}://{utils.get_ip_address()}:{config.SERVER_PORT}" + + +def update_device_preview( + device_id: str, + device_state: Optional[Dict[str, Any]], + entry_index: Optional[int] +) -> Tuple[Optional[str], Optional[str]]: + if entry_index is None or entry_index < 0: + return None, None + target_state = device_state or get_device_state(device_id) + with STATE_LOCK: + previous_index = target_state.get('current_preview_entry_index') + target_state['current_preview_entry_index'] = entry_index + existing_token = target_state.get('current_preview_token') + if previous_index == entry_index and existing_token: + token = str(existing_token) + else: + sequence = int(target_state.get('token_sequence', 0)) + token = sha1(f"{device_id}-{entry_index}-{sequence}".encode('utf-8')).hexdigest()[:16] + target_state['current_preview_token'] = token + target_state['current_preview_url'] = f"/preview/{quote(device_id)}?token={token}" + return target_state['current_preview_url'], token + + +def _client_metrics_store() -> Dict[str, Dict[str, Any]]: + return global_state.setdefault('client_metrics', {}) + + +def get_client_metrics(device_id: str) -> Dict[str, Any]: + with STATE_LOCK: + store = _client_metrics_store() + metrics = store.get(device_id) + if metrics is None: + metrics = { + 'refresh_rate': config.REFRESH_TIME, + 'battery_voltage': config.BATTERY_MAX_VOLTAGE, + 'rssi': -100, + 'last_contact': 0.0 + } + store[device_id] = metrics + return metrics + + +def update_client_metrics( + device_id: str, + *, + refresh_rate: Optional[int] = None, + battery_voltage: Optional[float] = None, + rssi: Optional[int] = None +) -> None: + with STATE_LOCK: + metrics = get_client_metrics(device_id) + if refresh_rate is not None: + metrics['refresh_rate'] = refresh_rate + if battery_voltage is not None: + metrics['battery_voltage'] = battery_voltage + if rssi is not None: + metrics['rssi'] = rssi + metrics['last_contact'] = time() + + +def get_all_client_metrics() -> Dict[str, Dict[str, Any]]: + with STATE_LOCK: + return {device_id: dict(metrics) for device_id, metrics in _client_metrics_store().items()} + + +def _device_profile_cache() -> Dict[str, Dict[str, Any]]: + return global_state.setdefault('device_profiles', {}) + + +def ensure_device_profile(device_id: str) -> Dict[str, Any]: + with STATE_LOCK: + cache = _device_profile_cache() + profile = cache.get(device_id) + if profile is None: + profile = models.ensure_device_profile(device_id) + with STATE_LOCK: + cache = _device_profile_cache() + cache[device_id] = profile + return profile + + +def refresh_device_profile(device_id: str) -> Dict[str, Any]: + profile = models.ensure_device_profile(device_id) + with STATE_LOCK: + cache = _device_profile_cache() + cache[device_id] = profile + return profile + + +def update_device_profile( + device_id: str, + *, + friendly_name: Optional[str] = None, + refresh_interval: Optional[int] = None, + time_zone: Optional[str] = None +) -> Dict[str, Any]: + profile = models.update_device_profile( + device_id, + friendly_name=friendly_name, + refresh_interval=refresh_interval, + time_zone=time_zone + ) + with STATE_LOCK: + cache = _device_profile_cache() + cache[device_id] = profile + return profile + + +def get_refresh_interval(device_id: str) -> int: + profile = ensure_device_profile(device_id) + refresh_interval = profile.get('refresh_interval') + if isinstance(refresh_interval, int) and refresh_interval > 0: + return refresh_interval + metrics = get_client_metrics(device_id) + return int(metrics.get('refresh_rate', config.REFRESH_TIME)) + + +def _build_device_state() -> Dict[str, Any]: + return { + 'bmp_send_switch': True, + 'current_preview_url': None, + 'current_preview_token': None, + 'current_preview_entry_index': None, + 'playlist_ids': [], + 'playlist_indexes': [], + 'playlist_media': [], + 'current_playlist_index': -1, + 'current_entry_index': -1, + 'current_entry_media': 'auto', + 'request_count': 0, + 'last_entry_hash': None, + 'last_entry_plugin': None, + 'pending_entry_index': None, + 'pending_entry_media': None, + 'supports_grayscale': False, + 'grayscale_send_switch': True, + 'token_sequence': 0 + } + + +global_state: Dict[str, Any] = { + 'rotation_master': { + 'bmp_entries': [], + 'png_entries': [], + 'hashes': [], + 'meta': [], + 'selected_ids': [], + 'version': 0 + }, + 'devices': {}, + 'device_playlists': {}, + 'device_profiles': {}, + 'client_metrics': {}, + 'server': { + 'uptime': 0, + 'cpu_load': 0, + 'current_time': 0 + }, + 'client': { + 'battery_voltage': 0, + 'battery_voltage_max': 0 + }, + 'plugins': {} +} + + +def _image_token_store() -> Dict[str, Dict[str, Any]]: + return global_state.setdefault('image_tokens', {}) + + +def register_image_token(device_id: str, token: str) -> None: + normalized_device = (device_id or '').strip() or DEFAULT_DEVICE_ID + if normalized_device == DEFAULT_DEVICE_ID: + return + token_value = (token or '').strip() + if not token_value: + return + now = time() + cutoff = now - _IMAGE_TOKEN_TTL_SECONDS + with STATE_LOCK: + store = _image_token_store() + store[token_value] = {'device_id': normalized_device, 'ts': now} + for key, payload in list(store.items()): + if not isinstance(payload, dict): + store.pop(key, None) + continue + ts = payload.get('ts') + if not isinstance(ts, (int, float)) or ts < cutoff: + store.pop(key, None) + + +def resolve_device_id_from_token(token: Optional[str]) -> Optional[str]: + token_value = (token or '').strip() + if not token_value: + return None + now = time() + cutoff = now - _IMAGE_TOKEN_TTL_SECONDS + with STATE_LOCK: + store = _image_token_store() + payload = store.get(token_value) + if not isinstance(payload, dict): + return None + ts = payload.get('ts') + if not isinstance(ts, (int, float)) or ts < cutoff: + store.pop(token_value, None) + return None + device_id = payload.get('device_id') + if isinstance(device_id, str) and device_id.strip() and device_id.strip() != DEFAULT_DEVICE_ID: + return device_id.strip() + return None + + +def _read_image_bytes(image_path: str) -> bytes: + with open(image_path, 'rb') as file: + return file.read() + + +def _digest_bytes(data: bytes) -> str: + return sha1(data).hexdigest() + + +def _rotation_entry_id(plugin_name: str, bmp_path: str, png_path: str) -> str: + plugin = (plugin_name or '').strip() + bmp_url = utils.path_to_web_url(bmp_path) + png_url = utils.path_to_web_url(png_path) + return f"{plugin}:{bmp_url}|{png_url}" + + +def _collision_safe_rotation_id(preferred: str, disallowed: set[str]) -> str: + if preferred not in disallowed: + return preferred + for idx in range(1, 100): + candidate = f"{preferred}#{idx}" + if candidate not in disallowed: + return candidate + return f"{preferred}#{len(disallowed) + 1}" + + +def rotation_master() -> Dict[str, Any]: + """Return the shared rotation master structure.""" + return global_state['rotation_master'] + + +def _selected_matches_all(master: Dict[str, Any]) -> bool: + selected_ids = master.get('selected_ids') or [] + meta = master.get('meta') or [] + ids = [entry.get('id') for entry in meta if entry.get('id')] + if len(selected_ids) != len(ids): + return False + return all(lhs == rhs for lhs, rhs in zip(selected_ids, ids)) + + +def _prune_missing_selected_ids(master: Dict[str, Any]) -> bool: + selected_ids = master.get('selected_ids') or [] + if not selected_ids: + return False + meta = master.get('meta') or [] + valid_ids = {entry.get('id') for entry in meta if entry.get('id')} + filtered_ids: List[str] = [] + for entry in selected_ids: + base_id, _ = _parse_playlist_entry_id(entry) + if base_id in valid_ids: + filtered_ids.append(entry) + if len(filtered_ids) == len(selected_ids): + return False + master['selected_ids'] = filtered_ids + return True + + +def persist_default_playlist(selected_ids: List[str]) -> None: + try: + models.save_rotation_playlist(selected_ids) + except Exception as exc: # noqa: BLE001 + logger.warning("Failed to persist default playlist: %s", exc) + + +def persist_device_playlist(device_id: str, selected_ids: List[str]) -> None: + try: + models.save_rotation_playlist(selected_ids, device_id=device_id) + except Exception as exc: # noqa: BLE001 + logger.warning("Failed to persist playlist for %s: %s", device_id, exc) + + +def cache_device_playlist(device_id: str, selected_ids: Optional[List[str]]) -> None: + with STATE_LOCK: + playlists = global_state.setdefault('device_playlists', {}) + if selected_ids is None: + playlists.pop(device_id, None) + else: + playlists[device_id] = selected_ids + + +def _named_playlists_store() -> Dict[str, List[str]]: + return global_state.setdefault('named_playlists', {}) + + +def cache_named_playlist(name: str, selected_ids: Optional[List[str]]) -> None: + normalized = (name or '').strip() + if not normalized or normalized == DEFAULT_DEVICE_ID: + return + with STATE_LOCK: + store = _named_playlists_store() + if selected_ids is None: + store.pop(normalized, None) + else: + store[normalized] = list(selected_ids) + + +def _device_playlist_binding_store() -> Dict[str, str]: + return global_state.setdefault('device_playlist_bindings', {}) + + +def cache_device_playlist_binding(device_id: str, playlist_name: Optional[str]) -> None: + normalized_device = (device_id or '').strip() or DEFAULT_DEVICE_ID + normalized_name = (playlist_name or '').strip() or DEFAULT_DEVICE_ID + if normalized_device == DEFAULT_DEVICE_ID: + return + with STATE_LOCK: + store = _device_playlist_binding_store() + if normalized_name == DEFAULT_DEVICE_ID: + store.pop(normalized_device, None) + else: + store[normalized_device] = normalized_name + + +def get_device_playlist_binding_name(device_id: str) -> Optional[str]: + normalized_device = (device_id or '').strip() or DEFAULT_DEVICE_ID + if normalized_device == DEFAULT_DEVICE_ID: + return None + with STATE_LOCK: + store = _device_playlist_binding_store() + cached = store.get(normalized_device) + if cached: + return cached + bound = models.get_device_playlist_binding(normalized_device) + cache_device_playlist_binding(normalized_device, bound) + if bound and bound.strip() and bound.strip() != DEFAULT_DEVICE_ID: + return bound.strip() + return None + + +def get_named_playlist_selection(name: str) -> Optional[List[str]]: + normalized = (name or '').strip() + if not normalized or normalized == DEFAULT_DEVICE_ID: + return None + with STATE_LOCK: + store = _named_playlists_store() + cached = store.get(normalized) + if cached is not None: + return list(cached) + selected = models.get_rotation_playlist(device_id=None, name=normalized) + cache_named_playlist(normalized, selected) + if selected is None: + return None + return list(selected) + + +def _ensure_device_playlist_cached(device_id: str) -> Optional[List[str]]: + with STATE_LOCK: + playlists = global_state.setdefault('device_playlists', {}) + if device_id in playlists: + return playlists[device_id] + selected_ids = models.get_rotation_playlist(device_id=device_id) + cache_device_playlist(device_id, selected_ids) + return selected_ids + + +def initialize_rotation_playlists_from_storage() -> None: + default_playlist = models.get_rotation_playlist() + if default_playlist is not None: + with STATE_LOCK: + master = rotation_master() + master['selected_ids'] = default_playlist + for device_id, selected_ids in models.list_device_playlists(): + cache_device_playlist(device_id, selected_ids) + + for name, selected_ids in models.list_named_rotation_playlists(): + cache_named_playlist(name, selected_ids) + + for device_id, playlist_name in models.list_device_playlist_bindings(): + cache_device_playlist_binding(device_id, playlist_name) + + +def _replace_selected_hash(master: Dict[str, Any], previous_hash: Optional[str], new_hash: str) -> None: + if not previous_hash: + return + selected_ids = master.get('selected_ids') + if not selected_ids: + return + master['selected_ids'] = [new_hash if entry == previous_hash else entry for entry in selected_ids] + + +def _selected_ids_for_device(device_id: Optional[str]) -> List[str]: + if device_id: + bound_name = get_device_playlist_binding_name(device_id) + if bound_name: + bound_playlist = get_named_playlist_selection(bound_name) + if bound_playlist: + return list(bound_playlist) + cached = _ensure_device_playlist_cached(device_id) + if cached is not None: + return list(cached) + master = rotation_master() + selected_ids = master.get('selected_ids') or [] + if selected_ids: + return list(selected_ids) + meta = master.get('meta') or [] + return [entry.get('id') for entry in meta if entry.get('id')] + + +def get_playlist_selection(device_id: Optional[str] = None) -> List[str]: + return _selected_ids_for_device(device_id) + + +def known_device_ids(include_default: bool = True) -> List[str]: + with STATE_LOCK: + ids = set(global_state.get('devices', {}).keys()) + ids.update((global_state.get('device_playlists') or {}).keys()) + ids.update((global_state.get('device_playlist_bindings') or {}).keys()) + ids.update((global_state.get('client_metrics') or {}).keys()) + ids.update((global_state.get('device_profiles') or {}).keys()) + if include_default: + ids.add(DEFAULT_DEVICE_ID) + return sorted(ids) + + +def list_playlist_targets(include_default: bool = True) -> List[Dict[str, Any]]: + assignments: List[Dict[str, Any]] = [] + if include_default: + default_playlist = _selected_ids_for_device(None) + assignments.append({ + 'device_id': DEFAULT_DEVICE_ID, + 'friendly_name': 'Default playlist', + 'playlist': list(default_playlist), + 'count': len(default_playlist) + }) + with STATE_LOCK: + overrides = list((global_state.get('device_playlists') or {}).items()) + for device_id, playlist_ids in sorted(overrides, key=lambda item: item[0]): + current_playlist = list(playlist_ids or []) + profile = ensure_device_profile(device_id) + assignments.append({ + 'device_id': device_id, + 'friendly_name': profile.get('friendly_name') or device_id, + 'playlist': current_playlist, + 'count': len(current_playlist) + }) + return assignments + + +def set_named_playlist(name: str, playlist_ids: List[str]) -> None: + normalized = (name or '').strip() + if not normalized or normalized == DEFAULT_DEVICE_ID: + raise ValueError('invalid playlist name') + if not playlist_ids: + raise ValueError('playlist must contain at least one active entry') + validate_playlist_ids(playlist_ids) + models.save_rotation_playlist(list(playlist_ids), device_id=None, name=normalized) + cache_named_playlist(normalized, list(playlist_ids)) + + +def delete_named_playlist(name: str) -> None: + normalized = (name or '').strip() + if not normalized or normalized == DEFAULT_DEVICE_ID: + raise ValueError('default playlist cannot be deleted') + + with STATE_LOCK: + bindings = dict(_device_playlist_binding_store()) + for device_id, playlist_name in bindings.items(): + if playlist_name == normalized: + models.delete_device_playlist_binding(device_id) + cache_device_playlist_binding(device_id, None) + with STATE_LOCK: + device_state = get_device_state(device_id) + device_state['request_count'] = 0 + device_state['current_playlist_index'] = -1 + device_state['current_entry_index'] = -1 + device_state['last_entry_hash'] = None + device_state['last_entry_plugin'] = None + persist_device_state(device_id, 0, -1, [], None, None) + + models.delete_named_rotation_playlist(normalized) + cache_named_playlist(normalized, None) + + +def set_device_playlist_binding(device_id: str, playlist_name: Optional[str]) -> None: + normalized_device = (device_id or '').strip() or DEFAULT_DEVICE_ID + if normalized_device == DEFAULT_DEVICE_ID: + raise ValueError('invalid device id') + + normalized_name = (playlist_name or '').strip() or DEFAULT_DEVICE_ID + # Binding is the primary assignment mechanism; clear any legacy per-device overrides + # so the binding is reflected immediately in rotation selection. + cache_device_playlist(normalized_device, None) + try: + models.delete_rotation_playlist(device_id=normalized_device) + except Exception as exc: # noqa: BLE001 + logger.warning("Failed to delete legacy rotation playlist for %s: %s", normalized_device, exc) + + if normalized_name != DEFAULT_DEVICE_ID: + selection = get_named_playlist_selection(normalized_name) + if not selection: + raise ValueError('unknown playlist') + models.set_device_playlist_binding(normalized_device, normalized_name) + cache_device_playlist_binding(normalized_device, normalized_name) + else: + models.delete_device_playlist_binding(normalized_device) + cache_device_playlist_binding(normalized_device, None) + + with STATE_LOCK: + device_state = get_device_state(normalized_device) + device_state['request_count'] = 0 + device_state['current_playlist_index'] = -1 + device_state['current_entry_index'] = -1 + device_state['pending_entry_index'] = None + device_state['last_entry_hash'] = None + device_state['last_entry_plugin'] = None + persist_device_state(normalized_device, 0, -1, [], None, None) + + +def _playlist_index_map(master: Optional[Dict[str, Any]] = None) -> Dict[str, int]: + if master is None: + master = rotation_master() + meta = master.get('meta') or [] + return {entry.get('id'): idx for idx, entry in enumerate(meta) if entry.get('id')} + + +def _parse_playlist_entry_id(entry_id: str) -> Tuple[str, Optional[str]]: + """Parse playlist entry IDs with optional media directives. + + Supported suffixes: '@bmp'/'@mono' forces 1-bit BMP delivery; '@png'/'@gray' + forces grayscale PNG delivery; '@auto' uses the default device behavior. + + Returns (base_id, media) where media is 'bmp', 'png', or None. + """ + raw = (entry_id or '').strip() + if not raw or '@' not in raw: + return raw, None + + base, suffix = raw.rsplit('@', 1) + suffix_norm = suffix.strip().lower() + if suffix_norm in ('bmp', 'mono', '1bit', '1-bit'): + return base, 'bmp' + if suffix_norm in ('png', 'gray', 'grayscale'): + return base, 'png' + if suffix_norm in ('auto',): + return base, None + return raw, None + + +def _resolved_playlist_for_device(device_id: Optional[str]) -> Tuple[List[str], List[int]]: + master = rotation_master() + playlist_ids = _selected_ids_for_device(device_id) + if not playlist_ids: + playlist_ids = [entry.get('id') for entry in master.get('meta') or [] if entry.get('id')] + mapping = _playlist_index_map(master) + resolved_ids: List[str] = [] + resolved_indexes: List[int] = [] + resolved_media: List[str] = [] + for entry_id in playlist_ids: + base_id, media = _parse_playlist_entry_id(entry_id) + index = mapping.get(base_id) + if index is None: + continue + resolved_ids.append(entry_id) + resolved_indexes.append(index) + resolved_media.append(media or 'auto') + return resolved_ids, resolved_indexes, resolved_media + + +def _update_playlist_snapshot(device_id: str, device_state: Dict[str, Any]) -> Tuple[List[str], List[int]]: + resolved_ids, resolved_indexes, resolved_media = _resolved_playlist_for_device(device_id) + device_state['playlist_ids'] = list(resolved_ids) + device_state['playlist_indexes'] = list(resolved_indexes) + device_state['playlist_media'] = list(resolved_media) + if resolved_indexes: + max_index = len(resolved_indexes) - 1 + if device_state.get('current_playlist_index', -1) > max_index: + device_state['current_playlist_index'] = -1 + else: + device_state['current_playlist_index'] = -1 + device_state['current_entry_index'] = -1 + device_state['current_entry_media'] = 'auto' + return device_state['playlist_ids'], device_state['playlist_indexes'] + + +def _select_next_playlist_entry(device_id: str, device_state: Dict[str, Any]) -> Tuple[int, str]: + with STATE_LOCK: + _, playlist_indexes = _update_playlist_snapshot(device_id, device_state) + if not playlist_indexes: + raise RotationUnavailableError(f'No rotation entries are available for {device_id}') + request_count = int(device_state.get('request_count') or 0) + position = request_count % len(playlist_indexes) + entry_index = playlist_indexes[position] + playlist_media = device_state.get('playlist_media') or [] + media = str(playlist_media[position]) if position < len(playlist_media) else 'auto' + if media not in ('bmp', 'png'): + media = 'auto' + master = rotation_master() + meta_list = master.get('meta') or [] + if entry_index < 0 or entry_index >= len(meta_list): + raise RotationUnavailableError(f'Playlist entry {entry_index} is invalid for {device_id}') + entry = meta_list[entry_index] + entry_id = entry.get('id') + plugin_id = entry.get('plugin') + device_state['request_count'] = request_count + 1 + device_state['current_playlist_index'] = position + device_state['current_entry_index'] = entry_index + device_state['current_entry_media'] = media + device_state['last_entry_hash'] = entry_id + device_state['last_entry_plugin'] = plugin_id + playlist_snapshot = list(playlist_indexes) + request_snapshot = device_state['request_count'] + persist_device_state( + device_id, + request_snapshot, + position, + playlist_snapshot, + entry_id, + plugin_id + ) + return entry_index, media + + +def validate_playlist_ids(playlist_ids: List[str]) -> None: + mapping = _playlist_index_map() + unknown: List[str] = [] + for pid in playlist_ids: + base_id, _ = _parse_playlist_entry_id(pid) + if base_id not in mapping: + unknown.append(pid) + if unknown: + raise ValueError(f'unknown playlist ids: {unknown}') + + +def set_default_playlist(playlist_ids: List[str]) -> None: + master = rotation_master() + mapping = _playlist_index_map(master) + unknown: List[str] = [] + for pid in playlist_ids: + base_id, _ = _parse_playlist_entry_id(pid) + if base_id not in mapping: + unknown.append(pid) + if unknown: + raise ValueError(f'unknown playlist ids: {unknown}') + with STATE_LOCK: + master = rotation_master() + master['selected_ids'] = playlist_ids + master['version'] += 1 + selection_snapshot = list(master['selected_ids']) + persist_default_playlist(selection_snapshot) + + +def set_device_playlist(device_id: str, playlist_ids: List[str]) -> None: + master = rotation_master() + mapping = _playlist_index_map(master) + unknown: List[str] = [] + resolved_indexes: List[int] = [] + for pid in playlist_ids: + base_id, _ = _parse_playlist_entry_id(pid) + idx = mapping.get(base_id) + if idx is None: + unknown.append(pid) + else: + resolved_indexes.append(idx) + if unknown: + raise ValueError(f'unknown playlist ids: {unknown}') + + playlist_indexes = resolved_indexes + with STATE_LOCK: + device_state = get_device_state(device_id) + device_state['playlist_ids'] = list(playlist_ids) + device_state['playlist_indexes'] = list(playlist_indexes) + device_state['playlist_media'] = [] + device_state['request_count'] = 0 + device_state['current_playlist_index'] = -1 + device_state['current_entry_index'] = -1 + device_state['current_entry_media'] = 'auto' + device_state['last_entry_hash'] = None + device_state['last_entry_plugin'] = None + device_state['pending_entry_media'] = None + cache_device_playlist(device_id, list(playlist_ids)) + persist_device_playlist(device_id, list(playlist_ids)) + persist_device_state(device_id, 0, -1, playlist_indexes, None, None) + + +def clear_device_playlist(device_id: str) -> None: + with STATE_LOCK: + playlists = global_state.setdefault('device_playlists', {}) + playlists.pop(device_id, None) + devices = global_state.setdefault('devices', {}) + device_state = devices.setdefault(device_id, _build_device_state()) + device_state['playlist_ids'] = [] + device_state['playlist_indexes'] = [] + device_state['request_count'] = 0 + device_state['current_playlist_index'] = -1 + device_state['current_entry_index'] = -1 + device_state['last_entry_hash'] = None + device_state['last_entry_plugin'] = None + + models.delete_rotation_playlist(device_id=device_id) + persist_device_state(device_id, 0, -1, [], None, None) + + +def persist_device_state( + device_id: str, + request_count: int, + playlist_position: int, + playlist_indexes: List[int], + current_entry_id: Optional[str], + current_plugin_id: Optional[str] +) -> None: + try: + snapshot = [str(idx) for idx in playlist_indexes] + models.save_device_state( + device_id=device_id, + rotation_version=request_count, + rotation_index=playlist_position, + rotation_hash_order=snapshot, + last_entry_hash=current_entry_id, + current_plugin_id=current_plugin_id + ) + except Exception as exc: # noqa: BLE001 + logger.warning("Failed to persist device state for %s: %s", device_id, exc) + + +def schedule_next_rotation_entry(device_id: str, device_state: Dict[str, Any]) -> int: + entry_idx, media = _select_next_playlist_entry(device_id, device_state) + with STATE_LOCK: + device_state['pending_entry_index'] = entry_idx + device_state['pending_entry_media'] = media + return entry_idx + + +def _pop_pending_entry_index(device_state: Dict[str, Any]) -> Optional[int]: + with STATE_LOCK: + pending = device_state.get('pending_entry_index') + device_state['pending_entry_index'] = None + device_state['pending_entry_media'] = None + return pending + + +def _resolve_next_entry(device_id: str, device_state: Dict[str, Any]) -> int: + pending = _pop_pending_entry_index(device_state) + if pending is not None: + return pending + entry_idx, _ = _select_next_playlist_entry(device_id, device_state) + return entry_idx + + +def _rotation_frame_bytes(entry_idx: int, media: str) -> bytes: + key = 'bmp_entries' if media == 'bmp' else 'png_entries' + with STATE_LOCK: + master = rotation_master() + entries = master.get(key) or [] + if entry_idx < 0 or entry_idx >= len(entries): + raise RotationUnavailableError(f'Rotation index {entry_idx} is out of range for {media.upper()} frames') + return entries[entry_idx] + + +def get_rotation_bmp_bytes(entry_idx: int) -> bytes: + return _rotation_frame_bytes(entry_idx, 'bmp') + + +def get_rotation_png_bytes(entry_idx: int) -> bytes: + return _rotation_frame_bytes(entry_idx, 'png') + + +def current_frame_entry_index(device_state: Dict[str, Any]) -> Optional[int]: + with STATE_LOCK: + pending = device_state.get('pending_entry_index') + if isinstance(pending, int) and pending >= 0: + return pending + current = device_state.get('current_entry_index') + if isinstance(current, int) and current >= 0: + return current + return None + + +def preview_frame_entry_index(device_state: Dict[str, Any]) -> Optional[int]: + with STATE_LOCK: + preview = device_state.get('current_preview_entry_index') + if isinstance(preview, int) and preview >= 0: + return preview + return None + + +def get_next_bmp_frame(device_id: str, device_state: Dict[str, Any]) -> BytesIO: + entry_idx = _resolve_next_entry(device_id, device_state) + bmp_bytes = get_rotation_bmp_bytes(entry_idx) + return BytesIO(bmp_bytes) + + +def get_next_png_frame(device_id: str, device_state: Dict[str, Any]) -> BytesIO: + entry_idx = _resolve_next_entry(device_id, device_state) + png_bytes = get_rotation_png_bytes(entry_idx) + return BytesIO(png_bytes) + + +def _build_rotation_meta( + plugin_name: str, + bmp_path: str, + png_path: str, + entry_id: str, + content_hash: str, + display_name: Optional[str] = None +) -> Dict[str, Any]: + label = display_name or plugin_name + return { + 'id': entry_id, + 'hash': content_hash, + 'plugin': plugin_name, + 'label': label, + 'bmp_path': abspath(bmp_path), + 'png_path': abspath(png_path), + 'url_bmp': utils.path_to_web_url(bmp_path), + 'url_png': utils.path_to_web_url(png_path) + } + + +def set_primary_rotation_assets( + plugin_name: str, + assets: PluginOutput, + display_name: Optional[str] = None +) -> None: + bmp_bytes = _read_image_bytes(assets.monochrome_path) + png_bytes = _read_image_bytes(assets.grayscale_path) + content_hash = _digest_bytes(b"|".join((bmp_bytes, png_bytes))) + preferred_id = _rotation_entry_id(plugin_name, assets.monochrome_path, assets.grayscale_path) + + selection_snapshot: Optional[List[str]] = None + with STATE_LOCK: + master = rotation_master() + if _prune_missing_selected_ids(master): + selection_snapshot = list(master.get('selected_ids') or []) + bmp_entries = master.setdefault('bmp_entries', []) + png_entries = master.setdefault('png_entries', []) + hashes = master.setdefault('hashes', []) + meta_list = master.setdefault('meta', []) + had_entries = bool(bmp_entries) + auto_fill_enabled = _selected_matches_all(master) + + previous_id = None + if had_entries and meta_list: + previous_id = meta_list[0].get('id') + disallowed_ids = {entry.get('id') for entry in meta_list if entry.get('id')} + if previous_id: + disallowed_ids.discard(previous_id) + entry_id = previous_id or preferred_id + entry_id = _collision_safe_rotation_id(entry_id, disallowed_ids) + meta_entry = _build_rotation_meta( + plugin_name, + assets.monochrome_path, + assets.grayscale_path, + entry_id, + content_hash, + display_name + ) + + if bmp_entries: + bmp_entries[0] = bmp_bytes + png_entries[0] = png_bytes + hashes[0] = content_hash + if meta_list: + meta_list[0] = meta_entry + else: + meta_list.append(meta_entry) + else: + bmp_entries.append(bmp_bytes) + png_entries.append(png_bytes) + hashes.append(content_hash) + meta_list.append(meta_entry) + + if not had_entries: + master['version'] += 1 + + if (not master.get('selected_ids')) or auto_fill_enabled: + master['selected_ids'] = [entry.get('id') for entry in meta_list if entry.get('id')] + selection_snapshot = list(master['selected_ids']) + + if selection_snapshot is not None: + persist_default_playlist(selection_snapshot) + + +def append_rotation_assets( + plugin_name: str, + assets: PluginOutput, + display_name: Optional[str] = None +) -> None: + bmp_bytes = _read_image_bytes(assets.monochrome_path) + png_bytes = _read_image_bytes(assets.grayscale_path) + content_hash = _digest_bytes(b"|".join((bmp_bytes, png_bytes))) + preferred_id = _rotation_entry_id(plugin_name, assets.monochrome_path, assets.grayscale_path) + selection_snapshot: Optional[List[str]] = None + replaced_entry = False + skip_append = False + with STATE_LOCK: + master = rotation_master() + if _prune_missing_selected_ids(master): + selection_snapshot = list(master.get('selected_ids') or []) + hashes = master.setdefault('hashes', []) + meta_list = master.setdefault('meta', []) + bmp_entries = master.setdefault('bmp_entries', []) + png_entries = master.setdefault('png_entries', []) + auto_fill_enabled = _selected_matches_all(master) + + replace_index = None + for idx, meta_entry in enumerate(meta_list): + if meta_entry.get('plugin') == plugin_name: + replace_index = idx + break + + if replace_index is not None: + previous_id = meta_list[replace_index].get('id') if replace_index < len(meta_list) else None + disallowed_ids = {entry.get('id') for entry in meta_list if entry.get('id')} + if previous_id: + disallowed_ids.discard(previous_id) + entry_id = previous_id or preferred_id + entry_id = _collision_safe_rotation_id(entry_id, disallowed_ids) + bmp_entries[replace_index] = bmp_bytes + png_entries[replace_index] = png_bytes + hashes[replace_index] = content_hash + meta_list[replace_index] = _build_rotation_meta( + plugin_name, + assets.monochrome_path, + assets.grayscale_path, + entry_id, + content_hash, + display_name + ) + selection_snapshot = list(master.get('selected_ids') or []) + replaced_entry = True + + if replace_index is None: + disallowed_ids = {entry.get('id') for entry in meta_list if entry.get('id')} + entry_id = _collision_safe_rotation_id(preferred_id, disallowed_ids) + + bmp_entries.append(bmp_bytes) + png_entries.append(png_bytes) + hashes.append(content_hash) + meta_list.append( + _build_rotation_meta( + plugin_name, + assets.monochrome_path, + assets.grayscale_path, + entry_id, + content_hash, + display_name + ) + ) + master['version'] += 1 + if (not master.get('selected_ids')) or auto_fill_enabled: + master['selected_ids'] = [entry.get('id') for entry in meta_list if entry.get('id')] + selection_snapshot = list(master['selected_ids']) + + if selection_snapshot is not None: + persist_default_playlist(selection_snapshot) + + if skip_append or replaced_entry: + return + + +def build_rotation_snapshot() -> Dict[str, Any]: + persist_default: Optional[List[str]] = None + persist_devices: Dict[str, List[str]] = {} + persist_named: Dict[str, List[str]] = {} + + with STATE_LOCK: + master = rotation_master() + if _prune_missing_selected_ids(master): + persist_default = list(master.get('selected_ids') or []) + + meta = list(master.get('meta') or []) + selected_ids = list(master.get('selected_ids') or []) + version = master.get('version', 0) + + device_playlists = { + device_id: list(playlist or []) + for device_id, playlist in (global_state.get('device_playlists') or {}).items() + if playlist is not None + } + named_playlists = { + name: list(value or []) + for name, value in (global_state.get('named_playlists') or {}).items() + if value is not None + } + bindings = { + device_id: playlist_name + for device_id, playlist_name in (global_state.get('device_playlist_bindings') or {}).items() + if playlist_name and playlist_name != DEFAULT_DEVICE_ID + } + entries: List[Dict[str, Any]] = [] + for entry in meta: + entries.append({ + 'id': entry.get('id'), + 'label': entry.get('label'), + 'plugin': entry.get('plugin'), + 'url_png': entry.get('url_png'), + 'url_bmp': entry.get('url_bmp') + }) + + valid_ids = {e.get('id') for e in entries if e.get('id')} + entry_fallback = [e.get('id') for e in entries if e.get('id')] + + # Hygiene: prune IDs that no longer exist in the current rotation entries. + original_default = list(selected_ids) + selected_ids = [entry_id for entry_id in selected_ids if _parse_playlist_entry_id(entry_id)[0] in valid_ids] + if selected_ids != original_default: + persist_default = list(selected_ids) + with STATE_LOCK: + master = rotation_master() + master['selected_ids'] = list(selected_ids) + + for device_id, playlist in list(device_playlists.items()): + original = list(playlist or []) + filtered = [entry_id for entry_id in original if _parse_playlist_entry_id(entry_id)[0] in valid_ids] + if filtered != original: + device_playlists[device_id] = filtered + persist_devices[device_id] = filtered + with STATE_LOCK: + global_state.setdefault('device_playlists', {})[device_id] = list(filtered) + + for name, playlist in list(named_playlists.items()): + original = list(playlist or []) + filtered = [entry_id for entry_id in original if _parse_playlist_entry_id(entry_id)[0] in valid_ids] + if filtered != original: + named_playlists[name] = filtered + persist_named[name] = filtered + with STATE_LOCK: + global_state.setdefault('named_playlists', {})[name] = list(filtered) + + default_playlist = selected_ids or entry_fallback + payload = { + 'version': version, + 'playlists': { + 'default': default_playlist + }, + 'entries': entries + } + if device_playlists: + payload['playlists']['devices'] = device_playlists + if named_playlists: + payload['playlists']['named'] = named_playlists + if bindings: + payload['playlists']['bindings'] = bindings + + # Persist pruned playlists back to SQLite (outside the state lock). + if persist_default is not None: + persist_default_playlist(list(persist_default)) + for device_id, playlist in persist_devices.items(): + persist_device_playlist(device_id, list(playlist)) + for name, playlist in persist_named.items(): + try: + models.save_rotation_playlist(list(playlist), device_id=None, name=name) + except Exception as exc: # noqa: BLE001 + logger.warning("Failed to persist named playlist '%s': %s", name, exc) + + return payload + + +def get_rotation_entry(entry_hash: Optional[str]) -> Optional[Dict[str, Any]]: + if not entry_hash: + return None + master = rotation_master() + for entry in master.get('meta') or []: + if entry.get('hash') == entry_hash or entry.get('id') == entry_hash: + return entry + return None + + +def _decode_persisted_playlist_indexes(device_id: str, stored_indexes: List[Any]) -> List[int]: + parsed: List[int] = [] + if not stored_indexes: + return parsed + mapping: Optional[Dict[str, int]] = None + for value in stored_indexes: + if isinstance(value, int): + parsed.append(value) + continue + try: + parsed.append(int(value)) + continue + except (TypeError, ValueError): + entry_id = str(value).strip() + if not entry_id: + continue + if mapping is None: + mapping = _playlist_index_map() + resolved_index = mapping.get(entry_id) + if resolved_index is None: + logger.info("Dropping legacy rotation entry '%s' for %s", entry_id, device_id) + continue + parsed.append(resolved_index) + return parsed + + +def get_device_state(device_id: str) -> Dict[str, Any]: + created = False + with STATE_LOCK: + devices = global_state.setdefault('devices', {}) + if device_id not in devices: + devices[device_id] = _build_device_state() + created = True + state = devices[device_id] + ensure_device_profile(device_id) + get_client_metrics(device_id) + if created: + persisted = models.get_device_state(device_id) + if persisted: + with STATE_LOCK: + state['request_count'] = int(persisted.get('rotation_version') or 0) + state['current_playlist_index'] = int(persisted.get('rotation_index', -1)) + stored_indexes = persisted.get('rotation_hash_order') or [] + parsed_indexes = _decode_persisted_playlist_indexes(device_id, stored_indexes) + state['playlist_indexes'] = parsed_indexes + state['last_entry_hash'] = persisted.get('last_entry_hash') + state['last_entry_plugin'] = persisted.get('current_plugin_id') + if 0 <= state['current_playlist_index'] < len(parsed_indexes): + state['current_entry_index'] = parsed_indexes[state['current_playlist_index']] + else: + state['current_playlist_index'] = -1 + state['current_entry_index'] = -1 + if 'grayscale_send_switch' not in state: + state['grayscale_send_switch'] = True + return state + + +def _extract_device_id(request: Optional[Request]) -> str: + if not request: + return DEFAULT_DEVICE_ID + for header in ('x-device-id', 'device-id', 'id'): + value = request.headers.get(header) + if value: + return value.strip() + query_params = request.query_params + for key in ('device', 'device_id', 'id', 'deviceId'): + candidate = query_params.get(key) + if candidate: + return candidate.strip() + return DEFAULT_DEVICE_ID + + +def request_base_url(request: Optional[Request]) -> str: + if not request: + return get_server_base_url() + base = str(request.base_url) + if base: + return base[:-1] if base.endswith('/') else base + host = request.headers.get('host') + scheme = request.url.scheme if request.url.scheme else config.SERVER_SCHEME + if host: + return f"{scheme}://{host}" + return get_server_base_url() + + +def get_device_state_from_request(request: Request) -> Tuple[str, Dict[str, Any]]: + device_id = _extract_device_id(request) + return device_id, get_device_state(device_id) diff --git a/trmnl_server/utils.py b/trmnl_server/utils.py new file mode 100644 index 0000000..1e50347 --- /dev/null +++ b/trmnl_server/utils.py @@ -0,0 +1,878 @@ +import os +import socket +from io import BytesIO +from functools import lru_cache +from pathlib import Path +from typing import List, Optional, Sequence, Tuple, Union +import hashlib +import math +import httpx +import datetime +from PIL import Image, ImageDraw, ImageFont +from . import config + +# Constants +PACKAGE_ROOT = Path(__file__).resolve().parent +PROJECT_ROOT = PACKAGE_ROOT.parent + +AVAILABLE_DITHER_MODES: Tuple[str, ...] = ( + 'none', + 'floyd-steinberg', + 'ordered-blue-noise', + 'perceptual', + 'multi-pass' +) + +_DITHER_TRUE_VALUES = {'true', '1', 'yes', 'on'} +_DITHER_MODE_ALIASES = { + 'none': 'none', + 'off': 'none', + '0': 'none', + 'false': 'none', + 'floyd': 'floyd-steinberg', + 'fs': 'floyd-steinberg', + 'floyd-steinberg': 'floyd-steinberg', + 'ordered': 'ordered-blue-noise', + 'blue-noise': 'ordered-blue-noise', + 'ordered-blue-noise': 'ordered-blue-noise', + 'perceptual': 'perceptual', + 'multi-pass': 'multi-pass', + 'multipass': 'multi-pass', + 'multi': 'multi-pass' +} + +BLUE_NOISE_MATRIX: List[List[int]] = [ + [50, 47, 14, 52, 44, 8, 56, 61], + [24, 23, 36, 37, 22, 12, 57, 34], + [42, 38, 32, 33, 63, 27, 58, 3], + [43, 31, 28, 11, 40, 17, 15, 20], + [62, 39, 5, 16, 10, 60, 26, 48], + [54, 35, 59, 45, 53, 9, 4, 46], + [25, 19, 55, 29, 2, 1, 49, 21], + [13, 41, 7, 6, 18, 0, 51, 30] +] +BLUE_NOISE_HEIGHT = len(BLUE_NOISE_MATRIX) +BLUE_NOISE_WIDTH = len(BLUE_NOISE_MATRIX[0]) +BLUE_NOISE_AREA = BLUE_NOISE_HEIGHT * BLUE_NOISE_WIDTH + + +def _clamp_byte(value: int) -> int: + return max(0, min(255, int(value))) + + +def _parse_tone_points(raw: str) -> List[Tuple[int, int]]: + """Parse EINK_TONE_POINTS as comma-separated "in:out" byte pairs.""" + points: List[Tuple[int, int]] = [] + raw = (raw or '').strip() + if not raw: + return points + + for token in raw.split(','): + token = token.strip() + if not token: + continue + if ':' not in token: + continue + left, right = token.split(':', 1) + left = left.strip() + right = right.strip() + if not left or not right: + continue + try: + x = _clamp_byte(int(left)) + y = _clamp_byte(int(right)) + except ValueError: + continue + points.append((x, y)) + + points = sorted(set(points), key=lambda pair: pair[0]) + return points + + +def _enforce_monotonic(values: List[int]) -> List[int]: + last = 0 + for idx, value in enumerate(values): + if idx == 0: + last = _clamp_byte(value) + values[idx] = last + continue + last = max(last, _clamp_byte(value)) + values[idx] = last + return values + + +@lru_cache(maxsize=32) +def _tone_curve_forward_lut_cached(points_raw: str, gamma: float) -> List[int]: + """Return 256-entry LUT mapping digital gray -> panel gray for the given settings.""" + points = _parse_tone_points(points_raw) + if points: + if points[0][0] != 0: + points = [(0, 0)] + points + if points[-1][0] != 255: + points = points + [(255, 255)] + + lut: List[int] = [0] * 256 + for (x0, y0), (x1, y1) in zip(points, points[1:]): + if x1 <= x0: + continue + span = x1 - x0 + for x in range(x0, x1 + 1): + if x < 0 or x > 255: + continue + t = (x - x0) / float(span) + lut[x] = _clamp_byte(int(round(y0 + (y1 - y0) * t))) + return _enforce_monotonic(lut) + + if gamma and gamma != 1.0: + lut = [_clamp_byte(int(round((math.pow(i / 255.0, gamma)) * 255))) for i in range(256)] + return _enforce_monotonic(lut) + + return list(range(256)) + + +def _tone_curve_forward_lut() -> List[int]: + """Return 256-entry LUT mapping digital gray -> panel gray.""" + points_raw = str(getattr(config, 'EINK_TONE_POINTS', '') or '') + gamma = float(getattr(config, 'EINK_TONE_GAMMA', 1.0) or 1.0) + return _tone_curve_forward_lut_cached(points_raw, gamma) + + +@lru_cache(maxsize=32) +def _tone_curve_inverse_lut_cached(points_raw: str, gamma: float) -> List[int]: + """Return 256-entry LUT mapping desired panel gray -> digital gray for the given settings.""" + forward = _tone_curve_forward_lut_cached(points_raw, gamma) + inverse: List[int] = [0] * 256 + + idx = 0 + for target in range(256): + while idx < 255 and forward[idx] < target: + idx += 1 + if idx == 0: + inverse[target] = 0 + continue + if forward[idx] == target or forward[idx] == forward[idx - 1]: + inverse[target] = idx + continue + y0 = forward[idx - 1] + y1 = forward[idx] + t = (target - y0) / float(y1 - y0) + inverse[target] = _clamp_byte(int(round((idx - 1) + t))) + + inverse[0] = 0 + inverse[255] = 255 + return _enforce_monotonic(inverse) + + +def _tone_curve_inverse_lut() -> List[int]: + """Return 256-entry LUT mapping desired panel gray -> digital gray.""" + points_raw = str(getattr(config, 'EINK_TONE_POINTS', '') or '') + gamma = float(getattr(config, 'EINK_TONE_GAMMA', 1.0) or 1.0) + return _tone_curve_inverse_lut_cached(points_raw, gamma) + + +def _tone_curve_enabled() -> bool: + points = (getattr(config, 'EINK_TONE_POINTS', '') or '').strip() + gamma = float(getattr(config, 'EINK_TONE_GAMMA', 1.0) or 1.0) + return bool(points) or (gamma != 1.0) + + +def _palette_levels_digital(levels: int) -> List[int]: + """Return list of palette gray values in digital space (0-255).""" + if levels <= 1: + return [0] + inverse = _tone_curve_inverse_lut() + + if not _tone_curve_enabled(): + step_values_panel = [int(round(index * 255 / (levels - 1))) for index in range(levels)] + else: + forward = _tone_curve_forward_lut() + panel_min = int(forward[0]) + panel_max = int(forward[255]) + if panel_max <= panel_min: + panel_min = 0 + panel_max = 255 + step_values_panel = [ + int(round(panel_min + (index * (panel_max - panel_min) / (levels - 1)))) + for index in range(levels) + ] + values = [inverse[v] for v in step_values_panel] + + for idx in range(1, len(values)): + if values[idx] <= values[idx - 1]: + values[idx] = min(255, values[idx - 1] + 1) + if len(set(values)) != len(values): + values = [int(round(index * 255 / (levels - 1))) for index in range(levels)] + return values + + +def get_effective_grayscale_palette_levels(levels: int = 4) -> Tuple[List[int], List[int]]: + """Return (panel_levels, digital_levels) used for grayscale palette generation. + + - panel_levels are the target levels in "panel space" (0-255) that the palette + aims to represent. + - digital_levels are the pixel values (0-255) that will be written into the + generated grayscale PNG/BMP assets. + """ + if levels <= 1: + return ([0], [0]) + + if not _tone_curve_enabled(): + levels_minus = levels - 1 + panel_levels = [int(round(index * 255 / levels_minus)) for index in range(levels)] + return (panel_levels, panel_levels) + + forward = _tone_curve_forward_lut() + panel_min = int(forward[0]) + panel_max = int(forward[255]) + if panel_max <= panel_min: + panel_min = 0 + panel_max = 255 + + levels_minus = levels - 1 + panel_levels = [ + int(round(panel_min + (index * (panel_max - panel_min) / levels_minus))) + for index in range(levels) + ] + return (panel_levels, _palette_levels_digital(levels)) + + +def get_assets_root() -> Path: + """Return the absolute path to the configured assets directory.""" + return Path(config.WEB_ROOT_DIR) + + +def asset_path(*parts: str) -> Path: + """Build a path inside the configured assets directory.""" + return static_asset_path(*parts) + + +def get_static_assets_root() -> Path: + """Return the absolute path to the static assets directory.""" + return Path(config.WEB_STATIC_DIR) + + +def get_generated_assets_root() -> Path: + """Return the absolute path to the generated assets directory.""" + return Path(config.WEB_GENERATED_DIR) + + +def static_asset_path(*parts: str) -> Path: + """Build a path inside the static assets directory.""" + return get_static_assets_root().joinpath(*parts) + + +def generated_asset_path(*parts: str) -> Path: + """Build a path inside the generated assets directory.""" + return get_generated_assets_root().joinpath(*parts) + + +def _default_font_candidates() -> Tuple[str, ...]: + return ( + asset_path('fonts/ttf/static/SpaceGrotesk-Medium.ttf').as_posix(), + asset_path('fonts/ttf/static/SpaceGrotesk-Regular.ttf').as_posix() + ) + + +def get_available_dither_modes() -> Tuple[str, ...]: + """Return the supported dithering mode names.""" + return AVAILABLE_DITHER_MODES + + +def path_to_web_url(path: str, prefix: str = '/web') -> Optional[str]: + """Convert a filesystem path into the correct static or generated URL.""" + candidate = Path(path) + try: + candidate = candidate.resolve() + except FileNotFoundError: + candidate = candidate if candidate.is_absolute() else (PROJECT_ROOT / candidate) + + lookups: Tuple[Tuple[Path, str], ...] = ( + (get_static_assets_root(), prefix), + (get_generated_assets_root(), '/generated'), + (get_assets_root(), prefix) + ) + for root, base in lookups: + try: + relative = candidate.relative_to(root) + return f"{base}/{relative.as_posix()}" + except ValueError: + continue + return None + + +def resolve_dither_mode(mode: Optional[str]) -> str: + """Normalize a user-specified dithering mode to a canonical value.""" + if not mode: + return config.DITHERING_MODE + + lowered = mode.strip().lower() + if lowered in _DITHER_TRUE_VALUES: + return config.DITHERING_MODE + if lowered in _DITHER_MODE_ALIASES: + return _DITHER_MODE_ALIASES[lowered] + + config.logger.warning("[dither] Unknown mode '%s', falling back to %s", mode, config.DITHERING_MODE) + return config.DITHERING_MODE + + +def load_font(size: int, candidates: Optional[Sequence[str]] = None) -> ImageFont.ImageFont: + """Load the first available font from the candidate list or fall back to default.""" + font_candidates = candidates or _default_font_candidates() + for candidate in font_candidates: + candidate_path = Path(candidate) + if not candidate_path.is_absolute(): + candidate_path = PROJECT_ROOT / candidate_path + if candidate_path.exists(): + try: + return ImageFont.truetype(candidate_path.as_posix(), size) + except OSError as exc: + config.logger.warning("[font] failed to load %s: %s", candidate_path, exc) + config.logger.warning("[font] falling back to default font") + return ImageFont.load_default() + +def get_ip_address() -> str: + """ + Get the local IP address of the machine. + """ + s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) + try: + # doesn't even have to be reachable + s.connect(('10.254.254.254', 1)) + ip = s.getsockname()[0] + except (IndexError, KeyError): + ip = '127.0.0.1' + finally: + s.close() + return ip + +def get_battery_state(battery_voltage: float) -> float: + """ + Calculate the battery state based on the given battery voltage. + """ + if float(battery_voltage) > 4.6: # is charging + return 255 + + try: + battery_state = round( + ( + (float(battery_voltage) - config.BATTERY_MIN_VOLTAGE) / + ( + config.BATTERY_MAX_VOLTAGE - + config.BATTERY_MIN_VOLTAGE + )) * 100, 1 + ) + except ZeroDivisionError: + battery_state = 0 + + if battery_state > 100: + battery_state = 100 + elif battery_state < 0: + battery_state = 0 + return battery_state + +def get_wifi_signal_strength(rssi: int) -> int: + """ + Calculate the WiFi signal strength quality based on the RSSI value. + """ + if rssi <= -100: + quality = 0 + elif rssi >= -50: + quality = 100 + else: + quality = 2 * (rssi + 100) + return quality + +def load_image(image_path: str) -> BytesIO: + """ + Load an image from a local file path or a URL. + """ + if image_path.startswith('http://') or image_path.startswith('https://'): + response = httpx.get(image_path, timeout=10) + response.raise_for_status() + return BytesIO(response.content) + with open(image_path, 'rb') as image_file: + return BytesIO(image_file.read()) + + +def ensure_image_mode(image: Union[Image.Image, BytesIO, bytes, bytearray], mode: str) -> Image.Image: + """Return the image in the requested mode, converting only if needed.""" + if isinstance(image, (bytes, bytearray)): + image = BytesIO(image) + if isinstance(image, BytesIO): + image.seek(0) + image = Image.open(image) + if image.mode == mode: + return image + return image.convert(mode) + +def get_no_image() -> BytesIO: + """ + Create a blank image with a white background and overlay text indicating no image is available, + along with the current date and time. The image is saved in BMP format and returned as + a BytesIO object. + """ + # Create a blank image with white background + img = Image.new('1', (800, 480), color=1) # '1' mode for 1-bit pixels, black and white + + # Initialize ImageDraw + d = ImageDraw.Draw(img) + + # Load font + text_font = load_font(24, ( + asset_path('DejaVuSans.ttf').as_posix(), + "DejaVuSans.ttf" + )) + + # Define text position and content + text = "No image available" + date_time = datetime.datetime.now().strftime("%d.%m.%Y %H:%M:%S") + text = f"{text}\n{date_time}" + text_bbox = d.textbbox((0, 0), text, font=text_font) + text_width, text_height = text_bbox[2] - text_bbox[0], text_bbox[3] - text_bbox[1] + text_position = ((img.width - text_width) // 2, (img.height - text_height) // 2) + + # Draw text on the image + d.text(text_position, text, fill=0, font=text_font) # fill=0 for black + + # Save the image to a BytesIO object + img_io = BytesIO() + img.save(img_io, format="BMP") + img_io.seek(0) + return img_io + +def convert_bmp_bytes_to_png(bmp_bytes: BytesIO) -> BytesIO: + """Convert a BMP image stored in memory to PNG format. + + The input BytesIO position is reset to the beginning before reading and the + returned BytesIO is positioned at the start of the PNG data. + """ + bmp_bytes.seek(0) + image = Image.open(bmp_bytes) + png_io = BytesIO() + image.save(png_io, format="PNG") + png_io.seek(0) + return png_io + + +def convert_to_grayscale_levels(image: Image.Image, levels: int = 4) -> Image.Image: + """Convert an image to discrete grayscale levels without dithering.""" + if levels < 2: + return image.convert('L') + + gray = image.convert('L') + levels_minus = max(levels - 1, 1) + + if not _tone_curve_enabled(): + step = 255 / levels_minus + + def _quantize(value: int) -> int: + return int(round(value / step) * step) + + return gray.point(_quantize) + + forward = _tone_curve_forward_lut() + panel_levels, digital_levels = get_effective_grayscale_palette_levels(levels) + panel_min = int(panel_levels[0]) if panel_levels else 0 + panel_max = int(panel_levels[-1]) if panel_levels else 255 + panel_min_n = panel_min / 255.0 + panel_max_n = panel_max / 255.0 + span_n = panel_max_n - panel_min_n + + remap: List[int] = [] + if span_n <= 0.0: + remap = list(range(256)) + return gray.point(remap) + + for value in range(256): + panel_value_n = forward[value] / 255.0 + scaled = (panel_value_n - panel_min_n) / span_n + scaled = max(0.0, min(1.0, scaled)) + level = int(round(scaled * levels_minus)) + level = max(0, min(level, levels_minus)) + remap.append(int(digital_levels[level])) + + return gray.point(remap) + + +def _build_grayscale_palette(levels: int) -> Tuple[List[int], List[int]]: + step_values = _palette_levels_digital(levels) + if step_values: + step_values[0] = 0 + step_values[-1] = 255 + palette: List[int] = [] + for value in step_values: + palette.extend([value, value, value]) + palette.extend([0] * (768 - len(palette))) + + remap_table: List[int] = [] + value_to_index = {value: idx for idx, value in enumerate(step_values)} + if not _tone_curve_enabled(): + for value in range(256): + target = value + closest = min(step_values, key=lambda candidate, t=target: abs(candidate - t)) + remap_table.append(value_to_index[closest]) + return palette, remap_table + + forward = _tone_curve_forward_lut() + palette_panel = [forward[value] for value in step_values] + for value in range(256): + panel_value = forward[value] + closest_index = min( + range(len(palette_panel)), + key=lambda idx, pv=panel_value: abs(palette_panel[idx] - pv) + ) + remap_table.append(closest_index) + return palette, remap_table + + +def _ordered_blue_noise_dither(image: Image.Image, levels: int) -> Image.Image: + gray = image.convert('L') + width, height = gray.size + result = Image.new('L', gray.size) + src = gray.load() + dst = result.load() + levels_minus = max(levels - 1, 1) + + if not _tone_curve_enabled(): + for y in range(height): + for x in range(width): + threshold = BLUE_NOISE_MATRIX[y % BLUE_NOISE_HEIGHT][x % BLUE_NOISE_WIDTH] / BLUE_NOISE_AREA + value = src[x, y] / 255.0 + scaled = value * levels_minus + base_level = math.floor(scaled) + frac = scaled - base_level + level = base_level + if frac > threshold and level < levels_minus: + level += 1 + dst[x, y] = int(round((level / levels_minus) * 255)) if levels_minus else 0 + return result + + forward = _tone_curve_forward_lut() + panel_levels, digital_levels = get_effective_grayscale_palette_levels(levels) + panel_min = int(panel_levels[0]) if panel_levels else 0 + panel_max = int(panel_levels[-1]) if panel_levels else 255 + panel_min_n = panel_min / 255.0 + panel_max_n = panel_max / 255.0 + span_n = panel_max_n - panel_min_n + if span_n <= 0.0: + return gray + + for y in range(height): + for x in range(width): + threshold = BLUE_NOISE_MATRIX[y % BLUE_NOISE_HEIGHT][x % BLUE_NOISE_WIDTH] / BLUE_NOISE_AREA + value = forward[int(src[x, y])] / 255.0 + scaled = (value - panel_min_n) / span_n + scaled = max(0.0, min(1.0, scaled)) * levels_minus + base_level = math.floor(scaled) + frac = scaled - base_level + level = base_level + if frac > threshold and level < levels_minus: + level += 1 + level = max(0, min(int(level), levels_minus)) + dst[x, y] = int(digital_levels[level]) + return result + + +def _error_diffusion_dither(image: Image.Image, levels: int, gamma: Optional[float] = None) -> Image.Image: + gray = image.convert('L') + width, height = gray.size + levels_minus = max(levels - 1, 1) + work: List[List[float]] = [] + + if _tone_curve_enabled(): + forward = _tone_curve_forward_lut() + panel_levels, digital_levels = get_effective_grayscale_palette_levels(levels) + panel_min = int(panel_levels[0]) if panel_levels else 0 + panel_max = int(panel_levels[-1]) if panel_levels else 255 + panel_min_n = panel_min / 255.0 + panel_max_n = panel_max / 255.0 + span_n = panel_max_n - panel_min_n + if span_n <= 0.0: + return image.convert('L') + + use_gamma = bool(gamma) and float(gamma) != 1.0 + for y in range(height): + row: List[float] = [] + for x in range(width): + value = forward[int(gray.getpixel((x, y)))] / 255.0 + scaled = (value - panel_min_n) / span_n + scaled = max(0.0, min(1.0, scaled)) + if use_gamma: + scaled = math.pow(scaled, float(gamma)) + row.append(scaled) + work.append(row) + result = Image.new('L', gray.size) + dst = result.load() + kernel = ( + (1, 0, 7 / 16), + (-1, 1, 3 / 16), + (0, 1, 5 / 16), + (1, 1, 1 / 16) + ) + + for y in range(height): + for x in range(width): + value = work[y][x] + scaled = max(0.0, min(1.0, value)) + level = int(round(scaled * levels_minus)) + level = max(0, min(level, levels_minus)) + + if levels_minus: + linear_level = level / levels_minus + else: + linear_level = 0.0 + quantized = math.pow(linear_level, float(gamma)) if use_gamma else linear_level + dst[x, y] = int(digital_levels[level]) + error = value - quantized + + for dx, dy, weight in kernel: + nx = x + dx + ny = y + dy + if 0 <= nx < width and 0 <= ny < height: + work[ny][nx] += error * weight + work[ny][nx] = max(0.0, min(1.0, work[ny][nx])) + return result + + inv_gamma = 1.0 / gamma if gamma else None + + for y in range(height): + row = [] + for x in range(width): + linear = gray.getpixel((x, y)) / 255.0 + row.append(math.pow(linear, gamma) if gamma else linear) + work.append(row) + + result = Image.new('L', gray.size) + dst = result.load() + kernel = ( + (1, 0, 7 / 16), + (-1, 1, 3 / 16), + (0, 1, 5 / 16), + (1, 1, 1 / 16) + ) + + for y in range(height): + for x in range(width): + value = work[y][x] + scaled = value * levels_minus + level = round(scaled) + level = max(0, min(level, levels_minus)) + quantized = level / levels_minus if levels_minus else 0.0 + linear_value = math.pow(quantized, inv_gamma) if inv_gamma else quantized + dst[x, y] = int(round(linear_value * 255)) + error = value - quantized + + for dx, dy, weight in kernel: + nx = x + dx + ny = y + dy + if 0 <= nx < width and 0 <= ny < height: + work[ny][nx] += error * weight + work[ny][nx] = max(0.0, min(1.0, work[ny][nx])) + + return result + + +def _multi_pass_dither(image: Image.Image, levels: int) -> Image.Image: + higher_levels = min(levels * 2, 16) + ordered = _ordered_blue_noise_dither(image, higher_levels) + return _error_diffusion_dither(ordered, levels) + + +def apply_dithering( + image: Image.Image, + levels: int, + mode: Optional[str] = None +) -> Image.Image: + """Apply the configured dithering mode to the provided image.""" + normalized = resolve_dither_mode(mode) + + if normalized == 'none': + return convert_to_grayscale_levels(image, levels) + if normalized == 'ordered-blue-noise': + return _ordered_blue_noise_dither(image, levels) + if normalized == 'perceptual': + return _error_diffusion_dither(image, levels, gamma=2.2) + if normalized == 'multi-pass': + return _multi_pass_dither(image, levels) + # Default to Floyd-Steinberg + return _error_diffusion_dither(image, levels) + + +def ensure_monochrome_bmp(image_blob: BytesIO, dither_mode: Optional[str] = None) -> BytesIO: + """Convert arbitrary bytes into a TRMNL-compatible 1-bit, palette BMP.""" + image_blob.seek(0) + image = Image.open(image_blob) + + if image.size != (800, 480): + image = image.resize((800, 480), resample=Image.Resampling.NEAREST) + + dithered = apply_dithering(image, levels=2, mode=dither_mode) + mono = dithered.point(lambda value: 255 if value >= 128 else 0, mode='1') + + mono_io = BytesIO() + mono.save(mono_io, format='BMP') + mono_io.seek(0) + image_blob.seek(0) + + bmp_bytes = bytearray(mono_io.getvalue()) + # force 2 color table entries (black, white) + bmp_bytes[46:50] = (2).to_bytes(4, 'little') + bmp_bytes[54:62] = bytes([0, 0, 0, 0, 255, 255, 255, 0]) + + corrected = BytesIO(bmp_bytes) + corrected.seek(0) + return corrected + + +def save_display_assets( + image: Image.Image, + output_dir: str, + basename: str, + dither_mode: Optional[str] = None, + grayscale_levels: Optional[int] = 4 +) -> Tuple[str, str]: + """Persist monochrome BMP plus grayscale PNG assets with optional dithering.""" + os.makedirs(output_dir, exist_ok=True) + safe_name = Path(basename).stem or 'plugin_output' + + if grayscale_levels is None: + grayscale = image.convert('L') if image.mode != 'L' else image + else: + levels = int(grayscale_levels) + if dither_mode: + grayscale = apply_dithering(image, levels=levels, mode=dither_mode) + else: + grayscale = convert_to_grayscale_levels(image, levels=levels) + png_path = os.path.abspath(os.path.join(output_dir, f"{safe_name}.png")) + grayscale.save(png_path, format='PNG') + + bmp_path = os.path.abspath(os.path.join(output_dir, f"{safe_name}.bmp")) + if grayscale_levels is None: + mono = grayscale.point(lambda value: 255 if value >= 128 else 0, mode='1') + mono_io = BytesIO() + mono.save(mono_io, format='BMP') + mono_io.seek(0) + bmp_bytes = bytearray(mono_io.getvalue()) + bmp_bytes[46:50] = (2).to_bytes(4, 'little') + bmp_bytes[54:62] = bytes([0, 0, 0, 0, 255, 255, 255, 0]) + with open(bmp_path, 'wb') as file: + file.write(bytes(bmp_bytes)) + else: + buffer = BytesIO() + grayscale.save(buffer, format='PNG') + buffer.seek(0) + mono_blob = ensure_monochrome_bmp(buffer, dither_mode=dither_mode) + with open(bmp_path, 'wb') as file: + file.write(mono_blob.getvalue()) + + return bmp_path, png_path + + +def generate_image_token( + image_blob: BytesIO, + length: int = 16, + salt: Optional[str] = None +) -> str: + """Return a short digest that identifies the current image payload.""" + position = image_blob.tell() + image_blob.seek(0) + hasher = hashlib.sha256() + hasher.update(image_blob.read()) + if salt: + hasher.update(salt.encode('utf-8')) + digest = hasher.hexdigest() + image_blob.seek(position) + return digest[:length] + + +def generate_grayscale_png(image_blob: BytesIO, levels: int = 4) -> BytesIO: + """Convert the provided image into a palette PNG with limited grayscale levels.""" + if levels < 2: + raise ValueError("levels must be >= 2 for grayscale rendering") + + position = image_blob.tell() + image_blob.seek(0) + image = Image.open(image_blob) + quantized = convert_to_grayscale_levels(image, levels) + palette, remap_table = _build_grayscale_palette(levels) + + indexed = quantized.point(remap_table, 'P') + indexed.putpalette(palette) + + png_io = BytesIO() + indexed.save(png_io, format='PNG', optimize=True) + png_io.seek(0) + image_blob.seek(position) + return png_io + + +def generate_dithered_grayscale_png( + image_blob: BytesIO, + levels: int = 4, + mode: Optional[str] = None +) -> BytesIO: + """Create a multi-tone PNG using the selected dithering strategy.""" + if levels < 2: + raise ValueError("levels must be >= 2 for grayscale rendering") + + position = image_blob.tell() + image_blob.seek(0) + image = Image.open(image_blob) + dithered = apply_dithering(image, levels, mode=mode) + palette, remap_table = _build_grayscale_palette(levels) + + indexed = dithered.point(remap_table, 'P') + indexed.putpalette(palette) + + png_io = BytesIO() + indexed.save(png_io, format='PNG', optimize=True) + png_io.seek(0) + image_blob.seek(position) + return png_io + + +def parse_semver(version: Optional[str]) -> Tuple[int, int, int]: + """Parse a semantic version string into a numeric tuple.""" + if not version: + return (0, 0, 0) + parts = version.split('.') + numbers = [] + for part in parts[:3]: + digits = ''.join(ch for ch in part if ch.isdigit()) + if digits: + numbers.append(int(digits)) + else: + numbers.append(0) + while len(numbers) < 3: + numbers.append(0) + return numbers[0], numbers[1], numbers[2] + + +def firmware_supports_grayscale( + version: Optional[str], + minimum: Tuple[int, int, int] = (1, 6, 0) +) -> bool: + """Return True if the firmware version meets the minimum required for grayscale.""" + parsed = parse_semver(version) + return parsed >= minimum + + +def to_iso_datetime(value: Optional[datetime.datetime]) -> str: + """Return an ISO-8601 representation for datetimes or POSIX timestamps.""" + if value is None: + return '' + if isinstance(value, (int, float)): + if value <= 0: + return '' + value = datetime.datetime.fromtimestamp(value, datetime.timezone.utc) + trimmed = value.replace(microsecond=0) + return trimmed.isoformat() + + +def to_iso_timestamp(timestamp: Optional[float]) -> str: + """Return an ISO-8601 string for a POSIX timestamp in seconds.""" + if timestamp is None or timestamp <= 0: + return '' + dt = datetime.datetime.fromtimestamp(timestamp, datetime.timezone.utc) + return to_iso_datetime(dt) + diff --git a/web/css/styles.css b/web/css/styles.css new file mode 100644 index 0000000..201ba49 --- /dev/null +++ b/web/css/styles.css @@ -0,0 +1,255 @@ +@font-face { + font-family: 'Space Grotesk Local'; + src: url('/web/fonts/woff2/static/SpaceGrotesk-Regular.woff2') format('woff2'), + url('/web/fonts/ttf/static/SpaceGrotesk-Regular.ttf') format('truetype'); + font-weight: 400; + font-style: normal; + font-display: swap; +} +@font-face { + font-family: 'Space Grotesk Local'; + src: url('/web/fonts/woff2/static/SpaceGrotesk-Medium.woff2') format('woff2'), + url('/web/fonts/ttf/static/SpaceGrotesk-Medium.ttf') format('truetype'); + font-weight: 500; + font-style: normal; + font-display: swap; +} +@font-face { + font-family: 'Space Grotesk Local'; + src: url('/web/fonts/woff2/static/SpaceGrotesk-Bold.woff2') format('woff2'), + url('/web/fonts/ttf/static/SpaceGrotesk-Bold.ttf') format('truetype'); + font-weight: 700; + font-style: normal; + font-display: swap; +} + +:root { + color-scheme: light; + --color-bg: #f5f7fb; + --color-surface: #ffffff; + --color-border: #dfe3ec; + --color-border-strong: #c4cad8; + --color-text: #0d111a; + --color-muted: #5f6677; + --color-accent: #2f7bff; + --color-menu-bg: var(--color-surface); + --color-menu-active: rgba(47, 123, 255, 0.12); + --color-menu-text: var(--color-text); + --color-topbar-bg: var(--color-surface); + --color-topbar-text: var(--color-text); + --color-log-bg: #f4f6fb; + --color-log-entry-bg: #ffffff; + --color-log-border: #dde3f0; + --color-log-text: #1f2535; + --color-card-bg: #ffffff; + --color-card-border: #dfe3ec; + --color-card-thumb-bg: #eff3ff; + --color-progress-blue: #1b6bff; + --color-progress-green: #1dab7b; + --device-card-padding: 18px; +} + +:root[data-theme='dark'] { + color-scheme: dark; + --color-bg: #05070e; + --color-surface: #101526; + --color-border: #232a3d; + --color-border-strong: #3a4356; + --color-text: #e2e7f5; + --color-muted: #9aa7c1; + --color-accent: #73c6ff; + --color-menu-bg: var(--color-surface); + --color-menu-active: rgba(115, 198, 255, 0.16); + --color-menu-text: var(--color-text); + --color-topbar-bg: var(--color-surface); + --color-topbar-text: var(--color-text); + --color-log-bg: #05070b; + --color-log-entry-bg: #10131f; + --color-log-border: #1e232f; + --color-log-text: #f4f6ff; + --color-card-bg: #0f1117; + --color-card-border: #272d3a; + --color-card-thumb-bg: #080b14; + --color-progress-blue: #589dff; + --color-progress-green: #2fd3a6; + --device-card-padding: 18px; +} + +body { + margin: 0; + padding: 0; + min-height: 100vh; + background: var(--color-bg); + color: var(--color-text); + font-family: 'Space Grotesk Local', 'Space Grotesk', 'IBM Plex Sans', system-ui, -apple-system, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif; + font-size: 16px; + line-height: 1.5; +} + + button { + font-family: inherit; + font-size: 0.9rem; + padding: 6px 14px; + border-radius: 6px; + border: 1px solid var(--color-border); + background: var(--color-surface); + color: var(--color-text); + cursor: pointer; + transition: background 0.2s ease, border-color 0.2s ease, color 0.2s ease; + } + + button:hover { + background: var(--color-bg); + border-color: var(--color-border-strong); + } + + button:disabled { + opacity: 0.6; + cursor: not-allowed; + } + + .app-shell { display: flex; min-height: 100vh; } + .menu { width: 200px; position: fixed; top: 56px; left: 0; height: calc(100% - 56px); background-color: var(--color-menu-bg); color: var(--color-menu-text); padding: 20px 0; box-sizing: border-box; border-right: 1px solid var(--color-border); box-shadow: 8px 0 24px rgba(15, 23, 42, 0.04); } + .menu a { padding: 10px 20px; text-decoration: none; font-size: 0.95rem; font-weight: 500; color: inherit; display: block; cursor: pointer; transition: background 0.2s ease, color 0.2s ease; } + .menu a:hover, .menu a.active { background-color: var(--color-menu-active); color: var(--color-accent); } + .menu a .icon { margin-right: 10px; } + .icon { display: inline-block; width: 20px; } + .topbar { position: fixed; top: 0; left: 0; right: 0; height: 56px; background-color: var(--color-topbar-bg); color: var(--color-topbar-text); display: flex; align-items: center; justify-content: space-between; padding: 0 20px; box-sizing: border-box; z-index: 1000; gap: 20px; border-bottom: 1px solid var(--color-border); box-shadow: 0 8px 24px rgba(15, 23, 42, 0.08); } + .topbar-left { display: flex; align-items: center; gap: 16px; flex-wrap: wrap; } + .topbar-item { display: flex; align-items: center; } + .topbar-title { font-size: 1.1rem; font-weight: 600; color: inherit; } + .topbar-metrics { display: flex; align-items: center; gap: 16px; flex-wrap: wrap; } + .topbar .status-item { display: flex; align-items: center; gap: 6px; font-size: 0.85rem; color: var(--color-topbar-text); } + .topbar .status-item i { color: var(--color-accent); } + .container-wrapper { flex: 1; margin-left: 200px; padding-top: 70px; } + .container { display: none; padding: 10px; } + .container.active { display: block; } + .section { margin: 10px; padding: 16px; border: 1px solid var(--color-border); border-radius: 12px; background: var(--color-surface); box-shadow: 0 10px 30px rgba(15, 23, 42, 0.08); box-sizing: border-box; } + .section-subtitle { font-size: 0.8rem; text-transform: uppercase; letter-spacing: 0.12em; color: var(--color-muted); } + .device-meta { display: flex; gap: 14px; font-size: 0.85rem; color: var(--color-muted); } + .device-meta span { display: flex; align-items: center; gap: 6px; } + .section-heading { display: flex; align-items: center; justify-content: space-between; gap: 16px; flex-wrap: wrap; margin-bottom: 12px; } + .section h2, .section h3 { margin-top: 0; color: var(--color-text); } + .status-item { display: flex; align-items: center; margin-bottom: 10px; color: var(--color-text); } + .status-name { width: 200px; color: var(--color-muted); } + .status-value { width: 100px; text-align: right; margin-right: 20px; } + .progress-bar { width: 100%; background-color: rgba(0,0,0,0.07); border-radius: 5px; overflow: hidden; } + .progress-bar-inner { height: 20px; transition: width 0.9s ease-in-out; } + .progress-bar-blue { background-color: var(--color-progress-blue); } + .progress-bar-green { background-color: var(--color-progress-green); } + .home-row { display: grid; grid-template-columns: minmax(320px, 2fr) minmax(260px, 1fr); gap: 18px; margin-bottom: 18px; align-items: stretch; } + .home-row .section { margin: 0; height: 100%; } + .home-card { height: 100%; } + .home-card-status .status-item { margin-bottom: 12px; } + .device-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(220px, 1fr)); gap: 16px; } + .device-grid-empty { padding: 24px; text-align: center; color: var(--color-muted); border: 1px dashed var(--color-border); border-radius: 12px; } + .device-card { border: 1px solid var(--color-card-border); border-radius: 12px; background: var(--color-card-bg); padding: var(--device-card-padding); text-align: left; cursor: pointer; transition: transform 0.15s ease, border-color 0.2s ease, box-shadow 0.2s ease; box-shadow: 0 4px 14px rgba(15, 23, 42, 0.08); display: flex; flex-direction: column; gap: 12px; color: inherit; } + .device-card:hover { transform: translateY(-2px); border-color: var(--color-accent); } + .device-card.active { border-color: var(--color-accent); box-shadow: 0 6px 18px rgba(47, 123, 255, 0.24); } + .device-card-preview { width: 100%; } + .device-card-thumb { width: 100%; } + .device-card-thumb-placeholder { width: 100%; min-height: 160px; max-height: 160px; border: 1px dashed var(--color-card-border); border-radius: 4px; display: flex; align-items: center; justify-content: center; color: var(--color-muted); font-size: 0.85rem; background: var(--color-card-thumb-bg); } + .device-card-header { display: flex; justify-content: space-between; align-items: baseline; gap: 8px; flex-wrap: wrap; } + .device-card-name { font-weight: 600; font-size: 1rem; word-break: break-word; overflow-wrap: anywhere; min-width: 0; } + .device-card-id { font-size: 0.78rem; color: var(--color-muted); word-break: break-word; overflow-wrap: anywhere; min-width: 0; } + .device-card-body { display: flex; flex-direction: column; gap: 6px; color: var(--color-muted); font-size: 0.9rem; word-break: break-word; overflow-wrap: anywhere; } + .device-card-metric { display: flex; align-items: center; gap: 6px; } + .device-card-footer { font-size: 0.8rem; color: var(--color-muted); word-break: break-word; overflow-wrap: anywhere; display: flex; flex-direction: column; gap: 2px; } + .device-card-playlist { font-size: 0.75rem; letter-spacing: 0.08em; text-transform: uppercase; color: var(--color-muted); } + .device-card-plugin { font-size: 0.75rem; letter-spacing: 0.08em; text-transform: uppercase; color: var(--color-muted); } + + .device-selector { display: flex; flex-direction: column; gap: 4px; color: var(--color-topbar-text); font-size: 0.75rem; letter-spacing: 0.08em; text-transform: uppercase; } + .device-selector select, .rotation-target-control select, .rotation-target-control input, .device-form input, .device-form select { + border: 1px solid var(--color-border); + border-radius: 999px; + background: var(--color-surface); + color: var(--color-text); + padding: 6px 12px; + font-family: inherit; + } + .topbar .device-selector select { min-width: 180px; background: var(--color-bg); color: var(--color-text); border-color: var(--color-border); } + .rotation-heading { align-items: flex-start; } + .rotation-target-control { display: flex; flex-direction: column; gap: 6px; font-size: 0.8rem; color: var(--color-muted); } + .rotation-target-row { display: flex; align-items: flex-end; gap: 10px; flex-wrap: wrap; } + .rotation-target-row > label { display: flex; flex-direction: column; gap: 4px; } + .rotation-target-row > label input { min-width: 220px; } + .rotation-assignment { margin-top: 18px; border-top: 1px solid var(--color-border); padding-top: 12px; display: flex; flex-direction: column; gap: 12px; } + .rotation-assignment h4 { margin: 0; font-size: 0.95rem; } + .rotation-playlist-manager { gap: 12px; } + .rotation-assignment-list { display: flex; flex-direction: column; gap: 10px; } + .rotation-assignment-row { display: grid; grid-template-columns: auto 1fr auto; align-items: center; gap: 12px; padding: 10px 14px; border: 1px solid var(--color-border); border-radius: 10px; background: var(--color-card-bg); cursor: pointer; } + .rotation-assignment-row.active { border-color: var(--color-accent); box-shadow: 0 6px 16px rgba(47, 128, 237, 0.2); } + .rotation-assignment-row input { margin: 0; accent-color: var(--color-accent); } + .rotation-assignment-info { display: flex; flex-direction: column; gap: 4px; font-size: 0.85rem; color: var(--color-muted); } + .rotation-assignment-info strong { font-size: 0.95rem; color: var(--color-text); } + .rotation-assignment-detail { font-size: 0.8rem; color: var(--color-muted); text-transform: uppercase; letter-spacing: 0.08em; } + .rotation-assignment-empty { font-size: 0.85rem; color: var(--color-muted); } + .button-danger { border-color: #d9534f; color: #d9534f; } + .button-danger:hover { border-color: #b52b27; color: #b52b27; background: rgba(217, 83, 79, 0.08); } + + .devices-page { padding: 10px; display: flex; flex-direction: column; gap: 16px; } + .devices-layout { display: grid; grid-template-columns: minmax(320px, 1fr) minmax(360px, 1fr); gap: 24px; align-items: flex-start; } + .devices-column { display: flex; flex-direction: column; gap: 16px; } + .devices-card, .metrics-card { border: 1px solid var(--color-border); border-radius: 16px; padding: 20px; background: var(--color-surface); box-shadow: 0 12px 30px rgba(15, 23, 42, 0.08); } + .devices-card .device-card { padding: var(--device-card-padding); } + .devices-list-card { padding-bottom: 0; } + .device-settings-card .device-form { margin-top: 12px; } + .device-stats { display: flex; flex-wrap: wrap; gap: 12px; font-size: 0.85rem; color: var(--color-muted); } + .device-stats span { display: flex; align-items: center; gap: 6px; } + .device-form { display: flex; flex-direction: column; gap: 12px; } + .device-form label { display: flex; flex-direction: column; gap: 6px; font-size: 0.85rem; color: var(--color-muted); } + .device-form input { border-radius: 10px; background: rgba(15, 23, 42, 0.03); color: var(--color-text); } + .device-form input:focus { outline: 2px solid var(--color-accent); border-color: transparent; } + .device-form-actions { display: flex; align-items: center; gap: 10px; } + .device-form-feedback { font-size: 0.85rem; color: var(--color-progress-green); } + .device-history-empty { font-size: 0.85rem; color: var(--color-muted); margin-top: 8px; } + .log-controls { display: flex; align-items: center; justify-content: flex-end; gap: 12px; flex-wrap: wrap; } + .log-autorefresh { display: flex; align-items: center; gap: 6px; font-size: 0.9rem; color: var(--color-muted); } + .log-autorefresh input { accent-color: var(--color-accent); } + .log-container { height: 70vh; overflow-y: auto; border: 1px solid var(--color-border); padding: 10px; background: var(--color-log-bg); } + .log-entry { margin: 10px 0; padding: 10px; border: 1px solid var(--color-log-border); border-radius: 6px; background: var(--color-log-entry-bg); color: var(--color-log-text); box-shadow: 0 1px 2px rgba(0,0,0,0.08); } + .log-entry-header { display: flex; justify-content: space-between; align-items: baseline; margin-bottom: 6px; gap: 12px; } + .timestamp { font-weight: 600; font-size: 0.9rem; color: var(--color-accent); white-space: nowrap; } + .context { color: var(--color-accent); font-size: 0.9rem; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } + .info { color: var(--color-log-text); font-family: 'SFMono-Regular', Menlo, Monaco, Consolas, 'Liberation Mono', 'Courier New', monospace; font-size: 0.85rem; margin: 0; white-space: pre-wrap; word-break: break-word; } + .rotation-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(180px, 1fr)); gap: 15px; width: 100%; } + .rotation-card { border: 1px solid var(--color-border); border-radius: 8px; padding: 10px; background: var(--color-surface); box-shadow: 0 1px 3px rgba(0, 0, 0, 0.08); display: flex; flex-direction: column; gap: 8px; } + .rotation-card img { width: 100%; height: 120px; object-fit: cover; border-radius: 5px; border: 1px solid var(--color-border); } + .rotation-actions { display: flex; align-items: center; gap: 12px; margin-top: 12px; flex-wrap: wrap; } + .rotation-feedback { font-size: 0.9rem; color: var(--color-progress-green); } + .client-playlist-row { display: flex; align-items: center; justify-content: space-between; padding: 8px 0; border-bottom: 1px solid var(--color-border); } + .client-playlist-row:last-child { border-bottom: none; } + .client-playlist-row select { min-width: 180px; background: var(--color-surface); color: var(--color-text); border: 1px solid var(--color-border); border-radius: 4px; } + .device-playlist-row { display: flex; align-items: center; justify-content: space-between; padding: 10px 0; border-bottom: 1px solid var(--color-border); } + .device-playlist-row:last-child { border-bottom: none; } + .battery-charts { display: flex; gap: 20px; flex-wrap: wrap; } + .battery-chart { flex: 1 1 400px; min-height: 220px; } + .battery-chart canvas { width: 100% !important; height: 100% !important; } + .playlist-grid { display: flex; flex-wrap: wrap; gap: 12px; margin-top: 12px; } + .playlist-card { position: relative; border: 1px solid var(--color-card-border); border-radius: 6px; background: var(--color-card-bg); padding: 8px; cursor: grab; display: flex; flex-direction: column; gap: 6px; align-items: stretch; flex: 0 1 180px; color: var(--color-text); } + .playlist-card:active { cursor: grabbing; } + .playlist-card.disabled { opacity: 0.4; } + .playlist-card-thumb { width: 100%; height: 160px; object-fit: contain; border-radius: 4px; border: 1px solid var(--color-card-border); background: var(--color-card-thumb-bg); } + .playlist-dropzone { flex: 0 0 12px; align-self: stretch; min-height: 120px; border: 2px dashed transparent; border-radius: 4px; margin: 0 2px; box-sizing: border-box; } + .playlist-dropzone.active { border-color: var(--color-accent); background: rgba(78, 161, 255, 0.1); } + .playlist-card-label { font-size: 0.9rem; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; color: var(--color-text); } + .playlist-card-toggle { display: flex; align-items: center; gap: 6px; font-size: 0.75rem; color: var(--color-muted); } + .stats-table-wrapper { overflow-x: auto; margin-top: 12px; } + .stats-table { width: 100%; border-collapse: collapse; font-size: 0.9rem; color: var(--color-text); } + .stats-table th, .stats-table td { padding: 6px 8px; border-bottom: 1px solid var(--color-border); text-align: right; } + .stats-table th:nth-child(1), .stats-table td:nth-child(1) { text-align: left; white-space: nowrap; } + .stats-table tbody tr:hover { background: rgba(0,0,0,0.05); } + .stats-table-note { margin-top: 6px; font-size: 0.8rem; color: var(--color-muted); } + .theme-toggle { display: flex; align-items: center; gap: 6px; border: 1px solid var(--color-border); background: var(--color-bg); color: var(--color-text); padding: 6px 14px; border-radius: 999px; cursor: pointer; font-size: 0.85rem; box-shadow: 0 6px 18px rgba(15, 23, 42, 0.1); } + .theme-toggle:hover { background: var(--color-surface); } + .theme-toggle i { font-size: 0.9rem; color: var(--color-accent); } + @media (max-width: 768px) { + .menu { width: 100%; height: auto; position: static; top: 0; padding-top: 0; } + .menu a { float: left; } + .topbar { position: static; width: 100%; height: auto; padding: 8px 16px; } + .container-wrapper { margin-left: 0; padding-top: 0; } + .home-row { grid-template-columns: 1fr; } + .devices-layout { grid-template-columns: 1fr; } + } + @media (max-width: 480px) { .menu a { text-align: center; float: none; } } + diff --git a/web/fonts/InterDisplay-Medium.ttf b/web/fonts/InterDisplay-Medium.ttf new file mode 100644 index 0000000..394f88d Binary files /dev/null and b/web/fonts/InterDisplay-Medium.ttf differ diff --git a/web/fonts/fontawesome-webfont.ttf b/web/fonts/fontawesome-webfont.ttf new file mode 100644 index 0000000..35acda2 Binary files /dev/null and b/web/fonts/fontawesome-webfont.ttf differ diff --git a/web/fonts/otf/SpaceGrotesk-Bold.otf b/web/fonts/otf/SpaceGrotesk-Bold.otf new file mode 100644 index 0000000..fad9462 Binary files /dev/null and b/web/fonts/otf/SpaceGrotesk-Bold.otf differ diff --git a/web/fonts/otf/SpaceGrotesk-Light.otf b/web/fonts/otf/SpaceGrotesk-Light.otf new file mode 100644 index 0000000..0fdb747 Binary files /dev/null and b/web/fonts/otf/SpaceGrotesk-Light.otf differ diff --git a/web/fonts/otf/SpaceGrotesk-Medium.otf b/web/fonts/otf/SpaceGrotesk-Medium.otf new file mode 100644 index 0000000..dedd82f Binary files /dev/null and b/web/fonts/otf/SpaceGrotesk-Medium.otf differ diff --git a/web/fonts/otf/SpaceGrotesk-Regular.otf b/web/fonts/otf/SpaceGrotesk-Regular.otf new file mode 100644 index 0000000..c71366c Binary files /dev/null and b/web/fonts/otf/SpaceGrotesk-Regular.otf differ diff --git a/web/fonts/ttf/SpaceGrotesk[wght].ttf b/web/fonts/ttf/SpaceGrotesk[wght].ttf new file mode 100644 index 0000000..a1b2e6c Binary files /dev/null and b/web/fonts/ttf/SpaceGrotesk[wght].ttf differ diff --git a/web/fonts/ttf/static/SpaceGrotesk-Bold.ttf b/web/fonts/ttf/static/SpaceGrotesk-Bold.ttf new file mode 100644 index 0000000..f8eb245 Binary files /dev/null and b/web/fonts/ttf/static/SpaceGrotesk-Bold.ttf differ diff --git a/web/fonts/ttf/static/SpaceGrotesk-Light.ttf b/web/fonts/ttf/static/SpaceGrotesk-Light.ttf new file mode 100644 index 0000000..b2c106e Binary files /dev/null and b/web/fonts/ttf/static/SpaceGrotesk-Light.ttf differ diff --git a/web/fonts/ttf/static/SpaceGrotesk-Medium.ttf b/web/fonts/ttf/static/SpaceGrotesk-Medium.ttf new file mode 100644 index 0000000..341b633 Binary files /dev/null and b/web/fonts/ttf/static/SpaceGrotesk-Medium.ttf differ diff --git a/web/fonts/ttf/static/SpaceGrotesk-Regular.ttf b/web/fonts/ttf/static/SpaceGrotesk-Regular.ttf new file mode 100644 index 0000000..46aa5da Binary files /dev/null and b/web/fonts/ttf/static/SpaceGrotesk-Regular.ttf differ diff --git a/web/fonts/woff2/SpaceGrotesk[wght].woff2 b/web/fonts/woff2/SpaceGrotesk[wght].woff2 new file mode 100644 index 0000000..0c4d658 Binary files /dev/null and b/web/fonts/woff2/SpaceGrotesk[wght].woff2 differ diff --git a/web/fonts/woff2/static/SpaceGrotesk-Bold.woff2 b/web/fonts/woff2/static/SpaceGrotesk-Bold.woff2 new file mode 100644 index 0000000..6025ccf Binary files /dev/null and b/web/fonts/woff2/static/SpaceGrotesk-Bold.woff2 differ diff --git a/web/fonts/woff2/static/SpaceGrotesk-Light.woff2 b/web/fonts/woff2/static/SpaceGrotesk-Light.woff2 new file mode 100644 index 0000000..57348b8 Binary files /dev/null and b/web/fonts/woff2/static/SpaceGrotesk-Light.woff2 differ diff --git a/web/fonts/woff2/static/SpaceGrotesk-Medium.woff2 b/web/fonts/woff2/static/SpaceGrotesk-Medium.woff2 new file mode 100644 index 0000000..ffcb76b Binary files /dev/null and b/web/fonts/woff2/static/SpaceGrotesk-Medium.woff2 differ diff --git a/web/fonts/woff2/static/SpaceGrotesk-Regular.woff2 b/web/fonts/woff2/static/SpaceGrotesk-Regular.woff2 new file mode 100644 index 0000000..568d15a Binary files /dev/null and b/web/fonts/woff2/static/SpaceGrotesk-Regular.woff2 differ diff --git a/web/img/dummy.bmp b/web/img/dummy.bmp new file mode 100644 index 0000000..1dc24e9 Binary files /dev/null and b/web/img/dummy.bmp differ diff --git a/web/index.html b/web/index.html new file mode 100644 index 0000000..e1fc293 --- /dev/null +++ b/web/index.html @@ -0,0 +1,19 @@ + + + + + + + TRMNL Server + + + + + + +
+ + + + + diff --git a/web/js/app.js b/web/js/app.js new file mode 100644 index 0000000..6ac9fc5 --- /dev/null +++ b/web/js/app.js @@ -0,0 +1,1681 @@ +(function () { + const { h, render, Fragment } = preact; + const { useState, useEffect, useMemo, useCallback, useRef } = preactHooks; + const html = htm.bind(h); + + const TABS = [ + { id: 'home', label: 'Home', icon: 'fa-home' }, + { id: 'devices', label: 'Devices', icon: 'fa-tablet-screen-button' }, + { id: 'logs', label: 'Server Logs', icon: 'fa-history' }, + { id: 'rotation', label: 'Playlists', icon: 'fa-images' } + ]; + + const LOG_PAGE_SIZE = 50; + const LOG_BUFFER_LIMIT = 200; + + function parsePlaylistToken(value) { + if (typeof value !== 'string') { + return { id: value, mode: null, raw: value }; + } + const trimmed = value.trim(); + if (!trimmed) { + return { id: '', mode: null, raw: value }; + } + const atIndex = trimmed.indexOf('@'); + const baseId = atIndex >= 0 ? trimmed.slice(0, atIndex) : trimmed; + const suffix = atIndex >= 0 ? trimmed.slice(atIndex + 1).trim().toLowerCase() : ''; + if (!suffix || suffix === 'auto') { + return { id: baseId, mode: null, raw: baseId }; + } + if (suffix === 'bmp' || suffix === 'mono') { + return { id: baseId, mode: 'bmp', raw: `${baseId}@bmp` }; + } + if (suffix === 'png' || suffix === 'gray' || suffix === 'grayscale') { + return { id: baseId, mode: 'png', raw: `${baseId}@png` }; + } + return { id: baseId, mode: null, raw: baseId }; + } + + function buildPlaylistTokensFromOrder(orderIds, tokens) { + const tokenByBase = new Map(); + (tokens || []).forEach((token) => { + const parsed = parsePlaylistToken(token); + if (parsed && parsed.id) { + tokenByBase.set(parsed.id, parsed.raw); + } + }); + return Array.from(orderIds || []).filter((id) => tokenByBase.has(id)).map((id) => tokenByBase.get(id)); + } + + function uniqueOrdered(list) { + const seen = new Set(); + const out = []; + (list || []).forEach((value) => { + if (!seen.has(value)) { + seen.add(value); + out.push(value); + } + }); + return out; + } + + const DEFAULT_STATUS = { + server: { cpu_load: 0, current_time: '', uptime: '' }, + client: { + device_id: '', + friendly_name: '', + battery_voltage: 0, + battery_voltage_max: 5, + battery_voltage_min: 2.5, + battery_state: 0, + wifi_signal: 0, + wifi_signal_strength: 0, + refresh_time: 0, + last_contact: '', + current_entry_hash: '', + current_plugin_id: '', + current_preview_url: '', + current_preview_token: '', + profile: { + refresh_interval: null, + time_zone: null, + last_seen: null + } + }, + client_data_db: [], + devices: [], + playlists: [] + }; + + function withCacheBuster(url, seed, fallbackToNow = true) { + if (!url) { + return url; + } + if (seed == null && !fallbackToNow) { + return url; + } + const raw = seed != null ? seed : Date.now(); + const marker = encodeURIComponent(String(raw)); + const separator = url.includes('?') ? '&' : '?'; + return `${url}${separator}_=${marker}`; + } + + function useInterval(callback, delay, enabled = true) { + useEffect(() => { + if (!enabled || delay == null) return undefined; + const id = setInterval(callback, delay); + return () => clearInterval(id); + }, [callback, delay, enabled]); + } + + function computeRotationOrder(entries, playlistIds, prevOrder = []) { + const entryIds = (entries || []).map((e) => e.id).filter(Boolean); + const seen = new Set(); + const ordered = []; + + const playlistBaseIds = uniqueOrdered((playlistIds || []).map((token) => parsePlaylistToken(token).id).filter(Boolean)); + + // 1) Playlist (active) order from server/client + (playlistBaseIds || []).forEach((id) => { + if (entryIds.includes(id) && !seen.has(id)) { + ordered.push(id); + seen.add(id); + } + }); + + // 2) Preserve previous ordering for remaining entries + prevOrder.forEach((id) => { + if (entryIds.includes(id) && !seen.has(id)) { + ordered.push(id); + seen.add(id); + } + }); + + // 3) Append any new entries not seen before + entryIds.forEach((id) => { + if (!seen.has(id)) { + ordered.push(id); + seen.add(id); + } + }); + + return ordered; + } + + function parseUptime(uptimeStr) { + if (!uptimeStr || typeof uptimeStr !== 'string') { + return null; + } + const trimmed = uptimeStr.trim(); + if (!trimmed) { + return null; + } + let dayCount = 0; + let timePortion = trimmed; + const dayMatch = trimmed.match(/(\d+)\s+day/); + if (dayMatch) { + dayCount = Number(dayMatch[1]) || 0; + const commaIndex = trimmed.indexOf(','); + timePortion = commaIndex >= 0 ? trimmed.slice(commaIndex + 1).trim() : trimmed; + } + const parts = timePortion.split(':').map((value) => Number(value)); + if (parts.some((value) => Number.isNaN(value))) { + return null; + } + let hours = 0; + let minutes = 0; + let seconds = 0; + if (parts.length === 3) { + [hours, minutes, seconds] = parts; + } else if (parts.length === 2) { + [minutes, seconds] = parts; + } else if (parts.length === 1) { + [seconds] = parts; + } else { + return null; + } + return (dayCount * 86400) + (hours * 3600) + (minutes * 60) + seconds; + } + + function formatUptime(totalSeconds) { + if (!Number.isFinite(totalSeconds)) { + return ''; + } + const rounded = Math.max(0, Math.floor(totalSeconds)); + const days = Math.floor(rounded / 86400); + let remainder = rounded - (days * 86400); + const hours = Math.floor(remainder / 3600); + remainder -= hours * 3600; + const minutes = Math.floor(remainder / 60); + const seconds = remainder - (minutes * 60); + const timePart = `${hours}:${String(minutes).padStart(2, '0')}:${String(seconds).padStart(2, '0')}`; + if (days > 0) { + return `${days} day${days === 1 ? '' : 's'}, ${timePart}`; + } + return timePart; + } + + function formatDisplayTimestamp(value) { + if (value == null || value === '') { + return 'N/A'; + } + let candidate = ''; + if (typeof value === 'number') { + if (value <= 0) { + return 'N/A'; + } + candidate = new Date(value * 1000).toISOString(); + } else if (typeof value === 'string') { + candidate = value.trim(); + if (!candidate) { + return 'N/A'; + } + } else { + return 'N/A'; + } + const match = candidate.match(/^(\d{4}-\d{2}-\d{2})[T ](\d{2}:\d{2}:\d{2})/); + if (match) { + return `${match[1]} ${match[2]}`; + } + if (candidate.includes('T')) { + return candidate.replace('T', ' '); + } + return candidate; + } + + function arraysEqual(lhs = [], rhs = []) { + if (lhs === rhs) { + return true; + } + if (!lhs || !rhs || lhs.length !== rhs.length) { + return false; + } + for (let idx = 0; idx < lhs.length; idx += 1) { + if (lhs[idx] !== rhs[idx]) { + return false; + } + } + return true; + } + + function normalizeDevicesList(rawDevices = []) { + if (!Array.isArray(rawDevices)) { + return []; + } + const seen = new Set(); + return rawDevices.filter((device) => { + if (!device || !device.device_id || device.device_id === 'default') { + return false; + } + if (seen.has(device.device_id)) { + return false; + } + seen.add(device.device_id); + return true; + }); + } + + function App() { + const [activeTab, setActiveTab] = useState('home'); + const [status, setStatus] = useState(DEFAULT_STATUS); + const [devices, setDevices] = useState([]); + const [selectedDeviceId, setSelectedDeviceId] = useState(''); + const [rotation, setRotation] = useState({ entries: [], playlists: { default: [] } }); + const [rotationOrder, setRotationOrder] = useState([]); + const [activeRotationIds, setActiveRotationIds] = useState([]); + const [activePlaylistTokens, setActivePlaylistTokens] = useState([]); + const [rotationTarget, setRotationTarget] = useState('default'); + const [draftPlaylists, setDraftPlaylists] = useState({}); + const [logsData, setLogsData] = useState([]); + const [logsAutoRefresh, setLogsAutoRefresh] = useState(true); + const [logsLoading, setLogsLoading] = useState(false); + const [logsError, setLogsError] = useState(null); + const [rotationFeedback, setRotationFeedback] = useState(''); + const [theme, setTheme] = useState(() => { + if (typeof window === 'undefined') { + return 'light'; + } + const stored = window.localStorage.getItem('trmnl-theme'); + if (stored === 'light' || stored === 'dark') { + return stored; + } + return window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light'; + }); + const [pageVisible, setPageVisible] = useState(() => { + if (typeof document === 'undefined') { + return true; + } + return document.visibilityState !== 'hidden'; + }); + const lastLogIdRef = useRef(null); + const pendingLogResetRef = useRef(0); + const mergeDevices = useCallback((incoming) => { + if (!Array.isArray(incoming) || incoming.length === 0) { + return; + } + setDevices((prev) => { + const map = new Map(); + (Array.isArray(prev) ? prev : []).forEach((device) => { + if (device && device.device_id && device.device_id !== 'default') { + map.set(device.device_id, device); + } + }); + incoming.forEach((device) => { + if (device && device.device_id && device.device_id !== 'default') { + map.set(device.device_id, device); + } + }); + return Array.from(map.values()); + }); + }, []); + const statusInterval = useMemo(() => { + const refreshSeconds = Number(status?.client?.refresh_time) || 60; + return Math.max(5000, (refreshSeconds * 1000) / 2); + }, [status?.client?.refresh_time]); + const deviceOptions = useMemo(() => { + const source = devices.length ? devices : (status.devices || []); + return normalizeDevicesList(source); + }, [devices, status.devices]); + const handleDeviceSelect = useCallback((nextId) => { + if (!nextId) { + return; + } + setSelectedDeviceId(nextId); + }, []); + const toggleTheme = useCallback(() => { + setTheme((prev) => (prev === 'dark' ? 'light' : 'dark')); + }, []); + const handleRotationTargetChange = useCallback((value) => { + const nextTarget = value || 'default'; + if (rotationTarget && rotationTarget !== 'default') { + setDraftPlaylists((prev) => { + if (!Object.prototype.hasOwnProperty.call(prev, rotationTarget)) { + return prev; + } + const activeOrdered = rotationOrder.filter((id) => activeRotationIds.includes(id)); + const current = Array.isArray(prev[rotationTarget]) ? prev[rotationTarget] : []; + if (arraysEqual(current, activeOrdered)) { + return prev; + } + return { ...prev, [rotationTarget]: activeOrdered }; + }); + } + setRotationTarget(nextTarget); + }, [activeRotationIds, rotationOrder, rotationTarget]); + const resolvePlaylistForTarget = useCallback((snapshot, target, drafts) => { + if (!snapshot || !snapshot.playlists) { + return []; + } + if (target && target !== 'default') { + if (drafts && Object.prototype.hasOwnProperty.call(drafts, target)) { + return Array.from(drafts[target] || []); + } + const named = snapshot.playlists?.named || {}; + if (named[target]) { + return Array.from(named[target]); + } + } + return Array.from(snapshot.playlists?.default || []); + }, []); + const fetchStatus = useCallback(async (deviceOverride) => { + try { + const targetDevice = deviceOverride || selectedDeviceId; + const params = new URLSearchParams(); + if (targetDevice) { + params.set('device_id', targetDevice); + } + const query = params.toString(); + const res = await fetch(withCacheBuster(query ? `/status?${query}` : '/status')); + if (!res.ok) return; + const data = await res.json(); + setStatus(data); + if (Array.isArray(data?.devices)) { + mergeDevices(data.devices); + } + const incomingDeviceId = data?.client?.device_id; + if (incomingDeviceId) { + if (!selectedDeviceId) { + setSelectedDeviceId(incomingDeviceId); + } else if (deviceOverride && incomingDeviceId !== selectedDeviceId) { + setSelectedDeviceId(incomingDeviceId); + } + } + } catch (e) { + console.warn('status fetch failed', e); + } + }, [mergeDevices, selectedDeviceId]); + + const fetchDevices = useCallback(async () => { + try { + const res = await fetch(withCacheBuster('/devices?include_default=false')); + if (!res.ok) return; + const data = await res.json(); + if (Array.isArray(data?.devices)) { + mergeDevices(data.devices); + } + } catch (e) { + console.warn('devices fetch failed', e); + } + }, [mergeDevices]); + + useEffect(() => { + if (typeof document !== 'undefined') { + document.documentElement.dataset.theme = theme; + } + if (typeof window !== 'undefined' && window.localStorage) { + window.localStorage.setItem('trmnl-theme', theme); + } + }, [theme]); + + useEffect(() => { + if (typeof document === 'undefined') { + return undefined; + } + const handleVisibilityChange = () => setPageVisible(document.visibilityState !== 'hidden'); + document.addEventListener('visibilitychange', handleVisibilityChange); + return () => document.removeEventListener('visibilitychange', handleVisibilityChange); + }, []); + + const fetchRotation = useCallback(async () => { + try { + const res = await fetch(withCacheBuster('/rotation')); + if (!res.ok) return; + const data = await res.json(); + setRotation(data); + } catch (e) { + console.warn('rotation fetch failed', e); + } + }, []); + + const handleDeviceUpdate = useCallback( + async (deviceId, payload) => { + if (!deviceId) { + return false; + } + try { + const res = await fetch(withCacheBuster(`/devices/${deviceId}`), { + method: 'PATCH', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify(payload) + }); + if (!res.ok) { + throw new Error(`Status ${res.status}`); + } + const nextStatusDevice = deviceId === selectedDeviceId ? deviceId : (selectedDeviceId || deviceId); + await fetchStatus(nextStatusDevice); + await fetchRotation(); + return true; + } catch (err) { + console.warn('device update failed', err); + return false; + } + }, + [fetchRotation, fetchStatus, selectedDeviceId] + ); + + const fetchLogs = useCallback( + async (options = {}) => { + const { reset = false } = options; + if (reset) { + lastLogIdRef.current = null; + pendingLogResetRef.current += 1; + setLogsLoading(true); + } + setLogsError(null); + try { + const params = new URLSearchParams({ + format: 'json', + limit: String(LOG_PAGE_SIZE) + }); + if (!reset && lastLogIdRef.current != null) { + params.set('after', String(lastLogIdRef.current)); + } + const res = await fetch(withCacheBuster(`/server/log?${params.toString()}`), { + cache: 'no-store', + headers: { Accept: 'application/json' } + }); + if (!res.ok) throw new Error(`status ${res.status}`); + const data = await res.json(); + if (reset) { + setLogsData(data.slice(-LOG_BUFFER_LIMIT)); + } else if (data.length) { + setLogsData((prev) => { + const existingIds = new Set(prev.map((entry) => entry.id)); + const merged = [...prev]; + data.forEach((entry) => { + if (!existingIds.has(entry.id)) { + merged.push(entry); + } + }); + if (merged.length > LOG_BUFFER_LIMIT) { + return merged.slice(-LOG_BUFFER_LIMIT); + } + return merged; + }); + } + if (data.length) { + lastLogIdRef.current = data[data.length - 1].id; + } + } catch (e) { + console.warn('logs fetch failed', e); + setLogsError(e.message || String(e)); + } finally { + if (reset) { + pendingLogResetRef.current = Math.max(0, pendingLogResetRef.current - 1); + if (pendingLogResetRef.current === 0) { + setLogsLoading(false); + } + } + } + }, + [] + ); + + const refreshLogs = useCallback(() => { + fetchLogs({ reset: true }); + }, [fetchLogs]); + + const appendLogs = useCallback(() => { + fetchLogs({ reset: false }); + }, [fetchLogs]); + + useEffect(() => { + fetchStatus(); + fetchRotation(); + fetchDevices(); + }, [fetchStatus, fetchRotation, fetchDevices]); + + useEffect(() => { + if (activeTab === 'rotation') { + fetchRotation(); + fetchDevices(); + } + }, [activeTab, fetchRotation, fetchDevices]); + + useEffect(() => { + if (activeTab === 'home') { + fetchStatus(); + } + }, [activeTab, fetchStatus]); + + useEffect(() => { + if (activeTab !== 'rotation' && selectedDeviceId) { + fetchStatus(selectedDeviceId); + } + }, [activeTab, selectedDeviceId, fetchStatus]); + + useEffect(() => { + if (!rotation || !rotation.entries) { + return; + } + const playlistTokens = resolvePlaylistForTarget(rotation, rotationTarget, draftPlaylists); + const playlistBaseIds = uniqueOrdered((playlistTokens || []).map((token) => parsePlaylistToken(token).id).filter(Boolean)); + setActivePlaylistTokens((prev) => (arraysEqual(prev, playlistTokens) ? prev : playlistTokens)); + setActiveRotationIds((prev) => (arraysEqual(prev, playlistBaseIds) ? prev : playlistBaseIds)); + setRotationOrder((prev) => { + const next = computeRotationOrder(rotation.entries, playlistTokens, prev); + return arraysEqual(prev, next) ? prev : next; + }); + }, [rotation, rotationTarget, resolvePlaylistForTarget, draftPlaylists]); + + useInterval(fetchStatus, statusInterval, pageVisible && activeTab !== 'rotation'); + useInterval(appendLogs, 5000, activeTab === 'logs' && logsAutoRefresh); + + useEffect(() => { + if (activeTab === 'logs') { + refreshLogs(); + } + }, [activeTab, refreshLogs]); + + const toggleSelection = (id) => { + setActivePlaylistTokens((prevTokens) => { + const existing = (prevTokens || []).find((token) => parsePlaylistToken(token).id === id); + const nextTokens = existing + ? (prevTokens || []).filter((token) => parsePlaylistToken(token).id !== id) + : [...(prevTokens || []), id]; + + const nextActiveIds = uniqueOrdered(nextTokens.map((token) => parsePlaylistToken(token).id).filter(Boolean)); + setActiveRotationIds((prevIds) => (arraysEqual(prevIds, nextActiveIds) ? prevIds : nextActiveIds)); + + if (rotationTarget && rotationTarget !== 'default') { + setDraftPlaylists((draftPrev) => { + if (!Object.prototype.hasOwnProperty.call(draftPrev, rotationTarget)) { + return draftPrev; + } + const orderedTokens = buildPlaylistTokensFromOrder(rotationOrder, nextTokens); + const current = Array.isArray(draftPrev[rotationTarget]) ? draftPrev[rotationTarget] : []; + if (arraysEqual(current, orderedTokens)) { + return draftPrev; + } + return { ...draftPrev, [rotationTarget]: orderedTokens }; + }); + } + return nextTokens; + }); + }; + + const toggleForceOneBit = useCallback((id, enabled) => { + setActivePlaylistTokens((prevTokens) => { + const tokens = Array.isArray(prevTokens) ? prevTokens : []; + const idx = tokens.findIndex((token) => parsePlaylistToken(token).id === id); + if (idx < 0) { + return tokens; + } + const current = parsePlaylistToken(tokens[idx]); + const nextRaw = enabled ? `${current.id}@bmp` : current.id; + const nextTokens = tokens.slice(); + nextTokens[idx] = nextRaw; + + if (rotationTarget && rotationTarget !== 'default') { + setDraftPlaylists((draftPrev) => { + if (!Object.prototype.hasOwnProperty.call(draftPrev, rotationTarget)) { + return draftPrev; + } + const orderedTokens = buildPlaylistTokensFromOrder(rotationOrder, nextTokens); + const currentDraft = Array.isArray(draftPrev[rotationTarget]) ? draftPrev[rotationTarget] : []; + if (arraysEqual(currentDraft, orderedTokens)) { + return draftPrev; + } + return { ...draftPrev, [rotationTarget]: orderedTokens }; + }); + } + return nextTokens; + }); + }, [rotationOrder, rotationTarget]); + + const handleRotationReorder = useCallback((nextOrder) => { + setRotationOrder(nextOrder); + if (rotationTarget && rotationTarget !== 'default') { + setDraftPlaylists((prev) => { + if (!Object.prototype.hasOwnProperty.call(prev, rotationTarget)) { + return prev; + } + const ordered = buildPlaylistTokensFromOrder(nextOrder || [], activePlaylistTokens); + const current = Array.isArray(prev[rotationTarget]) ? prev[rotationTarget] : []; + if (arraysEqual(current, ordered)) { + return prev; + } + return { ...prev, [rotationTarget]: ordered }; + }); + } + }, [activePlaylistTokens, rotationTarget]); + + const buildActivePlaylist = useCallback(() => { + return buildPlaylistTokensFromOrder(rotationOrder, activePlaylistTokens); + }, [rotationOrder, activePlaylistTokens]); + + const savePlaylistForTarget = useCallback( + async (targetId) => { + const playlist = buildActivePlaylist(); + if (!playlist.length) { + return { success: false, count: 0, message: 'Select at least one plugin' }; + } + try { + const isDefault = !targetId || targetId === 'default'; + const endpoint = isDefault ? '/rotation' : '/playlists'; + const payload = isDefault ? { playlist } : { name: targetId, playlist }; + const res = await fetch(withCacheBuster(endpoint), { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify(payload) + }); + if (!res.ok) { + throw new Error(`Status ${res.status}`); + } + const data = await res.json(); + setRotation(data); + if (!isDefault) { + setDraftPlaylists((prev) => { + if (!Object.prototype.hasOwnProperty.call(prev, targetId)) { + return prev; + } + const next = { ...prev }; + delete next[targetId]; + return next; + }); + } + return { success: true, count: playlist.length }; + } catch (err) { + console.error('playlist save failed', err); + return { success: false, count: playlist.length, message: 'Failed to save playlist' }; + } + }, + [buildActivePlaylist, setRotation] + ); + + const deletePlaylist = useCallback(async (name) => { + const target = (name || '').trim(); + if (!target || target === 'default') { + return false; + } + if (Object.prototype.hasOwnProperty.call(draftPlaylists, target)) { + setDraftPlaylists((prev) => { + const next = { ...prev }; + delete next[target]; + return next; + }); + if (rotationTarget === target) { + setRotationTarget('default'); + } + return true; + } + try { + const res = await fetch(withCacheBuster(`/playlists/${encodeURIComponent(target)}`), { method: 'DELETE' }); + if (!res.ok) { + throw new Error(`Status ${res.status}`); + } + const data = await res.json(); + setRotation(data); + if (rotationTarget === target) { + setRotationTarget('default'); + } + return true; + } catch (err) { + console.warn('playlist delete failed', err); + setRotationFeedback('Unable to delete playlist'); + return false; + } + }, [draftPlaylists, rotationTarget, setRotation, setRotationFeedback]); + + const createPlaylist = useCallback((rawName) => { + const target = (rawName || '').trim(); + if (!target || target === 'default') { + setRotationFeedback('Invalid playlist name'); + return false; + } + const existing = rotation?.playlists?.named || {}; + if (existing[target] || Object.prototype.hasOwnProperty.call(draftPlaylists, target)) { + setRotationFeedback('Playlist already exists'); + return false; + } + setDraftPlaylists((prev) => ({ ...prev, [target]: [] })); + setRotationTarget(target); + setRotationFeedback('New playlist created. Toggle at least one plugin, then Save.'); + return true; + }, [draftPlaylists, rotation, setRotationFeedback]); + + const persistRotation = async () => { + setRotationFeedback(''); + const scopeLabel = rotationTarget === 'default' ? 'default playlist' : `playlist ${rotationTarget}`; + const result = await savePlaylistForTarget(rotationTarget); + if (result.success) { + setRotationFeedback(`Saved ${result.count} image(s) for ${scopeLabel}`); + } else { + setRotationFeedback(result.message || 'Failed to save playlist'); + } + }; + + const handleDeviceAssignmentToggle = useCallback( + async (deviceId, enabled) => { + if (!deviceId || deviceId === 'default' || !rotationTarget || rotationTarget === 'default') { + return; + } + const named = rotation?.playlists?.named || {}; + const isDraft = Object.prototype.hasOwnProperty.call(draftPlaylists, rotationTarget) && !named[rotationTarget]; + if (isDraft) { + setRotationFeedback('Save the playlist before assigning devices'); + return; + } + const payload = enabled ? { playlist_name: rotationTarget } : { playlist_name: null }; + const ok = await handleDeviceUpdate(deviceId, payload); + if (ok) { + setRotationFeedback(enabled ? `Assigned ${deviceId} to ${rotationTarget}` : `Unassigned ${deviceId}`); + } else { + setRotationFeedback('Failed to update device assignment'); + } + }, + [draftPlaylists, handleDeviceUpdate, rotation, rotationTarget, setRotationFeedback] + ); + + const logsList = useMemo(() => { + if (!logsData || logsData.length === 0) { + return []; + } + return [...logsData].reverse(); + }, [logsData]); + + return html` +
+ <${Menu} activeTab=${activeTab} setActiveTab=${setActiveTab} /> + <${Topbar} + status=${status} + theme=${theme} + onToggleTheme=${toggleTheme} + uptimeRaw=${status?.server?.uptime} + devices=${deviceOptions} + selectedDeviceId=${selectedDeviceId} + onSelectDevice=${handleDeviceSelect} + /> +
+ ${activeTab === 'home' + ? html`<${Container} id="home" activeTab=${activeTab}> + <${HomeTab} + status=${status} + devices=${deviceOptions} + onSelectDevice=${handleDeviceSelect} + selectedDeviceId=${selectedDeviceId} + /> + ` + : null} + ${activeTab === 'devices' + ? html`<${Container} id="devices" activeTab=${activeTab}> + <${DevicesTab} + devices=${deviceOptions} + selectedDeviceId=${selectedDeviceId} + onSelectDevice=${handleDeviceSelect} + onUpdateDevice=${handleDeviceUpdate} + deviceHistory=${status.client_data_db} + clientStats=${status.client} + /> + ` + : null} + ${activeTab === 'logs' + ? html`<${Container} id="logs" activeTab=${activeTab}> + <${LogsTab} + logsList=${logsList} + onRefresh=${refreshLogs} + autoRefresh=${logsAutoRefresh} + setAutoRefresh=${setLogsAutoRefresh} + loading=${logsLoading} + error=${logsError} + /> + ` + : null} + ${activeTab === 'rotation' + ? html`<${Container} id="rotation" activeTab=${activeTab}> + <${RotationTab} + rotation=${rotation} + rotationOrder=${rotationOrder} + activeRotationIds=${activeRotationIds} + activePlaylistTokens=${activePlaylistTokens} + toggleSelection=${toggleSelection} + toggleForceOneBit=${toggleForceOneBit} + persistRotation=${persistRotation} + rotationFeedback=${rotationFeedback} + onReorder=${handleRotationReorder} + rotationTarget=${rotationTarget} + onTargetChange=${handleRotationTargetChange} + devices=${deviceOptions} + onAssignmentToggle=${handleDeviceAssignmentToggle} + onCreatePlaylist=${createPlaylist} + onDeletePlaylist=${deletePlaylist} + draftNames=${Object.keys(draftPlaylists || {})} + /> + ` + : null} +
+
+ `; + } + + function Menu({ activeTab, setActiveTab }) { + return html` + + `; + } + + function Topbar({ status, theme, onToggleTheme, uptimeRaw, devices, selectedDeviceId, onSelectDevice }) { + const deviceList = normalizeDevicesList((Array.isArray(devices) && devices.length ? devices : status.devices) || []); + const selectorValue = selectedDeviceId || (deviceList[0]?.device_id || ''); + const uptimeDisplay = uptimeRaw || status.server.uptime || '--'; + return html` +
+
+ +

TRMNL Server

+
+
+
+ + ${uptimeDisplay} +
+
+ +
+
+
+ `; + } + + function Container({ id, activeTab, children }) { + return html`
${children}
`; + } + + function HomeTab({ status, devices, onSelectDevice, selectedDeviceId }) { + const serverTimeDisplay = formatDisplayTimestamp(status.server.current_time); + const deviceList = normalizeDevicesList((devices && devices.length ? devices : status.devices) || []); + const effectiveSelectedId = selectedDeviceId || status.client.device_id || 'default'; + const deviceSubtitle = deviceList.length ? `${deviceList.length} active` : 'Waiting for devices'; + const serverSubtitle = serverTimeDisplay !== 'N/A' ? `Updated ${serverTimeDisplay}` : 'Awaiting metrics'; + return html` + <${Fragment}> +
+
+
+

Connected Devices

+ ${deviceSubtitle} +
+ ${deviceList.length + ? html` + <${DeviceGrid} + devices=${deviceList} + selectedDeviceId=${effectiveSelectedId} + onSelectDevice=${onSelectDevice} + /> + ` + : html`
No devices have checked in yet.
`} +
+
+
+

Server Status

+ ${serverSubtitle} +
+ <${StatusItem} + name="CPU Load" + value=${`${status.server.cpu_load} %`} + barId="cpu-load-bar" + barValue=${status.server.cpu_load} + barClass="progress-bar-blue" + /> +

Current Time:

${serverTimeDisplay}

+

Uptime:

${status.server.uptime}

+

Devices Online:

${deviceList.length}

+
+
+ + `; + } + + function StatusItem({ name, value, barId, barValue, barClass }) { + return html` +
+

${name}:

+

${value}

+
+
+
+
+ `; + } + + function DeviceGrid({ devices, selectedDeviceId, onSelectDevice }) { + const normalizedDevices = normalizeDevicesList(devices || []); + if (!normalizedDevices.length) { + return html`
No devices recorded yet
`; + } + return html` +
+ ${normalizedDevices.map((device) => { + const friendly = device.friendly_name || device.device_id; + const metrics = device.metrics || {}; + const profile = device.profile || {}; + const voltageValue = Number(metrics.battery_voltage); + const wifiValue = metrics.rssi; + const voltage = Number.isFinite(voltageValue) ? `${voltageValue.toFixed(2)} V` : 'N/A'; + const wifi = Number.isFinite(wifiValue) ? `${wifiValue} dBm` : 'N/A'; + const rawRefresh = metrics.refresh_rate ?? profile.refresh_interval; + const refreshNumber = Number(rawRefresh); + const refreshText = Number.isFinite(refreshNumber) && refreshNumber > 0 ? `${refreshNumber}s` : 'N/A'; + const lastContact = formatDisplayTimestamp(metrics.last_contact || profile.last_seen); + const previewUrl = device.state?.current_preview_url; + const previewSeed = device.state?.current_preview_token || device.state?.current_entry_hash; + const previewSrc = withCacheBuster(previewUrl, previewSeed, false); + const pluginLabel = device.state?.current_plugin_id || 'Awaiting rotation'; + const playlistName = (device.playlist_name && String(device.playlist_name).trim()) ? String(device.playlist_name).trim() : 'default'; + const playlistLabel = playlistName === 'default' ? 'Default playlist' : playlistName; + const isActive = device.device_id === selectedDeviceId; + return html` + + `; + })} +
+ `; + } + + function DevicesTab({ + devices, + selectedDeviceId, + onSelectDevice, + onUpdateDevice, + deviceHistory, + clientStats + }) { + const deviceList = normalizeDevicesList(devices || []); + const activeDevice = deviceList.find((device) => device.device_id === selectedDeviceId) || deviceList[0]; + const hasDevices = deviceList.length > 0; + const [formValues, setFormValues] = useState({ friendly_name: '', refresh_interval: '', time_zone: '' }); + const [saving, setSaving] = useState(false); + const [feedback, setFeedback] = useState(''); + const history = Array.isArray(deviceHistory) ? deviceHistory : []; + const historyMatchesSelection = activeDevice && clientStats?.device_id === activeDevice.device_id; + let filteredHistory = historyMatchesSelection ? history : []; + if (filteredHistory && filteredHistory.length > 10) { + filteredHistory = filteredHistory.slice(-10); + } + + useEffect(() => { + if (!activeDevice) { + return; + } + setFormValues({ + friendly_name: activeDevice.friendly_name || '', + refresh_interval: activeDevice.refresh_interval || activeDevice.metrics?.refresh_rate || '', + time_zone: (activeDevice.profile && activeDevice.profile.time_zone) || '' + }); + setFeedback(''); + }, [activeDevice]); + + useEffect(() => { + if (!deviceList.length || !onSelectDevice) { + return; + } + const exists = deviceList.some((device) => device.device_id === selectedDeviceId); + if (!exists && deviceList[0]) { + onSelectDevice(deviceList[0].device_id); + } + }, [deviceList, onSelectDevice, selectedDeviceId]); + + const handleInput = (key, value) => { + setFormValues((prev) => ({ ...prev, [key]: value })); + }; + + const handleSubmit = async (event) => { + event.preventDefault(); + if (!activeDevice || !onUpdateDevice) { + return; + } + setSaving(true); + const payload = {}; + if (formValues.friendly_name !== (activeDevice.friendly_name || '')) { + payload.friendly_name = formValues.friendly_name; + } + const refreshValue = Number(formValues.refresh_interval); + if (Number.isFinite(refreshValue) && refreshValue > 0) { + payload.refresh_interval = refreshValue; + } + if (formValues.time_zone !== ((activeDevice.profile && activeDevice.profile.time_zone) || '')) { + payload.time_zone = formValues.time_zone; + } + if (!Object.keys(payload).length) { + setFeedback('Nothing to update'); + setSaving(false); + return; + } + const success = await onUpdateDevice(activeDevice.device_id, payload); + setFeedback(success ? 'Saved' : 'Unable to save'); + setSaving(false); + }; + + const metrics = activeDevice?.metrics || {}; + const profile = activeDevice?.profile || {}; + const batteryValue = Number(metrics.battery_voltage); + const batteryText = Number.isFinite(batteryValue) ? `${batteryValue.toFixed(2)} V` : 'N/A'; + const wifiValue = Number(metrics.rssi); + const wifiText = Number.isFinite(wifiValue) ? `${wifiValue} dBm` : 'N/A'; + const lastSeenText = formatDisplayTimestamp(metrics.last_contact || profile.last_seen); + + if (!hasDevices) { + return html` +
+
+ No devices found in the database yet. A TRMNL will appear here once it checks in. +
+
+ `; + } + return html` +
+
+
+
+
+

Devices

+ ${deviceList.length} total +
+ <${DeviceGrid} + devices=${deviceList} + selectedDeviceId=${selectedDeviceId} + onSelectDevice=${onSelectDevice} + /> +
+ ${activeDevice + ? html` +
+
+

Device settings

+ ID: ${activeDevice.device_id} +
+
+ ${batteryText} + ${wifiText} + ${lastSeenText} +
+
+ + + +
+ + +
+
+
` + : html`

Select a device to edit settings.

`} +
+
+ ${activeDevice + ? html` +
+
+

Battery & Signal

+ + ${filteredHistory.length ? `${filteredHistory.length} samples (most recent)` : 'No telemetry yet'} + +
+ ${filteredHistory.length + ? html` + <${BatteryCharts} + data=${filteredHistory} + batteryMin=${clientStats?.battery_voltage_min} + batteryMax=${clientStats?.battery_voltage_max} + /> + ` + : html`

No telemetry stored for this device yet.

`} +
+
+
+

Telemetry samples

+ Latest readings +
+ ${filteredHistory.length + ? html`<${StatsTable} data=${filteredHistory} />` + : html`

No telemetry stored for this device yet.

`} +
+ ` + : html`

Select a device to view metrics.

`} +
+
+
+ `; + } + + function BatteryCharts({ data, batteryMin = 2.5, batteryMax = 5.0 }) { + const voltageCanvasRef = useRef(null); + const rssiCanvasRef = useRef(null); + const voltageChartRef = useRef(null); + const rssiChartRef = useRef(null); + + useEffect(() => { + if (!data || data.length === 0 || typeof Chart === 'undefined') { + return undefined; + } + + const timestamps = data.map((entry) => entry.timestamp); + const voltages = data.map((entry) => entry.battery_voltage); + const socs = data.map((entry) => { + const v = entry.battery_voltage; + const soc = ((v - batteryMin) / (batteryMax - batteryMin)) * 100; + return Math.max(0, Math.min(soc, 100)); + }); + + if (voltageChartRef.current) { + voltageChartRef.current.destroy(); + } + + voltageChartRef.current = new Chart(voltageCanvasRef.current.getContext('2d'), { + type: 'line', + data: { + labels: timestamps, + datasets: [ + { + label: 'Battery Voltage', + data: voltages, + borderColor: 'rgba(75, 192, 192, 1)', + backgroundColor: 'rgba(75, 192, 192, 0.2)', + fill: true, + yAxisID: 'y-voltage' + }, + { + label: 'Battery SOC (%)', + data: socs, + borderColor: 'rgba(255, 99, 132, 1)', + backgroundColor: 'rgba(255, 99, 132, 0.2)', + fill: true, + yAxisID: 'y-soc' + } + ] + }, + options: { + animation: false, + responsive: true, + maintainAspectRatio: false, + scales: { + x: { + type: 'time', + time: { unit: 'hour', displayFormats: { hour: 'dd.MM. HH:mm' } } + }, + 'y-voltage': { + beginAtZero: false, + title: { display: true, text: 'Battery Voltage (V)' }, + position: 'left' + }, + 'y-soc': { + beginAtZero: true, + title: { display: true, text: 'Battery SOC (%)' }, + position: 'right', + grid: { drawOnChartArea: false } + } + } + } + }); + + const rssiValues = data.map((entry) => entry.rssi); + if (rssiChartRef.current) { + rssiChartRef.current.destroy(); + } + rssiChartRef.current = new Chart(rssiCanvasRef.current.getContext('2d'), { + type: 'line', + data: { + labels: timestamps, + datasets: [ + { + label: 'WiFi Signal Strength (dBm)', + data: rssiValues, + borderColor: 'rgba(75, 192, 192, 1)', + backgroundColor: 'rgba(75, 192, 192, 0.2)', + fill: true, + yAxisID: 'y-rssi' + }, + { + label: 'WiFi Signal Strength (%)', + data: rssiValues.map(getWifiStrength), + borderColor: 'rgba(255, 99, 132, 1)', + backgroundColor: 'rgba(255, 99, 132, 0.2)', + fill: true, + yAxisID: 'y-strength' + } + ] + }, + options: { + animation: false, + responsive: true, + maintainAspectRatio: false, + scales: { + x: { + type: 'time', + time: { unit: 'hour', displayFormats: { hour: 'dd.MM. HH:mm' } } + }, + 'y-rssi': { + beginAtZero: false, + title: { display: true, text: 'RSSI (dBm)' } + }, + 'y-strength': { + beginAtZero: false, + title: { display: true, text: 'Wifi Strength (%)' }, + position: 'right' + } + } + } + }); + + return () => { + if (voltageChartRef.current) { + voltageChartRef.current.destroy(); + voltageChartRef.current = null; + } + if (rssiChartRef.current) { + rssiChartRef.current.destroy(); + rssiChartRef.current = null; + } + }; + }, [data, batteryMin, batteryMax]); + + if (!data || data.length === 0) { + return html`
No data
`; + } + + return html` +
+
+
+
+ `; + } + + function StatsTable({ data }) { + if (!data || data.length === 0) { + return html`
No data
`; + } + const rows = [...data].slice(-100).reverse(); + return html` +
+ + + + + + ${rows.map( + (entry, idx) => html` + + + + + + + ` + )} + +
TimestampVoltage (V)RSSI (dBm)WiFi (%)
${formatDisplayTimestamp(entry.timestamp)}${entry.battery_voltage != null ? Number(entry.battery_voltage).toFixed(2) : ''}${entry.rssi != null ? entry.rssi : ''}${entry.rssi != null ? Math.round(getWifiStrength(entry.rssi)) : ''}
+ ${data.length > 100 + ? html`
Showing latest 100 of ${data.length} entries
` + : null} +
+ `; + } + + function LogsTab({ logsList, onRefresh, autoRefresh, setAutoRefresh, loading, error }) { + return html` +
+
+

Server Logs

+
+ + +
+
+ ${loading + ? html`
Loading...
` + : error + ? html`
Error: ${error}
` + : html`
+ ${logsList.length === 0 + ? html`
No logs available.
` + : logsList.map( + (log) => html` +
+
+ ${formatDisplayTimestamp(log.timestamp)} + ${ + log.context ? `[${log.context}]` : '(no context)' + } +
+
${log.info || ''}
+
+ ` + )} +
`} +
+ `; + } + + function RotationTab({ + rotation, + rotationOrder, + activeRotationIds, + activePlaylistTokens, + toggleSelection, + toggleForceOneBit, + persistRotation, + rotationFeedback, + onReorder, + rotationTarget, + onTargetChange, + devices, + onAssignmentToggle, + onCreatePlaylist, + onDeletePlaylist, + draftNames + }) { + const entries = rotation.entries || []; + const [newPlaylistName, setNewPlaylistName] = useState(''); + const entriesById = useMemo(() => { + const map = {}; + entries.forEach((e) => { + map[e.id] = e; + }); + return map; + }, [entries]); + + const orderedIds = useMemo(() => { + return rotationOrder && rotationOrder.length ? rotationOrder : entries.map((e) => e.id); + }, [rotationOrder, entries]); + + const forceOneBitIds = useMemo(() => { + const forced = new Set(); + (activePlaylistTokens || []).forEach((token) => { + const parsed = parsePlaylistToken(token); + if (parsed && parsed.id && parsed.mode === 'bmp') { + forced.add(parsed.id); + } + }); + return forced; + }, [activePlaylistTokens]); + const normalizedDevices = useMemo(() => normalizeDevicesList(devices || []), [devices]); + const namedPlaylists = rotation.playlists?.named || {}; + const bindings = rotation.playlists?.bindings || {}; + const playlistOptions = useMemo(() => { + const seen = new Set(['default']); + const base = [{ id: 'default', label: 'Default playlist' }]; + Object.keys(namedPlaylists || {}).sort().forEach((name) => { + if (!seen.has(name)) { + base.push({ id: name, label: name }); + seen.add(name); + } + }); + (Array.isArray(draftNames) ? draftNames : []).sort().forEach((name) => { + if (name && !seen.has(name)) { + base.push({ id: name, label: name }); + seen.add(name); + } + }); + return base; + }, [namedPlaylists, draftNames]); + const playlistLabel = rotationTarget === 'default' ? 'Default playlist' : rotationTarget; + const isDraft = rotationTarget && rotationTarget !== 'default' + && Array.isArray(draftNames) + && draftNames.includes(rotationTarget) + && !namedPlaylists[rotationTarget]; + const canDelete = rotationTarget && rotationTarget !== 'default' && (isDraft || namedPlaylists[rotationTarget]); + + return html` +
+
+
+

Playlist

+

Editing: ${playlistLabel}${isDraft ? ' (unsaved)' : ''}

+
+
+
+ + + + +
+
+
+

Drag thumbnails to reorder. Toggle to enable/disable; disabled plugins stay in the grid but are skipped by the server.

+ <${PlaylistGrid} + entriesById=${entriesById} + orderedIds=${orderedIds} + activeIds=${activeRotationIds} + forceOneBitIds=${forceOneBitIds} + onReorder=${onReorder} + onToggleActive=${toggleSelection} + onToggleForceOneBit=${toggleForceOneBit} + /> +
+ + ${rotationFeedback} +
+
+
+

Device assignments

+ Select devices that should use this playlist +
+ ${rotationTarget === 'default' + ? html`

Default playlist applies to unassigned devices.

` + : isDraft + ? html`

Save this playlist before assigning devices.

` + : normalizedDevices.length + ? html` +
+ ${normalizedDevices.map((device) => { + const deviceId = device.device_id; + const assigned = bindings[deviceId] === rotationTarget; + const detail = assigned ? 'Assigned' : 'Follows default'; + return html` + `; + })} +
` + : html`

No devices available for assignment yet.

`} +
+
+ `; + } + + function PlaylistGrid({ entriesById, orderedIds, activeIds, forceOneBitIds, onReorder, onToggleActive, onToggleForceOneBit }) { + const [draggingId, setDraggingId] = useState(null); + const [dropIndex, setDropIndex] = useState(null); + const uniqueOrderedIds = useMemo(() => Array.from(new Set(orderedIds)), [orderedIds]); + + const handleDropAt = (index) => { + if (!draggingId) return; + const next = uniqueOrderedIds.filter((id) => id !== draggingId); + next.splice(index, 0, draggingId); + onReorder(next); + setDraggingId(null); + setDropIndex(null); + }; + + const renderDropZone = (index) => html` +
{ + e.preventDefault(); + setDropIndex(index); + }} + onDragOver=${(e) => { + e.preventDefault(); + setDropIndex(index); + }} + onDragLeave=${(e) => { + e.preventDefault(); + setDropIndex((cur) => (cur === index ? null : cur)); + }} + onDrop=${(e) => { + e.preventDefault(); + handleDropAt(index); + }} + >
+ `; + + const items = []; + items.push(renderDropZone(0)); + uniqueOrderedIds.forEach((id, idx) => { + const entry = entriesById[id] || { label: id, id }; + const active = activeIds.includes(id); + const forceOneBit = forceOneBitIds && typeof forceOneBitIds.has === 'function' ? forceOneBitIds.has(id) : false; + items.push(html` +
{ + setDraggingId(id); + if (e.dataTransfer) { + e.dataTransfer.effectAllowed = 'move'; + e.dataTransfer.setData('text/plain', id); + } + }} + onDragEnd=${() => { + setDraggingId(null); + setDropIndex(null); + }} + > + ${entry.label} +
${entry.label || entry.id}
+ + +
+ `); + items.push(renderDropZone(idx + 1)); + }); + + return html`
${items}
`; + } + + function getWifiStrength(rssi) { + if (rssi <= -100) { + return 0; + } + if (rssi >= -50) { + return 100; + } + return 2 * (rssi + 100); + } + + render(html`<${App} />`, document.getElementById('app-root')); +})(); diff --git a/web/js/vendor/chart.umd.js b/web/js/vendor/chart.umd.js new file mode 100644 index 0000000..44f8065 --- /dev/null +++ b/web/js/vendor/chart.umd.js @@ -0,0 +1,14 @@ +/*! + * Chart.js v4.4.1 + * https://www.chartjs.org + * (c) 2023 Chart.js Contributors + * Released under the MIT License + */ +!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).Chart=e()}(this,(function(){"use strict";var t=Object.freeze({__proto__:null,get Colors(){return Go},get Decimation(){return Qo},get Filler(){return ma},get Legend(){return ya},get SubTitle(){return ka},get Title(){return Ma},get Tooltip(){return Ba}});function e(){}const i=(()=>{let t=0;return()=>t++})();function s(t){return null==t}function n(t){if(Array.isArray&&Array.isArray(t))return!0;const e=Object.prototype.toString.call(t);return"[object"===e.slice(0,7)&&"Array]"===e.slice(-6)}function o(t){return null!==t&&"[object Object]"===Object.prototype.toString.call(t)}function a(t){return("number"==typeof t||t instanceof Number)&&isFinite(+t)}function r(t,e){return a(t)?t:e}function l(t,e){return void 0===t?e:t}const h=(t,e)=>"string"==typeof t&&t.endsWith("%")?parseFloat(t)/100:+t/e,c=(t,e)=>"string"==typeof t&&t.endsWith("%")?parseFloat(t)/100*e:+t;function d(t,e,i){if(t&&"function"==typeof t.call)return t.apply(i,e)}function u(t,e,i,s){let a,r,l;if(n(t))if(r=t.length,s)for(a=r-1;a>=0;a--)e.call(i,t[a],a);else for(a=0;at,x:t=>t.x,y:t=>t.y};function v(t){const e=t.split("."),i=[];let s="";for(const t of e)s+=t,s.endsWith("\\")?s=s.slice(0,-1)+".":(i.push(s),s="");return i}function M(t,e){const i=y[e]||(y[e]=function(t){const e=v(t);return t=>{for(const i of e){if(""===i)break;t=t&&t[i]}return t}}(e));return i(t)}function w(t){return t.charAt(0).toUpperCase()+t.slice(1)}const k=t=>void 0!==t,S=t=>"function"==typeof t,P=(t,e)=>{if(t.size!==e.size)return!1;for(const i of t)if(!e.has(i))return!1;return!0};function D(t){return"mouseup"===t.type||"click"===t.type||"contextmenu"===t.type}const C=Math.PI,O=2*C,A=O+C,T=Number.POSITIVE_INFINITY,L=C/180,E=C/2,R=C/4,I=2*C/3,z=Math.log10,F=Math.sign;function V(t,e,i){return Math.abs(t-e)t-e)).pop(),e}function N(t){return!isNaN(parseFloat(t))&&isFinite(t)}function H(t,e){const i=Math.round(t);return i-e<=t&&i+e>=t}function j(t,e,i){let s,n,o;for(s=0,n=t.length;sl&&h=Math.min(e,i)-s&&t<=Math.max(e,i)+s}function et(t,e,i){i=i||(i=>t[i]1;)s=o+n>>1,i(s)?o=s:n=s;return{lo:o,hi:n}}const it=(t,e,i,s)=>et(t,i,s?s=>{const n=t[s][e];return nt[s][e]et(t,i,(s=>t[s][e]>=i));function nt(t,e,i){let s=0,n=t.length;for(;ss&&t[n-1]>i;)n--;return s>0||n{const i="_onData"+w(e),s=t[e];Object.defineProperty(t,e,{configurable:!0,enumerable:!1,value(...e){const n=s.apply(this,e);return t._chartjs.listeners.forEach((t=>{"function"==typeof t[i]&&t[i](...e)})),n}})})))}function rt(t,e){const i=t._chartjs;if(!i)return;const s=i.listeners,n=s.indexOf(e);-1!==n&&s.splice(n,1),s.length>0||(ot.forEach((e=>{delete t[e]})),delete t._chartjs)}function lt(t){const e=new Set(t);return e.size===t.length?t:Array.from(e)}const ht="undefined"==typeof window?function(t){return t()}:window.requestAnimationFrame;function ct(t,e){let i=[],s=!1;return function(...n){i=n,s||(s=!0,ht.call(window,(()=>{s=!1,t.apply(e,i)})))}}function dt(t,e){let i;return function(...s){return e?(clearTimeout(i),i=setTimeout(t,e,s)):t.apply(this,s),e}}const ut=t=>"start"===t?"left":"end"===t?"right":"center",ft=(t,e,i)=>"start"===t?e:"end"===t?i:(e+i)/2,gt=(t,e,i,s)=>t===(s?"left":"right")?i:"center"===t?(e+i)/2:e;function pt(t,e,i){const s=e.length;let n=0,o=s;if(t._sorted){const{iScale:a,_parsed:r}=t,l=a.axis,{min:h,max:c,minDefined:d,maxDefined:u}=a.getUserBounds();d&&(n=J(Math.min(it(r,l,h).lo,i?s:it(e,l,a.getPixelForValue(h)).lo),0,s-1)),o=u?J(Math.max(it(r,a.axis,c,!0).hi+1,i?0:it(e,l,a.getPixelForValue(c),!0).hi+1),n,s)-n:s-n}return{start:n,count:o}}function mt(t){const{xScale:e,yScale:i,_scaleRanges:s}=t,n={xmin:e.min,xmax:e.max,ymin:i.min,ymax:i.max};if(!s)return t._scaleRanges=n,!0;const o=s.xmin!==e.min||s.xmax!==e.max||s.ymin!==i.min||s.ymax!==i.max;return Object.assign(s,n),o}class bt{constructor(){this._request=null,this._charts=new Map,this._running=!1,this._lastDate=void 0}_notify(t,e,i,s){const n=e.listeners[s],o=e.duration;n.forEach((s=>s({chart:t,initial:e.initial,numSteps:o,currentStep:Math.min(i-e.start,o)})))}_refresh(){this._request||(this._running=!0,this._request=ht.call(window,(()=>{this._update(),this._request=null,this._running&&this._refresh()})))}_update(t=Date.now()){let e=0;this._charts.forEach(((i,s)=>{if(!i.running||!i.items.length)return;const n=i.items;let o,a=n.length-1,r=!1;for(;a>=0;--a)o=n[a],o._active?(o._total>i.duration&&(i.duration=o._total),o.tick(t),r=!0):(n[a]=n[n.length-1],n.pop());r&&(s.draw(),this._notify(s,i,t,"progress")),n.length||(i.running=!1,this._notify(s,i,t,"complete"),i.initial=!1),e+=n.length})),this._lastDate=t,0===e&&(this._running=!1)}_getAnims(t){const e=this._charts;let i=e.get(t);return i||(i={running:!1,initial:!0,items:[],listeners:{complete:[],progress:[]}},e.set(t,i)),i}listen(t,e,i){this._getAnims(t).listeners[e].push(i)}add(t,e){e&&e.length&&this._getAnims(t).items.push(...e)}has(t){return this._getAnims(t).items.length>0}start(t){const e=this._charts.get(t);e&&(e.running=!0,e.start=Date.now(),e.duration=e.items.reduce(((t,e)=>Math.max(t,e._duration)),0),this._refresh())}running(t){if(!this._running)return!1;const e=this._charts.get(t);return!!(e&&e.running&&e.items.length)}stop(t){const e=this._charts.get(t);if(!e||!e.items.length)return;const i=e.items;let s=i.length-1;for(;s>=0;--s)i[s].cancel();e.items=[],this._notify(t,e,Date.now(),"complete")}remove(t){return this._charts.delete(t)}}var xt=new bt; +/*! + * @kurkle/color v0.3.2 + * https://github.com/kurkle/color#readme + * (c) 2023 Jukka Kurkela + * Released under the MIT License + */function _t(t){return t+.5|0}const yt=(t,e,i)=>Math.max(Math.min(t,i),e);function vt(t){return yt(_t(2.55*t),0,255)}function Mt(t){return yt(_t(255*t),0,255)}function wt(t){return yt(_t(t/2.55)/100,0,1)}function kt(t){return yt(_t(100*t),0,100)}const St={0:0,1:1,2:2,3:3,4:4,5:5,6:6,7:7,8:8,9:9,A:10,B:11,C:12,D:13,E:14,F:15,a:10,b:11,c:12,d:13,e:14,f:15},Pt=[..."0123456789ABCDEF"],Dt=t=>Pt[15&t],Ct=t=>Pt[(240&t)>>4]+Pt[15&t],Ot=t=>(240&t)>>4==(15&t);function At(t){var e=(t=>Ot(t.r)&&Ot(t.g)&&Ot(t.b)&&Ot(t.a))(t)?Dt:Ct;return t?"#"+e(t.r)+e(t.g)+e(t.b)+((t,e)=>t<255?e(t):"")(t.a,e):void 0}const Tt=/^(hsla?|hwb|hsv)\(\s*([-+.e\d]+)(?:deg)?[\s,]+([-+.e\d]+)%[\s,]+([-+.e\d]+)%(?:[\s,]+([-+.e\d]+)(%)?)?\s*\)$/;function Lt(t,e,i){const s=e*Math.min(i,1-i),n=(e,n=(e+t/30)%12)=>i-s*Math.max(Math.min(n-3,9-n,1),-1);return[n(0),n(8),n(4)]}function Et(t,e,i){const s=(s,n=(s+t/60)%6)=>i-i*e*Math.max(Math.min(n,4-n,1),0);return[s(5),s(3),s(1)]}function Rt(t,e,i){const s=Lt(t,1,.5);let n;for(e+i>1&&(n=1/(e+i),e*=n,i*=n),n=0;n<3;n++)s[n]*=1-e-i,s[n]+=e;return s}function It(t){const e=t.r/255,i=t.g/255,s=t.b/255,n=Math.max(e,i,s),o=Math.min(e,i,s),a=(n+o)/2;let r,l,h;return n!==o&&(h=n-o,l=a>.5?h/(2-n-o):h/(n+o),r=function(t,e,i,s,n){return t===n?(e-i)/s+(e>16&255,o>>8&255,255&o]}return t}(),Ht.transparent=[0,0,0,0]);const e=Ht[t.toLowerCase()];return e&&{r:e[0],g:e[1],b:e[2],a:4===e.length?e[3]:255}}const $t=/^rgba?\(\s*([-+.\d]+)(%)?[\s,]+([-+.e\d]+)(%)?[\s,]+([-+.e\d]+)(%)?(?:[\s,/]+([-+.e\d]+)(%)?)?\s*\)$/;const Yt=t=>t<=.0031308?12.92*t:1.055*Math.pow(t,1/2.4)-.055,Ut=t=>t<=.04045?t/12.92:Math.pow((t+.055)/1.055,2.4);function Xt(t,e,i){if(t){let s=It(t);s[e]=Math.max(0,Math.min(s[e]+s[e]*i,0===e?360:1)),s=Ft(s),t.r=s[0],t.g=s[1],t.b=s[2]}}function qt(t,e){return t?Object.assign(e||{},t):t}function Kt(t){var e={r:0,g:0,b:0,a:255};return Array.isArray(t)?t.length>=3&&(e={r:t[0],g:t[1],b:t[2],a:255},t.length>3&&(e.a=Mt(t[3]))):(e=qt(t,{r:0,g:0,b:0,a:1})).a=Mt(e.a),e}function Gt(t){return"r"===t.charAt(0)?function(t){const e=$t.exec(t);let i,s,n,o=255;if(e){if(e[7]!==i){const t=+e[7];o=e[8]?vt(t):yt(255*t,0,255)}return i=+e[1],s=+e[3],n=+e[5],i=255&(e[2]?vt(i):yt(i,0,255)),s=255&(e[4]?vt(s):yt(s,0,255)),n=255&(e[6]?vt(n):yt(n,0,255)),{r:i,g:s,b:n,a:o}}}(t):Bt(t)}class Zt{constructor(t){if(t instanceof Zt)return t;const e=typeof t;let i;var s,n,o;"object"===e?i=Kt(t):"string"===e&&(o=(s=t).length,"#"===s[0]&&(4===o||5===o?n={r:255&17*St[s[1]],g:255&17*St[s[2]],b:255&17*St[s[3]],a:5===o?17*St[s[4]]:255}:7!==o&&9!==o||(n={r:St[s[1]]<<4|St[s[2]],g:St[s[3]]<<4|St[s[4]],b:St[s[5]]<<4|St[s[6]],a:9===o?St[s[7]]<<4|St[s[8]]:255})),i=n||jt(t)||Gt(t)),this._rgb=i,this._valid=!!i}get valid(){return this._valid}get rgb(){var t=qt(this._rgb);return t&&(t.a=wt(t.a)),t}set rgb(t){this._rgb=Kt(t)}rgbString(){return this._valid?(t=this._rgb)&&(t.a<255?`rgba(${t.r}, ${t.g}, ${t.b}, ${wt(t.a)})`:`rgb(${t.r}, ${t.g}, ${t.b})`):void 0;var t}hexString(){return this._valid?At(this._rgb):void 0}hslString(){return this._valid?function(t){if(!t)return;const e=It(t),i=e[0],s=kt(e[1]),n=kt(e[2]);return t.a<255?`hsla(${i}, ${s}%, ${n}%, ${wt(t.a)})`:`hsl(${i}, ${s}%, ${n}%)`}(this._rgb):void 0}mix(t,e){if(t){const i=this.rgb,s=t.rgb;let n;const o=e===n?.5:e,a=2*o-1,r=i.a-s.a,l=((a*r==-1?a:(a+r)/(1+a*r))+1)/2;n=1-l,i.r=255&l*i.r+n*s.r+.5,i.g=255&l*i.g+n*s.g+.5,i.b=255&l*i.b+n*s.b+.5,i.a=o*i.a+(1-o)*s.a,this.rgb=i}return this}interpolate(t,e){return t&&(this._rgb=function(t,e,i){const s=Ut(wt(t.r)),n=Ut(wt(t.g)),o=Ut(wt(t.b));return{r:Mt(Yt(s+i*(Ut(wt(e.r))-s))),g:Mt(Yt(n+i*(Ut(wt(e.g))-n))),b:Mt(Yt(o+i*(Ut(wt(e.b))-o))),a:t.a+i*(e.a-t.a)}}(this._rgb,t._rgb,e)),this}clone(){return new Zt(this.rgb)}alpha(t){return this._rgb.a=Mt(t),this}clearer(t){return this._rgb.a*=1-t,this}greyscale(){const t=this._rgb,e=_t(.3*t.r+.59*t.g+.11*t.b);return t.r=t.g=t.b=e,this}opaquer(t){return this._rgb.a*=1+t,this}negate(){const t=this._rgb;return t.r=255-t.r,t.g=255-t.g,t.b=255-t.b,this}lighten(t){return Xt(this._rgb,2,t),this}darken(t){return Xt(this._rgb,2,-t),this}saturate(t){return Xt(this._rgb,1,t),this}desaturate(t){return Xt(this._rgb,1,-t),this}rotate(t){return function(t,e){var i=It(t);i[0]=Vt(i[0]+e),i=Ft(i),t.r=i[0],t.g=i[1],t.b=i[2]}(this._rgb,t),this}}function Jt(t){if(t&&"object"==typeof t){const e=t.toString();return"[object CanvasPattern]"===e||"[object CanvasGradient]"===e}return!1}function Qt(t){return Jt(t)?t:new Zt(t)}function te(t){return Jt(t)?t:new Zt(t).saturate(.5).darken(.1).hexString()}const ee=["x","y","borderWidth","radius","tension"],ie=["color","borderColor","backgroundColor"];const se=new Map;function ne(t,e,i){return function(t,e){e=e||{};const i=t+JSON.stringify(e);let s=se.get(i);return s||(s=new Intl.NumberFormat(t,e),se.set(i,s)),s}(e,i).format(t)}const oe={values:t=>n(t)?t:""+t,numeric(t,e,i){if(0===t)return"0";const s=this.chart.options.locale;let n,o=t;if(i.length>1){const e=Math.max(Math.abs(i[0].value),Math.abs(i[i.length-1].value));(e<1e-4||e>1e15)&&(n="scientific"),o=function(t,e){let i=e.length>3?e[2].value-e[1].value:e[1].value-e[0].value;Math.abs(i)>=1&&t!==Math.floor(t)&&(i=t-Math.floor(t));return i}(t,i)}const a=z(Math.abs(o)),r=isNaN(a)?1:Math.max(Math.min(-1*Math.floor(a),20),0),l={notation:n,minimumFractionDigits:r,maximumFractionDigits:r};return Object.assign(l,this.options.ticks.format),ne(t,s,l)},logarithmic(t,e,i){if(0===t)return"0";const s=i[e].significand||t/Math.pow(10,Math.floor(z(t)));return[1,2,3,5,10,15].includes(s)||e>.8*i.length?oe.numeric.call(this,t,e,i):""}};var ae={formatters:oe};const re=Object.create(null),le=Object.create(null);function he(t,e){if(!e)return t;const i=e.split(".");for(let e=0,s=i.length;et.chart.platform.getDevicePixelRatio(),this.elements={},this.events=["mousemove","mouseout","click","touchstart","touchmove"],this.font={family:"'Helvetica Neue', 'Helvetica', 'Arial', sans-serif",size:12,style:"normal",lineHeight:1.2,weight:null},this.hover={},this.hoverBackgroundColor=(t,e)=>te(e.backgroundColor),this.hoverBorderColor=(t,e)=>te(e.borderColor),this.hoverColor=(t,e)=>te(e.color),this.indexAxis="x",this.interaction={mode:"nearest",intersect:!0,includeInvisible:!1},this.maintainAspectRatio=!0,this.onHover=null,this.onClick=null,this.parsing=!0,this.plugins={},this.responsive=!0,this.scale=void 0,this.scales={},this.showLine=!0,this.drawActiveElementsOnTop=!0,this.describe(t),this.apply(e)}set(t,e){return ce(this,t,e)}get(t){return he(this,t)}describe(t,e){return ce(le,t,e)}override(t,e){return ce(re,t,e)}route(t,e,i,s){const n=he(this,t),a=he(this,i),r="_"+e;Object.defineProperties(n,{[r]:{value:n[e],writable:!0},[e]:{enumerable:!0,get(){const t=this[r],e=a[s];return o(t)?Object.assign({},e,t):l(t,e)},set(t){this[r]=t}}})}apply(t){t.forEach((t=>t(this)))}}var ue=new de({_scriptable:t=>!t.startsWith("on"),_indexable:t=>"events"!==t,hover:{_fallback:"interaction"},interaction:{_scriptable:!1,_indexable:!1}},[function(t){t.set("animation",{delay:void 0,duration:1e3,easing:"easeOutQuart",fn:void 0,from:void 0,loop:void 0,to:void 0,type:void 0}),t.describe("animation",{_fallback:!1,_indexable:!1,_scriptable:t=>"onProgress"!==t&&"onComplete"!==t&&"fn"!==t}),t.set("animations",{colors:{type:"color",properties:ie},numbers:{type:"number",properties:ee}}),t.describe("animations",{_fallback:"animation"}),t.set("transitions",{active:{animation:{duration:400}},resize:{animation:{duration:0}},show:{animations:{colors:{from:"transparent"},visible:{type:"boolean",duration:0}}},hide:{animations:{colors:{to:"transparent"},visible:{type:"boolean",easing:"linear",fn:t=>0|t}}}})},function(t){t.set("layout",{autoPadding:!0,padding:{top:0,right:0,bottom:0,left:0}})},function(t){t.set("scale",{display:!0,offset:!1,reverse:!1,beginAtZero:!1,bounds:"ticks",clip:!0,grace:0,grid:{display:!0,lineWidth:1,drawOnChartArea:!0,drawTicks:!0,tickLength:8,tickWidth:(t,e)=>e.lineWidth,tickColor:(t,e)=>e.color,offset:!1},border:{display:!0,dash:[],dashOffset:0,width:1},title:{display:!1,text:"",padding:{top:4,bottom:4}},ticks:{minRotation:0,maxRotation:50,mirror:!1,textStrokeWidth:0,textStrokeColor:"",padding:3,display:!0,autoSkip:!0,autoSkipPadding:3,labelOffset:0,callback:ae.formatters.values,minor:{},major:{},align:"center",crossAlign:"near",showLabelBackdrop:!1,backdropColor:"rgba(255, 255, 255, 0.75)",backdropPadding:2}}),t.route("scale.ticks","color","","color"),t.route("scale.grid","color","","borderColor"),t.route("scale.border","color","","borderColor"),t.route("scale.title","color","","color"),t.describe("scale",{_fallback:!1,_scriptable:t=>!t.startsWith("before")&&!t.startsWith("after")&&"callback"!==t&&"parser"!==t,_indexable:t=>"borderDash"!==t&&"tickBorderDash"!==t&&"dash"!==t}),t.describe("scales",{_fallback:"scale"}),t.describe("scale.ticks",{_scriptable:t=>"backdropPadding"!==t&&"callback"!==t,_indexable:t=>"backdropPadding"!==t})}]);function fe(){return"undefined"!=typeof window&&"undefined"!=typeof document}function ge(t){let e=t.parentNode;return e&&"[object ShadowRoot]"===e.toString()&&(e=e.host),e}function pe(t,e,i){let s;return"string"==typeof t?(s=parseInt(t,10),-1!==t.indexOf("%")&&(s=s/100*e.parentNode[i])):s=t,s}const me=t=>t.ownerDocument.defaultView.getComputedStyle(t,null);function be(t,e){return me(t).getPropertyValue(e)}const xe=["top","right","bottom","left"];function _e(t,e,i){const s={};i=i?"-"+i:"";for(let n=0;n<4;n++){const o=xe[n];s[o]=parseFloat(t[e+"-"+o+i])||0}return s.width=s.left+s.right,s.height=s.top+s.bottom,s}const ye=(t,e,i)=>(t>0||e>0)&&(!i||!i.shadowRoot);function ve(t,e){if("native"in t)return t;const{canvas:i,currentDevicePixelRatio:s}=e,n=me(i),o="border-box"===n.boxSizing,a=_e(n,"padding"),r=_e(n,"border","width"),{x:l,y:h,box:c}=function(t,e){const i=t.touches,s=i&&i.length?i[0]:t,{offsetX:n,offsetY:o}=s;let a,r,l=!1;if(ye(n,o,t.target))a=n,r=o;else{const t=e.getBoundingClientRect();a=s.clientX-t.left,r=s.clientY-t.top,l=!0}return{x:a,y:r,box:l}}(t,i),d=a.left+(c&&r.left),u=a.top+(c&&r.top);let{width:f,height:g}=e;return o&&(f-=a.width+r.width,g-=a.height+r.height),{x:Math.round((l-d)/f*i.width/s),y:Math.round((h-u)/g*i.height/s)}}const Me=t=>Math.round(10*t)/10;function we(t,e,i,s){const n=me(t),o=_e(n,"margin"),a=pe(n.maxWidth,t,"clientWidth")||T,r=pe(n.maxHeight,t,"clientHeight")||T,l=function(t,e,i){let s,n;if(void 0===e||void 0===i){const o=ge(t);if(o){const t=o.getBoundingClientRect(),a=me(o),r=_e(a,"border","width"),l=_e(a,"padding");e=t.width-l.width-r.width,i=t.height-l.height-r.height,s=pe(a.maxWidth,o,"clientWidth"),n=pe(a.maxHeight,o,"clientHeight")}else e=t.clientWidth,i=t.clientHeight}return{width:e,height:i,maxWidth:s||T,maxHeight:n||T}}(t,e,i);let{width:h,height:c}=l;if("content-box"===n.boxSizing){const t=_e(n,"border","width"),e=_e(n,"padding");h-=e.width+t.width,c-=e.height+t.height}h=Math.max(0,h-o.width),c=Math.max(0,s?h/s:c-o.height),h=Me(Math.min(h,a,l.maxWidth)),c=Me(Math.min(c,r,l.maxHeight)),h&&!c&&(c=Me(h/2));return(void 0!==e||void 0!==i)&&s&&l.height&&c>l.height&&(c=l.height,h=Me(Math.floor(c*s))),{width:h,height:c}}function ke(t,e,i){const s=e||1,n=Math.floor(t.height*s),o=Math.floor(t.width*s);t.height=Math.floor(t.height),t.width=Math.floor(t.width);const a=t.canvas;return a.style&&(i||!a.style.height&&!a.style.width)&&(a.style.height=`${t.height}px`,a.style.width=`${t.width}px`),(t.currentDevicePixelRatio!==s||a.height!==n||a.width!==o)&&(t.currentDevicePixelRatio=s,a.height=n,a.width=o,t.ctx.setTransform(s,0,0,s,0,0),!0)}const Se=function(){let t=!1;try{const e={get passive(){return t=!0,!1}};fe()&&(window.addEventListener("test",null,e),window.removeEventListener("test",null,e))}catch(t){}return t}();function Pe(t,e){const i=be(t,e),s=i&&i.match(/^(\d+)(\.\d+)?px$/);return s?+s[1]:void 0}function De(t){return!t||s(t.size)||s(t.family)?null:(t.style?t.style+" ":"")+(t.weight?t.weight+" ":"")+t.size+"px "+t.family}function Ce(t,e,i,s,n){let o=e[n];return o||(o=e[n]=t.measureText(n).width,i.push(n)),o>s&&(s=o),s}function Oe(t,e,i,s){let o=(s=s||{}).data=s.data||{},a=s.garbageCollect=s.garbageCollect||[];s.font!==e&&(o=s.data={},a=s.garbageCollect=[],s.font=e),t.save(),t.font=e;let r=0;const l=i.length;let h,c,d,u,f;for(h=0;hi.length){for(h=0;h0&&t.stroke()}}function Re(t,e,i){return i=i||.5,!e||t&&t.x>e.left-i&&t.xe.top-i&&t.y0&&""!==r.strokeColor;let c,d;for(t.save(),t.font=a.string,function(t,e){e.translation&&t.translate(e.translation[0],e.translation[1]),s(e.rotation)||t.rotate(e.rotation),e.color&&(t.fillStyle=e.color),e.textAlign&&(t.textAlign=e.textAlign),e.textBaseline&&(t.textBaseline=e.textBaseline)}(t,r),c=0;ct[0])){const o=i||t;void 0===s&&(s=ti("_fallback",t));const a={[Symbol.toStringTag]:"Object",_cacheable:!0,_scopes:t,_rootScopes:o,_fallback:s,_getTarget:n,override:i=>je([i,...t],e,o,s)};return new Proxy(a,{deleteProperty:(e,i)=>(delete e[i],delete e._keys,delete t[0][i],!0),get:(i,s)=>qe(i,s,(()=>function(t,e,i,s){let n;for(const o of e)if(n=ti(Ue(o,t),i),void 0!==n)return Xe(t,n)?Je(i,s,t,n):n}(s,e,t,i))),getOwnPropertyDescriptor:(t,e)=>Reflect.getOwnPropertyDescriptor(t._scopes[0],e),getPrototypeOf:()=>Reflect.getPrototypeOf(t[0]),has:(t,e)=>ei(t).includes(e),ownKeys:t=>ei(t),set(t,e,i){const s=t._storage||(t._storage=n());return t[e]=s[e]=i,delete t._keys,!0}})}function $e(t,e,i,s){const a={_cacheable:!1,_proxy:t,_context:e,_subProxy:i,_stack:new Set,_descriptors:Ye(t,s),setContext:e=>$e(t,e,i,s),override:n=>$e(t.override(n),e,i,s)};return new Proxy(a,{deleteProperty:(e,i)=>(delete e[i],delete t[i],!0),get:(t,e,i)=>qe(t,e,(()=>function(t,e,i){const{_proxy:s,_context:a,_subProxy:r,_descriptors:l}=t;let h=s[e];S(h)&&l.isScriptable(e)&&(h=function(t,e,i,s){const{_proxy:n,_context:o,_subProxy:a,_stack:r}=i;if(r.has(t))throw new Error("Recursion detected: "+Array.from(r).join("->")+"->"+t);r.add(t);let l=e(o,a||s);r.delete(t),Xe(t,l)&&(l=Je(n._scopes,n,t,l));return l}(e,h,t,i));n(h)&&h.length&&(h=function(t,e,i,s){const{_proxy:n,_context:a,_subProxy:r,_descriptors:l}=i;if(void 0!==a.index&&s(t))return e[a.index%e.length];if(o(e[0])){const i=e,s=n._scopes.filter((t=>t!==i));e=[];for(const o of i){const i=Je(s,n,t,o);e.push($e(i,a,r&&r[t],l))}}return e}(e,h,t,l.isIndexable));Xe(e,h)&&(h=$e(h,a,r&&r[e],l));return h}(t,e,i))),getOwnPropertyDescriptor:(e,i)=>e._descriptors.allKeys?Reflect.has(t,i)?{enumerable:!0,configurable:!0}:void 0:Reflect.getOwnPropertyDescriptor(t,i),getPrototypeOf:()=>Reflect.getPrototypeOf(t),has:(e,i)=>Reflect.has(t,i),ownKeys:()=>Reflect.ownKeys(t),set:(e,i,s)=>(t[i]=s,delete e[i],!0)})}function Ye(t,e={scriptable:!0,indexable:!0}){const{_scriptable:i=e.scriptable,_indexable:s=e.indexable,_allKeys:n=e.allKeys}=t;return{allKeys:n,scriptable:i,indexable:s,isScriptable:S(i)?i:()=>i,isIndexable:S(s)?s:()=>s}}const Ue=(t,e)=>t?t+w(e):e,Xe=(t,e)=>o(e)&&"adapters"!==t&&(null===Object.getPrototypeOf(e)||e.constructor===Object);function qe(t,e,i){if(Object.prototype.hasOwnProperty.call(t,e))return t[e];const s=i();return t[e]=s,s}function Ke(t,e,i){return S(t)?t(e,i):t}const Ge=(t,e)=>!0===t?e:"string"==typeof t?M(e,t):void 0;function Ze(t,e,i,s,n){for(const o of e){const e=Ge(i,o);if(e){t.add(e);const o=Ke(e._fallback,i,n);if(void 0!==o&&o!==i&&o!==s)return o}else if(!1===e&&void 0!==s&&i!==s)return null}return!1}function Je(t,e,i,s){const a=e._rootScopes,r=Ke(e._fallback,i,s),l=[...t,...a],h=new Set;h.add(s);let c=Qe(h,l,i,r||i,s);return null!==c&&((void 0===r||r===i||(c=Qe(h,l,r,c,s),null!==c))&&je(Array.from(h),[""],a,r,(()=>function(t,e,i){const s=t._getTarget();e in s||(s[e]={});const a=s[e];if(n(a)&&o(i))return i;return a||{}}(e,i,s))))}function Qe(t,e,i,s,n){for(;i;)i=Ze(t,e,i,s,n);return i}function ti(t,e){for(const i of e){if(!i)continue;const e=i[t];if(void 0!==e)return e}}function ei(t){let e=t._keys;return e||(e=t._keys=function(t){const e=new Set;for(const i of t)for(const t of Object.keys(i).filter((t=>!t.startsWith("_"))))e.add(t);return Array.from(e)}(t._scopes)),e}function ii(t,e,i,s){const{iScale:n}=t,{key:o="r"}=this._parsing,a=new Array(s);let r,l,h,c;for(r=0,l=s;re"x"===t?"y":"x";function ai(t,e,i,s){const n=t.skip?e:t,o=e,a=i.skip?e:i,r=q(o,n),l=q(a,o);let h=r/(r+l),c=l/(r+l);h=isNaN(h)?0:h,c=isNaN(c)?0:c;const d=s*h,u=s*c;return{previous:{x:o.x-d*(a.x-n.x),y:o.y-d*(a.y-n.y)},next:{x:o.x+u*(a.x-n.x),y:o.y+u*(a.y-n.y)}}}function ri(t,e="x"){const i=oi(e),s=t.length,n=Array(s).fill(0),o=Array(s);let a,r,l,h=ni(t,0);for(a=0;a!t.skip))),"monotone"===e.cubicInterpolationMode)ri(t,n);else{let i=s?t[t.length-1]:t[0];for(o=0,a=t.length;o0===t||1===t,di=(t,e,i)=>-Math.pow(2,10*(t-=1))*Math.sin((t-e)*O/i),ui=(t,e,i)=>Math.pow(2,-10*t)*Math.sin((t-e)*O/i)+1,fi={linear:t=>t,easeInQuad:t=>t*t,easeOutQuad:t=>-t*(t-2),easeInOutQuad:t=>(t/=.5)<1?.5*t*t:-.5*(--t*(t-2)-1),easeInCubic:t=>t*t*t,easeOutCubic:t=>(t-=1)*t*t+1,easeInOutCubic:t=>(t/=.5)<1?.5*t*t*t:.5*((t-=2)*t*t+2),easeInQuart:t=>t*t*t*t,easeOutQuart:t=>-((t-=1)*t*t*t-1),easeInOutQuart:t=>(t/=.5)<1?.5*t*t*t*t:-.5*((t-=2)*t*t*t-2),easeInQuint:t=>t*t*t*t*t,easeOutQuint:t=>(t-=1)*t*t*t*t+1,easeInOutQuint:t=>(t/=.5)<1?.5*t*t*t*t*t:.5*((t-=2)*t*t*t*t+2),easeInSine:t=>1-Math.cos(t*E),easeOutSine:t=>Math.sin(t*E),easeInOutSine:t=>-.5*(Math.cos(C*t)-1),easeInExpo:t=>0===t?0:Math.pow(2,10*(t-1)),easeOutExpo:t=>1===t?1:1-Math.pow(2,-10*t),easeInOutExpo:t=>ci(t)?t:t<.5?.5*Math.pow(2,10*(2*t-1)):.5*(2-Math.pow(2,-10*(2*t-1))),easeInCirc:t=>t>=1?t:-(Math.sqrt(1-t*t)-1),easeOutCirc:t=>Math.sqrt(1-(t-=1)*t),easeInOutCirc:t=>(t/=.5)<1?-.5*(Math.sqrt(1-t*t)-1):.5*(Math.sqrt(1-(t-=2)*t)+1),easeInElastic:t=>ci(t)?t:di(t,.075,.3),easeOutElastic:t=>ci(t)?t:ui(t,.075,.3),easeInOutElastic(t){const e=.1125;return ci(t)?t:t<.5?.5*di(2*t,e,.45):.5+.5*ui(2*t-1,e,.45)},easeInBack(t){const e=1.70158;return t*t*((e+1)*t-e)},easeOutBack(t){const e=1.70158;return(t-=1)*t*((e+1)*t+e)+1},easeInOutBack(t){let e=1.70158;return(t/=.5)<1?t*t*((1+(e*=1.525))*t-e)*.5:.5*((t-=2)*t*((1+(e*=1.525))*t+e)+2)},easeInBounce:t=>1-fi.easeOutBounce(1-t),easeOutBounce(t){const e=7.5625,i=2.75;return t<1/i?e*t*t:t<2/i?e*(t-=1.5/i)*t+.75:t<2.5/i?e*(t-=2.25/i)*t+.9375:e*(t-=2.625/i)*t+.984375},easeInOutBounce:t=>t<.5?.5*fi.easeInBounce(2*t):.5*fi.easeOutBounce(2*t-1)+.5};function gi(t,e,i,s){return{x:t.x+i*(e.x-t.x),y:t.y+i*(e.y-t.y)}}function pi(t,e,i,s){return{x:t.x+i*(e.x-t.x),y:"middle"===s?i<.5?t.y:e.y:"after"===s?i<1?t.y:e.y:i>0?e.y:t.y}}function mi(t,e,i,s){const n={x:t.cp2x,y:t.cp2y},o={x:e.cp1x,y:e.cp1y},a=gi(t,n,i),r=gi(n,o,i),l=gi(o,e,i),h=gi(a,r,i),c=gi(r,l,i);return gi(h,c,i)}const bi=/^(normal|(\d+(?:\.\d+)?)(px|em|%)?)$/,xi=/^(normal|italic|initial|inherit|unset|(oblique( -?[0-9]?[0-9]deg)?))$/;function _i(t,e){const i=(""+t).match(bi);if(!i||"normal"===i[1])return 1.2*e;switch(t=+i[2],i[3]){case"px":return t;case"%":t/=100}return e*t}const yi=t=>+t||0;function vi(t,e){const i={},s=o(e),n=s?Object.keys(e):e,a=o(t)?s?i=>l(t[i],t[e[i]]):e=>t[e]:()=>t;for(const t of n)i[t]=yi(a(t));return i}function Mi(t){return vi(t,{top:"y",right:"x",bottom:"y",left:"x"})}function wi(t){return vi(t,["topLeft","topRight","bottomLeft","bottomRight"])}function ki(t){const e=Mi(t);return e.width=e.left+e.right,e.height=e.top+e.bottom,e}function Si(t,e){t=t||{},e=e||ue.font;let i=l(t.size,e.size);"string"==typeof i&&(i=parseInt(i,10));let s=l(t.style,e.style);s&&!(""+s).match(xi)&&(console.warn('Invalid font style specified: "'+s+'"'),s=void 0);const n={family:l(t.family,e.family),lineHeight:_i(l(t.lineHeight,e.lineHeight),i),size:i,style:s,weight:l(t.weight,e.weight),string:""};return n.string=De(n),n}function Pi(t,e,i,s){let o,a,r,l=!0;for(o=0,a=t.length;oi&&0===t?0:t+e;return{min:a(s,-Math.abs(o)),max:a(n,o)}}function Ci(t,e){return Object.assign(Object.create(t),e)}function Oi(t,e,i){return t?function(t,e){return{x:i=>t+t+e-i,setWidth(t){e=t},textAlign:t=>"center"===t?t:"right"===t?"left":"right",xPlus:(t,e)=>t-e,leftForLtr:(t,e)=>t-e}}(e,i):{x:t=>t,setWidth(t){},textAlign:t=>t,xPlus:(t,e)=>t+e,leftForLtr:(t,e)=>t}}function Ai(t,e){let i,s;"ltr"!==e&&"rtl"!==e||(i=t.canvas.style,s=[i.getPropertyValue("direction"),i.getPropertyPriority("direction")],i.setProperty("direction",e,"important"),t.prevTextDirection=s)}function Ti(t,e){void 0!==e&&(delete t.prevTextDirection,t.canvas.style.setProperty("direction",e[0],e[1]))}function Li(t){return"angle"===t?{between:Z,compare:K,normalize:G}:{between:tt,compare:(t,e)=>t-e,normalize:t=>t}}function Ei({start:t,end:e,count:i,loop:s,style:n}){return{start:t%i,end:e%i,loop:s&&(e-t+1)%i==0,style:n}}function Ri(t,e,i){if(!i)return[t];const{property:s,start:n,end:o}=i,a=e.length,{compare:r,between:l,normalize:h}=Li(s),{start:c,end:d,loop:u,style:f}=function(t,e,i){const{property:s,start:n,end:o}=i,{between:a,normalize:r}=Li(s),l=e.length;let h,c,{start:d,end:u,loop:f}=t;if(f){for(d+=l,u+=l,h=0,c=l;hx||l(n,b,p)&&0!==r(n,b),v=()=>!x||0===r(o,p)||l(o,b,p);for(let t=c,i=c;t<=d;++t)m=e[t%a],m.skip||(p=h(m[s]),p!==b&&(x=l(p,n,o),null===_&&y()&&(_=0===r(p,n)?t:i),null!==_&&v()&&(g.push(Ei({start:_,end:t,loop:u,count:a,style:f})),_=null),i=t,b=p));return null!==_&&g.push(Ei({start:_,end:d,loop:u,count:a,style:f})),g}function Ii(t,e){const i=[],s=t.segments;for(let n=0;nn&&t[o%e].skip;)o--;return o%=e,{start:n,end:o}}(i,n,o,s);if(!0===s)return Fi(t,[{start:a,end:r,loop:o}],i,e);return Fi(t,function(t,e,i,s){const n=t.length,o=[];let a,r=e,l=t[e];for(a=e+1;a<=i;++a){const i=t[a%n];i.skip||i.stop?l.skip||(s=!1,o.push({start:e%n,end:(a-1)%n,loop:s}),e=r=i.stop?a:null):(r=a,l.skip&&(e=a)),l=i}return null!==r&&o.push({start:e%n,end:r%n,loop:s}),o}(i,a,r{t[a](e[i],n)&&(o.push({element:t,datasetIndex:s,index:l}),r=r||t.inRange(e.x,e.y,n))})),s&&!r?[]:o}var Xi={evaluateInteractionItems:Hi,modes:{index(t,e,i,s){const n=ve(e,t),o=i.axis||"x",a=i.includeInvisible||!1,r=i.intersect?ji(t,n,o,s,a):Yi(t,n,o,!1,s,a),l=[];return r.length?(t.getSortedVisibleDatasetMetas().forEach((t=>{const e=r[0].index,i=t.data[e];i&&!i.skip&&l.push({element:i,datasetIndex:t.index,index:e})})),l):[]},dataset(t,e,i,s){const n=ve(e,t),o=i.axis||"xy",a=i.includeInvisible||!1;let r=i.intersect?ji(t,n,o,s,a):Yi(t,n,o,!1,s,a);if(r.length>0){const e=r[0].datasetIndex,i=t.getDatasetMeta(e).data;r=[];for(let t=0;tji(t,ve(e,t),i.axis||"xy",s,i.includeInvisible||!1),nearest(t,e,i,s){const n=ve(e,t),o=i.axis||"xy",a=i.includeInvisible||!1;return Yi(t,n,o,i.intersect,s,a)},x:(t,e,i,s)=>Ui(t,ve(e,t),"x",i.intersect,s),y:(t,e,i,s)=>Ui(t,ve(e,t),"y",i.intersect,s)}};const qi=["left","top","right","bottom"];function Ki(t,e){return t.filter((t=>t.pos===e))}function Gi(t,e){return t.filter((t=>-1===qi.indexOf(t.pos)&&t.box.axis===e))}function Zi(t,e){return t.sort(((t,i)=>{const s=e?i:t,n=e?t:i;return s.weight===n.weight?s.index-n.index:s.weight-n.weight}))}function Ji(t,e){const i=function(t){const e={};for(const i of t){const{stack:t,pos:s,stackWeight:n}=i;if(!t||!qi.includes(s))continue;const o=e[t]||(e[t]={count:0,placed:0,weight:0,size:0});o.count++,o.weight+=n}return e}(t),{vBoxMaxWidth:s,hBoxMaxHeight:n}=e;let o,a,r;for(o=0,a=t.length;o{s[t]=Math.max(e[t],i[t])})),s}return s(t?["left","right"]:["top","bottom"])}function ss(t,e,i,s){const n=[];let o,a,r,l,h,c;for(o=0,a=t.length,h=0;ot.box.fullSize)),!0),s=Zi(Ki(e,"left"),!0),n=Zi(Ki(e,"right")),o=Zi(Ki(e,"top"),!0),a=Zi(Ki(e,"bottom")),r=Gi(e,"x"),l=Gi(e,"y");return{fullSize:i,leftAndTop:s.concat(o),rightAndBottom:n.concat(l).concat(a).concat(r),chartArea:Ki(e,"chartArea"),vertical:s.concat(n).concat(l),horizontal:o.concat(a).concat(r)}}(t.boxes),l=r.vertical,h=r.horizontal;u(t.boxes,(t=>{"function"==typeof t.beforeLayout&&t.beforeLayout()}));const c=l.reduce(((t,e)=>e.box.options&&!1===e.box.options.display?t:t+1),0)||1,d=Object.freeze({outerWidth:e,outerHeight:i,padding:n,availableWidth:o,availableHeight:a,vBoxMaxWidth:o/2/c,hBoxMaxHeight:a/2}),f=Object.assign({},n);ts(f,ki(s));const g=Object.assign({maxPadding:f,w:o,h:a,x:n.left,y:n.top},n),p=Ji(l.concat(h),d);ss(r.fullSize,g,d,p),ss(l,g,d,p),ss(h,g,d,p)&&ss(l,g,d,p),function(t){const e=t.maxPadding;function i(i){const s=Math.max(e[i]-t[i],0);return t[i]+=s,s}t.y+=i("top"),t.x+=i("left"),i("right"),i("bottom")}(g),os(r.leftAndTop,g,d,p),g.x+=g.w,g.y+=g.h,os(r.rightAndBottom,g,d,p),t.chartArea={left:g.left,top:g.top,right:g.left+g.w,bottom:g.top+g.h,height:g.h,width:g.w},u(r.chartArea,(e=>{const i=e.box;Object.assign(i,t.chartArea),i.update(g.w,g.h,{left:0,top:0,right:0,bottom:0})}))}};class rs{acquireContext(t,e){}releaseContext(t){return!1}addEventListener(t,e,i){}removeEventListener(t,e,i){}getDevicePixelRatio(){return 1}getMaximumSize(t,e,i,s){return e=Math.max(0,e||t.width),i=i||t.height,{width:e,height:Math.max(0,s?Math.floor(e/s):i)}}isAttached(t){return!0}updateConfig(t){}}class ls extends rs{acquireContext(t){return t&&t.getContext&&t.getContext("2d")||null}updateConfig(t){t.options.animation=!1}}const hs="$chartjs",cs={touchstart:"mousedown",touchmove:"mousemove",touchend:"mouseup",pointerenter:"mouseenter",pointerdown:"mousedown",pointermove:"mousemove",pointerup:"mouseup",pointerleave:"mouseout",pointerout:"mouseout"},ds=t=>null===t||""===t;const us=!!Se&&{passive:!0};function fs(t,e,i){t.canvas.removeEventListener(e,i,us)}function gs(t,e){for(const i of t)if(i===e||i.contains(e))return!0}function ps(t,e,i){const s=t.canvas,n=new MutationObserver((t=>{let e=!1;for(const i of t)e=e||gs(i.addedNodes,s),e=e&&!gs(i.removedNodes,s);e&&i()}));return n.observe(document,{childList:!0,subtree:!0}),n}function ms(t,e,i){const s=t.canvas,n=new MutationObserver((t=>{let e=!1;for(const i of t)e=e||gs(i.removedNodes,s),e=e&&!gs(i.addedNodes,s);e&&i()}));return n.observe(document,{childList:!0,subtree:!0}),n}const bs=new Map;let xs=0;function _s(){const t=window.devicePixelRatio;t!==xs&&(xs=t,bs.forEach(((e,i)=>{i.currentDevicePixelRatio!==t&&e()})))}function ys(t,e,i){const s=t.canvas,n=s&&ge(s);if(!n)return;const o=ct(((t,e)=>{const s=n.clientWidth;i(t,e),s{const e=t[0],i=e.contentRect.width,s=e.contentRect.height;0===i&&0===s||o(i,s)}));return a.observe(n),function(t,e){bs.size||window.addEventListener("resize",_s),bs.set(t,e)}(t,o),a}function vs(t,e,i){i&&i.disconnect(),"resize"===e&&function(t){bs.delete(t),bs.size||window.removeEventListener("resize",_s)}(t)}function Ms(t,e,i){const s=t.canvas,n=ct((e=>{null!==t.ctx&&i(function(t,e){const i=cs[t.type]||t.type,{x:s,y:n}=ve(t,e);return{type:i,chart:e,native:t,x:void 0!==s?s:null,y:void 0!==n?n:null}}(e,t))}),t);return function(t,e,i){t.addEventListener(e,i,us)}(s,e,n),n}class ws extends rs{acquireContext(t,e){const i=t&&t.getContext&&t.getContext("2d");return i&&i.canvas===t?(function(t,e){const i=t.style,s=t.getAttribute("height"),n=t.getAttribute("width");if(t[hs]={initial:{height:s,width:n,style:{display:i.display,height:i.height,width:i.width}}},i.display=i.display||"block",i.boxSizing=i.boxSizing||"border-box",ds(n)){const e=Pe(t,"width");void 0!==e&&(t.width=e)}if(ds(s))if(""===t.style.height)t.height=t.width/(e||2);else{const e=Pe(t,"height");void 0!==e&&(t.height=e)}}(t,e),i):null}releaseContext(t){const e=t.canvas;if(!e[hs])return!1;const i=e[hs].initial;["height","width"].forEach((t=>{const n=i[t];s(n)?e.removeAttribute(t):e.setAttribute(t,n)}));const n=i.style||{};return Object.keys(n).forEach((t=>{e.style[t]=n[t]})),e.width=e.width,delete e[hs],!0}addEventListener(t,e,i){this.removeEventListener(t,e);const s=t.$proxies||(t.$proxies={}),n={attach:ps,detach:ms,resize:ys}[e]||Ms;s[e]=n(t,e,i)}removeEventListener(t,e){const i=t.$proxies||(t.$proxies={}),s=i[e];if(!s)return;({attach:vs,detach:vs,resize:vs}[e]||fs)(t,e,s),i[e]=void 0}getDevicePixelRatio(){return window.devicePixelRatio}getMaximumSize(t,e,i,s){return we(t,e,i,s)}isAttached(t){const e=ge(t);return!(!e||!e.isConnected)}}function ks(t){return!fe()||"undefined"!=typeof OffscreenCanvas&&t instanceof OffscreenCanvas?ls:ws}var Ss=Object.freeze({__proto__:null,BasePlatform:rs,BasicPlatform:ls,DomPlatform:ws,_detectPlatform:ks});const Ps="transparent",Ds={boolean:(t,e,i)=>i>.5?e:t,color(t,e,i){const s=Qt(t||Ps),n=s.valid&&Qt(e||Ps);return n&&n.valid?n.mix(s,i).hexString():e},number:(t,e,i)=>t+(e-t)*i};class Cs{constructor(t,e,i,s){const n=e[i];s=Pi([t.to,s,n,t.from]);const o=Pi([t.from,n,s]);this._active=!0,this._fn=t.fn||Ds[t.type||typeof o],this._easing=fi[t.easing]||fi.linear,this._start=Math.floor(Date.now()+(t.delay||0)),this._duration=this._total=Math.floor(t.duration),this._loop=!!t.loop,this._target=e,this._prop=i,this._from=o,this._to=s,this._promises=void 0}active(){return this._active}update(t,e,i){if(this._active){this._notify(!1);const s=this._target[this._prop],n=i-this._start,o=this._duration-n;this._start=i,this._duration=Math.floor(Math.max(o,t.duration)),this._total+=n,this._loop=!!t.loop,this._to=Pi([t.to,e,s,t.from]),this._from=Pi([t.from,s,e])}}cancel(){this._active&&(this.tick(Date.now()),this._active=!1,this._notify(!1))}tick(t){const e=t-this._start,i=this._duration,s=this._prop,n=this._from,o=this._loop,a=this._to;let r;if(this._active=n!==a&&(o||e1?2-r:r,r=this._easing(Math.min(1,Math.max(0,r))),this._target[s]=this._fn(n,a,r))}wait(){const t=this._promises||(this._promises=[]);return new Promise(((e,i)=>{t.push({res:e,rej:i})}))}_notify(t){const e=t?"res":"rej",i=this._promises||[];for(let t=0;t{const a=t[s];if(!o(a))return;const r={};for(const t of e)r[t]=a[t];(n(a.properties)&&a.properties||[s]).forEach((t=>{t!==s&&i.has(t)||i.set(t,r)}))}))}_animateOptions(t,e){const i=e.options,s=function(t,e){if(!e)return;let i=t.options;if(!i)return void(t.options=e);i.$shared&&(t.options=i=Object.assign({},i,{$shared:!1,$animations:{}}));return i}(t,i);if(!s)return[];const n=this._createAnimations(s,i);return i.$shared&&function(t,e){const i=[],s=Object.keys(e);for(let e=0;e{t.options=i}),(()=>{})),n}_createAnimations(t,e){const i=this._properties,s=[],n=t.$animations||(t.$animations={}),o=Object.keys(e),a=Date.now();let r;for(r=o.length-1;r>=0;--r){const l=o[r];if("$"===l.charAt(0))continue;if("options"===l){s.push(...this._animateOptions(t,e));continue}const h=e[l];let c=n[l];const d=i.get(l);if(c){if(d&&c.active()){c.update(d,h,a);continue}c.cancel()}d&&d.duration?(n[l]=c=new Cs(d,t,l,h),s.push(c)):t[l]=h}return s}update(t,e){if(0===this._properties.size)return void Object.assign(t,e);const i=this._createAnimations(t,e);return i.length?(xt.add(this._chart,i),!0):void 0}}function As(t,e){const i=t&&t.options||{},s=i.reverse,n=void 0===i.min?e:0,o=void 0===i.max?e:0;return{start:s?o:n,end:s?n:o}}function Ts(t,e){const i=[],s=t._getSortedDatasetMetas(e);let n,o;for(n=0,o=s.length;n0||!i&&e<0)return n.index}return null}function zs(t,e){const{chart:i,_cachedMeta:s}=t,n=i._stacks||(i._stacks={}),{iScale:o,vScale:a,index:r}=s,l=o.axis,h=a.axis,c=function(t,e,i){return`${t.id}.${e.id}.${i.stack||i.type}`}(o,a,s),d=e.length;let u;for(let t=0;ti[t].axis===e)).shift()}function Vs(t,e){const i=t.controller.index,s=t.vScale&&t.vScale.axis;if(s){e=e||t._parsed;for(const t of e){const e=t._stacks;if(!e||void 0===e[s]||void 0===e[s][i])return;delete e[s][i],void 0!==e[s]._visualValues&&void 0!==e[s]._visualValues[i]&&delete e[s]._visualValues[i]}}}const Bs=t=>"reset"===t||"none"===t,Ws=(t,e)=>e?t:Object.assign({},t);class Ns{static defaults={};static datasetElementType=null;static dataElementType=null;constructor(t,e){this.chart=t,this._ctx=t.ctx,this.index=e,this._cachedDataOpts={},this._cachedMeta=this.getMeta(),this._type=this._cachedMeta.type,this.options=void 0,this._parsing=!1,this._data=void 0,this._objectData=void 0,this._sharedOptions=void 0,this._drawStart=void 0,this._drawCount=void 0,this.enableOptionSharing=!1,this.supportsDecimation=!1,this.$context=void 0,this._syncList=[],this.datasetElementType=new.target.datasetElementType,this.dataElementType=new.target.dataElementType,this.initialize()}initialize(){const t=this._cachedMeta;this.configure(),this.linkScales(),t._stacked=Es(t.vScale,t),this.addElements(),this.options.fill&&!this.chart.isPluginEnabled("filler")&&console.warn("Tried to use the 'fill' option without the 'Filler' plugin enabled. Please import and register the 'Filler' plugin and make sure it is not disabled in the options")}updateIndex(t){this.index!==t&&Vs(this._cachedMeta),this.index=t}linkScales(){const t=this.chart,e=this._cachedMeta,i=this.getDataset(),s=(t,e,i,s)=>"x"===t?e:"r"===t?s:i,n=e.xAxisID=l(i.xAxisID,Fs(t,"x")),o=e.yAxisID=l(i.yAxisID,Fs(t,"y")),a=e.rAxisID=l(i.rAxisID,Fs(t,"r")),r=e.indexAxis,h=e.iAxisID=s(r,n,o,a),c=e.vAxisID=s(r,o,n,a);e.xScale=this.getScaleForId(n),e.yScale=this.getScaleForId(o),e.rScale=this.getScaleForId(a),e.iScale=this.getScaleForId(h),e.vScale=this.getScaleForId(c)}getDataset(){return this.chart.data.datasets[this.index]}getMeta(){return this.chart.getDatasetMeta(this.index)}getScaleForId(t){return this.chart.scales[t]}_getOtherScale(t){const e=this._cachedMeta;return t===e.iScale?e.vScale:e.iScale}reset(){this._update("reset")}_destroy(){const t=this._cachedMeta;this._data&&rt(this._data,this),t._stacked&&Vs(t)}_dataCheck(){const t=this.getDataset(),e=t.data||(t.data=[]),i=this._data;if(o(e))this._data=function(t){const e=Object.keys(t),i=new Array(e.length);let s,n,o;for(s=0,n=e.length;s0&&i._parsed[t-1];if(!1===this._parsing)i._parsed=s,i._sorted=!0,d=s;else{d=n(s[t])?this.parseArrayData(i,s,t,e):o(s[t])?this.parseObjectData(i,s,t,e):this.parsePrimitiveData(i,s,t,e);const a=()=>null===c[l]||f&&c[l]t&&!e.hidden&&e._stacked&&{keys:Ts(i,!0),values:null})(e,i,this.chart),h={min:Number.POSITIVE_INFINITY,max:Number.NEGATIVE_INFINITY},{min:c,max:d}=function(t){const{min:e,max:i,minDefined:s,maxDefined:n}=t.getUserBounds();return{min:s?e:Number.NEGATIVE_INFINITY,max:n?i:Number.POSITIVE_INFINITY}}(r);let u,f;function g(){f=s[u];const e=f[r.axis];return!a(f[t.axis])||c>e||d=0;--u)if(!g()){this.updateRangeFromParsed(h,t,f,l);break}return h}getAllParsedValues(t){const e=this._cachedMeta._parsed,i=[];let s,n,o;for(s=0,n=e.length;s=0&&tthis.getContext(i,s,e)),c);return f.$shared&&(f.$shared=r,n[o]=Object.freeze(Ws(f,r))),f}_resolveAnimations(t,e,i){const s=this.chart,n=this._cachedDataOpts,o=`animation-${e}`,a=n[o];if(a)return a;let r;if(!1!==s.options.animation){const s=this.chart.config,n=s.datasetAnimationScopeKeys(this._type,e),o=s.getOptionScopes(this.getDataset(),n);r=s.createResolver(o,this.getContext(t,i,e))}const l=new Os(s,r&&r.animations);return r&&r._cacheable&&(n[o]=Object.freeze(l)),l}getSharedOptions(t){if(t.$shared)return this._sharedOptions||(this._sharedOptions=Object.assign({},t))}includeOptions(t,e){return!e||Bs(t)||this.chart._animationsDisabled}_getSharedOptions(t,e){const i=this.resolveDataElementOptions(t,e),s=this._sharedOptions,n=this.getSharedOptions(i),o=this.includeOptions(e,n)||n!==s;return this.updateSharedOptions(n,e,i),{sharedOptions:n,includeOptions:o}}updateElement(t,e,i,s){Bs(s)?Object.assign(t,i):this._resolveAnimations(e,s).update(t,i)}updateSharedOptions(t,e,i){t&&!Bs(e)&&this._resolveAnimations(void 0,e).update(t,i)}_setStyle(t,e,i,s){t.active=s;const n=this.getStyle(e,s);this._resolveAnimations(e,i,s).update(t,{options:!s&&this.getSharedOptions(n)||n})}removeHoverStyle(t,e,i){this._setStyle(t,i,"active",!1)}setHoverStyle(t,e,i){this._setStyle(t,i,"active",!0)}_removeDatasetHoverStyle(){const t=this._cachedMeta.dataset;t&&this._setStyle(t,void 0,"active",!1)}_setDatasetHoverStyle(){const t=this._cachedMeta.dataset;t&&this._setStyle(t,void 0,"active",!0)}_resyncElements(t){const e=this._data,i=this._cachedMeta.data;for(const[t,e,i]of this._syncList)this[t](e,i);this._syncList=[];const s=i.length,n=e.length,o=Math.min(n,s);o&&this.parse(0,o),n>s?this._insertElements(s,n-s,t):n{for(t.length+=e,a=t.length-1;a>=o;a--)t[a]=t[a-e]};for(r(n),a=t;a{s[t]=i[t]&&i[t].active()?i[t]._to:this[t]})),s}}function js(t,e){const i=t.options.ticks,n=function(t){const e=t.options.offset,i=t._tickSize(),s=t._length/i+(e?0:1),n=t._maxLength/i;return Math.floor(Math.min(s,n))}(t),o=Math.min(i.maxTicksLimit||n,n),a=i.major.enabled?function(t){const e=[];let i,s;for(i=0,s=t.length;io)return function(t,e,i,s){let n,o=0,a=i[0];for(s=Math.ceil(s),n=0;nn)return e}return Math.max(n,1)}(a,e,o);if(r>0){let t,i;const n=r>1?Math.round((h-l)/(r-1)):null;for($s(e,c,d,s(n)?0:l-n,l),t=0,i=r-1;t"top"===e||"left"===e?t[e]+i:t[e]-i,Us=(t,e)=>Math.min(e||t,t);function Xs(t,e){const i=[],s=t.length/e,n=t.length;let o=0;for(;oa+r)))return h}function Ks(t){return t.drawTicks?t.tickLength:0}function Gs(t,e){if(!t.display)return 0;const i=Si(t.font,e),s=ki(t.padding);return(n(t.text)?t.text.length:1)*i.lineHeight+s.height}function Zs(t,e,i){let s=ut(t);return(i&&"right"!==e||!i&&"right"===e)&&(s=(t=>"left"===t?"right":"right"===t?"left":t)(s)),s}class Js extends Hs{constructor(t){super(),this.id=t.id,this.type=t.type,this.options=void 0,this.ctx=t.ctx,this.chart=t.chart,this.top=void 0,this.bottom=void 0,this.left=void 0,this.right=void 0,this.width=void 0,this.height=void 0,this._margins={left:0,right:0,top:0,bottom:0},this.maxWidth=void 0,this.maxHeight=void 0,this.paddingTop=void 0,this.paddingBottom=void 0,this.paddingLeft=void 0,this.paddingRight=void 0,this.axis=void 0,this.labelRotation=void 0,this.min=void 0,this.max=void 0,this._range=void 0,this.ticks=[],this._gridLineItems=null,this._labelItems=null,this._labelSizes=null,this._length=0,this._maxLength=0,this._longestTextCache={},this._startPixel=void 0,this._endPixel=void 0,this._reversePixels=!1,this._userMax=void 0,this._userMin=void 0,this._suggestedMax=void 0,this._suggestedMin=void 0,this._ticksLength=0,this._borderValue=0,this._cache={},this._dataLimitsCached=!1,this.$context=void 0}init(t){this.options=t.setContext(this.getContext()),this.axis=t.axis,this._userMin=this.parse(t.min),this._userMax=this.parse(t.max),this._suggestedMin=this.parse(t.suggestedMin),this._suggestedMax=this.parse(t.suggestedMax)}parse(t,e){return t}getUserBounds(){let{_userMin:t,_userMax:e,_suggestedMin:i,_suggestedMax:s}=this;return t=r(t,Number.POSITIVE_INFINITY),e=r(e,Number.NEGATIVE_INFINITY),i=r(i,Number.POSITIVE_INFINITY),s=r(s,Number.NEGATIVE_INFINITY),{min:r(t,i),max:r(e,s),minDefined:a(t),maxDefined:a(e)}}getMinMax(t){let e,{min:i,max:s,minDefined:n,maxDefined:o}=this.getUserBounds();if(n&&o)return{min:i,max:s};const a=this.getMatchingVisibleMetas();for(let r=0,l=a.length;rs?s:i,s=n&&i>s?i:s,{min:r(i,r(s,i)),max:r(s,r(i,s))}}getPadding(){return{left:this.paddingLeft||0,top:this.paddingTop||0,right:this.paddingRight||0,bottom:this.paddingBottom||0}}getTicks(){return this.ticks}getLabels(){const t=this.chart.data;return this.options.labels||(this.isHorizontal()?t.xLabels:t.yLabels)||t.labels||[]}getLabelItems(t=this.chart.chartArea){return this._labelItems||(this._labelItems=this._computeLabelItems(t))}beforeLayout(){this._cache={},this._dataLimitsCached=!1}beforeUpdate(){d(this.options.beforeUpdate,[this])}update(t,e,i){const{beginAtZero:s,grace:n,ticks:o}=this.options,a=o.sampleSize;this.beforeUpdate(),this.maxWidth=t,this.maxHeight=e,this._margins=i=Object.assign({left:0,right:0,top:0,bottom:0},i),this.ticks=null,this._labelSizes=null,this._gridLineItems=null,this._labelItems=null,this.beforeSetDimensions(),this.setDimensions(),this.afterSetDimensions(),this._maxLength=this.isHorizontal()?this.width+i.left+i.right:this.height+i.top+i.bottom,this._dataLimitsCached||(this.beforeDataLimits(),this.determineDataLimits(),this.afterDataLimits(),this._range=Di(this,n,s),this._dataLimitsCached=!0),this.beforeBuildTicks(),this.ticks=this.buildTicks()||[],this.afterBuildTicks();const r=a=n||i<=1||!this.isHorizontal())return void(this.labelRotation=s);const h=this._getLabelSizes(),c=h.widest.width,d=h.highest.height,u=J(this.chart.width-c,0,this.maxWidth);o=t.offset?this.maxWidth/i:u/(i-1),c+6>o&&(o=u/(i-(t.offset?.5:1)),a=this.maxHeight-Ks(t.grid)-e.padding-Gs(t.title,this.chart.options.font),r=Math.sqrt(c*c+d*d),l=Y(Math.min(Math.asin(J((h.highest.height+6)/o,-1,1)),Math.asin(J(a/r,-1,1))-Math.asin(J(d/r,-1,1)))),l=Math.max(s,Math.min(n,l))),this.labelRotation=l}afterCalculateLabelRotation(){d(this.options.afterCalculateLabelRotation,[this])}afterAutoSkip(){}beforeFit(){d(this.options.beforeFit,[this])}fit(){const t={width:0,height:0},{chart:e,options:{ticks:i,title:s,grid:n}}=this,o=this._isVisible(),a=this.isHorizontal();if(o){const o=Gs(s,e.options.font);if(a?(t.width=this.maxWidth,t.height=Ks(n)+o):(t.height=this.maxHeight,t.width=Ks(n)+o),i.display&&this.ticks.length){const{first:e,last:s,widest:n,highest:o}=this._getLabelSizes(),r=2*i.padding,l=$(this.labelRotation),h=Math.cos(l),c=Math.sin(l);if(a){const e=i.mirror?0:c*n.width+h*o.height;t.height=Math.min(this.maxHeight,t.height+e+r)}else{const e=i.mirror?0:h*n.width+c*o.height;t.width=Math.min(this.maxWidth,t.width+e+r)}this._calculatePadding(e,s,c,h)}}this._handleMargins(),a?(this.width=this._length=e.width-this._margins.left-this._margins.right,this.height=t.height):(this.width=t.width,this.height=this._length=e.height-this._margins.top-this._margins.bottom)}_calculatePadding(t,e,i,s){const{ticks:{align:n,padding:o},position:a}=this.options,r=0!==this.labelRotation,l="top"!==a&&"x"===this.axis;if(this.isHorizontal()){const a=this.getPixelForTick(0)-this.left,h=this.right-this.getPixelForTick(this.ticks.length-1);let c=0,d=0;r?l?(c=s*t.width,d=i*e.height):(c=i*t.height,d=s*e.width):"start"===n?d=e.width:"end"===n?c=t.width:"inner"!==n&&(c=t.width/2,d=e.width/2),this.paddingLeft=Math.max((c-a+o)*this.width/(this.width-a),0),this.paddingRight=Math.max((d-h+o)*this.width/(this.width-h),0)}else{let i=e.height/2,s=t.height/2;"start"===n?(i=0,s=t.height):"end"===n&&(i=e.height,s=0),this.paddingTop=i+o,this.paddingBottom=s+o}}_handleMargins(){this._margins&&(this._margins.left=Math.max(this.paddingLeft,this._margins.left),this._margins.top=Math.max(this.paddingTop,this._margins.top),this._margins.right=Math.max(this.paddingRight,this._margins.right),this._margins.bottom=Math.max(this.paddingBottom,this._margins.bottom))}afterFit(){d(this.options.afterFit,[this])}isHorizontal(){const{axis:t,position:e}=this.options;return"top"===e||"bottom"===e||"x"===t}isFullSize(){return this.options.fullSize}_convertTicksToLabels(t){let e,i;for(this.beforeTickToLabelConversion(),this.generateTickLabels(t),e=0,i=t.length;e{const i=t.gc,s=i.length/2;let n;if(s>e){for(n=0;n({width:r[t]||0,height:l[t]||0});return{first:P(0),last:P(e-1),widest:P(k),highest:P(S),widths:r,heights:l}}getLabelForValue(t){return t}getPixelForValue(t,e){return NaN}getValueForPixel(t){}getPixelForTick(t){const e=this.ticks;return t<0||t>e.length-1?null:this.getPixelForValue(e[t].value)}getPixelForDecimal(t){this._reversePixels&&(t=1-t);const e=this._startPixel+t*this._length;return Q(this._alignToPixels?Ae(this.chart,e,0):e)}getDecimalForPixel(t){const e=(t-this._startPixel)/this._length;return this._reversePixels?1-e:e}getBasePixel(){return this.getPixelForValue(this.getBaseValue())}getBaseValue(){const{min:t,max:e}=this;return t<0&&e<0?e:t>0&&e>0?t:0}getContext(t){const e=this.ticks||[];if(t>=0&&ta*s?a/i:r/s:r*s0}_computeGridLineItems(t){const e=this.axis,i=this.chart,s=this.options,{grid:n,position:a,border:r}=s,h=n.offset,c=this.isHorizontal(),d=this.ticks.length+(h?1:0),u=Ks(n),f=[],g=r.setContext(this.getContext()),p=g.display?g.width:0,m=p/2,b=function(t){return Ae(i,t,p)};let x,_,y,v,M,w,k,S,P,D,C,O;if("top"===a)x=b(this.bottom),w=this.bottom-u,S=x-m,D=b(t.top)+m,O=t.bottom;else if("bottom"===a)x=b(this.top),D=t.top,O=b(t.bottom)-m,w=x+m,S=this.top+u;else if("left"===a)x=b(this.right),M=this.right-u,k=x-m,P=b(t.left)+m,C=t.right;else if("right"===a)x=b(this.left),P=t.left,C=b(t.right)-m,M=x+m,k=this.left+u;else if("x"===e){if("center"===a)x=b((t.top+t.bottom)/2+.5);else if(o(a)){const t=Object.keys(a)[0],e=a[t];x=b(this.chart.scales[t].getPixelForValue(e))}D=t.top,O=t.bottom,w=x+m,S=w+u}else if("y"===e){if("center"===a)x=b((t.left+t.right)/2);else if(o(a)){const t=Object.keys(a)[0],e=a[t];x=b(this.chart.scales[t].getPixelForValue(e))}M=x-m,k=M-u,P=t.left,C=t.right}const A=l(s.ticks.maxTicksLimit,d),T=Math.max(1,Math.ceil(d/A));for(_=0;_0&&(o-=s/2)}d={left:o,top:n,width:s+e.width,height:i+e.height,color:t.backdropColor}}b.push({label:v,font:P,textOffset:O,options:{rotation:m,color:i,strokeColor:o,strokeWidth:h,textAlign:f,textBaseline:A,translation:[M,w],backdrop:d}})}return b}_getXAxisLabelAlignment(){const{position:t,ticks:e}=this.options;if(-$(this.labelRotation))return"top"===t?"left":"right";let i="center";return"start"===e.align?i="left":"end"===e.align?i="right":"inner"===e.align&&(i="inner"),i}_getYAxisLabelAlignment(t){const{position:e,ticks:{crossAlign:i,mirror:s,padding:n}}=this.options,o=t+n,a=this._getLabelSizes().widest.width;let r,l;return"left"===e?s?(l=this.right+n,"near"===i?r="left":"center"===i?(r="center",l+=a/2):(r="right",l+=a)):(l=this.right-o,"near"===i?r="right":"center"===i?(r="center",l-=a/2):(r="left",l=this.left)):"right"===e?s?(l=this.left+n,"near"===i?r="right":"center"===i?(r="center",l-=a/2):(r="left",l-=a)):(l=this.left+o,"near"===i?r="left":"center"===i?(r="center",l+=a/2):(r="right",l=this.right)):r="right",{textAlign:r,x:l}}_computeLabelArea(){if(this.options.ticks.mirror)return;const t=this.chart,e=this.options.position;return"left"===e||"right"===e?{top:0,left:this.left,bottom:t.height,right:this.right}:"top"===e||"bottom"===e?{top:this.top,left:0,bottom:this.bottom,right:t.width}:void 0}drawBackground(){const{ctx:t,options:{backgroundColor:e},left:i,top:s,width:n,height:o}=this;e&&(t.save(),t.fillStyle=e,t.fillRect(i,s,n,o),t.restore())}getLineWidthForValue(t){const e=this.options.grid;if(!this._isVisible()||!e.display)return 0;const i=this.ticks.findIndex((e=>e.value===t));if(i>=0){return e.setContext(this.getContext(i)).lineWidth}return 0}drawGrid(t){const e=this.options.grid,i=this.ctx,s=this._gridLineItems||(this._gridLineItems=this._computeGridLineItems(t));let n,o;const a=(t,e,s)=>{s.width&&s.color&&(i.save(),i.lineWidth=s.width,i.strokeStyle=s.color,i.setLineDash(s.borderDash||[]),i.lineDashOffset=s.borderDashOffset,i.beginPath(),i.moveTo(t.x,t.y),i.lineTo(e.x,e.y),i.stroke(),i.restore())};if(e.display)for(n=0,o=s.length;n{this.drawBackground(),this.drawGrid(t),this.drawTitle()}},{z:s,draw:()=>{this.drawBorder()}},{z:e,draw:t=>{this.drawLabels(t)}}]:[{z:e,draw:t=>{this.draw(t)}}]}getMatchingVisibleMetas(t){const e=this.chart.getSortedVisibleDatasetMetas(),i=this.axis+"AxisID",s=[];let n,o;for(n=0,o=e.length;n{const s=i.split("."),n=s.pop(),o=[t].concat(s).join("."),a=e[i].split("."),r=a.pop(),l=a.join(".");ue.route(o,n,l,r)}))}(e,t.defaultRoutes);t.descriptors&&ue.describe(e,t.descriptors)}(t,o,i),this.override&&ue.override(t.id,t.overrides)),o}get(t){return this.items[t]}unregister(t){const e=this.items,i=t.id,s=this.scope;i in e&&delete e[i],s&&i in ue[s]&&(delete ue[s][i],this.override&&delete re[i])}}class tn{constructor(){this.controllers=new Qs(Ns,"datasets",!0),this.elements=new Qs(Hs,"elements"),this.plugins=new Qs(Object,"plugins"),this.scales=new Qs(Js,"scales"),this._typedRegistries=[this.controllers,this.scales,this.elements]}add(...t){this._each("register",t)}remove(...t){this._each("unregister",t)}addControllers(...t){this._each("register",t,this.controllers)}addElements(...t){this._each("register",t,this.elements)}addPlugins(...t){this._each("register",t,this.plugins)}addScales(...t){this._each("register",t,this.scales)}getController(t){return this._get(t,this.controllers,"controller")}getElement(t){return this._get(t,this.elements,"element")}getPlugin(t){return this._get(t,this.plugins,"plugin")}getScale(t){return this._get(t,this.scales,"scale")}removeControllers(...t){this._each("unregister",t,this.controllers)}removeElements(...t){this._each("unregister",t,this.elements)}removePlugins(...t){this._each("unregister",t,this.plugins)}removeScales(...t){this._each("unregister",t,this.scales)}_each(t,e,i){[...e].forEach((e=>{const s=i||this._getRegistryForType(e);i||s.isForType(e)||s===this.plugins&&e.id?this._exec(t,s,e):u(e,(e=>{const s=i||this._getRegistryForType(e);this._exec(t,s,e)}))}))}_exec(t,e,i){const s=w(t);d(i["before"+s],[],i),e[t](i),d(i["after"+s],[],i)}_getRegistryForType(t){for(let e=0;et.filter((t=>!e.some((e=>t.plugin.id===e.plugin.id))));this._notify(s(e,i),t,"stop"),this._notify(s(i,e),t,"start")}}function nn(t,e){return e||!1!==t?!0===t?{}:t:null}function on(t,{plugin:e,local:i},s,n){const o=t.pluginScopeKeys(e),a=t.getOptionScopes(s,o);return i&&e.defaults&&a.push(e.defaults),t.createResolver(a,n,[""],{scriptable:!1,indexable:!1,allKeys:!0})}function an(t,e){const i=ue.datasets[t]||{};return((e.datasets||{})[t]||{}).indexAxis||e.indexAxis||i.indexAxis||"x"}function rn(t){if("x"===t||"y"===t||"r"===t)return t}function ln(t,...e){if(rn(t))return t;for(const s of e){const e=s.axis||("top"===(i=s.position)||"bottom"===i?"x":"left"===i||"right"===i?"y":void 0)||t.length>1&&rn(t[0].toLowerCase());if(e)return e}var i;throw new Error(`Cannot determine type of '${t}' axis. Please provide 'axis' or 'position' option.`)}function hn(t,e,i){if(i[e+"AxisID"]===t)return{axis:e}}function cn(t,e){const i=re[t.type]||{scales:{}},s=e.scales||{},n=an(t.type,e),a=Object.create(null);return Object.keys(s).forEach((e=>{const r=s[e];if(!o(r))return console.error(`Invalid scale configuration for scale: ${e}`);if(r._proxy)return console.warn(`Ignoring resolver passed as options for scale: ${e}`);const l=ln(e,r,function(t,e){if(e.data&&e.data.datasets){const i=e.data.datasets.filter((e=>e.xAxisID===t||e.yAxisID===t));if(i.length)return hn(t,"x",i[0])||hn(t,"y",i[0])}return{}}(e,t),ue.scales[r.type]),h=function(t,e){return t===e?"_index_":"_value_"}(l,n),c=i.scales||{};a[e]=x(Object.create(null),[{axis:l},r,c[l],c[h]])})),t.data.datasets.forEach((i=>{const n=i.type||t.type,o=i.indexAxis||an(n,e),r=(re[n]||{}).scales||{};Object.keys(r).forEach((t=>{const e=function(t,e){let i=t;return"_index_"===t?i=e:"_value_"===t&&(i="x"===e?"y":"x"),i}(t,o),n=i[e+"AxisID"]||e;a[n]=a[n]||Object.create(null),x(a[n],[{axis:e},s[n],r[t]])}))})),Object.keys(a).forEach((t=>{const e=a[t];x(e,[ue.scales[e.type],ue.scale])})),a}function dn(t){const e=t.options||(t.options={});e.plugins=l(e.plugins,{}),e.scales=cn(t,e)}function un(t){return(t=t||{}).datasets=t.datasets||[],t.labels=t.labels||[],t}const fn=new Map,gn=new Set;function pn(t,e){let i=fn.get(t);return i||(i=e(),fn.set(t,i),gn.add(i)),i}const mn=(t,e,i)=>{const s=M(e,i);void 0!==s&&t.add(s)};class bn{constructor(t){this._config=function(t){return(t=t||{}).data=un(t.data),dn(t),t}(t),this._scopeCache=new Map,this._resolverCache=new Map}get platform(){return this._config.platform}get type(){return this._config.type}set type(t){this._config.type=t}get data(){return this._config.data}set data(t){this._config.data=un(t)}get options(){return this._config.options}set options(t){this._config.options=t}get plugins(){return this._config.plugins}update(){const t=this._config;this.clearCache(),dn(t)}clearCache(){this._scopeCache.clear(),this._resolverCache.clear()}datasetScopeKeys(t){return pn(t,(()=>[[`datasets.${t}`,""]]))}datasetAnimationScopeKeys(t,e){return pn(`${t}.transition.${e}`,(()=>[[`datasets.${t}.transitions.${e}`,`transitions.${e}`],[`datasets.${t}`,""]]))}datasetElementScopeKeys(t,e){return pn(`${t}-${e}`,(()=>[[`datasets.${t}.elements.${e}`,`datasets.${t}`,`elements.${e}`,""]]))}pluginScopeKeys(t){const e=t.id;return pn(`${this.type}-plugin-${e}`,(()=>[[`plugins.${e}`,...t.additionalOptionScopes||[]]]))}_cachedScopes(t,e){const i=this._scopeCache;let s=i.get(t);return s&&!e||(s=new Map,i.set(t,s)),s}getOptionScopes(t,e,i){const{options:s,type:n}=this,o=this._cachedScopes(t,i),a=o.get(e);if(a)return a;const r=new Set;e.forEach((e=>{t&&(r.add(t),e.forEach((e=>mn(r,t,e)))),e.forEach((t=>mn(r,s,t))),e.forEach((t=>mn(r,re[n]||{},t))),e.forEach((t=>mn(r,ue,t))),e.forEach((t=>mn(r,le,t)))}));const l=Array.from(r);return 0===l.length&&l.push(Object.create(null)),gn.has(e)&&o.set(e,l),l}chartOptionScopes(){const{options:t,type:e}=this;return[t,re[e]||{},ue.datasets[e]||{},{type:e},ue,le]}resolveNamedOptions(t,e,i,s=[""]){const o={$shared:!0},{resolver:a,subPrefixes:r}=xn(this._resolverCache,t,s);let l=a;if(function(t,e){const{isScriptable:i,isIndexable:s}=Ye(t);for(const o of e){const e=i(o),a=s(o),r=(a||e)&&t[o];if(e&&(S(r)||_n(r))||a&&n(r))return!0}return!1}(a,e)){o.$shared=!1;l=$e(a,i=S(i)?i():i,this.createResolver(t,i,r))}for(const t of e)o[t]=l[t];return o}createResolver(t,e,i=[""],s){const{resolver:n}=xn(this._resolverCache,t,i);return o(e)?$e(n,e,void 0,s):n}}function xn(t,e,i){let s=t.get(e);s||(s=new Map,t.set(e,s));const n=i.join();let o=s.get(n);if(!o){o={resolver:je(e,i),subPrefixes:i.filter((t=>!t.toLowerCase().includes("hover")))},s.set(n,o)}return o}const _n=t=>o(t)&&Object.getOwnPropertyNames(t).some((e=>S(t[e])));const yn=["top","bottom","left","right","chartArea"];function vn(t,e){return"top"===t||"bottom"===t||-1===yn.indexOf(t)&&"x"===e}function Mn(t,e){return function(i,s){return i[t]===s[t]?i[e]-s[e]:i[t]-s[t]}}function wn(t){const e=t.chart,i=e.options.animation;e.notifyPlugins("afterRender"),d(i&&i.onComplete,[t],e)}function kn(t){const e=t.chart,i=e.options.animation;d(i&&i.onProgress,[t],e)}function Sn(t){return fe()&&"string"==typeof t?t=document.getElementById(t):t&&t.length&&(t=t[0]),t&&t.canvas&&(t=t.canvas),t}const Pn={},Dn=t=>{const e=Sn(t);return Object.values(Pn).filter((t=>t.canvas===e)).pop()};function Cn(t,e,i){const s=Object.keys(t);for(const n of s){const s=+n;if(s>=e){const o=t[n];delete t[n],(i>0||s>e)&&(t[s+i]=o)}}}function On(t,e,i){return t.options.clip?t[i]:e[i]}class An{static defaults=ue;static instances=Pn;static overrides=re;static registry=en;static version="4.4.1";static getChart=Dn;static register(...t){en.add(...t),Tn()}static unregister(...t){en.remove(...t),Tn()}constructor(t,e){const s=this.config=new bn(e),n=Sn(t),o=Dn(n);if(o)throw new Error("Canvas is already in use. Chart with ID '"+o.id+"' must be destroyed before the canvas with ID '"+o.canvas.id+"' can be reused.");const a=s.createResolver(s.chartOptionScopes(),this.getContext());this.platform=new(s.platform||ks(n)),this.platform.updateConfig(s);const r=this.platform.acquireContext(n,a.aspectRatio),l=r&&r.canvas,h=l&&l.height,c=l&&l.width;this.id=i(),this.ctx=r,this.canvas=l,this.width=c,this.height=h,this._options=a,this._aspectRatio=this.aspectRatio,this._layers=[],this._metasets=[],this._stacks=void 0,this.boxes=[],this.currentDevicePixelRatio=void 0,this.chartArea=void 0,this._active=[],this._lastEvent=void 0,this._listeners={},this._responsiveListeners=void 0,this._sortedMetasets=[],this.scales={},this._plugins=new sn,this.$proxies={},this._hiddenIndices={},this.attached=!1,this._animationsDisabled=void 0,this.$context=void 0,this._doResize=dt((t=>this.update(t)),a.resizeDelay||0),this._dataChanges=[],Pn[this.id]=this,r&&l?(xt.listen(this,"complete",wn),xt.listen(this,"progress",kn),this._initialize(),this.attached&&this.update()):console.error("Failed to create chart: can't acquire context from the given item")}get aspectRatio(){const{options:{aspectRatio:t,maintainAspectRatio:e},width:i,height:n,_aspectRatio:o}=this;return s(t)?e&&o?o:n?i/n:null:t}get data(){return this.config.data}set data(t){this.config.data=t}get options(){return this._options}set options(t){this.config.options=t}get registry(){return en}_initialize(){return this.notifyPlugins("beforeInit"),this.options.responsive?this.resize():ke(this,this.options.devicePixelRatio),this.bindEvents(),this.notifyPlugins("afterInit"),this}clear(){return Te(this.canvas,this.ctx),this}stop(){return xt.stop(this),this}resize(t,e){xt.running(this)?this._resizeBeforeDraw={width:t,height:e}:this._resize(t,e)}_resize(t,e){const i=this.options,s=this.canvas,n=i.maintainAspectRatio&&this.aspectRatio,o=this.platform.getMaximumSize(s,t,e,n),a=i.devicePixelRatio||this.platform.getDevicePixelRatio(),r=this.width?"resize":"attach";this.width=o.width,this.height=o.height,this._aspectRatio=this.aspectRatio,ke(this,a,!0)&&(this.notifyPlugins("resize",{size:o}),d(i.onResize,[this,o],this),this.attached&&this._doResize(r)&&this.render())}ensureScalesHaveIDs(){u(this.options.scales||{},((t,e)=>{t.id=e}))}buildOrUpdateScales(){const t=this.options,e=t.scales,i=this.scales,s=Object.keys(i).reduce(((t,e)=>(t[e]=!1,t)),{});let n=[];e&&(n=n.concat(Object.keys(e).map((t=>{const i=e[t],s=ln(t,i),n="r"===s,o="x"===s;return{options:i,dposition:n?"chartArea":o?"bottom":"left",dtype:n?"radialLinear":o?"category":"linear"}})))),u(n,(e=>{const n=e.options,o=n.id,a=ln(o,n),r=l(n.type,e.dtype);void 0!==n.position&&vn(n.position,a)===vn(e.dposition)||(n.position=e.dposition),s[o]=!0;let h=null;if(o in i&&i[o].type===r)h=i[o];else{h=new(en.getScale(r))({id:o,type:r,ctx:this.ctx,chart:this}),i[h.id]=h}h.init(n,t)})),u(s,((t,e)=>{t||delete i[e]})),u(i,(t=>{as.configure(this,t,t.options),as.addBox(this,t)}))}_updateMetasets(){const t=this._metasets,e=this.data.datasets.length,i=t.length;if(t.sort(((t,e)=>t.index-e.index)),i>e){for(let t=e;te.length&&delete this._stacks,t.forEach(((t,i)=>{0===e.filter((e=>e===t._dataset)).length&&this._destroyDatasetMeta(i)}))}buildOrUpdateControllers(){const t=[],e=this.data.datasets;let i,s;for(this._removeUnreferencedMetasets(),i=0,s=e.length;i{this.getDatasetMeta(e).controller.reset()}),this)}reset(){this._resetElements(),this.notifyPlugins("reset")}update(t){const e=this.config;e.update();const i=this._options=e.createResolver(e.chartOptionScopes(),this.getContext()),s=this._animationsDisabled=!i.animation;if(this._updateScales(),this._checkEventBindings(),this._updateHiddenIndices(),this._plugins.invalidate(),!1===this.notifyPlugins("beforeUpdate",{mode:t,cancelable:!0}))return;const n=this.buildOrUpdateControllers();this.notifyPlugins("beforeElementsUpdate");let o=0;for(let t=0,e=this.data.datasets.length;t{t.reset()})),this._updateDatasets(t),this.notifyPlugins("afterUpdate",{mode:t}),this._layers.sort(Mn("z","_idx"));const{_active:a,_lastEvent:r}=this;r?this._eventHandler(r,!0):a.length&&this._updateHoverStyles(a,a,!0),this.render()}_updateScales(){u(this.scales,(t=>{as.removeBox(this,t)})),this.ensureScalesHaveIDs(),this.buildOrUpdateScales()}_checkEventBindings(){const t=this.options,e=new Set(Object.keys(this._listeners)),i=new Set(t.events);P(e,i)&&!!this._responsiveListeners===t.responsive||(this.unbindEvents(),this.bindEvents())}_updateHiddenIndices(){const{_hiddenIndices:t}=this,e=this._getUniformDataChanges()||[];for(const{method:i,start:s,count:n}of e){Cn(t,s,"_removeElements"===i?-n:n)}}_getUniformDataChanges(){const t=this._dataChanges;if(!t||!t.length)return;this._dataChanges=[];const e=this.data.datasets.length,i=e=>new Set(t.filter((t=>t[0]===e)).map(((t,e)=>e+","+t.splice(1).join(",")))),s=i(0);for(let t=1;tt.split(","))).map((t=>({method:t[1],start:+t[2],count:+t[3]})))}_updateLayout(t){if(!1===this.notifyPlugins("beforeLayout",{cancelable:!0}))return;as.update(this,this.width,this.height,t);const e=this.chartArea,i=e.width<=0||e.height<=0;this._layers=[],u(this.boxes,(t=>{i&&"chartArea"===t.position||(t.configure&&t.configure(),this._layers.push(...t._layers()))}),this),this._layers.forEach(((t,e)=>{t._idx=e})),this.notifyPlugins("afterLayout")}_updateDatasets(t){if(!1!==this.notifyPlugins("beforeDatasetsUpdate",{mode:t,cancelable:!0})){for(let t=0,e=this.data.datasets.length;t=0;--e)this._drawDataset(t[e]);this.notifyPlugins("afterDatasetsDraw")}_drawDataset(t){const e=this.ctx,i=t._clip,s=!i.disabled,n=function(t,e){const{xScale:i,yScale:s}=t;return i&&s?{left:On(i,e,"left"),right:On(i,e,"right"),top:On(s,e,"top"),bottom:On(s,e,"bottom")}:e}(t,this.chartArea),o={meta:t,index:t.index,cancelable:!0};!1!==this.notifyPlugins("beforeDatasetDraw",o)&&(s&&Ie(e,{left:!1===i.left?0:n.left-i.left,right:!1===i.right?this.width:n.right+i.right,top:!1===i.top?0:n.top-i.top,bottom:!1===i.bottom?this.height:n.bottom+i.bottom}),t.controller.draw(),s&&ze(e),o.cancelable=!1,this.notifyPlugins("afterDatasetDraw",o))}isPointInArea(t){return Re(t,this.chartArea,this._minPadding)}getElementsAtEventForMode(t,e,i,s){const n=Xi.modes[e];return"function"==typeof n?n(this,t,i,s):[]}getDatasetMeta(t){const e=this.data.datasets[t],i=this._metasets;let s=i.filter((t=>t&&t._dataset===e)).pop();return s||(s={type:null,data:[],dataset:null,controller:null,hidden:null,xAxisID:null,yAxisID:null,order:e&&e.order||0,index:t,_dataset:e,_parsed:[],_sorted:!1},i.push(s)),s}getContext(){return this.$context||(this.$context=Ci(null,{chart:this,type:"chart"}))}getVisibleDatasetCount(){return this.getSortedVisibleDatasetMetas().length}isDatasetVisible(t){const e=this.data.datasets[t];if(!e)return!1;const i=this.getDatasetMeta(t);return"boolean"==typeof i.hidden?!i.hidden:!e.hidden}setDatasetVisibility(t,e){this.getDatasetMeta(t).hidden=!e}toggleDataVisibility(t){this._hiddenIndices[t]=!this._hiddenIndices[t]}getDataVisibility(t){return!this._hiddenIndices[t]}_updateVisibility(t,e,i){const s=i?"show":"hide",n=this.getDatasetMeta(t),o=n.controller._resolveAnimations(void 0,s);k(e)?(n.data[e].hidden=!i,this.update()):(this.setDatasetVisibility(t,i),o.update(n,{visible:i}),this.update((e=>e.datasetIndex===t?s:void 0)))}hide(t,e){this._updateVisibility(t,e,!1)}show(t,e){this._updateVisibility(t,e,!0)}_destroyDatasetMeta(t){const e=this._metasets[t];e&&e.controller&&e.controller._destroy(),delete this._metasets[t]}_stop(){let t,e;for(this.stop(),xt.remove(this),t=0,e=this.data.datasets.length;t{e.addEventListener(this,i,s),t[i]=s},s=(t,e,i)=>{t.offsetX=e,t.offsetY=i,this._eventHandler(t)};u(this.options.events,(t=>i(t,s)))}bindResponsiveEvents(){this._responsiveListeners||(this._responsiveListeners={});const t=this._responsiveListeners,e=this.platform,i=(i,s)=>{e.addEventListener(this,i,s),t[i]=s},s=(i,s)=>{t[i]&&(e.removeEventListener(this,i,s),delete t[i])},n=(t,e)=>{this.canvas&&this.resize(t,e)};let o;const a=()=>{s("attach",a),this.attached=!0,this.resize(),i("resize",n),i("detach",o)};o=()=>{this.attached=!1,s("resize",n),this._stop(),this._resize(0,0),i("attach",a)},e.isAttached(this.canvas)?a():o()}unbindEvents(){u(this._listeners,((t,e)=>{this.platform.removeEventListener(this,e,t)})),this._listeners={},u(this._responsiveListeners,((t,e)=>{this.platform.removeEventListener(this,e,t)})),this._responsiveListeners=void 0}updateHoverStyle(t,e,i){const s=i?"set":"remove";let n,o,a,r;for("dataset"===e&&(n=this.getDatasetMeta(t[0].datasetIndex),n.controller["_"+s+"DatasetHoverStyle"]()),a=0,r=t.length;a{const i=this.getDatasetMeta(t);if(!i)throw new Error("No dataset found at index "+t);return{datasetIndex:t,element:i.data[e],index:e}}));!f(i,e)&&(this._active=i,this._lastEvent=null,this._updateHoverStyles(i,e))}notifyPlugins(t,e,i){return this._plugins.notify(this,t,e,i)}isPluginEnabled(t){return 1===this._plugins._cache.filter((e=>e.plugin.id===t)).length}_updateHoverStyles(t,e,i){const s=this.options.hover,n=(t,e)=>t.filter((t=>!e.some((e=>t.datasetIndex===e.datasetIndex&&t.index===e.index)))),o=n(e,t),a=i?t:n(t,e);o.length&&this.updateHoverStyle(o,s.mode,!1),a.length&&s.mode&&this.updateHoverStyle(a,s.mode,!0)}_eventHandler(t,e){const i={event:t,replay:e,cancelable:!0,inChartArea:this.isPointInArea(t)},s=e=>(e.options.events||this.options.events).includes(t.native.type);if(!1===this.notifyPlugins("beforeEvent",i,s))return;const n=this._handleEvent(t,e,i.inChartArea);return i.cancelable=!1,this.notifyPlugins("afterEvent",i,s),(n||i.changed)&&this.render(),this}_handleEvent(t,e,i){const{_active:s=[],options:n}=this,o=e,a=this._getActiveElements(t,s,i,o),r=D(t),l=function(t,e,i,s){return i&&"mouseout"!==t.type?s?e:t:null}(t,this._lastEvent,i,r);i&&(this._lastEvent=null,d(n.onHover,[t,a,this],this),r&&d(n.onClick,[t,a,this],this));const h=!f(a,s);return(h||e)&&(this._active=a,this._updateHoverStyles(a,s,e)),this._lastEvent=l,h}_getActiveElements(t,e,i,s){if("mouseout"===t.type)return[];if(!i)return e;const n=this.options.hover;return this.getElementsAtEventForMode(t,n.mode,n,s)}}function Tn(){return u(An.instances,(t=>t._plugins.invalidate()))}function Ln(){throw new Error("This method is not implemented: Check that a complete date adapter is provided.")}class En{static override(t){Object.assign(En.prototype,t)}options;constructor(t){this.options=t||{}}init(){}formats(){return Ln()}parse(){return Ln()}format(){return Ln()}add(){return Ln()}diff(){return Ln()}startOf(){return Ln()}endOf(){return Ln()}}var Rn={_date:En};function In(t){const e=t.iScale,i=function(t,e){if(!t._cache.$bar){const i=t.getMatchingVisibleMetas(e);let s=[];for(let e=0,n=i.length;et-e)))}return t._cache.$bar}(e,t.type);let s,n,o,a,r=e._length;const l=()=>{32767!==o&&-32768!==o&&(k(a)&&(r=Math.min(r,Math.abs(o-a)||r)),a=o)};for(s=0,n=i.length;sMath.abs(r)&&(l=r,h=a),e[i.axis]=h,e._custom={barStart:l,barEnd:h,start:n,end:o,min:a,max:r}}(t,e,i,s):e[i.axis]=i.parse(t,s),e}function Fn(t,e,i,s){const n=t.iScale,o=t.vScale,a=n.getLabels(),r=n===o,l=[];let h,c,d,u;for(h=i,c=i+s;ht.x,i="left",s="right"):(e=t.base"spacing"!==t,_indexable:t=>"spacing"!==t&&!t.startsWith("borderDash")&&!t.startsWith("hoverBorderDash")};static overrides={aspectRatio:1,plugins:{legend:{labels:{generateLabels(t){const e=t.data;if(e.labels.length&&e.datasets.length){const{labels:{pointStyle:i,color:s}}=t.legend.options;return e.labels.map(((e,n)=>{const o=t.getDatasetMeta(0).controller.getStyle(n);return{text:e,fillStyle:o.backgroundColor,strokeStyle:o.borderColor,fontColor:s,lineWidth:o.borderWidth,pointStyle:i,hidden:!t.getDataVisibility(n),index:n}}))}return[]}},onClick(t,e,i){i.chart.toggleDataVisibility(e.index),i.chart.update()}}}};constructor(t,e){super(t,e),this.enableOptionSharing=!0,this.innerRadius=void 0,this.outerRadius=void 0,this.offsetX=void 0,this.offsetY=void 0}linkScales(){}parse(t,e){const i=this.getDataset().data,s=this._cachedMeta;if(!1===this._parsing)s._parsed=i;else{let n,a,r=t=>+i[t];if(o(i[t])){const{key:t="value"}=this._parsing;r=e=>+M(i[e],t)}for(n=t,a=t+e;nZ(t,r,l,!0)?1:Math.max(e,e*i,s,s*i),g=(t,e,s)=>Z(t,r,l,!0)?-1:Math.min(e,e*i,s,s*i),p=f(0,h,d),m=f(E,c,u),b=g(C,h,d),x=g(C+E,c,u);s=(p-b)/2,n=(m-x)/2,o=-(p+b)/2,a=-(m+x)/2}return{ratioX:s,ratioY:n,offsetX:o,offsetY:a}}(u,d,r),b=(i.width-o)/f,x=(i.height-o)/g,_=Math.max(Math.min(b,x)/2,0),y=c(this.options.radius,_),v=(y-Math.max(y*r,0))/this._getVisibleDatasetWeightTotal();this.offsetX=p*y,this.offsetY=m*y,s.total=this.calculateTotal(),this.outerRadius=y-v*this._getRingWeightOffset(this.index),this.innerRadius=Math.max(this.outerRadius-v*l,0),this.updateElements(n,0,n.length,t)}_circumference(t,e){const i=this.options,s=this._cachedMeta,n=this._getCircumference();return e&&i.animation.animateRotate||!this.chart.getDataVisibility(t)||null===s._parsed[t]||s.data[t].hidden?0:this.calculateCircumference(s._parsed[t]*n/O)}updateElements(t,e,i,s){const n="reset"===s,o=this.chart,a=o.chartArea,r=o.options.animation,l=(a.left+a.right)/2,h=(a.top+a.bottom)/2,c=n&&r.animateScale,d=c?0:this.innerRadius,u=c?0:this.outerRadius,{sharedOptions:f,includeOptions:g}=this._getSharedOptions(e,s);let p,m=this._getRotation();for(p=0;p0&&!isNaN(t)?O*(Math.abs(t)/e):0}getLabelAndValue(t){const e=this._cachedMeta,i=this.chart,s=i.data.labels||[],n=ne(e._parsed[t],i.options.locale);return{label:s[t]||"",value:n}}getMaxBorderWidth(t){let e=0;const i=this.chart;let s,n,o,a,r;if(!t)for(s=0,n=i.data.datasets.length;s{const o=t.getDatasetMeta(0).controller.getStyle(n);return{text:e,fillStyle:o.backgroundColor,strokeStyle:o.borderColor,fontColor:s,lineWidth:o.borderWidth,pointStyle:i,hidden:!t.getDataVisibility(n),index:n}}))}return[]}},onClick(t,e,i){i.chart.toggleDataVisibility(e.index),i.chart.update()}}},scales:{r:{type:"radialLinear",angleLines:{display:!1},beginAtZero:!0,grid:{circular:!0},pointLabels:{display:!1},startAngle:0}}};constructor(t,e){super(t,e),this.innerRadius=void 0,this.outerRadius=void 0}getLabelAndValue(t){const e=this._cachedMeta,i=this.chart,s=i.data.labels||[],n=ne(e._parsed[t].r,i.options.locale);return{label:s[t]||"",value:n}}parseObjectData(t,e,i,s){return ii.bind(this)(t,e,i,s)}update(t){const e=this._cachedMeta.data;this._updateRadius(),this.updateElements(e,0,e.length,t)}getMinMax(){const t=this._cachedMeta,e={min:Number.POSITIVE_INFINITY,max:Number.NEGATIVE_INFINITY};return t.data.forEach(((t,i)=>{const s=this.getParsed(i).r;!isNaN(s)&&this.chart.getDataVisibility(i)&&(se.max&&(e.max=s))})),e}_updateRadius(){const t=this.chart,e=t.chartArea,i=t.options,s=Math.min(e.right-e.left,e.bottom-e.top),n=Math.max(s/2,0),o=(n-Math.max(i.cutoutPercentage?n/100*i.cutoutPercentage:1,0))/t.getVisibleDatasetCount();this.outerRadius=n-o*this.index,this.innerRadius=this.outerRadius-o}updateElements(t,e,i,s){const n="reset"===s,o=this.chart,a=o.options.animation,r=this._cachedMeta.rScale,l=r.xCenter,h=r.yCenter,c=r.getIndexAngle(0)-.5*C;let d,u=c;const f=360/this.countVisibleElements();for(d=0;d{!isNaN(this.getParsed(i).r)&&this.chart.getDataVisibility(i)&&e++})),e}_computeAngle(t,e,i){return this.chart.getDataVisibility(t)?$(this.resolveDataElementOptions(t,e).angle||i):0}}var Yn=Object.freeze({__proto__:null,BarController:class extends Ns{static id="bar";static defaults={datasetElementType:!1,dataElementType:"bar",categoryPercentage:.8,barPercentage:.9,grouped:!0,animations:{numbers:{type:"number",properties:["x","y","base","width","height"]}}};static overrides={scales:{_index_:{type:"category",offset:!0,grid:{offset:!0}},_value_:{type:"linear",beginAtZero:!0}}};parsePrimitiveData(t,e,i,s){return Fn(t,e,i,s)}parseArrayData(t,e,i,s){return Fn(t,e,i,s)}parseObjectData(t,e,i,s){const{iScale:n,vScale:o}=t,{xAxisKey:a="x",yAxisKey:r="y"}=this._parsing,l="x"===n.axis?a:r,h="x"===o.axis?a:r,c=[];let d,u,f,g;for(d=i,u=i+s;dt.controller.options.grouped)),o=i.options.stacked,a=[],r=t=>{const i=t.controller.getParsed(e),n=i&&i[t.vScale.axis];if(s(n)||isNaN(n))return!0};for(const i of n)if((void 0===e||!r(i))&&((!1===o||-1===a.indexOf(i.stack)||void 0===o&&void 0===i.stack)&&a.push(i.stack),i.index===t))break;return a.length||a.push(void 0),a}_getStackCount(t){return this._getStacks(void 0,t).length}_getStackIndex(t,e,i){const s=this._getStacks(t,i),n=void 0!==e?s.indexOf(e):-1;return-1===n?s.length-1:n}_getRuler(){const t=this.options,e=this._cachedMeta,i=e.iScale,s=[];let n,o;for(n=0,o=e.data.length;n=i?1:-1)}(u,e,r)*a,f===r&&(b-=u/2);const t=e.getPixelForDecimal(0),s=e.getPixelForDecimal(1),o=Math.min(t,s),h=Math.max(t,s);b=Math.max(Math.min(b,h),o),d=b+u,i&&!c&&(l._stacks[e.axis]._visualValues[n]=e.getValueForPixel(d)-e.getValueForPixel(b))}if(b===e.getPixelForValue(r)){const t=F(u)*e.getLineWidthForValue(r)/2;b+=t,u-=t}return{size:u,base:b,head:d,center:d+u/2}}_calculateBarIndexPixels(t,e){const i=e.scale,n=this.options,o=n.skipNull,a=l(n.maxBarThickness,1/0);let r,h;if(e.grouped){const i=o?this._getStackCount(t):e.stackCount,l="flex"===n.barThickness?function(t,e,i,s){const n=e.pixels,o=n[t];let a=t>0?n[t-1]:null,r=t=0;--i)e=Math.max(e,t[i].size(this.resolveDataElementOptions(i))/2);return e>0&&e}getLabelAndValue(t){const e=this._cachedMeta,i=this.chart.data.labels||[],{xScale:s,yScale:n}=e,o=this.getParsed(t),a=s.getLabelForValue(o.x),r=n.getLabelForValue(o.y),l=o._custom;return{label:i[t]||"",value:"("+a+", "+r+(l?", "+l:"")+")"}}update(t){const e=this._cachedMeta.data;this.updateElements(e,0,e.length,t)}updateElements(t,e,i,s){const n="reset"===s,{iScale:o,vScale:a}=this._cachedMeta,{sharedOptions:r,includeOptions:l}=this._getSharedOptions(e,s),h=o.axis,c=a.axis;for(let d=e;d0&&this.getParsed(e-1);for(let i=0;i<_;++i){const g=t[i],_=b?g:{};if(i=x){_.skip=!0;continue}const v=this.getParsed(i),M=s(v[f]),w=_[u]=a.getPixelForValue(v[u],i),k=_[f]=o||M?r.getBasePixel():r.getPixelForValue(l?this.applyStack(r,v,l):v[f],i);_.skip=isNaN(w)||isNaN(k)||M,_.stop=i>0&&Math.abs(v[u]-y[u])>m,p&&(_.parsed=v,_.raw=h.data[i]),d&&(_.options=c||this.resolveDataElementOptions(i,g.active?"active":n)),b||this.updateElement(g,i,_,n),y=v}}getMaxOverflow(){const t=this._cachedMeta,e=t.dataset,i=e.options&&e.options.borderWidth||0,s=t.data||[];if(!s.length)return i;const n=s[0].size(this.resolveDataElementOptions(0)),o=s[s.length-1].size(this.resolveDataElementOptions(s.length-1));return Math.max(i,n,o)/2}draw(){const t=this._cachedMeta;t.dataset.updateControlPoints(this.chart.chartArea,t.iScale.axis),super.draw()}},PieController:class extends jn{static id="pie";static defaults={cutout:0,rotation:0,circumference:360,radius:"100%"}},PolarAreaController:$n,RadarController:class extends Ns{static id="radar";static defaults={datasetElementType:"line",dataElementType:"point",indexAxis:"r",showLine:!0,elements:{line:{fill:"start"}}};static overrides={aspectRatio:1,scales:{r:{type:"radialLinear"}}};getLabelAndValue(t){const e=this._cachedMeta.vScale,i=this.getParsed(t);return{label:e.getLabels()[t],value:""+e.getLabelForValue(i[e.axis])}}parseObjectData(t,e,i,s){return ii.bind(this)(t,e,i,s)}update(t){const e=this._cachedMeta,i=e.dataset,s=e.data||[],n=e.iScale.getLabels();if(i.points=s,"resize"!==t){const e=this.resolveDatasetElementOptions(t);this.options.showLine||(e.borderWidth=0);const o={_loop:!0,_fullLoop:n.length===s.length,options:e};this.updateElement(i,void 0,o,t)}this.updateElements(s,0,s.length,t)}updateElements(t,e,i,s){const n=this._cachedMeta.rScale,o="reset"===s;for(let a=e;a0&&this.getParsed(e-1);for(let c=e;c0&&Math.abs(i[f]-_[f])>b,m&&(p.parsed=i,p.raw=h.data[c]),u&&(p.options=d||this.resolveDataElementOptions(c,e.active?"active":n)),x||this.updateElement(e,c,p,n),_=i}this.updateSharedOptions(d,n,c)}getMaxOverflow(){const t=this._cachedMeta,e=t.data||[];if(!this.options.showLine){let t=0;for(let i=e.length-1;i>=0;--i)t=Math.max(t,e[i].size(this.resolveDataElementOptions(i))/2);return t>0&&t}const i=t.dataset,s=i.options&&i.options.borderWidth||0;if(!e.length)return s;const n=e[0].size(this.resolveDataElementOptions(0)),o=e[e.length-1].size(this.resolveDataElementOptions(e.length-1));return Math.max(s,n,o)/2}}});function Un(t,e,i,s){const n=vi(t.options.borderRadius,["outerStart","outerEnd","innerStart","innerEnd"]);const o=(i-e)/2,a=Math.min(o,s*e/2),r=t=>{const e=(i-Math.min(o,t))*s/2;return J(t,0,Math.min(o,e))};return{outerStart:r(n.outerStart),outerEnd:r(n.outerEnd),innerStart:J(n.innerStart,0,a),innerEnd:J(n.innerEnd,0,a)}}function Xn(t,e,i,s){return{x:i+t*Math.cos(e),y:s+t*Math.sin(e)}}function qn(t,e,i,s,n,o){const{x:a,y:r,startAngle:l,pixelMargin:h,innerRadius:c}=e,d=Math.max(e.outerRadius+s+i-h,0),u=c>0?c+s+i+h:0;let f=0;const g=n-l;if(s){const t=((c>0?c-s:0)+(d>0?d-s:0))/2;f=(g-(0!==t?g*t/(t+s):g))/2}const p=(g-Math.max(.001,g*d-i/C)/d)/2,m=l+p+f,b=n-p-f,{outerStart:x,outerEnd:_,innerStart:y,innerEnd:v}=Un(e,u,d,b-m),M=d-x,w=d-_,k=m+x/M,S=b-_/w,P=u+y,D=u+v,O=m+y/P,A=b-v/D;if(t.beginPath(),o){const e=(k+S)/2;if(t.arc(a,r,d,k,e),t.arc(a,r,d,e,S),_>0){const e=Xn(w,S,a,r);t.arc(e.x,e.y,_,S,b+E)}const i=Xn(D,b,a,r);if(t.lineTo(i.x,i.y),v>0){const e=Xn(D,A,a,r);t.arc(e.x,e.y,v,b+E,A+Math.PI)}const s=(b-v/u+(m+y/u))/2;if(t.arc(a,r,u,b-v/u,s,!0),t.arc(a,r,u,s,m+y/u,!0),y>0){const e=Xn(P,O,a,r);t.arc(e.x,e.y,y,O+Math.PI,m-E)}const n=Xn(M,m,a,r);if(t.lineTo(n.x,n.y),x>0){const e=Xn(M,k,a,r);t.arc(e.x,e.y,x,m-E,k)}}else{t.moveTo(a,r);const e=Math.cos(k)*d+a,i=Math.sin(k)*d+r;t.lineTo(e,i);const s=Math.cos(S)*d+a,n=Math.sin(S)*d+r;t.lineTo(s,n)}t.closePath()}function Kn(t,e,i,s,n){const{fullCircles:o,startAngle:a,circumference:r,options:l}=e,{borderWidth:h,borderJoinStyle:c,borderDash:d,borderDashOffset:u}=l,f="inner"===l.borderAlign;if(!h)return;t.setLineDash(d||[]),t.lineDashOffset=u,f?(t.lineWidth=2*h,t.lineJoin=c||"round"):(t.lineWidth=h,t.lineJoin=c||"bevel");let g=e.endAngle;if(o){qn(t,e,i,s,g,n);for(let e=0;en?(h=n/l,t.arc(o,a,l,i+h,s-h,!0)):t.arc(o,a,n,i+E,s-E),t.closePath(),t.clip()}(t,e,g),o||(qn(t,e,i,s,g,n),t.stroke())}function Gn(t,e,i=e){t.lineCap=l(i.borderCapStyle,e.borderCapStyle),t.setLineDash(l(i.borderDash,e.borderDash)),t.lineDashOffset=l(i.borderDashOffset,e.borderDashOffset),t.lineJoin=l(i.borderJoinStyle,e.borderJoinStyle),t.lineWidth=l(i.borderWidth,e.borderWidth),t.strokeStyle=l(i.borderColor,e.borderColor)}function Zn(t,e,i){t.lineTo(i.x,i.y)}function Jn(t,e,i={}){const s=t.length,{start:n=0,end:o=s-1}=i,{start:a,end:r}=e,l=Math.max(n,a),h=Math.min(o,r),c=nr&&o>r;return{count:s,start:l,loop:e.loop,ilen:h(a+(h?r-t:t))%o,_=()=>{f!==g&&(t.lineTo(m,g),t.lineTo(m,f),t.lineTo(m,p))};for(l&&(d=n[x(0)],t.moveTo(d.x,d.y)),c=0;c<=r;++c){if(d=n[x(c)],d.skip)continue;const e=d.x,i=d.y,s=0|e;s===u?(ig&&(g=i),m=(b*m+e)/++b):(_(),t.lineTo(e,i),u=s,b=0,f=g=i),p=i}_()}function eo(t){const e=t.options,i=e.borderDash&&e.borderDash.length;return!(t._decimated||t._loop||e.tension||"monotone"===e.cubicInterpolationMode||e.stepped||i)?to:Qn}const io="function"==typeof Path2D;function so(t,e,i,s){io&&!e.options.segment?function(t,e,i,s){let n=e._path;n||(n=e._path=new Path2D,e.path(n,i,s)&&n.closePath()),Gn(t,e.options),t.stroke(n)}(t,e,i,s):function(t,e,i,s){const{segments:n,options:o}=e,a=eo(e);for(const r of n)Gn(t,o,r.style),t.beginPath(),a(t,e,r,{start:i,end:i+s-1})&&t.closePath(),t.stroke()}(t,e,i,s)}class no extends Hs{static id="line";static defaults={borderCapStyle:"butt",borderDash:[],borderDashOffset:0,borderJoinStyle:"miter",borderWidth:3,capBezierPoints:!0,cubicInterpolationMode:"default",fill:!1,spanGaps:!1,stepped:!1,tension:0};static defaultRoutes={backgroundColor:"backgroundColor",borderColor:"borderColor"};static descriptors={_scriptable:!0,_indexable:t=>"borderDash"!==t&&"fill"!==t};constructor(t){super(),this.animated=!0,this.options=void 0,this._chart=void 0,this._loop=void 0,this._fullLoop=void 0,this._path=void 0,this._points=void 0,this._segments=void 0,this._decimated=!1,this._pointsUpdated=!1,this._datasetIndex=void 0,t&&Object.assign(this,t)}updateControlPoints(t,e){const i=this.options;if((i.tension||"monotone"===i.cubicInterpolationMode)&&!i.stepped&&!this._pointsUpdated){const s=i.spanGaps?this._loop:this._fullLoop;hi(this._points,i,t,s,e),this._pointsUpdated=!0}}set points(t){this._points=t,delete this._segments,delete this._path,this._pointsUpdated=!1}get points(){return this._points}get segments(){return this._segments||(this._segments=zi(this,this.options.segment))}first(){const t=this.segments,e=this.points;return t.length&&e[t[0].start]}last(){const t=this.segments,e=this.points,i=t.length;return i&&e[t[i-1].end]}interpolate(t,e){const i=this.options,s=t[e],n=this.points,o=Ii(this,{property:e,start:s,end:s});if(!o.length)return;const a=[],r=function(t){return t.stepped?pi:t.tension||"monotone"===t.cubicInterpolationMode?mi:gi}(i);let l,h;for(l=0,h=o.length;l"borderDash"!==t};circumference;endAngle;fullCircles;innerRadius;outerRadius;pixelMargin;startAngle;constructor(t){super(),this.options=void 0,this.circumference=void 0,this.startAngle=void 0,this.endAngle=void 0,this.innerRadius=void 0,this.outerRadius=void 0,this.pixelMargin=0,this.fullCircles=0,t&&Object.assign(this,t)}inRange(t,e,i){const s=this.getProps(["x","y"],i),{angle:n,distance:o}=X(s,{x:t,y:e}),{startAngle:a,endAngle:r,innerRadius:h,outerRadius:c,circumference:d}=this.getProps(["startAngle","endAngle","innerRadius","outerRadius","circumference"],i),u=(this.options.spacing+this.options.borderWidth)/2,f=l(d,r-a)>=O||Z(n,a,r),g=tt(o,h+u,c+u);return f&&g}getCenterPoint(t){const{x:e,y:i,startAngle:s,endAngle:n,innerRadius:o,outerRadius:a}=this.getProps(["x","y","startAngle","endAngle","innerRadius","outerRadius"],t),{offset:r,spacing:l}=this.options,h=(s+n)/2,c=(o+a+l+r)/2;return{x:e+Math.cos(h)*c,y:i+Math.sin(h)*c}}tooltipPosition(t){return this.getCenterPoint(t)}draw(t){const{options:e,circumference:i}=this,s=(e.offset||0)/4,n=(e.spacing||0)/2,o=e.circular;if(this.pixelMargin="inner"===e.borderAlign?.33:0,this.fullCircles=i>O?Math.floor(i/O):0,0===i||this.innerRadius<0||this.outerRadius<0)return;t.save();const a=(this.startAngle+this.endAngle)/2;t.translate(Math.cos(a)*s,Math.sin(a)*s);const r=s*(1-Math.sin(Math.min(C,i||0)));t.fillStyle=e.backgroundColor,t.strokeStyle=e.borderColor,function(t,e,i,s,n){const{fullCircles:o,startAngle:a,circumference:r}=e;let l=e.endAngle;if(o){qn(t,e,i,s,l,n);for(let e=0;e("string"==typeof e?(i=t.push(e)-1,s.unshift({index:i,label:e})):isNaN(e)&&(i=null),i))(t,e,i,s);return n!==t.lastIndexOf(e)?i:n}function po(t){const e=this.getLabels();return t>=0&&ts=e?s:t,a=t=>n=i?n:t;if(t){const t=F(s),e=F(n);t<0&&e<0?a(0):t>0&&e>0&&o(0)}if(s===n){let e=0===n?1:Math.abs(.05*n);a(n+e),t||o(s-e)}this.min=s,this.max=n}getTickLimit(){const t=this.options.ticks;let e,{maxTicksLimit:i,stepSize:s}=t;return s?(e=Math.ceil(this.max/s)-Math.floor(this.min/s)+1,e>1e3&&(console.warn(`scales.${this.id}.ticks.stepSize: ${s} would result generating up to ${e} ticks. Limiting to 1000.`),e=1e3)):(e=this.computeTickLimit(),i=i||11),i&&(e=Math.min(i,e)),e}computeTickLimit(){return Number.POSITIVE_INFINITY}buildTicks(){const t=this.options,e=t.ticks;let i=this.getTickLimit();i=Math.max(2,i);const n=function(t,e){const i=[],{bounds:n,step:o,min:a,max:r,precision:l,count:h,maxTicks:c,maxDigits:d,includeBounds:u}=t,f=o||1,g=c-1,{min:p,max:m}=e,b=!s(a),x=!s(r),_=!s(h),y=(m-p)/(d+1);let v,M,w,k,S=B((m-p)/g/f)*f;if(S<1e-14&&!b&&!x)return[{value:p},{value:m}];k=Math.ceil(m/S)-Math.floor(p/S),k>g&&(S=B(k*S/g/f)*f),s(l)||(v=Math.pow(10,l),S=Math.ceil(S*v)/v),"ticks"===n?(M=Math.floor(p/S)*S,w=Math.ceil(m/S)*S):(M=p,w=m),b&&x&&o&&H((r-a)/o,S/1e3)?(k=Math.round(Math.min((r-a)/S,c)),S=(r-a)/k,M=a,w=r):_?(M=b?a:M,w=x?r:w,k=h-1,S=(w-M)/k):(k=(w-M)/S,k=V(k,Math.round(k),S/1e3)?Math.round(k):Math.ceil(k));const P=Math.max(U(S),U(M));v=Math.pow(10,s(l)?P:l),M=Math.round(M*v)/v,w=Math.round(w*v)/v;let D=0;for(b&&(u&&M!==a?(i.push({value:a}),Mr)break;i.push({value:t})}return x&&u&&w!==r?i.length&&V(i[i.length-1].value,r,mo(r,y,t))?i[i.length-1].value=r:i.push({value:r}):x&&w!==r||i.push({value:w}),i}({maxTicks:i,bounds:t.bounds,min:t.min,max:t.max,precision:e.precision,step:e.stepSize,count:e.count,maxDigits:this._maxDigits(),horizontal:this.isHorizontal(),minRotation:e.minRotation||0,includeBounds:!1!==e.includeBounds},this._range||this);return"ticks"===t.bounds&&j(n,this,"value"),t.reverse?(n.reverse(),this.start=this.max,this.end=this.min):(this.start=this.min,this.end=this.max),n}configure(){const t=this.ticks;let e=this.min,i=this.max;if(super.configure(),this.options.offset&&t.length){const s=(i-e)/Math.max(t.length-1,1)/2;e-=s,i+=s}this._startValue=e,this._endValue=i,this._valueRange=i-e}getLabelForValue(t){return ne(t,this.chart.options.locale,this.options.ticks.format)}}class xo extends bo{static id="linear";static defaults={ticks:{callback:ae.formatters.numeric}};determineDataLimits(){const{min:t,max:e}=this.getMinMax(!0);this.min=a(t)?t:0,this.max=a(e)?e:1,this.handleTickRangeOptions()}computeTickLimit(){const t=this.isHorizontal(),e=t?this.width:this.height,i=$(this.options.ticks.minRotation),s=(t?Math.sin(i):Math.cos(i))||.001,n=this._resolveTickFontOptions(0);return Math.ceil(e/Math.min(40,n.lineHeight/s))}getPixelForValue(t){return null===t?NaN:this.getPixelForDecimal((t-this._startValue)/this._valueRange)}getValueForPixel(t){return this._startValue+this.getDecimalForPixel(t)*this._valueRange}}const _o=t=>Math.floor(z(t)),yo=(t,e)=>Math.pow(10,_o(t)+e);function vo(t){return 1===t/Math.pow(10,_o(t))}function Mo(t,e,i){const s=Math.pow(10,i),n=Math.floor(t/s);return Math.ceil(e/s)-n}function wo(t,{min:e,max:i}){e=r(t.min,e);const s=[],n=_o(e);let o=function(t,e){let i=_o(e-t);for(;Mo(t,e,i)>10;)i++;for(;Mo(t,e,i)<10;)i--;return Math.min(i,_o(t))}(e,i),a=o<0?Math.pow(10,Math.abs(o)):1;const l=Math.pow(10,o),h=n>o?Math.pow(10,n):0,c=Math.round((e-h)*a)/a,d=Math.floor((e-h)/l/10)*l*10;let u=Math.floor((c-d)/Math.pow(10,o)),f=r(t.min,Math.round((h+d+u*Math.pow(10,o))*a)/a);for(;f=10?u=u<15?15:20:u++,u>=20&&(o++,u=2,a=o>=0?1:a),f=Math.round((h+d+u*Math.pow(10,o))*a)/a;const g=r(t.max,f);return s.push({value:g,major:vo(g),significand:u}),s}class ko extends Js{static id="logarithmic";static defaults={ticks:{callback:ae.formatters.logarithmic,major:{enabled:!0}}};constructor(t){super(t),this.start=void 0,this.end=void 0,this._startValue=void 0,this._valueRange=0}parse(t,e){const i=bo.prototype.parse.apply(this,[t,e]);if(0!==i)return a(i)&&i>0?i:null;this._zero=!0}determineDataLimits(){const{min:t,max:e}=this.getMinMax(!0);this.min=a(t)?Math.max(0,t):null,this.max=a(e)?Math.max(0,e):null,this.options.beginAtZero&&(this._zero=!0),this._zero&&this.min!==this._suggestedMin&&!a(this._userMin)&&(this.min=t===yo(this.min,0)?yo(this.min,-1):yo(this.min,0)),this.handleTickRangeOptions()}handleTickRangeOptions(){const{minDefined:t,maxDefined:e}=this.getUserBounds();let i=this.min,s=this.max;const n=e=>i=t?i:e,o=t=>s=e?s:t;i===s&&(i<=0?(n(1),o(10)):(n(yo(i,-1)),o(yo(s,1)))),i<=0&&n(yo(s,-1)),s<=0&&o(yo(i,1)),this.min=i,this.max=s}buildTicks(){const t=this.options,e=wo({min:this._userMin,max:this._userMax},this);return"ticks"===t.bounds&&j(e,this,"value"),t.reverse?(e.reverse(),this.start=this.max,this.end=this.min):(this.start=this.min,this.end=this.max),e}getLabelForValue(t){return void 0===t?"0":ne(t,this.chart.options.locale,this.options.ticks.format)}configure(){const t=this.min;super.configure(),this._startValue=z(t),this._valueRange=z(this.max)-z(t)}getPixelForValue(t){return void 0!==t&&0!==t||(t=this.min),null===t||isNaN(t)?NaN:this.getPixelForDecimal(t===this.min?0:(z(t)-this._startValue)/this._valueRange)}getValueForPixel(t){const e=this.getDecimalForPixel(t);return Math.pow(10,this._startValue+e*this._valueRange)}}function So(t){const e=t.ticks;if(e.display&&t.display){const t=ki(e.backdropPadding);return l(e.font&&e.font.size,ue.font.size)+t.height}return 0}function Po(t,e,i,s,n){return t===s||t===n?{start:e-i/2,end:e+i/2}:tn?{start:e-i,end:e}:{start:e,end:e+i}}function Do(t){const e={l:t.left+t._padding.left,r:t.right-t._padding.right,t:t.top+t._padding.top,b:t.bottom-t._padding.bottom},i=Object.assign({},e),s=[],o=[],a=t._pointLabels.length,r=t.options.pointLabels,l=r.centerPointLabels?C/a:0;for(let u=0;ue.r&&(r=(s.end-e.r)/o,t.r=Math.max(t.r,e.r+r)),n.starte.b&&(l=(n.end-e.b)/a,t.b=Math.max(t.b,e.b+l))}function Oo(t,e,i){const s=t.drawingArea,{extra:n,additionalAngle:o,padding:a,size:r}=i,l=t.getPointPosition(e,s+n+a,o),h=Math.round(Y(G(l.angle+E))),c=function(t,e,i){90===i||270===i?t-=e/2:(i>270||i<90)&&(t-=e);return t}(l.y,r.h,h),d=function(t){if(0===t||180===t)return"center";if(t<180)return"left";return"right"}(h),u=function(t,e,i){"right"===i?t-=e:"center"===i&&(t-=e/2);return t}(l.x,r.w,d);return{visible:!0,x:l.x,y:c,textAlign:d,left:u,top:c,right:u+r.w,bottom:c+r.h}}function Ao(t,e){if(!e)return!0;const{left:i,top:s,right:n,bottom:o}=t;return!(Re({x:i,y:s},e)||Re({x:i,y:o},e)||Re({x:n,y:s},e)||Re({x:n,y:o},e))}function To(t,e,i){const{left:n,top:o,right:a,bottom:r}=i,{backdropColor:l}=e;if(!s(l)){const i=wi(e.borderRadius),s=ki(e.backdropPadding);t.fillStyle=l;const h=n-s.left,c=o-s.top,d=a-n+s.width,u=r-o+s.height;Object.values(i).some((t=>0!==t))?(t.beginPath(),He(t,{x:h,y:c,w:d,h:u,radius:i}),t.fill()):t.fillRect(h,c,d,u)}}function Lo(t,e,i,s){const{ctx:n}=t;if(i)n.arc(t.xCenter,t.yCenter,e,0,O);else{let i=t.getPointPosition(0,e);n.moveTo(i.x,i.y);for(let o=1;ot,padding:5,centerPointLabels:!1}};static defaultRoutes={"angleLines.color":"borderColor","pointLabels.color":"color","ticks.color":"color"};static descriptors={angleLines:{_fallback:"grid"}};constructor(t){super(t),this.xCenter=void 0,this.yCenter=void 0,this.drawingArea=void 0,this._pointLabels=[],this._pointLabelItems=[]}setDimensions(){const t=this._padding=ki(So(this.options)/2),e=this.width=this.maxWidth-t.width,i=this.height=this.maxHeight-t.height;this.xCenter=Math.floor(this.left+e/2+t.left),this.yCenter=Math.floor(this.top+i/2+t.top),this.drawingArea=Math.floor(Math.min(e,i)/2)}determineDataLimits(){const{min:t,max:e}=this.getMinMax(!1);this.min=a(t)&&!isNaN(t)?t:0,this.max=a(e)&&!isNaN(e)?e:0,this.handleTickRangeOptions()}computeTickLimit(){return Math.ceil(this.drawingArea/So(this.options))}generateTickLabels(t){bo.prototype.generateTickLabels.call(this,t),this._pointLabels=this.getLabels().map(((t,e)=>{const i=d(this.options.pointLabels.callback,[t,e],this);return i||0===i?i:""})).filter(((t,e)=>this.chart.getDataVisibility(e)))}fit(){const t=this.options;t.display&&t.pointLabels.display?Do(this):this.setCenterPoint(0,0,0,0)}setCenterPoint(t,e,i,s){this.xCenter+=Math.floor((t-e)/2),this.yCenter+=Math.floor((i-s)/2),this.drawingArea-=Math.min(this.drawingArea/2,Math.max(t,e,i,s))}getIndexAngle(t){return G(t*(O/(this._pointLabels.length||1))+$(this.options.startAngle||0))}getDistanceFromCenterForValue(t){if(s(t))return NaN;const e=this.drawingArea/(this.max-this.min);return this.options.reverse?(this.max-t)*e:(t-this.min)*e}getValueForDistanceFromCenter(t){if(s(t))return NaN;const e=t/(this.drawingArea/(this.max-this.min));return this.options.reverse?this.max-e:this.min+e}getPointLabelContext(t){const e=this._pointLabels||[];if(t>=0&&t=0;n--){const e=t._pointLabelItems[n];if(!e.visible)continue;const o=s.setContext(t.getPointLabelContext(n));To(i,o,e);const a=Si(o.font),{x:r,y:l,textAlign:h}=e;Ne(i,t._pointLabels[n],r,l+a.lineHeight/2,a,{color:o.color,textAlign:h,textBaseline:"middle"})}}(this,o),s.display&&this.ticks.forEach(((t,e)=>{if(0!==e){r=this.getDistanceFromCenterForValue(t.value);const i=this.getContext(e),a=s.setContext(i),l=n.setContext(i);!function(t,e,i,s,n){const o=t.ctx,a=e.circular,{color:r,lineWidth:l}=e;!a&&!s||!r||!l||i<0||(o.save(),o.strokeStyle=r,o.lineWidth=l,o.setLineDash(n.dash),o.lineDashOffset=n.dashOffset,o.beginPath(),Lo(t,i,a,s),o.closePath(),o.stroke(),o.restore())}(this,a,r,o,l)}})),i.display){for(t.save(),a=o-1;a>=0;a--){const s=i.setContext(this.getPointLabelContext(a)),{color:n,lineWidth:o}=s;o&&n&&(t.lineWidth=o,t.strokeStyle=n,t.setLineDash(s.borderDash),t.lineDashOffset=s.borderDashOffset,r=this.getDistanceFromCenterForValue(e.ticks.reverse?this.min:this.max),l=this.getPointPosition(a,r),t.beginPath(),t.moveTo(this.xCenter,this.yCenter),t.lineTo(l.x,l.y),t.stroke())}t.restore()}}drawBorder(){}drawLabels(){const t=this.ctx,e=this.options,i=e.ticks;if(!i.display)return;const s=this.getIndexAngle(0);let n,o;t.save(),t.translate(this.xCenter,this.yCenter),t.rotate(s),t.textAlign="center",t.textBaseline="middle",this.ticks.forEach(((s,a)=>{if(0===a&&!e.reverse)return;const r=i.setContext(this.getContext(a)),l=Si(r.font);if(n=this.getDistanceFromCenterForValue(this.ticks[a].value),r.showLabelBackdrop){t.font=l.string,o=t.measureText(s.label).width,t.fillStyle=r.backdropColor;const e=ki(r.backdropPadding);t.fillRect(-o/2-e.left,-n-l.size/2-e.top,o+e.width,l.size+e.height)}Ne(t,s.label,0,-n,l,{color:r.color,strokeColor:r.textStrokeColor,strokeWidth:r.textStrokeWidth})})),t.restore()}drawTitle(){}}const Ro={millisecond:{common:!0,size:1,steps:1e3},second:{common:!0,size:1e3,steps:60},minute:{common:!0,size:6e4,steps:60},hour:{common:!0,size:36e5,steps:24},day:{common:!0,size:864e5,steps:30},week:{common:!1,size:6048e5,steps:4},month:{common:!0,size:2628e6,steps:12},quarter:{common:!1,size:7884e6,steps:4},year:{common:!0,size:3154e7}},Io=Object.keys(Ro);function zo(t,e){return t-e}function Fo(t,e){if(s(e))return null;const i=t._adapter,{parser:n,round:o,isoWeekday:r}=t._parseOpts;let l=e;return"function"==typeof n&&(l=n(l)),a(l)||(l="string"==typeof n?i.parse(l,n):i.parse(l)),null===l?null:(o&&(l="week"!==o||!N(r)&&!0!==r?i.startOf(l,o):i.startOf(l,"isoWeek",r)),+l)}function Vo(t,e,i,s){const n=Io.length;for(let o=Io.indexOf(t);o=e?i[s]:i[n]]=!0}}else t[e]=!0}function Wo(t,e,i){const s=[],n={},o=e.length;let a,r;for(a=0;a=0&&(e[l].major=!0);return e}(t,s,n,i):s}class No extends Js{static id="time";static defaults={bounds:"data",adapters:{},time:{parser:!1,unit:!1,round:!1,isoWeekday:!1,minUnit:"millisecond",displayFormats:{}},ticks:{source:"auto",callback:!1,major:{enabled:!1}}};constructor(t){super(t),this._cache={data:[],labels:[],all:[]},this._unit="day",this._majorUnit=void 0,this._offsets={},this._normalized=!1,this._parseOpts=void 0}init(t,e={}){const i=t.time||(t.time={}),s=this._adapter=new Rn._date(t.adapters.date);s.init(e),x(i.displayFormats,s.formats()),this._parseOpts={parser:i.parser,round:i.round,isoWeekday:i.isoWeekday},super.init(t),this._normalized=e.normalized}parse(t,e){return void 0===t?null:Fo(this,t)}beforeLayout(){super.beforeLayout(),this._cache={data:[],labels:[],all:[]}}determineDataLimits(){const t=this.options,e=this._adapter,i=t.time.unit||"day";let{min:s,max:n,minDefined:o,maxDefined:r}=this.getUserBounds();function l(t){o||isNaN(t.min)||(s=Math.min(s,t.min)),r||isNaN(t.max)||(n=Math.max(n,t.max))}o&&r||(l(this._getLabelBounds()),"ticks"===t.bounds&&"labels"===t.ticks.source||l(this.getMinMax(!1))),s=a(s)&&!isNaN(s)?s:+e.startOf(Date.now(),i),n=a(n)&&!isNaN(n)?n:+e.endOf(Date.now(),i)+1,this.min=Math.min(s,n-1),this.max=Math.max(s+1,n)}_getLabelBounds(){const t=this.getLabelTimestamps();let e=Number.POSITIVE_INFINITY,i=Number.NEGATIVE_INFINITY;return t.length&&(e=t[0],i=t[t.length-1]),{min:e,max:i}}buildTicks(){const t=this.options,e=t.time,i=t.ticks,s="labels"===i.source?this.getLabelTimestamps():this._generate();"ticks"===t.bounds&&s.length&&(this.min=this._userMin||s[0],this.max=this._userMax||s[s.length-1]);const n=this.min,o=nt(s,n,this.max);return this._unit=e.unit||(i.autoSkip?Vo(e.minUnit,this.min,this.max,this._getLabelCapacity(n)):function(t,e,i,s,n){for(let o=Io.length-1;o>=Io.indexOf(i);o--){const i=Io[o];if(Ro[i].common&&t._adapter.diff(n,s,i)>=e-1)return i}return Io[i?Io.indexOf(i):0]}(this,o.length,e.minUnit,this.min,this.max)),this._majorUnit=i.major.enabled&&"year"!==this._unit?function(t){for(let e=Io.indexOf(t)+1,i=Io.length;e+t.value)))}initOffsets(t=[]){let e,i,s=0,n=0;this.options.offset&&t.length&&(e=this.getDecimalForValue(t[0]),s=1===t.length?1-e:(this.getDecimalForValue(t[1])-e)/2,i=this.getDecimalForValue(t[t.length-1]),n=1===t.length?i:(i-this.getDecimalForValue(t[t.length-2]))/2);const o=t.length<3?.5:.25;s=J(s,0,o),n=J(n,0,o),this._offsets={start:s,end:n,factor:1/(s+1+n)}}_generate(){const t=this._adapter,e=this.min,i=this.max,s=this.options,n=s.time,o=n.unit||Vo(n.minUnit,e,i,this._getLabelCapacity(e)),a=l(s.ticks.stepSize,1),r="week"===o&&n.isoWeekday,h=N(r)||!0===r,c={};let d,u,f=e;if(h&&(f=+t.startOf(f,"isoWeek",r)),f=+t.startOf(f,h?"day":o),t.diff(i,e,o)>1e5*a)throw new Error(e+" and "+i+" are too far apart with stepSize of "+a+" "+o);const g="data"===s.ticks.source&&this.getDataTimestamps();for(d=f,u=0;d+t))}getLabelForValue(t){const e=this._adapter,i=this.options.time;return i.tooltipFormat?e.format(t,i.tooltipFormat):e.format(t,i.displayFormats.datetime)}format(t,e){const i=this.options.time.displayFormats,s=this._unit,n=e||i[s];return this._adapter.format(t,n)}_tickFormatFunction(t,e,i,s){const n=this.options,o=n.ticks.callback;if(o)return d(o,[t,e,i],this);const a=n.time.displayFormats,r=this._unit,l=this._majorUnit,h=r&&a[r],c=l&&a[l],u=i[e],f=l&&c&&u&&u.major;return this._adapter.format(t,s||(f?c:h))}generateTickLabels(t){let e,i,s;for(e=0,i=t.length;e0?a:1}getDataTimestamps(){let t,e,i=this._cache.data||[];if(i.length)return i;const s=this.getMatchingVisibleMetas();if(this._normalized&&s.length)return this._cache.data=s[0].controller.getAllParsedValues(this);for(t=0,e=s.length;t=t[r].pos&&e<=t[l].pos&&({lo:r,hi:l}=it(t,"pos",e)),({pos:s,time:o}=t[r]),({pos:n,time:a}=t[l])):(e>=t[r].time&&e<=t[l].time&&({lo:r,hi:l}=it(t,"time",e)),({time:s,pos:o}=t[r]),({time:n,pos:a}=t[l]));const h=n-s;return h?o+(a-o)*(e-s)/h:o}var jo=Object.freeze({__proto__:null,CategoryScale:class extends Js{static id="category";static defaults={ticks:{callback:po}};constructor(t){super(t),this._startValue=void 0,this._valueRange=0,this._addedLabels=[]}init(t){const e=this._addedLabels;if(e.length){const t=this.getLabels();for(const{index:i,label:s}of e)t[i]===s&&t.splice(i,1);this._addedLabels=[]}super.init(t)}parse(t,e){if(s(t))return null;const i=this.getLabels();return((t,e)=>null===t?null:J(Math.round(t),0,e))(e=isFinite(e)&&i[e]===t?e:go(i,t,l(e,t),this._addedLabels),i.length-1)}determineDataLimits(){const{minDefined:t,maxDefined:e}=this.getUserBounds();let{min:i,max:s}=this.getMinMax(!0);"ticks"===this.options.bounds&&(t||(i=0),e||(s=this.getLabels().length-1)),this.min=i,this.max=s}buildTicks(){const t=this.min,e=this.max,i=this.options.offset,s=[];let n=this.getLabels();n=0===t&&e===n.length-1?n:n.slice(t,e+1),this._valueRange=Math.max(n.length-(i?0:1),1),this._startValue=this.min-(i?.5:0);for(let i=t;i<=e;i++)s.push({value:i});return s}getLabelForValue(t){return po.call(this,t)}configure(){super.configure(),this.isHorizontal()||(this._reversePixels=!this._reversePixels)}getPixelForValue(t){return"number"!=typeof t&&(t=this.parse(t)),null===t?NaN:this.getPixelForDecimal((t-this._startValue)/this._valueRange)}getPixelForTick(t){const e=this.ticks;return t<0||t>e.length-1?null:this.getPixelForValue(e[t].value)}getValueForPixel(t){return Math.round(this._startValue+this.getDecimalForPixel(t)*this._valueRange)}getBasePixel(){return this.bottom}},LinearScale:xo,LogarithmicScale:ko,RadialLinearScale:Eo,TimeScale:No,TimeSeriesScale:class extends No{static id="timeseries";static defaults=No.defaults;constructor(t){super(t),this._table=[],this._minPos=void 0,this._tableRange=void 0}initOffsets(){const t=this._getTimestampsForTable(),e=this._table=this.buildLookupTable(t);this._minPos=Ho(e,this.min),this._tableRange=Ho(e,this.max)-this._minPos,super.initOffsets(t)}buildLookupTable(t){const{min:e,max:i}=this,s=[],n=[];let o,a,r,l,h;for(o=0,a=t.length;o=e&&l<=i&&s.push(l);if(s.length<2)return[{time:e,pos:0},{time:i,pos:1}];for(o=0,a=s.length;ot-e))}_getTimestampsForTable(){let t=this._cache.all||[];if(t.length)return t;const e=this.getDataTimestamps(),i=this.getLabelTimestamps();return t=e.length&&i.length?this.normalize(e.concat(i)):e.length?e:i,t=this._cache.all=t,t}getDecimalForValue(t){return(Ho(this._table,t)-this._minPos)/this._tableRange}getValueForPixel(t){const e=this._offsets,i=this.getDecimalForPixel(t)/e.factor-e.end;return Ho(this._table,i*this._tableRange+this._minPos,!0)}}});const $o=["rgb(54, 162, 235)","rgb(255, 99, 132)","rgb(255, 159, 64)","rgb(255, 205, 86)","rgb(75, 192, 192)","rgb(153, 102, 255)","rgb(201, 203, 207)"],Yo=$o.map((t=>t.replace("rgb(","rgba(").replace(")",", 0.5)")));function Uo(t){return $o[t%$o.length]}function Xo(t){return Yo[t%Yo.length]}function qo(t){let e=0;return(i,s)=>{const n=t.getDatasetMeta(s).controller;n instanceof jn?e=function(t,e){return t.backgroundColor=t.data.map((()=>Uo(e++))),e}(i,e):n instanceof $n?e=function(t,e){return t.backgroundColor=t.data.map((()=>Xo(e++))),e}(i,e):n&&(e=function(t,e){return t.borderColor=Uo(e),t.backgroundColor=Xo(e),++e}(i,e))}}function Ko(t){let e;for(e in t)if(t[e].borderColor||t[e].backgroundColor)return!0;return!1}var Go={id:"colors",defaults:{enabled:!0,forceOverride:!1},beforeLayout(t,e,i){if(!i.enabled)return;const{data:{datasets:s},options:n}=t.config,{elements:o}=n;if(!i.forceOverride&&(Ko(s)||(a=n)&&(a.borderColor||a.backgroundColor)||o&&Ko(o)))return;var a;const r=qo(t);s.forEach(r)}};function Zo(t){if(t._decimated){const e=t._data;delete t._decimated,delete t._data,Object.defineProperty(t,"data",{configurable:!0,enumerable:!0,writable:!0,value:e})}}function Jo(t){t.data.datasets.forEach((t=>{Zo(t)}))}var Qo={id:"decimation",defaults:{algorithm:"min-max",enabled:!1},beforeElementsUpdate:(t,e,i)=>{if(!i.enabled)return void Jo(t);const n=t.width;t.data.datasets.forEach(((e,o)=>{const{_data:a,indexAxis:r}=e,l=t.getDatasetMeta(o),h=a||e.data;if("y"===Pi([r,t.options.indexAxis]))return;if(!l.controller.supportsDecimation)return;const c=t.scales[l.xAxisID];if("linear"!==c.type&&"time"!==c.type)return;if(t.options.parsing)return;let{start:d,count:u}=function(t,e){const i=e.length;let s,n=0;const{iScale:o}=t,{min:a,max:r,minDefined:l,maxDefined:h}=o.getUserBounds();return l&&(n=J(it(e,o.axis,a).lo,0,i-1)),s=h?J(it(e,o.axis,r).hi+1,n,i)-n:i-n,{start:n,count:s}}(l,h);if(u<=(i.threshold||4*n))return void Zo(e);let f;switch(s(a)&&(e._data=h,delete e.data,Object.defineProperty(e,"data",{configurable:!0,enumerable:!0,get:function(){return this._decimated},set:function(t){this._data=t}})),i.algorithm){case"lttb":f=function(t,e,i,s,n){const o=n.samples||s;if(o>=i)return t.slice(e,e+i);const a=[],r=(i-2)/(o-2);let l=0;const h=e+i-1;let c,d,u,f,g,p=e;for(a[l++]=t[p],c=0;cu&&(u=f,d=t[s],g=s);a[l++]=d,p=g}return a[l++]=t[h],a}(h,d,u,n,i);break;case"min-max":f=function(t,e,i,n){let o,a,r,l,h,c,d,u,f,g,p=0,m=0;const b=[],x=e+i-1,_=t[e].x,y=t[x].x-_;for(o=e;og&&(g=l,d=o),p=(m*p+a.x)/++m;else{const i=o-1;if(!s(c)&&!s(d)){const e=Math.min(c,d),s=Math.max(c,d);e!==u&&e!==i&&b.push({...t[e],x:p}),s!==u&&s!==i&&b.push({...t[s],x:p})}o>0&&i!==u&&b.push(t[i]),b.push(a),h=e,m=0,f=g=l,c=d=u=o}}return b}(h,d,u,n);break;default:throw new Error(`Unsupported decimation algorithm '${i.algorithm}'`)}e._decimated=f}))},destroy(t){Jo(t)}};function ta(t,e,i,s){if(s)return;let n=e[t],o=i[t];return"angle"===t&&(n=G(n),o=G(o)),{property:t,start:n,end:o}}function ea(t,e,i){for(;e>t;e--){const t=i[e];if(!isNaN(t.x)&&!isNaN(t.y))break}return e}function ia(t,e,i,s){return t&&e?s(t[i],e[i]):t?t[i]:e?e[i]:0}function sa(t,e){let i=[],s=!1;return n(t)?(s=!0,i=t):i=function(t,e){const{x:i=null,y:s=null}=t||{},n=e.points,o=[];return e.segments.forEach((({start:t,end:e})=>{e=ea(t,e,n);const a=n[t],r=n[e];null!==s?(o.push({x:a.x,y:s}),o.push({x:r.x,y:s})):null!==i&&(o.push({x:i,y:a.y}),o.push({x:i,y:r.y}))})),o}(t,e),i.length?new no({points:i,options:{tension:0},_loop:s,_fullLoop:s}):null}function na(t){return t&&!1!==t.fill}function oa(t,e,i){let s=t[e].fill;const n=[e];let o;if(!i)return s;for(;!1!==s&&-1===n.indexOf(s);){if(!a(s))return s;if(o=t[s],!o)return!1;if(o.visible)return s;n.push(s),s=o.fill}return!1}function aa(t,e,i){const s=function(t){const e=t.options,i=e.fill;let s=l(i&&i.target,i);void 0===s&&(s=!!e.backgroundColor);if(!1===s||null===s)return!1;if(!0===s)return"origin";return s}(t);if(o(s))return!isNaN(s.value)&&s;let n=parseFloat(s);return a(n)&&Math.floor(n)===n?function(t,e,i,s){"-"!==t&&"+"!==t||(i=e+i);if(i===e||i<0||i>=s)return!1;return i}(s[0],e,n,i):["origin","start","end","stack","shape"].indexOf(s)>=0&&s}function ra(t,e,i){const s=[];for(let n=0;n=0;--e){const i=n[e].$filler;i&&(i.line.updateControlPoints(o,i.axis),s&&i.fill&&da(t.ctx,i,o))}},beforeDatasetsDraw(t,e,i){if("beforeDatasetsDraw"!==i.drawTime)return;const s=t.getSortedVisibleDatasetMetas();for(let e=s.length-1;e>=0;--e){const i=s[e].$filler;na(i)&&da(t.ctx,i,t.chartArea)}},beforeDatasetDraw(t,e,i){const s=e.meta.$filler;na(s)&&"beforeDatasetDraw"===i.drawTime&&da(t.ctx,s,t.chartArea)},defaults:{propagate:!0,drawTime:"beforeDatasetDraw"}};const ba=(t,e)=>{let{boxHeight:i=e,boxWidth:s=e}=t;return t.usePointStyle&&(i=Math.min(i,e),s=t.pointStyleWidth||Math.min(s,e)),{boxWidth:s,boxHeight:i,itemHeight:Math.max(e,i)}};class xa extends Hs{constructor(t){super(),this._added=!1,this.legendHitBoxes=[],this._hoveredItem=null,this.doughnutMode=!1,this.chart=t.chart,this.options=t.options,this.ctx=t.ctx,this.legendItems=void 0,this.columnSizes=void 0,this.lineWidths=void 0,this.maxHeight=void 0,this.maxWidth=void 0,this.top=void 0,this.bottom=void 0,this.left=void 0,this.right=void 0,this.height=void 0,this.width=void 0,this._margins=void 0,this.position=void 0,this.weight=void 0,this.fullSize=void 0}update(t,e,i){this.maxWidth=t,this.maxHeight=e,this._margins=i,this.setDimensions(),this.buildLabels(),this.fit()}setDimensions(){this.isHorizontal()?(this.width=this.maxWidth,this.left=this._margins.left,this.right=this.width):(this.height=this.maxHeight,this.top=this._margins.top,this.bottom=this.height)}buildLabels(){const t=this.options.labels||{};let e=d(t.generateLabels,[this.chart],this)||[];t.filter&&(e=e.filter((e=>t.filter(e,this.chart.data)))),t.sort&&(e=e.sort(((e,i)=>t.sort(e,i,this.chart.data)))),this.options.reverse&&e.reverse(),this.legendItems=e}fit(){const{options:t,ctx:e}=this;if(!t.display)return void(this.width=this.height=0);const i=t.labels,s=Si(i.font),n=s.size,o=this._computeTitleHeight(),{boxWidth:a,itemHeight:r}=ba(i,n);let l,h;e.font=s.string,this.isHorizontal()?(l=this.maxWidth,h=this._fitRows(o,n,a,r)+10):(h=this.maxHeight,l=this._fitCols(o,s,a,r)+10),this.width=Math.min(l,t.maxWidth||this.maxWidth),this.height=Math.min(h,t.maxHeight||this.maxHeight)}_fitRows(t,e,i,s){const{ctx:n,maxWidth:o,options:{labels:{padding:a}}}=this,r=this.legendHitBoxes=[],l=this.lineWidths=[0],h=s+a;let c=t;n.textAlign="left",n.textBaseline="middle";let d=-1,u=-h;return this.legendItems.forEach(((t,f)=>{const g=i+e/2+n.measureText(t.text).width;(0===f||l[l.length-1]+g+2*a>o)&&(c+=h,l[l.length-(f>0?0:1)]=0,u+=h,d++),r[f]={left:0,top:u,row:d,width:g,height:s},l[l.length-1]+=g+a})),c}_fitCols(t,e,i,s){const{ctx:n,maxHeight:o,options:{labels:{padding:a}}}=this,r=this.legendHitBoxes=[],l=this.columnSizes=[],h=o-t;let c=a,d=0,u=0,f=0,g=0;return this.legendItems.forEach(((t,o)=>{const{itemWidth:p,itemHeight:m}=function(t,e,i,s,n){const o=function(t,e,i,s){let n=t.text;n&&"string"!=typeof n&&(n=n.reduce(((t,e)=>t.length>e.length?t:e)));return e+i.size/2+s.measureText(n).width}(s,t,e,i),a=function(t,e,i){let s=t;"string"!=typeof e.text&&(s=_a(e,i));return s}(n,s,e.lineHeight);return{itemWidth:o,itemHeight:a}}(i,e,n,t,s);o>0&&u+m+2*a>h&&(c+=d+a,l.push({width:d,height:u}),f+=d+a,g++,d=u=0),r[o]={left:f,top:u,col:g,width:p,height:m},d=Math.max(d,p),u+=m+a})),c+=d,l.push({width:d,height:u}),c}adjustHitBoxes(){if(!this.options.display)return;const t=this._computeTitleHeight(),{legendHitBoxes:e,options:{align:i,labels:{padding:s},rtl:n}}=this,o=Oi(n,this.left,this.width);if(this.isHorizontal()){let n=0,a=ft(i,this.left+s,this.right-this.lineWidths[n]);for(const r of e)n!==r.row&&(n=r.row,a=ft(i,this.left+s,this.right-this.lineWidths[n])),r.top+=this.top+t+s,r.left=o.leftForLtr(o.x(a),r.width),a+=r.width+s}else{let n=0,a=ft(i,this.top+t+s,this.bottom-this.columnSizes[n].height);for(const r of e)r.col!==n&&(n=r.col,a=ft(i,this.top+t+s,this.bottom-this.columnSizes[n].height)),r.top=a,r.left+=this.left+s,r.left=o.leftForLtr(o.x(r.left),r.width),a+=r.height+s}}isHorizontal(){return"top"===this.options.position||"bottom"===this.options.position}draw(){if(this.options.display){const t=this.ctx;Ie(t,this),this._draw(),ze(t)}}_draw(){const{options:t,columnSizes:e,lineWidths:i,ctx:s}=this,{align:n,labels:o}=t,a=ue.color,r=Oi(t.rtl,this.left,this.width),h=Si(o.font),{padding:c}=o,d=h.size,u=d/2;let f;this.drawTitle(),s.textAlign=r.textAlign("left"),s.textBaseline="middle",s.lineWidth=.5,s.font=h.string;const{boxWidth:g,boxHeight:p,itemHeight:m}=ba(o,d),b=this.isHorizontal(),x=this._computeTitleHeight();f=b?{x:ft(n,this.left+c,this.right-i[0]),y:this.top+c+x,line:0}:{x:this.left+c,y:ft(n,this.top+x+c,this.bottom-e[0].height),line:0},Ai(this.ctx,t.textDirection);const _=m+c;this.legendItems.forEach(((y,v)=>{s.strokeStyle=y.fontColor,s.fillStyle=y.fontColor;const M=s.measureText(y.text).width,w=r.textAlign(y.textAlign||(y.textAlign=o.textAlign)),k=g+u+M;let S=f.x,P=f.y;r.setWidth(this.width),b?v>0&&S+k+c>this.right&&(P=f.y+=_,f.line++,S=f.x=ft(n,this.left+c,this.right-i[f.line])):v>0&&P+_>this.bottom&&(S=f.x=S+e[f.line].width+c,f.line++,P=f.y=ft(n,this.top+x+c,this.bottom-e[f.line].height));if(function(t,e,i){if(isNaN(g)||g<=0||isNaN(p)||p<0)return;s.save();const n=l(i.lineWidth,1);if(s.fillStyle=l(i.fillStyle,a),s.lineCap=l(i.lineCap,"butt"),s.lineDashOffset=l(i.lineDashOffset,0),s.lineJoin=l(i.lineJoin,"miter"),s.lineWidth=n,s.strokeStyle=l(i.strokeStyle,a),s.setLineDash(l(i.lineDash,[])),o.usePointStyle){const a={radius:p*Math.SQRT2/2,pointStyle:i.pointStyle,rotation:i.rotation,borderWidth:n},l=r.xPlus(t,g/2);Ee(s,a,l,e+u,o.pointStyleWidth&&g)}else{const o=e+Math.max((d-p)/2,0),a=r.leftForLtr(t,g),l=wi(i.borderRadius);s.beginPath(),Object.values(l).some((t=>0!==t))?He(s,{x:a,y:o,w:g,h:p,radius:l}):s.rect(a,o,g,p),s.fill(),0!==n&&s.stroke()}s.restore()}(r.x(S),P,y),S=gt(w,S+g+u,b?S+k:this.right,t.rtl),function(t,e,i){Ne(s,i.text,t,e+m/2,h,{strikethrough:i.hidden,textAlign:r.textAlign(i.textAlign)})}(r.x(S),P,y),b)f.x+=k+c;else if("string"!=typeof y.text){const t=h.lineHeight;f.y+=_a(y,t)+c}else f.y+=_})),Ti(this.ctx,t.textDirection)}drawTitle(){const t=this.options,e=t.title,i=Si(e.font),s=ki(e.padding);if(!e.display)return;const n=Oi(t.rtl,this.left,this.width),o=this.ctx,a=e.position,r=i.size/2,l=s.top+r;let h,c=this.left,d=this.width;if(this.isHorizontal())d=Math.max(...this.lineWidths),h=this.top+l,c=ft(t.align,c,this.right-d);else{const e=this.columnSizes.reduce(((t,e)=>Math.max(t,e.height)),0);h=l+ft(t.align,this.top,this.bottom-e-t.labels.padding-this._computeTitleHeight())}const u=ft(a,c,c+d);o.textAlign=n.textAlign(ut(a)),o.textBaseline="middle",o.strokeStyle=e.color,o.fillStyle=e.color,o.font=i.string,Ne(o,e.text,u,h,i)}_computeTitleHeight(){const t=this.options.title,e=Si(t.font),i=ki(t.padding);return t.display?e.lineHeight+i.height:0}_getLegendItemAt(t,e){let i,s,n;if(tt(t,this.left,this.right)&&tt(e,this.top,this.bottom))for(n=this.legendHitBoxes,i=0;it.chart.options.color,boxWidth:40,padding:10,generateLabels(t){const e=t.data.datasets,{labels:{usePointStyle:i,pointStyle:s,textAlign:n,color:o,useBorderRadius:a,borderRadius:r}}=t.legend.options;return t._getSortedDatasetMetas().map((t=>{const l=t.controller.getStyle(i?0:void 0),h=ki(l.borderWidth);return{text:e[t.index].label,fillStyle:l.backgroundColor,fontColor:o,hidden:!t.visible,lineCap:l.borderCapStyle,lineDash:l.borderDash,lineDashOffset:l.borderDashOffset,lineJoin:l.borderJoinStyle,lineWidth:(h.width+h.height)/4,strokeStyle:l.borderColor,pointStyle:s||l.pointStyle,rotation:l.rotation,textAlign:n||l.textAlign,borderRadius:a&&(r||l.borderRadius),datasetIndex:t.index}}),this)}},title:{color:t=>t.chart.options.color,display:!1,position:"center",text:""}},descriptors:{_scriptable:t=>!t.startsWith("on"),labels:{_scriptable:t=>!["generateLabels","filter","sort"].includes(t)}}};class va extends Hs{constructor(t){super(),this.chart=t.chart,this.options=t.options,this.ctx=t.ctx,this._padding=void 0,this.top=void 0,this.bottom=void 0,this.left=void 0,this.right=void 0,this.width=void 0,this.height=void 0,this.position=void 0,this.weight=void 0,this.fullSize=void 0}update(t,e){const i=this.options;if(this.left=0,this.top=0,!i.display)return void(this.width=this.height=this.right=this.bottom=0);this.width=this.right=t,this.height=this.bottom=e;const s=n(i.text)?i.text.length:1;this._padding=ki(i.padding);const o=s*Si(i.font).lineHeight+this._padding.height;this.isHorizontal()?this.height=o:this.width=o}isHorizontal(){const t=this.options.position;return"top"===t||"bottom"===t}_drawArgs(t){const{top:e,left:i,bottom:s,right:n,options:o}=this,a=o.align;let r,l,h,c=0;return this.isHorizontal()?(l=ft(a,i,n),h=e+t,r=n-i):("left"===o.position?(l=i+t,h=ft(a,s,e),c=-.5*C):(l=n-t,h=ft(a,e,s),c=.5*C),r=s-e),{titleX:l,titleY:h,maxWidth:r,rotation:c}}draw(){const t=this.ctx,e=this.options;if(!e.display)return;const i=Si(e.font),s=i.lineHeight/2+this._padding.top,{titleX:n,titleY:o,maxWidth:a,rotation:r}=this._drawArgs(s);Ne(t,e.text,0,0,i,{color:e.color,maxWidth:a,rotation:r,textAlign:ut(e.align),textBaseline:"middle",translation:[n,o]})}}var Ma={id:"title",_element:va,start(t,e,i){!function(t,e){const i=new va({ctx:t.ctx,options:e,chart:t});as.configure(t,i,e),as.addBox(t,i),t.titleBlock=i}(t,i)},stop(t){const e=t.titleBlock;as.removeBox(t,e),delete t.titleBlock},beforeUpdate(t,e,i){const s=t.titleBlock;as.configure(t,s,i),s.options=i},defaults:{align:"center",display:!1,font:{weight:"bold"},fullSize:!0,padding:10,position:"top",text:"",weight:2e3},defaultRoutes:{color:"color"},descriptors:{_scriptable:!0,_indexable:!1}};const wa=new WeakMap;var ka={id:"subtitle",start(t,e,i){const s=new va({ctx:t.ctx,options:i,chart:t});as.configure(t,s,i),as.addBox(t,s),wa.set(t,s)},stop(t){as.removeBox(t,wa.get(t)),wa.delete(t)},beforeUpdate(t,e,i){const s=wa.get(t);as.configure(t,s,i),s.options=i},defaults:{align:"center",display:!1,font:{weight:"normal"},fullSize:!0,padding:0,position:"top",text:"",weight:1500},defaultRoutes:{color:"color"},descriptors:{_scriptable:!0,_indexable:!1}};const Sa={average(t){if(!t.length)return!1;let e,i,s=0,n=0,o=0;for(e=0,i=t.length;e-1?t.split("\n"):t}function Ca(t,e){const{element:i,datasetIndex:s,index:n}=e,o=t.getDatasetMeta(s).controller,{label:a,value:r}=o.getLabelAndValue(n);return{chart:t,label:a,parsed:o.getParsed(n),raw:t.data.datasets[s].data[n],formattedValue:r,dataset:o.getDataset(),dataIndex:n,datasetIndex:s,element:i}}function Oa(t,e){const i=t.chart.ctx,{body:s,footer:n,title:o}=t,{boxWidth:a,boxHeight:r}=e,l=Si(e.bodyFont),h=Si(e.titleFont),c=Si(e.footerFont),d=o.length,f=n.length,g=s.length,p=ki(e.padding);let m=p.height,b=0,x=s.reduce(((t,e)=>t+e.before.length+e.lines.length+e.after.length),0);if(x+=t.beforeBody.length+t.afterBody.length,d&&(m+=d*h.lineHeight+(d-1)*e.titleSpacing+e.titleMarginBottom),x){m+=g*(e.displayColors?Math.max(r,l.lineHeight):l.lineHeight)+(x-g)*l.lineHeight+(x-1)*e.bodySpacing}f&&(m+=e.footerMarginTop+f*c.lineHeight+(f-1)*e.footerSpacing);let _=0;const y=function(t){b=Math.max(b,i.measureText(t).width+_)};return i.save(),i.font=h.string,u(t.title,y),i.font=l.string,u(t.beforeBody.concat(t.afterBody),y),_=e.displayColors?a+2+e.boxPadding:0,u(s,(t=>{u(t.before,y),u(t.lines,y),u(t.after,y)})),_=0,i.font=c.string,u(t.footer,y),i.restore(),b+=p.width,{width:b,height:m}}function Aa(t,e,i,s){const{x:n,width:o}=i,{width:a,chartArea:{left:r,right:l}}=t;let h="center";return"center"===s?h=n<=(r+l)/2?"left":"right":n<=o/2?h="left":n>=a-o/2&&(h="right"),function(t,e,i,s){const{x:n,width:o}=s,a=i.caretSize+i.caretPadding;return"left"===t&&n+o+a>e.width||"right"===t&&n-o-a<0||void 0}(h,t,e,i)&&(h="center"),h}function Ta(t,e,i){const s=i.yAlign||e.yAlign||function(t,e){const{y:i,height:s}=e;return it.height-s/2?"bottom":"center"}(t,i);return{xAlign:i.xAlign||e.xAlign||Aa(t,e,i,s),yAlign:s}}function La(t,e,i,s){const{caretSize:n,caretPadding:o,cornerRadius:a}=t,{xAlign:r,yAlign:l}=i,h=n+o,{topLeft:c,topRight:d,bottomLeft:u,bottomRight:f}=wi(a);let g=function(t,e){let{x:i,width:s}=t;return"right"===e?i-=s:"center"===e&&(i-=s/2),i}(e,r);const p=function(t,e,i){let{y:s,height:n}=t;return"top"===e?s+=i:s-="bottom"===e?n+i:n/2,s}(e,l,h);return"center"===l?"left"===r?g+=h:"right"===r&&(g-=h):"left"===r?g-=Math.max(c,u)+n:"right"===r&&(g+=Math.max(d,f)+n),{x:J(g,0,s.width-e.width),y:J(p,0,s.height-e.height)}}function Ea(t,e,i){const s=ki(i.padding);return"center"===e?t.x+t.width/2:"right"===e?t.x+t.width-s.right:t.x+s.left}function Ra(t){return Pa([],Da(t))}function Ia(t,e){const i=e&&e.dataset&&e.dataset.tooltip&&e.dataset.tooltip.callbacks;return i?t.override(i):t}const za={beforeTitle:e,title(t){if(t.length>0){const e=t[0],i=e.chart.data.labels,s=i?i.length:0;if(this&&this.options&&"dataset"===this.options.mode)return e.dataset.label||"";if(e.label)return e.label;if(s>0&&e.dataIndex{const e={before:[],lines:[],after:[]},n=Ia(i,t);Pa(e.before,Da(Fa(n,"beforeLabel",this,t))),Pa(e.lines,Fa(n,"label",this,t)),Pa(e.after,Da(Fa(n,"afterLabel",this,t))),s.push(e)})),s}getAfterBody(t,e){return Ra(Fa(e.callbacks,"afterBody",this,t))}getFooter(t,e){const{callbacks:i}=e,s=Fa(i,"beforeFooter",this,t),n=Fa(i,"footer",this,t),o=Fa(i,"afterFooter",this,t);let a=[];return a=Pa(a,Da(s)),a=Pa(a,Da(n)),a=Pa(a,Da(o)),a}_createItems(t){const e=this._active,i=this.chart.data,s=[],n=[],o=[];let a,r,l=[];for(a=0,r=e.length;at.filter(e,s,n,i)))),t.itemSort&&(l=l.sort(((e,s)=>t.itemSort(e,s,i)))),u(l,(e=>{const i=Ia(t.callbacks,e);s.push(Fa(i,"labelColor",this,e)),n.push(Fa(i,"labelPointStyle",this,e)),o.push(Fa(i,"labelTextColor",this,e))})),this.labelColors=s,this.labelPointStyles=n,this.labelTextColors=o,this.dataPoints=l,l}update(t,e){const i=this.options.setContext(this.getContext()),s=this._active;let n,o=[];if(s.length){const t=Sa[i.position].call(this,s,this._eventPosition);o=this._createItems(i),this.title=this.getTitle(o,i),this.beforeBody=this.getBeforeBody(o,i),this.body=this.getBody(o,i),this.afterBody=this.getAfterBody(o,i),this.footer=this.getFooter(o,i);const e=this._size=Oa(this,i),a=Object.assign({},t,e),r=Ta(this.chart,i,a),l=La(i,a,r,this.chart);this.xAlign=r.xAlign,this.yAlign=r.yAlign,n={opacity:1,x:l.x,y:l.y,width:e.width,height:e.height,caretX:t.x,caretY:t.y}}else 0!==this.opacity&&(n={opacity:0});this._tooltipItems=o,this.$context=void 0,n&&this._resolveAnimations().update(this,n),t&&i.external&&i.external.call(this,{chart:this.chart,tooltip:this,replay:e})}drawCaret(t,e,i,s){const n=this.getCaretPosition(t,i,s);e.lineTo(n.x1,n.y1),e.lineTo(n.x2,n.y2),e.lineTo(n.x3,n.y3)}getCaretPosition(t,e,i){const{xAlign:s,yAlign:n}=this,{caretSize:o,cornerRadius:a}=i,{topLeft:r,topRight:l,bottomLeft:h,bottomRight:c}=wi(a),{x:d,y:u}=t,{width:f,height:g}=e;let p,m,b,x,_,y;return"center"===n?(_=u+g/2,"left"===s?(p=d,m=p-o,x=_+o,y=_-o):(p=d+f,m=p+o,x=_-o,y=_+o),b=p):(m="left"===s?d+Math.max(r,h)+o:"right"===s?d+f-Math.max(l,c)-o:this.caretX,"top"===n?(x=u,_=x-o,p=m-o,b=m+o):(x=u+g,_=x+o,p=m+o,b=m-o),y=x),{x1:p,x2:m,x3:b,y1:x,y2:_,y3:y}}drawTitle(t,e,i){const s=this.title,n=s.length;let o,a,r;if(n){const l=Oi(i.rtl,this.x,this.width);for(t.x=Ea(this,i.titleAlign,i),e.textAlign=l.textAlign(i.titleAlign),e.textBaseline="middle",o=Si(i.titleFont),a=i.titleSpacing,e.fillStyle=i.titleColor,e.font=o.string,r=0;r0!==t))?(t.beginPath(),t.fillStyle=n.multiKeyBackground,He(t,{x:e,y:g,w:h,h:l,radius:r}),t.fill(),t.stroke(),t.fillStyle=a.backgroundColor,t.beginPath(),He(t,{x:i,y:g+1,w:h-2,h:l-2,radius:r}),t.fill()):(t.fillStyle=n.multiKeyBackground,t.fillRect(e,g,h,l),t.strokeRect(e,g,h,l),t.fillStyle=a.backgroundColor,t.fillRect(i,g+1,h-2,l-2))}t.fillStyle=this.labelTextColors[i]}drawBody(t,e,i){const{body:s}=this,{bodySpacing:n,bodyAlign:o,displayColors:a,boxHeight:r,boxWidth:l,boxPadding:h}=i,c=Si(i.bodyFont);let d=c.lineHeight,f=0;const g=Oi(i.rtl,this.x,this.width),p=function(i){e.fillText(i,g.x(t.x+f),t.y+d/2),t.y+=d+n},m=g.textAlign(o);let b,x,_,y,v,M,w;for(e.textAlign=o,e.textBaseline="middle",e.font=c.string,t.x=Ea(this,m,i),e.fillStyle=i.bodyColor,u(this.beforeBody,p),f=a&&"right"!==m?"center"===o?l/2+h:l+2+h:0,y=0,M=s.length;y0&&e.stroke()}_updateAnimationTarget(t){const e=this.chart,i=this.$animations,s=i&&i.x,n=i&&i.y;if(s||n){const i=Sa[t.position].call(this,this._active,this._eventPosition);if(!i)return;const o=this._size=Oa(this,t),a=Object.assign({},i,this._size),r=Ta(e,t,a),l=La(t,a,r,e);s._to===l.x&&n._to===l.y||(this.xAlign=r.xAlign,this.yAlign=r.yAlign,this.width=o.width,this.height=o.height,this.caretX=i.x,this.caretY=i.y,this._resolveAnimations().update(this,l))}}_willRender(){return!!this.opacity}draw(t){const e=this.options.setContext(this.getContext());let i=this.opacity;if(!i)return;this._updateAnimationTarget(e);const s={width:this.width,height:this.height},n={x:this.x,y:this.y};i=Math.abs(i)<.001?0:i;const o=ki(e.padding),a=this.title.length||this.beforeBody.length||this.body.length||this.afterBody.length||this.footer.length;e.enabled&&a&&(t.save(),t.globalAlpha=i,this.drawBackground(n,t,s,e),Ai(t,e.textDirection),n.y+=o.top,this.drawTitle(n,t,e),this.drawBody(n,t,e),this.drawFooter(n,t,e),Ti(t,e.textDirection),t.restore())}getActiveElements(){return this._active||[]}setActiveElements(t,e){const i=this._active,s=t.map((({datasetIndex:t,index:e})=>{const i=this.chart.getDatasetMeta(t);if(!i)throw new Error("Cannot find a dataset at index "+t);return{datasetIndex:t,element:i.data[e],index:e}})),n=!f(i,s),o=this._positionChanged(s,e);(n||o)&&(this._active=s,this._eventPosition=e,this._ignoreReplayEvents=!0,this.update(!0))}handleEvent(t,e,i=!0){if(e&&this._ignoreReplayEvents)return!1;this._ignoreReplayEvents=!1;const s=this.options,n=this._active||[],o=this._getActiveElements(t,n,e,i),a=this._positionChanged(o,t),r=e||!f(o,n)||a;return r&&(this._active=o,(s.enabled||s.external)&&(this._eventPosition={x:t.x,y:t.y},this.update(!0,e))),r}_getActiveElements(t,e,i,s){const n=this.options;if("mouseout"===t.type)return[];if(!s)return e.filter((t=>this.chart.data.datasets[t.datasetIndex]&&void 0!==this.chart.getDatasetMeta(t.datasetIndex).controller.getParsed(t.index)));const o=this.chart.getElementsAtEventForMode(t,n.mode,n,i);return n.reverse&&o.reverse(),o}_positionChanged(t,e){const{caretX:i,caretY:s,options:n}=this,o=Sa[n.position].call(this,t,e);return!1!==o&&(i!==o.x||s!==o.y)}}var Ba={id:"tooltip",_element:Va,positioners:Sa,afterInit(t,e,i){i&&(t.tooltip=new Va({chart:t,options:i}))},beforeUpdate(t,e,i){t.tooltip&&t.tooltip.initialize(i)},reset(t,e,i){t.tooltip&&t.tooltip.initialize(i)},afterDraw(t){const e=t.tooltip;if(e&&e._willRender()){const i={tooltip:e};if(!1===t.notifyPlugins("beforeTooltipDraw",{...i,cancelable:!0}))return;e.draw(t.ctx),t.notifyPlugins("afterTooltipDraw",i)}},afterEvent(t,e){if(t.tooltip){const i=e.replay;t.tooltip.handleEvent(e.event,i,e.inChartArea)&&(e.changed=!0)}},defaults:{enabled:!0,external:null,position:"average",backgroundColor:"rgba(0,0,0,0.8)",titleColor:"#fff",titleFont:{weight:"bold"},titleSpacing:2,titleMarginBottom:6,titleAlign:"left",bodyColor:"#fff",bodySpacing:2,bodyFont:{},bodyAlign:"left",footerColor:"#fff",footerSpacing:2,footerMarginTop:6,footerFont:{weight:"bold"},footerAlign:"left",padding:6,caretPadding:2,caretSize:5,cornerRadius:6,boxHeight:(t,e)=>e.bodyFont.size,boxWidth:(t,e)=>e.bodyFont.size,multiKeyBackground:"#fff",displayColors:!0,boxPadding:0,borderColor:"rgba(0,0,0,0)",borderWidth:0,animation:{duration:400,easing:"easeOutQuart"},animations:{numbers:{type:"number",properties:["x","y","width","height","caretX","caretY"]},opacity:{easing:"linear",duration:200}},callbacks:za},defaultRoutes:{bodyFont:"font",footerFont:"font",titleFont:"font"},descriptors:{_scriptable:t=>"filter"!==t&&"itemSort"!==t&&"external"!==t,_indexable:!1,callbacks:{_scriptable:!1,_indexable:!1},animation:{_fallback:!1},animations:{_fallback:"animation"}},additionalOptionScopes:["interaction"]};return An.register(Yn,jo,fo,t),An.helpers={...Wi},An._adapters=Rn,An.Animation=Cs,An.Animations=Os,An.animator=xt,An.controllers=en.controllers.items,An.DatasetController=Ns,An.Element=Hs,An.elements=fo,An.Interaction=Xi,An.layouts=as,An.platforms=Ss,An.Scale=Js,An.Ticks=ae,Object.assign(An,Yn,jo,fo,t,Ss),An.Chart=An,"undefined"!=typeof window&&(window.Chart=An),An})); +//# sourceMappingURL=chart.umd.js.map diff --git a/web/js/vendor/chartjs-adapter-date-fns.bundle.js b/web/js/vendor/chartjs-adapter-date-fns.bundle.js new file mode 100644 index 0000000..39c150e --- /dev/null +++ b/web/js/vendor/chartjs-adapter-date-fns.bundle.js @@ -0,0 +1,6322 @@ +(function (global, factory) { +typeof exports === 'object' && typeof module !== 'undefined' ? factory(require('chart.js')) : +typeof define === 'function' && define.amd ? define(['chart.js'], factory) : +(global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.Chart)); +})(this, (function (chart_js) { 'use strict'; + +function toInteger(dirtyNumber) { + if (dirtyNumber === null || dirtyNumber === true || dirtyNumber === false) { + return NaN; + } + + var number = Number(dirtyNumber); + + if (isNaN(number)) { + return number; + } + + return number < 0 ? Math.ceil(number) : Math.floor(number); +} + +function requiredArgs(required, args) { + if (args.length < required) { + throw new TypeError(required + ' argument' + (required > 1 ? 's' : '') + ' required, but only ' + args.length + ' present'); + } +} + +/** + * @name toDate + * @category Common Helpers + * @summary Convert the given argument to an instance of Date. + * + * @description + * Convert the given argument to an instance of Date. + * + * If the argument is an instance of Date, the function returns its clone. + * + * If the argument is a number, it is treated as a timestamp. + * + * If the argument is none of the above, the function returns Invalid Date. + * + * **Note**: *all* Date arguments passed to any *date-fns* function is processed by `toDate`. + * + * @param {Date|Number} argument - the value to convert + * @returns {Date} the parsed date in the local time zone + * @throws {TypeError} 1 argument required + * + * @example + * // Clone the date: + * const result = toDate(new Date(2014, 1, 11, 11, 30, 30)) + * //=> Tue Feb 11 2014 11:30:30 + * + * @example + * // Convert the timestamp to date: + * const result = toDate(1392098430000) + * //=> Tue Feb 11 2014 11:30:30 + */ + +function toDate(argument) { + requiredArgs(1, arguments); + var argStr = Object.prototype.toString.call(argument); // Clone the date + + if (argument instanceof Date || typeof argument === 'object' && argStr === '[object Date]') { + // Prevent the date to lose the milliseconds when passed to new Date() in IE10 + return new Date(argument.getTime()); + } else if (typeof argument === 'number' || argStr === '[object Number]') { + return new Date(argument); + } else { + if ((typeof argument === 'string' || argStr === '[object String]') && typeof console !== 'undefined') { + // eslint-disable-next-line no-console + console.warn("Starting with v2.0.0-beta.1 date-fns doesn't accept strings as date arguments. Please use `parseISO` to parse strings. See: https://git.io/fjule"); // eslint-disable-next-line no-console + + console.warn(new Error().stack); + } + + return new Date(NaN); + } +} + +/** + * @name addDays + * @category Day Helpers + * @summary Add the specified number of days to the given date. + * + * @description + * Add the specified number of days to the given date. + * + * ### v2.0.0 breaking changes: + * + * - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes). + * + * @param {Date|Number} date - the date to be changed + * @param {Number} amount - the amount of days to be added. Positive decimals will be rounded using `Math.floor`, decimals less than zero will be rounded using `Math.ceil`. + * @returns {Date} the new date with the days added + * @throws {TypeError} 2 arguments required + * + * @example + * // Add 10 days to 1 September 2014: + * const result = addDays(new Date(2014, 8, 1), 10) + * //=> Thu Sep 11 2014 00:00:00 + */ + +function addDays(dirtyDate, dirtyAmount) { + requiredArgs(2, arguments); + var date = toDate(dirtyDate); + var amount = toInteger(dirtyAmount); + + if (isNaN(amount)) { + return new Date(NaN); + } + + if (!amount) { + // If 0 days, no-op to avoid changing times in the hour before end of DST + return date; + } + + date.setDate(date.getDate() + amount); + return date; +} + +/** + * @name addMonths + * @category Month Helpers + * @summary Add the specified number of months to the given date. + * + * @description + * Add the specified number of months to the given date. + * + * ### v2.0.0 breaking changes: + * + * - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes). + * + * @param {Date|Number} date - the date to be changed + * @param {Number} amount - the amount of months to be added. Positive decimals will be rounded using `Math.floor`, decimals less than zero will be rounded using `Math.ceil`. + * @returns {Date} the new date with the months added + * @throws {TypeError} 2 arguments required + * + * @example + * // Add 5 months to 1 September 2014: + * const result = addMonths(new Date(2014, 8, 1), 5) + * //=> Sun Feb 01 2015 00:00:00 + */ + +function addMonths(dirtyDate, dirtyAmount) { + requiredArgs(2, arguments); + var date = toDate(dirtyDate); + var amount = toInteger(dirtyAmount); + + if (isNaN(amount)) { + return new Date(NaN); + } + + if (!amount) { + // If 0 months, no-op to avoid changing times in the hour before end of DST + return date; + } + + var dayOfMonth = date.getDate(); // The JS Date object supports date math by accepting out-of-bounds values for + // month, day, etc. For example, new Date(2020, 1, 0) returns 31 Dec 2019 and + // new Date(2020, 13, 1) returns 1 Feb 2021. This is *almost* the behavior we + // want except that dates will wrap around the end of a month, meaning that + // new Date(2020, 13, 31) will return 3 Mar 2021 not 28 Feb 2021 as desired. So + // we'll default to the end of the desired month by adding 1 to the desired + // month and using a date of 0 to back up one day to the end of the desired + // month. + + var endOfDesiredMonth = new Date(date.getTime()); + endOfDesiredMonth.setMonth(date.getMonth() + amount + 1, 0); + var daysInMonth = endOfDesiredMonth.getDate(); + + if (dayOfMonth >= daysInMonth) { + // If we're already at the end of the month, then this is the correct date + // and we're done. + return endOfDesiredMonth; + } else { + // Otherwise, we now know that setting the original day-of-month value won't + // cause an overflow, so set the desired day-of-month. Note that we can't + // just set the date of `endOfDesiredMonth` because that object may have had + // its time changed in the unusual case where where a DST transition was on + // the last day of the month and its local time was in the hour skipped or + // repeated next to a DST transition. So we use `date` instead which is + // guaranteed to still have the original time. + date.setFullYear(endOfDesiredMonth.getFullYear(), endOfDesiredMonth.getMonth(), dayOfMonth); + return date; + } +} + +/** + * @name addMilliseconds + * @category Millisecond Helpers + * @summary Add the specified number of milliseconds to the given date. + * + * @description + * Add the specified number of milliseconds to the given date. + * + * ### v2.0.0 breaking changes: + * + * - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes). + * + * @param {Date|Number} date - the date to be changed + * @param {Number} amount - the amount of milliseconds to be added. Positive decimals will be rounded using `Math.floor`, decimals less than zero will be rounded using `Math.ceil`. + * @returns {Date} the new date with the milliseconds added + * @throws {TypeError} 2 arguments required + * + * @example + * // Add 750 milliseconds to 10 July 2014 12:45:30.000: + * const result = addMilliseconds(new Date(2014, 6, 10, 12, 45, 30, 0), 750) + * //=> Thu Jul 10 2014 12:45:30.750 + */ + +function addMilliseconds(dirtyDate, dirtyAmount) { + requiredArgs(2, arguments); + var timestamp = toDate(dirtyDate).getTime(); + var amount = toInteger(dirtyAmount); + return new Date(timestamp + amount); +} + +var MILLISECONDS_IN_HOUR$3 = 3600000; +/** + * @name addHours + * @category Hour Helpers + * @summary Add the specified number of hours to the given date. + * + * @description + * Add the specified number of hours to the given date. + * + * ### v2.0.0 breaking changes: + * + * - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes). + * + * @param {Date|Number} date - the date to be changed + * @param {Number} amount - the amount of hours to be added. Positive decimals will be rounded using `Math.floor`, decimals less than zero will be rounded using `Math.ceil`. + * @returns {Date} the new date with the hours added + * @throws {TypeError} 2 arguments required + * + * @example + * // Add 2 hours to 10 July 2014 23:00:00: + * const result = addHours(new Date(2014, 6, 10, 23, 0), 2) + * //=> Fri Jul 11 2014 01:00:00 + */ + +function addHours(dirtyDate, dirtyAmount) { + requiredArgs(2, arguments); + var amount = toInteger(dirtyAmount); + return addMilliseconds(dirtyDate, amount * MILLISECONDS_IN_HOUR$3); +} + +/** + * @name startOfWeek + * @category Week Helpers + * @summary Return the start of a week for the given date. + * + * @description + * Return the start of a week for the given date. + * The result will be in the local timezone. + * + * ### v2.0.0 breaking changes: + * + * - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes). + * + * @param {Date|Number} date - the original date + * @param {Object} [options] - an object with options. + * @param {Locale} [options.locale=defaultLocale] - the locale object. See [Locale]{@link https://date-fns.org/docs/Locale} + * @param {0|1|2|3|4|5|6} [options.weekStartsOn=0] - the index of the first day of the week (0 - Sunday) + * @returns {Date} the start of a week + * @throws {TypeError} 1 argument required + * @throws {RangeError} `options.weekStartsOn` must be between 0 and 6 + * + * @example + * // The start of a week for 2 September 2014 11:55:00: + * var result = startOfWeek(new Date(2014, 8, 2, 11, 55, 0)) + * //=> Sun Aug 31 2014 00:00:00 + * + * @example + * // If the week starts on Monday, the start of the week for 2 September 2014 11:55:00: + * var result = startOfWeek(new Date(2014, 8, 2, 11, 55, 0), { weekStartsOn: 1 }) + * //=> Mon Sep 01 2014 00:00:00 + */ + +function startOfWeek(dirtyDate, dirtyOptions) { + requiredArgs(1, arguments); + var options = dirtyOptions || {}; + var locale = options.locale; + var localeWeekStartsOn = locale && locale.options && locale.options.weekStartsOn; + var defaultWeekStartsOn = localeWeekStartsOn == null ? 0 : toInteger(localeWeekStartsOn); + var weekStartsOn = options.weekStartsOn == null ? defaultWeekStartsOn : toInteger(options.weekStartsOn); // Test if weekStartsOn is between 0 and 6 _and_ is not NaN + + if (!(weekStartsOn >= 0 && weekStartsOn <= 6)) { + throw new RangeError('weekStartsOn must be between 0 and 6 inclusively'); + } + + var date = toDate(dirtyDate); + var day = date.getDay(); + var diff = (day < weekStartsOn ? 7 : 0) + day - weekStartsOn; + date.setDate(date.getDate() - diff); + date.setHours(0, 0, 0, 0); + return date; +} + +/** + * Google Chrome as of 67.0.3396.87 introduced timezones with offset that includes seconds. + * They usually appear for dates that denote time before the timezones were introduced + * (e.g. for 'Europe/Prague' timezone the offset is GMT+00:57:44 before 1 October 1891 + * and GMT+01:00:00 after that date) + * + * Date#getTimezoneOffset returns the offset in minutes and would return 57 for the example above, + * which would lead to incorrect calculations. + * + * This function returns the timezone offset in milliseconds that takes seconds in account. + */ +function getTimezoneOffsetInMilliseconds(date) { + var utcDate = new Date(Date.UTC(date.getFullYear(), date.getMonth(), date.getDate(), date.getHours(), date.getMinutes(), date.getSeconds(), date.getMilliseconds())); + utcDate.setUTCFullYear(date.getFullYear()); + return date.getTime() - utcDate.getTime(); +} + +/** + * @name startOfDay + * @category Day Helpers + * @summary Return the start of a day for the given date. + * + * @description + * Return the start of a day for the given date. + * The result will be in the local timezone. + * + * ### v2.0.0 breaking changes: + * + * - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes). + * + * @param {Date|Number} date - the original date + * @returns {Date} the start of a day + * @throws {TypeError} 1 argument required + * + * @example + * // The start of a day for 2 September 2014 11:55:00: + * const result = startOfDay(new Date(2014, 8, 2, 11, 55, 0)) + * //=> Tue Sep 02 2014 00:00:00 + */ + +function startOfDay(dirtyDate) { + requiredArgs(1, arguments); + var date = toDate(dirtyDate); + date.setHours(0, 0, 0, 0); + return date; +} + +var MILLISECONDS_IN_DAY$1 = 86400000; +/** + * @name differenceInCalendarDays + * @category Day Helpers + * @summary Get the number of calendar days between the given dates. + * + * @description + * Get the number of calendar days between the given dates. This means that the times are removed + * from the dates and then the difference in days is calculated. + * + * ### v2.0.0 breaking changes: + * + * - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes). + * + * @param {Date|Number} dateLeft - the later date + * @param {Date|Number} dateRight - the earlier date + * @returns {Number} the number of calendar days + * @throws {TypeError} 2 arguments required + * + * @example + * // How many calendar days are between + * // 2 July 2011 23:00:00 and 2 July 2012 00:00:00? + * var result = differenceInCalendarDays( + * new Date(2012, 6, 2, 0, 0), + * new Date(2011, 6, 2, 23, 0) + * ) + * //=> 366 + * // How many calendar days are between + * // 2 July 2011 23:59:00 and 3 July 2011 00:01:00? + * var result = differenceInCalendarDays( + * new Date(2011, 6, 3, 0, 1), + * new Date(2011, 6, 2, 23, 59) + * ) + * //=> 1 + */ + +function differenceInCalendarDays(dirtyDateLeft, dirtyDateRight) { + requiredArgs(2, arguments); + var startOfDayLeft = startOfDay(dirtyDateLeft); + var startOfDayRight = startOfDay(dirtyDateRight); + var timestampLeft = startOfDayLeft.getTime() - getTimezoneOffsetInMilliseconds(startOfDayLeft); + var timestampRight = startOfDayRight.getTime() - getTimezoneOffsetInMilliseconds(startOfDayRight); // Round the number of days to the nearest integer + // because the number of milliseconds in a day is not constant + // (e.g. it's different in the day of the daylight saving time clock shift) + + return Math.round((timestampLeft - timestampRight) / MILLISECONDS_IN_DAY$1); +} + +var MILLISECONDS_IN_MINUTE$3 = 60000; +/** + * @name addMinutes + * @category Minute Helpers + * @summary Add the specified number of minutes to the given date. + * + * @description + * Add the specified number of minutes to the given date. + * + * ### v2.0.0 breaking changes: + * + * - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes). + * + * @param {Date|Number} date - the date to be changed + * @param {Number} amount - the amount of minutes to be added. Positive decimals will be rounded using `Math.floor`, decimals less than zero will be rounded using `Math.ceil`. + * @returns {Date} the new date with the minutes added + * @throws {TypeError} 2 arguments required + * + * @example + * // Add 30 minutes to 10 July 2014 12:00:00: + * const result = addMinutes(new Date(2014, 6, 10, 12, 0), 30) + * //=> Thu Jul 10 2014 12:30:00 + */ + +function addMinutes(dirtyDate, dirtyAmount) { + requiredArgs(2, arguments); + var amount = toInteger(dirtyAmount); + return addMilliseconds(dirtyDate, amount * MILLISECONDS_IN_MINUTE$3); +} + +/** + * @name addQuarters + * @category Quarter Helpers + * @summary Add the specified number of year quarters to the given date. + * + * @description + * Add the specified number of year quarters to the given date. + * + * ### v2.0.0 breaking changes: + * + * - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes). + * + * @param {Date|Number} date - the date to be changed + * @param {Number} amount - the amount of quarters to be added. Positive decimals will be rounded using `Math.floor`, decimals less than zero will be rounded using `Math.ceil`. + * @returns {Date} the new date with the quarters added + * @throws {TypeError} 2 arguments required + * + * @example + * // Add 1 quarter to 1 September 2014: + * const result = addQuarters(new Date(2014, 8, 1), 1) + * //=> Mon Dec 01 2014 00:00:00 + */ + +function addQuarters(dirtyDate, dirtyAmount) { + requiredArgs(2, arguments); + var amount = toInteger(dirtyAmount); + var months = amount * 3; + return addMonths(dirtyDate, months); +} + +/** + * @name addSeconds + * @category Second Helpers + * @summary Add the specified number of seconds to the given date. + * + * @description + * Add the specified number of seconds to the given date. + * + * ### v2.0.0 breaking changes: + * + * - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes). + * + * @param {Date|Number} date - the date to be changed + * @param {Number} amount - the amount of seconds to be added. Positive decimals will be rounded using `Math.floor`, decimals less than zero will be rounded using `Math.ceil`. + * @returns {Date} the new date with the seconds added + * @throws {TypeError} 2 arguments required + * + * @example + * // Add 30 seconds to 10 July 2014 12:45:00: + * const result = addSeconds(new Date(2014, 6, 10, 12, 45, 0), 30) + * //=> Thu Jul 10 2014 12:45:30 + */ + +function addSeconds(dirtyDate, dirtyAmount) { + requiredArgs(2, arguments); + var amount = toInteger(dirtyAmount); + return addMilliseconds(dirtyDate, amount * 1000); +} + +/** + * @name addWeeks + * @category Week Helpers + * @summary Add the specified number of weeks to the given date. + * + * @description + * Add the specified number of week to the given date. + * + * ### v2.0.0 breaking changes: + * + * - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes). + * + * @param {Date|Number} date - the date to be changed + * @param {Number} amount - the amount of weeks to be added. Positive decimals will be rounded using `Math.floor`, decimals less than zero will be rounded using `Math.ceil`. + * @returns {Date} the new date with the weeks added + * @throws {TypeError} 2 arguments required + * + * @example + * // Add 4 weeks to 1 September 2014: + * const result = addWeeks(new Date(2014, 8, 1), 4) + * //=> Mon Sep 29 2014 00:00:00 + */ + +function addWeeks(dirtyDate, dirtyAmount) { + requiredArgs(2, arguments); + var amount = toInteger(dirtyAmount); + var days = amount * 7; + return addDays(dirtyDate, days); +} + +/** + * @name addYears + * @category Year Helpers + * @summary Add the specified number of years to the given date. + * + * @description + * Add the specified number of years to the given date. + * + * ### v2.0.0 breaking changes: + * + * - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes). + * + * @param {Date|Number} date - the date to be changed + * @param {Number} amount - the amount of years to be added. Positive decimals will be rounded using `Math.floor`, decimals less than zero will be rounded using `Math.ceil`. + * @returns {Date} the new date with the years added + * @throws {TypeError} 2 arguments required + * + * @example + * // Add 5 years to 1 September 2014: + * const result = addYears(new Date(2014, 8, 1), 5) + * //=> Sun Sep 01 2019 00:00:00 + */ + +function addYears(dirtyDate, dirtyAmount) { + requiredArgs(2, arguments); + var amount = toInteger(dirtyAmount); + return addMonths(dirtyDate, amount * 12); +} + +/** + * @name compareAsc + * @category Common Helpers + * @summary Compare the two dates and return -1, 0 or 1. + * + * @description + * Compare the two dates and return 1 if the first date is after the second, + * -1 if the first date is before the second or 0 if dates are equal. + * + * ### v2.0.0 breaking changes: + * + * - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes). + * + * @param {Date|Number} dateLeft - the first date to compare + * @param {Date|Number} dateRight - the second date to compare + * @returns {Number} the result of the comparison + * @throws {TypeError} 2 arguments required + * + * @example + * // Compare 11 February 1987 and 10 July 1989: + * const result = compareAsc(new Date(1987, 1, 11), new Date(1989, 6, 10)) + * //=> -1 + * + * @example + * // Sort the array of dates: + * const result = [ + * new Date(1995, 6, 2), + * new Date(1987, 1, 11), + * new Date(1989, 6, 10) + * ].sort(compareAsc) + * //=> [ + * // Wed Feb 11 1987 00:00:00, + * // Mon Jul 10 1989 00:00:00, + * // Sun Jul 02 1995 00:00:00 + * // ] + */ + +function compareAsc(dirtyDateLeft, dirtyDateRight) { + requiredArgs(2, arguments); + var dateLeft = toDate(dirtyDateLeft); + var dateRight = toDate(dirtyDateRight); + var diff = dateLeft.getTime() - dateRight.getTime(); + + if (diff < 0) { + return -1; + } else if (diff > 0) { + return 1; // Return 0 if diff is 0; return NaN if diff is NaN + } else { + return diff; + } +} + +/** + * @name isValid + * @category Common Helpers + * @summary Is the given date valid? + * + * @description + * Returns false if argument is Invalid Date and true otherwise. + * Argument is converted to Date using `toDate`. See [toDate]{@link https://date-fns.org/docs/toDate} + * Invalid Date is a Date, whose time value is NaN. + * + * Time value of Date: http://es5.github.io/#x15.9.1.1 + * + * ### v2.0.0 breaking changes: + * + * - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes). + * + * - Now `isValid` doesn't throw an exception + * if the first argument is not an instance of Date. + * Instead, argument is converted beforehand using `toDate`. + * + * Examples: + * + * | `isValid` argument | Before v2.0.0 | v2.0.0 onward | + * |---------------------------|---------------|---------------| + * | `new Date()` | `true` | `true` | + * | `new Date('2016-01-01')` | `true` | `true` | + * | `new Date('')` | `false` | `false` | + * | `new Date(1488370835081)` | `true` | `true` | + * | `new Date(NaN)` | `false` | `false` | + * | `'2016-01-01'` | `TypeError` | `false` | + * | `''` | `TypeError` | `false` | + * | `1488370835081` | `TypeError` | `true` | + * | `NaN` | `TypeError` | `false` | + * + * We introduce this change to make *date-fns* consistent with ECMAScript behavior + * that try to coerce arguments to the expected type + * (which is also the case with other *date-fns* functions). + * + * @param {*} date - the date to check + * @returns {Boolean} the date is valid + * @throws {TypeError} 1 argument required + * + * @example + * // For the valid date: + * var result = isValid(new Date(2014, 1, 31)) + * //=> true + * + * @example + * // For the value, convertable into a date: + * var result = isValid(1393804800000) + * //=> true + * + * @example + * // For the invalid date: + * var result = isValid(new Date('')) + * //=> false + */ + +function isValid(dirtyDate) { + requiredArgs(1, arguments); + var date = toDate(dirtyDate); + return !isNaN(date); +} + +/** + * @name differenceInCalendarMonths + * @category Month Helpers + * @summary Get the number of calendar months between the given dates. + * + * @description + * Get the number of calendar months between the given dates. + * + * ### v2.0.0 breaking changes: + * + * - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes). + * + * @param {Date|Number} dateLeft - the later date + * @param {Date|Number} dateRight - the earlier date + * @returns {Number} the number of calendar months + * @throws {TypeError} 2 arguments required + * + * @example + * // How many calendar months are between 31 January 2014 and 1 September 2014? + * var result = differenceInCalendarMonths( + * new Date(2014, 8, 1), + * new Date(2014, 0, 31) + * ) + * //=> 8 + */ + +function differenceInCalendarMonths(dirtyDateLeft, dirtyDateRight) { + requiredArgs(2, arguments); + var dateLeft = toDate(dirtyDateLeft); + var dateRight = toDate(dirtyDateRight); + var yearDiff = dateLeft.getFullYear() - dateRight.getFullYear(); + var monthDiff = dateLeft.getMonth() - dateRight.getMonth(); + return yearDiff * 12 + monthDiff; +} + +/** + * @name differenceInCalendarYears + * @category Year Helpers + * @summary Get the number of calendar years between the given dates. + * + * @description + * Get the number of calendar years between the given dates. + * + * ### v2.0.0 breaking changes: + * + * - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes). + * + * @param {Date|Number} dateLeft - the later date + * @param {Date|Number} dateRight - the earlier date + * @returns {Number} the number of calendar years + * @throws {TypeError} 2 arguments required + * + * @example + * // How many calendar years are between 31 December 2013 and 11 February 2015? + * var result = differenceInCalendarYears( + * new Date(2015, 1, 11), + * new Date(2013, 11, 31) + * ) + * //=> 2 + */ + +function differenceInCalendarYears(dirtyDateLeft, dirtyDateRight) { + requiredArgs(2, arguments); + var dateLeft = toDate(dirtyDateLeft); + var dateRight = toDate(dirtyDateRight); + return dateLeft.getFullYear() - dateRight.getFullYear(); +} + +// for accurate equality comparisons of UTC timestamps that end up +// having the same representation in local time, e.g. one hour before +// DST ends vs. the instant that DST ends. + +function compareLocalAsc(dateLeft, dateRight) { + var diff = dateLeft.getFullYear() - dateRight.getFullYear() || dateLeft.getMonth() - dateRight.getMonth() || dateLeft.getDate() - dateRight.getDate() || dateLeft.getHours() - dateRight.getHours() || dateLeft.getMinutes() - dateRight.getMinutes() || dateLeft.getSeconds() - dateRight.getSeconds() || dateLeft.getMilliseconds() - dateRight.getMilliseconds(); + + if (diff < 0) { + return -1; + } else if (diff > 0) { + return 1; // Return 0 if diff is 0; return NaN if diff is NaN + } else { + return diff; + } +} +/** + * @name differenceInDays + * @category Day Helpers + * @summary Get the number of full days between the given dates. + * + * @description + * Get the number of full day periods between two dates. Fractional days are + * truncated towards zero. + * + * One "full day" is the distance between a local time in one day to the same + * local time on the next or previous day. A full day can sometimes be less than + * or more than 24 hours if a daylight savings change happens between two dates. + * + * To ignore DST and only measure exact 24-hour periods, use this instead: + * `Math.floor(differenceInHours(dateLeft, dateRight)/24)|0`. + * + * + * ### v2.0.0 breaking changes: + * + * - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes). + * + * @param {Date|Number} dateLeft - the later date + * @param {Date|Number} dateRight - the earlier date + * @returns {Number} the number of full days according to the local timezone + * @throws {TypeError} 2 arguments required + * + * @example + * // How many full days are between + * // 2 July 2011 23:00:00 and 2 July 2012 00:00:00? + * var result = differenceInDays( + * new Date(2012, 6, 2, 0, 0), + * new Date(2011, 6, 2, 23, 0) + * ) + * //=> 365 + * // How many full days are between + * // 2 July 2011 23:59:00 and 3 July 2011 00:01:00? + * var result = differenceInDays( + * new Date(2011, 6, 3, 0, 1), + * new Date(2011, 6, 2, 23, 59) + * ) + * //=> 0 + * // How many full days are between + * // 1 March 2020 0:00 and 1 June 2020 0:00 ? + * // Note: because local time is used, the + * // result will always be 92 days, even in + * // time zones where DST starts and the + * // period has only 92*24-1 hours. + * var result = differenceInDays( + * new Date(2020, 5, 1), + * new Date(2020, 2, 1) + * ) +//=> 92 + */ + + +function differenceInDays(dirtyDateLeft, dirtyDateRight) { + requiredArgs(2, arguments); + var dateLeft = toDate(dirtyDateLeft); + var dateRight = toDate(dirtyDateRight); + var sign = compareLocalAsc(dateLeft, dateRight); + var difference = Math.abs(differenceInCalendarDays(dateLeft, dateRight)); + dateLeft.setDate(dateLeft.getDate() - sign * difference); // Math.abs(diff in full days - diff in calendar days) === 1 if last calendar day is not full + // If so, result must be decreased by 1 in absolute value + + var isLastDayNotFull = compareLocalAsc(dateLeft, dateRight) === -sign; + var result = sign * (difference - isLastDayNotFull); // Prevent negative zero + + return result === 0 ? 0 : result; +} + +/** + * @name differenceInMilliseconds + * @category Millisecond Helpers + * @summary Get the number of milliseconds between the given dates. + * + * @description + * Get the number of milliseconds between the given dates. + * + * ### v2.0.0 breaking changes: + * + * - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes). + * + * @param {Date|Number} dateLeft - the later date + * @param {Date|Number} dateRight - the earlier date + * @returns {Number} the number of milliseconds + * @throws {TypeError} 2 arguments required + * + * @example + * // How many milliseconds are between + * // 2 July 2014 12:30:20.600 and 2 July 2014 12:30:21.700? + * var result = differenceInMilliseconds( + * new Date(2014, 6, 2, 12, 30, 21, 700), + * new Date(2014, 6, 2, 12, 30, 20, 600) + * ) + * //=> 1100 + */ + +function differenceInMilliseconds(dirtyDateLeft, dirtyDateRight) { + requiredArgs(2, arguments); + var dateLeft = toDate(dirtyDateLeft); + var dateRight = toDate(dirtyDateRight); + return dateLeft.getTime() - dateRight.getTime(); +} + +var MILLISECONDS_IN_HOUR$2 = 3600000; +/** + * @name differenceInHours + * @category Hour Helpers + * @summary Get the number of hours between the given dates. + * + * @description + * Get the number of hours between the given dates. + * + * ### v2.0.0 breaking changes: + * + * - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes). + * + * @param {Date|Number} dateLeft - the later date + * @param {Date|Number} dateRight - the earlier date + * @returns {Number} the number of hours + * @throws {TypeError} 2 arguments required + * + * @example + * // How many hours are between 2 July 2014 06:50:00 and 2 July 2014 19:00:00? + * var result = differenceInHours( + * new Date(2014, 6, 2, 19, 0), + * new Date(2014, 6, 2, 6, 50) + * ) + * //=> 12 + */ + +function differenceInHours(dirtyDateLeft, dirtyDateRight) { + requiredArgs(2, arguments); + var diff = differenceInMilliseconds(dirtyDateLeft, dirtyDateRight) / MILLISECONDS_IN_HOUR$2; + return diff > 0 ? Math.floor(diff) : Math.ceil(diff); +} + +var MILLISECONDS_IN_MINUTE$2 = 60000; +/** + * @name differenceInMinutes + * @category Minute Helpers + * @summary Get the number of minutes between the given dates. + * + * @description + * Get the signed number of full (rounded towards 0) minutes between the given dates. + * + * ### v2.0.0 breaking changes: + * + * - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes). + * + * @param {Date|Number} dateLeft - the later date + * @param {Date|Number} dateRight - the earlier date + * @returns {Number} the number of minutes + * @throws {TypeError} 2 arguments required + * + * @example + * // How many minutes are between 2 July 2014 12:07:59 and 2 July 2014 12:20:00? + * var result = differenceInMinutes( + * new Date(2014, 6, 2, 12, 20, 0), + * new Date(2014, 6, 2, 12, 7, 59) + * ) + * //=> 12 + * + * @example + * // How many minutes are from 10:01:59 to 10:00:00 + * var result = differenceInMinutes( + * new Date(2000, 0, 1, 10, 0, 0), + * new Date(2000, 0, 1, 10, 1, 59) + * ) + * //=> -1 + */ + +function differenceInMinutes(dirtyDateLeft, dirtyDateRight) { + requiredArgs(2, arguments); + var diff = differenceInMilliseconds(dirtyDateLeft, dirtyDateRight) / MILLISECONDS_IN_MINUTE$2; + return diff > 0 ? Math.floor(diff) : Math.ceil(diff); +} + +/** + * @name endOfDay + * @category Day Helpers + * @summary Return the end of a day for the given date. + * + * @description + * Return the end of a day for the given date. + * The result will be in the local timezone. + * + * ### v2.0.0 breaking changes: + * + * - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes). + * + * @param {Date|Number} date - the original date + * @returns {Date} the end of a day + * @throws {TypeError} 1 argument required + * + * @example + * // The end of a day for 2 September 2014 11:55:00: + * const result = endOfDay(new Date(2014, 8, 2, 11, 55, 0)) + * //=> Tue Sep 02 2014 23:59:59.999 + */ + +function endOfDay(dirtyDate) { + requiredArgs(1, arguments); + var date = toDate(dirtyDate); + date.setHours(23, 59, 59, 999); + return date; +} + +/** + * @name endOfMonth + * @category Month Helpers + * @summary Return the end of a month for the given date. + * + * @description + * Return the end of a month for the given date. + * The result will be in the local timezone. + * + * ### v2.0.0 breaking changes: + * + * - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes). + * + * @param {Date|Number} date - the original date + * @returns {Date} the end of a month + * @throws {TypeError} 1 argument required + * + * @example + * // The end of a month for 2 September 2014 11:55:00: + * const result = endOfMonth(new Date(2014, 8, 2, 11, 55, 0)) + * //=> Tue Sep 30 2014 23:59:59.999 + */ + +function endOfMonth(dirtyDate) { + requiredArgs(1, arguments); + var date = toDate(dirtyDate); + var month = date.getMonth(); + date.setFullYear(date.getFullYear(), month + 1, 0); + date.setHours(23, 59, 59, 999); + return date; +} + +/** + * @name isLastDayOfMonth + * @category Month Helpers + * @summary Is the given date the last day of a month? + * + * @description + * Is the given date the last day of a month? + * + * ### v2.0.0 breaking changes: + * + * - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes). + * + * @param {Date|Number} date - the date to check + * @returns {Boolean} the date is the last day of a month + * @throws {TypeError} 1 argument required + * + * @example + * // Is 28 February 2014 the last day of a month? + * var result = isLastDayOfMonth(new Date(2014, 1, 28)) + * //=> true + */ + +function isLastDayOfMonth(dirtyDate) { + requiredArgs(1, arguments); + var date = toDate(dirtyDate); + return endOfDay(date).getTime() === endOfMonth(date).getTime(); +} + +/** + * @name differenceInMonths + * @category Month Helpers + * @summary Get the number of full months between the given dates. + * + * @description + * Get the number of full months between the given dates. + * + * ### v2.0.0 breaking changes: + * + * - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes). + * + * @param {Date|Number} dateLeft - the later date + * @param {Date|Number} dateRight - the earlier date + * @returns {Number} the number of full months + * @throws {TypeError} 2 arguments required + * + * @example + * // How many full months are between 31 January 2014 and 1 September 2014? + * var result = differenceInMonths(new Date(2014, 8, 1), new Date(2014, 0, 31)) + * //=> 7 + */ + +function differenceInMonths(dirtyDateLeft, dirtyDateRight) { + requiredArgs(2, arguments); + var dateLeft = toDate(dirtyDateLeft); + var dateRight = toDate(dirtyDateRight); + var sign = compareAsc(dateLeft, dateRight); + var difference = Math.abs(differenceInCalendarMonths(dateLeft, dateRight)); + var result; // Check for the difference of less than month + + if (difference < 1) { + result = 0; + } else { + if (dateLeft.getMonth() === 1 && dateLeft.getDate() > 27) { + // This will check if the date is end of Feb and assign a higher end of month date + // to compare it with Jan + dateLeft.setDate(30); + } + + dateLeft.setMonth(dateLeft.getMonth() - sign * difference); // Math.abs(diff in full months - diff in calendar months) === 1 if last calendar month is not full + // If so, result must be decreased by 1 in absolute value + + var isLastMonthNotFull = compareAsc(dateLeft, dateRight) === -sign; // Check for cases of one full calendar month + + if (isLastDayOfMonth(toDate(dirtyDateLeft)) && difference === 1 && compareAsc(dirtyDateLeft, dateRight) === 1) { + isLastMonthNotFull = false; + } + + result = sign * (difference - isLastMonthNotFull); + } // Prevent negative zero + + + return result === 0 ? 0 : result; +} + +/** + * @name differenceInQuarters + * @category Quarter Helpers + * @summary Get the number of full quarters between the given dates. + * + * @description + * Get the number of full quarters between the given dates. + * + * ### v2.0.0 breaking changes: + * + * - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes). + * + * @param {Date|Number} dateLeft - the later date + * @param {Date|Number} dateRight - the earlier date + * @returns {Number} the number of full quarters + * @throws {TypeError} 2 arguments required + * + * @example + * // How many full quarters are between 31 December 2013 and 2 July 2014? + * var result = differenceInQuarters(new Date(2014, 6, 2), new Date(2013, 11, 31)) + * //=> 2 + */ + +function differenceInQuarters(dirtyDateLeft, dirtyDateRight) { + requiredArgs(2, arguments); + var diff = differenceInMonths(dirtyDateLeft, dirtyDateRight) / 3; + return diff > 0 ? Math.floor(diff) : Math.ceil(diff); +} + +/** + * @name differenceInSeconds + * @category Second Helpers + * @summary Get the number of seconds between the given dates. + * + * @description + * Get the number of seconds between the given dates. + * + * ### v2.0.0 breaking changes: + * + * - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes). + * + * @param {Date|Number} dateLeft - the later date + * @param {Date|Number} dateRight - the earlier date + * @returns {Number} the number of seconds + * @throws {TypeError} 2 arguments required + * + * @example + * // How many seconds are between + * // 2 July 2014 12:30:07.999 and 2 July 2014 12:30:20.000? + * var result = differenceInSeconds( + * new Date(2014, 6, 2, 12, 30, 20, 0), + * new Date(2014, 6, 2, 12, 30, 7, 999) + * ) + * //=> 12 + */ + +function differenceInSeconds(dirtyDateLeft, dirtyDateRight) { + requiredArgs(2, arguments); + var diff = differenceInMilliseconds(dirtyDateLeft, dirtyDateRight) / 1000; + return diff > 0 ? Math.floor(diff) : Math.ceil(diff); +} + +/** + * @name differenceInWeeks + * @category Week Helpers + * @summary Get the number of full weeks between the given dates. + * + * @description + * Get the number of full weeks between two dates. Fractional weeks are + * truncated towards zero. + * + * One "full week" is the distance between a local time in one day to the same + * local time 7 days earlier or later. A full week can sometimes be less than + * or more than 7*24 hours if a daylight savings change happens between two dates. + * + * To ignore DST and only measure exact 7*24-hour periods, use this instead: + * `Math.floor(differenceInHours(dateLeft, dateRight)/(7*24))|0`. + * + * + * ### v2.0.0 breaking changes: + * + * - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes). + * + * @param {Date|Number} dateLeft - the later date + * @param {Date|Number} dateRight - the earlier date + * @returns {Number} the number of full weeks + * @throws {TypeError} 2 arguments required + * + * @example + * // How many full weeks are between 5 July 2014 and 20 July 2014? + * var result = differenceInWeeks(new Date(2014, 6, 20), new Date(2014, 6, 5)) + * //=> 2 + * + * // How many full weeks are between + * // 1 March 2020 0:00 and 6 June 2020 0:00 ? + * // Note: because local time is used, the + * // result will always be 8 weeks (54 days), + * // even if DST starts and the period has + * // only 54*24-1 hours. + * var result = differenceInWeeks( + * new Date(2020, 5, 1), + * new Date(2020, 2, 6) + * ) + * //=> 8 + */ + +function differenceInWeeks(dirtyDateLeft, dirtyDateRight) { + requiredArgs(2, arguments); + var diff = differenceInDays(dirtyDateLeft, dirtyDateRight) / 7; + return diff > 0 ? Math.floor(diff) : Math.ceil(diff); +} + +/** + * @name differenceInYears + * @category Year Helpers + * @summary Get the number of full years between the given dates. + * + * @description + * Get the number of full years between the given dates. + * + * ### v2.0.0 breaking changes: + * + * - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes). + * + * @param {Date|Number} dateLeft - the later date + * @param {Date|Number} dateRight - the earlier date + * @returns {Number} the number of full years + * @throws {TypeError} 2 arguments required + * + * @example + * // How many full years are between 31 December 2013 and 11 February 2015? + * var result = differenceInYears(new Date(2015, 1, 11), new Date(2013, 11, 31)) + * //=> 1 + */ + +function differenceInYears(dirtyDateLeft, dirtyDateRight) { + requiredArgs(2, arguments); + var dateLeft = toDate(dirtyDateLeft); + var dateRight = toDate(dirtyDateRight); + var sign = compareAsc(dateLeft, dateRight); + var difference = Math.abs(differenceInCalendarYears(dateLeft, dateRight)); // Set both dates to a valid leap year for accurate comparison when dealing + // with leap days + + dateLeft.setFullYear('1584'); + dateRight.setFullYear('1584'); // Math.abs(diff in full years - diff in calendar years) === 1 if last calendar year is not full + // If so, result must be decreased by 1 in absolute value + + var isLastYearNotFull = compareAsc(dateLeft, dateRight) === -sign; + var result = sign * (difference - isLastYearNotFull); // Prevent negative zero + + return result === 0 ? 0 : result; +} + +/** + * @name startOfQuarter + * @category Quarter Helpers + * @summary Return the start of a year quarter for the given date. + * + * @description + * Return the start of a year quarter for the given date. + * The result will be in the local timezone. + * + * ### v2.0.0 breaking changes: + * + * - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes). + * + * @param {Date|Number} date - the original date + * @returns {Date} the start of a quarter + * @throws {TypeError} 1 argument required + * + * @example + * // The start of a quarter for 2 September 2014 11:55:00: + * const result = startOfQuarter(new Date(2014, 8, 2, 11, 55, 0)) + * //=> Tue Jul 01 2014 00:00:00 + */ + +function startOfQuarter(dirtyDate) { + requiredArgs(1, arguments); + var date = toDate(dirtyDate); + var currentMonth = date.getMonth(); + var month = currentMonth - currentMonth % 3; + date.setMonth(month, 1); + date.setHours(0, 0, 0, 0); + return date; +} + +/** + * @name startOfMonth + * @category Month Helpers + * @summary Return the start of a month for the given date. + * + * @description + * Return the start of a month for the given date. + * The result will be in the local timezone. + * + * ### v2.0.0 breaking changes: + * + * - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes). + * + * @param {Date|Number} date - the original date + * @returns {Date} the start of a month + * @throws {TypeError} 1 argument required + * + * @example + * // The start of a month for 2 September 2014 11:55:00: + * const result = startOfMonth(new Date(2014, 8, 2, 11, 55, 0)) + * //=> Mon Sep 01 2014 00:00:00 + */ + +function startOfMonth(dirtyDate) { + requiredArgs(1, arguments); + var date = toDate(dirtyDate); + date.setDate(1); + date.setHours(0, 0, 0, 0); + return date; +} + +/** + * @name startOfYear + * @category Year Helpers + * @summary Return the start of a year for the given date. + * + * @description + * Return the start of a year for the given date. + * The result will be in the local timezone. + * + * ### v2.0.0 breaking changes: + * + * - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes). + * + * @param {Date|Number} date - the original date + * @returns {Date} the start of a year + * @throws {TypeError} 1 argument required + * + * @example + * // The start of a year for 2 September 2014 11:55:00: + * const result = startOfYear(new Date(2014, 8, 2, 11, 55, 00)) + * //=> Wed Jan 01 2014 00:00:00 + */ + +function startOfYear(dirtyDate) { + requiredArgs(1, arguments); + var cleanDate = toDate(dirtyDate); + var date = new Date(0); + date.setFullYear(cleanDate.getFullYear(), 0, 1); + date.setHours(0, 0, 0, 0); + return date; +} + +/** + * @name endOfYear + * @category Year Helpers + * @summary Return the end of a year for the given date. + * + * @description + * Return the end of a year for the given date. + * The result will be in the local timezone. + * + * ### v2.0.0 breaking changes: + * + * - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes). + * + * @param {Date|Number} date - the original date + * @returns {Date} the end of a year + * @throws {TypeError} 1 argument required + * + * @example + * // The end of a year for 2 September 2014 11:55:00: + * var result = endOfYear(new Date(2014, 8, 2, 11, 55, 00)) + * //=> Wed Dec 31 2014 23:59:59.999 + */ + +function endOfYear(dirtyDate) { + requiredArgs(1, arguments); + var date = toDate(dirtyDate); + var year = date.getFullYear(); + date.setFullYear(year + 1, 0, 0); + date.setHours(23, 59, 59, 999); + return date; +} + +/** + * @name endOfHour + * @category Hour Helpers + * @summary Return the end of an hour for the given date. + * + * @description + * Return the end of an hour for the given date. + * The result will be in the local timezone. + * + * ### v2.0.0 breaking changes: + * + * - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes). + * + * @param {Date|Number} date - the original date + * @returns {Date} the end of an hour + * @throws {TypeError} 1 argument required + * + * @example + * // The end of an hour for 2 September 2014 11:55:00: + * const result = endOfHour(new Date(2014, 8, 2, 11, 55)) + * //=> Tue Sep 02 2014 11:59:59.999 + */ + +function endOfHour(dirtyDate) { + requiredArgs(1, arguments); + var date = toDate(dirtyDate); + date.setMinutes(59, 59, 999); + return date; +} + +/** + * @name endOfWeek + * @category Week Helpers + * @summary Return the end of a week for the given date. + * + * @description + * Return the end of a week for the given date. + * The result will be in the local timezone. + * + * ### v2.0.0 breaking changes: + * + * - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes). + * + * @param {Date|Number} date - the original date + * @param {Object} [options] - an object with options. + * @param {Locale} [options.locale=defaultLocale] - the locale object. See [Locale]{@link https://date-fns.org/docs/Locale} + * @param {0|1|2|3|4|5|6} [options.weekStartsOn=0] - the index of the first day of the week (0 - Sunday) + * @returns {Date} the end of a week + * @throws {TypeError} 1 argument required + * @throws {RangeError} `options.weekStartsOn` must be between 0 and 6 + * + * @example + * // The end of a week for 2 September 2014 11:55:00: + * const result = endOfWeek(new Date(2014, 8, 2, 11, 55, 0)) + * //=> Sat Sep 06 2014 23:59:59.999 + * + * @example + * // If the week starts on Monday, the end of the week for 2 September 2014 11:55:00: + * const result = endOfWeek(new Date(2014, 8, 2, 11, 55, 0), { weekStartsOn: 1 }) + * //=> Sun Sep 07 2014 23:59:59.999 + */ +function endOfWeek(dirtyDate, dirtyOptions) { + requiredArgs(1, arguments); + var options = dirtyOptions || {}; + var locale = options.locale; + var localeWeekStartsOn = locale && locale.options && locale.options.weekStartsOn; + var defaultWeekStartsOn = localeWeekStartsOn == null ? 0 : toInteger(localeWeekStartsOn); + var weekStartsOn = options.weekStartsOn == null ? defaultWeekStartsOn : toInteger(options.weekStartsOn); // Test if weekStartsOn is between 0 and 6 _and_ is not NaN + + if (!(weekStartsOn >= 0 && weekStartsOn <= 6)) { + throw new RangeError('weekStartsOn must be between 0 and 6 inclusively'); + } + + var date = toDate(dirtyDate); + var day = date.getDay(); + var diff = (day < weekStartsOn ? -7 : 0) + 6 - (day - weekStartsOn); + date.setDate(date.getDate() + diff); + date.setHours(23, 59, 59, 999); + return date; +} + +/** + * @name endOfMinute + * @category Minute Helpers + * @summary Return the end of a minute for the given date. + * + * @description + * Return the end of a minute for the given date. + * The result will be in the local timezone. + * + * ### v2.0.0 breaking changes: + * + * - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes). + * + * @param {Date|Number} date - the original date + * @returns {Date} the end of a minute + * @throws {TypeError} 1 argument required + * + * @example + * // The end of a minute for 1 December 2014 22:15:45.400: + * const result = endOfMinute(new Date(2014, 11, 1, 22, 15, 45, 400)) + * //=> Mon Dec 01 2014 22:15:59.999 + */ + +function endOfMinute(dirtyDate) { + requiredArgs(1, arguments); + var date = toDate(dirtyDate); + date.setSeconds(59, 999); + return date; +} + +/** + * @name endOfQuarter + * @category Quarter Helpers + * @summary Return the end of a year quarter for the given date. + * + * @description + * Return the end of a year quarter for the given date. + * The result will be in the local timezone. + * + * ### v2.0.0 breaking changes: + * + * - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes). + * + * @param {Date|Number} date - the original date + * @returns {Date} the end of a quarter + * @throws {TypeError} 1 argument required + * + * @example + * // The end of a quarter for 2 September 2014 11:55:00: + * const result = endOfQuarter(new Date(2014, 8, 2, 11, 55, 0)) + * //=> Tue Sep 30 2014 23:59:59.999 + */ + +function endOfQuarter(dirtyDate) { + requiredArgs(1, arguments); + var date = toDate(dirtyDate); + var currentMonth = date.getMonth(); + var month = currentMonth - currentMonth % 3 + 3; + date.setMonth(month, 0); + date.setHours(23, 59, 59, 999); + return date; +} + +/** + * @name endOfSecond + * @category Second Helpers + * @summary Return the end of a second for the given date. + * + * @description + * Return the end of a second for the given date. + * The result will be in the local timezone. + * + * ### v2.0.0 breaking changes: + * + * - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes). + * + * @param {Date|Number} date - the original date + * @returns {Date} the end of a second + * @throws {TypeError} 1 argument required + * + * @example + * // The end of a second for 1 December 2014 22:15:45.400: + * const result = endOfSecond(new Date(2014, 11, 1, 22, 15, 45, 400)) + * //=> Mon Dec 01 2014 22:15:45.999 + */ + +function endOfSecond(dirtyDate) { + requiredArgs(1, arguments); + var date = toDate(dirtyDate); + date.setMilliseconds(999); + return date; +} + +var formatDistanceLocale = { + lessThanXSeconds: { + one: 'less than a second', + other: 'less than {{count}} seconds' + }, + xSeconds: { + one: '1 second', + other: '{{count}} seconds' + }, + halfAMinute: 'half a minute', + lessThanXMinutes: { + one: 'less than a minute', + other: 'less than {{count}} minutes' + }, + xMinutes: { + one: '1 minute', + other: '{{count}} minutes' + }, + aboutXHours: { + one: 'about 1 hour', + other: 'about {{count}} hours' + }, + xHours: { + one: '1 hour', + other: '{{count}} hours' + }, + xDays: { + one: '1 day', + other: '{{count}} days' + }, + aboutXWeeks: { + one: 'about 1 week', + other: 'about {{count}} weeks' + }, + xWeeks: { + one: '1 week', + other: '{{count}} weeks' + }, + aboutXMonths: { + one: 'about 1 month', + other: 'about {{count}} months' + }, + xMonths: { + one: '1 month', + other: '{{count}} months' + }, + aboutXYears: { + one: 'about 1 year', + other: 'about {{count}} years' + }, + xYears: { + one: '1 year', + other: '{{count}} years' + }, + overXYears: { + one: 'over 1 year', + other: 'over {{count}} years' + }, + almostXYears: { + one: 'almost 1 year', + other: 'almost {{count}} years' + } +}; +function formatDistance(token, count, options) { + options = options || {}; + var result; + + if (typeof formatDistanceLocale[token] === 'string') { + result = formatDistanceLocale[token]; + } else if (count === 1) { + result = formatDistanceLocale[token].one; + } else { + result = formatDistanceLocale[token].other.replace('{{count}}', count); + } + + if (options.addSuffix) { + if (options.comparison > 0) { + return 'in ' + result; + } else { + return result + ' ago'; + } + } + + return result; +} + +function buildFormatLongFn(args) { + return function (dirtyOptions) { + var options = dirtyOptions || {}; + var width = options.width ? String(options.width) : args.defaultWidth; + var format = args.formats[width] || args.formats[args.defaultWidth]; + return format; + }; +} + +var dateFormats = { + full: 'EEEE, MMMM do, y', + long: 'MMMM do, y', + medium: 'MMM d, y', + short: 'MM/dd/yyyy' +}; +var timeFormats = { + full: 'h:mm:ss a zzzz', + long: 'h:mm:ss a z', + medium: 'h:mm:ss a', + short: 'h:mm a' +}; +var dateTimeFormats = { + full: "{{date}} 'at' {{time}}", + long: "{{date}} 'at' {{time}}", + medium: '{{date}}, {{time}}', + short: '{{date}}, {{time}}' +}; +var formatLong = { + date: buildFormatLongFn({ + formats: dateFormats, + defaultWidth: 'full' + }), + time: buildFormatLongFn({ + formats: timeFormats, + defaultWidth: 'full' + }), + dateTime: buildFormatLongFn({ + formats: dateTimeFormats, + defaultWidth: 'full' + }) +}; +var formatLong$1 = formatLong; + +var formatRelativeLocale = { + lastWeek: "'last' eeee 'at' p", + yesterday: "'yesterday at' p", + today: "'today at' p", + tomorrow: "'tomorrow at' p", + nextWeek: "eeee 'at' p", + other: 'P' +}; +function formatRelative(token, _date, _baseDate, _options) { + return formatRelativeLocale[token]; +} + +function buildLocalizeFn(args) { + return function (dirtyIndex, dirtyOptions) { + var options = dirtyOptions || {}; + var context = options.context ? String(options.context) : 'standalone'; + var valuesArray; + + if (context === 'formatting' && args.formattingValues) { + var defaultWidth = args.defaultFormattingWidth || args.defaultWidth; + var width = options.width ? String(options.width) : defaultWidth; + valuesArray = args.formattingValues[width] || args.formattingValues[defaultWidth]; + } else { + var _defaultWidth = args.defaultWidth; + + var _width = options.width ? String(options.width) : args.defaultWidth; + + valuesArray = args.values[_width] || args.values[_defaultWidth]; + } + + var index = args.argumentCallback ? args.argumentCallback(dirtyIndex) : dirtyIndex; + return valuesArray[index]; + }; +} + +var eraValues = { + narrow: ['B', 'A'], + abbreviated: ['BC', 'AD'], + wide: ['Before Christ', 'Anno Domini'] +}; +var quarterValues = { + narrow: ['1', '2', '3', '4'], + abbreviated: ['Q1', 'Q2', 'Q3', 'Q4'], + wide: ['1st quarter', '2nd quarter', '3rd quarter', '4th quarter'] // Note: in English, the names of days of the week and months are capitalized. + // If you are making a new locale based on this one, check if the same is true for the language you're working on. + // Generally, formatted dates should look like they are in the middle of a sentence, + // e.g. in Spanish language the weekdays and months should be in the lowercase. + +}; +var monthValues = { + narrow: ['J', 'F', 'M', 'A', 'M', 'J', 'J', 'A', 'S', 'O', 'N', 'D'], + abbreviated: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'], + wide: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'] +}; +var dayValues = { + narrow: ['S', 'M', 'T', 'W', 'T', 'F', 'S'], + short: ['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa'], + abbreviated: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'], + wide: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'] +}; +var dayPeriodValues = { + narrow: { + am: 'a', + pm: 'p', + midnight: 'mi', + noon: 'n', + morning: 'morning', + afternoon: 'afternoon', + evening: 'evening', + night: 'night' + }, + abbreviated: { + am: 'AM', + pm: 'PM', + midnight: 'midnight', + noon: 'noon', + morning: 'morning', + afternoon: 'afternoon', + evening: 'evening', + night: 'night' + }, + wide: { + am: 'a.m.', + pm: 'p.m.', + midnight: 'midnight', + noon: 'noon', + morning: 'morning', + afternoon: 'afternoon', + evening: 'evening', + night: 'night' + } +}; +var formattingDayPeriodValues = { + narrow: { + am: 'a', + pm: 'p', + midnight: 'mi', + noon: 'n', + morning: 'in the morning', + afternoon: 'in the afternoon', + evening: 'in the evening', + night: 'at night' + }, + abbreviated: { + am: 'AM', + pm: 'PM', + midnight: 'midnight', + noon: 'noon', + morning: 'in the morning', + afternoon: 'in the afternoon', + evening: 'in the evening', + night: 'at night' + }, + wide: { + am: 'a.m.', + pm: 'p.m.', + midnight: 'midnight', + noon: 'noon', + morning: 'in the morning', + afternoon: 'in the afternoon', + evening: 'in the evening', + night: 'at night' + } +}; + +function ordinalNumber(dirtyNumber, _dirtyOptions) { + var number = Number(dirtyNumber); // If ordinal numbers depend on context, for example, + // if they are different for different grammatical genders, + // use `options.unit`: + // + // var options = dirtyOptions || {} + // var unit = String(options.unit) + // + // where `unit` can be 'year', 'quarter', 'month', 'week', 'date', 'dayOfYear', + // 'day', 'hour', 'minute', 'second' + + var rem100 = number % 100; + + if (rem100 > 20 || rem100 < 10) { + switch (rem100 % 10) { + case 1: + return number + 'st'; + + case 2: + return number + 'nd'; + + case 3: + return number + 'rd'; + } + } + + return number + 'th'; +} + +var localize = { + ordinalNumber: ordinalNumber, + era: buildLocalizeFn({ + values: eraValues, + defaultWidth: 'wide' + }), + quarter: buildLocalizeFn({ + values: quarterValues, + defaultWidth: 'wide', + argumentCallback: function (quarter) { + return Number(quarter) - 1; + } + }), + month: buildLocalizeFn({ + values: monthValues, + defaultWidth: 'wide' + }), + day: buildLocalizeFn({ + values: dayValues, + defaultWidth: 'wide' + }), + dayPeriod: buildLocalizeFn({ + values: dayPeriodValues, + defaultWidth: 'wide', + formattingValues: formattingDayPeriodValues, + defaultFormattingWidth: 'wide' + }) +}; +var localize$1 = localize; + +function buildMatchPatternFn(args) { + return function (dirtyString, dirtyOptions) { + var string = String(dirtyString); + var options = dirtyOptions || {}; + var matchResult = string.match(args.matchPattern); + + if (!matchResult) { + return null; + } + + var matchedString = matchResult[0]; + var parseResult = string.match(args.parsePattern); + + if (!parseResult) { + return null; + } + + var value = args.valueCallback ? args.valueCallback(parseResult[0]) : parseResult[0]; + value = options.valueCallback ? options.valueCallback(value) : value; + return { + value: value, + rest: string.slice(matchedString.length) + }; + }; +} + +function buildMatchFn(args) { + return function (dirtyString, dirtyOptions) { + var string = String(dirtyString); + var options = dirtyOptions || {}; + var width = options.width; + var matchPattern = width && args.matchPatterns[width] || args.matchPatterns[args.defaultMatchWidth]; + var matchResult = string.match(matchPattern); + + if (!matchResult) { + return null; + } + + var matchedString = matchResult[0]; + var parsePatterns = width && args.parsePatterns[width] || args.parsePatterns[args.defaultParseWidth]; + var value; + + if (Object.prototype.toString.call(parsePatterns) === '[object Array]') { + value = findIndex(parsePatterns, function (pattern) { + return pattern.test(matchedString); + }); + } else { + value = findKey(parsePatterns, function (pattern) { + return pattern.test(matchedString); + }); + } + + value = args.valueCallback ? args.valueCallback(value) : value; + value = options.valueCallback ? options.valueCallback(value) : value; + return { + value: value, + rest: string.slice(matchedString.length) + }; + }; +} + +function findKey(object, predicate) { + for (var key in object) { + if (object.hasOwnProperty(key) && predicate(object[key])) { + return key; + } + } +} + +function findIndex(array, predicate) { + for (var key = 0; key < array.length; key++) { + if (predicate(array[key])) { + return key; + } + } +} + +var matchOrdinalNumberPattern = /^(\d+)(th|st|nd|rd)?/i; +var parseOrdinalNumberPattern = /\d+/i; +var matchEraPatterns = { + narrow: /^(b|a)/i, + abbreviated: /^(b\.?\s?c\.?|b\.?\s?c\.?\s?e\.?|a\.?\s?d\.?|c\.?\s?e\.?)/i, + wide: /^(before christ|before common era|anno domini|common era)/i +}; +var parseEraPatterns = { + any: [/^b/i, /^(a|c)/i] +}; +var matchQuarterPatterns = { + narrow: /^[1234]/i, + abbreviated: /^q[1234]/i, + wide: /^[1234](th|st|nd|rd)? quarter/i +}; +var parseQuarterPatterns = { + any: [/1/i, /2/i, /3/i, /4/i] +}; +var matchMonthPatterns = { + narrow: /^[jfmasond]/i, + abbreviated: /^(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)/i, + wide: /^(january|february|march|april|may|june|july|august|september|october|november|december)/i +}; +var parseMonthPatterns = { + narrow: [/^j/i, /^f/i, /^m/i, /^a/i, /^m/i, /^j/i, /^j/i, /^a/i, /^s/i, /^o/i, /^n/i, /^d/i], + any: [/^ja/i, /^f/i, /^mar/i, /^ap/i, /^may/i, /^jun/i, /^jul/i, /^au/i, /^s/i, /^o/i, /^n/i, /^d/i] +}; +var matchDayPatterns = { + narrow: /^[smtwf]/i, + short: /^(su|mo|tu|we|th|fr|sa)/i, + abbreviated: /^(sun|mon|tue|wed|thu|fri|sat)/i, + wide: /^(sunday|monday|tuesday|wednesday|thursday|friday|saturday)/i +}; +var parseDayPatterns = { + narrow: [/^s/i, /^m/i, /^t/i, /^w/i, /^t/i, /^f/i, /^s/i], + any: [/^su/i, /^m/i, /^tu/i, /^w/i, /^th/i, /^f/i, /^sa/i] +}; +var matchDayPeriodPatterns = { + narrow: /^(a|p|mi|n|(in the|at) (morning|afternoon|evening|night))/i, + any: /^([ap]\.?\s?m\.?|midnight|noon|(in the|at) (morning|afternoon|evening|night))/i +}; +var parseDayPeriodPatterns = { + any: { + am: /^a/i, + pm: /^p/i, + midnight: /^mi/i, + noon: /^no/i, + morning: /morning/i, + afternoon: /afternoon/i, + evening: /evening/i, + night: /night/i + } +}; +var match = { + ordinalNumber: buildMatchPatternFn({ + matchPattern: matchOrdinalNumberPattern, + parsePattern: parseOrdinalNumberPattern, + valueCallback: function (value) { + return parseInt(value, 10); + } + }), + era: buildMatchFn({ + matchPatterns: matchEraPatterns, + defaultMatchWidth: 'wide', + parsePatterns: parseEraPatterns, + defaultParseWidth: 'any' + }), + quarter: buildMatchFn({ + matchPatterns: matchQuarterPatterns, + defaultMatchWidth: 'wide', + parsePatterns: parseQuarterPatterns, + defaultParseWidth: 'any', + valueCallback: function (index) { + return index + 1; + } + }), + month: buildMatchFn({ + matchPatterns: matchMonthPatterns, + defaultMatchWidth: 'wide', + parsePatterns: parseMonthPatterns, + defaultParseWidth: 'any' + }), + day: buildMatchFn({ + matchPatterns: matchDayPatterns, + defaultMatchWidth: 'wide', + parsePatterns: parseDayPatterns, + defaultParseWidth: 'any' + }), + dayPeriod: buildMatchFn({ + matchPatterns: matchDayPeriodPatterns, + defaultMatchWidth: 'any', + parsePatterns: parseDayPeriodPatterns, + defaultParseWidth: 'any' + }) +}; +var match$1 = match; + +/** + * @type {Locale} + * @category Locales + * @summary English locale (United States). + * @language English + * @iso-639-2 eng + * @author Sasha Koss [@kossnocorp]{@link https://github.com/kossnocorp} + * @author Lesha Koss [@leshakoss]{@link https://github.com/leshakoss} + */ + +var locale = { + code: 'en-US', + formatDistance: formatDistance, + formatLong: formatLong$1, + formatRelative: formatRelative, + localize: localize$1, + match: match$1, + options: { + weekStartsOn: 0 + /* Sunday */ + , + firstWeekContainsDate: 1 + } +}; +var defaultLocale = locale; + +/** + * @name subMilliseconds + * @category Millisecond Helpers + * @summary Subtract the specified number of milliseconds from the given date. + * + * @description + * Subtract the specified number of milliseconds from the given date. + * + * ### v2.0.0 breaking changes: + * + * - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes). + * + * @param {Date|Number} date - the date to be changed + * @param {Number} amount - the amount of milliseconds to be subtracted. Positive decimals will be rounded using `Math.floor`, decimals less than zero will be rounded using `Math.ceil`. + * @returns {Date} the new date with the milliseconds subtracted + * @throws {TypeError} 2 arguments required + * + * @example + * // Subtract 750 milliseconds from 10 July 2014 12:45:30.000: + * const result = subMilliseconds(new Date(2014, 6, 10, 12, 45, 30, 0), 750) + * //=> Thu Jul 10 2014 12:45:29.250 + */ + +function subMilliseconds(dirtyDate, dirtyAmount) { + requiredArgs(2, arguments); + var amount = toInteger(dirtyAmount); + return addMilliseconds(dirtyDate, -amount); +} + +function addLeadingZeros(number, targetLength) { + var sign = number < 0 ? '-' : ''; + var output = Math.abs(number).toString(); + + while (output.length < targetLength) { + output = '0' + output; + } + + return sign + output; +} + +/* + * | | Unit | | Unit | + * |-----|--------------------------------|-----|--------------------------------| + * | a | AM, PM | A* | | + * | d | Day of month | D | | + * | h | Hour [1-12] | H | Hour [0-23] | + * | m | Minute | M | Month | + * | s | Second | S | Fraction of second | + * | y | Year (abs) | Y | | + * + * Letters marked by * are not implemented but reserved by Unicode standard. + */ + +var formatters$2 = { + // Year + y: function (date, token) { + // From http://www.unicode.org/reports/tr35/tr35-31/tr35-dates.html#Date_Format_tokens + // | Year | y | yy | yyy | yyyy | yyyyy | + // |----------|-------|----|-------|-------|-------| + // | AD 1 | 1 | 01 | 001 | 0001 | 00001 | + // | AD 12 | 12 | 12 | 012 | 0012 | 00012 | + // | AD 123 | 123 | 23 | 123 | 0123 | 00123 | + // | AD 1234 | 1234 | 34 | 1234 | 1234 | 01234 | + // | AD 12345 | 12345 | 45 | 12345 | 12345 | 12345 | + var signedYear = date.getUTCFullYear(); // Returns 1 for 1 BC (which is year 0 in JavaScript) + + var year = signedYear > 0 ? signedYear : 1 - signedYear; + return addLeadingZeros(token === 'yy' ? year % 100 : year, token.length); + }, + // Month + M: function (date, token) { + var month = date.getUTCMonth(); + return token === 'M' ? String(month + 1) : addLeadingZeros(month + 1, 2); + }, + // Day of the month + d: function (date, token) { + return addLeadingZeros(date.getUTCDate(), token.length); + }, + // AM or PM + a: function (date, token) { + var dayPeriodEnumValue = date.getUTCHours() / 12 >= 1 ? 'pm' : 'am'; + + switch (token) { + case 'a': + case 'aa': + return dayPeriodEnumValue.toUpperCase(); + + case 'aaa': + return dayPeriodEnumValue; + + case 'aaaaa': + return dayPeriodEnumValue[0]; + + case 'aaaa': + default: + return dayPeriodEnumValue === 'am' ? 'a.m.' : 'p.m.'; + } + }, + // Hour [1-12] + h: function (date, token) { + return addLeadingZeros(date.getUTCHours() % 12 || 12, token.length); + }, + // Hour [0-23] + H: function (date, token) { + return addLeadingZeros(date.getUTCHours(), token.length); + }, + // Minute + m: function (date, token) { + return addLeadingZeros(date.getUTCMinutes(), token.length); + }, + // Second + s: function (date, token) { + return addLeadingZeros(date.getUTCSeconds(), token.length); + }, + // Fraction of second + S: function (date, token) { + var numberOfDigits = token.length; + var milliseconds = date.getUTCMilliseconds(); + var fractionalSeconds = Math.floor(milliseconds * Math.pow(10, numberOfDigits - 3)); + return addLeadingZeros(fractionalSeconds, token.length); + } +}; +var formatters$3 = formatters$2; + +var MILLISECONDS_IN_DAY = 86400000; // This function will be a part of public API when UTC function will be implemented. +// See issue: https://github.com/date-fns/date-fns/issues/376 + +function getUTCDayOfYear(dirtyDate) { + requiredArgs(1, arguments); + var date = toDate(dirtyDate); + var timestamp = date.getTime(); + date.setUTCMonth(0, 1); + date.setUTCHours(0, 0, 0, 0); + var startOfYearTimestamp = date.getTime(); + var difference = timestamp - startOfYearTimestamp; + return Math.floor(difference / MILLISECONDS_IN_DAY) + 1; +} + +// See issue: https://github.com/date-fns/date-fns/issues/376 + +function startOfUTCISOWeek(dirtyDate) { + requiredArgs(1, arguments); + var weekStartsOn = 1; + var date = toDate(dirtyDate); + var day = date.getUTCDay(); + var diff = (day < weekStartsOn ? 7 : 0) + day - weekStartsOn; + date.setUTCDate(date.getUTCDate() - diff); + date.setUTCHours(0, 0, 0, 0); + return date; +} + +// See issue: https://github.com/date-fns/date-fns/issues/376 + +function getUTCISOWeekYear(dirtyDate) { + requiredArgs(1, arguments); + var date = toDate(dirtyDate); + var year = date.getUTCFullYear(); + var fourthOfJanuaryOfNextYear = new Date(0); + fourthOfJanuaryOfNextYear.setUTCFullYear(year + 1, 0, 4); + fourthOfJanuaryOfNextYear.setUTCHours(0, 0, 0, 0); + var startOfNextYear = startOfUTCISOWeek(fourthOfJanuaryOfNextYear); + var fourthOfJanuaryOfThisYear = new Date(0); + fourthOfJanuaryOfThisYear.setUTCFullYear(year, 0, 4); + fourthOfJanuaryOfThisYear.setUTCHours(0, 0, 0, 0); + var startOfThisYear = startOfUTCISOWeek(fourthOfJanuaryOfThisYear); + + if (date.getTime() >= startOfNextYear.getTime()) { + return year + 1; + } else if (date.getTime() >= startOfThisYear.getTime()) { + return year; + } else { + return year - 1; + } +} + +// See issue: https://github.com/date-fns/date-fns/issues/376 + +function startOfUTCISOWeekYear(dirtyDate) { + requiredArgs(1, arguments); + var year = getUTCISOWeekYear(dirtyDate); + var fourthOfJanuary = new Date(0); + fourthOfJanuary.setUTCFullYear(year, 0, 4); + fourthOfJanuary.setUTCHours(0, 0, 0, 0); + var date = startOfUTCISOWeek(fourthOfJanuary); + return date; +} + +var MILLISECONDS_IN_WEEK$1 = 604800000; // This function will be a part of public API when UTC function will be implemented. +// See issue: https://github.com/date-fns/date-fns/issues/376 + +function getUTCISOWeek(dirtyDate) { + requiredArgs(1, arguments); + var date = toDate(dirtyDate); + var diff = startOfUTCISOWeek(date).getTime() - startOfUTCISOWeekYear(date).getTime(); // Round the number of days to the nearest integer + // because the number of milliseconds in a week is not constant + // (e.g. it's different in the week of the daylight saving time clock shift) + + return Math.round(diff / MILLISECONDS_IN_WEEK$1) + 1; +} + +// See issue: https://github.com/date-fns/date-fns/issues/376 + +function startOfUTCWeek(dirtyDate, dirtyOptions) { + requiredArgs(1, arguments); + var options = dirtyOptions || {}; + var locale = options.locale; + var localeWeekStartsOn = locale && locale.options && locale.options.weekStartsOn; + var defaultWeekStartsOn = localeWeekStartsOn == null ? 0 : toInteger(localeWeekStartsOn); + var weekStartsOn = options.weekStartsOn == null ? defaultWeekStartsOn : toInteger(options.weekStartsOn); // Test if weekStartsOn is between 0 and 6 _and_ is not NaN + + if (!(weekStartsOn >= 0 && weekStartsOn <= 6)) { + throw new RangeError('weekStartsOn must be between 0 and 6 inclusively'); + } + + var date = toDate(dirtyDate); + var day = date.getUTCDay(); + var diff = (day < weekStartsOn ? 7 : 0) + day - weekStartsOn; + date.setUTCDate(date.getUTCDate() - diff); + date.setUTCHours(0, 0, 0, 0); + return date; +} + +// See issue: https://github.com/date-fns/date-fns/issues/376 + +function getUTCWeekYear(dirtyDate, dirtyOptions) { + requiredArgs(1, arguments); + var date = toDate(dirtyDate, dirtyOptions); + var year = date.getUTCFullYear(); + var options = dirtyOptions || {}; + var locale = options.locale; + var localeFirstWeekContainsDate = locale && locale.options && locale.options.firstWeekContainsDate; + var defaultFirstWeekContainsDate = localeFirstWeekContainsDate == null ? 1 : toInteger(localeFirstWeekContainsDate); + var firstWeekContainsDate = options.firstWeekContainsDate == null ? defaultFirstWeekContainsDate : toInteger(options.firstWeekContainsDate); // Test if weekStartsOn is between 1 and 7 _and_ is not NaN + + if (!(firstWeekContainsDate >= 1 && firstWeekContainsDate <= 7)) { + throw new RangeError('firstWeekContainsDate must be between 1 and 7 inclusively'); + } + + var firstWeekOfNextYear = new Date(0); + firstWeekOfNextYear.setUTCFullYear(year + 1, 0, firstWeekContainsDate); + firstWeekOfNextYear.setUTCHours(0, 0, 0, 0); + var startOfNextYear = startOfUTCWeek(firstWeekOfNextYear, dirtyOptions); + var firstWeekOfThisYear = new Date(0); + firstWeekOfThisYear.setUTCFullYear(year, 0, firstWeekContainsDate); + firstWeekOfThisYear.setUTCHours(0, 0, 0, 0); + var startOfThisYear = startOfUTCWeek(firstWeekOfThisYear, dirtyOptions); + + if (date.getTime() >= startOfNextYear.getTime()) { + return year + 1; + } else if (date.getTime() >= startOfThisYear.getTime()) { + return year; + } else { + return year - 1; + } +} + +// See issue: https://github.com/date-fns/date-fns/issues/376 + +function startOfUTCWeekYear(dirtyDate, dirtyOptions) { + requiredArgs(1, arguments); + var options = dirtyOptions || {}; + var locale = options.locale; + var localeFirstWeekContainsDate = locale && locale.options && locale.options.firstWeekContainsDate; + var defaultFirstWeekContainsDate = localeFirstWeekContainsDate == null ? 1 : toInteger(localeFirstWeekContainsDate); + var firstWeekContainsDate = options.firstWeekContainsDate == null ? defaultFirstWeekContainsDate : toInteger(options.firstWeekContainsDate); + var year = getUTCWeekYear(dirtyDate, dirtyOptions); + var firstWeek = new Date(0); + firstWeek.setUTCFullYear(year, 0, firstWeekContainsDate); + firstWeek.setUTCHours(0, 0, 0, 0); + var date = startOfUTCWeek(firstWeek, dirtyOptions); + return date; +} + +var MILLISECONDS_IN_WEEK = 604800000; // This function will be a part of public API when UTC function will be implemented. +// See issue: https://github.com/date-fns/date-fns/issues/376 + +function getUTCWeek(dirtyDate, options) { + requiredArgs(1, arguments); + var date = toDate(dirtyDate); + var diff = startOfUTCWeek(date, options).getTime() - startOfUTCWeekYear(date, options).getTime(); // Round the number of days to the nearest integer + // because the number of milliseconds in a week is not constant + // (e.g. it's different in the week of the daylight saving time clock shift) + + return Math.round(diff / MILLISECONDS_IN_WEEK) + 1; +} + +var dayPeriodEnum = { + am: 'am', + pm: 'pm', + midnight: 'midnight', + noon: 'noon', + morning: 'morning', + afternoon: 'afternoon', + evening: 'evening', + night: 'night' + /* + * | | Unit | | Unit | + * |-----|--------------------------------|-----|--------------------------------| + * | a | AM, PM | A* | Milliseconds in day | + * | b | AM, PM, noon, midnight | B | Flexible day period | + * | c | Stand-alone local day of week | C* | Localized hour w/ day period | + * | d | Day of month | D | Day of year | + * | e | Local day of week | E | Day of week | + * | f | | F* | Day of week in month | + * | g* | Modified Julian day | G | Era | + * | h | Hour [1-12] | H | Hour [0-23] | + * | i! | ISO day of week | I! | ISO week of year | + * | j* | Localized hour w/ day period | J* | Localized hour w/o day period | + * | k | Hour [1-24] | K | Hour [0-11] | + * | l* | (deprecated) | L | Stand-alone month | + * | m | Minute | M | Month | + * | n | | N | | + * | o! | Ordinal number modifier | O | Timezone (GMT) | + * | p! | Long localized time | P! | Long localized date | + * | q | Stand-alone quarter | Q | Quarter | + * | r* | Related Gregorian year | R! | ISO week-numbering year | + * | s | Second | S | Fraction of second | + * | t! | Seconds timestamp | T! | Milliseconds timestamp | + * | u | Extended year | U* | Cyclic year | + * | v* | Timezone (generic non-locat.) | V* | Timezone (location) | + * | w | Local week of year | W* | Week of month | + * | x | Timezone (ISO-8601 w/o Z) | X | Timezone (ISO-8601) | + * | y | Year (abs) | Y | Local week-numbering year | + * | z | Timezone (specific non-locat.) | Z* | Timezone (aliases) | + * + * Letters marked by * are not implemented but reserved by Unicode standard. + * + * Letters marked by ! are non-standard, but implemented by date-fns: + * - `o` modifies the previous token to turn it into an ordinal (see `format` docs) + * - `i` is ISO day of week. For `i` and `ii` is returns numeric ISO week days, + * i.e. 7 for Sunday, 1 for Monday, etc. + * - `I` is ISO week of year, as opposed to `w` which is local week of year. + * - `R` is ISO week-numbering year, as opposed to `Y` which is local week-numbering year. + * `R` is supposed to be used in conjunction with `I` and `i` + * for universal ISO week-numbering date, whereas + * `Y` is supposed to be used in conjunction with `w` and `e` + * for week-numbering date specific to the locale. + * - `P` is long localized date format + * - `p` is long localized time format + */ + +}; +var formatters = { + // Era + G: function (date, token, localize) { + var era = date.getUTCFullYear() > 0 ? 1 : 0; + + switch (token) { + // AD, BC + case 'G': + case 'GG': + case 'GGG': + return localize.era(era, { + width: 'abbreviated' + }); + // A, B + + case 'GGGGG': + return localize.era(era, { + width: 'narrow' + }); + // Anno Domini, Before Christ + + case 'GGGG': + default: + return localize.era(era, { + width: 'wide' + }); + } + }, + // Year + y: function (date, token, localize) { + // Ordinal number + if (token === 'yo') { + var signedYear = date.getUTCFullYear(); // Returns 1 for 1 BC (which is year 0 in JavaScript) + + var year = signedYear > 0 ? signedYear : 1 - signedYear; + return localize.ordinalNumber(year, { + unit: 'year' + }); + } + + return formatters$3.y(date, token); + }, + // Local week-numbering year + Y: function (date, token, localize, options) { + var signedWeekYear = getUTCWeekYear(date, options); // Returns 1 for 1 BC (which is year 0 in JavaScript) + + var weekYear = signedWeekYear > 0 ? signedWeekYear : 1 - signedWeekYear; // Two digit year + + if (token === 'YY') { + var twoDigitYear = weekYear % 100; + return addLeadingZeros(twoDigitYear, 2); + } // Ordinal number + + + if (token === 'Yo') { + return localize.ordinalNumber(weekYear, { + unit: 'year' + }); + } // Padding + + + return addLeadingZeros(weekYear, token.length); + }, + // ISO week-numbering year + R: function (date, token) { + var isoWeekYear = getUTCISOWeekYear(date); // Padding + + return addLeadingZeros(isoWeekYear, token.length); + }, + // Extended year. This is a single number designating the year of this calendar system. + // The main difference between `y` and `u` localizers are B.C. years: + // | Year | `y` | `u` | + // |------|-----|-----| + // | AC 1 | 1 | 1 | + // | BC 1 | 1 | 0 | + // | BC 2 | 2 | -1 | + // Also `yy` always returns the last two digits of a year, + // while `uu` pads single digit years to 2 characters and returns other years unchanged. + u: function (date, token) { + var year = date.getUTCFullYear(); + return addLeadingZeros(year, token.length); + }, + // Quarter + Q: function (date, token, localize) { + var quarter = Math.ceil((date.getUTCMonth() + 1) / 3); + + switch (token) { + // 1, 2, 3, 4 + case 'Q': + return String(quarter); + // 01, 02, 03, 04 + + case 'QQ': + return addLeadingZeros(quarter, 2); + // 1st, 2nd, 3rd, 4th + + case 'Qo': + return localize.ordinalNumber(quarter, { + unit: 'quarter' + }); + // Q1, Q2, Q3, Q4 + + case 'QQQ': + return localize.quarter(quarter, { + width: 'abbreviated', + context: 'formatting' + }); + // 1, 2, 3, 4 (narrow quarter; could be not numerical) + + case 'QQQQQ': + return localize.quarter(quarter, { + width: 'narrow', + context: 'formatting' + }); + // 1st quarter, 2nd quarter, ... + + case 'QQQQ': + default: + return localize.quarter(quarter, { + width: 'wide', + context: 'formatting' + }); + } + }, + // Stand-alone quarter + q: function (date, token, localize) { + var quarter = Math.ceil((date.getUTCMonth() + 1) / 3); + + switch (token) { + // 1, 2, 3, 4 + case 'q': + return String(quarter); + // 01, 02, 03, 04 + + case 'qq': + return addLeadingZeros(quarter, 2); + // 1st, 2nd, 3rd, 4th + + case 'qo': + return localize.ordinalNumber(quarter, { + unit: 'quarter' + }); + // Q1, Q2, Q3, Q4 + + case 'qqq': + return localize.quarter(quarter, { + width: 'abbreviated', + context: 'standalone' + }); + // 1, 2, 3, 4 (narrow quarter; could be not numerical) + + case 'qqqqq': + return localize.quarter(quarter, { + width: 'narrow', + context: 'standalone' + }); + // 1st quarter, 2nd quarter, ... + + case 'qqqq': + default: + return localize.quarter(quarter, { + width: 'wide', + context: 'standalone' + }); + } + }, + // Month + M: function (date, token, localize) { + var month = date.getUTCMonth(); + + switch (token) { + case 'M': + case 'MM': + return formatters$3.M(date, token); + // 1st, 2nd, ..., 12th + + case 'Mo': + return localize.ordinalNumber(month + 1, { + unit: 'month' + }); + // Jan, Feb, ..., Dec + + case 'MMM': + return localize.month(month, { + width: 'abbreviated', + context: 'formatting' + }); + // J, F, ..., D + + case 'MMMMM': + return localize.month(month, { + width: 'narrow', + context: 'formatting' + }); + // January, February, ..., December + + case 'MMMM': + default: + return localize.month(month, { + width: 'wide', + context: 'formatting' + }); + } + }, + // Stand-alone month + L: function (date, token, localize) { + var month = date.getUTCMonth(); + + switch (token) { + // 1, 2, ..., 12 + case 'L': + return String(month + 1); + // 01, 02, ..., 12 + + case 'LL': + return addLeadingZeros(month + 1, 2); + // 1st, 2nd, ..., 12th + + case 'Lo': + return localize.ordinalNumber(month + 1, { + unit: 'month' + }); + // Jan, Feb, ..., Dec + + case 'LLL': + return localize.month(month, { + width: 'abbreviated', + context: 'standalone' + }); + // J, F, ..., D + + case 'LLLLL': + return localize.month(month, { + width: 'narrow', + context: 'standalone' + }); + // January, February, ..., December + + case 'LLLL': + default: + return localize.month(month, { + width: 'wide', + context: 'standalone' + }); + } + }, + // Local week of year + w: function (date, token, localize, options) { + var week = getUTCWeek(date, options); + + if (token === 'wo') { + return localize.ordinalNumber(week, { + unit: 'week' + }); + } + + return addLeadingZeros(week, token.length); + }, + // ISO week of year + I: function (date, token, localize) { + var isoWeek = getUTCISOWeek(date); + + if (token === 'Io') { + return localize.ordinalNumber(isoWeek, { + unit: 'week' + }); + } + + return addLeadingZeros(isoWeek, token.length); + }, + // Day of the month + d: function (date, token, localize) { + if (token === 'do') { + return localize.ordinalNumber(date.getUTCDate(), { + unit: 'date' + }); + } + + return formatters$3.d(date, token); + }, + // Day of year + D: function (date, token, localize) { + var dayOfYear = getUTCDayOfYear(date); + + if (token === 'Do') { + return localize.ordinalNumber(dayOfYear, { + unit: 'dayOfYear' + }); + } + + return addLeadingZeros(dayOfYear, token.length); + }, + // Day of week + E: function (date, token, localize) { + var dayOfWeek = date.getUTCDay(); + + switch (token) { + // Tue + case 'E': + case 'EE': + case 'EEE': + return localize.day(dayOfWeek, { + width: 'abbreviated', + context: 'formatting' + }); + // T + + case 'EEEEE': + return localize.day(dayOfWeek, { + width: 'narrow', + context: 'formatting' + }); + // Tu + + case 'EEEEEE': + return localize.day(dayOfWeek, { + width: 'short', + context: 'formatting' + }); + // Tuesday + + case 'EEEE': + default: + return localize.day(dayOfWeek, { + width: 'wide', + context: 'formatting' + }); + } + }, + // Local day of week + e: function (date, token, localize, options) { + var dayOfWeek = date.getUTCDay(); + var localDayOfWeek = (dayOfWeek - options.weekStartsOn + 8) % 7 || 7; + + switch (token) { + // Numerical value (Nth day of week with current locale or weekStartsOn) + case 'e': + return String(localDayOfWeek); + // Padded numerical value + + case 'ee': + return addLeadingZeros(localDayOfWeek, 2); + // 1st, 2nd, ..., 7th + + case 'eo': + return localize.ordinalNumber(localDayOfWeek, { + unit: 'day' + }); + + case 'eee': + return localize.day(dayOfWeek, { + width: 'abbreviated', + context: 'formatting' + }); + // T + + case 'eeeee': + return localize.day(dayOfWeek, { + width: 'narrow', + context: 'formatting' + }); + // Tu + + case 'eeeeee': + return localize.day(dayOfWeek, { + width: 'short', + context: 'formatting' + }); + // Tuesday + + case 'eeee': + default: + return localize.day(dayOfWeek, { + width: 'wide', + context: 'formatting' + }); + } + }, + // Stand-alone local day of week + c: function (date, token, localize, options) { + var dayOfWeek = date.getUTCDay(); + var localDayOfWeek = (dayOfWeek - options.weekStartsOn + 8) % 7 || 7; + + switch (token) { + // Numerical value (same as in `e`) + case 'c': + return String(localDayOfWeek); + // Padded numerical value + + case 'cc': + return addLeadingZeros(localDayOfWeek, token.length); + // 1st, 2nd, ..., 7th + + case 'co': + return localize.ordinalNumber(localDayOfWeek, { + unit: 'day' + }); + + case 'ccc': + return localize.day(dayOfWeek, { + width: 'abbreviated', + context: 'standalone' + }); + // T + + case 'ccccc': + return localize.day(dayOfWeek, { + width: 'narrow', + context: 'standalone' + }); + // Tu + + case 'cccccc': + return localize.day(dayOfWeek, { + width: 'short', + context: 'standalone' + }); + // Tuesday + + case 'cccc': + default: + return localize.day(dayOfWeek, { + width: 'wide', + context: 'standalone' + }); + } + }, + // ISO day of week + i: function (date, token, localize) { + var dayOfWeek = date.getUTCDay(); + var isoDayOfWeek = dayOfWeek === 0 ? 7 : dayOfWeek; + + switch (token) { + // 2 + case 'i': + return String(isoDayOfWeek); + // 02 + + case 'ii': + return addLeadingZeros(isoDayOfWeek, token.length); + // 2nd + + case 'io': + return localize.ordinalNumber(isoDayOfWeek, { + unit: 'day' + }); + // Tue + + case 'iii': + return localize.day(dayOfWeek, { + width: 'abbreviated', + context: 'formatting' + }); + // T + + case 'iiiii': + return localize.day(dayOfWeek, { + width: 'narrow', + context: 'formatting' + }); + // Tu + + case 'iiiiii': + return localize.day(dayOfWeek, { + width: 'short', + context: 'formatting' + }); + // Tuesday + + case 'iiii': + default: + return localize.day(dayOfWeek, { + width: 'wide', + context: 'formatting' + }); + } + }, + // AM or PM + a: function (date, token, localize) { + var hours = date.getUTCHours(); + var dayPeriodEnumValue = hours / 12 >= 1 ? 'pm' : 'am'; + + switch (token) { + case 'a': + case 'aa': + return localize.dayPeriod(dayPeriodEnumValue, { + width: 'abbreviated', + context: 'formatting' + }); + + case 'aaa': + return localize.dayPeriod(dayPeriodEnumValue, { + width: 'abbreviated', + context: 'formatting' + }).toLowerCase(); + + case 'aaaaa': + return localize.dayPeriod(dayPeriodEnumValue, { + width: 'narrow', + context: 'formatting' + }); + + case 'aaaa': + default: + return localize.dayPeriod(dayPeriodEnumValue, { + width: 'wide', + context: 'formatting' + }); + } + }, + // AM, PM, midnight, noon + b: function (date, token, localize) { + var hours = date.getUTCHours(); + var dayPeriodEnumValue; + + if (hours === 12) { + dayPeriodEnumValue = dayPeriodEnum.noon; + } else if (hours === 0) { + dayPeriodEnumValue = dayPeriodEnum.midnight; + } else { + dayPeriodEnumValue = hours / 12 >= 1 ? 'pm' : 'am'; + } + + switch (token) { + case 'b': + case 'bb': + return localize.dayPeriod(dayPeriodEnumValue, { + width: 'abbreviated', + context: 'formatting' + }); + + case 'bbb': + return localize.dayPeriod(dayPeriodEnumValue, { + width: 'abbreviated', + context: 'formatting' + }).toLowerCase(); + + case 'bbbbb': + return localize.dayPeriod(dayPeriodEnumValue, { + width: 'narrow', + context: 'formatting' + }); + + case 'bbbb': + default: + return localize.dayPeriod(dayPeriodEnumValue, { + width: 'wide', + context: 'formatting' + }); + } + }, + // in the morning, in the afternoon, in the evening, at night + B: function (date, token, localize) { + var hours = date.getUTCHours(); + var dayPeriodEnumValue; + + if (hours >= 17) { + dayPeriodEnumValue = dayPeriodEnum.evening; + } else if (hours >= 12) { + dayPeriodEnumValue = dayPeriodEnum.afternoon; + } else if (hours >= 4) { + dayPeriodEnumValue = dayPeriodEnum.morning; + } else { + dayPeriodEnumValue = dayPeriodEnum.night; + } + + switch (token) { + case 'B': + case 'BB': + case 'BBB': + return localize.dayPeriod(dayPeriodEnumValue, { + width: 'abbreviated', + context: 'formatting' + }); + + case 'BBBBB': + return localize.dayPeriod(dayPeriodEnumValue, { + width: 'narrow', + context: 'formatting' + }); + + case 'BBBB': + default: + return localize.dayPeriod(dayPeriodEnumValue, { + width: 'wide', + context: 'formatting' + }); + } + }, + // Hour [1-12] + h: function (date, token, localize) { + if (token === 'ho') { + var hours = date.getUTCHours() % 12; + if (hours === 0) hours = 12; + return localize.ordinalNumber(hours, { + unit: 'hour' + }); + } + + return formatters$3.h(date, token); + }, + // Hour [0-23] + H: function (date, token, localize) { + if (token === 'Ho') { + return localize.ordinalNumber(date.getUTCHours(), { + unit: 'hour' + }); + } + + return formatters$3.H(date, token); + }, + // Hour [0-11] + K: function (date, token, localize) { + var hours = date.getUTCHours() % 12; + + if (token === 'Ko') { + return localize.ordinalNumber(hours, { + unit: 'hour' + }); + } + + return addLeadingZeros(hours, token.length); + }, + // Hour [1-24] + k: function (date, token, localize) { + var hours = date.getUTCHours(); + if (hours === 0) hours = 24; + + if (token === 'ko') { + return localize.ordinalNumber(hours, { + unit: 'hour' + }); + } + + return addLeadingZeros(hours, token.length); + }, + // Minute + m: function (date, token, localize) { + if (token === 'mo') { + return localize.ordinalNumber(date.getUTCMinutes(), { + unit: 'minute' + }); + } + + return formatters$3.m(date, token); + }, + // Second + s: function (date, token, localize) { + if (token === 'so') { + return localize.ordinalNumber(date.getUTCSeconds(), { + unit: 'second' + }); + } + + return formatters$3.s(date, token); + }, + // Fraction of second + S: function (date, token) { + return formatters$3.S(date, token); + }, + // Timezone (ISO-8601. If offset is 0, output is always `'Z'`) + X: function (date, token, _localize, options) { + var originalDate = options._originalDate || date; + var timezoneOffset = originalDate.getTimezoneOffset(); + + if (timezoneOffset === 0) { + return 'Z'; + } + + switch (token) { + // Hours and optional minutes + case 'X': + return formatTimezoneWithOptionalMinutes(timezoneOffset); + // Hours, minutes and optional seconds without `:` delimiter + // Note: neither ISO-8601 nor JavaScript supports seconds in timezone offsets + // so this token always has the same output as `XX` + + case 'XXXX': + case 'XX': + // Hours and minutes without `:` delimiter + return formatTimezone(timezoneOffset); + // Hours, minutes and optional seconds with `:` delimiter + // Note: neither ISO-8601 nor JavaScript supports seconds in timezone offsets + // so this token always has the same output as `XXX` + + case 'XXXXX': + case 'XXX': // Hours and minutes with `:` delimiter + + default: + return formatTimezone(timezoneOffset, ':'); + } + }, + // Timezone (ISO-8601. If offset is 0, output is `'+00:00'` or equivalent) + x: function (date, token, _localize, options) { + var originalDate = options._originalDate || date; + var timezoneOffset = originalDate.getTimezoneOffset(); + + switch (token) { + // Hours and optional minutes + case 'x': + return formatTimezoneWithOptionalMinutes(timezoneOffset); + // Hours, minutes and optional seconds without `:` delimiter + // Note: neither ISO-8601 nor JavaScript supports seconds in timezone offsets + // so this token always has the same output as `xx` + + case 'xxxx': + case 'xx': + // Hours and minutes without `:` delimiter + return formatTimezone(timezoneOffset); + // Hours, minutes and optional seconds with `:` delimiter + // Note: neither ISO-8601 nor JavaScript supports seconds in timezone offsets + // so this token always has the same output as `xxx` + + case 'xxxxx': + case 'xxx': // Hours and minutes with `:` delimiter + + default: + return formatTimezone(timezoneOffset, ':'); + } + }, + // Timezone (GMT) + O: function (date, token, _localize, options) { + var originalDate = options._originalDate || date; + var timezoneOffset = originalDate.getTimezoneOffset(); + + switch (token) { + // Short + case 'O': + case 'OO': + case 'OOO': + return 'GMT' + formatTimezoneShort(timezoneOffset, ':'); + // Long + + case 'OOOO': + default: + return 'GMT' + formatTimezone(timezoneOffset, ':'); + } + }, + // Timezone (specific non-location) + z: function (date, token, _localize, options) { + var originalDate = options._originalDate || date; + var timezoneOffset = originalDate.getTimezoneOffset(); + + switch (token) { + // Short + case 'z': + case 'zz': + case 'zzz': + return 'GMT' + formatTimezoneShort(timezoneOffset, ':'); + // Long + + case 'zzzz': + default: + return 'GMT' + formatTimezone(timezoneOffset, ':'); + } + }, + // Seconds timestamp + t: function (date, token, _localize, options) { + var originalDate = options._originalDate || date; + var timestamp = Math.floor(originalDate.getTime() / 1000); + return addLeadingZeros(timestamp, token.length); + }, + // Milliseconds timestamp + T: function (date, token, _localize, options) { + var originalDate = options._originalDate || date; + var timestamp = originalDate.getTime(); + return addLeadingZeros(timestamp, token.length); + } +}; + +function formatTimezoneShort(offset, dirtyDelimiter) { + var sign = offset > 0 ? '-' : '+'; + var absOffset = Math.abs(offset); + var hours = Math.floor(absOffset / 60); + var minutes = absOffset % 60; + + if (minutes === 0) { + return sign + String(hours); + } + + var delimiter = dirtyDelimiter || ''; + return sign + String(hours) + delimiter + addLeadingZeros(minutes, 2); +} + +function formatTimezoneWithOptionalMinutes(offset, dirtyDelimiter) { + if (offset % 60 === 0) { + var sign = offset > 0 ? '-' : '+'; + return sign + addLeadingZeros(Math.abs(offset) / 60, 2); + } + + return formatTimezone(offset, dirtyDelimiter); +} + +function formatTimezone(offset, dirtyDelimiter) { + var delimiter = dirtyDelimiter || ''; + var sign = offset > 0 ? '-' : '+'; + var absOffset = Math.abs(offset); + var hours = addLeadingZeros(Math.floor(absOffset / 60), 2); + var minutes = addLeadingZeros(absOffset % 60, 2); + return sign + hours + delimiter + minutes; +} + +var formatters$1 = formatters; + +function dateLongFormatter(pattern, formatLong) { + switch (pattern) { + case 'P': + return formatLong.date({ + width: 'short' + }); + + case 'PP': + return formatLong.date({ + width: 'medium' + }); + + case 'PPP': + return formatLong.date({ + width: 'long' + }); + + case 'PPPP': + default: + return formatLong.date({ + width: 'full' + }); + } +} + +function timeLongFormatter(pattern, formatLong) { + switch (pattern) { + case 'p': + return formatLong.time({ + width: 'short' + }); + + case 'pp': + return formatLong.time({ + width: 'medium' + }); + + case 'ppp': + return formatLong.time({ + width: 'long' + }); + + case 'pppp': + default: + return formatLong.time({ + width: 'full' + }); + } +} + +function dateTimeLongFormatter(pattern, formatLong) { + var matchResult = pattern.match(/(P+)(p+)?/); + var datePattern = matchResult[1]; + var timePattern = matchResult[2]; + + if (!timePattern) { + return dateLongFormatter(pattern, formatLong); + } + + var dateTimeFormat; + + switch (datePattern) { + case 'P': + dateTimeFormat = formatLong.dateTime({ + width: 'short' + }); + break; + + case 'PP': + dateTimeFormat = formatLong.dateTime({ + width: 'medium' + }); + break; + + case 'PPP': + dateTimeFormat = formatLong.dateTime({ + width: 'long' + }); + break; + + case 'PPPP': + default: + dateTimeFormat = formatLong.dateTime({ + width: 'full' + }); + break; + } + + return dateTimeFormat.replace('{{date}}', dateLongFormatter(datePattern, formatLong)).replace('{{time}}', timeLongFormatter(timePattern, formatLong)); +} + +var longFormatters = { + p: timeLongFormatter, + P: dateTimeLongFormatter +}; +var longFormatters$1 = longFormatters; + +var protectedDayOfYearTokens = ['D', 'DD']; +var protectedWeekYearTokens = ['YY', 'YYYY']; +function isProtectedDayOfYearToken(token) { + return protectedDayOfYearTokens.indexOf(token) !== -1; +} +function isProtectedWeekYearToken(token) { + return protectedWeekYearTokens.indexOf(token) !== -1; +} +function throwProtectedError(token, format, input) { + if (token === 'YYYY') { + throw new RangeError("Use `yyyy` instead of `YYYY` (in `".concat(format, "`) for formatting years to the input `").concat(input, "`; see: https://git.io/fxCyr")); + } else if (token === 'YY') { + throw new RangeError("Use `yy` instead of `YY` (in `".concat(format, "`) for formatting years to the input `").concat(input, "`; see: https://git.io/fxCyr")); + } else if (token === 'D') { + throw new RangeError("Use `d` instead of `D` (in `".concat(format, "`) for formatting days of the month to the input `").concat(input, "`; see: https://git.io/fxCyr")); + } else if (token === 'DD') { + throw new RangeError("Use `dd` instead of `DD` (in `".concat(format, "`) for formatting days of the month to the input `").concat(input, "`; see: https://git.io/fxCyr")); + } +} + +// - [yYQqMLwIdDecihHKkms]o matches any available ordinal number token +// (one of the certain letters followed by `o`) +// - (\w)\1* matches any sequences of the same letter +// - '' matches two quote characters in a row +// - '(''|[^'])+('|$) matches anything surrounded by two quote characters ('), +// except a single quote symbol, which ends the sequence. +// Two quote characters do not end the sequence. +// If there is no matching single quote +// then the sequence will continue until the end of the string. +// - . matches any single character unmatched by previous parts of the RegExps + +var formattingTokensRegExp$1 = /[yYQqMLwIdDecihHKkms]o|(\w)\1*|''|'(''|[^'])+('|$)|./g; // This RegExp catches symbols escaped by quotes, and also +// sequences of symbols P, p, and the combinations like `PPPPPPPppppp` + +var longFormattingTokensRegExp$1 = /P+p+|P+|p+|''|'(''|[^'])+('|$)|./g; +var escapedStringRegExp$1 = /^'([^]*?)'?$/; +var doubleQuoteRegExp$1 = /''/g; +var unescapedLatinCharacterRegExp$1 = /[a-zA-Z]/; +/** + * @name format + * @category Common Helpers + * @summary Format the date. + * + * @description + * Return the formatted date string in the given format. The result may vary by locale. + * + * > ⚠️ Please note that the `format` tokens differ from Moment.js and other libraries. + * > See: https://git.io/fxCyr + * + * The characters wrapped between two single quotes characters (') are escaped. + * Two single quotes in a row, whether inside or outside a quoted sequence, represent a 'real' single quote. + * (see the last example) + * + * Format of the string is based on Unicode Technical Standard #35: + * https://www.unicode.org/reports/tr35/tr35-dates.html#Date_Field_Symbol_Table + * with a few additions (see note 7 below the table). + * + * Accepted patterns: + * | Unit | Pattern | Result examples | Notes | + * |---------------------------------|---------|-----------------------------------|-------| + * | Era | G..GGG | AD, BC | | + * | | GGGG | Anno Domini, Before Christ | 2 | + * | | GGGGG | A, B | | + * | Calendar year | y | 44, 1, 1900, 2017 | 5 | + * | | yo | 44th, 1st, 0th, 17th | 5,7 | + * | | yy | 44, 01, 00, 17 | 5 | + * | | yyy | 044, 001, 1900, 2017 | 5 | + * | | yyyy | 0044, 0001, 1900, 2017 | 5 | + * | | yyyyy | ... | 3,5 | + * | Local week-numbering year | Y | 44, 1, 1900, 2017 | 5 | + * | | Yo | 44th, 1st, 1900th, 2017th | 5,7 | + * | | YY | 44, 01, 00, 17 | 5,8 | + * | | YYY | 044, 001, 1900, 2017 | 5 | + * | | YYYY | 0044, 0001, 1900, 2017 | 5,8 | + * | | YYYYY | ... | 3,5 | + * | ISO week-numbering year | R | -43, 0, 1, 1900, 2017 | 5,7 | + * | | RR | -43, 00, 01, 1900, 2017 | 5,7 | + * | | RRR | -043, 000, 001, 1900, 2017 | 5,7 | + * | | RRRR | -0043, 0000, 0001, 1900, 2017 | 5,7 | + * | | RRRRR | ... | 3,5,7 | + * | Extended year | u | -43, 0, 1, 1900, 2017 | 5 | + * | | uu | -43, 01, 1900, 2017 | 5 | + * | | uuu | -043, 001, 1900, 2017 | 5 | + * | | uuuu | -0043, 0001, 1900, 2017 | 5 | + * | | uuuuu | ... | 3,5 | + * | Quarter (formatting) | Q | 1, 2, 3, 4 | | + * | | Qo | 1st, 2nd, 3rd, 4th | 7 | + * | | QQ | 01, 02, 03, 04 | | + * | | QQQ | Q1, Q2, Q3, Q4 | | + * | | QQQQ | 1st quarter, 2nd quarter, ... | 2 | + * | | QQQQQ | 1, 2, 3, 4 | 4 | + * | Quarter (stand-alone) | q | 1, 2, 3, 4 | | + * | | qo | 1st, 2nd, 3rd, 4th | 7 | + * | | qq | 01, 02, 03, 04 | | + * | | qqq | Q1, Q2, Q3, Q4 | | + * | | qqqq | 1st quarter, 2nd quarter, ... | 2 | + * | | qqqqq | 1, 2, 3, 4 | 4 | + * | Month (formatting) | M | 1, 2, ..., 12 | | + * | | Mo | 1st, 2nd, ..., 12th | 7 | + * | | MM | 01, 02, ..., 12 | | + * | | MMM | Jan, Feb, ..., Dec | | + * | | MMMM | January, February, ..., December | 2 | + * | | MMMMM | J, F, ..., D | | + * | Month (stand-alone) | L | 1, 2, ..., 12 | | + * | | Lo | 1st, 2nd, ..., 12th | 7 | + * | | LL | 01, 02, ..., 12 | | + * | | LLL | Jan, Feb, ..., Dec | | + * | | LLLL | January, February, ..., December | 2 | + * | | LLLLL | J, F, ..., D | | + * | Local week of year | w | 1, 2, ..., 53 | | + * | | wo | 1st, 2nd, ..., 53th | 7 | + * | | ww | 01, 02, ..., 53 | | + * | ISO week of year | I | 1, 2, ..., 53 | 7 | + * | | Io | 1st, 2nd, ..., 53th | 7 | + * | | II | 01, 02, ..., 53 | 7 | + * | Day of month | d | 1, 2, ..., 31 | | + * | | do | 1st, 2nd, ..., 31st | 7 | + * | | dd | 01, 02, ..., 31 | | + * | Day of year | D | 1, 2, ..., 365, 366 | 9 | + * | | Do | 1st, 2nd, ..., 365th, 366th | 7 | + * | | DD | 01, 02, ..., 365, 366 | 9 | + * | | DDD | 001, 002, ..., 365, 366 | | + * | | DDDD | ... | 3 | + * | Day of week (formatting) | E..EEE | Mon, Tue, Wed, ..., Sun | | + * | | EEEE | Monday, Tuesday, ..., Sunday | 2 | + * | | EEEEE | M, T, W, T, F, S, S | | + * | | EEEEEE | Mo, Tu, We, Th, Fr, Su, Sa | | + * | ISO day of week (formatting) | i | 1, 2, 3, ..., 7 | 7 | + * | | io | 1st, 2nd, ..., 7th | 7 | + * | | ii | 01, 02, ..., 07 | 7 | + * | | iii | Mon, Tue, Wed, ..., Sun | 7 | + * | | iiii | Monday, Tuesday, ..., Sunday | 2,7 | + * | | iiiii | M, T, W, T, F, S, S | 7 | + * | | iiiiii | Mo, Tu, We, Th, Fr, Su, Sa | 7 | + * | Local day of week (formatting) | e | 2, 3, 4, ..., 1 | | + * | | eo | 2nd, 3rd, ..., 1st | 7 | + * | | ee | 02, 03, ..., 01 | | + * | | eee | Mon, Tue, Wed, ..., Sun | | + * | | eeee | Monday, Tuesday, ..., Sunday | 2 | + * | | eeeee | M, T, W, T, F, S, S | | + * | | eeeeee | Mo, Tu, We, Th, Fr, Su, Sa | | + * | Local day of week (stand-alone) | c | 2, 3, 4, ..., 1 | | + * | | co | 2nd, 3rd, ..., 1st | 7 | + * | | cc | 02, 03, ..., 01 | | + * | | ccc | Mon, Tue, Wed, ..., Sun | | + * | | cccc | Monday, Tuesday, ..., Sunday | 2 | + * | | ccccc | M, T, W, T, F, S, S | | + * | | cccccc | Mo, Tu, We, Th, Fr, Su, Sa | | + * | AM, PM | a..aa | AM, PM | | + * | | aaa | am, pm | | + * | | aaaa | a.m., p.m. | 2 | + * | | aaaaa | a, p | | + * | AM, PM, noon, midnight | b..bb | AM, PM, noon, midnight | | + * | | bbb | am, pm, noon, midnight | | + * | | bbbb | a.m., p.m., noon, midnight | 2 | + * | | bbbbb | a, p, n, mi | | + * | Flexible day period | B..BBB | at night, in the morning, ... | | + * | | BBBB | at night, in the morning, ... | 2 | + * | | BBBBB | at night, in the morning, ... | | + * | Hour [1-12] | h | 1, 2, ..., 11, 12 | | + * | | ho | 1st, 2nd, ..., 11th, 12th | 7 | + * | | hh | 01, 02, ..., 11, 12 | | + * | Hour [0-23] | H | 0, 1, 2, ..., 23 | | + * | | Ho | 0th, 1st, 2nd, ..., 23rd | 7 | + * | | HH | 00, 01, 02, ..., 23 | | + * | Hour [0-11] | K | 1, 2, ..., 11, 0 | | + * | | Ko | 1st, 2nd, ..., 11th, 0th | 7 | + * | | KK | 01, 02, ..., 11, 00 | | + * | Hour [1-24] | k | 24, 1, 2, ..., 23 | | + * | | ko | 24th, 1st, 2nd, ..., 23rd | 7 | + * | | kk | 24, 01, 02, ..., 23 | | + * | Minute | m | 0, 1, ..., 59 | | + * | | mo | 0th, 1st, ..., 59th | 7 | + * | | mm | 00, 01, ..., 59 | | + * | Second | s | 0, 1, ..., 59 | | + * | | so | 0th, 1st, ..., 59th | 7 | + * | | ss | 00, 01, ..., 59 | | + * | Fraction of second | S | 0, 1, ..., 9 | | + * | | SS | 00, 01, ..., 99 | | + * | | SSS | 000, 0001, ..., 999 | | + * | | SSSS | ... | 3 | + * | Timezone (ISO-8601 w/ Z) | X | -08, +0530, Z | | + * | | XX | -0800, +0530, Z | | + * | | XXX | -08:00, +05:30, Z | | + * | | XXXX | -0800, +0530, Z, +123456 | 2 | + * | | XXXXX | -08:00, +05:30, Z, +12:34:56 | | + * | Timezone (ISO-8601 w/o Z) | x | -08, +0530, +00 | | + * | | xx | -0800, +0530, +0000 | | + * | | xxx | -08:00, +05:30, +00:00 | 2 | + * | | xxxx | -0800, +0530, +0000, +123456 | | + * | | xxxxx | -08:00, +05:30, +00:00, +12:34:56 | | + * | Timezone (GMT) | O...OOO | GMT-8, GMT+5:30, GMT+0 | | + * | | OOOO | GMT-08:00, GMT+05:30, GMT+00:00 | 2 | + * | Timezone (specific non-locat.) | z...zzz | GMT-8, GMT+5:30, GMT+0 | 6 | + * | | zzzz | GMT-08:00, GMT+05:30, GMT+00:00 | 2,6 | + * | Seconds timestamp | t | 512969520 | 7 | + * | | tt | ... | 3,7 | + * | Milliseconds timestamp | T | 512969520900 | 7 | + * | | TT | ... | 3,7 | + * | Long localized date | P | 04/29/1453 | 7 | + * | | PP | Apr 29, 1453 | 7 | + * | | PPP | April 29th, 1453 | 7 | + * | | PPPP | Friday, April 29th, 1453 | 2,7 | + * | Long localized time | p | 12:00 AM | 7 | + * | | pp | 12:00:00 AM | 7 | + * | | ppp | 12:00:00 AM GMT+2 | 7 | + * | | pppp | 12:00:00 AM GMT+02:00 | 2,7 | + * | Combination of date and time | Pp | 04/29/1453, 12:00 AM | 7 | + * | | PPpp | Apr 29, 1453, 12:00:00 AM | 7 | + * | | PPPppp | April 29th, 1453 at ... | 7 | + * | | PPPPpppp| Friday, April 29th, 1453 at ... | 2,7 | + * Notes: + * 1. "Formatting" units (e.g. formatting quarter) in the default en-US locale + * are the same as "stand-alone" units, but are different in some languages. + * "Formatting" units are declined according to the rules of the language + * in the context of a date. "Stand-alone" units are always nominative singular: + * + * `format(new Date(2017, 10, 6), 'do LLLL', {locale: cs}) //=> '6. listopad'` + * + * `format(new Date(2017, 10, 6), 'do MMMM', {locale: cs}) //=> '6. listopadu'` + * + * 2. Any sequence of the identical letters is a pattern, unless it is escaped by + * the single quote characters (see below). + * If the sequence is longer than listed in table (e.g. `EEEEEEEEEEE`) + * the output will be the same as default pattern for this unit, usually + * the longest one (in case of ISO weekdays, `EEEE`). Default patterns for units + * are marked with "2" in the last column of the table. + * + * `format(new Date(2017, 10, 6), 'MMM') //=> 'Nov'` + * + * `format(new Date(2017, 10, 6), 'MMMM') //=> 'November'` + * + * `format(new Date(2017, 10, 6), 'MMMMM') //=> 'N'` + * + * `format(new Date(2017, 10, 6), 'MMMMMM') //=> 'November'` + * + * `format(new Date(2017, 10, 6), 'MMMMMMM') //=> 'November'` + * + * 3. Some patterns could be unlimited length (such as `yyyyyyyy`). + * The output will be padded with zeros to match the length of the pattern. + * + * `format(new Date(2017, 10, 6), 'yyyyyyyy') //=> '00002017'` + * + * 4. `QQQQQ` and `qqqqq` could be not strictly numerical in some locales. + * These tokens represent the shortest form of the quarter. + * + * 5. The main difference between `y` and `u` patterns are B.C. years: + * + * | Year | `y` | `u` | + * |------|-----|-----| + * | AC 1 | 1 | 1 | + * | BC 1 | 1 | 0 | + * | BC 2 | 2 | -1 | + * + * Also `yy` always returns the last two digits of a year, + * while `uu` pads single digit years to 2 characters and returns other years unchanged: + * + * | Year | `yy` | `uu` | + * |------|------|------| + * | 1 | 01 | 01 | + * | 14 | 14 | 14 | + * | 376 | 76 | 376 | + * | 1453 | 53 | 1453 | + * + * The same difference is true for local and ISO week-numbering years (`Y` and `R`), + * except local week-numbering years are dependent on `options.weekStartsOn` + * and `options.firstWeekContainsDate` (compare [getISOWeekYear]{@link https://date-fns.org/docs/getISOWeekYear} + * and [getWeekYear]{@link https://date-fns.org/docs/getWeekYear}). + * + * 6. Specific non-location timezones are currently unavailable in `date-fns`, + * so right now these tokens fall back to GMT timezones. + * + * 7. These patterns are not in the Unicode Technical Standard #35: + * - `i`: ISO day of week + * - `I`: ISO week of year + * - `R`: ISO week-numbering year + * - `t`: seconds timestamp + * - `T`: milliseconds timestamp + * - `o`: ordinal number modifier + * - `P`: long localized date + * - `p`: long localized time + * + * 8. `YY` and `YYYY` tokens represent week-numbering years but they are often confused with years. + * You should enable `options.useAdditionalWeekYearTokens` to use them. See: https://git.io/fxCyr + * + * 9. `D` and `DD` tokens represent days of the year but they are ofthen confused with days of the month. + * You should enable `options.useAdditionalDayOfYearTokens` to use them. See: https://git.io/fxCyr + * + * ### v2.0.0 breaking changes: + * + * - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes). + * + * - The second argument is now required for the sake of explicitness. + * + * ```javascript + * // Before v2.0.0 + * format(new Date(2016, 0, 1)) + * + * // v2.0.0 onward + * format(new Date(2016, 0, 1), "yyyy-MM-dd'T'HH:mm:ss.SSSxxx") + * ``` + * + * - New format string API for `format` function + * which is based on [Unicode Technical Standard #35](https://www.unicode.org/reports/tr35/tr35-dates.html#Date_Field_Symbol_Table). + * See [this post](https://blog.date-fns.org/post/unicode-tokens-in-date-fns-v2-sreatyki91jg) for more details. + * + * - Characters are now escaped using single quote symbols (`'`) instead of square brackets. + * + * @param {Date|Number} date - the original date + * @param {String} format - the string of tokens + * @param {Object} [options] - an object with options. + * @param {Locale} [options.locale=defaultLocale] - the locale object. See [Locale]{@link https://date-fns.org/docs/Locale} + * @param {0|1|2|3|4|5|6} [options.weekStartsOn=0] - the index of the first day of the week (0 - Sunday) + * @param {Number} [options.firstWeekContainsDate=1] - the day of January, which is + * @param {Boolean} [options.useAdditionalWeekYearTokens=false] - if true, allows usage of the week-numbering year tokens `YY` and `YYYY`; + * see: https://git.io/fxCyr + * @param {Boolean} [options.useAdditionalDayOfYearTokens=false] - if true, allows usage of the day of year tokens `D` and `DD`; + * see: https://git.io/fxCyr + * @returns {String} the formatted date string + * @throws {TypeError} 2 arguments required + * @throws {RangeError} `date` must not be Invalid Date + * @throws {RangeError} `options.locale` must contain `localize` property + * @throws {RangeError} `options.locale` must contain `formatLong` property + * @throws {RangeError} `options.weekStartsOn` must be between 0 and 6 + * @throws {RangeError} `options.firstWeekContainsDate` must be between 1 and 7 + * @throws {RangeError} use `yyyy` instead of `YYYY` for formatting years using [format provided] to the input [input provided]; see: https://git.io/fxCyr + * @throws {RangeError} use `yy` instead of `YY` for formatting years using [format provided] to the input [input provided]; see: https://git.io/fxCyr + * @throws {RangeError} use `d` instead of `D` for formatting days of the month using [format provided] to the input [input provided]; see: https://git.io/fxCyr + * @throws {RangeError} use `dd` instead of `DD` for formatting days of the month using [format provided] to the input [input provided]; see: https://git.io/fxCyr + * @throws {RangeError} format string contains an unescaped latin alphabet character + * + * @example + * // Represent 11 February 2014 in middle-endian format: + * var result = format(new Date(2014, 1, 11), 'MM/dd/yyyy') + * //=> '02/11/2014' + * + * @example + * // Represent 2 July 2014 in Esperanto: + * import { eoLocale } from 'date-fns/locale/eo' + * var result = format(new Date(2014, 6, 2), "do 'de' MMMM yyyy", { + * locale: eoLocale + * }) + * //=> '2-a de julio 2014' + * + * @example + * // Escape string by single quote characters: + * var result = format(new Date(2014, 6, 2, 15), "h 'o''clock'") + * //=> "3 o'clock" + */ + +function format(dirtyDate, dirtyFormatStr, dirtyOptions) { + requiredArgs(2, arguments); + var formatStr = String(dirtyFormatStr); + var options = dirtyOptions || {}; + var locale = options.locale || defaultLocale; + var localeFirstWeekContainsDate = locale.options && locale.options.firstWeekContainsDate; + var defaultFirstWeekContainsDate = localeFirstWeekContainsDate == null ? 1 : toInteger(localeFirstWeekContainsDate); + var firstWeekContainsDate = options.firstWeekContainsDate == null ? defaultFirstWeekContainsDate : toInteger(options.firstWeekContainsDate); // Test if weekStartsOn is between 1 and 7 _and_ is not NaN + + if (!(firstWeekContainsDate >= 1 && firstWeekContainsDate <= 7)) { + throw new RangeError('firstWeekContainsDate must be between 1 and 7 inclusively'); + } + + var localeWeekStartsOn = locale.options && locale.options.weekStartsOn; + var defaultWeekStartsOn = localeWeekStartsOn == null ? 0 : toInteger(localeWeekStartsOn); + var weekStartsOn = options.weekStartsOn == null ? defaultWeekStartsOn : toInteger(options.weekStartsOn); // Test if weekStartsOn is between 0 and 6 _and_ is not NaN + + if (!(weekStartsOn >= 0 && weekStartsOn <= 6)) { + throw new RangeError('weekStartsOn must be between 0 and 6 inclusively'); + } + + if (!locale.localize) { + throw new RangeError('locale must contain localize property'); + } + + if (!locale.formatLong) { + throw new RangeError('locale must contain formatLong property'); + } + + var originalDate = toDate(dirtyDate); + + if (!isValid(originalDate)) { + throw new RangeError('Invalid time value'); + } // Convert the date in system timezone to the same date in UTC+00:00 timezone. + // This ensures that when UTC functions will be implemented, locales will be compatible with them. + // See an issue about UTC functions: https://github.com/date-fns/date-fns/issues/376 + + + var timezoneOffset = getTimezoneOffsetInMilliseconds(originalDate); + var utcDate = subMilliseconds(originalDate, timezoneOffset); + var formatterOptions = { + firstWeekContainsDate: firstWeekContainsDate, + weekStartsOn: weekStartsOn, + locale: locale, + _originalDate: originalDate + }; + var result = formatStr.match(longFormattingTokensRegExp$1).map(function (substring) { + var firstCharacter = substring[0]; + + if (firstCharacter === 'p' || firstCharacter === 'P') { + var longFormatter = longFormatters$1[firstCharacter]; + return longFormatter(substring, locale.formatLong, formatterOptions); + } + + return substring; + }).join('').match(formattingTokensRegExp$1).map(function (substring) { + // Replace two single quote characters with one single quote character + if (substring === "''") { + return "'"; + } + + var firstCharacter = substring[0]; + + if (firstCharacter === "'") { + return cleanEscapedString$1(substring); + } + + var formatter = formatters$1[firstCharacter]; + + if (formatter) { + if (!options.useAdditionalWeekYearTokens && isProtectedWeekYearToken(substring)) { + throwProtectedError(substring, dirtyFormatStr, dirtyDate); + } + + if (!options.useAdditionalDayOfYearTokens && isProtectedDayOfYearToken(substring)) { + throwProtectedError(substring, dirtyFormatStr, dirtyDate); + } + + return formatter(utcDate, substring, locale.localize, formatterOptions); + } + + if (firstCharacter.match(unescapedLatinCharacterRegExp$1)) { + throw new RangeError('Format string contains an unescaped latin alphabet character `' + firstCharacter + '`'); + } + + return substring; + }).join(''); + return result; +} + +function cleanEscapedString$1(input) { + return input.match(escapedStringRegExp$1)[1].replace(doubleQuoteRegExp$1, "'"); +} + +function assign(target, dirtyObject) { + if (target == null) { + throw new TypeError('assign requires that input parameter not be null or undefined'); + } + + dirtyObject = dirtyObject || {}; + + for (var property in dirtyObject) { + if (dirtyObject.hasOwnProperty(property)) { + target[property] = dirtyObject[property]; + } + } + + return target; +} + +// See issue: https://github.com/date-fns/date-fns/issues/376 + +function setUTCDay(dirtyDate, dirtyDay, dirtyOptions) { + requiredArgs(2, arguments); + var options = dirtyOptions || {}; + var locale = options.locale; + var localeWeekStartsOn = locale && locale.options && locale.options.weekStartsOn; + var defaultWeekStartsOn = localeWeekStartsOn == null ? 0 : toInteger(localeWeekStartsOn); + var weekStartsOn = options.weekStartsOn == null ? defaultWeekStartsOn : toInteger(options.weekStartsOn); // Test if weekStartsOn is between 0 and 6 _and_ is not NaN + + if (!(weekStartsOn >= 0 && weekStartsOn <= 6)) { + throw new RangeError('weekStartsOn must be between 0 and 6 inclusively'); + } + + var date = toDate(dirtyDate); + var day = toInteger(dirtyDay); + var currentDay = date.getUTCDay(); + var remainder = day % 7; + var dayIndex = (remainder + 7) % 7; + var diff = (dayIndex < weekStartsOn ? 7 : 0) + day - currentDay; + date.setUTCDate(date.getUTCDate() + diff); + return date; +} + +// See issue: https://github.com/date-fns/date-fns/issues/376 + +function setUTCISODay(dirtyDate, dirtyDay) { + requiredArgs(2, arguments); + var day = toInteger(dirtyDay); + + if (day % 7 === 0) { + day = day - 7; + } + + var weekStartsOn = 1; + var date = toDate(dirtyDate); + var currentDay = date.getUTCDay(); + var remainder = day % 7; + var dayIndex = (remainder + 7) % 7; + var diff = (dayIndex < weekStartsOn ? 7 : 0) + day - currentDay; + date.setUTCDate(date.getUTCDate() + diff); + return date; +} + +// See issue: https://github.com/date-fns/date-fns/issues/376 + +function setUTCISOWeek(dirtyDate, dirtyISOWeek) { + requiredArgs(2, arguments); + var date = toDate(dirtyDate); + var isoWeek = toInteger(dirtyISOWeek); + var diff = getUTCISOWeek(date) - isoWeek; + date.setUTCDate(date.getUTCDate() - diff * 7); + return date; +} + +// See issue: https://github.com/date-fns/date-fns/issues/376 + +function setUTCWeek(dirtyDate, dirtyWeek, options) { + requiredArgs(2, arguments); + var date = toDate(dirtyDate); + var week = toInteger(dirtyWeek); + var diff = getUTCWeek(date, options) - week; + date.setUTCDate(date.getUTCDate() - diff * 7); + return date; +} + +var MILLISECONDS_IN_HOUR$1 = 3600000; +var MILLISECONDS_IN_MINUTE$1 = 60000; +var MILLISECONDS_IN_SECOND = 1000; +var numericPatterns = { + month: /^(1[0-2]|0?\d)/, + // 0 to 12 + date: /^(3[0-1]|[0-2]?\d)/, + // 0 to 31 + dayOfYear: /^(36[0-6]|3[0-5]\d|[0-2]?\d?\d)/, + // 0 to 366 + week: /^(5[0-3]|[0-4]?\d)/, + // 0 to 53 + hour23h: /^(2[0-3]|[0-1]?\d)/, + // 0 to 23 + hour24h: /^(2[0-4]|[0-1]?\d)/, + // 0 to 24 + hour11h: /^(1[0-1]|0?\d)/, + // 0 to 11 + hour12h: /^(1[0-2]|0?\d)/, + // 0 to 12 + minute: /^[0-5]?\d/, + // 0 to 59 + second: /^[0-5]?\d/, + // 0 to 59 + singleDigit: /^\d/, + // 0 to 9 + twoDigits: /^\d{1,2}/, + // 0 to 99 + threeDigits: /^\d{1,3}/, + // 0 to 999 + fourDigits: /^\d{1,4}/, + // 0 to 9999 + anyDigitsSigned: /^-?\d+/, + singleDigitSigned: /^-?\d/, + // 0 to 9, -0 to -9 + twoDigitsSigned: /^-?\d{1,2}/, + // 0 to 99, -0 to -99 + threeDigitsSigned: /^-?\d{1,3}/, + // 0 to 999, -0 to -999 + fourDigitsSigned: /^-?\d{1,4}/ // 0 to 9999, -0 to -9999 + +}; +var timezonePatterns = { + basicOptionalMinutes: /^([+-])(\d{2})(\d{2})?|Z/, + basic: /^([+-])(\d{2})(\d{2})|Z/, + basicOptionalSeconds: /^([+-])(\d{2})(\d{2})((\d{2}))?|Z/, + extended: /^([+-])(\d{2}):(\d{2})|Z/, + extendedOptionalSeconds: /^([+-])(\d{2}):(\d{2})(:(\d{2}))?|Z/ +}; + +function parseNumericPattern(pattern, string, valueCallback) { + var matchResult = string.match(pattern); + + if (!matchResult) { + return null; + } + + var value = parseInt(matchResult[0], 10); + return { + value: valueCallback ? valueCallback(value) : value, + rest: string.slice(matchResult[0].length) + }; +} + +function parseTimezonePattern(pattern, string) { + var matchResult = string.match(pattern); + + if (!matchResult) { + return null; + } // Input is 'Z' + + + if (matchResult[0] === 'Z') { + return { + value: 0, + rest: string.slice(1) + }; + } + + var sign = matchResult[1] === '+' ? 1 : -1; + var hours = matchResult[2] ? parseInt(matchResult[2], 10) : 0; + var minutes = matchResult[3] ? parseInt(matchResult[3], 10) : 0; + var seconds = matchResult[5] ? parseInt(matchResult[5], 10) : 0; + return { + value: sign * (hours * MILLISECONDS_IN_HOUR$1 + minutes * MILLISECONDS_IN_MINUTE$1 + seconds * MILLISECONDS_IN_SECOND), + rest: string.slice(matchResult[0].length) + }; +} + +function parseAnyDigitsSigned(string, valueCallback) { + return parseNumericPattern(numericPatterns.anyDigitsSigned, string, valueCallback); +} + +function parseNDigits(n, string, valueCallback) { + switch (n) { + case 1: + return parseNumericPattern(numericPatterns.singleDigit, string, valueCallback); + + case 2: + return parseNumericPattern(numericPatterns.twoDigits, string, valueCallback); + + case 3: + return parseNumericPattern(numericPatterns.threeDigits, string, valueCallback); + + case 4: + return parseNumericPattern(numericPatterns.fourDigits, string, valueCallback); + + default: + return parseNumericPattern(new RegExp('^\\d{1,' + n + '}'), string, valueCallback); + } +} + +function parseNDigitsSigned(n, string, valueCallback) { + switch (n) { + case 1: + return parseNumericPattern(numericPatterns.singleDigitSigned, string, valueCallback); + + case 2: + return parseNumericPattern(numericPatterns.twoDigitsSigned, string, valueCallback); + + case 3: + return parseNumericPattern(numericPatterns.threeDigitsSigned, string, valueCallback); + + case 4: + return parseNumericPattern(numericPatterns.fourDigitsSigned, string, valueCallback); + + default: + return parseNumericPattern(new RegExp('^-?\\d{1,' + n + '}'), string, valueCallback); + } +} + +function dayPeriodEnumToHours(enumValue) { + switch (enumValue) { + case 'morning': + return 4; + + case 'evening': + return 17; + + case 'pm': + case 'noon': + case 'afternoon': + return 12; + + case 'am': + case 'midnight': + case 'night': + default: + return 0; + } +} + +function normalizeTwoDigitYear(twoDigitYear, currentYear) { + var isCommonEra = currentYear > 0; // Absolute number of the current year: + // 1 -> 1 AC + // 0 -> 1 BC + // -1 -> 2 BC + + var absCurrentYear = isCommonEra ? currentYear : 1 - currentYear; + var result; + + if (absCurrentYear <= 50) { + result = twoDigitYear || 100; + } else { + var rangeEnd = absCurrentYear + 50; + var rangeEndCentury = Math.floor(rangeEnd / 100) * 100; + var isPreviousCentury = twoDigitYear >= rangeEnd % 100; + result = twoDigitYear + rangeEndCentury - (isPreviousCentury ? 100 : 0); + } + + return isCommonEra ? result : 1 - result; +} + +var DAYS_IN_MONTH = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; +var DAYS_IN_MONTH_LEAP_YEAR = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; // User for validation + +function isLeapYearIndex$1(year) { + return year % 400 === 0 || year % 4 === 0 && year % 100 !== 0; +} +/* + * | | Unit | | Unit | + * |-----|--------------------------------|-----|--------------------------------| + * | a | AM, PM | A* | Milliseconds in day | + * | b | AM, PM, noon, midnight | B | Flexible day period | + * | c | Stand-alone local day of week | C* | Localized hour w/ day period | + * | d | Day of month | D | Day of year | + * | e | Local day of week | E | Day of week | + * | f | | F* | Day of week in month | + * | g* | Modified Julian day | G | Era | + * | h | Hour [1-12] | H | Hour [0-23] | + * | i! | ISO day of week | I! | ISO week of year | + * | j* | Localized hour w/ day period | J* | Localized hour w/o day period | + * | k | Hour [1-24] | K | Hour [0-11] | + * | l* | (deprecated) | L | Stand-alone month | + * | m | Minute | M | Month | + * | n | | N | | + * | o! | Ordinal number modifier | O* | Timezone (GMT) | + * | p | | P | | + * | q | Stand-alone quarter | Q | Quarter | + * | r* | Related Gregorian year | R! | ISO week-numbering year | + * | s | Second | S | Fraction of second | + * | t! | Seconds timestamp | T! | Milliseconds timestamp | + * | u | Extended year | U* | Cyclic year | + * | v* | Timezone (generic non-locat.) | V* | Timezone (location) | + * | w | Local week of year | W* | Week of month | + * | x | Timezone (ISO-8601 w/o Z) | X | Timezone (ISO-8601) | + * | y | Year (abs) | Y | Local week-numbering year | + * | z* | Timezone (specific non-locat.) | Z* | Timezone (aliases) | + * + * Letters marked by * are not implemented but reserved by Unicode standard. + * + * Letters marked by ! are non-standard, but implemented by date-fns: + * - `o` modifies the previous token to turn it into an ordinal (see `parse` docs) + * - `i` is ISO day of week. For `i` and `ii` is returns numeric ISO week days, + * i.e. 7 for Sunday, 1 for Monday, etc. + * - `I` is ISO week of year, as opposed to `w` which is local week of year. + * - `R` is ISO week-numbering year, as opposed to `Y` which is local week-numbering year. + * `R` is supposed to be used in conjunction with `I` and `i` + * for universal ISO week-numbering date, whereas + * `Y` is supposed to be used in conjunction with `w` and `e` + * for week-numbering date specific to the locale. + */ + + +var parsers = { + // Era + G: { + priority: 140, + parse: function (string, token, match, _options) { + switch (token) { + // AD, BC + case 'G': + case 'GG': + case 'GGG': + return match.era(string, { + width: 'abbreviated' + }) || match.era(string, { + width: 'narrow' + }); + // A, B + + case 'GGGGG': + return match.era(string, { + width: 'narrow' + }); + // Anno Domini, Before Christ + + case 'GGGG': + default: + return match.era(string, { + width: 'wide' + }) || match.era(string, { + width: 'abbreviated' + }) || match.era(string, { + width: 'narrow' + }); + } + }, + set: function (date, flags, value, _options) { + flags.era = value; + date.setUTCFullYear(value, 0, 1); + date.setUTCHours(0, 0, 0, 0); + return date; + }, + incompatibleTokens: ['R', 'u', 't', 'T'] + }, + // Year + y: { + // From http://www.unicode.org/reports/tr35/tr35-31/tr35-dates.html#Date_Format_Patterns + // | Year | y | yy | yyy | yyyy | yyyyy | + // |----------|-------|----|-------|-------|-------| + // | AD 1 | 1 | 01 | 001 | 0001 | 00001 | + // | AD 12 | 12 | 12 | 012 | 0012 | 00012 | + // | AD 123 | 123 | 23 | 123 | 0123 | 00123 | + // | AD 1234 | 1234 | 34 | 1234 | 1234 | 01234 | + // | AD 12345 | 12345 | 45 | 12345 | 12345 | 12345 | + priority: 130, + parse: function (string, token, match, _options) { + var valueCallback = function (year) { + return { + year: year, + isTwoDigitYear: token === 'yy' + }; + }; + + switch (token) { + case 'y': + return parseNDigits(4, string, valueCallback); + + case 'yo': + return match.ordinalNumber(string, { + unit: 'year', + valueCallback: valueCallback + }); + + default: + return parseNDigits(token.length, string, valueCallback); + } + }, + validate: function (_date, value, _options) { + return value.isTwoDigitYear || value.year > 0; + }, + set: function (date, flags, value, _options) { + var currentYear = date.getUTCFullYear(); + + if (value.isTwoDigitYear) { + var normalizedTwoDigitYear = normalizeTwoDigitYear(value.year, currentYear); + date.setUTCFullYear(normalizedTwoDigitYear, 0, 1); + date.setUTCHours(0, 0, 0, 0); + return date; + } + + var year = !('era' in flags) || flags.era === 1 ? value.year : 1 - value.year; + date.setUTCFullYear(year, 0, 1); + date.setUTCHours(0, 0, 0, 0); + return date; + }, + incompatibleTokens: ['Y', 'R', 'u', 'w', 'I', 'i', 'e', 'c', 't', 'T'] + }, + // Local week-numbering year + Y: { + priority: 130, + parse: function (string, token, match, _options) { + var valueCallback = function (year) { + return { + year: year, + isTwoDigitYear: token === 'YY' + }; + }; + + switch (token) { + case 'Y': + return parseNDigits(4, string, valueCallback); + + case 'Yo': + return match.ordinalNumber(string, { + unit: 'year', + valueCallback: valueCallback + }); + + default: + return parseNDigits(token.length, string, valueCallback); + } + }, + validate: function (_date, value, _options) { + return value.isTwoDigitYear || value.year > 0; + }, + set: function (date, flags, value, options) { + var currentYear = getUTCWeekYear(date, options); + + if (value.isTwoDigitYear) { + var normalizedTwoDigitYear = normalizeTwoDigitYear(value.year, currentYear); + date.setUTCFullYear(normalizedTwoDigitYear, 0, options.firstWeekContainsDate); + date.setUTCHours(0, 0, 0, 0); + return startOfUTCWeek(date, options); + } + + var year = !('era' in flags) || flags.era === 1 ? value.year : 1 - value.year; + date.setUTCFullYear(year, 0, options.firstWeekContainsDate); + date.setUTCHours(0, 0, 0, 0); + return startOfUTCWeek(date, options); + }, + incompatibleTokens: ['y', 'R', 'u', 'Q', 'q', 'M', 'L', 'I', 'd', 'D', 'i', 't', 'T'] + }, + // ISO week-numbering year + R: { + priority: 130, + parse: function (string, token, _match, _options) { + if (token === 'R') { + return parseNDigitsSigned(4, string); + } + + return parseNDigitsSigned(token.length, string); + }, + set: function (_date, _flags, value, _options) { + var firstWeekOfYear = new Date(0); + firstWeekOfYear.setUTCFullYear(value, 0, 4); + firstWeekOfYear.setUTCHours(0, 0, 0, 0); + return startOfUTCISOWeek(firstWeekOfYear); + }, + incompatibleTokens: ['G', 'y', 'Y', 'u', 'Q', 'q', 'M', 'L', 'w', 'd', 'D', 'e', 'c', 't', 'T'] + }, + // Extended year + u: { + priority: 130, + parse: function (string, token, _match, _options) { + if (token === 'u') { + return parseNDigitsSigned(4, string); + } + + return parseNDigitsSigned(token.length, string); + }, + set: function (date, _flags, value, _options) { + date.setUTCFullYear(value, 0, 1); + date.setUTCHours(0, 0, 0, 0); + return date; + }, + incompatibleTokens: ['G', 'y', 'Y', 'R', 'w', 'I', 'i', 'e', 'c', 't', 'T'] + }, + // Quarter + Q: { + priority: 120, + parse: function (string, token, match, _options) { + switch (token) { + // 1, 2, 3, 4 + case 'Q': + case 'QQ': + // 01, 02, 03, 04 + return parseNDigits(token.length, string); + // 1st, 2nd, 3rd, 4th + + case 'Qo': + return match.ordinalNumber(string, { + unit: 'quarter' + }); + // Q1, Q2, Q3, Q4 + + case 'QQQ': + return match.quarter(string, { + width: 'abbreviated', + context: 'formatting' + }) || match.quarter(string, { + width: 'narrow', + context: 'formatting' + }); + // 1, 2, 3, 4 (narrow quarter; could be not numerical) + + case 'QQQQQ': + return match.quarter(string, { + width: 'narrow', + context: 'formatting' + }); + // 1st quarter, 2nd quarter, ... + + case 'QQQQ': + default: + return match.quarter(string, { + width: 'wide', + context: 'formatting' + }) || match.quarter(string, { + width: 'abbreviated', + context: 'formatting' + }) || match.quarter(string, { + width: 'narrow', + context: 'formatting' + }); + } + }, + validate: function (_date, value, _options) { + return value >= 1 && value <= 4; + }, + set: function (date, _flags, value, _options) { + date.setUTCMonth((value - 1) * 3, 1); + date.setUTCHours(0, 0, 0, 0); + return date; + }, + incompatibleTokens: ['Y', 'R', 'q', 'M', 'L', 'w', 'I', 'd', 'D', 'i', 'e', 'c', 't', 'T'] + }, + // Stand-alone quarter + q: { + priority: 120, + parse: function (string, token, match, _options) { + switch (token) { + // 1, 2, 3, 4 + case 'q': + case 'qq': + // 01, 02, 03, 04 + return parseNDigits(token.length, string); + // 1st, 2nd, 3rd, 4th + + case 'qo': + return match.ordinalNumber(string, { + unit: 'quarter' + }); + // Q1, Q2, Q3, Q4 + + case 'qqq': + return match.quarter(string, { + width: 'abbreviated', + context: 'standalone' + }) || match.quarter(string, { + width: 'narrow', + context: 'standalone' + }); + // 1, 2, 3, 4 (narrow quarter; could be not numerical) + + case 'qqqqq': + return match.quarter(string, { + width: 'narrow', + context: 'standalone' + }); + // 1st quarter, 2nd quarter, ... + + case 'qqqq': + default: + return match.quarter(string, { + width: 'wide', + context: 'standalone' + }) || match.quarter(string, { + width: 'abbreviated', + context: 'standalone' + }) || match.quarter(string, { + width: 'narrow', + context: 'standalone' + }); + } + }, + validate: function (_date, value, _options) { + return value >= 1 && value <= 4; + }, + set: function (date, _flags, value, _options) { + date.setUTCMonth((value - 1) * 3, 1); + date.setUTCHours(0, 0, 0, 0); + return date; + }, + incompatibleTokens: ['Y', 'R', 'Q', 'M', 'L', 'w', 'I', 'd', 'D', 'i', 'e', 'c', 't', 'T'] + }, + // Month + M: { + priority: 110, + parse: function (string, token, match, _options) { + var valueCallback = function (value) { + return value - 1; + }; + + switch (token) { + // 1, 2, ..., 12 + case 'M': + return parseNumericPattern(numericPatterns.month, string, valueCallback); + // 01, 02, ..., 12 + + case 'MM': + return parseNDigits(2, string, valueCallback); + // 1st, 2nd, ..., 12th + + case 'Mo': + return match.ordinalNumber(string, { + unit: 'month', + valueCallback: valueCallback + }); + // Jan, Feb, ..., Dec + + case 'MMM': + return match.month(string, { + width: 'abbreviated', + context: 'formatting' + }) || match.month(string, { + width: 'narrow', + context: 'formatting' + }); + // J, F, ..., D + + case 'MMMMM': + return match.month(string, { + width: 'narrow', + context: 'formatting' + }); + // January, February, ..., December + + case 'MMMM': + default: + return match.month(string, { + width: 'wide', + context: 'formatting' + }) || match.month(string, { + width: 'abbreviated', + context: 'formatting' + }) || match.month(string, { + width: 'narrow', + context: 'formatting' + }); + } + }, + validate: function (_date, value, _options) { + return value >= 0 && value <= 11; + }, + set: function (date, _flags, value, _options) { + date.setUTCMonth(value, 1); + date.setUTCHours(0, 0, 0, 0); + return date; + }, + incompatibleTokens: ['Y', 'R', 'q', 'Q', 'L', 'w', 'I', 'D', 'i', 'e', 'c', 't', 'T'] + }, + // Stand-alone month + L: { + priority: 110, + parse: function (string, token, match, _options) { + var valueCallback = function (value) { + return value - 1; + }; + + switch (token) { + // 1, 2, ..., 12 + case 'L': + return parseNumericPattern(numericPatterns.month, string, valueCallback); + // 01, 02, ..., 12 + + case 'LL': + return parseNDigits(2, string, valueCallback); + // 1st, 2nd, ..., 12th + + case 'Lo': + return match.ordinalNumber(string, { + unit: 'month', + valueCallback: valueCallback + }); + // Jan, Feb, ..., Dec + + case 'LLL': + return match.month(string, { + width: 'abbreviated', + context: 'standalone' + }) || match.month(string, { + width: 'narrow', + context: 'standalone' + }); + // J, F, ..., D + + case 'LLLLL': + return match.month(string, { + width: 'narrow', + context: 'standalone' + }); + // January, February, ..., December + + case 'LLLL': + default: + return match.month(string, { + width: 'wide', + context: 'standalone' + }) || match.month(string, { + width: 'abbreviated', + context: 'standalone' + }) || match.month(string, { + width: 'narrow', + context: 'standalone' + }); + } + }, + validate: function (_date, value, _options) { + return value >= 0 && value <= 11; + }, + set: function (date, _flags, value, _options) { + date.setUTCMonth(value, 1); + date.setUTCHours(0, 0, 0, 0); + return date; + }, + incompatibleTokens: ['Y', 'R', 'q', 'Q', 'M', 'w', 'I', 'D', 'i', 'e', 'c', 't', 'T'] + }, + // Local week of year + w: { + priority: 100, + parse: function (string, token, match, _options) { + switch (token) { + case 'w': + return parseNumericPattern(numericPatterns.week, string); + + case 'wo': + return match.ordinalNumber(string, { + unit: 'week' + }); + + default: + return parseNDigits(token.length, string); + } + }, + validate: function (_date, value, _options) { + return value >= 1 && value <= 53; + }, + set: function (date, _flags, value, options) { + return startOfUTCWeek(setUTCWeek(date, value, options), options); + }, + incompatibleTokens: ['y', 'R', 'u', 'q', 'Q', 'M', 'L', 'I', 'd', 'D', 'i', 't', 'T'] + }, + // ISO week of year + I: { + priority: 100, + parse: function (string, token, match, _options) { + switch (token) { + case 'I': + return parseNumericPattern(numericPatterns.week, string); + + case 'Io': + return match.ordinalNumber(string, { + unit: 'week' + }); + + default: + return parseNDigits(token.length, string); + } + }, + validate: function (_date, value, _options) { + return value >= 1 && value <= 53; + }, + set: function (date, _flags, value, options) { + return startOfUTCISOWeek(setUTCISOWeek(date, value, options), options); + }, + incompatibleTokens: ['y', 'Y', 'u', 'q', 'Q', 'M', 'L', 'w', 'd', 'D', 'e', 'c', 't', 'T'] + }, + // Day of the month + d: { + priority: 90, + subPriority: 1, + parse: function (string, token, match, _options) { + switch (token) { + case 'd': + return parseNumericPattern(numericPatterns.date, string); + + case 'do': + return match.ordinalNumber(string, { + unit: 'date' + }); + + default: + return parseNDigits(token.length, string); + } + }, + validate: function (date, value, _options) { + var year = date.getUTCFullYear(); + var isLeapYear = isLeapYearIndex$1(year); + var month = date.getUTCMonth(); + + if (isLeapYear) { + return value >= 1 && value <= DAYS_IN_MONTH_LEAP_YEAR[month]; + } else { + return value >= 1 && value <= DAYS_IN_MONTH[month]; + } + }, + set: function (date, _flags, value, _options) { + date.setUTCDate(value); + date.setUTCHours(0, 0, 0, 0); + return date; + }, + incompatibleTokens: ['Y', 'R', 'q', 'Q', 'w', 'I', 'D', 'i', 'e', 'c', 't', 'T'] + }, + // Day of year + D: { + priority: 90, + subPriority: 1, + parse: function (string, token, match, _options) { + switch (token) { + case 'D': + case 'DD': + return parseNumericPattern(numericPatterns.dayOfYear, string); + + case 'Do': + return match.ordinalNumber(string, { + unit: 'date' + }); + + default: + return parseNDigits(token.length, string); + } + }, + validate: function (date, value, _options) { + var year = date.getUTCFullYear(); + var isLeapYear = isLeapYearIndex$1(year); + + if (isLeapYear) { + return value >= 1 && value <= 366; + } else { + return value >= 1 && value <= 365; + } + }, + set: function (date, _flags, value, _options) { + date.setUTCMonth(0, value); + date.setUTCHours(0, 0, 0, 0); + return date; + }, + incompatibleTokens: ['Y', 'R', 'q', 'Q', 'M', 'L', 'w', 'I', 'd', 'E', 'i', 'e', 'c', 't', 'T'] + }, + // Day of week + E: { + priority: 90, + parse: function (string, token, match, _options) { + switch (token) { + // Tue + case 'E': + case 'EE': + case 'EEE': + return match.day(string, { + width: 'abbreviated', + context: 'formatting' + }) || match.day(string, { + width: 'short', + context: 'formatting' + }) || match.day(string, { + width: 'narrow', + context: 'formatting' + }); + // T + + case 'EEEEE': + return match.day(string, { + width: 'narrow', + context: 'formatting' + }); + // Tu + + case 'EEEEEE': + return match.day(string, { + width: 'short', + context: 'formatting' + }) || match.day(string, { + width: 'narrow', + context: 'formatting' + }); + // Tuesday + + case 'EEEE': + default: + return match.day(string, { + width: 'wide', + context: 'formatting' + }) || match.day(string, { + width: 'abbreviated', + context: 'formatting' + }) || match.day(string, { + width: 'short', + context: 'formatting' + }) || match.day(string, { + width: 'narrow', + context: 'formatting' + }); + } + }, + validate: function (_date, value, _options) { + return value >= 0 && value <= 6; + }, + set: function (date, _flags, value, options) { + date = setUTCDay(date, value, options); + date.setUTCHours(0, 0, 0, 0); + return date; + }, + incompatibleTokens: ['D', 'i', 'e', 'c', 't', 'T'] + }, + // Local day of week + e: { + priority: 90, + parse: function (string, token, match, options) { + var valueCallback = function (value) { + var wholeWeekDays = Math.floor((value - 1) / 7) * 7; + return (value + options.weekStartsOn + 6) % 7 + wholeWeekDays; + }; + + switch (token) { + // 3 + case 'e': + case 'ee': + // 03 + return parseNDigits(token.length, string, valueCallback); + // 3rd + + case 'eo': + return match.ordinalNumber(string, { + unit: 'day', + valueCallback: valueCallback + }); + // Tue + + case 'eee': + return match.day(string, { + width: 'abbreviated', + context: 'formatting' + }) || match.day(string, { + width: 'short', + context: 'formatting' + }) || match.day(string, { + width: 'narrow', + context: 'formatting' + }); + // T + + case 'eeeee': + return match.day(string, { + width: 'narrow', + context: 'formatting' + }); + // Tu + + case 'eeeeee': + return match.day(string, { + width: 'short', + context: 'formatting' + }) || match.day(string, { + width: 'narrow', + context: 'formatting' + }); + // Tuesday + + case 'eeee': + default: + return match.day(string, { + width: 'wide', + context: 'formatting' + }) || match.day(string, { + width: 'abbreviated', + context: 'formatting' + }) || match.day(string, { + width: 'short', + context: 'formatting' + }) || match.day(string, { + width: 'narrow', + context: 'formatting' + }); + } + }, + validate: function (_date, value, _options) { + return value >= 0 && value <= 6; + }, + set: function (date, _flags, value, options) { + date = setUTCDay(date, value, options); + date.setUTCHours(0, 0, 0, 0); + return date; + }, + incompatibleTokens: ['y', 'R', 'u', 'q', 'Q', 'M', 'L', 'I', 'd', 'D', 'E', 'i', 'c', 't', 'T'] + }, + // Stand-alone local day of week + c: { + priority: 90, + parse: function (string, token, match, options) { + var valueCallback = function (value) { + var wholeWeekDays = Math.floor((value - 1) / 7) * 7; + return (value + options.weekStartsOn + 6) % 7 + wholeWeekDays; + }; + + switch (token) { + // 3 + case 'c': + case 'cc': + // 03 + return parseNDigits(token.length, string, valueCallback); + // 3rd + + case 'co': + return match.ordinalNumber(string, { + unit: 'day', + valueCallback: valueCallback + }); + // Tue + + case 'ccc': + return match.day(string, { + width: 'abbreviated', + context: 'standalone' + }) || match.day(string, { + width: 'short', + context: 'standalone' + }) || match.day(string, { + width: 'narrow', + context: 'standalone' + }); + // T + + case 'ccccc': + return match.day(string, { + width: 'narrow', + context: 'standalone' + }); + // Tu + + case 'cccccc': + return match.day(string, { + width: 'short', + context: 'standalone' + }) || match.day(string, { + width: 'narrow', + context: 'standalone' + }); + // Tuesday + + case 'cccc': + default: + return match.day(string, { + width: 'wide', + context: 'standalone' + }) || match.day(string, { + width: 'abbreviated', + context: 'standalone' + }) || match.day(string, { + width: 'short', + context: 'standalone' + }) || match.day(string, { + width: 'narrow', + context: 'standalone' + }); + } + }, + validate: function (_date, value, _options) { + return value >= 0 && value <= 6; + }, + set: function (date, _flags, value, options) { + date = setUTCDay(date, value, options); + date.setUTCHours(0, 0, 0, 0); + return date; + }, + incompatibleTokens: ['y', 'R', 'u', 'q', 'Q', 'M', 'L', 'I', 'd', 'D', 'E', 'i', 'e', 't', 'T'] + }, + // ISO day of week + i: { + priority: 90, + parse: function (string, token, match, _options) { + var valueCallback = function (value) { + if (value === 0) { + return 7; + } + + return value; + }; + + switch (token) { + // 2 + case 'i': + case 'ii': + // 02 + return parseNDigits(token.length, string); + // 2nd + + case 'io': + return match.ordinalNumber(string, { + unit: 'day' + }); + // Tue + + case 'iii': + return match.day(string, { + width: 'abbreviated', + context: 'formatting', + valueCallback: valueCallback + }) || match.day(string, { + width: 'short', + context: 'formatting', + valueCallback: valueCallback + }) || match.day(string, { + width: 'narrow', + context: 'formatting', + valueCallback: valueCallback + }); + // T + + case 'iiiii': + return match.day(string, { + width: 'narrow', + context: 'formatting', + valueCallback: valueCallback + }); + // Tu + + case 'iiiiii': + return match.day(string, { + width: 'short', + context: 'formatting', + valueCallback: valueCallback + }) || match.day(string, { + width: 'narrow', + context: 'formatting', + valueCallback: valueCallback + }); + // Tuesday + + case 'iiii': + default: + return match.day(string, { + width: 'wide', + context: 'formatting', + valueCallback: valueCallback + }) || match.day(string, { + width: 'abbreviated', + context: 'formatting', + valueCallback: valueCallback + }) || match.day(string, { + width: 'short', + context: 'formatting', + valueCallback: valueCallback + }) || match.day(string, { + width: 'narrow', + context: 'formatting', + valueCallback: valueCallback + }); + } + }, + validate: function (_date, value, _options) { + return value >= 1 && value <= 7; + }, + set: function (date, _flags, value, options) { + date = setUTCISODay(date, value, options); + date.setUTCHours(0, 0, 0, 0); + return date; + }, + incompatibleTokens: ['y', 'Y', 'u', 'q', 'Q', 'M', 'L', 'w', 'd', 'D', 'E', 'e', 'c', 't', 'T'] + }, + // AM or PM + a: { + priority: 80, + parse: function (string, token, match, _options) { + switch (token) { + case 'a': + case 'aa': + case 'aaa': + return match.dayPeriod(string, { + width: 'abbreviated', + context: 'formatting' + }) || match.dayPeriod(string, { + width: 'narrow', + context: 'formatting' + }); + + case 'aaaaa': + return match.dayPeriod(string, { + width: 'narrow', + context: 'formatting' + }); + + case 'aaaa': + default: + return match.dayPeriod(string, { + width: 'wide', + context: 'formatting' + }) || match.dayPeriod(string, { + width: 'abbreviated', + context: 'formatting' + }) || match.dayPeriod(string, { + width: 'narrow', + context: 'formatting' + }); + } + }, + set: function (date, _flags, value, _options) { + date.setUTCHours(dayPeriodEnumToHours(value), 0, 0, 0); + return date; + }, + incompatibleTokens: ['b', 'B', 'H', 'K', 'k', 't', 'T'] + }, + // AM, PM, midnight + b: { + priority: 80, + parse: function (string, token, match, _options) { + switch (token) { + case 'b': + case 'bb': + case 'bbb': + return match.dayPeriod(string, { + width: 'abbreviated', + context: 'formatting' + }) || match.dayPeriod(string, { + width: 'narrow', + context: 'formatting' + }); + + case 'bbbbb': + return match.dayPeriod(string, { + width: 'narrow', + context: 'formatting' + }); + + case 'bbbb': + default: + return match.dayPeriod(string, { + width: 'wide', + context: 'formatting' + }) || match.dayPeriod(string, { + width: 'abbreviated', + context: 'formatting' + }) || match.dayPeriod(string, { + width: 'narrow', + context: 'formatting' + }); + } + }, + set: function (date, _flags, value, _options) { + date.setUTCHours(dayPeriodEnumToHours(value), 0, 0, 0); + return date; + }, + incompatibleTokens: ['a', 'B', 'H', 'K', 'k', 't', 'T'] + }, + // in the morning, in the afternoon, in the evening, at night + B: { + priority: 80, + parse: function (string, token, match, _options) { + switch (token) { + case 'B': + case 'BB': + case 'BBB': + return match.dayPeriod(string, { + width: 'abbreviated', + context: 'formatting' + }) || match.dayPeriod(string, { + width: 'narrow', + context: 'formatting' + }); + + case 'BBBBB': + return match.dayPeriod(string, { + width: 'narrow', + context: 'formatting' + }); + + case 'BBBB': + default: + return match.dayPeriod(string, { + width: 'wide', + context: 'formatting' + }) || match.dayPeriod(string, { + width: 'abbreviated', + context: 'formatting' + }) || match.dayPeriod(string, { + width: 'narrow', + context: 'formatting' + }); + } + }, + set: function (date, _flags, value, _options) { + date.setUTCHours(dayPeriodEnumToHours(value), 0, 0, 0); + return date; + }, + incompatibleTokens: ['a', 'b', 't', 'T'] + }, + // Hour [1-12] + h: { + priority: 70, + parse: function (string, token, match, _options) { + switch (token) { + case 'h': + return parseNumericPattern(numericPatterns.hour12h, string); + + case 'ho': + return match.ordinalNumber(string, { + unit: 'hour' + }); + + default: + return parseNDigits(token.length, string); + } + }, + validate: function (_date, value, _options) { + return value >= 1 && value <= 12; + }, + set: function (date, _flags, value, _options) { + var isPM = date.getUTCHours() >= 12; + + if (isPM && value < 12) { + date.setUTCHours(value + 12, 0, 0, 0); + } else if (!isPM && value === 12) { + date.setUTCHours(0, 0, 0, 0); + } else { + date.setUTCHours(value, 0, 0, 0); + } + + return date; + }, + incompatibleTokens: ['H', 'K', 'k', 't', 'T'] + }, + // Hour [0-23] + H: { + priority: 70, + parse: function (string, token, match, _options) { + switch (token) { + case 'H': + return parseNumericPattern(numericPatterns.hour23h, string); + + case 'Ho': + return match.ordinalNumber(string, { + unit: 'hour' + }); + + default: + return parseNDigits(token.length, string); + } + }, + validate: function (_date, value, _options) { + return value >= 0 && value <= 23; + }, + set: function (date, _flags, value, _options) { + date.setUTCHours(value, 0, 0, 0); + return date; + }, + incompatibleTokens: ['a', 'b', 'h', 'K', 'k', 't', 'T'] + }, + // Hour [0-11] + K: { + priority: 70, + parse: function (string, token, match, _options) { + switch (token) { + case 'K': + return parseNumericPattern(numericPatterns.hour11h, string); + + case 'Ko': + return match.ordinalNumber(string, { + unit: 'hour' + }); + + default: + return parseNDigits(token.length, string); + } + }, + validate: function (_date, value, _options) { + return value >= 0 && value <= 11; + }, + set: function (date, _flags, value, _options) { + var isPM = date.getUTCHours() >= 12; + + if (isPM && value < 12) { + date.setUTCHours(value + 12, 0, 0, 0); + } else { + date.setUTCHours(value, 0, 0, 0); + } + + return date; + }, + incompatibleTokens: ['a', 'b', 'h', 'H', 'k', 't', 'T'] + }, + // Hour [1-24] + k: { + priority: 70, + parse: function (string, token, match, _options) { + switch (token) { + case 'k': + return parseNumericPattern(numericPatterns.hour24h, string); + + case 'ko': + return match.ordinalNumber(string, { + unit: 'hour' + }); + + default: + return parseNDigits(token.length, string); + } + }, + validate: function (_date, value, _options) { + return value >= 1 && value <= 24; + }, + set: function (date, _flags, value, _options) { + var hours = value <= 24 ? value % 24 : value; + date.setUTCHours(hours, 0, 0, 0); + return date; + }, + incompatibleTokens: ['a', 'b', 'h', 'H', 'K', 't', 'T'] + }, + // Minute + m: { + priority: 60, + parse: function (string, token, match, _options) { + switch (token) { + case 'm': + return parseNumericPattern(numericPatterns.minute, string); + + case 'mo': + return match.ordinalNumber(string, { + unit: 'minute' + }); + + default: + return parseNDigits(token.length, string); + } + }, + validate: function (_date, value, _options) { + return value >= 0 && value <= 59; + }, + set: function (date, _flags, value, _options) { + date.setUTCMinutes(value, 0, 0); + return date; + }, + incompatibleTokens: ['t', 'T'] + }, + // Second + s: { + priority: 50, + parse: function (string, token, match, _options) { + switch (token) { + case 's': + return parseNumericPattern(numericPatterns.second, string); + + case 'so': + return match.ordinalNumber(string, { + unit: 'second' + }); + + default: + return parseNDigits(token.length, string); + } + }, + validate: function (_date, value, _options) { + return value >= 0 && value <= 59; + }, + set: function (date, _flags, value, _options) { + date.setUTCSeconds(value, 0); + return date; + }, + incompatibleTokens: ['t', 'T'] + }, + // Fraction of second + S: { + priority: 30, + parse: function (string, token, _match, _options) { + var valueCallback = function (value) { + return Math.floor(value * Math.pow(10, -token.length + 3)); + }; + + return parseNDigits(token.length, string, valueCallback); + }, + set: function (date, _flags, value, _options) { + date.setUTCMilliseconds(value); + return date; + }, + incompatibleTokens: ['t', 'T'] + }, + // Timezone (ISO-8601. +00:00 is `'Z'`) + X: { + priority: 10, + parse: function (string, token, _match, _options) { + switch (token) { + case 'X': + return parseTimezonePattern(timezonePatterns.basicOptionalMinutes, string); + + case 'XX': + return parseTimezonePattern(timezonePatterns.basic, string); + + case 'XXXX': + return parseTimezonePattern(timezonePatterns.basicOptionalSeconds, string); + + case 'XXXXX': + return parseTimezonePattern(timezonePatterns.extendedOptionalSeconds, string); + + case 'XXX': + default: + return parseTimezonePattern(timezonePatterns.extended, string); + } + }, + set: function (date, flags, value, _options) { + if (flags.timestampIsSet) { + return date; + } + + return new Date(date.getTime() - value); + }, + incompatibleTokens: ['t', 'T', 'x'] + }, + // Timezone (ISO-8601) + x: { + priority: 10, + parse: function (string, token, _match, _options) { + switch (token) { + case 'x': + return parseTimezonePattern(timezonePatterns.basicOptionalMinutes, string); + + case 'xx': + return parseTimezonePattern(timezonePatterns.basic, string); + + case 'xxxx': + return parseTimezonePattern(timezonePatterns.basicOptionalSeconds, string); + + case 'xxxxx': + return parseTimezonePattern(timezonePatterns.extendedOptionalSeconds, string); + + case 'xxx': + default: + return parseTimezonePattern(timezonePatterns.extended, string); + } + }, + set: function (date, flags, value, _options) { + if (flags.timestampIsSet) { + return date; + } + + return new Date(date.getTime() - value); + }, + incompatibleTokens: ['t', 'T', 'X'] + }, + // Seconds timestamp + t: { + priority: 40, + parse: function (string, _token, _match, _options) { + return parseAnyDigitsSigned(string); + }, + set: function (_date, _flags, value, _options) { + return [new Date(value * 1000), { + timestampIsSet: true + }]; + }, + incompatibleTokens: '*' + }, + // Milliseconds timestamp + T: { + priority: 20, + parse: function (string, _token, _match, _options) { + return parseAnyDigitsSigned(string); + }, + set: function (_date, _flags, value, _options) { + return [new Date(value), { + timestampIsSet: true + }]; + }, + incompatibleTokens: '*' + } +}; +var parsers$1 = parsers; + +var TIMEZONE_UNIT_PRIORITY = 10; // This RegExp consists of three parts separated by `|`: +// - [yYQqMLwIdDecihHKkms]o matches any available ordinal number token +// (one of the certain letters followed by `o`) +// - (\w)\1* matches any sequences of the same letter +// - '' matches two quote characters in a row +// - '(''|[^'])+('|$) matches anything surrounded by two quote characters ('), +// except a single quote symbol, which ends the sequence. +// Two quote characters do not end the sequence. +// If there is no matching single quote +// then the sequence will continue until the end of the string. +// - . matches any single character unmatched by previous parts of the RegExps + +var formattingTokensRegExp = /[yYQqMLwIdDecihHKkms]o|(\w)\1*|''|'(''|[^'])+('|$)|./g; // This RegExp catches symbols escaped by quotes, and also +// sequences of symbols P, p, and the combinations like `PPPPPPPppppp` + +var longFormattingTokensRegExp = /P+p+|P+|p+|''|'(''|[^'])+('|$)|./g; +var escapedStringRegExp = /^'([^]*?)'?$/; +var doubleQuoteRegExp = /''/g; +var notWhitespaceRegExp = /\S/; +var unescapedLatinCharacterRegExp = /[a-zA-Z]/; +/** + * @name parse + * @category Common Helpers + * @summary Parse the date. + * + * @description + * Return the date parsed from string using the given format string. + * + * > ⚠️ Please note that the `format` tokens differ from Moment.js and other libraries. + * > See: https://git.io/fxCyr + * + * The characters in the format string wrapped between two single quotes characters (') are escaped. + * Two single quotes in a row, whether inside or outside a quoted sequence, represent a 'real' single quote. + * + * Format of the format string is based on Unicode Technical Standard #35: + * https://www.unicode.org/reports/tr35/tr35-dates.html#Date_Field_Symbol_Table + * with a few additions (see note 5 below the table). + * + * Not all tokens are compatible. Combinations that don't make sense or could lead to bugs are prohibited + * and will throw `RangeError`. For example usage of 24-hour format token with AM/PM token will throw an exception: + * + * ```javascript + * parse('23 AM', 'HH a', new Date()) + * //=> RangeError: The format string mustn't contain `HH` and `a` at the same time + * ``` + * + * See the compatibility table: https://docs.google.com/spreadsheets/d/e/2PACX-1vQOPU3xUhplll6dyoMmVUXHKl_8CRDs6_ueLmex3SoqwhuolkuN3O05l4rqx5h1dKX8eb46Ul-CCSrq/pubhtml?gid=0&single=true + * + * Accepted format string patterns: + * | Unit |Prior| Pattern | Result examples | Notes | + * |---------------------------------|-----|---------|-----------------------------------|-------| + * | Era | 140 | G..GGG | AD, BC | | + * | | | GGGG | Anno Domini, Before Christ | 2 | + * | | | GGGGG | A, B | | + * | Calendar year | 130 | y | 44, 1, 1900, 2017, 9999 | 4 | + * | | | yo | 44th, 1st, 1900th, 9999999th | 4,5 | + * | | | yy | 44, 01, 00, 17 | 4 | + * | | | yyy | 044, 001, 123, 999 | 4 | + * | | | yyyy | 0044, 0001, 1900, 2017 | 4 | + * | | | yyyyy | ... | 2,4 | + * | Local week-numbering year | 130 | Y | 44, 1, 1900, 2017, 9000 | 4 | + * | | | Yo | 44th, 1st, 1900th, 9999999th | 4,5 | + * | | | YY | 44, 01, 00, 17 | 4,6 | + * | | | YYY | 044, 001, 123, 999 | 4 | + * | | | YYYY | 0044, 0001, 1900, 2017 | 4,6 | + * | | | YYYYY | ... | 2,4 | + * | ISO week-numbering year | 130 | R | -43, 1, 1900, 2017, 9999, -9999 | 4,5 | + * | | | RR | -43, 01, 00, 17 | 4,5 | + * | | | RRR | -043, 001, 123, 999, -999 | 4,5 | + * | | | RRRR | -0043, 0001, 2017, 9999, -9999 | 4,5 | + * | | | RRRRR | ... | 2,4,5 | + * | Extended year | 130 | u | -43, 1, 1900, 2017, 9999, -999 | 4 | + * | | | uu | -43, 01, 99, -99 | 4 | + * | | | uuu | -043, 001, 123, 999, -999 | 4 | + * | | | uuuu | -0043, 0001, 2017, 9999, -9999 | 4 | + * | | | uuuuu | ... | 2,4 | + * | Quarter (formatting) | 120 | Q | 1, 2, 3, 4 | | + * | | | Qo | 1st, 2nd, 3rd, 4th | 5 | + * | | | QQ | 01, 02, 03, 04 | | + * | | | QQQ | Q1, Q2, Q3, Q4 | | + * | | | QQQQ | 1st quarter, 2nd quarter, ... | 2 | + * | | | QQQQQ | 1, 2, 3, 4 | 4 | + * | Quarter (stand-alone) | 120 | q | 1, 2, 3, 4 | | + * | | | qo | 1st, 2nd, 3rd, 4th | 5 | + * | | | qq | 01, 02, 03, 04 | | + * | | | qqq | Q1, Q2, Q3, Q4 | | + * | | | qqqq | 1st quarter, 2nd quarter, ... | 2 | + * | | | qqqqq | 1, 2, 3, 4 | 3 | + * | Month (formatting) | 110 | M | 1, 2, ..., 12 | | + * | | | Mo | 1st, 2nd, ..., 12th | 5 | + * | | | MM | 01, 02, ..., 12 | | + * | | | MMM | Jan, Feb, ..., Dec | | + * | | | MMMM | January, February, ..., December | 2 | + * | | | MMMMM | J, F, ..., D | | + * | Month (stand-alone) | 110 | L | 1, 2, ..., 12 | | + * | | | Lo | 1st, 2nd, ..., 12th | 5 | + * | | | LL | 01, 02, ..., 12 | | + * | | | LLL | Jan, Feb, ..., Dec | | + * | | | LLLL | January, February, ..., December | 2 | + * | | | LLLLL | J, F, ..., D | | + * | Local week of year | 100 | w | 1, 2, ..., 53 | | + * | | | wo | 1st, 2nd, ..., 53th | 5 | + * | | | ww | 01, 02, ..., 53 | | + * | ISO week of year | 100 | I | 1, 2, ..., 53 | 5 | + * | | | Io | 1st, 2nd, ..., 53th | 5 | + * | | | II | 01, 02, ..., 53 | 5 | + * | Day of month | 90 | d | 1, 2, ..., 31 | | + * | | | do | 1st, 2nd, ..., 31st | 5 | + * | | | dd | 01, 02, ..., 31 | | + * | Day of year | 90 | D | 1, 2, ..., 365, 366 | 7 | + * | | | Do | 1st, 2nd, ..., 365th, 366th | 5 | + * | | | DD | 01, 02, ..., 365, 366 | 7 | + * | | | DDD | 001, 002, ..., 365, 366 | | + * | | | DDDD | ... | 2 | + * | Day of week (formatting) | 90 | E..EEE | Mon, Tue, Wed, ..., Sun | | + * | | | EEEE | Monday, Tuesday, ..., Sunday | 2 | + * | | | EEEEE | M, T, W, T, F, S, S | | + * | | | EEEEEE | Mo, Tu, We, Th, Fr, Su, Sa | | + * | ISO day of week (formatting) | 90 | i | 1, 2, 3, ..., 7 | 5 | + * | | | io | 1st, 2nd, ..., 7th | 5 | + * | | | ii | 01, 02, ..., 07 | 5 | + * | | | iii | Mon, Tue, Wed, ..., Sun | 5 | + * | | | iiii | Monday, Tuesday, ..., Sunday | 2,5 | + * | | | iiiii | M, T, W, T, F, S, S | 5 | + * | | | iiiiii | Mo, Tu, We, Th, Fr, Su, Sa | 5 | + * | Local day of week (formatting) | 90 | e | 2, 3, 4, ..., 1 | | + * | | | eo | 2nd, 3rd, ..., 1st | 5 | + * | | | ee | 02, 03, ..., 01 | | + * | | | eee | Mon, Tue, Wed, ..., Sun | | + * | | | eeee | Monday, Tuesday, ..., Sunday | 2 | + * | | | eeeee | M, T, W, T, F, S, S | | + * | | | eeeeee | Mo, Tu, We, Th, Fr, Su, Sa | | + * | Local day of week (stand-alone) | 90 | c | 2, 3, 4, ..., 1 | | + * | | | co | 2nd, 3rd, ..., 1st | 5 | + * | | | cc | 02, 03, ..., 01 | | + * | | | ccc | Mon, Tue, Wed, ..., Sun | | + * | | | cccc | Monday, Tuesday, ..., Sunday | 2 | + * | | | ccccc | M, T, W, T, F, S, S | | + * | | | cccccc | Mo, Tu, We, Th, Fr, Su, Sa | | + * | AM, PM | 80 | a..aaa | AM, PM | | + * | | | aaaa | a.m., p.m. | 2 | + * | | | aaaaa | a, p | | + * | AM, PM, noon, midnight | 80 | b..bbb | AM, PM, noon, midnight | | + * | | | bbbb | a.m., p.m., noon, midnight | 2 | + * | | | bbbbb | a, p, n, mi | | + * | Flexible day period | 80 | B..BBB | at night, in the morning, ... | | + * | | | BBBB | at night, in the morning, ... | 2 | + * | | | BBBBB | at night, in the morning, ... | | + * | Hour [1-12] | 70 | h | 1, 2, ..., 11, 12 | | + * | | | ho | 1st, 2nd, ..., 11th, 12th | 5 | + * | | | hh | 01, 02, ..., 11, 12 | | + * | Hour [0-23] | 70 | H | 0, 1, 2, ..., 23 | | + * | | | Ho | 0th, 1st, 2nd, ..., 23rd | 5 | + * | | | HH | 00, 01, 02, ..., 23 | | + * | Hour [0-11] | 70 | K | 1, 2, ..., 11, 0 | | + * | | | Ko | 1st, 2nd, ..., 11th, 0th | 5 | + * | | | KK | 01, 02, ..., 11, 00 | | + * | Hour [1-24] | 70 | k | 24, 1, 2, ..., 23 | | + * | | | ko | 24th, 1st, 2nd, ..., 23rd | 5 | + * | | | kk | 24, 01, 02, ..., 23 | | + * | Minute | 60 | m | 0, 1, ..., 59 | | + * | | | mo | 0th, 1st, ..., 59th | 5 | + * | | | mm | 00, 01, ..., 59 | | + * | Second | 50 | s | 0, 1, ..., 59 | | + * | | | so | 0th, 1st, ..., 59th | 5 | + * | | | ss | 00, 01, ..., 59 | | + * | Seconds timestamp | 40 | t | 512969520 | | + * | | | tt | ... | 2 | + * | Fraction of second | 30 | S | 0, 1, ..., 9 | | + * | | | SS | 00, 01, ..., 99 | | + * | | | SSS | 000, 0001, ..., 999 | | + * | | | SSSS | ... | 2 | + * | Milliseconds timestamp | 20 | T | 512969520900 | | + * | | | TT | ... | 2 | + * | Timezone (ISO-8601 w/ Z) | 10 | X | -08, +0530, Z | | + * | | | XX | -0800, +0530, Z | | + * | | | XXX | -08:00, +05:30, Z | | + * | | | XXXX | -0800, +0530, Z, +123456 | 2 | + * | | | XXXXX | -08:00, +05:30, Z, +12:34:56 | | + * | Timezone (ISO-8601 w/o Z) | 10 | x | -08, +0530, +00 | | + * | | | xx | -0800, +0530, +0000 | | + * | | | xxx | -08:00, +05:30, +00:00 | 2 | + * | | | xxxx | -0800, +0530, +0000, +123456 | | + * | | | xxxxx | -08:00, +05:30, +00:00, +12:34:56 | | + * | Long localized date | NA | P | 05/29/1453 | 5,8 | + * | | | PP | May 29, 1453 | | + * | | | PPP | May 29th, 1453 | | + * | | | PPPP | Sunday, May 29th, 1453 | 2,5,8 | + * | Long localized time | NA | p | 12:00 AM | 5,8 | + * | | | pp | 12:00:00 AM | | + * | Combination of date and time | NA | Pp | 05/29/1453, 12:00 AM | | + * | | | PPpp | May 29, 1453, 12:00:00 AM | | + * | | | PPPpp | May 29th, 1453 at ... | | + * | | | PPPPpp | Sunday, May 29th, 1453 at ... | 2,5,8 | + * Notes: + * 1. "Formatting" units (e.g. formatting quarter) in the default en-US locale + * are the same as "stand-alone" units, but are different in some languages. + * "Formatting" units are declined according to the rules of the language + * in the context of a date. "Stand-alone" units are always nominative singular. + * In `format` function, they will produce different result: + * + * `format(new Date(2017, 10, 6), 'do LLLL', {locale: cs}) //=> '6. listopad'` + * + * `format(new Date(2017, 10, 6), 'do MMMM', {locale: cs}) //=> '6. listopadu'` + * + * `parse` will try to match both formatting and stand-alone units interchangably. + * + * 2. Any sequence of the identical letters is a pattern, unless it is escaped by + * the single quote characters (see below). + * If the sequence is longer than listed in table: + * - for numerical units (`yyyyyyyy`) `parse` will try to match a number + * as wide as the sequence + * - for text units (`MMMMMMMM`) `parse` will try to match the widest variation of the unit. + * These variations are marked with "2" in the last column of the table. + * + * 3. `QQQQQ` and `qqqqq` could be not strictly numerical in some locales. + * These tokens represent the shortest form of the quarter. + * + * 4. The main difference between `y` and `u` patterns are B.C. years: + * + * | Year | `y` | `u` | + * |------|-----|-----| + * | AC 1 | 1 | 1 | + * | BC 1 | 1 | 0 | + * | BC 2 | 2 | -1 | + * + * Also `yy` will try to guess the century of two digit year by proximity with `referenceDate`: + * + * `parse('50', 'yy', new Date(2018, 0, 1)) //=> Sat Jan 01 2050 00:00:00` + * + * `parse('75', 'yy', new Date(2018, 0, 1)) //=> Wed Jan 01 1975 00:00:00` + * + * while `uu` will just assign the year as is: + * + * `parse('50', 'uu', new Date(2018, 0, 1)) //=> Sat Jan 01 0050 00:00:00` + * + * `parse('75', 'uu', new Date(2018, 0, 1)) //=> Tue Jan 01 0075 00:00:00` + * + * The same difference is true for local and ISO week-numbering years (`Y` and `R`), + * except local week-numbering years are dependent on `options.weekStartsOn` + * and `options.firstWeekContainsDate` (compare [setISOWeekYear]{@link https://date-fns.org/docs/setISOWeekYear} + * and [setWeekYear]{@link https://date-fns.org/docs/setWeekYear}). + * + * 5. These patterns are not in the Unicode Technical Standard #35: + * - `i`: ISO day of week + * - `I`: ISO week of year + * - `R`: ISO week-numbering year + * - `o`: ordinal number modifier + * - `P`: long localized date + * - `p`: long localized time + * + * 6. `YY` and `YYYY` tokens represent week-numbering years but they are often confused with years. + * You should enable `options.useAdditionalWeekYearTokens` to use them. See: https://git.io/fxCyr + * + * 7. `D` and `DD` tokens represent days of the year but they are ofthen confused with days of the month. + * You should enable `options.useAdditionalDayOfYearTokens` to use them. See: https://git.io/fxCyr + * + * 8. `P+` tokens do not have a defined priority since they are merely aliases to other tokens based + * on the given locale. + * + * using `en-US` locale: `P` => `MM/dd/yyyy` + * using `en-US` locale: `p` => `hh:mm a` + * using `pt-BR` locale: `P` => `dd/MM/yyyy` + * using `pt-BR` locale: `p` => `HH:mm` + * + * Values will be assigned to the date in the descending order of its unit's priority. + * Units of an equal priority overwrite each other in the order of appearance. + * + * If no values of higher priority are parsed (e.g. when parsing string 'January 1st' without a year), + * the values will be taken from 3rd argument `referenceDate` which works as a context of parsing. + * + * `referenceDate` must be passed for correct work of the function. + * If you're not sure which `referenceDate` to supply, create a new instance of Date: + * `parse('02/11/2014', 'MM/dd/yyyy', new Date())` + * In this case parsing will be done in the context of the current date. + * If `referenceDate` is `Invalid Date` or a value not convertible to valid `Date`, + * then `Invalid Date` will be returned. + * + * The result may vary by locale. + * + * If `formatString` matches with `dateString` but does not provides tokens, `referenceDate` will be returned. + * + * If parsing failed, `Invalid Date` will be returned. + * Invalid Date is a Date, whose time value is NaN. + * Time value of Date: http://es5.github.io/#x15.9.1.1 + * + * ### v2.0.0 breaking changes: + * + * - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes). + * + * - Old `parse` was renamed to `toDate`. + * Now `parse` is a new function which parses a string using a provided format. + * + * ```javascript + * // Before v2.0.0 + * parse('2016-01-01') + * + * // v2.0.0 onward (toDate no longer accepts a string) + * toDate(1392098430000) // Unix to timestamp + * toDate(new Date(2014, 1, 11, 11, 30, 30)) // Cloning the date + * parse('2016-01-01', 'yyyy-MM-dd', new Date()) + * ``` + * + * @param {String} dateString - the string to parse + * @param {String} formatString - the string of tokens + * @param {Date|Number} referenceDate - defines values missing from the parsed dateString + * @param {Object} [options] - an object with options. + * @param {Locale} [options.locale=defaultLocale] - the locale object. See [Locale]{@link https://date-fns.org/docs/Locale} + * @param {0|1|2|3|4|5|6} [options.weekStartsOn=0] - the index of the first day of the week (0 - Sunday) + * @param {1|2|3|4|5|6|7} [options.firstWeekContainsDate=1] - the day of January, which is always in the first week of the year + * @param {Boolean} [options.useAdditionalWeekYearTokens=false] - if true, allows usage of the week-numbering year tokens `YY` and `YYYY`; + * see: https://git.io/fxCyr + * @param {Boolean} [options.useAdditionalDayOfYearTokens=false] - if true, allows usage of the day of year tokens `D` and `DD`; + * see: https://git.io/fxCyr + * @returns {Date} the parsed date + * @throws {TypeError} 3 arguments required + * @throws {RangeError} `options.weekStartsOn` must be between 0 and 6 + * @throws {RangeError} `options.firstWeekContainsDate` must be between 1 and 7 + * @throws {RangeError} `options.locale` must contain `match` property + * @throws {RangeError} use `yyyy` instead of `YYYY` for formatting years using [format provided] to the input [input provided]; see: https://git.io/fxCyr + * @throws {RangeError} use `yy` instead of `YY` for formatting years using [format provided] to the input [input provided]; see: https://git.io/fxCyr + * @throws {RangeError} use `d` instead of `D` for formatting days of the month using [format provided] to the input [input provided]; see: https://git.io/fxCyr + * @throws {RangeError} use `dd` instead of `DD` for formatting days of the month using [format provided] to the input [input provided]; see: https://git.io/fxCyr + * @throws {RangeError} format string contains an unescaped latin alphabet character + * + * @example + * // Parse 11 February 2014 from middle-endian format: + * var result = parse('02/11/2014', 'MM/dd/yyyy', new Date()) + * //=> Tue Feb 11 2014 00:00:00 + * + * @example + * // Parse 28th of February in Esperanto locale in the context of 2010 year: + * import eo from 'date-fns/locale/eo' + * var result = parse('28-a de februaro', "do 'de' MMMM", new Date(2010, 0, 1), { + * locale: eo + * }) + * //=> Sun Feb 28 2010 00:00:00 + */ + +function parse(dirtyDateString, dirtyFormatString, dirtyReferenceDate, dirtyOptions) { + requiredArgs(3, arguments); + var dateString = String(dirtyDateString); + var formatString = String(dirtyFormatString); + var options = dirtyOptions || {}; + var locale = options.locale || defaultLocale; + + if (!locale.match) { + throw new RangeError('locale must contain match property'); + } + + var localeFirstWeekContainsDate = locale.options && locale.options.firstWeekContainsDate; + var defaultFirstWeekContainsDate = localeFirstWeekContainsDate == null ? 1 : toInteger(localeFirstWeekContainsDate); + var firstWeekContainsDate = options.firstWeekContainsDate == null ? defaultFirstWeekContainsDate : toInteger(options.firstWeekContainsDate); // Test if weekStartsOn is between 1 and 7 _and_ is not NaN + + if (!(firstWeekContainsDate >= 1 && firstWeekContainsDate <= 7)) { + throw new RangeError('firstWeekContainsDate must be between 1 and 7 inclusively'); + } + + var localeWeekStartsOn = locale.options && locale.options.weekStartsOn; + var defaultWeekStartsOn = localeWeekStartsOn == null ? 0 : toInteger(localeWeekStartsOn); + var weekStartsOn = options.weekStartsOn == null ? defaultWeekStartsOn : toInteger(options.weekStartsOn); // Test if weekStartsOn is between 0 and 6 _and_ is not NaN + + if (!(weekStartsOn >= 0 && weekStartsOn <= 6)) { + throw new RangeError('weekStartsOn must be between 0 and 6 inclusively'); + } + + if (formatString === '') { + if (dateString === '') { + return toDate(dirtyReferenceDate); + } else { + return new Date(NaN); + } + } + + var subFnOptions = { + firstWeekContainsDate: firstWeekContainsDate, + weekStartsOn: weekStartsOn, + locale: locale // If timezone isn't specified, it will be set to the system timezone + + }; + var setters = [{ + priority: TIMEZONE_UNIT_PRIORITY, + subPriority: -1, + set: dateToSystemTimezone, + index: 0 + }]; + var i; + var tokens = formatString.match(longFormattingTokensRegExp).map(function (substring) { + var firstCharacter = substring[0]; + + if (firstCharacter === 'p' || firstCharacter === 'P') { + var longFormatter = longFormatters$1[firstCharacter]; + return longFormatter(substring, locale.formatLong, subFnOptions); + } + + return substring; + }).join('').match(formattingTokensRegExp); + var usedTokens = []; + + for (i = 0; i < tokens.length; i++) { + var token = tokens[i]; + + if (!options.useAdditionalWeekYearTokens && isProtectedWeekYearToken(token)) { + throwProtectedError(token, formatString, dirtyDateString); + } + + if (!options.useAdditionalDayOfYearTokens && isProtectedDayOfYearToken(token)) { + throwProtectedError(token, formatString, dirtyDateString); + } + + var firstCharacter = token[0]; + var parser = parsers$1[firstCharacter]; + + if (parser) { + var incompatibleTokens = parser.incompatibleTokens; + + if (Array.isArray(incompatibleTokens)) { + var incompatibleToken = void 0; + + for (var _i = 0; _i < usedTokens.length; _i++) { + var usedToken = usedTokens[_i].token; + + if (incompatibleTokens.indexOf(usedToken) !== -1 || usedToken === firstCharacter) { + incompatibleToken = usedTokens[_i]; + break; + } + } + + if (incompatibleToken) { + throw new RangeError("The format string mustn't contain `".concat(incompatibleToken.fullToken, "` and `").concat(token, "` at the same time")); + } + } else if (parser.incompatibleTokens === '*' && usedTokens.length) { + throw new RangeError("The format string mustn't contain `".concat(token, "` and any other token at the same time")); + } + + usedTokens.push({ + token: firstCharacter, + fullToken: token + }); + var parseResult = parser.parse(dateString, token, locale.match, subFnOptions); + + if (!parseResult) { + return new Date(NaN); + } + + setters.push({ + priority: parser.priority, + subPriority: parser.subPriority || 0, + set: parser.set, + validate: parser.validate, + value: parseResult.value, + index: setters.length + }); + dateString = parseResult.rest; + } else { + if (firstCharacter.match(unescapedLatinCharacterRegExp)) { + throw new RangeError('Format string contains an unescaped latin alphabet character `' + firstCharacter + '`'); + } // Replace two single quote characters with one single quote character + + + if (token === "''") { + token = "'"; + } else if (firstCharacter === "'") { + token = cleanEscapedString(token); + } // Cut token from string, or, if string doesn't match the token, return Invalid Date + + + if (dateString.indexOf(token) === 0) { + dateString = dateString.slice(token.length); + } else { + return new Date(NaN); + } + } + } // Check if the remaining input contains something other than whitespace + + + if (dateString.length > 0 && notWhitespaceRegExp.test(dateString)) { + return new Date(NaN); + } + + var uniquePrioritySetters = setters.map(function (setter) { + return setter.priority; + }).sort(function (a, b) { + return b - a; + }).filter(function (priority, index, array) { + return array.indexOf(priority) === index; + }).map(function (priority) { + return setters.filter(function (setter) { + return setter.priority === priority; + }).sort(function (a, b) { + return b.subPriority - a.subPriority; + }); + }).map(function (setterArray) { + return setterArray[0]; + }); + var date = toDate(dirtyReferenceDate); + + if (isNaN(date)) { + return new Date(NaN); + } // Convert the date in system timezone to the same date in UTC+00:00 timezone. + // This ensures that when UTC functions will be implemented, locales will be compatible with them. + // See an issue about UTC functions: https://github.com/date-fns/date-fns/issues/37 + + + var utcDate = subMilliseconds(date, getTimezoneOffsetInMilliseconds(date)); + var flags = {}; + + for (i = 0; i < uniquePrioritySetters.length; i++) { + var setter = uniquePrioritySetters[i]; + + if (setter.validate && !setter.validate(utcDate, setter.value, subFnOptions)) { + return new Date(NaN); + } + + var result = setter.set(utcDate, flags, setter.value, subFnOptions); // Result is tuple (date, flags) + + if (result[0]) { + utcDate = result[0]; + assign(flags, result[1]); // Result is date + } else { + utcDate = result; + } + } + + return utcDate; +} + +function dateToSystemTimezone(date, flags) { + if (flags.timestampIsSet) { + return date; + } + + var convertedDate = new Date(0); + convertedDate.setFullYear(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate()); + convertedDate.setHours(date.getUTCHours(), date.getUTCMinutes(), date.getUTCSeconds(), date.getUTCMilliseconds()); + return convertedDate; +} + +function cleanEscapedString(input) { + return input.match(escapedStringRegExp)[1].replace(doubleQuoteRegExp, "'"); +} + +/** + * @name startOfHour + * @category Hour Helpers + * @summary Return the start of an hour for the given date. + * + * @description + * Return the start of an hour for the given date. + * The result will be in the local timezone. + * + * ### v2.0.0 breaking changes: + * + * - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes). + * + * @param {Date|Number} date - the original date + * @returns {Date} the start of an hour + * @throws {TypeError} 1 argument required + * + * @example + * // The start of an hour for 2 September 2014 11:55:00: + * const result = startOfHour(new Date(2014, 8, 2, 11, 55)) + * //=> Tue Sep 02 2014 11:00:00 + */ + +function startOfHour(dirtyDate) { + requiredArgs(1, arguments); + var date = toDate(dirtyDate); + date.setMinutes(0, 0, 0); + return date; +} + +/** + * @name startOfMinute + * @category Minute Helpers + * @summary Return the start of a minute for the given date. + * + * @description + * Return the start of a minute for the given date. + * The result will be in the local timezone. + * + * ### v2.0.0 breaking changes: + * + * - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes). + * + * @param {Date|Number} date - the original date + * @returns {Date} the start of a minute + * @throws {TypeError} 1 argument required + * + * @example + * // The start of a minute for 1 December 2014 22:15:45.400: + * const result = startOfMinute(new Date(2014, 11, 1, 22, 15, 45, 400)) + * //=> Mon Dec 01 2014 22:15:00 + */ + +function startOfMinute(dirtyDate) { + requiredArgs(1, arguments); + var date = toDate(dirtyDate); + date.setSeconds(0, 0); + return date; +} + +/** + * @name startOfSecond + * @category Second Helpers + * @summary Return the start of a second for the given date. + * + * @description + * Return the start of a second for the given date. + * The result will be in the local timezone. + * + * ### v2.0.0 breaking changes: + * + * - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes). + * + * @param {Date|Number} date - the original date + * @returns {Date} the start of a second + * @throws {TypeError} 1 argument required + * + * @example + * // The start of a second for 1 December 2014 22:15:45.400: + * const result = startOfSecond(new Date(2014, 11, 1, 22, 15, 45, 400)) + * //=> Mon Dec 01 2014 22:15:45.000 + */ + +function startOfSecond(dirtyDate) { + requiredArgs(1, arguments); + var date = toDate(dirtyDate); + date.setMilliseconds(0); + return date; +} + +var MILLISECONDS_IN_HOUR = 3600000; +var MILLISECONDS_IN_MINUTE = 60000; +var DEFAULT_ADDITIONAL_DIGITS = 2; +var patterns = { + dateTimeDelimiter: /[T ]/, + timeZoneDelimiter: /[Z ]/i, + timezone: /([Z+-].*)$/ +}; +var dateRegex = /^-?(?:(\d{3})|(\d{2})(?:-?(\d{2}))?|W(\d{2})(?:-?(\d{1}))?|)$/; +var timeRegex = /^(\d{2}(?:[.,]\d*)?)(?::?(\d{2}(?:[.,]\d*)?))?(?::?(\d{2}(?:[.,]\d*)?))?$/; +var timezoneRegex = /^([+-])(\d{2})(?::?(\d{2}))?$/; +/** + * @name parseISO + * @category Common Helpers + * @summary Parse ISO string + * + * @description + * Parse the given string in ISO 8601 format and return an instance of Date. + * + * Function accepts complete ISO 8601 formats as well as partial implementations. + * ISO 8601: http://en.wikipedia.org/wiki/ISO_8601 + * + * If the argument isn't a string, the function cannot parse the string or + * the values are invalid, it returns Invalid Date. + * + * ### v2.0.0 breaking changes: + * + * - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes). + * + * - The previous `parse` implementation was renamed to `parseISO`. + * + * ```javascript + * // Before v2.0.0 + * parse('2016-01-01') + * + * // v2.0.0 onward + * parseISO('2016-01-01') + * ``` + * + * - `parseISO` now validates separate date and time values in ISO-8601 strings + * and returns `Invalid Date` if the date is invalid. + * + * ```javascript + * parseISO('2018-13-32') + * //=> Invalid Date + * ``` + * + * - `parseISO` now doesn't fall back to `new Date` constructor + * if it fails to parse a string argument. Instead, it returns `Invalid Date`. + * + * @param {String} argument - the value to convert + * @param {Object} [options] - an object with options. + * @param {0|1|2} [options.additionalDigits=2] - the additional number of digits in the extended year format + * @returns {Date} the parsed date in the local time zone + * @throws {TypeError} 1 argument required + * @throws {RangeError} `options.additionalDigits` must be 0, 1 or 2 + * + * @example + * // Convert string '2014-02-11T11:30:30' to date: + * var result = parseISO('2014-02-11T11:30:30') + * //=> Tue Feb 11 2014 11:30:30 + * + * @example + * // Convert string '+02014101' to date, + * // if the additional number of digits in the extended year format is 1: + * var result = parseISO('+02014101', { additionalDigits: 1 }) + * //=> Fri Apr 11 2014 00:00:00 + */ + +function parseISO(argument, dirtyOptions) { + requiredArgs(1, arguments); + var options = dirtyOptions || {}; + var additionalDigits = options.additionalDigits == null ? DEFAULT_ADDITIONAL_DIGITS : toInteger(options.additionalDigits); + + if (additionalDigits !== 2 && additionalDigits !== 1 && additionalDigits !== 0) { + throw new RangeError('additionalDigits must be 0, 1 or 2'); + } + + if (!(typeof argument === 'string' || Object.prototype.toString.call(argument) === '[object String]')) { + return new Date(NaN); + } + + var dateStrings = splitDateString(argument); + var date; + + if (dateStrings.date) { + var parseYearResult = parseYear(dateStrings.date, additionalDigits); + date = parseDate(parseYearResult.restDateString, parseYearResult.year); + } + + if (isNaN(date) || !date) { + return new Date(NaN); + } + + var timestamp = date.getTime(); + var time = 0; + var offset; + + if (dateStrings.time) { + time = parseTime(dateStrings.time); + + if (isNaN(time) || time === null) { + return new Date(NaN); + } + } + + if (dateStrings.timezone) { + offset = parseTimezone(dateStrings.timezone); + + if (isNaN(offset)) { + return new Date(NaN); + } + } else { + var dirtyDate = new Date(timestamp + time); // js parsed string assuming it's in UTC timezone + // but we need it to be parsed in our timezone + // so we use utc values to build date in our timezone. + // Year values from 0 to 99 map to the years 1900 to 1999 + // so set year explicitly with setFullYear. + + var result = new Date(0); + result.setFullYear(dirtyDate.getUTCFullYear(), dirtyDate.getUTCMonth(), dirtyDate.getUTCDate()); + result.setHours(dirtyDate.getUTCHours(), dirtyDate.getUTCMinutes(), dirtyDate.getUTCSeconds(), dirtyDate.getUTCMilliseconds()); + return result; + } + + return new Date(timestamp + time + offset); +} + +function splitDateString(dateString) { + var dateStrings = {}; + var array = dateString.split(patterns.dateTimeDelimiter); + var timeString; // The regex match should only return at maximum two array elements. + // [date], [time], or [date, time]. + + if (array.length > 2) { + return dateStrings; + } + + if (/:/.test(array[0])) { + dateStrings.date = null; + timeString = array[0]; + } else { + dateStrings.date = array[0]; + timeString = array[1]; + + if (patterns.timeZoneDelimiter.test(dateStrings.date)) { + dateStrings.date = dateString.split(patterns.timeZoneDelimiter)[0]; + timeString = dateString.substr(dateStrings.date.length, dateString.length); + } + } + + if (timeString) { + var token = patterns.timezone.exec(timeString); + + if (token) { + dateStrings.time = timeString.replace(token[1], ''); + dateStrings.timezone = token[1]; + } else { + dateStrings.time = timeString; + } + } + + return dateStrings; +} + +function parseYear(dateString, additionalDigits) { + var regex = new RegExp('^(?:(\\d{4}|[+-]\\d{' + (4 + additionalDigits) + '})|(\\d{2}|[+-]\\d{' + (2 + additionalDigits) + '})$)'); + var captures = dateString.match(regex); // Invalid ISO-formatted year + + if (!captures) return { + year: null + }; + var year = captures[1] && parseInt(captures[1]); + var century = captures[2] && parseInt(captures[2]); + return { + year: century == null ? year : century * 100, + restDateString: dateString.slice((captures[1] || captures[2]).length) + }; +} + +function parseDate(dateString, year) { + // Invalid ISO-formatted year + if (year === null) return null; + var captures = dateString.match(dateRegex); // Invalid ISO-formatted string + + if (!captures) return null; + var isWeekDate = !!captures[4]; + var dayOfYear = parseDateUnit(captures[1]); + var month = parseDateUnit(captures[2]) - 1; + var day = parseDateUnit(captures[3]); + var week = parseDateUnit(captures[4]); + var dayOfWeek = parseDateUnit(captures[5]) - 1; + + if (isWeekDate) { + if (!validateWeekDate(year, week, dayOfWeek)) { + return new Date(NaN); + } + + return dayOfISOWeekYear(year, week, dayOfWeek); + } else { + var date = new Date(0); + + if (!validateDate(year, month, day) || !validateDayOfYearDate(year, dayOfYear)) { + return new Date(NaN); + } + + date.setUTCFullYear(year, month, Math.max(dayOfYear, day)); + return date; + } +} + +function parseDateUnit(value) { + return value ? parseInt(value) : 1; +} + +function parseTime(timeString) { + var captures = timeString.match(timeRegex); + if (!captures) return null; // Invalid ISO-formatted time + + var hours = parseTimeUnit(captures[1]); + var minutes = parseTimeUnit(captures[2]); + var seconds = parseTimeUnit(captures[3]); + + if (!validateTime(hours, minutes, seconds)) { + return NaN; + } + + return hours * MILLISECONDS_IN_HOUR + minutes * MILLISECONDS_IN_MINUTE + seconds * 1000; +} + +function parseTimeUnit(value) { + return value && parseFloat(value.replace(',', '.')) || 0; +} + +function parseTimezone(timezoneString) { + if (timezoneString === 'Z') return 0; + var captures = timezoneString.match(timezoneRegex); + if (!captures) return 0; + var sign = captures[1] === '+' ? -1 : 1; + var hours = parseInt(captures[2]); + var minutes = captures[3] && parseInt(captures[3]) || 0; + + if (!validateTimezone(hours, minutes)) { + return NaN; + } + + return sign * (hours * MILLISECONDS_IN_HOUR + minutes * MILLISECONDS_IN_MINUTE); +} + +function dayOfISOWeekYear(isoWeekYear, week, day) { + var date = new Date(0); + date.setUTCFullYear(isoWeekYear, 0, 4); + var fourthOfJanuaryDay = date.getUTCDay() || 7; + var diff = (week - 1) * 7 + day + 1 - fourthOfJanuaryDay; + date.setUTCDate(date.getUTCDate() + diff); + return date; +} // Validation functions +// February is null to handle the leap year (using ||) + + +var daysInMonths = [31, null, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; + +function isLeapYearIndex(year) { + return year % 400 === 0 || year % 4 === 0 && year % 100; +} + +function validateDate(year, month, date) { + return month >= 0 && month <= 11 && date >= 1 && date <= (daysInMonths[month] || (isLeapYearIndex(year) ? 29 : 28)); +} + +function validateDayOfYearDate(year, dayOfYear) { + return dayOfYear >= 1 && dayOfYear <= (isLeapYearIndex(year) ? 366 : 365); +} + +function validateWeekDate(_year, week, day) { + return week >= 1 && week <= 53 && day >= 0 && day <= 6; +} + +function validateTime(hours, minutes, seconds) { + if (hours === 24) { + return minutes === 0 && seconds === 0; + } + + return seconds >= 0 && seconds < 60 && minutes >= 0 && minutes < 60 && hours >= 0 && hours < 25; +} + +function validateTimezone(_hours, minutes) { + return minutes >= 0 && minutes <= 59; +} + +const FORMATS = { + datetime: 'MMM d, yyyy, h:mm:ss aaaa', + millisecond: 'h:mm:ss.SSS aaaa', + second: 'h:mm:ss aaaa', + minute: 'h:mm aaaa', + hour: 'ha', + day: 'MMM d', + week: 'PP', + month: 'MMM yyyy', + quarter: 'qqq - yyyy', + year: 'yyyy' +}; + +chart_js._adapters._date.override({ + _id: 'date-fns', // DEBUG + + formats: function() { + return FORMATS; + }, + + parse: function(value, fmt) { + if (value === null || typeof value === 'undefined') { + return null; + } + const type = typeof value; + if (type === 'number' || value instanceof Date) { + value = toDate(value); + } else if (type === 'string') { + if (typeof fmt === 'string') { + value = parse(value, fmt, new Date(), this.options); + } else { + value = parseISO(value, this.options); + } + } + return isValid(value) ? value.getTime() : null; + }, + + format: function(time, fmt) { + return format(time, fmt, this.options); + }, + + add: function(time, amount, unit) { + switch (unit) { + case 'millisecond': return addMilliseconds(time, amount); + case 'second': return addSeconds(time, amount); + case 'minute': return addMinutes(time, amount); + case 'hour': return addHours(time, amount); + case 'day': return addDays(time, amount); + case 'week': return addWeeks(time, amount); + case 'month': return addMonths(time, amount); + case 'quarter': return addQuarters(time, amount); + case 'year': return addYears(time, amount); + default: return time; + } + }, + + diff: function(max, min, unit) { + switch (unit) { + case 'millisecond': return differenceInMilliseconds(max, min); + case 'second': return differenceInSeconds(max, min); + case 'minute': return differenceInMinutes(max, min); + case 'hour': return differenceInHours(max, min); + case 'day': return differenceInDays(max, min); + case 'week': return differenceInWeeks(max, min); + case 'month': return differenceInMonths(max, min); + case 'quarter': return differenceInQuarters(max, min); + case 'year': return differenceInYears(max, min); + default: return 0; + } + }, + + startOf: function(time, unit, weekday) { + switch (unit) { + case 'second': return startOfSecond(time); + case 'minute': return startOfMinute(time); + case 'hour': return startOfHour(time); + case 'day': return startOfDay(time); + case 'week': return startOfWeek(time); + case 'isoWeek': return startOfWeek(time, {weekStartsOn: +weekday}); + case 'month': return startOfMonth(time); + case 'quarter': return startOfQuarter(time); + case 'year': return startOfYear(time); + default: return time; + } + }, + + endOf: function(time, unit) { + switch (unit) { + case 'second': return endOfSecond(time); + case 'minute': return endOfMinute(time); + case 'hour': return endOfHour(time); + case 'day': return endOfDay(time); + case 'week': return endOfWeek(time); + case 'month': return endOfMonth(time); + case 'quarter': return endOfQuarter(time); + case 'year': return endOfYear(time); + default: return time; + } + } +}); + +})); diff --git a/web/js/vendor/chartjs-adapter-date-fns.bundle.min.js b/web/js/vendor/chartjs-adapter-date-fns.bundle.min.js new file mode 100644 index 0000000..37bffe6 --- /dev/null +++ b/web/js/vendor/chartjs-adapter-date-fns.bundle.min.js @@ -0,0 +1,7 @@ +/*! + * chartjs-adapter-date-fns v3.0.0 + * https://www.chartjs.org + * (c) 2022 chartjs-adapter-date-fns Contributors + * Released under the MIT license + */ +!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(require("chart.js")):"function"==typeof define&&define.amd?define(["chart.js"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).Chart)}(this,(function(t){"use strict";function e(t){if(null===t||!0===t||!1===t)return NaN;var e=Number(t);return isNaN(e)?e:e<0?Math.ceil(e):Math.floor(e)}function r(t,e){if(e.length1?"s":"")+" required, but only "+e.length+" present")}function n(t){r(1,arguments);var e=Object.prototype.toString.call(t);return t instanceof Date||"object"==typeof t&&"[object Date]"===e?new Date(t.getTime()):"number"==typeof t||"[object Number]"===e?new Date(t):("string"!=typeof t&&"[object String]"!==e||"undefined"==typeof console||(console.warn("Starting with v2.0.0-beta.1 date-fns doesn't accept strings as date arguments. Please use `parseISO` to parse strings. See: https://git.io/fjule"),console.warn((new Error).stack)),new Date(NaN))}function a(t,a){r(2,arguments);var i=n(t),o=e(a);return isNaN(o)?new Date(NaN):o?(i.setDate(i.getDate()+o),i):i}function i(t,a){r(2,arguments);var i=n(t),o=e(a);if(isNaN(o))return new Date(NaN);if(!o)return i;var u=i.getDate(),s=new Date(i.getTime());s.setMonth(i.getMonth()+o+1,0);var c=s.getDate();return u>=c?s:(i.setFullYear(s.getFullYear(),s.getMonth(),u),i)}function o(t,a){r(2,arguments);var i=n(t).getTime(),o=e(a);return new Date(i+o)}var u=36e5;function s(t,a){r(1,arguments);var i=a||{},o=i.locale,u=o&&o.options&&o.options.weekStartsOn,s=null==u?0:e(u),c=null==i.weekStartsOn?s:e(i.weekStartsOn);if(!(c>=0&&c<=6))throw new RangeError("weekStartsOn must be between 0 and 6 inclusively");var d=n(t),l=d.getDay(),f=(l0?1:o}function m(t){r(1,arguments);var e=n(t);return!isNaN(e)}function w(t,e){r(2,arguments);var a=n(t),i=n(e),o=a.getFullYear()-i.getFullYear(),u=a.getMonth()-i.getMonth();return 12*o+u}function g(t,e){r(2,arguments);var a=n(t),i=n(e);return a.getFullYear()-i.getFullYear()}function v(t,e){var r=t.getFullYear()-e.getFullYear()||t.getMonth()-e.getMonth()||t.getDate()-e.getDate()||t.getHours()-e.getHours()||t.getMinutes()-e.getMinutes()||t.getSeconds()-e.getSeconds()||t.getMilliseconds()-e.getMilliseconds();return r<0?-1:r>0?1:r}function y(t,e){r(2,arguments);var a=n(t),i=n(e),o=v(a,i),u=Math.abs(f(a,i));a.setDate(a.getDate()-o*u);var s=v(a,i)===-o,c=o*(u-s);return 0===c?0:c}function b(t,e){r(2,arguments);var a=n(t),i=n(e);return a.getTime()-i.getTime()}var T=36e5;function p(t){r(1,arguments);var e=n(t);return e.setHours(23,59,59,999),e}function C(t){r(1,arguments);var e=n(t),a=e.getMonth();return e.setFullYear(e.getFullYear(),a+1,0),e.setHours(23,59,59,999),e}function M(t){r(1,arguments);var e=n(t);return p(e).getTime()===C(e).getTime()}function D(t,e){r(2,arguments);var a,i=n(t),o=n(e),u=h(i,o),s=Math.abs(w(i,o));if(s<1)a=0;else{1===i.getMonth()&&i.getDate()>27&&i.setDate(30),i.setMonth(i.getMonth()-u*s);var c=h(i,o)===-u;M(n(t))&&1===s&&1===h(t,o)&&(c=!1),a=u*(s-c)}return 0===a?0:a}var x={lessThanXSeconds:{one:"less than a second",other:"less than {{count}} seconds"},xSeconds:{one:"1 second",other:"{{count}} seconds"},halfAMinute:"half a minute",lessThanXMinutes:{one:"less than a minute",other:"less than {{count}} minutes"},xMinutes:{one:"1 minute",other:"{{count}} minutes"},aboutXHours:{one:"about 1 hour",other:"about {{count}} hours"},xHours:{one:"1 hour",other:"{{count}} hours"},xDays:{one:"1 day",other:"{{count}} days"},aboutXWeeks:{one:"about 1 week",other:"about {{count}} weeks"},xWeeks:{one:"1 week",other:"{{count}} weeks"},aboutXMonths:{one:"about 1 month",other:"about {{count}} months"},xMonths:{one:"1 month",other:"{{count}} months"},aboutXYears:{one:"about 1 year",other:"about {{count}} years"},xYears:{one:"1 year",other:"{{count}} years"},overXYears:{one:"over 1 year",other:"over {{count}} years"},almostXYears:{one:"almost 1 year",other:"almost {{count}} years"}};function k(t){return function(e){var r=e||{},n=r.width?String(r.width):t.defaultWidth;return t.formats[n]||t.formats[t.defaultWidth]}}var U={date:k({formats:{full:"EEEE, MMMM do, y",long:"MMMM do, y",medium:"MMM d, y",short:"MM/dd/yyyy"},defaultWidth:"full"}),time:k({formats:{full:"h:mm:ss a zzzz",long:"h:mm:ss a z",medium:"h:mm:ss a",short:"h:mm a"},defaultWidth:"full"}),dateTime:k({formats:{full:"{{date}} 'at' {{time}}",long:"{{date}} 'at' {{time}}",medium:"{{date}}, {{time}}",short:"{{date}}, {{time}}"},defaultWidth:"full"})},Y={lastWeek:"'last' eeee 'at' p",yesterday:"'yesterday at' p",today:"'today at' p",tomorrow:"'tomorrow at' p",nextWeek:"eeee 'at' p",other:"P"};function N(t){return function(e,r){var n,a=r||{};if("formatting"===(a.context?String(a.context):"standalone")&&t.formattingValues){var i=t.defaultFormattingWidth||t.defaultWidth,o=a.width?String(a.width):i;n=t.formattingValues[o]||t.formattingValues[i]}else{var u=t.defaultWidth,s=a.width?String(a.width):t.defaultWidth;n=t.values[s]||t.values[u]}return n[t.argumentCallback?t.argumentCallback(e):e]}}function S(t){return function(e,r){var n=String(e),a=r||{},i=a.width,o=i&&t.matchPatterns[i]||t.matchPatterns[t.defaultMatchWidth],u=n.match(o);if(!u)return null;var s,c=u[0],d=i&&t.parsePatterns[i]||t.parsePatterns[t.defaultParseWidth];return s="[object Array]"===Object.prototype.toString.call(d)?function(t,e){for(var r=0;r0?"in "+n:n+" ago":n},formatLong:U,formatRelative:function(t,e,r,n){return Y[t]},localize:{ordinalNumber:function(t,e){var r=Number(t),n=r%100;if(n>20||n<10)switch(n%10){case 1:return r+"st";case 2:return r+"nd";case 3:return r+"rd"}return r+"th"},era:N({values:{narrow:["B","A"],abbreviated:["BC","AD"],wide:["Before Christ","Anno Domini"]},defaultWidth:"wide"}),quarter:N({values:{narrow:["1","2","3","4"],abbreviated:["Q1","Q2","Q3","Q4"],wide:["1st quarter","2nd quarter","3rd quarter","4th quarter"]},defaultWidth:"wide",argumentCallback:function(t){return Number(t)-1}}),month:N({values:{narrow:["J","F","M","A","M","J","J","A","S","O","N","D"],abbreviated:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],wide:["January","February","March","April","May","June","July","August","September","October","November","December"]},defaultWidth:"wide"}),day:N({values:{narrow:["S","M","T","W","T","F","S"],short:["Su","Mo","Tu","We","Th","Fr","Sa"],abbreviated:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],wide:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"]},defaultWidth:"wide"}),dayPeriod:N({values:{narrow:{am:"a",pm:"p",midnight:"mi",noon:"n",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"},abbreviated:{am:"AM",pm:"PM",midnight:"midnight",noon:"noon",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"},wide:{am:"a.m.",pm:"p.m.",midnight:"midnight",noon:"noon",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"}},defaultWidth:"wide",formattingValues:{narrow:{am:"a",pm:"p",midnight:"mi",noon:"n",morning:"in the morning",afternoon:"in the afternoon",evening:"in the evening",night:"at night"},abbreviated:{am:"AM",pm:"PM",midnight:"midnight",noon:"noon",morning:"in the morning",afternoon:"in the afternoon",evening:"in the evening",night:"at night"},wide:{am:"a.m.",pm:"p.m.",midnight:"midnight",noon:"noon",morning:"in the morning",afternoon:"in the afternoon",evening:"in the evening",night:"at night"}},defaultFormattingWidth:"wide"})},match:{ordinalNumber:(P={matchPattern:/^(\d+)(th|st|nd|rd)?/i,parsePattern:/\d+/i,valueCallback:function(t){return parseInt(t,10)}},function(t,e){var r=String(t),n=e||{},a=r.match(P.matchPattern);if(!a)return null;var i=a[0],o=r.match(P.parsePattern);if(!o)return null;var u=P.valueCallback?P.valueCallback(o[0]):o[0];return{value:u=n.valueCallback?n.valueCallback(u):u,rest:r.slice(i.length)}}),era:S({matchPatterns:{narrow:/^(b|a)/i,abbreviated:/^(b\.?\s?c\.?|b\.?\s?c\.?\s?e\.?|a\.?\s?d\.?|c\.?\s?e\.?)/i,wide:/^(before christ|before common era|anno domini|common era)/i},defaultMatchWidth:"wide",parsePatterns:{any:[/^b/i,/^(a|c)/i]},defaultParseWidth:"any"}),quarter:S({matchPatterns:{narrow:/^[1234]/i,abbreviated:/^q[1234]/i,wide:/^[1234](th|st|nd|rd)? quarter/i},defaultMatchWidth:"wide",parsePatterns:{any:[/1/i,/2/i,/3/i,/4/i]},defaultParseWidth:"any",valueCallback:function(t){return t+1}}),month:S({matchPatterns:{narrow:/^[jfmasond]/i,abbreviated:/^(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)/i,wide:/^(january|february|march|april|may|june|july|august|september|october|november|december)/i},defaultMatchWidth:"wide",parsePatterns:{narrow:[/^j/i,/^f/i,/^m/i,/^a/i,/^m/i,/^j/i,/^j/i,/^a/i,/^s/i,/^o/i,/^n/i,/^d/i],any:[/^ja/i,/^f/i,/^mar/i,/^ap/i,/^may/i,/^jun/i,/^jul/i,/^au/i,/^s/i,/^o/i,/^n/i,/^d/i]},defaultParseWidth:"any"}),day:S({matchPatterns:{narrow:/^[smtwf]/i,short:/^(su|mo|tu|we|th|fr|sa)/i,abbreviated:/^(sun|mon|tue|wed|thu|fri|sat)/i,wide:/^(sunday|monday|tuesday|wednesday|thursday|friday|saturday)/i},defaultMatchWidth:"wide",parsePatterns:{narrow:[/^s/i,/^m/i,/^t/i,/^w/i,/^t/i,/^f/i,/^s/i],any:[/^su/i,/^m/i,/^tu/i,/^w/i,/^th/i,/^f/i,/^sa/i]},defaultParseWidth:"any"}),dayPeriod:S({matchPatterns:{narrow:/^(a|p|mi|n|(in the|at) (morning|afternoon|evening|night))/i,any:/^([ap]\.?\s?m\.?|midnight|noon|(in the|at) (morning|afternoon|evening|night))/i},defaultMatchWidth:"any",parsePatterns:{any:{am:/^a/i,pm:/^p/i,midnight:/^mi/i,noon:/^no/i,morning:/morning/i,afternoon:/afternoon/i,evening:/evening/i,night:/night/i}},defaultParseWidth:"any"})},options:{weekStartsOn:0,firstWeekContainsDate:1}};function H(t,n){r(2,arguments);var a=e(n);return o(t,-a)}function E(t,e){for(var r=t<0?"-":"",n=Math.abs(t).toString();n.length0?r:1-r;return E("yy"===e?n%100:n,e.length)},M:function(t,e){var r=t.getUTCMonth();return"M"===e?String(r+1):E(r+1,2)},d:function(t,e){return E(t.getUTCDate(),e.length)},a:function(t,e){var r=t.getUTCHours()/12>=1?"pm":"am";switch(e){case"a":case"aa":return r.toUpperCase();case"aaa":return r;case"aaaaa":return r[0];default:return"am"===r?"a.m.":"p.m."}},h:function(t,e){return E(t.getUTCHours()%12||12,e.length)},H:function(t,e){return E(t.getUTCHours(),e.length)},m:function(t,e){return E(t.getUTCMinutes(),e.length)},s:function(t,e){return E(t.getUTCSeconds(),e.length)},S:function(t,e){var r=e.length,n=t.getUTCMilliseconds();return E(Math.floor(n*Math.pow(10,r-3)),e.length)}},F=864e5;function W(t){r(1,arguments);var e=1,a=n(t),i=a.getUTCDay(),o=(i=o.getTime()?a+1:e.getTime()>=s.getTime()?a:a-1}function Q(t){r(1,arguments);var e=L(t),n=new Date(0);n.setUTCFullYear(e,0,4),n.setUTCHours(0,0,0,0);var a=W(n);return a}var R=6048e5;function I(t){r(1,arguments);var e=n(t),a=W(e).getTime()-Q(e).getTime();return Math.round(a/R)+1}function G(t,a){r(1,arguments);var i=a||{},o=i.locale,u=o&&o.options&&o.options.weekStartsOn,s=null==u?0:e(u),c=null==i.weekStartsOn?s:e(i.weekStartsOn);if(!(c>=0&&c<=6))throw new RangeError("weekStartsOn must be between 0 and 6 inclusively");var d=n(t),l=d.getUTCDay(),f=(l=1&&l<=7))throw new RangeError("firstWeekContainsDate must be between 1 and 7 inclusively");var f=new Date(0);f.setUTCFullYear(o+1,0,l),f.setUTCHours(0,0,0,0);var h=G(f,a),m=new Date(0);m.setUTCFullYear(o,0,l),m.setUTCHours(0,0,0,0);var w=G(m,a);return i.getTime()>=h.getTime()?o+1:i.getTime()>=w.getTime()?o:o-1}function j(t,n){r(1,arguments);var a=n||{},i=a.locale,o=i&&i.options&&i.options.firstWeekContainsDate,u=null==o?1:e(o),s=null==a.firstWeekContainsDate?u:e(a.firstWeekContainsDate),c=X(t,n),d=new Date(0);d.setUTCFullYear(c,0,s),d.setUTCHours(0,0,0,0);var l=G(d,n);return l}var B=6048e5;function z(t,e){r(1,arguments);var a=n(t),i=G(a,e).getTime()-j(a,e).getTime();return Math.round(i/B)+1}var A="midnight",Z="noon",K="morning",$="afternoon",_="evening",J="night",V={G:function(t,e,r){var n=t.getUTCFullYear()>0?1:0;switch(e){case"G":case"GG":case"GGG":return r.era(n,{width:"abbreviated"});case"GGGGG":return r.era(n,{width:"narrow"});default:return r.era(n,{width:"wide"})}},y:function(t,e,r){if("yo"===e){var n=t.getUTCFullYear(),a=n>0?n:1-n;return r.ordinalNumber(a,{unit:"year"})}return O.y(t,e)},Y:function(t,e,r,n){var a=X(t,n),i=a>0?a:1-a;return"YY"===e?E(i%100,2):"Yo"===e?r.ordinalNumber(i,{unit:"year"}):E(i,e.length)},R:function(t,e){return E(L(t),e.length)},u:function(t,e){return E(t.getUTCFullYear(),e.length)},Q:function(t,e,r){var n=Math.ceil((t.getUTCMonth()+1)/3);switch(e){case"Q":return String(n);case"QQ":return E(n,2);case"Qo":return r.ordinalNumber(n,{unit:"quarter"});case"QQQ":return r.quarter(n,{width:"abbreviated",context:"formatting"});case"QQQQQ":return r.quarter(n,{width:"narrow",context:"formatting"});default:return r.quarter(n,{width:"wide",context:"formatting"})}},q:function(t,e,r){var n=Math.ceil((t.getUTCMonth()+1)/3);switch(e){case"q":return String(n);case"qq":return E(n,2);case"qo":return r.ordinalNumber(n,{unit:"quarter"});case"qqq":return r.quarter(n,{width:"abbreviated",context:"standalone"});case"qqqqq":return r.quarter(n,{width:"narrow",context:"standalone"});default:return r.quarter(n,{width:"wide",context:"standalone"})}},M:function(t,e,r){var n=t.getUTCMonth();switch(e){case"M":case"MM":return O.M(t,e);case"Mo":return r.ordinalNumber(n+1,{unit:"month"});case"MMM":return r.month(n,{width:"abbreviated",context:"formatting"});case"MMMMM":return r.month(n,{width:"narrow",context:"formatting"});default:return r.month(n,{width:"wide",context:"formatting"})}},L:function(t,e,r){var n=t.getUTCMonth();switch(e){case"L":return String(n+1);case"LL":return E(n+1,2);case"Lo":return r.ordinalNumber(n+1,{unit:"month"});case"LLL":return r.month(n,{width:"abbreviated",context:"standalone"});case"LLLLL":return r.month(n,{width:"narrow",context:"standalone"});default:return r.month(n,{width:"wide",context:"standalone"})}},w:function(t,e,r,n){var a=z(t,n);return"wo"===e?r.ordinalNumber(a,{unit:"week"}):E(a,e.length)},I:function(t,e,r){var n=I(t);return"Io"===e?r.ordinalNumber(n,{unit:"week"}):E(n,e.length)},d:function(t,e,r){return"do"===e?r.ordinalNumber(t.getUTCDate(),{unit:"date"}):O.d(t,e)},D:function(t,e,a){var i=function(t){r(1,arguments);var e=n(t),a=e.getTime();e.setUTCMonth(0,1),e.setUTCHours(0,0,0,0);var i=e.getTime(),o=a-i;return Math.floor(o/F)+1}(t);return"Do"===e?a.ordinalNumber(i,{unit:"dayOfYear"}):E(i,e.length)},E:function(t,e,r){var n=t.getUTCDay();switch(e){case"E":case"EE":case"EEE":return r.day(n,{width:"abbreviated",context:"formatting"});case"EEEEE":return r.day(n,{width:"narrow",context:"formatting"});case"EEEEEE":return r.day(n,{width:"short",context:"formatting"});default:return r.day(n,{width:"wide",context:"formatting"})}},e:function(t,e,r,n){var a=t.getUTCDay(),i=(a-n.weekStartsOn+8)%7||7;switch(e){case"e":return String(i);case"ee":return E(i,2);case"eo":return r.ordinalNumber(i,{unit:"day"});case"eee":return r.day(a,{width:"abbreviated",context:"formatting"});case"eeeee":return r.day(a,{width:"narrow",context:"formatting"});case"eeeeee":return r.day(a,{width:"short",context:"formatting"});default:return r.day(a,{width:"wide",context:"formatting"})}},c:function(t,e,r,n){var a=t.getUTCDay(),i=(a-n.weekStartsOn+8)%7||7;switch(e){case"c":return String(i);case"cc":return E(i,e.length);case"co":return r.ordinalNumber(i,{unit:"day"});case"ccc":return r.day(a,{width:"abbreviated",context:"standalone"});case"ccccc":return r.day(a,{width:"narrow",context:"standalone"});case"cccccc":return r.day(a,{width:"short",context:"standalone"});default:return r.day(a,{width:"wide",context:"standalone"})}},i:function(t,e,r){var n=t.getUTCDay(),a=0===n?7:n;switch(e){case"i":return String(a);case"ii":return E(a,e.length);case"io":return r.ordinalNumber(a,{unit:"day"});case"iii":return r.day(n,{width:"abbreviated",context:"formatting"});case"iiiii":return r.day(n,{width:"narrow",context:"formatting"});case"iiiiii":return r.day(n,{width:"short",context:"formatting"});default:return r.day(n,{width:"wide",context:"formatting"})}},a:function(t,e,r){var n=t.getUTCHours()/12>=1?"pm":"am";switch(e){case"a":case"aa":return r.dayPeriod(n,{width:"abbreviated",context:"formatting"});case"aaa":return r.dayPeriod(n,{width:"abbreviated",context:"formatting"}).toLowerCase();case"aaaaa":return r.dayPeriod(n,{width:"narrow",context:"formatting"});default:return r.dayPeriod(n,{width:"wide",context:"formatting"})}},b:function(t,e,r){var n,a=t.getUTCHours();switch(n=12===a?Z:0===a?A:a/12>=1?"pm":"am",e){case"b":case"bb":return r.dayPeriod(n,{width:"abbreviated",context:"formatting"});case"bbb":return r.dayPeriod(n,{width:"abbreviated",context:"formatting"}).toLowerCase();case"bbbbb":return r.dayPeriod(n,{width:"narrow",context:"formatting"});default:return r.dayPeriod(n,{width:"wide",context:"formatting"})}},B:function(t,e,r){var n,a=t.getUTCHours();switch(n=a>=17?_:a>=12?$:a>=4?K:J,e){case"B":case"BB":case"BBB":return r.dayPeriod(n,{width:"abbreviated",context:"formatting"});case"BBBBB":return r.dayPeriod(n,{width:"narrow",context:"formatting"});default:return r.dayPeriod(n,{width:"wide",context:"formatting"})}},h:function(t,e,r){if("ho"===e){var n=t.getUTCHours()%12;return 0===n&&(n=12),r.ordinalNumber(n,{unit:"hour"})}return O.h(t,e)},H:function(t,e,r){return"Ho"===e?r.ordinalNumber(t.getUTCHours(),{unit:"hour"}):O.H(t,e)},K:function(t,e,r){var n=t.getUTCHours()%12;return"Ko"===e?r.ordinalNumber(n,{unit:"hour"}):E(n,e.length)},k:function(t,e,r){var n=t.getUTCHours();return 0===n&&(n=24),"ko"===e?r.ordinalNumber(n,{unit:"hour"}):E(n,e.length)},m:function(t,e,r){return"mo"===e?r.ordinalNumber(t.getUTCMinutes(),{unit:"minute"}):O.m(t,e)},s:function(t,e,r){return"so"===e?r.ordinalNumber(t.getUTCSeconds(),{unit:"second"}):O.s(t,e)},S:function(t,e){return O.S(t,e)},X:function(t,e,r,n){var a=(n._originalDate||t).getTimezoneOffset();if(0===a)return"Z";switch(e){case"X":return et(a);case"XXXX":case"XX":return rt(a);default:return rt(a,":")}},x:function(t,e,r,n){var a=(n._originalDate||t).getTimezoneOffset();switch(e){case"x":return et(a);case"xxxx":case"xx":return rt(a);default:return rt(a,":")}},O:function(t,e,r,n){var a=(n._originalDate||t).getTimezoneOffset();switch(e){case"O":case"OO":case"OOO":return"GMT"+tt(a,":");default:return"GMT"+rt(a,":")}},z:function(t,e,r,n){var a=(n._originalDate||t).getTimezoneOffset();switch(e){case"z":case"zz":case"zzz":return"GMT"+tt(a,":");default:return"GMT"+rt(a,":")}},t:function(t,e,r,n){var a=n._originalDate||t;return E(Math.floor(a.getTime()/1e3),e.length)},T:function(t,e,r,n){return E((n._originalDate||t).getTime(),e.length)}};function tt(t,e){var r=t>0?"-":"+",n=Math.abs(t),a=Math.floor(n/60),i=n%60;if(0===i)return r+String(a);var o=e||"";return r+String(a)+o+E(i,2)}function et(t,e){return t%60==0?(t>0?"-":"+")+E(Math.abs(t)/60,2):rt(t,e)}function rt(t,e){var r=e||"",n=t>0?"-":"+",a=Math.abs(t);return n+E(Math.floor(a/60),2)+r+E(a%60,2)}var nt=V;function at(t,e){switch(t){case"P":return e.date({width:"short"});case"PP":return e.date({width:"medium"});case"PPP":return e.date({width:"long"});default:return e.date({width:"full"})}}function it(t,e){switch(t){case"p":return e.time({width:"short"});case"pp":return e.time({width:"medium"});case"ppp":return e.time({width:"long"});default:return e.time({width:"full"})}}var ot={p:it,P:function(t,e){var r,n=t.match(/(P+)(p+)?/),a=n[1],i=n[2];if(!i)return at(t,e);switch(a){case"P":r=e.dateTime({width:"short"});break;case"PP":r=e.dateTime({width:"medium"});break;case"PPP":r=e.dateTime({width:"long"});break;default:r=e.dateTime({width:"full"})}return r.replace("{{date}}",at(a,e)).replace("{{time}}",it(i,e))}},ut=ot,st=["D","DD"],ct=["YY","YYYY"];function dt(t){return-1!==st.indexOf(t)}function lt(t){return-1!==ct.indexOf(t)}function ft(t,e,r){if("YYYY"===t)throw new RangeError("Use `yyyy` instead of `YYYY` (in `".concat(e,"`) for formatting years to the input `").concat(r,"`; see: https://git.io/fxCyr"));if("YY"===t)throw new RangeError("Use `yy` instead of `YY` (in `".concat(e,"`) for formatting years to the input `").concat(r,"`; see: https://git.io/fxCyr"));if("D"===t)throw new RangeError("Use `d` instead of `D` (in `".concat(e,"`) for formatting days of the month to the input `").concat(r,"`; see: https://git.io/fxCyr"));if("DD"===t)throw new RangeError("Use `dd` instead of `DD` (in `".concat(e,"`) for formatting days of the month to the input `").concat(r,"`; see: https://git.io/fxCyr"))}var ht=/[yYQqMLwIdDecihHKkms]o|(\w)\1*|''|'(''|[^'])+('|$)|./g,mt=/P+p+|P+|p+|''|'(''|[^'])+('|$)|./g,wt=/^'([^]*?)'?$/,gt=/''/g,vt=/[a-zA-Z]/;function yt(t){return t.match(wt)[1].replace(gt,"'")}function bt(t,e){if(null==t)throw new TypeError("assign requires that input parameter not be null or undefined");for(var r in e=e||{})e.hasOwnProperty(r)&&(t[r]=e[r]);return t}function Tt(t,a,i){r(2,arguments);var o=i||{},u=o.locale,s=u&&u.options&&u.options.weekStartsOn,c=null==s?0:e(s),d=null==o.weekStartsOn?c:e(o.weekStartsOn);if(!(d>=0&&d<=6))throw new RangeError("weekStartsOn must be between 0 and 6 inclusively");var l=n(t),f=e(a),h=l.getUTCDay(),m=f%7,w=(m+7)%7,g=(w0,a=n?e:1-e;if(a<=50)r=t||100;else{var i=a+50;r=t+100*Math.floor(i/100)-(t>=i%100?100:0)}return n?r:1-r}var Jt=[31,28,31,30,31,30,31,31,30,31,30,31],Vt=[31,29,31,30,31,30,31,31,30,31,30,31];function te(t){return t%400==0||t%4==0&&t%100!=0}var ee={G:{priority:140,parse:function(t,e,r,n){switch(e){case"G":case"GG":case"GGG":return r.era(t,{width:"abbreviated"})||r.era(t,{width:"narrow"});case"GGGGG":return r.era(t,{width:"narrow"});default:return r.era(t,{width:"wide"})||r.era(t,{width:"abbreviated"})||r.era(t,{width:"narrow"})}},set:function(t,e,r,n){return e.era=r,t.setUTCFullYear(r,0,1),t.setUTCHours(0,0,0,0),t},incompatibleTokens:["R","u","t","T"]},y:{priority:130,parse:function(t,e,r,n){var a=function(t){return{year:t,isTwoDigitYear:"yy"===e}};switch(e){case"y":return Zt(4,t,a);case"yo":return r.ordinalNumber(t,{unit:"year",valueCallback:a});default:return Zt(e.length,t,a)}},validate:function(t,e,r){return e.isTwoDigitYear||e.year>0},set:function(t,e,r,n){var a=t.getUTCFullYear();if(r.isTwoDigitYear){var i=_t(r.year,a);return t.setUTCFullYear(i,0,1),t.setUTCHours(0,0,0,0),t}var o="era"in e&&1!==e.era?1-r.year:r.year;return t.setUTCFullYear(o,0,1),t.setUTCHours(0,0,0,0),t},incompatibleTokens:["Y","R","u","w","I","i","e","c","t","T"]},Y:{priority:130,parse:function(t,e,r,n){var a=function(t){return{year:t,isTwoDigitYear:"YY"===e}};switch(e){case"Y":return Zt(4,t,a);case"Yo":return r.ordinalNumber(t,{unit:"year",valueCallback:a});default:return Zt(e.length,t,a)}},validate:function(t,e,r){return e.isTwoDigitYear||e.year>0},set:function(t,e,r,n){var a=X(t,n);if(r.isTwoDigitYear){var i=_t(r.year,a);return t.setUTCFullYear(i,0,n.firstWeekContainsDate),t.setUTCHours(0,0,0,0),G(t,n)}var o="era"in e&&1!==e.era?1-r.year:r.year;return t.setUTCFullYear(o,0,n.firstWeekContainsDate),t.setUTCHours(0,0,0,0),G(t,n)},incompatibleTokens:["y","R","u","Q","q","M","L","I","d","D","i","t","T"]},R:{priority:130,parse:function(t,e,r,n){return Kt("R"===e?4:e.length,t)},set:function(t,e,r,n){var a=new Date(0);return a.setUTCFullYear(r,0,4),a.setUTCHours(0,0,0,0),W(a)},incompatibleTokens:["G","y","Y","u","Q","q","M","L","w","d","D","e","c","t","T"]},u:{priority:130,parse:function(t,e,r,n){return Kt("u"===e?4:e.length,t)},set:function(t,e,r,n){return t.setUTCFullYear(r,0,1),t.setUTCHours(0,0,0,0),t},incompatibleTokens:["G","y","Y","R","w","I","i","e","c","t","T"]},Q:{priority:120,parse:function(t,e,r,n){switch(e){case"Q":case"QQ":return Zt(e.length,t);case"Qo":return r.ordinalNumber(t,{unit:"quarter"});case"QQQ":return r.quarter(t,{width:"abbreviated",context:"formatting"})||r.quarter(t,{width:"narrow",context:"formatting"});case"QQQQQ":return r.quarter(t,{width:"narrow",context:"formatting"});default:return r.quarter(t,{width:"wide",context:"formatting"})||r.quarter(t,{width:"abbreviated",context:"formatting"})||r.quarter(t,{width:"narrow",context:"formatting"})}},validate:function(t,e,r){return e>=1&&e<=4},set:function(t,e,r,n){return t.setUTCMonth(3*(r-1),1),t.setUTCHours(0,0,0,0),t},incompatibleTokens:["Y","R","q","M","L","w","I","d","D","i","e","c","t","T"]},q:{priority:120,parse:function(t,e,r,n){switch(e){case"q":case"qq":return Zt(e.length,t);case"qo":return r.ordinalNumber(t,{unit:"quarter"});case"qqq":return r.quarter(t,{width:"abbreviated",context:"standalone"})||r.quarter(t,{width:"narrow",context:"standalone"});case"qqqqq":return r.quarter(t,{width:"narrow",context:"standalone"});default:return r.quarter(t,{width:"wide",context:"standalone"})||r.quarter(t,{width:"abbreviated",context:"standalone"})||r.quarter(t,{width:"narrow",context:"standalone"})}},validate:function(t,e,r){return e>=1&&e<=4},set:function(t,e,r,n){return t.setUTCMonth(3*(r-1),1),t.setUTCHours(0,0,0,0),t},incompatibleTokens:["Y","R","Q","M","L","w","I","d","D","i","e","c","t","T"]},M:{priority:110,parse:function(t,e,r,n){var a=function(t){return t-1};switch(e){case"M":return Bt(pt,t,a);case"MM":return Zt(2,t,a);case"Mo":return r.ordinalNumber(t,{unit:"month",valueCallback:a});case"MMM":return r.month(t,{width:"abbreviated",context:"formatting"})||r.month(t,{width:"narrow",context:"formatting"});case"MMMMM":return r.month(t,{width:"narrow",context:"formatting"});default:return r.month(t,{width:"wide",context:"formatting"})||r.month(t,{width:"abbreviated",context:"formatting"})||r.month(t,{width:"narrow",context:"formatting"})}},validate:function(t,e,r){return e>=0&&e<=11},set:function(t,e,r,n){return t.setUTCMonth(r,1),t.setUTCHours(0,0,0,0),t},incompatibleTokens:["Y","R","q","Q","L","w","I","D","i","e","c","t","T"]},L:{priority:110,parse:function(t,e,r,n){var a=function(t){return t-1};switch(e){case"L":return Bt(pt,t,a);case"LL":return Zt(2,t,a);case"Lo":return r.ordinalNumber(t,{unit:"month",valueCallback:a});case"LLL":return r.month(t,{width:"abbreviated",context:"standalone"})||r.month(t,{width:"narrow",context:"standalone"});case"LLLLL":return r.month(t,{width:"narrow",context:"standalone"});default:return r.month(t,{width:"wide",context:"standalone"})||r.month(t,{width:"abbreviated",context:"standalone"})||r.month(t,{width:"narrow",context:"standalone"})}},validate:function(t,e,r){return e>=0&&e<=11},set:function(t,e,r,n){return t.setUTCMonth(r,1),t.setUTCHours(0,0,0,0),t},incompatibleTokens:["Y","R","q","Q","M","w","I","D","i","e","c","t","T"]},w:{priority:100,parse:function(t,e,r,n){switch(e){case"w":return Bt(Dt,t);case"wo":return r.ordinalNumber(t,{unit:"week"});default:return Zt(e.length,t)}},validate:function(t,e,r){return e>=1&&e<=53},set:function(t,a,i,o){return G(function(t,a,i){r(2,arguments);var o=n(t),u=e(a),s=z(o,i)-u;return o.setUTCDate(o.getUTCDate()-7*s),o}(t,i,o),o)},incompatibleTokens:["y","R","u","q","Q","M","L","I","d","D","i","t","T"]},I:{priority:100,parse:function(t,e,r,n){switch(e){case"I":return Bt(Dt,t);case"Io":return r.ordinalNumber(t,{unit:"week"});default:return Zt(e.length,t)}},validate:function(t,e,r){return e>=1&&e<=53},set:function(t,a,i,o){return W(function(t,a){r(2,arguments);var i=n(t),o=e(a),u=I(i)-o;return i.setUTCDate(i.getUTCDate()-7*u),i}(t,i,o),o)},incompatibleTokens:["y","Y","u","q","Q","M","L","w","d","D","e","c","t","T"]},d:{priority:90,subPriority:1,parse:function(t,e,r,n){switch(e){case"d":return Bt(Ct,t);case"do":return r.ordinalNumber(t,{unit:"date"});default:return Zt(e.length,t)}},validate:function(t,e,r){var n=te(t.getUTCFullYear()),a=t.getUTCMonth();return n?e>=1&&e<=Vt[a]:e>=1&&e<=Jt[a]},set:function(t,e,r,n){return t.setUTCDate(r),t.setUTCHours(0,0,0,0),t},incompatibleTokens:["Y","R","q","Q","w","I","D","i","e","c","t","T"]},D:{priority:90,subPriority:1,parse:function(t,e,r,n){switch(e){case"D":case"DD":return Bt(Mt,t);case"Do":return r.ordinalNumber(t,{unit:"date"});default:return Zt(e.length,t)}},validate:function(t,e,r){return te(t.getUTCFullYear())?e>=1&&e<=366:e>=1&&e<=365},set:function(t,e,r,n){return t.setUTCMonth(0,r),t.setUTCHours(0,0,0,0),t},incompatibleTokens:["Y","R","q","Q","M","L","w","I","d","E","i","e","c","t","T"]},E:{priority:90,parse:function(t,e,r,n){switch(e){case"E":case"EE":case"EEE":return r.day(t,{width:"abbreviated",context:"formatting"})||r.day(t,{width:"short",context:"formatting"})||r.day(t,{width:"narrow",context:"formatting"});case"EEEEE":return r.day(t,{width:"narrow",context:"formatting"});case"EEEEEE":return r.day(t,{width:"short",context:"formatting"})||r.day(t,{width:"narrow",context:"formatting"});default:return r.day(t,{width:"wide",context:"formatting"})||r.day(t,{width:"abbreviated",context:"formatting"})||r.day(t,{width:"short",context:"formatting"})||r.day(t,{width:"narrow",context:"formatting"})}},validate:function(t,e,r){return e>=0&&e<=6},set:function(t,e,r,n){return(t=Tt(t,r,n)).setUTCHours(0,0,0,0),t},incompatibleTokens:["D","i","e","c","t","T"]},e:{priority:90,parse:function(t,e,r,n){var a=function(t){var e=7*Math.floor((t-1)/7);return(t+n.weekStartsOn+6)%7+e};switch(e){case"e":case"ee":return Zt(e.length,t,a);case"eo":return r.ordinalNumber(t,{unit:"day",valueCallback:a});case"eee":return r.day(t,{width:"abbreviated",context:"formatting"})||r.day(t,{width:"short",context:"formatting"})||r.day(t,{width:"narrow",context:"formatting"});case"eeeee":return r.day(t,{width:"narrow",context:"formatting"});case"eeeeee":return r.day(t,{width:"short",context:"formatting"})||r.day(t,{width:"narrow",context:"formatting"});default:return r.day(t,{width:"wide",context:"formatting"})||r.day(t,{width:"abbreviated",context:"formatting"})||r.day(t,{width:"short",context:"formatting"})||r.day(t,{width:"narrow",context:"formatting"})}},validate:function(t,e,r){return e>=0&&e<=6},set:function(t,e,r,n){return(t=Tt(t,r,n)).setUTCHours(0,0,0,0),t},incompatibleTokens:["y","R","u","q","Q","M","L","I","d","D","E","i","c","t","T"]},c:{priority:90,parse:function(t,e,r,n){var a=function(t){var e=7*Math.floor((t-1)/7);return(t+n.weekStartsOn+6)%7+e};switch(e){case"c":case"cc":return Zt(e.length,t,a);case"co":return r.ordinalNumber(t,{unit:"day",valueCallback:a});case"ccc":return r.day(t,{width:"abbreviated",context:"standalone"})||r.day(t,{width:"short",context:"standalone"})||r.day(t,{width:"narrow",context:"standalone"});case"ccccc":return r.day(t,{width:"narrow",context:"standalone"});case"cccccc":return r.day(t,{width:"short",context:"standalone"})||r.day(t,{width:"narrow",context:"standalone"});default:return r.day(t,{width:"wide",context:"standalone"})||r.day(t,{width:"abbreviated",context:"standalone"})||r.day(t,{width:"short",context:"standalone"})||r.day(t,{width:"narrow",context:"standalone"})}},validate:function(t,e,r){return e>=0&&e<=6},set:function(t,e,r,n){return(t=Tt(t,r,n)).setUTCHours(0,0,0,0),t},incompatibleTokens:["y","R","u","q","Q","M","L","I","d","D","E","i","e","t","T"]},i:{priority:90,parse:function(t,e,r,n){var a=function(t){return 0===t?7:t};switch(e){case"i":case"ii":return Zt(e.length,t);case"io":return r.ordinalNumber(t,{unit:"day"});case"iii":return r.day(t,{width:"abbreviated",context:"formatting",valueCallback:a})||r.day(t,{width:"short",context:"formatting",valueCallback:a})||r.day(t,{width:"narrow",context:"formatting",valueCallback:a});case"iiiii":return r.day(t,{width:"narrow",context:"formatting",valueCallback:a});case"iiiiii":return r.day(t,{width:"short",context:"formatting",valueCallback:a})||r.day(t,{width:"narrow",context:"formatting",valueCallback:a});default:return r.day(t,{width:"wide",context:"formatting",valueCallback:a})||r.day(t,{width:"abbreviated",context:"formatting",valueCallback:a})||r.day(t,{width:"short",context:"formatting",valueCallback:a})||r.day(t,{width:"narrow",context:"formatting",valueCallback:a})}},validate:function(t,e,r){return e>=1&&e<=7},set:function(t,a,i,o){return t=function(t,a){r(2,arguments);var i=e(a);i%7==0&&(i-=7);var o=1,u=n(t),s=u.getUTCDay(),c=((i%7+7)%7=1&&e<=12},set:function(t,e,r,n){var a=t.getUTCHours()>=12;return a&&r<12?t.setUTCHours(r+12,0,0,0):a||12!==r?t.setUTCHours(r,0,0,0):t.setUTCHours(0,0,0,0),t},incompatibleTokens:["H","K","k","t","T"]},H:{priority:70,parse:function(t,e,r,n){switch(e){case"H":return Bt(xt,t);case"Ho":return r.ordinalNumber(t,{unit:"hour"});default:return Zt(e.length,t)}},validate:function(t,e,r){return e>=0&&e<=23},set:function(t,e,r,n){return t.setUTCHours(r,0,0,0),t},incompatibleTokens:["a","b","h","K","k","t","T"]},K:{priority:70,parse:function(t,e,r,n){switch(e){case"K":return Bt(Ut,t);case"Ko":return r.ordinalNumber(t,{unit:"hour"});default:return Zt(e.length,t)}},validate:function(t,e,r){return e>=0&&e<=11},set:function(t,e,r,n){return t.getUTCHours()>=12&&r<12?t.setUTCHours(r+12,0,0,0):t.setUTCHours(r,0,0,0),t},incompatibleTokens:["a","b","h","H","k","t","T"]},k:{priority:70,parse:function(t,e,r,n){switch(e){case"k":return Bt(kt,t);case"ko":return r.ordinalNumber(t,{unit:"hour"});default:return Zt(e.length,t)}},validate:function(t,e,r){return e>=1&&e<=24},set:function(t,e,r,n){var a=r<=24?r%24:r;return t.setUTCHours(a,0,0,0),t},incompatibleTokens:["a","b","h","H","K","t","T"]},m:{priority:60,parse:function(t,e,r,n){switch(e){case"m":return Bt(Nt,t);case"mo":return r.ordinalNumber(t,{unit:"minute"});default:return Zt(e.length,t)}},validate:function(t,e,r){return e>=0&&e<=59},set:function(t,e,r,n){return t.setUTCMinutes(r,0,0),t},incompatibleTokens:["t","T"]},s:{priority:50,parse:function(t,e,r,n){switch(e){case"s":return Bt(St,t);case"so":return r.ordinalNumber(t,{unit:"second"});default:return Zt(e.length,t)}},validate:function(t,e,r){return e>=0&&e<=59},set:function(t,e,r,n){return t.setUTCSeconds(r,0),t},incompatibleTokens:["t","T"]},S:{priority:30,parse:function(t,e,r,n){return Zt(e.length,t,(function(t){return Math.floor(t*Math.pow(10,3-e.length))}))},set:function(t,e,r,n){return t.setUTCMilliseconds(r),t},incompatibleTokens:["t","T"]},X:{priority:10,parse:function(t,e,r,n){switch(e){case"X":return zt(Rt,t);case"XX":return zt(It,t);case"XXXX":return zt(Gt,t);case"XXXXX":return zt(jt,t);default:return zt(Xt,t)}},set:function(t,e,r,n){return e.timestampIsSet?t:new Date(t.getTime()-r)},incompatibleTokens:["t","T","x"]},x:{priority:10,parse:function(t,e,r,n){switch(e){case"x":return zt(Rt,t);case"xx":return zt(It,t);case"xxxx":return zt(Gt,t);case"xxxxx":return zt(jt,t);default:return zt(Xt,t)}},set:function(t,e,r,n){return e.timestampIsSet?t:new Date(t.getTime()-r)},incompatibleTokens:["t","T","X"]},t:{priority:40,parse:function(t,e,r,n){return At(t)},set:function(t,e,r,n){return[new Date(1e3*r),{timestampIsSet:!0}]},incompatibleTokens:"*"},T:{priority:20,parse:function(t,e,r,n){return At(t)},set:function(t,e,r,n){return[new Date(r),{timestampIsSet:!0}]},incompatibleTokens:"*"}},re=ee,ne=/[yYQqMLwIdDecihHKkms]o|(\w)\1*|''|'(''|[^'])+('|$)|./g,ae=/P+p+|P+|p+|''|'(''|[^'])+('|$)|./g,ie=/^'([^]*?)'?$/,oe=/''/g,ue=/\S/,se=/[a-zA-Z]/;function ce(t,e){if(e.timestampIsSet)return t;var r=new Date(0);return r.setFullYear(t.getUTCFullYear(),t.getUTCMonth(),t.getUTCDate()),r.setHours(t.getUTCHours(),t.getUTCMinutes(),t.getUTCSeconds(),t.getUTCMilliseconds()),r}function de(t){return t.match(ie)[1].replace(oe,"'")}var le=36e5,fe={dateTimeDelimiter:/[T ]/,timeZoneDelimiter:/[Z ]/i,timezone:/([Z+-].*)$/},he=/^-?(?:(\d{3})|(\d{2})(?:-?(\d{2}))?|W(\d{2})(?:-?(\d{1}))?|)$/,me=/^(\d{2}(?:[.,]\d*)?)(?::?(\d{2}(?:[.,]\d*)?))?(?::?(\d{2}(?:[.,]\d*)?))?$/,we=/^([+-])(\d{2})(?::?(\d{2}))?$/;function ge(t){var e,r={},n=t.split(fe.dateTimeDelimiter);if(n.length>2)return r;if(/:/.test(n[0])?(r.date=null,e=n[0]):(r.date=n[0],e=n[1],fe.timeZoneDelimiter.test(r.date)&&(r.date=t.split(fe.timeZoneDelimiter)[0],e=t.substr(r.date.length,t.length))),e){var a=fe.timezone.exec(e);a?(r.time=e.replace(a[1],""),r.timezone=a[1]):r.time=e}return r}function ve(t,e){var r=new RegExp("^(?:(\\d{4}|[+-]\\d{"+(4+e)+"})|(\\d{2}|[+-]\\d{"+(2+e)+"})$)"),n=t.match(r);if(!n)return{year:null};var a=n[1]&&parseInt(n[1]),i=n[2]&&parseInt(n[2]);return{year:null==i?a:100*i,restDateString:t.slice((n[1]||n[2]).length)}}function ye(t,e){if(null===e)return null;var r=t.match(he);if(!r)return null;var n=!!r[4],a=be(r[1]),i=be(r[2])-1,o=be(r[3]),u=be(r[4]),s=be(r[5])-1;if(n)return function(t,e,r){return e>=1&&e<=53&&r>=0&&r<=6}(0,u,s)?function(t,e,r){var n=new Date(0);n.setUTCFullYear(t,0,4);var a=n.getUTCDay()||7,i=7*(e-1)+r+1-a;return n.setUTCDate(n.getUTCDate()+i),n}(e,u,s):new Date(NaN);var c=new Date(0);return function(t,e,r){return e>=0&&e<=11&&r>=1&&r<=(Me[e]||(De(t)?29:28))}(e,i,o)&&function(t,e){return e>=1&&e<=(De(t)?366:365)}(e,a)?(c.setUTCFullYear(e,i,Math.max(a,o)),c):new Date(NaN)}function be(t){return t?parseInt(t):1}function Te(t){var e=t.match(me);if(!e)return null;var r=pe(e[1]),n=pe(e[2]),a=pe(e[3]);return function(t,e,r){if(24===t)return 0===e&&0===r;return r>=0&&r<60&&e>=0&&e<60&&t>=0&&t<25}(r,n,a)?r*le+6e4*n+1e3*a:NaN}function pe(t){return t&&parseFloat(t.replace(",","."))||0}function Ce(t){if("Z"===t)return 0;var e=t.match(we);if(!e)return 0;var r="+"===e[1]?-1:1,n=parseInt(e[2]),a=e[3]&&parseInt(e[3])||0;return function(t,e){return e>=0&&e<=59}(0,a)?r*(n*le+6e4*a):NaN}var Me=[31,null,31,30,31,30,31,31,30,31,30,31];function De(t){return t%400==0||t%4==0&&t%100}const xe={datetime:"MMM d, yyyy, h:mm:ss aaaa",millisecond:"h:mm:ss.SSS aaaa",second:"h:mm:ss aaaa",minute:"h:mm aaaa",hour:"ha",day:"MMM d",week:"PP",month:"MMM yyyy",quarter:"qqq - yyyy",year:"yyyy"};t._adapters._date.override({_id:"date-fns",formats:function(){return xe},parse:function(t,a){if(null==t)return null;const i=typeof t;return"number"===i||t instanceof Date?t=n(t):"string"===i&&(t="string"==typeof a?function(t,a,i,o){r(3,arguments);var u=String(t),s=String(a),d=o||{},l=d.locale||q;if(!l.match)throw new RangeError("locale must contain match property");var f=l.options&&l.options.firstWeekContainsDate,h=null==f?1:e(f),m=null==d.firstWeekContainsDate?h:e(d.firstWeekContainsDate);if(!(m>=1&&m<=7))throw new RangeError("firstWeekContainsDate must be between 1 and 7 inclusively");var w=l.options&&l.options.weekStartsOn,g=null==w?0:e(w),v=null==d.weekStartsOn?g:e(d.weekStartsOn);if(!(v>=0&&v<=6))throw new RangeError("weekStartsOn must be between 0 and 6 inclusively");if(""===s)return""===u?n(i):new Date(NaN);var y,b={firstWeekContainsDate:m,weekStartsOn:v,locale:l},T=[{priority:10,subPriority:-1,set:ce,index:0}],p=s.match(ae).map((function(t){var e=t[0];return"p"===e||"P"===e?(0,ut[e])(t,l.formatLong,b):t})).join("").match(ne),C=[];for(y=0;y0&&ue.test(u))return new Date(NaN);var P=T.map((function(t){return t.priority})).sort((function(t,e){return e-t})).filter((function(t,e,r){return r.indexOf(t)===e})).map((function(t){return T.filter((function(e){return e.priority===t})).sort((function(t,e){return e.subPriority-t.subPriority}))})).map((function(t){return t[0]})),E=n(i);if(isNaN(E))return new Date(NaN);var O=H(E,c(E)),F={};for(y=0;y=1&&f<=7))throw new RangeError("firstWeekContainsDate must be between 1 and 7 inclusively");var h=s.options&&s.options.weekStartsOn,w=null==h?0:e(h),g=null==u.weekStartsOn?w:e(u.weekStartsOn);if(!(g>=0&&g<=6))throw new RangeError("weekStartsOn must be between 0 and 6 inclusively");if(!s.localize)throw new RangeError("locale must contain localize property");if(!s.formatLong)throw new RangeError("locale must contain formatLong property");var v=n(t);if(!m(v))throw new RangeError("Invalid time value");var y=c(v),b=H(v,y),T={firstWeekContainsDate:f,weekStartsOn:g,locale:s,_originalDate:v},p=o.match(mt).map((function(t){var e=t[0];return"p"===e||"P"===e?(0,ut[e])(t,s.formatLong,T):t})).join("").match(ht).map((function(e){if("''"===e)return"'";var r=e[0];if("'"===r)return yt(e);var n=nt[r];if(n)return!u.useAdditionalWeekYearTokens&<(e)&&ft(e,a,t),!u.useAdditionalDayOfYearTokens&&dt(e)&&ft(e,a,t),n(b,e,s.localize,T);if(r.match(vt))throw new RangeError("Format string contains an unescaped latin alphabet character `"+r+"`");return e})).join("");return p}(t,a,this.options)},add:function(t,n,s){switch(s){case"millisecond":return o(t,n);case"second":return function(t,n){r(2,arguments);var a=e(n);return o(t,1e3*a)}(t,n);case"minute":return function(t,n){r(2,arguments);var a=e(n);return o(t,6e4*a)}(t,n);case"hour":return function(t,n){r(2,arguments);var a=e(n);return o(t,a*u)}(t,n);case"day":return a(t,n);case"week":return function(t,n){r(2,arguments);var i=e(n),o=7*i;return a(t,o)}(t,n);case"month":return i(t,n);case"quarter":return function(t,n){r(2,arguments);var a=e(n),o=3*a;return i(t,o)}(t,n);case"year":return function(t,n){r(2,arguments);var a=e(n);return i(t,12*a)}(t,n);default:return t}},diff:function(t,e,a){switch(a){case"millisecond":return b(t,e);case"second":return function(t,e){r(2,arguments);var n=b(t,e)/1e3;return n>0?Math.floor(n):Math.ceil(n)}(t,e);case"minute":return function(t,e){r(2,arguments);var n=b(t,e)/6e4;return n>0?Math.floor(n):Math.ceil(n)}(t,e);case"hour":return function(t,e){r(2,arguments);var n=b(t,e)/T;return n>0?Math.floor(n):Math.ceil(n)}(t,e);case"day":return y(t,e);case"week":return function(t,e){r(2,arguments);var n=y(t,e)/7;return n>0?Math.floor(n):Math.ceil(n)}(t,e);case"month":return D(t,e);case"quarter":return function(t,e){r(2,arguments);var n=D(t,e)/3;return n>0?Math.floor(n):Math.ceil(n)}(t,e);case"year":return function(t,e){r(2,arguments);var a=n(t),i=n(e),o=h(a,i),u=Math.abs(g(a,i));a.setFullYear("1584"),i.setFullYear("1584");var s=h(a,i)===-o,c=o*(u-s);return 0===c?0:c}(t,e);default:return 0}},startOf:function(t,e,a){switch(e){case"second":return function(t){r(1,arguments);var e=n(t);return e.setMilliseconds(0),e}(t);case"minute":return function(t){r(1,arguments);var e=n(t);return e.setSeconds(0,0),e}(t);case"hour":return function(t){r(1,arguments);var e=n(t);return e.setMinutes(0,0,0),e}(t);case"day":return d(t);case"week":return s(t);case"isoWeek":return s(t,{weekStartsOn:+a});case"month":return function(t){r(1,arguments);var e=n(t);return e.setDate(1),e.setHours(0,0,0,0),e}(t);case"quarter":return function(t){r(1,arguments);var e=n(t),a=e.getMonth(),i=a-a%3;return e.setMonth(i,1),e.setHours(0,0,0,0),e}(t);case"year":return function(t){r(1,arguments);var e=n(t),a=new Date(0);return a.setFullYear(e.getFullYear(),0,1),a.setHours(0,0,0,0),a}(t);default:return t}},endOf:function(t,a){switch(a){case"second":return function(t){r(1,arguments);var e=n(t);return e.setMilliseconds(999),e}(t);case"minute":return function(t){r(1,arguments);var e=n(t);return e.setSeconds(59,999),e}(t);case"hour":return function(t){r(1,arguments);var e=n(t);return e.setMinutes(59,59,999),e}(t);case"day":return p(t);case"week":return function(t,a){r(1,arguments);var i=a||{},o=i.locale,u=o&&o.options&&o.options.weekStartsOn,s=null==u?0:e(u),c=null==i.weekStartsOn?s:e(i.weekStartsOn);if(!(c>=0&&c<=6))throw new RangeError("weekStartsOn must be between 0 and 6 inclusively");var d=n(t),l=d.getDay(),f=6+(l=5&&((s||!n&&5===u)&&(p.push(u,0,s,t),u=6),n&&(p.push(u,n,0,t),u=6)),s=""},o=0;o"===e?(u=1,s=""):s=e+s[0]:r?e===r?r="":s+=e:'"'===e||"'"===e?r=e:">"===e?(h(),u=1):u&&("="===e?(u=5,t=s,s=""):"/"===e&&(u<5||">"===n[o][f+1])?(h(),3===u&&(p=p[0]),u=p,(p=p[0]).push(2,0,u),u=0):" "===e||"\t"===e||"\n"===e||"\r"===e?(h(),u=2):s+=e),3===u&&"!--"===s&&(u=4,p=p[0])}return h(),p}(t)),u),arguments,[])).length>1?u:u[0]}}); diff --git a/web/js/vendor/preact-hooks.umd.js b/web/js/vendor/preact-hooks.umd.js new file mode 100644 index 0000000..47ab528 --- /dev/null +++ b/web/js/vendor/preact-hooks.umd.js @@ -0,0 +1,2 @@ +!function(n,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("preact")):"function"==typeof define&&define.amd?define(["exports","preact"],t):t((n||self).preactHooks={},n.preact)}(this,function(n,t){var u,r,i,o,f=0,e=[],c=[],a=t.options.__b,v=t.options.__r,l=t.options.diffed,d=t.options.__c,s=t.options.unmount;function p(n,u){t.options.__h&&t.options.__h(r,n,f||u),f=0;var i=r.__H||(r.__H={__:[],__h:[]});return n>=i.__.length&&i.__.push({__V:c}),i.__[n]}function h(n){return f=1,y(g,n)}function y(n,t,i){var o=p(u++,2);if(o.t=n,!o.__c&&(o.__=[i?i(t):g(void 0,t),function(n){var t=o.__N?o.__N[0]:o.__[0],u=o.t(t,n);t!==u&&(o.__N=[u,o.__[1]],o.__c.setState({}))}],o.__c=r,!r.u)){var f=function(n,t,u){if(!o.__c.__H)return!0;var r=o.__c.__H.__.filter(function(n){return n.__c});if(r.every(function(n){return!n.__N}))return!e||e.call(this,n,t,u);var i=!1;return r.forEach(function(n){if(n.__N){var t=n.__[0];n.__=n.__N,n.__N=void 0,t!==n.__[0]&&(i=!0)}}),!(!i&&o.__c.props===n)&&(!e||e.call(this,n,t,u))};r.u=!0;var e=r.shouldComponentUpdate,c=r.componentWillUpdate;r.componentWillUpdate=function(n,t,u){if(this.__e){var r=e;e=void 0,f(n,t,u),e=r}c&&c.call(this,n,t,u)},r.shouldComponentUpdate=f}return o.__N||o.__}function m(n,i){var o=p(u++,4);!t.options.__s&&F(o.__H,i)&&(o.__=n,o.i=i,r.__h.push(o))}function _(n,t){var r=p(u++,7);return F(r.__H,t)?(r.__V=n(),r.i=t,r.__h=n,r.__V):r.__}function T(){for(var n;n=e.shift();)if(n.__P&&n.__H)try{n.__H.__h.forEach(x),n.__H.__h.forEach(A),n.__H.__h=[]}catch(u){n.__H.__h=[],t.options.__e(u,n.__v)}}t.options.__b=function(n){r=null,a&&a(n)},t.options.__r=function(n){v&&v(n),u=0;var t=(r=n.__c).__H;t&&(i===r?(t.__h=[],r.__h=[],t.__.forEach(function(n){n.__N&&(n.__=n.__N),n.__V=c,n.__N=n.i=void 0})):(t.__h.forEach(x),t.__h.forEach(A),t.__h=[],u=0)),i=r},t.options.diffed=function(n){l&&l(n);var u=n.__c;u&&u.__H&&(u.__H.__h.length&&(1!==e.push(u)&&o===t.options.requestAnimationFrame||((o=t.options.requestAnimationFrame)||q)(T)),u.__H.__.forEach(function(n){n.i&&(n.__H=n.i),n.__V!==c&&(n.__=n.__V),n.i=void 0,n.__V=c})),i=r=null},t.options.__c=function(n,u){u.some(function(n){try{n.__h.forEach(x),n.__h=n.__h.filter(function(n){return!n.__||A(n)})}catch(r){u.some(function(n){n.__h&&(n.__h=[])}),u=[],t.options.__e(r,n.__v)}}),d&&d(n,u)},t.options.unmount=function(n){s&&s(n);var u,r=n.__c;r&&r.__H&&(r.__H.__.forEach(function(n){try{x(n)}catch(n){u=n}}),r.__H=void 0,u&&t.options.__e(u,r.__v))};var b="function"==typeof requestAnimationFrame;function q(n){var t,u=function(){clearTimeout(r),b&&cancelAnimationFrame(t),setTimeout(n)},r=setTimeout(u,100);b&&(t=requestAnimationFrame(u))}function x(n){var t=r,u=n.__c;"function"==typeof u&&(n.__c=void 0,u()),r=t}function A(n){var t=r;n.__c=n.__(),r=t}function F(n,t){return!n||n.length!==t.length||t.some(function(t,u){return t!==n[u]})}function g(n,t){return"function"==typeof t?t(n):t}n.useCallback=function(n,t){return f=8,_(function(){return n},t)},n.useContext=function(n){var t=r.context[n.__c],i=p(u++,9);return i.c=n,t?(null==i.__&&(i.__=!0,t.sub(r)),t.props.value):n.__},n.useDebugValue=function(n,u){t.options.useDebugValue&&t.options.useDebugValue(u?u(n):n)},n.useEffect=function(n,i){var o=p(u++,3);!t.options.__s&&F(o.__H,i)&&(o.__=n,o.i=i,r.__H.__h.push(o))},n.useErrorBoundary=function(n){var t=p(u++,10),i=h();return t.__=n,r.componentDidCatch||(r.componentDidCatch=function(n,u){t.__&&t.__(n,u),i[1](n)}),[i[0],function(){i[1](void 0)}]},n.useId=function(){var n=p(u++,11);if(!n.__){for(var t=r.__v;null!==t&&!t.__m&&null!==t.__;)t=t.__;var i=t.__m||(t.__m=[0,0]);n.__="P"+i[0]+"-"+i[1]++}return n.__},n.useImperativeHandle=function(n,t,u){f=6,m(function(){return"function"==typeof n?(n(t()),function(){return n(null)}):n?(n.current=t(),function(){return n.current=null}):void 0},null==u?u:u.concat(n))},n.useLayoutEffect=m,n.useMemo=_,n.useReducer=y,n.useRef=function(n){return f=5,_(function(){return{current:n}},[])},n.useState=h}); +//# sourceMappingURL=hooks.umd.js.map diff --git a/web/js/vendor/preact.umd.js b/web/js/vendor/preact.umd.js new file mode 100644 index 0000000..e259989 --- /dev/null +++ b/web/js/vendor/preact.umd.js @@ -0,0 +1,2 @@ +!function(n,l){"object"==typeof exports&&"undefined"!=typeof module?l(exports):"function"==typeof define&&define.amd?define(["exports"],l):l((n||self).preact={})}(this,function(n){var l,u,t,i,o,r,f,e,c,s=65536,a=1<<17,h={},p=[],v=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i,y=Array.isArray;function d(n,l){for(var u in l)n[u]=l[u];return n}function _(n){var l=n.parentNode;l&&l.removeChild(n)}function b(n,u,t){var i,o,r,f={};for(r in u)"key"==r?i=u[r]:"ref"==r?o=u[r]:f[r]=u[r];if(arguments.length>2&&(f.children=arguments.length>3?l.call(arguments,2):t),"function"==typeof n&&null!=n.defaultProps)for(r in n.defaultProps)void 0===f[r]&&(f[r]=n.defaultProps[r]);return g(n,f,i,o,null)}function g(n,l,i,o,r){var f={type:n,props:l,key:i,ref:o,__k:null,__:null,__b:0,__e:null,__d:void 0,__c:null,constructor:void 0,__v:null==r?++t:r,__i:-1,__u:0};return null==r&&null!=u.vnode&&u.vnode(f),f}function m(n){return n.children}function k(n,l){this.props=n,this.context=l}function w(n,l){if(null==l)return n.__?w(n.__,n.__i+1):null;for(var u;ll&&o.sort(e));S.__r=0}function T(n,l,u,t,i,o,r,f,e,c,a){var v,y,d,_,b,g=t&&t.__k||p,m=l.length;for(u.__d=e,$(u,l,g),e=u.__d,v=0;v0?g(i.type,i.props,i.key,i.ref?i.ref:null,i.__v):i)?(i.__=n,i.__b=n.__b+1,f=H(i,u,r=t+p,h),i.__i=f,o=null,-1!==f&&(h--,(o=u[f])&&(o.__u|=a)),null==o||null===o.__v?(-1==f&&p--,"function"!=typeof i.type&&(i.__u|=s)):f!==r&&(f===r+1?p++:f>r?h>e-r?p+=f-r:p--:p=f(null!=e&&0==(e.__u&a)?1:0))for(;r>=0||f=0){if((e=l[r])&&0==(e.__u&a)&&i==e.key&&o===e.type)return r;r--}if(f2&&(e.children=arguments.length>3?l.call(arguments,2):t),g(n.type,e,i||n.key,o||n.ref,null)},n.createContext=function(n,l){var u={__c:l="__cC"+c++,__:n,Consumer:function(n,l){return n.children(l)},Provider:function(n){var u,t;return this.getChildContext||(u=[],(t={})[l]=this,this.getChildContext=function(){return t},this.shouldComponentUpdate=function(n){this.props.value!==n.value&&u.some(function(n){n.__e=!0,P(n)})},this.sub=function(n){u.push(n);var l=n.componentWillUnmount;n.componentWillUnmount=function(){u.splice(u.indexOf(n),1),l&&l.call(n)}}),n.children}};return u.Provider.__=u.Consumer.contextType=u},n.createElement=b,n.createRef=function(){return{current:null}},n.h=b,n.hydrate=function n(l,u){B(l,u,n)},n.isValidElement=i,n.options=u,n.render=B,n.toChildArray=function n(l,u){return u=u||[],null==l||"boolean"==typeof l||(y(l)?l.some(function(l){n(l,u)}):u.push(l)),u}}); +//# sourceMappingURL=preact.umd.js.map