mirror of
https://github.com/lrnselfreliance/wrolpi.git
synced 2026-11-29 19:36:20 -05:00
Compare commits
272 commits
ai-preview
...
master
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d34b2a7088 | ||
|
|
2c3300b8b0 | ||
|
|
633b125dc6 | ||
|
|
b372a5fc90 | ||
|
|
34eeebb8b8 | ||
|
|
712c4d9abc | ||
|
|
762b5ff6a0 | ||
|
|
ee30d99212 | ||
|
|
92761e1c52 | ||
|
|
2db9e45d92 | ||
|
|
68d8eadd69 | ||
|
|
f58c86af88 | ||
|
|
4c9f413322 | ||
|
|
fcd9f1bc40 | ||
|
|
b57f64ee71 | ||
|
|
45a8fefe48 | ||
|
|
3ae978dc53 | ||
|
|
d4d288f84a | ||
|
|
72b507116e | ||
|
|
faf8e735d1 | ||
|
|
d157057d81 | ||
|
|
a5ab01198b | ||
|
|
38885990f6 | ||
|
|
8cfe36b3ea | ||
|
|
6772762ce9 | ||
|
|
ea7cc4dec2 | ||
|
|
2ac4a3a294 | ||
|
|
bb7a66b0d6 | ||
|
|
d11b72bbd1 | ||
|
|
dc219e0775 | ||
|
|
3e23022418 | ||
|
|
0389e4659c | ||
|
|
38832870c9 | ||
|
|
b2b8e2075c | ||
|
|
177d0dba4b | ||
|
|
113e70a402 | ||
|
|
4f58d2862f | ||
|
|
adb0adbd94 | ||
|
|
4072ac30ed | ||
|
|
30b2bf6df0 | ||
|
|
f1d344d8a2 | ||
|
|
2800112f3e | ||
|
|
a0f30a0a60 | ||
|
|
6cd233dce6 | ||
|
|
86f168d2c1 | ||
|
|
19ff59d5e0 | ||
|
|
d88db90ce9 | ||
|
|
f3f762ef1b | ||
|
|
d25ebb9e63 | ||
|
|
2e0e50c3aa | ||
|
|
6c24d7d762 | ||
|
|
aff5f1eb1f | ||
|
|
c7bafaa7fb | ||
|
|
e5987fdd7e | ||
|
|
20439437f8 | ||
|
|
ba9b47edf3 | ||
|
|
cafa2a2279 | ||
|
|
89b84c9765 | ||
|
|
479aa2254e | ||
|
|
87137cc40c | ||
|
|
9797af157a | ||
|
|
0aa4019f86 | ||
|
|
871a26324d | ||
|
|
c78378d4f5 | ||
|
|
b8122a4637 | ||
|
|
6c8ea61eaa | ||
|
|
2991f737da | ||
|
|
662a41afc3 | ||
|
|
31b47dacf8 | ||
|
|
7f275284a1 | ||
|
|
f782f347d1 | ||
|
|
ab6f17fb5b | ||
|
|
7487cb07a1 | ||
|
|
b9aae3f049 | ||
|
|
9c9b740d55 | ||
|
|
9af8ee89f5 | ||
|
|
c6d7084527 | ||
|
|
03a904d31a | ||
|
|
00fdfad8e2 | ||
|
|
5be899bf1f | ||
|
|
c0452e29e6 | ||
|
|
e6b7b9e5dd | ||
|
|
ee6c384dc6 | ||
|
|
851b12b060 | ||
|
|
6fc147ccdf | ||
|
|
21006eae09 | ||
|
|
bfe7b8afbd | ||
|
|
9c258b41ee | ||
|
|
8edace08bd | ||
|
|
fe85815c35 | ||
|
|
d69f8317aa | ||
|
|
ecdad6c3e0 | ||
|
|
bde1209c63 | ||
|
|
fb3b959fff | ||
|
|
70e915f610 | ||
|
|
dc3a8bb313 | ||
|
|
2caa2609ec | ||
|
|
78e2741db8 | ||
|
|
4c8e9fb68c | ||
|
|
32405a9132 | ||
|
|
a40beac0f6 | ||
|
|
44052741d3 | ||
|
|
56fee562b7 | ||
|
|
49eeef68e8 | ||
|
|
576f631d95 | ||
|
|
a44cc8a456 | ||
|
|
ce7095c0a1 | ||
|
|
98ceb67321 | ||
|
|
3c815245b4 | ||
|
|
9352002d07 | ||
|
|
f4cd3b6f77 | ||
|
|
4365e23327 | ||
|
|
edca3f610f | ||
|
|
8befb23e38 | ||
|
|
b14a32c7bc | ||
|
|
22ada7eb57 | ||
|
|
a248104b2f | ||
|
|
bc58a5cc35 | ||
|
|
eb82489426 | ||
|
|
ae97727b98 | ||
|
|
d16bac29e8 | ||
|
|
fffb2ed981 | ||
|
|
c577cae9d8 | ||
|
|
79526afebe | ||
|
|
0dd61b8e64 | ||
|
|
c3e25b84d6 | ||
|
|
ee10b34b15 | ||
|
|
315b60e9eb | ||
|
|
57c2a29022 | ||
|
|
5cdb4aaac0 | ||
|
|
adbcf944a5 | ||
|
|
b67d51b69a | ||
|
|
6434d5ca20 | ||
|
|
946043450e | ||
|
|
b5fa59a5c4 | ||
|
|
a93630576f | ||
|
|
604d467861 | ||
|
|
9bbef50ca1 | ||
|
|
da3dadde07 | ||
|
|
1f3762ff20 | ||
|
|
58192a7052 | ||
|
|
dd2e778fea | ||
|
|
74e4654a26 | ||
|
|
d992dc99d2 | ||
|
|
9ccf19b82b | ||
|
|
cbf69e3013 | ||
|
|
bcf977cfae | ||
|
|
82cc824fb7 | ||
|
|
72bea377ee | ||
|
|
3946e315fc | ||
|
|
cb830594ae | ||
|
|
212366c2eb | ||
|
|
a40b69cee9 | ||
|
|
22afb81879 | ||
|
|
97d7eb260c | ||
|
|
2f5d88ad4e | ||
|
|
4becad7d36 | ||
|
|
3a9beae119 | ||
|
|
1e89cb55f6 | ||
|
|
22be73a1c9 | ||
|
|
c6bdd759e4 | ||
|
|
1f07b5f944 | ||
|
|
06e35e1095 | ||
|
|
c6613dfee0 | ||
|
|
baa86b4ad1 | ||
|
|
f644a80c9a | ||
|
|
826f1cdc42 | ||
|
|
80678e1f6e | ||
|
|
ad56134851 | ||
|
|
559bfebc56 | ||
|
|
7aa7481a56 | ||
|
|
b83a9cf017 | ||
|
|
1554dfb268 | ||
|
|
295b3ccfc8 | ||
|
|
dc2ab22ae0 | ||
|
|
697a8180c7 | ||
|
|
ce923cbff0 | ||
|
|
4e53e02519 | ||
|
|
87e146487b | ||
|
|
61e58fac17 | ||
|
|
06ca3d421f | ||
|
|
f27720683d | ||
|
|
3ea8eb81f6 | ||
|
|
c717f11821 | ||
|
|
a95b187edc | ||
|
|
fc7db34864 | ||
|
|
4adc4e6a15 | ||
|
|
8e2ab935af | ||
|
|
99a0fc275d | ||
|
|
4202e6a7e5 | ||
|
|
673c23188c | ||
|
|
1f8a887c11 | ||
|
|
d8d28503b5 | ||
|
|
562150631c | ||
|
|
d205f7ca72 | ||
|
|
a36e3a3770 | ||
|
|
d5c02b34ae | ||
|
|
226f955dd0 | ||
|
|
ab6a40be20 | ||
|
|
a8dde44d4f | ||
|
|
dab333124e | ||
|
|
bb8945e8ad | ||
|
|
d75be8e1a4 | ||
|
|
c8d5765ea3 | ||
|
|
22b8b9c878 | ||
|
|
5ec85c3e04 | ||
|
|
3c362799b5 | ||
|
|
1ad451cddf | ||
|
|
fbdf5bac82 | ||
|
|
bcbc42632d | ||
|
|
1e112b678a | ||
|
|
cb189bacb1 | ||
|
|
184c95e250 | ||
|
|
9588af2601 | ||
|
|
531721c157 | ||
|
|
a1292005ce | ||
|
|
93d878952c | ||
|
|
1ded249fc7 | ||
|
|
b742a4a25f | ||
|
|
2b2361ed64 | ||
|
|
04779b8557 | ||
|
|
9739dc9e1b | ||
|
|
cc8afa5370 | ||
|
|
cfbed9e4d7 | ||
|
|
1f687fa825 | ||
|
|
8713a6136b | ||
|
|
bed25b429d | ||
|
|
a2bef48c6c | ||
|
|
d7deea668d | ||
|
|
1c8bbf1f10 | ||
|
|
c28a9e0078 | ||
|
|
f37098cb81 | ||
|
|
8610f9c97e | ||
|
|
6b79323d2c | ||
|
|
51d9c07784 | ||
|
|
9fc9929647 | ||
|
|
39cef45c59 | ||
|
|
920b619bcc | ||
|
|
a7103002b6 | ||
|
|
5e76914485 | ||
|
|
0d2431c41a | ||
|
|
3d0eb76337 | ||
|
|
3800f4d332 | ||
|
|
323b7e66df | ||
|
|
9eb56967e4 | ||
|
|
ecd8ce64be | ||
|
|
71287c9a23 | ||
|
|
0837330bd7 | ||
|
|
5439fff871 | ||
|
|
c973a4106f | ||
|
|
dd7269d1ca | ||
|
|
57e647c5b4 | ||
|
|
8d6f5b5cad | ||
|
|
5c78aa332d | ||
|
|
20be5dfc27 | ||
|
|
4fea50943b | ||
|
|
15d3792b0e | ||
|
|
63ddad69e8 | ||
|
|
20541d7184 | ||
|
|
eead78007d | ||
|
|
306386e801 | ||
|
|
6e251a009a | ||
|
|
ae745f1a18 | ||
|
|
5dda94492e | ||
|
|
86d4bbab98 | ||
|
|
9caa140fb6 | ||
|
|
811793d767 | ||
|
|
83362a65c1 | ||
|
|
25e00f75fd | ||
|
|
bcd12c9b96 | ||
|
|
92fa3f785f | ||
|
|
2d0f433450 |
1395 changed files with 101453 additions and 7514 deletions
|
|
@ -1,253 +0,0 @@
|
||||||
# Use the latest 2.1 version of CircleCI pipeline process engine.
|
|
||||||
# See: https://circleci.com/docs/2.0/configuration-reference
|
|
||||||
version: 2.1
|
|
||||||
|
|
||||||
# Define a job to be invoked later in a workflow.
|
|
||||||
# See: https://circleci.com/docs/2.0/configuration-reference/#jobs
|
|
||||||
jobs:
|
|
||||||
api-tests:
|
|
||||||
docker:
|
|
||||||
- image: cimg/python:3.13
|
|
||||||
# `large` (4 vCPU, 8 GB) so pytest-xdist's `-nauto` has room to scale.
|
|
||||||
resource_class: large
|
|
||||||
steps:
|
|
||||||
- checkout
|
|
||||||
- run: sudo apt-get update
|
|
||||||
- run: sudo apt-get install -y ffmpeg catdoc
|
|
||||||
- restore_cache:
|
|
||||||
key: deps-3.13-{{ checksum "requirements.txt" }}-6
|
|
||||||
- run:
|
|
||||||
name: Install Requirements
|
|
||||||
command: |
|
|
||||||
# A restored venv points at the exact interpreter that built it. CircleCI's
|
|
||||||
# cimg/python:3.13 gets patch bumps, and this cache key does not name the
|
|
||||||
# patch, so a venv cached before a bump has a dangling bin/python3 -- and
|
|
||||||
# `python3 -m venv` over it fails with `[Errno 2]` instead of repairing it,
|
|
||||||
# which broke every Python job. Rebuild when it cannot run: that costs a
|
|
||||||
# reinstall only on the first run after a bump.
|
|
||||||
if ! ./venv/bin/python3 --version >/dev/null 2>&1; then rm -rf venv; fi
|
|
||||||
python3 -m venv venv
|
|
||||||
. venv/bin/activate
|
|
||||||
pip install -r requirements.txt
|
|
||||||
- save_cache:
|
|
||||||
key: deps-3.13-{{ checksum "requirements.txt" }}-6
|
|
||||||
paths:
|
|
||||||
- "venv"
|
|
||||||
# `-nauto` parallelizes across all available cores via pytest-xdist.
|
|
||||||
# `-svv` was dumping the full test stdout to CircleCI logs on every run,
|
|
||||||
# which inflated wall time and produced multi-MB log artifacts; dropped.
|
|
||||||
- run:
|
|
||||||
command: './venv/bin/pytest -nauto --junitxml=test-results.xml'
|
|
||||||
- store_test_results:
|
|
||||||
path: test-results.xml
|
|
||||||
# Do the API and the frontend's test fixtures still agree?
|
|
||||||
#
|
|
||||||
# `api-tests` runs these too, as part of the whole suite. This job exists for the
|
|
||||||
# signal: fixture drift is silent by nature -- the frontend suite passes against a body the
|
|
||||||
# API stopped sending -- so it is worth a check whose name says what broke, failing in under a
|
|
||||||
# minute rather than somewhere inside seventeen hundred results.
|
|
||||||
#
|
|
||||||
# It needs no ffmpeg or catdoc (verified), and shares the dependency cache key with the other
|
|
||||||
# Python jobs, so it costs a venv restore and one test file.
|
|
||||||
api-contract-tests:
|
|
||||||
docker:
|
|
||||||
- image: cimg/python:3.13
|
|
||||||
resource_class: medium
|
|
||||||
steps:
|
|
||||||
- checkout
|
|
||||||
- restore_cache:
|
|
||||||
key: deps-3.13-{{ checksum "requirements.txt" }}-6
|
|
||||||
- run:
|
|
||||||
name: Install Requirements
|
|
||||||
command: |
|
|
||||||
# A restored venv points at the exact interpreter that built it. CircleCI's
|
|
||||||
# cimg/python:3.13 gets patch bumps, and this cache key does not name the
|
|
||||||
# patch, so a venv cached before a bump has a dangling bin/python3 -- and
|
|
||||||
# `python3 -m venv` over it fails with `[Errno 2]` instead of repairing it,
|
|
||||||
# which broke every Python job. Rebuild when it cannot run: that costs a
|
|
||||||
# reinstall only on the first run after a bump.
|
|
||||||
if ! ./venv/bin/python3 --version >/dev/null 2>&1; then rm -rf venv; fi
|
|
||||||
python3 -m venv venv
|
|
||||||
. venv/bin/activate
|
|
||||||
pip install -r requirements.txt
|
|
||||||
- run:
|
|
||||||
name: Fixtures match the OpenAPI spec, and the spec matches the handlers
|
|
||||||
command: './venv/bin/pytest wrolpi/test/test_api_fixtures.py -v'
|
|
||||||
|
|
||||||
api-alembic-migrations:
|
|
||||||
docker:
|
|
||||||
- image: cimg/python:3.13
|
|
||||||
resource_class: medium
|
|
||||||
steps:
|
|
||||||
- checkout
|
|
||||||
- restore_cache:
|
|
||||||
key: deps-3.13-{{ checksum "requirements.txt" }}-6
|
|
||||||
- run:
|
|
||||||
name: Install Requirements
|
|
||||||
command: |
|
|
||||||
# A restored venv points at the exact interpreter that built it. CircleCI's
|
|
||||||
# cimg/python:3.13 gets patch bumps, and this cache key does not name the
|
|
||||||
# patch, so a venv cached before a bump has a dangling bin/python3 -- and
|
|
||||||
# `python3 -m venv` over it fails with `[Errno 2]` instead of repairing it,
|
|
||||||
# which broke every Python job. Rebuild when it cannot run: that costs a
|
|
||||||
# reinstall only on the first run after a bump.
|
|
||||||
if ! ./venv/bin/python3 --version >/dev/null 2>&1; then rm -rf venv; fi
|
|
||||||
python3 -m venv venv
|
|
||||||
. venv/bin/activate
|
|
||||||
pip install -r requirements.txt
|
|
||||||
- run:
|
|
||||||
name: Create Media Directory
|
|
||||||
command: mkdir -p /tmp/wrolpi-media/config
|
|
||||||
- run:
|
|
||||||
name: Run Alembic Migrations
|
|
||||||
command: MEDIA_DIRECTORY=/tmp/wrolpi-media ./venv/bin/python ./main.py db upgrade
|
|
||||||
- run:
|
|
||||||
name: Check for Missing Migrations
|
|
||||||
command: MEDIA_DIRECTORY=/tmp/wrolpi-media ./venv/bin/python ./main.py db check
|
|
||||||
sanic-api-start:
|
|
||||||
docker:
|
|
||||||
- image: cimg/python:3.13
|
|
||||||
steps:
|
|
||||||
- checkout
|
|
||||||
- restore_cache:
|
|
||||||
key: deps-3.13-{{ checksum "requirements.txt" }}-6
|
|
||||||
- run:
|
|
||||||
name: Install dependencies
|
|
||||||
command: |
|
|
||||||
# A restored venv points at the exact interpreter that built it. CircleCI's
|
|
||||||
# cimg/python:3.13 gets patch bumps, and this cache key does not name the
|
|
||||||
# patch, so a venv cached before a bump has a dangling bin/python3 -- and
|
|
||||||
# `python3 -m venv` over it fails with `[Errno 2]` instead of repairing it,
|
|
||||||
# which broke every Python job. Rebuild when it cannot run: that costs a
|
|
||||||
# reinstall only on the first run after a bump.
|
|
||||||
if ! ./venv/bin/python3 --version >/dev/null 2>&1; then rm -rf venv; fi
|
|
||||||
python -m venv venv
|
|
||||||
. venv/bin/activate
|
|
||||||
pip install -r requirements.txt
|
|
||||||
sudo mkdir -p /media/wrolpi
|
|
||||||
- run:
|
|
||||||
name: Start Sanic API
|
|
||||||
command: |
|
|
||||||
. venv/bin/activate
|
|
||||||
sanic main:api_app -H 0.0.0.0 -p 8081
|
|
||||||
background: true
|
|
||||||
- run:
|
|
||||||
name: Test Sanic API
|
|
||||||
command: |
|
|
||||||
sleep 20
|
|
||||||
curl http://0.0.0.0:8081/api/echo
|
|
||||||
- run:
|
|
||||||
name: Stop Sanic API
|
|
||||||
command: pkill -f sanic
|
|
||||||
react-app-start:
|
|
||||||
docker:
|
|
||||||
- image: cimg/node:20.19
|
|
||||||
resource_class: large
|
|
||||||
steps:
|
|
||||||
- checkout
|
|
||||||
- restore_cache:
|
|
||||||
key: app-{{ checksum "app/package-lock.json" }}
|
|
||||||
- run: cd app && npm install
|
|
||||||
- save_cache:
|
|
||||||
key: app-{{ checksum "app/package-lock.json" }}
|
|
||||||
paths:
|
|
||||||
- ./app/node_modules
|
|
||||||
- run:
|
|
||||||
name: Build React App
|
|
||||||
command: cd app && DISABLE_ESLINT_PLUGIN=true npm run build
|
|
||||||
- run:
|
|
||||||
name: Start React App
|
|
||||||
command: cd app && DISABLE_ESLINT_PLUGIN=true npm run start
|
|
||||||
background: true
|
|
||||||
- run:
|
|
||||||
name: Test React App
|
|
||||||
command: |
|
|
||||||
sleep 20
|
|
||||||
curl http://0.0.0.0:3000/manifest.json
|
|
||||||
- run:
|
|
||||||
name: Stop React App
|
|
||||||
command: pkill -f npm
|
|
||||||
# Jest tests moved to GitHub Actions (.github/workflows/jest-tests.yml)
|
|
||||||
# Component specs live under `src/`, so they need `cypress run --component`; the e2e job's
|
|
||||||
# `cypress run` will not match them. Cypress starts its own dev server, so no `npm start`.
|
|
||||||
cypress-component-tests:
|
|
||||||
docker:
|
|
||||||
- image: cimg/node:20.19-browsers
|
|
||||||
resource_class: large
|
|
||||||
steps:
|
|
||||||
- checkout
|
|
||||||
- restore_cache:
|
|
||||||
key: app-browsers-{{ checksum "app/package-lock.json" }}
|
|
||||||
- run:
|
|
||||||
name: Install Dependencies
|
|
||||||
command: cd app && npm install
|
|
||||||
- run:
|
|
||||||
name: Install Cypress Binary
|
|
||||||
command: cd app && npx cypress install
|
|
||||||
- run:
|
|
||||||
name: Run Cypress Component Tests
|
|
||||||
command: cd app && CI=true npx cypress run --component
|
|
||||||
- store_artifacts:
|
|
||||||
path: app/cypress/screenshots
|
|
||||||
cypress-e2e-tests:
|
|
||||||
docker:
|
|
||||||
- image: cimg/node:20.19-browsers
|
|
||||||
resource_class: large
|
|
||||||
steps:
|
|
||||||
- checkout
|
|
||||||
- restore_cache:
|
|
||||||
key: app-browsers-{{ checksum "app/package-lock.json" }}
|
|
||||||
- run:
|
|
||||||
name: Install Dependencies
|
|
||||||
command: cd app && npm install
|
|
||||||
# The Cypress binary lives outside node_modules, so caching only
|
|
||||||
# node_modules lets the two drift apart: a restored cache satisfies npm,
|
|
||||||
# npm skips the postinstall download, and the binary for the new version
|
|
||||||
# is never fetched. Cache both, and install explicitly (a no-op when the
|
|
||||||
# binary is already present).
|
|
||||||
- run:
|
|
||||||
name: Install Cypress Binary
|
|
||||||
command: cd app && npx cypress install
|
|
||||||
- save_cache:
|
|
||||||
key: app-browsers-{{ checksum "app/package-lock.json" }}
|
|
||||||
paths:
|
|
||||||
- ./app/node_modules
|
|
||||||
- ~/.cache/Cypress
|
|
||||||
- run:
|
|
||||||
name: Start React App in Background
|
|
||||||
command: cd app && DISABLE_ESLINT_PLUGIN=true npm start
|
|
||||||
background: true
|
|
||||||
- run:
|
|
||||||
name: Wait for React App
|
|
||||||
command: |
|
|
||||||
for i in {1..60}; do
|
|
||||||
if curl -s http://localhost:3000 > /dev/null; then
|
|
||||||
echo "React app is ready!"
|
|
||||||
exit 0
|
|
||||||
fi
|
|
||||||
echo "Waiting for React app... ($i/60)"
|
|
||||||
sleep 2
|
|
||||||
done
|
|
||||||
echo "React app failed to start"
|
|
||||||
exit 1
|
|
||||||
- run:
|
|
||||||
name: Run Cypress Tests
|
|
||||||
command: cd app && CI=true npx cypress run
|
|
||||||
- store_artifacts:
|
|
||||||
path: app/cypress/videos
|
|
||||||
- store_artifacts:
|
|
||||||
path: app/cypress/screenshots
|
|
||||||
|
|
||||||
workflows:
|
|
||||||
wrolpi-api-tests:
|
|
||||||
jobs:
|
|
||||||
- sanic-api-start
|
|
||||||
- api-tests
|
|
||||||
- api-contract-tests
|
|
||||||
- api-alembic-migrations
|
|
||||||
wrolpi-app-test:
|
|
||||||
jobs:
|
|
||||||
- react-app-start
|
|
||||||
# jest-tests moved to GitHub Actions
|
|
||||||
- cypress-e2e-tests
|
|
||||||
- cypress-component-tests
|
|
||||||
41
.github/dependabot.yml
vendored
41
.github/dependabot.yml
vendored
|
|
@ -7,6 +7,11 @@ updates:
|
||||||
interval: "monthly"
|
interval: "monthly"
|
||||||
target-branch: "master"
|
target-branch: "master"
|
||||||
open-pull-requests-limit: 5
|
open-pull-requests-limit: 5
|
||||||
|
ignore:
|
||||||
|
# SQLAlchemy 2.1 is a minor release with its own deprecations; upgrade it
|
||||||
|
# deliberately rather than by an automatic bump.
|
||||||
|
- dependency-name: "SQLAlchemy"
|
||||||
|
versions: [">=2.1"]
|
||||||
groups:
|
groups:
|
||||||
python-dependencies:
|
python-dependencies:
|
||||||
patterns:
|
patterns:
|
||||||
|
|
@ -37,6 +42,42 @@ updates:
|
||||||
interval: "monthly"
|
interval: "monthly"
|
||||||
target-branch: "master"
|
target-branch: "master"
|
||||||
open-pull-requests-limit: 5
|
open-pull-requests-limit: 5
|
||||||
|
ignore:
|
||||||
|
# Major upgrades below need their own migration branch, not a bump PR.
|
||||||
|
# maplibre-gl 6: /map build depends on pinned babel/terser handling.
|
||||||
|
- dependency-name: "maplibre-gl"
|
||||||
|
versions: [">=6"]
|
||||||
|
# react-dropzone 15+ changed the accept API; 20 requires Node >=22.
|
||||||
|
- dependency-name: "react-dropzone"
|
||||||
|
versions: [">=15"]
|
||||||
|
# React 19: @react-three/fiber 8 pins react <19.
|
||||||
|
- dependency-name: "react"
|
||||||
|
update-types: ["version-update:semver-major"]
|
||||||
|
- dependency-name: "react-dom"
|
||||||
|
update-types: ["version-update:semver-major"]
|
||||||
|
- dependency-name: "@types/react"
|
||||||
|
update-types: ["version-update:semver-major"]
|
||||||
|
- dependency-name: "@types/react-dom"
|
||||||
|
update-types: ["version-update:semver-major"]
|
||||||
|
# TypeScript 6+/7 breaks the react-scripts toolchain.
|
||||||
|
- dependency-name: "typescript"
|
||||||
|
versions: [">=6"]
|
||||||
|
# Mantine 9: all @mantine packages move together with app code changes.
|
||||||
|
- dependency-name: "@mantine/*"
|
||||||
|
update-types: ["version-update:semver-major"]
|
||||||
|
# Cypress 16 requires Node >=22; CI and the app image run Node 20.
|
||||||
|
- dependency-name: "cypress"
|
||||||
|
versions: [">=16"]
|
||||||
|
# react-router 8 is a routing migration across ~40 files.
|
||||||
|
- dependency-name: "react-router"
|
||||||
|
update-types: ["version-update:semver-major"]
|
||||||
|
# @testing-library/react 14+ async act semantics break menu/popover tests.
|
||||||
|
- dependency-name: "@testing-library/react"
|
||||||
|
update-types: ["version-update:semver-major"]
|
||||||
|
# Cypress component testing resolves the top-level webpack-dev-server and only
|
||||||
|
# accepts major 5; 6 crashes cypress.config.js ("Unexpected major version").
|
||||||
|
- dependency-name: "webpack-dev-server"
|
||||||
|
versions: [">=6"]
|
||||||
groups:
|
groups:
|
||||||
npm-dependencies:
|
npm-dependencies:
|
||||||
patterns:
|
patterns:
|
||||||
|
|
|
||||||
146
.github/workflows/backend.yml
vendored
Normal file
146
.github/workflows/backend.yml
vendored
Normal file
|
|
@ -0,0 +1,146 @@
|
||||||
|
name: Backend Tests
|
||||||
|
|
||||||
|
# Same triggers as jest-tests.yml: `pull_request` is unfiltered so pull requests into feature
|
||||||
|
# branches are checked too, not only those into master.
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
branches: [master, feature/*]
|
||||||
|
pull_request:
|
||||||
|
|
||||||
|
# A new push to a pull request makes the run for the previous push worthless; cancel it so it
|
||||||
|
# does not hold runners (the free plan allows 20 concurrent jobs). Runs on master always finish.
|
||||||
|
concurrency:
|
||||||
|
group: ${{ github.workflow }}-${{ github.ref }}
|
||||||
|
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
# The suite is split by directory so it finishes in a few minutes, and so a check's name says
|
||||||
|
# which area broke. The groups are balanced by test time; `rest` runs everything the others do
|
||||||
|
# not, so a new directory is tested before anyone assigns it. A path added to any other group
|
||||||
|
# must also be added to `rest` as an --ignore, or its tests run twice.
|
||||||
|
api-tests:
|
||||||
|
name: api-tests (${{ matrix.name }})
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
strategy:
|
||||||
|
fail-fast: false
|
||||||
|
matrix:
|
||||||
|
include:
|
||||||
|
- name: core
|
||||||
|
paths: wrolpi/test
|
||||||
|
- name: media
|
||||||
|
paths: modules/videos modules/zim modules/docs modules/map modules/inventory modules/flasher tiles
|
||||||
|
- name: files
|
||||||
|
paths: wrolpi/files wrolpi/collections
|
||||||
|
- name: rest
|
||||||
|
paths: >-
|
||||||
|
--ignore=wrolpi/test
|
||||||
|
--ignore=modules/videos --ignore=modules/zim --ignore=modules/docs --ignore=modules/map
|
||||||
|
--ignore=modules/inventory --ignore=modules/flasher --ignore=tiles
|
||||||
|
--ignore=wrolpi/files --ignore=wrolpi/collections
|
||||||
|
steps:
|
||||||
|
- name: Checkout repository
|
||||||
|
uses: actions/checkout@v4
|
||||||
|
|
||||||
|
- name: Install system packages
|
||||||
|
# Mesa's EGL and GL drivers: the map tile service (tiles/) draws with them.
|
||||||
|
run: sudo apt-get update && sudo apt-get install -y ffmpeg catdoc libegl1 libegl-mesa0 libgl1-mesa-dri libgles2
|
||||||
|
|
||||||
|
- name: Setup Python
|
||||||
|
uses: actions/setup-python@v5
|
||||||
|
with:
|
||||||
|
# Trixie ships 3.13.
|
||||||
|
python-version: '3.13'
|
||||||
|
cache: 'pip'
|
||||||
|
cache-dependency-path: requirements.lock
|
||||||
|
|
||||||
|
- name: Install dependencies
|
||||||
|
run: scripts/install_python_requirements.sh pip requirements.txt
|
||||||
|
|
||||||
|
# `logical`, not `auto`: with psutil installed, `auto` counts physical cores, which is two on
|
||||||
|
# the four-vCPU runner. No `-v`: the full test output inflates wall time and logs.
|
||||||
|
- name: Run pytest
|
||||||
|
env:
|
||||||
|
PATHS: ${{ matrix.paths }}
|
||||||
|
run: pytest -n logical $PATHS --junitxml=test-results.xml
|
||||||
|
|
||||||
|
- name: Upload test results
|
||||||
|
if: ${{ !cancelled() }}
|
||||||
|
uses: actions/upload-artifact@v4
|
||||||
|
with:
|
||||||
|
name: api-test-results-${{ matrix.name }}
|
||||||
|
path: test-results.xml
|
||||||
|
retention-days: 30
|
||||||
|
|
||||||
|
# Do the API and the frontend's test fixtures still agree?
|
||||||
|
#
|
||||||
|
# `api-tests` runs these too, as part of the whole suite. This job exists for the signal:
|
||||||
|
# fixture drift is silent by nature -- the frontend suite passes against a body the API stopped
|
||||||
|
# sending -- so it is worth a check whose name says what broke, failing in under a minute rather
|
||||||
|
# than somewhere inside seventeen hundred results. It needs no ffmpeg or catdoc.
|
||||||
|
api-contract-tests:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- name: Checkout repository
|
||||||
|
uses: actions/checkout@v4
|
||||||
|
|
||||||
|
- name: Setup Python
|
||||||
|
uses: actions/setup-python@v5
|
||||||
|
with:
|
||||||
|
python-version: '3.13'
|
||||||
|
cache: 'pip'
|
||||||
|
cache-dependency-path: requirements.lock
|
||||||
|
|
||||||
|
- name: Install dependencies
|
||||||
|
run: scripts/install_python_requirements.sh pip requirements.txt
|
||||||
|
|
||||||
|
- name: Fixtures match the OpenAPI spec, and the spec matches the handlers
|
||||||
|
run: pytest wrolpi/test/test_api_fixtures.py -v
|
||||||
|
|
||||||
|
# The migrations apply to an empty database, the models match them, and the API starts.
|
||||||
|
api-migrations-and-start:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- name: Checkout repository
|
||||||
|
uses: actions/checkout@v4
|
||||||
|
|
||||||
|
- name: Setup Python
|
||||||
|
uses: actions/setup-python@v5
|
||||||
|
with:
|
||||||
|
python-version: '3.13'
|
||||||
|
cache: 'pip'
|
||||||
|
cache-dependency-path: requirements.lock
|
||||||
|
|
||||||
|
- name: Install dependencies
|
||||||
|
run: scripts/install_python_requirements.sh pip requirements.txt
|
||||||
|
|
||||||
|
- name: Run Alembic migrations
|
||||||
|
env:
|
||||||
|
MEDIA_DIRECTORY: ${{ runner.temp }}/wrolpi-media
|
||||||
|
run: |
|
||||||
|
mkdir -p "$MEDIA_DIRECTORY/config"
|
||||||
|
python ./main.py db upgrade
|
||||||
|
|
||||||
|
- name: Check for missing migrations
|
||||||
|
env:
|
||||||
|
MEDIA_DIRECTORY: ${{ runner.temp }}/wrolpi-media
|
||||||
|
run: python ./main.py db check
|
||||||
|
|
||||||
|
- name: Start Sanic API
|
||||||
|
run: |
|
||||||
|
sudo mkdir -p /media/wrolpi
|
||||||
|
nohup sanic main:api_app -H 0.0.0.0 -p 8081 > sanic.log 2>&1 &
|
||||||
|
for i in $(seq 1 60); do
|
||||||
|
if curl -sf http://localhost:8081/api/echo; then
|
||||||
|
echo
|
||||||
|
echo "Sanic API is up"
|
||||||
|
exit 0
|
||||||
|
fi
|
||||||
|
sleep 2
|
||||||
|
done
|
||||||
|
echo "Sanic API failed to start"
|
||||||
|
cat sanic.log
|
||||||
|
exit 1
|
||||||
|
|
||||||
|
- name: Stop Sanic API
|
||||||
|
if: ${{ always() }}
|
||||||
|
run: pkill -f sanic || true
|
||||||
4
.github/workflows/controller-tests.yml
vendored
4
.github/workflows/controller-tests.yml
vendored
|
|
@ -27,10 +27,10 @@ jobs:
|
||||||
# Trixie ships 3.13, and docker/controller/Dockerfile is python:3.13-slim-trixie.
|
# Trixie ships 3.13, and docker/controller/Dockerfile is python:3.13-slim-trixie.
|
||||||
python-version: '3.13'
|
python-version: '3.13'
|
||||||
cache: 'pip'
|
cache: 'pip'
|
||||||
cache-dependency-path: controller/requirements.txt
|
cache-dependency-path: controller/requirements.lock
|
||||||
|
|
||||||
- name: Install dependencies
|
- name: Install dependencies
|
||||||
run: pip install -r requirements.txt
|
run: ../scripts/install_python_requirements.sh pip requirements.txt
|
||||||
|
|
||||||
- name: Run pytest
|
- name: Run pytest
|
||||||
run: python -m pytest test/ -v --tb=short --confcutdir=$(pwd)
|
run: python -m pytest test/ -v --tb=short --confcutdir=$(pwd)
|
||||||
|
|
|
||||||
121
.github/workflows/cypress.yml
vendored
Normal file
121
.github/workflows/cypress.yml
vendored
Normal file
|
|
@ -0,0 +1,121 @@
|
||||||
|
name: Cypress Tests
|
||||||
|
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
branches: [master, feature/*]
|
||||||
|
pull_request:
|
||||||
|
|
||||||
|
concurrency:
|
||||||
|
group: ${{ github.workflow }}-${{ github.ref }}
|
||||||
|
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
# Component specs live under `src/`, so they need `cypress run --component`; the e2e job's
|
||||||
|
# `cypress run` will not match them. Cypress starts its own dev server, so no `npm start`.
|
||||||
|
cypress-component-tests:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
|
||||||
|
defaults:
|
||||||
|
run:
|
||||||
|
working-directory: app
|
||||||
|
|
||||||
|
steps:
|
||||||
|
- name: Checkout repository
|
||||||
|
uses: actions/checkout@v4
|
||||||
|
|
||||||
|
- name: Setup Node.js
|
||||||
|
uses: actions/setup-node@v4
|
||||||
|
with:
|
||||||
|
node-version: '20.19'
|
||||||
|
cache: 'npm'
|
||||||
|
cache-dependency-path: app/package-lock.json
|
||||||
|
|
||||||
|
# The Cypress binary lives outside node_modules, and setup-node only caches ~/.npm. Key it
|
||||||
|
# on the lockfile so a Cypress bump fetches the matching binary.
|
||||||
|
- name: Cache Cypress binary
|
||||||
|
uses: actions/cache@v4
|
||||||
|
with:
|
||||||
|
path: ~/.cache/Cypress
|
||||||
|
key: cypress-${{ runner.os }}-${{ hashFiles('app/package-lock.json') }}
|
||||||
|
|
||||||
|
- name: Install dependencies
|
||||||
|
run: npm install
|
||||||
|
|
||||||
|
# A no-op when the cached binary matches.
|
||||||
|
- name: Install Cypress binary
|
||||||
|
run: npx cypress install
|
||||||
|
|
||||||
|
- name: Run Cypress component tests
|
||||||
|
run: npx cypress run --component
|
||||||
|
|
||||||
|
- name: Upload screenshots
|
||||||
|
if: ${{ failure() }}
|
||||||
|
uses: actions/upload-artifact@v4
|
||||||
|
with:
|
||||||
|
name: cypress-component-screenshots
|
||||||
|
path: app/cypress/screenshots
|
||||||
|
retention-days: 14
|
||||||
|
|
||||||
|
# Waiting for `npm start` to serve the app also checks that the dev server starts.
|
||||||
|
cypress-e2e-tests:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
|
||||||
|
defaults:
|
||||||
|
run:
|
||||||
|
working-directory: app
|
||||||
|
|
||||||
|
steps:
|
||||||
|
- name: Checkout repository
|
||||||
|
uses: actions/checkout@v4
|
||||||
|
|
||||||
|
- name: Setup Node.js
|
||||||
|
uses: actions/setup-node@v4
|
||||||
|
with:
|
||||||
|
node-version: '20.19'
|
||||||
|
cache: 'npm'
|
||||||
|
cache-dependency-path: app/package-lock.json
|
||||||
|
|
||||||
|
- name: Cache Cypress binary
|
||||||
|
uses: actions/cache@v4
|
||||||
|
with:
|
||||||
|
path: ~/.cache/Cypress
|
||||||
|
key: cypress-${{ runner.os }}-${{ hashFiles('app/package-lock.json') }}
|
||||||
|
|
||||||
|
- name: Install dependencies
|
||||||
|
run: npm install
|
||||||
|
|
||||||
|
- name: Install Cypress binary
|
||||||
|
run: npx cypress install
|
||||||
|
|
||||||
|
# GitHub Actions sets `CI=true`, which makes cypress.config.js use http://localhost:3000 as
|
||||||
|
# the base URL.
|
||||||
|
- name: Start React app
|
||||||
|
env:
|
||||||
|
DISABLE_ESLINT_PLUGIN: 'true'
|
||||||
|
BROWSER: none
|
||||||
|
run: |
|
||||||
|
nohup npm start > react.log 2>&1 &
|
||||||
|
for i in $(seq 1 90); do
|
||||||
|
if curl -sf http://localhost:3000/manifest.json > /dev/null; then
|
||||||
|
echo "React app is ready"
|
||||||
|
exit 0
|
||||||
|
fi
|
||||||
|
sleep 2
|
||||||
|
done
|
||||||
|
echo "React app failed to start"
|
||||||
|
cat react.log
|
||||||
|
exit 1
|
||||||
|
|
||||||
|
- name: Run Cypress e2e tests
|
||||||
|
run: npx cypress run
|
||||||
|
|
||||||
|
- name: Upload videos and screenshots
|
||||||
|
if: ${{ failure() }}
|
||||||
|
uses: actions/upload-artifact@v4
|
||||||
|
with:
|
||||||
|
name: cypress-e2e-media
|
||||||
|
path: |
|
||||||
|
app/cypress/videos
|
||||||
|
app/cypress/screenshots
|
||||||
|
retention-days: 14
|
||||||
|
if-no-files-found: ignore
|
||||||
34
.github/workflows/dead-code.yml
vendored
Normal file
34
.github/workflows/dead-code.yml
vendored
Normal file
|
|
@ -0,0 +1,34 @@
|
||||||
|
name: Dead Code
|
||||||
|
|
||||||
|
# Same triggers as backend.yml: `pull_request` is unfiltered so pull requests into feature branches
|
||||||
|
# are checked too, not only those into master.
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
branches: [master, feature/*]
|
||||||
|
pull_request:
|
||||||
|
|
||||||
|
concurrency:
|
||||||
|
group: ${{ github.workflow }}-${{ github.ref }}
|
||||||
|
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
# Fails when vulture finds dead code that is not in scripts/vulture_baseline.txt. vulture only
|
||||||
|
# parses the source, so WROLPi's requirements are not installed.
|
||||||
|
vulture:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- name: Checkout repository
|
||||||
|
uses: actions/checkout@v4
|
||||||
|
|
||||||
|
- name: Setup Python
|
||||||
|
uses: actions/setup-python@v5
|
||||||
|
with:
|
||||||
|
# Trixie ships 3.13.
|
||||||
|
python-version: '3.13'
|
||||||
|
|
||||||
|
# Pinned: a new vulture release can report findings the baseline does not know about.
|
||||||
|
- name: Install vulture
|
||||||
|
run: pip install vulture==2.16
|
||||||
|
|
||||||
|
- name: Check for new dead code
|
||||||
|
run: python scripts/check_dead_code.py
|
||||||
4
.gitignore
vendored
4
.gitignore
vendored
|
|
@ -118,6 +118,7 @@ test/config
|
||||||
|
|
||||||
modules/node_modules/
|
modules/node_modules/
|
||||||
docker/archive/node_modules/
|
docker/archive/node_modules/
|
||||||
|
npm-tools/node_modules/
|
||||||
docker/archive/package-lock.json
|
docker/archive/package-lock.json
|
||||||
|
|
||||||
# open street map files
|
# open street map files
|
||||||
|
|
@ -150,3 +151,6 @@ app/cypress/videos
|
||||||
release/latest.json
|
release/latest.json
|
||||||
perf_results/
|
perf_results/
|
||||||
scripts/api_perf_hosts.json
|
scripts/api_perf_hosts.json
|
||||||
|
|
||||||
|
# Tile cache for scripts/build_solar_climatology.py
|
||||||
|
/scripts/.solar_climatology_cache/
|
||||||
|
|
|
||||||
65
INSTALL.md
65
INSTALL.md
|
|
@ -3,8 +3,10 @@
|
||||||
There are several ways to run WROLPi. Pick the one that matches your hardware:
|
There are several ways to run WROLPi. Pick the one that matches your hardware:
|
||||||
|
|
||||||
* [WROLPi Portable (Live USB)](#wrolpi-portable-live-usb) — boot a full WROLPi from a USB stick on any x86 PC or laptop, no installation required.
|
* [WROLPi Portable (Live USB)](#wrolpi-portable-live-usb) — boot a full WROLPi from a USB stick on any x86 PC or laptop, no installation required.
|
||||||
* [Debian 12 Install](#debian-12-install) — install WROLPi onto an x86 PC or laptop.
|
* [Debian 13 Install](#debian-13-install) — install WROLPi onto an x86 PC or laptop.
|
||||||
* [Raspberry Pi Install](#raspberry-pi-install) — install WROLPi onto a Raspberry Pi with an external drive.
|
* [Raspberry Pi Install](#raspberry-pi-install) — install WROLPi onto a Raspberry Pi with an external drive.
|
||||||
|
|
||||||
|
After installing, follow [First Boot](#first-boot) to set up your drive.
|
||||||
* [Docker](docker/README.md) — run the WROLPi containers on an existing Linux host (best for trying it out or development).
|
* [Docker](docker/README.md) — run the WROLPi containers on an existing Linux host (best for trying it out or development).
|
||||||
|
|
||||||
See [UPGRADE.md](UPGRADE.md) for upgrading an existing WROLPi.
|
See [UPGRADE.md](UPGRADE.md) for upgrading an existing WROLPi.
|
||||||
|
|
@ -36,6 +38,7 @@ Steps:
|
||||||
minute or two; progress is shown on screen.
|
minute or two; progress is shown on screen.
|
||||||
5. Once the desktop loads, browse to https://wrolpi.local or the IP address of
|
5. Once the desktop loads, browse to https://wrolpi.local or the IP address of
|
||||||
your WROLPi. Wi-Fi hotspot and all other features work as usual.
|
your WROLPi. Wi-Fi hotspot and all other features work as usual.
|
||||||
|
6. To use a terminal remotely: `ssh user@wrolpi.local`, password `live`.
|
||||||
|
|
||||||
Notes:
|
Notes:
|
||||||
|
|
||||||
|
|
@ -52,30 +55,50 @@ Notes:
|
||||||
* **Upgrading.** See [Upgrading a WROLPi Portable USB](UPGRADE.md#upgrading-a-wrolpi-portable-usb)
|
* **Upgrading.** See [Upgrading a WROLPi Portable USB](UPGRADE.md#upgrading-a-wrolpi-portable-usb)
|
||||||
to move to a newer ISO without losing your library.
|
to move to a newer ISO without losing your library.
|
||||||
|
|
||||||
## Debian 12 Install
|
## Debian 13 Install
|
||||||
|
|
||||||
Steps necessary to initialize your WROLPi after installing the Debian image from wrolpi.org
|
Install WROLPi onto the internal disk of an x86 PC or laptop. This uses the same
|
||||||
|
`WROLPi-v*-amd64.iso` as WROLPi Portable.
|
||||||
|
|
||||||
1. Download and copy a pre-built Debian image from https://wrolpi.org onto a USB thumb-drive (USB 2 recommended).
|
1. Download the latest `WROLPi-v*-amd64.iso` from [wrolpi.org](https://wrolpi.org) and flash it to a USB drive
|
||||||
2. Insert the thumb-drive into the laptop, boot to the thumb-drive.
|
(see [WROLPi Portable](#wrolpi-portable-live-usb) step 2).
|
||||||
1. Select "Start Installer".
|
2. Boot the PC from the USB drive. At the boot menu, choose **Install** or **Graphical Install**.
|
||||||
2. Install Debian 12 as you would like.
|
3. Install Debian 13 as you would like.
|
||||||
1. It is recommended to use the hostname **wrolpi**.
|
1. It is recommended to use the hostname **wrolpi**.
|
||||||
2. (WROLPi will be installed during the installation without your intervention.)
|
2. WROLPi is installed along with Debian; there is nothing extra to select.
|
||||||
3. Unplug the thumb-drive after the installation has completed.
|
4. Unplug the USB drive after the installation has completed, and reboot.
|
||||||
4. Login as the user _you_ created during installation.
|
5. Continue with [First Boot](#first-boot).
|
||||||
5. Initialize the WROLPi databases using the repair script: `/opt/wrolpi/repair.sh`
|
|
||||||
6. Reboot: `reboot`
|
|
||||||
7. Browse to https://wrolpi.local or the IP address of your WROLPi!
|
|
||||||
|
|
||||||
## Raspberry Pi Install
|
## Raspberry Pi Install
|
||||||
|
|
||||||
Steps necessary to initialize your WROLPi after installing the Raspberry Pi image from wrolpi.org
|
Install WROLPi onto a Raspberry Pi. An external drive is recommended for your library.
|
||||||
|
|
||||||
1. Download and copy a pre-built image from https://wrolpi.org onto an SD card.
|
1. Download the latest `WROLPi-v*-aarch64-desktop.img.xz` from [wrolpi.org](https://wrolpi.org).
|
||||||
2. Boot the Raspberry Pi, login with username pi and password wrolpi.
|
2. Flash it to an SD card using Raspberry Pi Imager.
|
||||||
3. Modify fstab to mount your external drive to /media/wrolpi (modify this command to match your system).
|
3. Plug in your external drive, insert the SD card, and boot the Raspberry Pi.
|
||||||
* `echo '/dev/sda1 /media/wrolpi auto defaults,nofail 0 0' | sudo tee -a /etc/fstab`
|
4. On the first boot, Raspberry Pi OS asks you to create your own user.
|
||||||
4. Initialize the WROLPi databases using the repair script: `sudo /opt/wrolpi/repair.sh`
|
5. Continue with [First Boot](#first-boot).
|
||||||
5. Reboot `sudo reboot`
|
|
||||||
6. Join the Hotspot or browse to https://wrolpi.local or the IP address of your WROLPi!
|
## First Boot
|
||||||
|
|
||||||
|
These steps are the same for every install.
|
||||||
|
|
||||||
|
1. Join the WROLPi hotspot (network **WROLPi**, password **wrolpi hotspot**; it starts on every boot), or connect
|
||||||
|
your WROLPi to your network, then browse to https://wrolpi.local (or the IP address of your WROLPi).
|
||||||
|
2. **Choose your drive.**
|
||||||
|
* **Raspberry Pi and Debian:** until a drive is set up, you will see the **Controller** with a *Welcome to WROLPi*
|
||||||
|
wizard (also at http://wrolpi.local). Select the drive which will hold your library; WROLPi mounts it
|
||||||
|
at `/media/wrolpi`, adds it to `/etc/fstab`, and runs the repair script for you. If the drive already holds a
|
||||||
|
WROLPi library (from another WROLPi, or a backup), its configuration is used. No external drive? Choose **Run
|
||||||
|
repair without external drive** to keep your library on the internal disk or SD card.
|
||||||
|
* **WROLPi Portable:** nothing to do; your library lives in the persistence partition on the USB drive.
|
||||||
|
3. **Trust the certificate.** Your browser will warn about the HTTPS certificate because it was made by your WROLPi,
|
||||||
|
not by a public authority. Download https://wrolpi.local/ca.crt and trust it on each device you use; see
|
||||||
|
*Help > Certificates* on your WROLPi for per-device instructions.
|
||||||
|
4. **Wait for the first refresh.** WROLPi refreshes all your files when it first starts so it can find anything already
|
||||||
|
on the drive. Your library looks empty, and Download and Upload are disabled, until the refresh completes.
|
||||||
|
5. Start adding content: download a video channel, archive a web page, or add a Zim (Wikipedia) file. The *Help* page
|
||||||
|
on your WROLPi explains each module.
|
||||||
|
|
||||||
|
You do not need to edit `/etc/fstab` or run `repair.sh` by hand. `sudo /opt/wrolpi/repair.sh` is still available if
|
||||||
|
your WROLPi ever needs repairing.
|
||||||
|
|
|
||||||
|
|
@ -1,6 +1,6 @@
|
||||||
# WROLPi
|
# WROLPi
|
||||||
|
|
||||||
[](https://app.circleci.com/pipelines/github/lrnselfreliance/wrolpi?branch=release&filter=all)
|
[](https://github.com/lrnselfreliance/wrolpi/actions/workflows/backend.yml?query=branch%3Amaster)
|
||||||
[](https://github.com/lrnselfreliance/wrolpi/blob/master/LICENSE)
|
[](https://github.com/lrnselfreliance/wrolpi/blob/master/LICENSE)
|
||||||
[](https://discord.gg/HrwFk7nqA2)
|
[](https://discord.gg/HrwFk7nqA2)
|
||||||
[](https://gitpod.io/#https://github.com/lrnselfreliance/wrolpi)
|
[](https://gitpod.io/#https://github.com/lrnselfreliance/wrolpi)
|
||||||
|
|
@ -40,8 +40,8 @@ network so that any user with a laptop/tablet/phone can connect and use the libr
|
||||||
- [x] Universal search
|
- [x] Universal search
|
||||||
- [x] Food Inventory management
|
- [x] Food Inventory management
|
||||||
- [x] One-Time pad generator, encrypter/decrypter
|
- [x] One-Time pad generator, encrypter/decrypter
|
||||||
- [ ] Synchronizer/duplicator
|
- [x] Sync to a second WROLPi, and backup to a second drive
|
||||||
- [ ] Food storage calculator
|
- [x] Food storage calculator
|
||||||
|
|
||||||
## Module features matrix
|
## Module features matrix
|
||||||
|
|
||||||
|
|
@ -93,7 +93,7 @@ More Docker documentation is available in [docker/README.md](docker/README.md)
|
||||||
Full installation instructions are in [INSTALL.md](INSTALL.md). Pick the option that matches your hardware:
|
Full installation instructions are in [INSTALL.md](INSTALL.md). Pick the option that matches your hardware:
|
||||||
|
|
||||||
* **[WROLPi Portable (Live USB)](INSTALL.md#wrolpi-portable-live-usb)** — boot a complete WROLPi from a USB stick on any x86 PC or laptop. Nothing is installed to the computer; the first boot creates a persistence partition on the USB so your library, database, and configuration survive reboots.
|
* **[WROLPi Portable (Live USB)](INSTALL.md#wrolpi-portable-live-usb)** — boot a complete WROLPi from a USB stick on any x86 PC or laptop. Nothing is installed to the computer; the first boot creates a persistence partition on the USB so your library, database, and configuration survive reboots.
|
||||||
* **[Debian 12](INSTALL.md#debian-12-install)** — install WROLPi onto an x86 PC or laptop.
|
* **[Debian 13](INSTALL.md#debian-13-install)** — install WROLPi onto an x86 PC or laptop.
|
||||||
* **[Raspberry Pi](INSTALL.md#raspberry-pi-install)** — install WROLPi onto a Raspberry Pi with an external drive.
|
* **[Raspberry Pi](INSTALL.md#raspberry-pi-install)** — install WROLPi onto a Raspberry Pi with an external drive.
|
||||||
* **[Docker](docker/README.md)** — run the WROLPi containers on an existing Linux host.
|
* **[Docker](docker/README.md)** — run the WROLPi containers on an existing Linux host.
|
||||||
|
|
||||||
|
|
|
||||||
10
UPGRADE.md
10
UPGRADE.md
|
|
@ -3,7 +3,7 @@
|
||||||
# Table of Contents
|
# Table of Contents
|
||||||
|
|
||||||
* [Upgrading Docker containers](#upgrading-docker-containers)
|
* [Upgrading Docker containers](#upgrading-docker-containers)
|
||||||
* [Upgrading Raspberry Pi or Debian 12 Installation](#upgrading-raspberry-pi-or-debian-12-installation)
|
* [Upgrading Raspberry Pi or Debian Installation](#upgrading-raspberry-pi-or-debian-installation)
|
||||||
* [Upgrading a WROLPi Portable USB](#upgrading-a-wrolpi-portable-usb)
|
* [Upgrading a WROLPi Portable USB](#upgrading-a-wrolpi-portable-usb)
|
||||||
|
|
||||||
## Upgrading Docker containers
|
## Upgrading Docker containers
|
||||||
|
|
@ -14,6 +14,8 @@
|
||||||
* `git pull origin master --ff`
|
* `git pull origin master --ff`
|
||||||
3. Build all docker containers
|
3. Build all docker containers
|
||||||
* `docker-compose build --parallel`
|
* `docker-compose build --parallel`
|
||||||
|
* Rebuild the VPN container without its cache, so it gets the latest qBittorrent (it faces the Internet
|
||||||
|
through the VPN): `docker compose build --pull --no-cache vpn`
|
||||||
4. Create the map volumes
|
4. Create the map volumes
|
||||||
* `docker volume create --name=openstreetmap-data`
|
* `docker volume create --name=openstreetmap-data`
|
||||||
* `docker volume create --name=openstreetmap-rendered-tiles`
|
* `docker volume create --name=openstreetmap-rendered-tiles`
|
||||||
|
|
@ -24,11 +26,15 @@
|
||||||
7. Start all docker containers
|
7. Start all docker containers
|
||||||
* `docker-compose up -d`
|
* `docker-compose up -d`
|
||||||
|
|
||||||
## Upgrading Raspberry Pi or Debian 12 Installation
|
## Upgrading Raspberry Pi or Debian Installation
|
||||||
|
|
||||||
|
A Debian 12 (bookworm) WROLPi stays on the final version for Debian 12; reinstall on Debian 13 to get newer versions.
|
||||||
|
|
||||||
1. Run the upgrade script
|
1. Run the upgrade script
|
||||||
* `sudo /bin/bash /opt/wrolpi/upgrade.sh`
|
* `sudo /bin/bash /opt/wrolpi/upgrade.sh`
|
||||||
* (If the upgrade script does not exist, run the installation script: `sudo /bin/bash /opt/wrolpi/install.sh`)
|
* (If the upgrade script does not exist, run the installation script: `sudo /bin/bash /opt/wrolpi/install.sh`)
|
||||||
|
* The upgrade refuses to move back to an older commit of the branch you are on. To downgrade on purpose,
|
||||||
|
run `sudo /bin/bash /opt/wrolpi/upgrade.sh -d`.
|
||||||
|
|
||||||
## Upgrading a WROLPi Portable USB
|
## Upgrading a WROLPi Portable USB
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -6,8 +6,9 @@ from alembic import context
|
||||||
# access to the values within the .ini file in use.
|
# access to the values within the .ini file in use.
|
||||||
config = context.config
|
config = context.config
|
||||||
|
|
||||||
# Interpret the config file for Python logging.
|
# Configure logging only for the alembic command line. WROLPi also migrates in-process at startup
|
||||||
# This line sets up loggers basically.
|
# (db_bootstrap), where fileConfig would replace the API's handlers and disable its existing loggers.
|
||||||
|
if config.cmd_opts is not None:
|
||||||
fileConfig(config.config_file_name)
|
fileConfig(config.config_file_name)
|
||||||
|
|
||||||
# add your model's MetaData object here
|
# add your model's MetaData object here
|
||||||
|
|
@ -23,6 +24,7 @@ from wrolpi.collections.models import Collection, CollectionItem # noqa: F401
|
||||||
from modules.videos.models import Video, Channel # noqa: F401
|
from modules.videos.models import Video, Channel # noqa: F401
|
||||||
from modules.archive.models import Archive # noqa: F401
|
from modules.archive.models import Archive # noqa: F401
|
||||||
from modules.zim.models import Zim, TagZimEntry, ZimSubscription # noqa: F401
|
from modules.zim.models import Zim, TagZimEntry, ZimSubscription # noqa: F401
|
||||||
|
from modules.repos.models import Repository # noqa: F401
|
||||||
|
|
||||||
target_metadata = Base.metadata
|
target_metadata = Base.metadata
|
||||||
|
|
||||||
|
|
@ -96,7 +98,10 @@ def run_migrations_online():
|
||||||
|
|
||||||
connectable = create_wrolpi_engine(get_url())
|
connectable = create_wrolpi_engine(get_url())
|
||||||
|
|
||||||
with connectable.connect() as connection:
|
# Autocommit: each migration statement is its own transaction. A migration may call WROLPi
|
||||||
|
# functions which write on their own connection; a migration connection holding an open read
|
||||||
|
# transaction could not then upgrade to a writer ("database is locked").
|
||||||
|
with connectable.connect().execution_options(isolation_level='AUTOCOMMIT') as connection:
|
||||||
context.configure(
|
context.configure(
|
||||||
connection=connection,
|
connection=connection,
|
||||||
target_metadata=target_metadata,
|
target_metadata=target_metadata,
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,45 @@
|
||||||
|
"""Maintain collection.item_count/total_size for Domain Collections with triggers.
|
||||||
|
|
||||||
|
Listing Domain Collections summed file_group.size through an archive join on every request,
|
||||||
|
one random page read per archive. The new triggers keep the summary columns current
|
||||||
|
(as the channel triggers already do for Channels); this migration installs them and
|
||||||
|
backfills existing Domain Collections.
|
||||||
|
|
||||||
|
Revision ID: 2026_09_27_1200
|
||||||
|
Revises: 2026_09_20_1200
|
||||||
|
"""
|
||||||
|
from alembic import op
|
||||||
|
|
||||||
|
# revision identifiers, used by Alembic.
|
||||||
|
revision = '2026_09_27_1200'
|
||||||
|
down_revision = '2026_09_20_1200'
|
||||||
|
branch_labels = None
|
||||||
|
depends_on = None
|
||||||
|
|
||||||
|
TRIGGERS = (
|
||||||
|
'archive_insert_collection_summary',
|
||||||
|
'archive_delete_collection_summary',
|
||||||
|
'archive_update_collection_summary',
|
||||||
|
'file_group_size_collection_summary',
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade():
|
||||||
|
from wrolpi.schema_ddl import install_raw_ddl
|
||||||
|
|
||||||
|
# Idempotent: only the new triggers are created.
|
||||||
|
install_raw_ddl(op.get_bind())
|
||||||
|
|
||||||
|
op.execute('''
|
||||||
|
UPDATE collection SET
|
||||||
|
item_count = (SELECT COUNT(*) FROM archive WHERE collection_id = collection.id),
|
||||||
|
total_size = (SELECT COALESCE(SUM(fg.size), 0) FROM archive a
|
||||||
|
LEFT JOIN file_group fg ON a.file_group_id = fg.id
|
||||||
|
WHERE a.collection_id = collection.id)
|
||||||
|
WHERE kind = 'domain'
|
||||||
|
''')
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade():
|
||||||
|
for name in TRIGGERS:
|
||||||
|
op.execute(f'DROP TRIGGER IF EXISTS {name}')
|
||||||
|
|
@ -0,0 +1,29 @@
|
||||||
|
"""Covering indexes for the Collection listing.
|
||||||
|
|
||||||
|
Listing Collections read every channel row (for video_count/total_size) and every download
|
||||||
|
row of those Collections (for the minimum frequency). Both tables store yt-dlp info_json,
|
||||||
|
so their rows are tens of KB and each sits on its own scattered page; from a cold disk cache
|
||||||
|
that was 10+ seconds. These indexes answer both queries without touching a row.
|
||||||
|
|
||||||
|
Revision ID: 2026_09_28_1200
|
||||||
|
Revises: 2026_09_27_1200
|
||||||
|
"""
|
||||||
|
from alembic import op
|
||||||
|
|
||||||
|
# revision identifiers, used by Alembic.
|
||||||
|
revision = '2026_09_28_1200'
|
||||||
|
down_revision = '2026_09_27_1200'
|
||||||
|
branch_labels = None
|
||||||
|
depends_on = None
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade():
|
||||||
|
op.execute('CREATE INDEX IF NOT EXISTS channel_collection_summary_idx'
|
||||||
|
' ON channel (collection_id, video_count, total_size)')
|
||||||
|
op.execute('CREATE INDEX IF NOT EXISTS download_collection_frequency_idx'
|
||||||
|
' ON download (collection_id, frequency)')
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade():
|
||||||
|
op.execute('DROP INDEX IF EXISTS channel_collection_summary_idx')
|
||||||
|
op.execute('DROP INDEX IF EXISTS download_collection_frequency_idx')
|
||||||
31
alembic/versions/2026_10_05_1200_markdown_mimetype.py
Normal file
31
alembic/versions/2026_10_05_1200_markdown_mimetype.py
Normal file
|
|
@ -0,0 +1,31 @@
|
||||||
|
"""Retag existing markdown file groups as text/markdown.
|
||||||
|
|
||||||
|
A refresh skips a group whose files have not changed, so markdown indexed before text/markdown
|
||||||
|
existed would keep the type libmagic gave it (text/plain, or a programming language when the file
|
||||||
|
holds code) and the indexer that type chose. Marking the rows unindexed lets apply_indexers
|
||||||
|
re-index them with TextIndexer. SQLite's LIKE is case-insensitive for ASCII, so `.MD` matches.
|
||||||
|
|
||||||
|
Revision ID: 2026_10_05_1200
|
||||||
|
Revises: 2026_09_28_1200
|
||||||
|
"""
|
||||||
|
from alembic import op
|
||||||
|
|
||||||
|
# revision identifiers, used by Alembic.
|
||||||
|
revision = '2026_10_05_1200'
|
||||||
|
down_revision = '2026_09_28_1200'
|
||||||
|
branch_labels = None
|
||||||
|
depends_on = None
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade():
|
||||||
|
op.execute("""
|
||||||
|
UPDATE file_group SET mimetype = 'text/markdown', "indexed" = 0
|
||||||
|
WHERE (primary_path LIKE '%.md' OR primary_path LIKE '%.markdown')
|
||||||
|
AND mimetype LIKE 'text/%'
|
||||||
|
AND mimetype != 'text/markdown'
|
||||||
|
""")
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade():
|
||||||
|
# The original types are not recorded; text/plain is what libmagic reports for most markdown.
|
||||||
|
op.execute("""UPDATE file_group SET mimetype = 'text/plain', "indexed" = 0 WHERE mimetype = 'text/markdown'""")
|
||||||
43
alembic/versions/2026_10_06_1200_repository.py
Normal file
43
alembic/versions/2026_10_06_1200_repository.py
Normal file
|
|
@ -0,0 +1,43 @@
|
||||||
|
"""Add the repository table for git Repos (Collections with kind='repo').
|
||||||
|
|
||||||
|
Revision ID: 2026_10_06_1200
|
||||||
|
Revises: 2026_10_05_1200
|
||||||
|
"""
|
||||||
|
import sqlalchemy as sa
|
||||||
|
from alembic import op
|
||||||
|
|
||||||
|
import wrolpi.dates
|
||||||
|
|
||||||
|
# revision identifiers, used by Alembic.
|
||||||
|
revision = '2026_10_06_1200'
|
||||||
|
down_revision = '2026_10_05_1200'
|
||||||
|
branch_labels = None
|
||||||
|
depends_on = None
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade():
|
||||||
|
op.create_table(
|
||||||
|
'repository',
|
||||||
|
sa.Column('id', sa.Integer(), nullable=False),
|
||||||
|
sa.Column('url', sa.String(), nullable=False),
|
||||||
|
sa.Column('host', sa.String(), nullable=True),
|
||||||
|
sa.Column('owner', sa.String(), nullable=True),
|
||||||
|
sa.Column('mode', sa.String(), nullable=False),
|
||||||
|
sa.Column('branch', sa.String(), nullable=True),
|
||||||
|
sa.Column('default_branch', sa.String(), nullable=True),
|
||||||
|
sa.Column('head_sha', sa.String(), nullable=True),
|
||||||
|
sa.Column('head_date', wrolpi.dates.TZDateTime(), nullable=True),
|
||||||
|
sa.Column('head_message', sa.Text(), nullable=True),
|
||||||
|
sa.Column('last_fetch', wrolpi.dates.TZDateTime(), nullable=True),
|
||||||
|
sa.Column('size', sa.BigInteger(), nullable=True),
|
||||||
|
sa.Column('readme_path', sa.String(), nullable=True),
|
||||||
|
sa.Column('collection_id', sa.Integer(), nullable=False),
|
||||||
|
sa.ForeignKeyConstraint(['collection_id'], ['collection.id'], ondelete='CASCADE'),
|
||||||
|
sa.PrimaryKeyConstraint('id'),
|
||||||
|
sa.UniqueConstraint('collection_id'),
|
||||||
|
sa.UniqueConstraint('url'),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade():
|
||||||
|
op.drop_table('repository')
|
||||||
39
alembic/versions/2026_10_06_1300_repository_search.py
Normal file
39
alembic/versions/2026_10_06_1300_repository_search.py
Normal file
|
|
@ -0,0 +1,39 @@
|
||||||
|
"""Search git Repos by name and README: repository.search_name/readme_text and repository_fts.
|
||||||
|
|
||||||
|
Revision ID: 2026_10_06_1300
|
||||||
|
Revises: 2026_10_06_1200
|
||||||
|
"""
|
||||||
|
import sqlalchemy as sa
|
||||||
|
from alembic import op
|
||||||
|
|
||||||
|
# revision identifiers, used by Alembic.
|
||||||
|
revision = '2026_10_06_1300'
|
||||||
|
down_revision = '2026_10_06_1200'
|
||||||
|
branch_labels = None
|
||||||
|
depends_on = None
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade():
|
||||||
|
from wrolpi.schema_ddl import install_raw_ddl
|
||||||
|
|
||||||
|
op.add_column('repository', sa.Column('search_name', sa.String(), nullable=True))
|
||||||
|
op.add_column('repository', sa.Column('readme_text', sa.Text(), nullable=True))
|
||||||
|
op.execute('''
|
||||||
|
UPDATE repository SET search_name = TRIM(
|
||||||
|
COALESCE((SELECT name FROM collection WHERE collection.id = repository.collection_id), '')
|
||||||
|
|| ' ' || COALESCE(owner, ''))
|
||||||
|
''')
|
||||||
|
|
||||||
|
# Creates repository_fts and its triggers now that the columns exist. The README text is filled by the next
|
||||||
|
# update of each Repo.
|
||||||
|
install_raw_ddl(op.get_bind())
|
||||||
|
op.execute("INSERT INTO repository_fts(repository_fts) VALUES('rebuild')")
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade():
|
||||||
|
for name in ('repository_fts_ai', 'repository_fts_ad', 'repository_fts_au'):
|
||||||
|
op.execute(f'DROP TRIGGER IF EXISTS {name}')
|
||||||
|
op.execute('DROP TABLE IF EXISTS repository_fts')
|
||||||
|
with op.batch_alter_table('repository') as batch_op:
|
||||||
|
batch_op.drop_column('readme_text')
|
||||||
|
batch_op.drop_column('search_name')
|
||||||
22
alembic/versions/2026_10_06_1400_repository_submodules.py
Normal file
22
alembic/versions/2026_10_06_1400_repository_submodules.py
Normal file
|
|
@ -0,0 +1,22 @@
|
||||||
|
"""A git Repo can also download its submodules: repository.submodules.
|
||||||
|
|
||||||
|
Revision ID: 2026_10_06_1400
|
||||||
|
Revises: 2026_10_06_1300
|
||||||
|
"""
|
||||||
|
import sqlalchemy as sa
|
||||||
|
from alembic import op
|
||||||
|
|
||||||
|
# revision identifiers, used by Alembic.
|
||||||
|
revision = '2026_10_06_1400'
|
||||||
|
down_revision = '2026_10_06_1300'
|
||||||
|
branch_labels = None
|
||||||
|
depends_on = None
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade():
|
||||||
|
op.add_column('repository', sa.Column('submodules', sa.Boolean(), server_default=sa.false(), nullable=False))
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade():
|
||||||
|
with op.batch_alter_table('repository') as batch_op:
|
||||||
|
batch_op.drop_column('submodules')
|
||||||
22
alembic/versions/2026_10_06_1500_repository_clone_token.py
Normal file
22
alembic/versions/2026_10_06_1500_repository_clone_token.py
Normal file
|
|
@ -0,0 +1,22 @@
|
||||||
|
"""A git Repo's clone holds a random token: repository.clone_token.
|
||||||
|
|
||||||
|
Revision ID: 2026_10_06_1500
|
||||||
|
Revises: 2026_10_06_1400
|
||||||
|
"""
|
||||||
|
import sqlalchemy as sa
|
||||||
|
from alembic import op
|
||||||
|
|
||||||
|
# revision identifiers, used by Alembic.
|
||||||
|
revision = '2026_10_06_1500'
|
||||||
|
down_revision = '2026_10_06_1400'
|
||||||
|
branch_labels = None
|
||||||
|
depends_on = None
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade():
|
||||||
|
op.add_column('repository', sa.Column('clone_token', sa.String(), nullable=True))
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade():
|
||||||
|
with op.batch_alter_table('repository') as batch_op:
|
||||||
|
batch_op.drop_column('clone_token')
|
||||||
24
alembic/versions/2026_10_08_1200_file_group_progress.py
Normal file
24
alembic/versions/2026_10_08_1200_file_group_progress.py
Normal file
|
|
@ -0,0 +1,24 @@
|
||||||
|
"""A FileGroup records how far the user is through it: file_group.progress and file_group.position.
|
||||||
|
|
||||||
|
Revision ID: 2026_10_08_1200
|
||||||
|
Revises: 2026_10_06_1500
|
||||||
|
"""
|
||||||
|
import sqlalchemy as sa
|
||||||
|
from alembic import op
|
||||||
|
|
||||||
|
# revision identifiers, used by Alembic.
|
||||||
|
revision = '2026_10_08_1200'
|
||||||
|
down_revision = '2026_10_06_1500'
|
||||||
|
branch_labels = None
|
||||||
|
depends_on = None
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade():
|
||||||
|
op.add_column('file_group', sa.Column('progress', sa.Float(), nullable=True))
|
||||||
|
op.add_column('file_group', sa.Column('position', sa.JSON(), nullable=True))
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade():
|
||||||
|
# Not batch_alter_table: rebuilding file_group drops its FTS triggers (see 2026_09_20_1200).
|
||||||
|
op.execute('ALTER TABLE file_group DROP COLUMN position')
|
||||||
|
op.execute('ALTER TABLE file_group DROP COLUMN progress')
|
||||||
27
alembic/versions/2026_10_24_1200_config_version.py
Normal file
27
alembic/versions/2026_10_24_1200_config_version.py
Normal file
|
|
@ -0,0 +1,27 @@
|
||||||
|
"""Each database config's version, so an import can tell whether the database or the file is newer
|
||||||
|
(see wrolpi.config_version).
|
||||||
|
|
||||||
|
Revision ID: 2026_10_24_1200
|
||||||
|
Revises: 2026_10_08_1200
|
||||||
|
"""
|
||||||
|
import sqlalchemy as sa
|
||||||
|
from alembic import op
|
||||||
|
|
||||||
|
# revision identifiers, used by Alembic.
|
||||||
|
revision = '2026_10_24_1200'
|
||||||
|
down_revision = '2026_10_08_1200'
|
||||||
|
branch_labels = None
|
||||||
|
depends_on = None
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade():
|
||||||
|
# No rows: a config's next import (without deletes) records its version.
|
||||||
|
op.create_table(
|
||||||
|
'config_version',
|
||||||
|
sa.Column('name', sa.String(), primary_key=True),
|
||||||
|
sa.Column('version', sa.Integer(), nullable=False),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade():
|
||||||
|
op.drop_table('config_version')
|
||||||
175
alembic/versions/2026_10_25_1200_strip_tag_names.py
Normal file
175
alembic/versions/2026_10_25_1200_strip_tag_names.py
Normal file
|
|
@ -0,0 +1,175 @@
|
||||||
|
"""Tag names have no leading or trailing whitespace.
|
||||||
|
|
||||||
|
A Tag whose name had whitespace is renamed. Tags whose names are the same once stripped are merged into one: it
|
||||||
|
keeps every tagged file, Zim entry and Collection, and the first color (by Tag id) of the merged Tags. Downloads
|
||||||
|
and the config files that name Tags are rewritten the same way, so the next import finds them in step with the
|
||||||
|
database (an import of the old names would create the padded Tags again, or delete the stripped ones).
|
||||||
|
|
||||||
|
Revision ID: 2026_10_25_1200
|
||||||
|
Revises: 2026_10_24_1200
|
||||||
|
"""
|
||||||
|
import json
|
||||||
|
import logging
|
||||||
|
|
||||||
|
import yaml
|
||||||
|
from alembic import op
|
||||||
|
|
||||||
|
from wrolpi.common import get_media_directory, write_config_data
|
||||||
|
|
||||||
|
# revision identifiers, used by Alembic.
|
||||||
|
revision = '2026_10_25_1200'
|
||||||
|
down_revision = '2026_10_24_1200'
|
||||||
|
branch_labels = None
|
||||||
|
depends_on = None
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
# The configs which name Tags.
|
||||||
|
CONFIG_FILES = ('tags.yaml', 'download_manager.yaml', 'channels.yaml', 'domains.yaml', 'playlists.yaml',
|
||||||
|
'repos.yaml', 'videos_downloader.yaml', 'archives_downloader.yaml')
|
||||||
|
|
||||||
|
|
||||||
|
def _strip(name):
|
||||||
|
"""A Tag name without its whitespace; a name that would be empty is kept (it cannot be renamed)."""
|
||||||
|
if isinstance(name, str) and name.strip():
|
||||||
|
return name.strip()
|
||||||
|
return name
|
||||||
|
|
||||||
|
|
||||||
|
def _strip_names(names: list) -> list:
|
||||||
|
stripped = list()
|
||||||
|
for name in map(_strip, names):
|
||||||
|
if name not in stripped:
|
||||||
|
stripped.append(name)
|
||||||
|
return stripped
|
||||||
|
|
||||||
|
|
||||||
|
def _strip_nested(data):
|
||||||
|
"""Strip the Tag names in a config's (or a Download's settings') `tag_name`, `tag_names` and
|
||||||
|
`channel_tag_name` values, at any depth."""
|
||||||
|
if isinstance(data, list):
|
||||||
|
return [_strip_nested(i) for i in data]
|
||||||
|
if not isinstance(data, dict):
|
||||||
|
return data
|
||||||
|
result = dict()
|
||||||
|
for key, value in data.items():
|
||||||
|
if key == 'tag_name':
|
||||||
|
value = _strip(value)
|
||||||
|
elif key in ('tag_names', 'channel_tag_name') and isinstance(value, list):
|
||||||
|
value = _strip_names(value)
|
||||||
|
else:
|
||||||
|
value = _strip_nested(value)
|
||||||
|
result[key] = value
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
def _strip_rows(rows: list, key_length: int) -> list:
|
||||||
|
"""tags.yaml's tag_files or tag_zims, each row keyed by its first `key_length` values (the Tag name first)."""
|
||||||
|
result, seen = list(), set()
|
||||||
|
for row in rows:
|
||||||
|
if isinstance(row, list) and row:
|
||||||
|
row = [_strip(row[0]), *row[1:]]
|
||||||
|
key = json.dumps(row[:key_length], default=str)
|
||||||
|
if key in seen:
|
||||||
|
continue
|
||||||
|
seen.add(key)
|
||||||
|
result.append(row)
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
def _strip_tags_config(config: dict, colors: dict) -> dict:
|
||||||
|
"""`colors`: each renamed Tag's color in the database, which the file must match (an import copies the file's
|
||||||
|
color into the database)."""
|
||||||
|
config = dict(config)
|
||||||
|
if isinstance(config.get('tags'), dict):
|
||||||
|
tags = dict()
|
||||||
|
for name, attrs in config['tags'].items():
|
||||||
|
stripped = _strip(name)
|
||||||
|
if stripped not in tags:
|
||||||
|
tags[stripped] = attrs
|
||||||
|
elif isinstance(attrs, dict) and attrs.get('color') and not (tags[stripped] or dict()).get('color'):
|
||||||
|
# The first color of the merged Tags.
|
||||||
|
tags[stripped] = {**(tags[stripped] or dict()), 'color': attrs['color']}
|
||||||
|
for name in tags.keys() & colors.keys():
|
||||||
|
tags[name] = {**(tags[name] or dict()), 'color': colors[name]}
|
||||||
|
config['tags'] = tags
|
||||||
|
if isinstance(config.get('tag_files'), list):
|
||||||
|
config['tag_files'] = _strip_rows(config['tag_files'], 2)
|
||||||
|
if isinstance(config.get('tag_zims'), list):
|
||||||
|
config['tag_zims'] = _strip_rows(config['tag_zims'], 3)
|
||||||
|
return config
|
||||||
|
|
||||||
|
|
||||||
|
def strip_tag_names_in_configs(colors: dict):
|
||||||
|
config_directory = get_media_directory() / 'config'
|
||||||
|
for file_name in CONFIG_FILES:
|
||||||
|
file = config_directory / file_name
|
||||||
|
if not file.is_file():
|
||||||
|
continue
|
||||||
|
try:
|
||||||
|
with file.open('rt') as fh:
|
||||||
|
config = yaml.load(fh, Loader=yaml.CSafeLoader)
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f'Cannot strip Tag names of invalid config: {file}', exc_info=e)
|
||||||
|
continue
|
||||||
|
if not isinstance(config, dict):
|
||||||
|
continue
|
||||||
|
stripped = _strip_tags_config(config, colors) if file_name == 'tags.yaml' else config
|
||||||
|
stripped = _strip_nested(stripped)
|
||||||
|
if stripped != config:
|
||||||
|
logger.warning(f'Stripping whitespace from Tag names in {file}')
|
||||||
|
write_config_data(stripped, file, width=500 if file_name == 'tags.yaml' else 90)
|
||||||
|
|
||||||
|
|
||||||
|
def strip_tag_names_in_db(connection) -> dict:
|
||||||
|
"""Returns the color of each renamed Tag, by its new name."""
|
||||||
|
groups, colors = dict(), dict()
|
||||||
|
for id_, name, color in connection.exec_driver_sql('SELECT id, name, color FROM tag ORDER BY id').fetchall():
|
||||||
|
groups.setdefault(_strip(name), list()).append((id_, name, color))
|
||||||
|
|
||||||
|
for stripped, tags in groups.items():
|
||||||
|
if all(name == stripped for _, name, _ in tags):
|
||||||
|
continue
|
||||||
|
# Keep the Tag already named this, if any, otherwise the oldest.
|
||||||
|
survivor_id = next((id_ for id_, name, _ in tags if name == stripped), tags[0][0])
|
||||||
|
color = colors[stripped] = next((color for _, _, color in tags if color), None)
|
||||||
|
for id_, name, _ in tags:
|
||||||
|
if id_ == survivor_id:
|
||||||
|
continue
|
||||||
|
logger.warning(f'Merging Tag {name!r} into {stripped!r}')
|
||||||
|
connection.exec_driver_sql(
|
||||||
|
'INSERT OR IGNORE INTO tag_file (tag_id, file_group_id, created_at)'
|
||||||
|
' SELECT ?, file_group_id, created_at FROM tag_file WHERE tag_id = ?', (survivor_id, id_))
|
||||||
|
connection.exec_driver_sql(
|
||||||
|
'INSERT OR IGNORE INTO tag_zim (tag_id, zim_id, zim_entry, created_at)'
|
||||||
|
' SELECT ?, zim_id, zim_entry, created_at FROM tag_zim WHERE tag_id = ?', (survivor_id, id_))
|
||||||
|
connection.exec_driver_sql('DELETE FROM tag_file WHERE tag_id = ?', (id_,))
|
||||||
|
connection.exec_driver_sql('DELETE FROM tag_zim WHERE tag_id = ?', (id_,))
|
||||||
|
connection.exec_driver_sql('UPDATE collection SET tag_id = ? WHERE tag_id = ?', (survivor_id, id_))
|
||||||
|
connection.exec_driver_sql('DELETE FROM tag WHERE id = ?', (id_,))
|
||||||
|
logger.warning(f'Renaming Tag to {stripped!r}')
|
||||||
|
connection.exec_driver_sql('UPDATE tag SET name = ?, color = ? WHERE id = ?', (stripped, color, survivor_id))
|
||||||
|
|
||||||
|
# The Downloads which apply them (download_manager.yaml is stripped the same way).
|
||||||
|
downloads = connection.exec_driver_sql(
|
||||||
|
'SELECT id, tag_names, settings FROM download WHERE tag_names IS NOT NULL OR settings IS NOT NULL').fetchall()
|
||||||
|
for id_, tag_names, settings in downloads:
|
||||||
|
tag_names, settings = json.loads(tag_names) if tag_names else None, json.loads(settings) if settings else None
|
||||||
|
new_tag_names = _strip_names(tag_names) if isinstance(tag_names, list) else tag_names
|
||||||
|
new_settings = _strip_nested(settings)
|
||||||
|
if new_tag_names != tag_names or new_settings != settings:
|
||||||
|
connection.exec_driver_sql(
|
||||||
|
'UPDATE download SET tag_names = ?, settings = ? WHERE id = ?',
|
||||||
|
(json.dumps(new_tag_names) if new_tag_names is not None else None,
|
||||||
|
json.dumps(new_settings) if new_settings is not None else None, id_))
|
||||||
|
return colors
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade():
|
||||||
|
colors = strip_tag_names_in_db(op.get_bind())
|
||||||
|
strip_tag_names_in_configs(colors)
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade():
|
||||||
|
# Whitespace that was stripped is not restored.
|
||||||
|
pass
|
||||||
|
|
@ -0,0 +1,24 @@
|
||||||
|
"""A partial index of the unindexed FileGroups.
|
||||||
|
|
||||||
|
The modelers and indexers look up `file_group WHERE indexed != 1` (and count it for progress) on every
|
||||||
|
refresh. SQLite cannot use an index on `indexed` for `!=`, so each lookup read every file_group row; on a
|
||||||
|
large library from a cold disk cache that was close to a minute. This index holds only the unindexed rows.
|
||||||
|
|
||||||
|
Revision ID: 2026_10_30_1200
|
||||||
|
Revises: 2026_10_25_1200
|
||||||
|
"""
|
||||||
|
from alembic import op
|
||||||
|
|
||||||
|
# revision identifiers, used by Alembic.
|
||||||
|
revision = '2026_10_30_1200'
|
||||||
|
down_revision = '2026_10_25_1200'
|
||||||
|
branch_labels = None
|
||||||
|
depends_on = None
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade():
|
||||||
|
op.execute('CREATE INDEX IF NOT EXISTS file_group_unindexed_idx ON file_group (id) WHERE "indexed" != 1')
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade():
|
||||||
|
op.execute('DROP INDEX IF EXISTS file_group_unindexed_idx')
|
||||||
|
|
@ -22,9 +22,14 @@ function sandboxPath(relativePath) {
|
||||||
return resolved;
|
return resolved;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function fileContent(content) {
|
||||||
|
return content && content.base64 !== undefined ? Buffer.from(content.base64, "base64") : (content ?? "");
|
||||||
|
}
|
||||||
|
|
||||||
const fileBrowserTasks = {
|
const fileBrowserTasks = {
|
||||||
// Wipe the sandbox (including leftovers from a crashed run) and create the given files.
|
// Wipe the sandbox (including leftovers from a crashed run) and create the given files.
|
||||||
// `files` maps sandbox-relative paths to file content; a trailing '/' makes a bare directory.
|
// `files` maps sandbox-relative paths to file content; a trailing '/' makes a bare directory.
|
||||||
|
// Content is text, or `{base64: '...'}` for a binary file.
|
||||||
"fb:reset": ({ files }) => {
|
"fb:reset": ({ files }) => {
|
||||||
fs.rmSync(SANDBOX_DIR, { recursive: true, force: true });
|
fs.rmSync(SANDBOX_DIR, { recursive: true, force: true });
|
||||||
fs.mkdirSync(SANDBOX_DIR, { recursive: true });
|
fs.mkdirSync(SANDBOX_DIR, { recursive: true });
|
||||||
|
|
@ -34,7 +39,7 @@ const fileBrowserTasks = {
|
||||||
} else {
|
} else {
|
||||||
const filePath = sandboxPath(relativePath);
|
const filePath = sandboxPath(relativePath);
|
||||||
fs.mkdirSync(path.dirname(filePath), { recursive: true });
|
fs.mkdirSync(path.dirname(filePath), { recursive: true });
|
||||||
fs.writeFileSync(filePath, content ?? "");
|
fs.writeFileSync(filePath, fileContent(content));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return SANDBOX_NAME;
|
return SANDBOX_NAME;
|
||||||
|
|
@ -69,10 +74,57 @@ const fileBrowserTasks = {
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Real map files for the standalone map viewer's e2e test, jailed to one directory inside the
|
||||||
|
* media directory's map directory.
|
||||||
|
*/
|
||||||
|
const zlib = require("zlib");
|
||||||
|
|
||||||
|
const MAP_SANDBOX_NAME = "cypress-map";
|
||||||
|
const MAP_SANDBOX_DIR = path.join(MEDIA_DIR, "map", MAP_SANDBOX_NAME);
|
||||||
|
|
||||||
|
// A PMTiles version 3 file with a header, metadata and an empty tile directory: enough for the
|
||||||
|
// map to list and add it, with no tiles to draw.
|
||||||
|
function pmtilesFile(metadata) {
|
||||||
|
const directory = zlib.gzipSync(Buffer.from([0]));
|
||||||
|
const meta = zlib.gzipSync(Buffer.from(JSON.stringify(metadata)));
|
||||||
|
const header = Buffer.alloc(127);
|
||||||
|
header.write("PMTiles", 0, "latin1");
|
||||||
|
header[7] = 3;
|
||||||
|
header.writeBigUInt64LE(127n, 8);
|
||||||
|
header.writeBigUInt64LE(BigInt(directory.length), 16);
|
||||||
|
header.writeBigUInt64LE(BigInt(127 + directory.length), 24);
|
||||||
|
header.writeBigUInt64LE(BigInt(meta.length), 32);
|
||||||
|
// Clustered, internal compression gzip, tile compression gzip, tile type mvt, zoom 0-8.
|
||||||
|
Buffer.from([1, 2, 2, 1, 0, 8]).copy(header, 96);
|
||||||
|
header.writeInt32LE(-1800000000, 102);
|
||||||
|
header.writeInt32LE(-850000000, 106);
|
||||||
|
header.writeInt32LE(1800000000, 110);
|
||||||
|
header.writeInt32LE(850000000, 114);
|
||||||
|
return Buffer.concat([header, directory, meta]);
|
||||||
|
}
|
||||||
|
|
||||||
|
const mapTasks = {
|
||||||
|
// Wipe the sandbox and create an overlay file there, with a style beside it if given.
|
||||||
|
"map:seed-overlay": ({ name, metadata, style }) => {
|
||||||
|
if (!/^[a-z-]+$/.test(name)) throw new Error(`Refusing the map file name: ${name}`);
|
||||||
|
fs.rmSync(MAP_SANDBOX_DIR, { recursive: true, force: true });
|
||||||
|
fs.mkdirSync(MAP_SANDBOX_DIR, { recursive: true });
|
||||||
|
fs.writeFileSync(path.join(MAP_SANDBOX_DIR, `${name}.pmtiles`), pmtilesFile(metadata));
|
||||||
|
if (style) fs.writeFileSync(path.join(MAP_SANDBOX_DIR, `${name}.style.json`), JSON.stringify(style));
|
||||||
|
return `${MAP_SANDBOX_NAME}/${name}.pmtiles`;
|
||||||
|
},
|
||||||
|
"map:cleanup": () => {
|
||||||
|
fs.rmSync(MAP_SANDBOX_DIR, { recursive: true, force: true });
|
||||||
|
return true;
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
module.exports = defineConfig({
|
module.exports = defineConfig({
|
||||||
e2e: {
|
e2e: {
|
||||||
setupNodeEvents(on) {
|
setupNodeEvents(on) {
|
||||||
on("task", fileBrowserTasks);
|
on("task", fileBrowserTasks);
|
||||||
|
on("task", mapTasks);
|
||||||
},
|
},
|
||||||
// Use HTTP for CI, HTTPS for local development
|
// Use HTTP for CI, HTTPS for local development
|
||||||
baseUrl: process.env.CI ? 'http://localhost:3000' : 'https://localhost:8443',
|
baseUrl: process.env.CI ? 'http://localhost:3000' : 'https://localhost:8443',
|
||||||
|
|
|
||||||
|
|
@ -108,16 +108,24 @@ import {
|
||||||
selectRow('fb-alpha');
|
selectRow('fb-alpha');
|
||||||
footerButton('Rename').click();
|
footerButton('Rename').click();
|
||||||
|
|
||||||
drainQueuedRefresh(() => {
|
// A directory rename is a file-worker move job; the request returns once it is queued, and the job
|
||||||
|
// reports when it is done. No refresh is queued.
|
||||||
|
cy.serverNow().then((since) => {
|
||||||
dialog().within(() => {
|
dialog().within(() => {
|
||||||
cy.get('input').clear().type('fb-alpha-renamed');
|
cy.get('input').clear().type('fb-alpha-renamed');
|
||||||
cy.contains('button', 'Rename').click();
|
cy.contains('button', 'Rename').click();
|
||||||
});
|
});
|
||||||
|
dialog().should('not.exist');
|
||||||
|
cy.waitForEvent({
|
||||||
|
since,
|
||||||
|
event: 'file_move_completed',
|
||||||
|
message: 'Renamed fb-alpha to fb-alpha-renamed',
|
||||||
|
failureEvent: 'file_move_failed',
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
// A directory rename runs as a file-worker move job; the modal stays open until
|
// The table is fetched again once the file worker is idle.
|
||||||
// the job finishes, which takes longer than the default timeout.
|
cy.contains('tr', 'fb-alpha-renamed', {timeout: 10000}).should('be.visible');
|
||||||
cy.get('[role="dialog"]', {timeout: 30000}).should('not.exist');
|
|
||||||
row('fb-alpha-renamed').should('be.visible');
|
|
||||||
// The folder row's text is just the name, so anchoring excludes 'fb-alpha-renamed'.
|
// The folder row's text is just the name, so anchoring excludes 'fb-alpha-renamed'.
|
||||||
cy.contains('tr', /fb-alpha$/).should('not.exist');
|
cy.contains('tr', /fb-alpha$/).should('not.exist');
|
||||||
|
|
||||||
|
|
@ -126,4 +134,3 @@ import {
|
||||||
cy.task('fb:exists', 'fb-alpha').should('be.false');
|
cy.task('fb:exists', 'fb-alpha').should('be.false');
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
});
|
|
||||||
|
|
|
||||||
89
app/cypress/e2e/files/stl-preview.cy.js
Normal file
89
app/cypress/e2e/files/stl-preview.cy.js
Normal file
|
|
@ -0,0 +1,89 @@
|
||||||
|
/*
|
||||||
|
* Previewing STL files, exercised against the live stack in a real browser (WebGL).
|
||||||
|
*
|
||||||
|
* An STL is either ASCII text or binary. Both must load in the preview: the dimensions line
|
||||||
|
* is only shown after the model has been parsed and framed, and a load failure is shown as an
|
||||||
|
* error (or thrown, which fails the test).
|
||||||
|
*/
|
||||||
|
import {assertWROLModeOff, SANDBOX, teardownFileBrowser} from '../../support/file-browser';
|
||||||
|
|
||||||
|
// One right triangle, legs of 2 along X and 1 along Y.
|
||||||
|
const ASCII_STL = `solid ASCII
|
||||||
|
facet normal 0 0 1
|
||||||
|
outer loop
|
||||||
|
vertex 0 0 0
|
||||||
|
vertex 2 0 0
|
||||||
|
vertex 0 1 0
|
||||||
|
endloop
|
||||||
|
endfacet
|
||||||
|
endsolid
|
||||||
|
`;
|
||||||
|
|
||||||
|
function binaryStlBase64() {
|
||||||
|
// 80-byte header, uint32 triangle count, then one 50-byte triangle: normal, three vertices.
|
||||||
|
const buffer = new ArrayBuffer(84 + 50);
|
||||||
|
const view = new DataView(buffer);
|
||||||
|
view.setUint32(80, 1, true);
|
||||||
|
const floats = [0, 0, 1, 0, 0, 0, 2, 0, 0, 0, 1, 0];
|
||||||
|
floats.forEach((value, i) => view.setFloat32(84 + i * 4, value, true));
|
||||||
|
return Cypress.Buffer.from(buffer).toString('base64');
|
||||||
|
}
|
||||||
|
|
||||||
|
// Requires the full stack (API + real media directory); CI runs only the React dev server.
|
||||||
|
(Cypress.env('CI') ? describe.skip : describe)('STL preview', () => {
|
||||||
|
|
||||||
|
before(() => {
|
||||||
|
assertWROLModeOff();
|
||||||
|
cy.task('fb:reset', {
|
||||||
|
files: {
|
||||||
|
'ascii.stl': ASCII_STL,
|
||||||
|
'binary.stl': {base64: binaryStlBase64()},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
cy.refreshFiles([SANDBOX]);
|
||||||
|
});
|
||||||
|
|
||||||
|
after(() => {
|
||||||
|
teardownFileBrowser();
|
||||||
|
});
|
||||||
|
|
||||||
|
const openPreview = (name) => {
|
||||||
|
const params = new URLSearchParams({folders: `${SANDBOX}/`, preview: `${SANDBOX}/${name}`});
|
||||||
|
cy.visit(`/files?${params}`);
|
||||||
|
cy.get('[role="dialog"]').should('contain', name);
|
||||||
|
};
|
||||||
|
|
||||||
|
const expectTriangleDimensions = () => {
|
||||||
|
// The triangle is 2 wide along X, which only a parsed model can report. Which axis
|
||||||
|
// reads as Height or Length depends on how the viewer orients the model, so only
|
||||||
|
// Width is asserted.
|
||||||
|
cy.get('[role="dialog"]').contains('Width:', {timeout: 20000}).parent()
|
||||||
|
.should('contain', 'Width: 2.00');
|
||||||
|
cy.get('[role="dialog"]').should('not.contain', 'Failed to');
|
||||||
|
};
|
||||||
|
|
||||||
|
it('previews an ASCII STL file', () => {
|
||||||
|
openPreview('ascii.stl');
|
||||||
|
expectTriangleDimensions();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('previews a binary STL file', () => {
|
||||||
|
openPreview('binary.stl');
|
||||||
|
expectTriangleDimensions();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('shows the action buttons without scrolling the preview', () => {
|
||||||
|
cy.viewport(1280, 720);
|
||||||
|
openPreview('binary.stl');
|
||||||
|
// The dimensions line is the last thing the preview adds, so the layout is final.
|
||||||
|
expectTriangleDimensions();
|
||||||
|
cy.get('.mantine-Modal-content').should(([content]) => {
|
||||||
|
expect(content.scrollHeight, 'preview modal content scrolls')
|
||||||
|
.to.be.at.most(content.clientHeight);
|
||||||
|
});
|
||||||
|
cy.get('.wrolpi-modal-actions').should(([actions]) => {
|
||||||
|
expect(actions.getBoundingClientRect().bottom, 'action buttons bottom edge')
|
||||||
|
.to.be.at.most(actions.ownerDocument.defaultView.innerHeight);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
136
app/cypress/e2e/map-standalone.cy.js
Normal file
136
app/cypress/e2e/map-standalone.cy.js
Normal file
|
|
@ -0,0 +1,136 @@
|
||||||
|
/*
|
||||||
|
* The standalone map viewer (port 8084) and overlays: map files which are not a basemap.
|
||||||
|
*
|
||||||
|
* The standalone viewer is plain HTML with no build step; it loads copies of the map viewer's
|
||||||
|
* overlay modules. This runs against the live stack with a real map file: the map:* tasks write
|
||||||
|
* a small overlay (no tiles) and a style beside it into the media directory's map directory.
|
||||||
|
*/
|
||||||
|
|
||||||
|
const VIEWER = 'https://localhost:8084/';
|
||||||
|
const LABEL = 'Cypress Overlay';
|
||||||
|
|
||||||
|
const METADATA = {
|
||||||
|
name: LABEL,
|
||||||
|
description: 'An overlay for the standalone viewer test',
|
||||||
|
type: 'overlay',
|
||||||
|
vector_layers: [
|
||||||
|
{id: 'towers', fields: {name: 'String'}, minzoom: 0, maxzoom: 8},
|
||||||
|
{id: 'power_lines', fields: {}, minzoom: 0, maxzoom: 8},
|
||||||
|
{id: 'parks', fields: {}, minzoom: 0, maxzoom: 8},
|
||||||
|
],
|
||||||
|
tilestats: {
|
||||||
|
layers: [
|
||||||
|
{layer: 'towers', geometry: 'Point', count: 1},
|
||||||
|
{layer: 'power_lines', geometry: 'LineString', count: 1},
|
||||||
|
{layer: 'parks', geometry: 'Polygon', count: 1},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
// Written for some other map: its own source name and URL, and one layer MapLibre cannot draw.
|
||||||
|
const STYLE = {
|
||||||
|
version: 8,
|
||||||
|
sources: {features: {type: 'vector', url: 'https://example.com/features.json'}},
|
||||||
|
layers: [
|
||||||
|
{id: 'background', type: 'background'},
|
||||||
|
{id: 'lines', type: 'line', source: 'features', 'source-layer': 'power_lines', paint: {'line-color': '#c60'}},
|
||||||
|
{id: 'bad', type: 'line', source: 'features', 'source-layer': 'parks', paint: {'line-width': 'wide'}},
|
||||||
|
{
|
||||||
|
id: 'towers', type: 'symbol', source: 'features', 'source-layer': 'towers',
|
||||||
|
layout: {'text-field': ['get', 'name'], 'text-font': ['Roboto Bold']},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
};
|
||||||
|
|
||||||
|
const overlayRow = () => cy.contains('.overlay-file', LABEL);
|
||||||
|
const overlayBox = () => overlayRow().find('input[type=checkbox]');
|
||||||
|
const layerBox = (name) => cy.contains('.overlay-layer', name).find('input[type=checkbox]');
|
||||||
|
const openPanel = () => cy.get('#overlay-section', {timeout: 20000}).should('be.visible');
|
||||||
|
|
||||||
|
// Requires the full stack (API, Caddy on 8084, real media directory); CI runs only the React dev server.
|
||||||
|
(Cypress.env('CI') ? describe.skip : describe)('Standalone map viewer: overlays', () => {
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
cy.task('map:cleanup');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('offers an overlay by its own name, hidden, with a checkbox per layer', () => {
|
||||||
|
cy.task('map:seed-overlay', {name: 'generic', metadata: METADATA});
|
||||||
|
cy.visit(VIEWER);
|
||||||
|
openPanel();
|
||||||
|
|
||||||
|
overlayBox().should('not.be.checked');
|
||||||
|
overlayRow().find('.overlay-zooms').should('have.text', 'z0\u20138');
|
||||||
|
|
||||||
|
overlayRow().find('.overlay-expand').click();
|
||||||
|
// Every layer of the file, each with the color it is drawn in.
|
||||||
|
cy.get('.overlay-layer').should('have.length', 3);
|
||||||
|
cy.get('.overlay-swatch').should('have.length', 3);
|
||||||
|
// The layers cannot be chosen while the file is off.
|
||||||
|
layerBox('towers').should('be.disabled');
|
||||||
|
|
||||||
|
overlayBox().check();
|
||||||
|
layerBox('towers').should('be.enabled').and('be.checked');
|
||||||
|
layerBox('towers').uncheck();
|
||||||
|
cy.contains('.overlay-all-none button', 'None').click();
|
||||||
|
layerBox('power_lines').should('not.be.checked');
|
||||||
|
cy.contains('.overlay-all-none button', 'All').click();
|
||||||
|
layerBox('power_lines').should('be.checked');
|
||||||
|
layerBox('towers').should('be.checked');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('remembers what was turned on', () => {
|
||||||
|
cy.task('map:seed-overlay', {name: 'remembered', metadata: METADATA});
|
||||||
|
cy.visit(VIEWER);
|
||||||
|
openPanel();
|
||||||
|
overlayBox().check();
|
||||||
|
overlayRow().find('.overlay-expand').click();
|
||||||
|
layerBox('parks').uncheck();
|
||||||
|
|
||||||
|
cy.reload();
|
||||||
|
openPanel();
|
||||||
|
overlayBox().should('be.checked');
|
||||||
|
overlayRow().find('.overlay-expand').click();
|
||||||
|
layerBox('parks').should('not.be.checked');
|
||||||
|
layerBox('towers').should('be.checked');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('draws an overlay with the style beside it, without the layer MapLibre refuses', () => {
|
||||||
|
cy.intercept('GET', '**/data/cypress-map/styled.style.json').as('style');
|
||||||
|
cy.intercept('GET', '**/sprites/overlay-icons*.json').as('icons');
|
||||||
|
cy.task('map:seed-overlay', {name: 'styled', metadata: METADATA, style: STYLE});
|
||||||
|
cy.visit(VIEWER);
|
||||||
|
// The style is fetched from the map directory this viewer is served.
|
||||||
|
cy.wait('@style').its('response.statusCode').should('eq', 200);
|
||||||
|
openPanel();
|
||||||
|
|
||||||
|
overlayRow().find('.overlay-expand').click();
|
||||||
|
// Only the layers the style draws, and no generic colors.
|
||||||
|
cy.get('.overlay-layer').should('have.length', 3);
|
||||||
|
cy.get('.overlay-swatch').should('have.length', 0);
|
||||||
|
// This viewer cannot check a layer before MapLibre does: the bad one is refused there.
|
||||||
|
cy.contains('.overlay-note', '1 style layer skipped');
|
||||||
|
// The panel is rebuilt by a change, so the checkbox is found again.
|
||||||
|
overlayBox().check();
|
||||||
|
overlayBox().should('be.checked');
|
||||||
|
// A style names icons: the map's own, a sprite of this viewer's. Its index has a name a
|
||||||
|
// style may use for an icon, beside the icon's own.
|
||||||
|
cy.wait('@icons').then(({response}) => {
|
||||||
|
expect(response.statusCode).to.eq(200);
|
||||||
|
expect(response.body).to.have.property('ham_radio');
|
||||||
|
expect(response.body.ham_radio).to.deep.eq(response.body.antenna);
|
||||||
|
expect(response.body.hospital.sdf).to.eq(true);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('does not offer an ignored file', () => {
|
||||||
|
cy.task('map:seed-overlay', {name: 'ignored', metadata: METADATA}).then((mapPath) => {
|
||||||
|
cy.request('POST', 'https://localhost:8084/api/map/files/visible', {map_path: mapPath, visible: false});
|
||||||
|
cy.visit(VIEWER);
|
||||||
|
cy.get('#layer-content', {timeout: 20000}).contains('Labels');
|
||||||
|
cy.contains('.overlay-file', LABEL).should('not.exist');
|
||||||
|
// Deleting the file forgets that it was ignored.
|
||||||
|
cy.request('DELETE', `https://localhost:8084/api/map/files/${mapPath}`);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
@ -1,5 +1,5 @@
|
||||||
/*
|
/*
|
||||||
* The five Special Directories fields on /admin/settings.
|
* The six Special Directories fields on /admin/settings.
|
||||||
*
|
*
|
||||||
* These are the fields that shipped printing their own prefix over their own value, and the
|
* These are the fields that shipped printing their own prefix over their own value, and the
|
||||||
* ones whose visible labels were never associated with their inputs. Both faults were
|
* ones whose visible labels were never associated with their inputs. Both faults were
|
||||||
|
|
@ -19,6 +19,7 @@ describe('Special Directories settings', () => {
|
||||||
['Map Directory', 'map'],
|
['Map Directory', 'map'],
|
||||||
['Zims Directory', 'zims'],
|
['Zims Directory', 'zims'],
|
||||||
['Playlists Directory', 'playlists'],
|
['Playlists Directory', 'playlists'],
|
||||||
|
['Repos Directory', 'repos/%(repo_tag)s/%(repo_name)s'],
|
||||||
];
|
];
|
||||||
|
|
||||||
beforeEach(() => {
|
beforeEach(() => {
|
||||||
|
|
@ -38,8 +39,8 @@ describe('Special Directories settings', () => {
|
||||||
|
|
||||||
it('names every directory field, so they can be told apart', () => {
|
it('names every directory field, so they can be told apart', () => {
|
||||||
/*
|
/*
|
||||||
* All five fields sit in one grid, hold similar-looking relative paths, and share the
|
* All six fields sit in one grid, hold similar-looking relative paths, and share the
|
||||||
* same prefix. Without a name attached to the input, a screen reader user hears five
|
* same prefix. Without a name attached to the input, a screen reader user hears six
|
||||||
* fields described only as "/media/wrolpi/" and cannot tell which one saves videos.
|
* fields described only as "/media/wrolpi/" and cannot tell which one saves videos.
|
||||||
*/
|
*/
|
||||||
directories.forEach(([label, value]) => {
|
directories.forEach(([label, value]) => {
|
||||||
|
|
|
||||||
|
|
@ -41,7 +41,7 @@ import React from "react";
|
||||||
|
|
||||||
Cypress.on('uncaught:exception', (err, runnable) => {
|
Cypress.on('uncaught:exception', (err, runnable) => {
|
||||||
if (err.message.includes('ChunkLoadError')) {
|
if (err.message.includes('ChunkLoadError')) {
|
||||||
return false; // Ignore this error which happens after CircleCI tests.
|
return false; // Ignore this error which happens after CI tests.
|
||||||
}
|
}
|
||||||
// Otherwise, fail like normal
|
// Otherwise, fail like normal
|
||||||
return true;
|
return true;
|
||||||
|
|
|
||||||
30
app/jest/babelTransform.js
Normal file
30
app/jest/babelTransform.js
Normal file
|
|
@ -0,0 +1,30 @@
|
||||||
|
'use strict';
|
||||||
|
|
||||||
|
// Replaces CRA's JS transform so Jest can load three.js. three ships ES modules
|
||||||
|
// with static class blocks, which babel-preset-react-app's class-properties plugin rejects at our
|
||||||
|
// pinned Babel version. Those files only need their imports converted to CommonJS; every other
|
||||||
|
// file goes through CRA's transform unchanged.
|
||||||
|
const babelJest = require('babel-jest').default;
|
||||||
|
const craTransform = require('react-scripts/config/jest/babelTransform');
|
||||||
|
|
||||||
|
const threeTransform = babelJest.createTransformer({
|
||||||
|
babelrc: false,
|
||||||
|
configFile: false,
|
||||||
|
plugins: [require.resolve('@babel/plugin-transform-modules-commonjs')],
|
||||||
|
});
|
||||||
|
|
||||||
|
const THREE_PATH = /[\\/]node_modules[\\/]three[\\/]/;
|
||||||
|
|
||||||
|
function pick(sourcePath) {
|
||||||
|
return THREE_PATH.test(sourcePath) ? threeTransform : craTransform;
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = {
|
||||||
|
canInstrument: true,
|
||||||
|
getCacheKey(sourceText, sourcePath, options) {
|
||||||
|
return pick(sourcePath).getCacheKey(sourceText, sourcePath, options);
|
||||||
|
},
|
||||||
|
process(sourceText, sourcePath, options) {
|
||||||
|
return pick(sourcePath).process(sourceText, sourcePath, options);
|
||||||
|
},
|
||||||
|
};
|
||||||
1402
app/package-lock.json
generated
1402
app/package-lock.json
generated
File diff suppressed because it is too large
Load diff
|
|
@ -9,35 +9,40 @@
|
||||||
"@mantine/core": "^8.3.18",
|
"@mantine/core": "^8.3.18",
|
||||||
"@mantine/hooks": "^8.3.18",
|
"@mantine/hooks": "^8.3.18",
|
||||||
"@mantine/notifications": "^8.3.18",
|
"@mantine/notifications": "^8.3.18",
|
||||||
"@tabler/icons-react": "^3.46.0",
|
"@mapbox/vector-tile": "^2.0.4",
|
||||||
|
"@maplibre/maplibre-gl-style-spec": "^24.8.5",
|
||||||
|
"@tabler/icons-react": "^3.50.0",
|
||||||
"@testing-library/react": "^13.4.0",
|
"@testing-library/react": "^13.4.0",
|
||||||
"@testing-library/user-event": "^14.6.6",
|
"@testing-library/user-event": "^14.6.8",
|
||||||
"cypress": "^15.21.1",
|
"cypress": "^15.21.1",
|
||||||
"esptool-js": "^0.6.1",
|
"dompurify": "^3.4.17",
|
||||||
|
"esptool-js": "^0.7.0",
|
||||||
"lodash": "^4.18.1",
|
"lodash": "^4.18.1",
|
||||||
"maplibre-gl": "^5.24.0",
|
"maplibre-gl": "^5.24.0",
|
||||||
|
"markdown-it": "^15.0.3",
|
||||||
"mathjs": "^15.2.0",
|
"mathjs": "^15.2.0",
|
||||||
|
"pbf": "^4.0.1",
|
||||||
"pmtiles": "^4.5.0",
|
"pmtiles": "^4.5.0",
|
||||||
"protomaps-themes-base": "^4.5.0",
|
"protomaps-themes-base": "^4.5.0",
|
||||||
"query-string": "^9.5.1",
|
"query-string": "^10.0.0",
|
||||||
"react": "^18.2.0",
|
"react": "^18.3.1",
|
||||||
"react-colorful": "^5.8.0",
|
"react-colorful": "^5.8.1",
|
||||||
"react-dom": "^18.2.0",
|
"react-dom": "^18.3.1",
|
||||||
"react-dropzone": "^14.2.3",
|
"react-dropzone": "^14.4.1",
|
||||||
"react-hotkeys-hook": "^5.3.3",
|
"react-hotkeys-hook": "^5.3.3",
|
||||||
"react-qr-code": "^2.2.0",
|
"react-qr-code": "^2.2.0",
|
||||||
"react-router": "^7.18.2",
|
"react-router": "^7.18.5",
|
||||||
"react-scripts": "5.0.1",
|
"react-scripts": "5.0.1",
|
||||||
"react-stl-viewer": "^2.5.0",
|
"three": "^0.186",
|
||||||
"three": "^0.185",
|
"web-vitals": "^6.2.3"
|
||||||
"web-vitals": "^5.3.0"
|
|
||||||
},
|
},
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"start": "react-scripts start",
|
"start": "react-scripts start",
|
||||||
"build": "BROWSERSLIST_IGNORE_OLD_DATA=true react-scripts build",
|
"build": "BROWSERSLIST_IGNORE_OLD_DATA=true react-scripts build",
|
||||||
"test": "react-scripts test",
|
"test": "TZ=America/New_York react-scripts test",
|
||||||
"eject": "react-scripts eject",
|
"eject": "react-scripts eject",
|
||||||
"cy:run": "cypress run",
|
"cy:run": "cypress run",
|
||||||
|
"sync:map-shared": "mkdir -p ../modules/map/static/js && cp src/map-shared/overlays.js src/map-shared/overlayStyle.js src/map-shared/terrain.js ../modules/map/static/js/",
|
||||||
"cy:open": "cypress open"
|
"cy:open": "cypress open"
|
||||||
},
|
},
|
||||||
"eslintConfig": {
|
"eslintConfig": {
|
||||||
|
|
@ -58,19 +63,25 @@
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@testing-library/dom": "^10.4.1",
|
"@testing-library/dom": "^10.4.2",
|
||||||
"@testing-library/jest-dom": "^7.0.1",
|
"@testing-library/jest-dom": "^7.0.1",
|
||||||
"@types/lodash": "^4.17.25",
|
"@types/lodash": "^4.17.27",
|
||||||
"@types/node": "^26.4.0",
|
"@types/node": "^26.6.6",
|
||||||
"@types/react": "^18.3.17",
|
"@types/react": "^18.3.17",
|
||||||
"@types/react-dom": "^18.3.5",
|
"@types/react-dom": "^18.3.5",
|
||||||
"typescript": "^5.9.3",
|
"typescript": "^5.9.3",
|
||||||
"webpack-dev-server": "^5.2.6"
|
"webpack-dev-server": "^5.2.7"
|
||||||
},
|
},
|
||||||
"jest": {
|
"jest": {
|
||||||
|
"transform": {
|
||||||
|
"^.+\\.(js|jsx|mjs|cjs|ts|tsx)$": "<rootDir>/jest/babelTransform.js"
|
||||||
|
},
|
||||||
"transformIgnorePatterns": [
|
"transformIgnorePatterns": [
|
||||||
"node_modules/(?!(react-hotkeys-hook)/)"
|
"node_modules/(?!(react-hotkeys-hook|three|@mapbox/vector-tile|@mapbox/point-geometry|pbf)/)"
|
||||||
]
|
],
|
||||||
|
"moduleNameMapper": {
|
||||||
|
"^(.*)/falloutWorker(\\.js)?$": "$1/falloutWorker.stub.js"
|
||||||
|
}
|
||||||
},
|
},
|
||||||
"overrides": {
|
"overrides": {
|
||||||
"@babel/code-frame": "7.29.0",
|
"@babel/code-frame": "7.29.0",
|
||||||
|
|
@ -89,9 +100,9 @@
|
||||||
"@babel/template": "7.28.6",
|
"@babel/template": "7.28.6",
|
||||||
"@babel/traverse": "7.29.0",
|
"@babel/traverse": "7.29.0",
|
||||||
"@babel/types": "7.29.0",
|
"@babel/types": "7.29.0",
|
||||||
|
"fork-ts-checker-webpack-plugin": "^6.5.3",
|
||||||
"react-scripts": {
|
"react-scripts": {
|
||||||
"typescript": "$typescript"
|
"typescript": "$typescript"
|
||||||
},
|
}
|
||||||
"fork-ts-checker-webpack-plugin": "^6.5.3"
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
11
app/public/data/solar-climatology.LICENSE.txt
Normal file
11
app/public/data/solar-climatology.LICENSE.txt
Normal file
|
|
@ -0,0 +1,11 @@
|
||||||
|
Solar climatology for the WROLPi Solar calculator
|
||||||
|
|
||||||
|
Source: NASA POWER, https://power.larc.nasa.gov/
|
||||||
|
Data: 2001-2020 monthly climatology of ALLSKY_SFC_SW_DWN, ALLSKY_SFC_SW_DIFF, ALLSKY_SRF_ALB, T2M, on a 1° grid.
|
||||||
|
The data was obtained from the POWER Project's POWER Climatology API v2.10.0 version on 2026/10/04.
|
||||||
|
|
||||||
|
The data was obtained from National Aeronautics and Space Administration (NASA) Langley Research Center's Prediction Of Worldwide Energy Resources (POWER) project funded through the NASA Earth Science Division.
|
||||||
|
|
||||||
|
License: Creative Commons Attribution 4.0 International (CC BY 4.0), https://creativecommons.org/licenses/by/4.0/
|
||||||
|
|
||||||
|
Changes: WROLPi modified the data: values are rounded to fit one byte each (0.04 kWh/m²/day for irradiance, 0.004 for albedo, 0.5 °C for temperature), temperatures are averaged from NASA's 0.5° x 0.625° grid into 1° cells, and the calculator interpolates between cells.
|
||||||
BIN
app/public/data/solar-climatology.bin
Normal file
BIN
app/public/data/solar-climatology.bin
Normal file
Binary file not shown.
|
|
@ -242,6 +242,8 @@ either expressed or implied, of the FreeBSD Project. -->
|
||||||
// Optional search term passed in from a search-result deep link. If present we'll
|
// Optional search term passed in from a search-result deep link. If present we'll
|
||||||
// search the spine item at `loc` and jump to + highlight the first match.
|
// search the spine item at `loc` and jump to + highlight the first match.
|
||||||
let searchQuery = (params && params.get("q")) ? params.get("q") : null;
|
let searchQuery = (params && params.get("q")) ? params.get("q") : null;
|
||||||
|
// Where the reader left off (an EPUB CFI). A search result's `loc` wins over it.
|
||||||
|
let startCfi = (params && params.get("cfi")) ? params.get("cfi") : null;
|
||||||
|
|
||||||
let book = ePub(url);
|
let book = ePub(url);
|
||||||
let rendition = book.renderTo("viewer", {
|
let rendition = book.renderTo("viewer", {
|
||||||
|
|
@ -250,7 +252,33 @@ either expressed or implied, of the FreeBSD Project. -->
|
||||||
height: "100%"
|
height: "100%"
|
||||||
});
|
});
|
||||||
|
|
||||||
rendition.display(currentSectionIndex);
|
rendition.display(currentSectionIndex !== undefined ? currentSectionIndex : (startCfi || undefined));
|
||||||
|
|
||||||
|
// How far through the book `location` is, from its chapter and its page within that chapter. Cheaper
|
||||||
|
// than `book.locations.generate()`, which stalls a Raspberry Pi on a large book.
|
||||||
|
function readingProgress(location) {
|
||||||
|
if (location.atEnd) {
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
const start = location.start;
|
||||||
|
const sections = book.spine.length || 1;
|
||||||
|
const displayed = start.displayed || {page: 1, total: 1};
|
||||||
|
const withinSection = (displayed.page - 1) / Math.max(displayed.total, 1);
|
||||||
|
return Math.min((start.index + withinSection) / sections, 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Tell the WROLPi page that embeds this viewer where the reader is, so it can save their place. Nothing is
|
||||||
|
// posted at the start of the book: that is where a finished book opens, and saving it would un-finish it.
|
||||||
|
function postLocation(location) {
|
||||||
|
if (window.parent === window || !location || !location.start || location.atStart) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
window.parent.postMessage({
|
||||||
|
type: "wrolpi:epub-location",
|
||||||
|
cfi: location.start.cfi,
|
||||||
|
progress: readingProgress(location),
|
||||||
|
}, window.location.origin);
|
||||||
|
}
|
||||||
|
|
||||||
// --- In-book search ---------------------------------------------------
|
// --- In-book search ---------------------------------------------------
|
||||||
// State is module-level so the toolbar buttons can drive it. `hits` is the
|
// State is module-level so the toolbar buttons can drive it. `hits` is the
|
||||||
|
|
@ -516,6 +544,7 @@ either expressed or implied, of the FreeBSD Project. -->
|
||||||
prev.style.visibility = "visible";
|
prev.style.visibility = "visible";
|
||||||
}
|
}
|
||||||
|
|
||||||
|
postLocation(location);
|
||||||
});
|
});
|
||||||
|
|
||||||
rendition.on("layout", function (layout) {
|
rendition.on("layout", function (layout) {
|
||||||
|
|
|
||||||
151
app/src/App.css
151
app/src/App.css
|
|
@ -293,9 +293,8 @@ pre.wrap-text {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Caps preview content to fit inside the file-preview Modal.
|
/* Caps preview content to fit inside a Modal (e.g. the Zim entry preview): 18.75rem is a guess at
|
||||||
300px reserves room for pathContent <pre>, Modal.Header, Modal.Actions row,
|
everything else in the modal. The file-preview Modal does not guess; see below.
|
||||||
inner content (e.g. STL dimensions banner), and modal padding.
|
|
||||||
Use 100dvh so mobile browser chrome (URL bar) is accounted for. */
|
Use 100dvh so mobile browser chrome (URL bar) is accounted for. */
|
||||||
.preview-fit {
|
.preview-fit {
|
||||||
width: 100%;
|
width: 100%;
|
||||||
|
|
@ -309,6 +308,36 @@ pre.wrap-text {
|
||||||
justify-content: center;
|
justify-content: center;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* In the file-preview Modal, a .preview-fit takes whatever height the rest of the modal leaves
|
||||||
|
(path, header, a 3D model's dimensions line, the action buttons however they wrap) rather
|
||||||
|
than reserving a fixed amount, so the buttons are always on screen without scrolling.
|
||||||
|
The modal fills Mantine's maximum height only when it frames a .preview-fit; other previews
|
||||||
|
keep the height of their content. */
|
||||||
|
.file-preview-modal-content:has(.preview-fit) {
|
||||||
|
height: calc(100dvh - var(--modal-y-offset) * 2);
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
}
|
||||||
|
|
||||||
|
.file-preview-modal-content:has(.preview-fit) > .mantine-Modal-header {
|
||||||
|
flex: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.file-preview-modal-content:has(.preview-fit) > .mantine-Modal-body {
|
||||||
|
flex: 1 1 auto;
|
||||||
|
min-height: 0;
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* The .preview-fit (a direct child of the body: MediaGate renders fragments) takes the leftover
|
||||||
|
height. The other children keep theirs: a flex item never shrinks below its content. */
|
||||||
|
.file-preview-modal-content .preview-fit {
|
||||||
|
flex: 1 1 0;
|
||||||
|
height: auto;
|
||||||
|
max-height: none;
|
||||||
|
}
|
||||||
|
|
||||||
/* Fresnel (Media) wraps iframes in a div which would otherwise shrink to the
|
/* Fresnel (Media) wraps iframes in a div which would otherwise shrink to the
|
||||||
default iframe size; make it fill the preview so the iframe's 100% works. */
|
default iframe size; make it fill the preview so the iframe's 100% works. */
|
||||||
.preview-fit .fresnel-container {
|
.preview-fit .fresnel-container {
|
||||||
|
|
@ -316,6 +345,90 @@ pre.wrap-text {
|
||||||
height: 100%;
|
height: 100%;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* A markdown file preview, formatted or raw. Scrolls rather than fitting like .preview-fit, because
|
||||||
|
it is a document to read, not media to frame. Colors come from the theme tokens. */
|
||||||
|
.markdown-preview {
|
||||||
|
height: calc(100dvh - 21rem);
|
||||||
|
min-height: 15rem;
|
||||||
|
overflow: auto;
|
||||||
|
margin-top: 0.5em;
|
||||||
|
padding: 0 0.25em;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* A repo's README is part of its page, not a modal; it grows with its content. */
|
||||||
|
.repo-readme .markdown-preview {
|
||||||
|
height: auto;
|
||||||
|
min-height: 0;
|
||||||
|
overflow: visible;
|
||||||
|
}
|
||||||
|
|
||||||
|
.markdown-raw {
|
||||||
|
margin: 0;
|
||||||
|
white-space: pre-wrap;
|
||||||
|
overflow-wrap: anywhere;
|
||||||
|
}
|
||||||
|
|
||||||
|
.markdown-body {
|
||||||
|
max-width: 50rem;
|
||||||
|
line-height: 1.6;
|
||||||
|
overflow-wrap: break-word;
|
||||||
|
}
|
||||||
|
|
||||||
|
.markdown-body > :first-child {
|
||||||
|
margin-top: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.markdown-body h1, .markdown-body h2 {
|
||||||
|
padding-bottom: 0.25em;
|
||||||
|
border-bottom: 1px solid var(--table-line);
|
||||||
|
}
|
||||||
|
|
||||||
|
.markdown-body img {
|
||||||
|
max-width: 100%;
|
||||||
|
}
|
||||||
|
|
||||||
|
.markdown-body blockquote {
|
||||||
|
margin: 0 0 1em;
|
||||||
|
padding: 0 1em;
|
||||||
|
color: var(--muted);
|
||||||
|
border-left: 0.25em solid var(--border);
|
||||||
|
}
|
||||||
|
|
||||||
|
.markdown-body code {
|
||||||
|
padding: 0.1em 0.3em;
|
||||||
|
border-radius: 0.25em;
|
||||||
|
background-color: var(--head);
|
||||||
|
}
|
||||||
|
|
||||||
|
.markdown-body pre {
|
||||||
|
padding: 0.75em 1em;
|
||||||
|
overflow-x: auto;
|
||||||
|
border-radius: 0.25em;
|
||||||
|
background-color: var(--head);
|
||||||
|
}
|
||||||
|
|
||||||
|
.markdown-body pre code {
|
||||||
|
padding: 0;
|
||||||
|
background-color: transparent;
|
||||||
|
}
|
||||||
|
|
||||||
|
.markdown-body table {
|
||||||
|
display: block;
|
||||||
|
max-width: 100%;
|
||||||
|
overflow-x: auto;
|
||||||
|
border-collapse: collapse;
|
||||||
|
}
|
||||||
|
|
||||||
|
.markdown-body th, .markdown-body td {
|
||||||
|
padding: 0.3em 0.75em;
|
||||||
|
border: 1px solid var(--table-line);
|
||||||
|
}
|
||||||
|
|
||||||
|
.markdown-body hr {
|
||||||
|
border: none;
|
||||||
|
border-top: 1px solid var(--border);
|
||||||
|
}
|
||||||
|
|
||||||
td.file-path {
|
td.file-path {
|
||||||
cursor: pointer;
|
cursor: pointer;
|
||||||
}
|
}
|
||||||
|
|
@ -725,3 +838,35 @@ tr.drag-deselecting td {
|
||||||
display: block;
|
display: block;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* Map popups (POI details and pins) follow the active theme's tokens. */
|
||||||
|
/* Scoped under .maplibregl-popup to outrank maplibre-gl.css, which loads after this file. */
|
||||||
|
.maplibregl-popup .maplibregl-popup-content {
|
||||||
|
background: var(--panel);
|
||||||
|
color: var(--text);
|
||||||
|
border: 1px solid var(--border);
|
||||||
|
border-radius: 0.25rem;
|
||||||
|
}
|
||||||
|
.maplibregl-popup .maplibregl-popup-close-button {
|
||||||
|
color: var(--muted);
|
||||||
|
}
|
||||||
|
.maplibregl-popup .maplibregl-popup-close-button:hover {
|
||||||
|
background: var(--head);
|
||||||
|
color: var(--text);
|
||||||
|
}
|
||||||
|
.maplibregl-popup.maplibregl-popup-anchor-top .maplibregl-popup-tip,
|
||||||
|
.maplibregl-popup.maplibregl-popup-anchor-top-left .maplibregl-popup-tip,
|
||||||
|
.maplibregl-popup.maplibregl-popup-anchor-top-right .maplibregl-popup-tip {
|
||||||
|
border-bottom-color: var(--panel);
|
||||||
|
}
|
||||||
|
.maplibregl-popup.maplibregl-popup-anchor-bottom .maplibregl-popup-tip,
|
||||||
|
.maplibregl-popup.maplibregl-popup-anchor-bottom-left .maplibregl-popup-tip,
|
||||||
|
.maplibregl-popup.maplibregl-popup-anchor-bottom-right .maplibregl-popup-tip {
|
||||||
|
border-top-color: var(--panel);
|
||||||
|
}
|
||||||
|
.maplibregl-popup.maplibregl-popup-anchor-left .maplibregl-popup-tip {
|
||||||
|
border-right-color: var(--panel);
|
||||||
|
}
|
||||||
|
.maplibregl-popup.maplibregl-popup-anchor-right .maplibregl-popup-tip {
|
||||||
|
border-left-color: var(--panel);
|
||||||
|
}
|
||||||
|
|
|
||||||
|
|
@ -4,6 +4,7 @@ import {NavBar} from "./components/Nav";
|
||||||
import {createBrowserRouter, createRoutesFromElements, Link, Outlet, Route, RouterProvider} from "react-router";
|
import {createBrowserRouter, createRoutesFromElements, Link, Outlet, Route, RouterProvider} from "react-router";
|
||||||
import {VideosTabLayout, VideosPage, VideosSettingsPage, VideosStatistics, VideoWrapper} from "./components/Videos";
|
import {VideosTabLayout, VideosPage, VideosSettingsPage, VideosStatistics, VideoWrapper} from "./components/Videos";
|
||||||
import AdminRoute from "./components/admin/AdminRoute";
|
import AdminRoute from "./components/admin/AdminRoute";
|
||||||
|
import {ExtensionRoute} from "./components/admin/ExtensionPage";
|
||||||
import {Box, Header} from "./components/ui";
|
import {Box, Header} from "./components/ui";
|
||||||
import '@mantine/core/styles.css';
|
import '@mantine/core/styles.css';
|
||||||
import '@mantine/notifications/styles.css';
|
import '@mantine/notifications/styles.css';
|
||||||
|
|
@ -15,8 +16,10 @@ import {MoreRoute} from "./components/Apps";
|
||||||
import {InventoryRoute} from "./components/inventory/InventoryRoute";
|
import {InventoryRoute} from "./components/inventory/InventoryRoute";
|
||||||
import {ArchiveRoute} from "./components/Archive";
|
import {ArchiveRoute} from "./components/Archive";
|
||||||
import {FilesRoute} from "./components/Files";
|
import {FilesRoute} from "./components/Files";
|
||||||
|
import {SyncingOverlay} from "./components/admin/Sync";
|
||||||
import {QueryProvider, StatusProvider} from "./hooks/customHooks";
|
import {QueryProvider, StatusProvider} from "./hooks/customHooks";
|
||||||
import {FileWorkerStatusProvider} from "./contexts/FileWorkerStatusContext";
|
import {FileWorkerStatusProvider} from "./contexts/FileWorkerStatusContext";
|
||||||
|
import {BookmarksProvider} from "./contexts/BookmarksContext";
|
||||||
import {ChannelEditPage, ChannelNewPage, ChannelsPage} from "./components/Channels";
|
import {ChannelEditPage, ChannelNewPage, ChannelsPage} from "./components/Channels";
|
||||||
import {MapRoute} from "./components/Map";
|
import {MapRoute} from "./components/Map";
|
||||||
import {MediaContextProvider, mediaStyles, StatusContext} from "./contexts/contexts";
|
import {MediaContextProvider, mediaStyles, StatusContext} from "./contexts/contexts";
|
||||||
|
|
@ -29,6 +32,7 @@ import {FilePreviewProvider} from "./components/FilePreview";
|
||||||
import {TagsProvider} from "./Tags";
|
import {TagsProvider} from "./Tags";
|
||||||
import {ZimRoute} from "./components/Zim";
|
import {ZimRoute} from "./components/Zim";
|
||||||
import {PlaylistsRoute} from "./components/Playlists";
|
import {PlaylistsRoute} from "./components/Playlists";
|
||||||
|
import {ReposRoute} from "./components/Repos";
|
||||||
import {DocsRoute} from "./components/Docs";
|
import {DocsRoute} from "./components/Docs";
|
||||||
import {FlasherRoute} from "./components/Flasher";
|
import {FlasherRoute} from "./components/Flasher";
|
||||||
import ErrorBoundary from "./components/ErrorBoundary";
|
import ErrorBoundary from "./components/ErrorBoundary";
|
||||||
|
|
@ -69,13 +73,16 @@ function Root() {
|
||||||
<TagsProvider>
|
<TagsProvider>
|
||||||
<KeyboardShortcutsProvider>
|
<KeyboardShortcutsProvider>
|
||||||
<FilePreviewProvider>
|
<FilePreviewProvider>
|
||||||
|
<BookmarksProvider>
|
||||||
<header>
|
<header>
|
||||||
<NavBar/>
|
<NavBar/>
|
||||||
</header>
|
</header>
|
||||||
|
<SyncingOverlay/>
|
||||||
<ErrorBoundary>
|
<ErrorBoundary>
|
||||||
<Outlet/>
|
<Outlet/>
|
||||||
</ErrorBoundary>
|
</ErrorBoundary>
|
||||||
<Footer/>
|
<Footer/>
|
||||||
|
</BookmarksProvider>
|
||||||
</FilePreviewProvider>
|
</FilePreviewProvider>
|
||||||
</KeyboardShortcutsProvider>
|
</KeyboardShortcutsProvider>
|
||||||
</TagsProvider>
|
</TagsProvider>
|
||||||
|
|
@ -83,10 +90,12 @@ function Root() {
|
||||||
</QueryProvider>
|
</QueryProvider>
|
||||||
}
|
}
|
||||||
|
|
||||||
const router = createBrowserRouter(createRoutesFromElements(<Route
|
export const routes = createRoutesFromElements(<Route
|
||||||
path='/'
|
path='/'
|
||||||
element={<Root/>}
|
element={<Root/>}
|
||||||
errorElement={<PageNotFound/>}
|
// Root (and its ThemeProvider) is not rendered when Root itself fails, so the error page
|
||||||
|
// brings its own theme; Mantine components cannot render without one.
|
||||||
|
errorElement={<ThemeProvider><PageNotFound/></ThemeProvider>}
|
||||||
>
|
>
|
||||||
<Route index element={<ErrorBoundary><DashboardPage/></ErrorBoundary>}/>
|
<Route index element={<ErrorBoundary><DashboardPage/></ErrorBoundary>}/>
|
||||||
<Route path='search/*' element={<ErrorBoundary><DashboardPage/></ErrorBoundary>}/>
|
<Route path='search/*' element={<ErrorBoundary><DashboardPage/></ErrorBoundary>}/>
|
||||||
|
|
@ -114,9 +123,15 @@ const router = createBrowserRouter(createRoutesFromElements(<Route
|
||||||
<Route path='map/*' element={<ErrorBoundary><MapRoute/></ErrorBoundary>}/>
|
<Route path='map/*' element={<ErrorBoundary><MapRoute/></ErrorBoundary>}/>
|
||||||
<Route path='zim/*' element={<ErrorBoundary><ZimRoute/></ErrorBoundary>}/>
|
<Route path='zim/*' element={<ErrorBoundary><ZimRoute/></ErrorBoundary>}/>
|
||||||
<Route path='playlists/*' element={<ErrorBoundary><PlaylistsRoute/></ErrorBoundary>}/>
|
<Route path='playlists/*' element={<ErrorBoundary><PlaylistsRoute/></ErrorBoundary>}/>
|
||||||
|
<Route path='repos/*' element={<ErrorBoundary><ReposRoute/></ErrorBoundary>}/>
|
||||||
<Route path='files/*' element={<ErrorBoundary><FilesRoute/></ErrorBoundary>}/>
|
<Route path='files/*' element={<ErrorBoundary><FilesRoute/></ErrorBoundary>}/>
|
||||||
<Route path='flasher/*' element={<ErrorBoundary><FlasherRoute/></ErrorBoundary>}/>
|
<Route path='flasher/*' element={<ErrorBoundary><FlasherRoute/></ErrorBoundary>}/>
|
||||||
</Route>));
|
<Route path='extension' element={<ErrorBoundary><ExtensionRoute/></ErrorBoundary>}/>
|
||||||
|
{/* Unknown URLs render inside Root, with the navigation bar and theme. */}
|
||||||
|
<Route path='*' element={<PageNotFound/>}/>
|
||||||
|
</Route>);
|
||||||
|
|
||||||
|
const router = createBrowserRouter(routes);
|
||||||
|
|
||||||
export default function App() {
|
export default function App() {
|
||||||
useEventsInterval();
|
useEventsInterval();
|
||||||
|
|
|
||||||
52
app/src/App.test.js
Normal file
52
app/src/App.test.js
Normal file
|
|
@ -0,0 +1,52 @@
|
||||||
|
import React from 'react';
|
||||||
|
import {render, screen} from '@testing-library/react';
|
||||||
|
import {createMemoryRouter, RouterProvider} from 'react-router';
|
||||||
|
import {routes} from './App';
|
||||||
|
import {StatusProvider} from './hooks/customHooks';
|
||||||
|
import {FileWorkerStatusProvider} from './contexts/FileWorkerStatusContext';
|
||||||
|
import {MediaContextProvider} from './contexts/contexts';
|
||||||
|
|
||||||
|
// Jest does not transform CSS inside node_modules (see transformIgnorePatterns).
|
||||||
|
jest.mock('@mantine/core/styles.css', () => ({}));
|
||||||
|
jest.mock('@mantine/notifications/styles.css', () => ({}));
|
||||||
|
// Routes this test does not visit, whose libraries jsdom/Jest cannot load (maplibre needs
|
||||||
|
// browser APIs; esptool-js is ESM-only).
|
||||||
|
jest.mock('./components/Map', () => ({MapRoute: () => null}));
|
||||||
|
jest.mock('./components/Flasher', () => ({FlasherRoute: () => null}));
|
||||||
|
|
||||||
|
describe('unknown routes', () => {
|
||||||
|
beforeEach(() => {
|
||||||
|
// resetMocks clears setupTests' implementation; the theme and media providers read it.
|
||||||
|
window.matchMedia.mockImplementation(query => ({
|
||||||
|
matches: false,
|
||||||
|
media: query,
|
||||||
|
addListener: jest.fn(),
|
||||||
|
removeListener: jest.fn(),
|
||||||
|
addEventListener: jest.fn(),
|
||||||
|
removeEventListener: jest.fn(),
|
||||||
|
}));
|
||||||
|
global.fetch = jest.fn(() => Promise.resolve({
|
||||||
|
ok: true,
|
||||||
|
status: 200,
|
||||||
|
headers: {get: () => 'application/json'},
|
||||||
|
json: () => Promise.resolve({tags: []}),
|
||||||
|
text: () => Promise.resolve('{}'),
|
||||||
|
}));
|
||||||
|
});
|
||||||
|
|
||||||
|
it('renders Page Not Found inside the app layout', async () => {
|
||||||
|
const router = createMemoryRouter(routes, {initialEntries: ['/no-such-page']});
|
||||||
|
// The providers App wraps around the router.
|
||||||
|
render(<StatusProvider>
|
||||||
|
<FileWorkerStatusProvider>
|
||||||
|
<MediaContextProvider>
|
||||||
|
<RouterProvider router={router}/>
|
||||||
|
</MediaContextProvider>
|
||||||
|
</FileWorkerStatusProvider>
|
||||||
|
</StatusProvider>);
|
||||||
|
|
||||||
|
expect(await screen.findByText('Page Not Found!')).toBeInTheDocument();
|
||||||
|
// Rendered inside Root's layout (the footer comes from Root), not as a bare error page.
|
||||||
|
expect(screen.getByText('Donate')).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
@ -5,8 +5,10 @@ import {
|
||||||
PageContainer,
|
PageContainer,
|
||||||
RefreshHeader,
|
RefreshHeader,
|
||||||
SearchResultsInput,
|
SearchResultsInput,
|
||||||
|
useLocalStorage,
|
||||||
useTitle
|
useTitle
|
||||||
} from "./components/Common";
|
} from "./components/Common";
|
||||||
|
import {SecondaryRoleMessage} from "./components/admin/Sync";
|
||||||
import React, {useContext, useState} from "react";
|
import React, {useContext, useState} from "react";
|
||||||
import {useHotkeys} from "react-hotkeys-hook";
|
import {useHotkeys} from "react-hotkeys-hook";
|
||||||
import {Media, SettingsContext, StatusContext} from "./contexts/contexts";
|
import {Media, SettingsContext, StatusContext} from "./contexts/contexts";
|
||||||
|
|
@ -14,6 +16,7 @@ import {DownloadMenu} from "./components/Download";
|
||||||
import {
|
import {
|
||||||
ActionInput,
|
ActionInput,
|
||||||
Button,
|
Button,
|
||||||
|
ButtonGroup,
|
||||||
Divider,
|
Divider,
|
||||||
Header,
|
Header,
|
||||||
Icon,
|
Icon,
|
||||||
|
|
@ -250,6 +253,8 @@ export function Getters() {
|
||||||
</div>
|
</div>
|
||||||
<span className='wrolpi-or-label'>Or</span>
|
<span className='wrolpi-or-label'>Or</span>
|
||||||
</div>
|
</div>
|
||||||
|
{status?.flags && gettersDisabled &&
|
||||||
|
<p>Download and Upload are available after your files are refreshed.</p>}
|
||||||
</Panel>;
|
</Panel>;
|
||||||
|
|
||||||
let getterModal;
|
let getterModal;
|
||||||
|
|
@ -351,7 +356,14 @@ export function DashboardStatus() {
|
||||||
}
|
}
|
||||||
|
|
||||||
function DashboardRecentFiles() {
|
function DashboardRecentFiles() {
|
||||||
const {searchFiles, loading, fetchFiles} = useSearchRecentFiles();
|
// Show only the files the user is part way through.
|
||||||
|
const [continueOnly, setContinueOnly] = useLocalStorage('dashboard_recent_continue', false);
|
||||||
|
const {searchFiles, loading, fetchFiles} = useSearchRecentFiles(continueOnly);
|
||||||
|
|
||||||
|
let files = <FileCards files={searchFiles} loading={loading}/>;
|
||||||
|
if (continueOnly && searchFiles && searchFiles.length === 0) {
|
||||||
|
files = <p>Nothing in progress. A video, audio file, ebook or comic you stop part way through will be here.</p>;
|
||||||
|
}
|
||||||
|
|
||||||
return <Panel>
|
return <Panel>
|
||||||
<RefreshHeader
|
<RefreshHeader
|
||||||
|
|
@ -359,7 +371,15 @@ function DashboardRecentFiles() {
|
||||||
popupContents='Fetch the most recent files again'
|
popupContents='Fetch the most recent files again'
|
||||||
onRefresh={fetchFiles}
|
onRefresh={fetchFiles}
|
||||||
/>
|
/>
|
||||||
<FileCards files={searchFiles} loading={loading}/>
|
<ButtonGroup>
|
||||||
|
<Button size='small' variant={continueOnly ? 'default' : 'filled'} onClick={() => setContinueOnly(false)}>
|
||||||
|
All
|
||||||
|
</Button>
|
||||||
|
<Button size='small' variant={continueOnly ? 'filled' : 'default'} onClick={() => setContinueOnly(true)}>
|
||||||
|
Continue
|
||||||
|
</Button>
|
||||||
|
</ButtonGroup>
|
||||||
|
<div style={{marginTop: '1em'}}>{files}</div>
|
||||||
</Panel>
|
</Panel>
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -412,18 +432,21 @@ export function DashboardPage() {
|
||||||
} else if (activeTags && activeTags.length > 1) {
|
} else if (activeTags && activeTags.length > 1) {
|
||||||
const tagNames = activeTags.join(' & ');
|
const tagNames = activeTags.join(' & ');
|
||||||
title = `Tags: ${tagNames} - Dashboard`;
|
title = `Tags: ${tagNames} - Dashboard`;
|
||||||
|
} else if (anyTag) {
|
||||||
|
title = 'Any Tag - Dashboard';
|
||||||
}
|
}
|
||||||
useTitle(title);
|
useTitle(title);
|
||||||
|
|
||||||
// Only show dashboard parts if not searching.
|
// Only show dashboard parts if not searching.
|
||||||
let body = <React.Fragment>
|
let body = <React.Fragment>
|
||||||
|
<SecondaryRoleMessage/>
|
||||||
<Getters/>
|
<Getters/>
|
||||||
<TagsDashboard/>
|
<TagsDashboard/>
|
||||||
<DashboardStatus/>
|
<DashboardStatus/>
|
||||||
<DashboardCalculators/>
|
<DashboardCalculators/>
|
||||||
<DashboardRecentFiles/>
|
<DashboardRecentFiles/>
|
||||||
</React.Fragment>;
|
</React.Fragment>;
|
||||||
if (searchStr || (activeTags && activeTags.length > 0)) {
|
if (searchStr || (activeTags && activeTags.length > 0) || anyTag) {
|
||||||
// User has submitted and wants full search.
|
// User has submitted and wants full search.
|
||||||
body = <SearchView suggestions={suggestions} suggestionsSums={suggestionsSums} loading={loading}/>;
|
body = <SearchView suggestions={suggestions} suggestionsSums={suggestionsSums} loading={loading}/>;
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -21,11 +21,11 @@ jest.mock('./hooks/customHooks', () => ({
|
||||||
useWROLMode: () => false,
|
useWROLMode: () => false,
|
||||||
}));
|
}));
|
||||||
|
|
||||||
function renderAtUrl(url) {
|
function renderAtUrl(url, flags = {refresh_complete: true}) {
|
||||||
// test-utils' render() wraps content in a BrowserRouter (not MemoryRouter),
|
// test-utils' render() wraps content in a BrowserRouter (not MemoryRouter),
|
||||||
// so point the jsdom location at the desired URL before rendering.
|
// so point the jsdom location at the desired URL before rendering.
|
||||||
window.history.pushState({}, '', url);
|
window.history.pushState({}, '', url);
|
||||||
const status = {flags: {refresh_complete: true}};
|
const status = {flags};
|
||||||
return render(
|
return render(
|
||||||
<StatusContext.Provider value={{status}}>
|
<StatusContext.Provider value={{status}}>
|
||||||
<Getters/>
|
<Getters/>
|
||||||
|
|
@ -67,6 +67,25 @@ describe('DashboardPage Getters deep-link', () => {
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
describe('DashboardPage Getters before the first refresh', () => {
|
||||||
|
const note = /available after your files are refreshed/i;
|
||||||
|
|
||||||
|
it('explains why Download and Upload are disabled', () => {
|
||||||
|
renderAtUrl('/', {refresh_complete: false});
|
||||||
|
expect(screen.getByText(note)).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('says nothing once the refresh has completed', () => {
|
||||||
|
renderAtUrl('/');
|
||||||
|
expect(screen.queryByText(note)).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('says nothing before the status has loaded', () => {
|
||||||
|
renderAtUrl('/', null);
|
||||||
|
expect(screen.queryByText(note)).toBeNull();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
// The DownloadMenu's seed-object construction (joining initialUrls with
|
// The DownloadMenu's seed-object construction (joining initialUrls with
|
||||||
// newlines into the `download` prop's `urls` field) is exercised in the
|
// newlines into the `download` prop's `urls` field) is exercised in the
|
||||||
// browser via manual verification, not unit-tested here — reaching into the
|
// browser via manual verification, not unit-tested here — reaching into the
|
||||||
|
|
|
||||||
|
|
@ -9,7 +9,7 @@ function eventToast(title, description, type = 'info', time = 5000, onClick = nu
|
||||||
toast({type: type, title: title, description: description, time: time, onClick: onClick});
|
toast({type: type, title: title, description: description, time: time, onClick: onClick});
|
||||||
}
|
}
|
||||||
|
|
||||||
function handleEvents(events) {
|
export function handleEvents(events) {
|
||||||
const newestEvents = {};
|
const newestEvents = {};
|
||||||
|
|
||||||
events.forEach(e => {
|
events.forEach(e => {
|
||||||
|
|
@ -46,6 +46,22 @@ function handleEvents(events) {
|
||||||
eventToast('Downloads Disabled', message);
|
eventToast('Downloads Disabled', message);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (event === 'backup_completed') {
|
||||||
|
eventToast('Backup Completed', message, 'success');
|
||||||
|
}
|
||||||
|
|
||||||
|
if (event === 'backup_failed') {
|
||||||
|
eventToast('Backup Failed', message, 'error');
|
||||||
|
}
|
||||||
|
|
||||||
|
if (event === 'sync_completed') {
|
||||||
|
eventToast('Sync Completed', message, 'success');
|
||||||
|
}
|
||||||
|
|
||||||
|
if (event === 'sync_failed') {
|
||||||
|
eventToast('Sync Failed', message, 'error');
|
||||||
|
}
|
||||||
|
|
||||||
if (event === 'map_import_complete') {
|
if (event === 'map_import_complete') {
|
||||||
eventToast('Map import completed', message, 'success');
|
eventToast('Map import completed', message, 'success');
|
||||||
}
|
}
|
||||||
|
|
@ -63,13 +79,17 @@ function handleEvents(events) {
|
||||||
}
|
}
|
||||||
|
|
||||||
if (event === 'user_notify_message') {
|
if (event === 'user_notify_message') {
|
||||||
console.log(message, url);
|
// Only a shared page carries a URL; other notifications (jobs, transcodes) are text.
|
||||||
|
if (url) {
|
||||||
eventToast(
|
eventToast(
|
||||||
message,
|
message,
|
||||||
'Click here to view the shared page',
|
'Click here to view the shared page',
|
||||||
'info',
|
'info',
|
||||||
10_000,
|
10_000,
|
||||||
() => window.open(url, '_self'));
|
() => window.open(url, '_self'));
|
||||||
|
} else {
|
||||||
|
eventToast(message, null, 'info', 10_000);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (event === 'deleted') {
|
if (event === 'deleted') {
|
||||||
|
|
|
||||||
33
app/src/Events.test.js
Normal file
33
app/src/Events.test.js
Normal file
|
|
@ -0,0 +1,33 @@
|
||||||
|
import {handleEvents} from './Events';
|
||||||
|
import {toast} from './components/ui';
|
||||||
|
|
||||||
|
jest.mock('./components/ui', () => ({toast: jest.fn()}));
|
||||||
|
|
||||||
|
const notify = (url) => ({event: 'user_notify_message', message: 'Transcoding video.mp4', dt: '2026-10-12', url});
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
toast.mockClear();
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('user_notify_message', () => {
|
||||||
|
it('a notification without a URL is plain text, not a link', () => {
|
||||||
|
handleEvents([notify(null)]);
|
||||||
|
|
||||||
|
expect(toast).toHaveBeenCalledTimes(1);
|
||||||
|
const options = toast.mock.calls[0][0];
|
||||||
|
expect(options.title).toBe('Transcoding video.mp4');
|
||||||
|
expect(options.description).toBeFalsy();
|
||||||
|
expect(options.onClick).toBeFalsy();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('a shared page opens its URL when clicked', () => {
|
||||||
|
const open = jest.spyOn(window, 'open').mockImplementation(() => null);
|
||||||
|
handleEvents([notify('/archive/1')]);
|
||||||
|
|
||||||
|
const options = toast.mock.calls[0][0];
|
||||||
|
expect(options.description).toBe('Click here to view the shared page');
|
||||||
|
options.onClick();
|
||||||
|
expect(open).toHaveBeenCalledWith('/archive/1', '_self');
|
||||||
|
open.mockRestore();
|
||||||
|
});
|
||||||
|
});
|
||||||
84
app/src/api.errorAsEmpty.test.js
Normal file
84
app/src/api.errorAsEmpty.test.js
Normal file
|
|
@ -0,0 +1,84 @@
|
||||||
|
import {
|
||||||
|
flasherSearch, getConfigBackups, getDownloaders, getInventoryBackups, getMapSearchStatus, searchMap,
|
||||||
|
} from './api';
|
||||||
|
|
||||||
|
// A helper that fails must say so. These used to turn a non-OK response into an empty value
|
||||||
|
// ([], {dates: []}, {results: []}, ...), so every consumer rendered "nothing here" for a server
|
||||||
|
// error. They now return undefined; an empty value only ever comes from the server.
|
||||||
|
|
||||||
|
jest.mock('./components/ui', () => ({
|
||||||
|
...jest.requireActual('./components/ui'),
|
||||||
|
toast: jest.fn(),
|
||||||
|
}));
|
||||||
|
|
||||||
|
const response = (ok, body = {}) => {
|
||||||
|
const r = {
|
||||||
|
ok,
|
||||||
|
status: ok ? 200 : 500,
|
||||||
|
json: async () => body,
|
||||||
|
text: async () => JSON.stringify(body),
|
||||||
|
};
|
||||||
|
r.clone = () => r;
|
||||||
|
return r;
|
||||||
|
};
|
||||||
|
|
||||||
|
let originalFetch;
|
||||||
|
beforeEach(() => {
|
||||||
|
originalFetch = global.fetch;
|
||||||
|
});
|
||||||
|
afterEach(() => {
|
||||||
|
global.fetch = originalFetch;
|
||||||
|
});
|
||||||
|
|
||||||
|
const failWith = () => {
|
||||||
|
global.fetch = jest.fn(() => Promise.resolve(response(false, {error: 'boom'})));
|
||||||
|
};
|
||||||
|
const succeedWith = (body) => {
|
||||||
|
global.fetch = jest.fn(() => Promise.resolve(response(true, body)));
|
||||||
|
};
|
||||||
|
|
||||||
|
describe('on a non-OK response, the helper returns undefined', () => {
|
||||||
|
test.each([
|
||||||
|
['getConfigBackups', () => getConfigBackups('wrolpi.yaml')],
|
||||||
|
['getInventoryBackups', () => getInventoryBackups('food')],
|
||||||
|
['getDownloaders', () => getDownloaders()],
|
||||||
|
['searchMap', () => searchMap('camp')],
|
||||||
|
['getMapSearchStatus', () => getMapSearchStatus()],
|
||||||
|
['flasherSearch', () => flasherSearch(null, null)],
|
||||||
|
])('%s', async (_name, call) => {
|
||||||
|
failWith();
|
||||||
|
expect(await call()).toBeUndefined();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('a confirmed empty result is still empty', () => {
|
||||||
|
test('getConfigBackups', async () => {
|
||||||
|
succeedWith({dates: []});
|
||||||
|
expect(await getConfigBackups('wrolpi.yaml')).toEqual({dates: []});
|
||||||
|
});
|
||||||
|
|
||||||
|
test('getInventoryBackups', async () => {
|
||||||
|
succeedWith({dates: []});
|
||||||
|
expect(await getInventoryBackups('food')).toEqual([]);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('getDownloaders', async () => {
|
||||||
|
succeedWith({downloaders: []});
|
||||||
|
expect(await getDownloaders()).toEqual({downloaders: []});
|
||||||
|
});
|
||||||
|
|
||||||
|
test('searchMap', async () => {
|
||||||
|
succeedWith({results: [], total: 0});
|
||||||
|
expect(await searchMap('camp')).toEqual({results: [], total: 0});
|
||||||
|
});
|
||||||
|
|
||||||
|
test('getMapSearchStatus', async () => {
|
||||||
|
succeedWith({indexed: [], missing: []});
|
||||||
|
expect(await getMapSearchStatus()).toEqual({indexed: [], missing: []});
|
||||||
|
});
|
||||||
|
|
||||||
|
test('flasherSearch', async () => {
|
||||||
|
succeedWith({file_groups: [], totals: {file_groups: 0}});
|
||||||
|
expect(await flasherSearch(null, null)).toEqual([[], 0]);
|
||||||
|
});
|
||||||
|
});
|
||||||
262
app/src/api.exportMapPdf.test.js
Normal file
262
app/src/api.exportMapPdf.test.js
Normal file
|
|
@ -0,0 +1,262 @@
|
||||||
|
import {ExportCancelled, exportMapPdf} from './api';
|
||||||
|
|
||||||
|
const MAP = {
|
||||||
|
width: 60, height: 90, dpi: 300, title: 'A quadrangle', bounds: [-150, 61.125, -149.875, 61.25],
|
||||||
|
sheet: {name: 'A quadrangle', credits: [], date: '2026-11-15'},
|
||||||
|
layers: [{name: 'Background', blob: new Blob(['background'])}, {name: 'Water', blob: new Blob(['water'])}],
|
||||||
|
};
|
||||||
|
|
||||||
|
const reply = (status, body) => ({
|
||||||
|
ok: status >= 200 && status < 300,
|
||||||
|
status,
|
||||||
|
json: () => Promise.resolve(body),
|
||||||
|
blob: () => Promise.resolve(body),
|
||||||
|
clone() {
|
||||||
|
return this;
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
// A server whose Job says each of `jobs` in turn, and then the last of them.
|
||||||
|
function fakeServer(jobs, {pdf = new Blob(['%PDF-']), replies = {}} = {}) {
|
||||||
|
const calls = [];
|
||||||
|
let asked = 0;
|
||||||
|
global.fetch = jest.fn(async (url, init = {}) => {
|
||||||
|
const path = String(url).replace(/^.*\/api/, '');
|
||||||
|
const method = init.method || 'GET';
|
||||||
|
calls.push(`${method} ${path}`);
|
||||||
|
if (replies[`${method} ${path}`]) return replies[`${method} ${path}`]();
|
||||||
|
if (path === '/map/export') return reply(201, {export_id: 'abc'});
|
||||||
|
if (path.startsWith('/map/export/abc/layer/')) return reply(204, null);
|
||||||
|
if (path === '/map/export/abc/start') return reply(202, {job_id: 'job-1'});
|
||||||
|
if (path === '/map/export/abc' && method === 'DELETE') return reply(204, null);
|
||||||
|
if (path === '/jobs/job-1') return reply(200, {job: jobs[Math.min(asked++, jobs.length - 1)]});
|
||||||
|
if (path === '/map/export/abc/pdf') return reply(200, pdf);
|
||||||
|
return reply(404, {error: 'Not found'});
|
||||||
|
});
|
||||||
|
return calls;
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('exportMapPdf', () => {
|
||||||
|
afterEach(() => {
|
||||||
|
delete global.fetch;
|
||||||
|
});
|
||||||
|
|
||||||
|
test('describes the map, sends each layer, watches the Job, and fetches the PDF', async () => {
|
||||||
|
const pdf = new Blob(['%PDF-']);
|
||||||
|
const calls = fakeServer([
|
||||||
|
{status: 'pending'}, {status: 'running', progress: 12.4}, {status: 'running', progress: 75},
|
||||||
|
{status: 'complete'},
|
||||||
|
], {pdf});
|
||||||
|
const statuses = [];
|
||||||
|
|
||||||
|
const result = await exportMapPdf(MAP, {onStatus: text => statuses.push(text), pollMs: 0});
|
||||||
|
|
||||||
|
expect(result).toBe(pdf);
|
||||||
|
expect(calls).toEqual([
|
||||||
|
'POST /map/export',
|
||||||
|
'POST /map/export/abc/layer/0',
|
||||||
|
'POST /map/export/abc/layer/1',
|
||||||
|
'POST /map/export/abc/start',
|
||||||
|
'GET /jobs/job-1', 'GET /jobs/job-1', 'GET /jobs/job-1', 'GET /jobs/job-1',
|
||||||
|
'GET /map/export/abc/pdf',
|
||||||
|
// With the PDF in hand, the server need keep nothing of the export.
|
||||||
|
'DELETE /map/export/abc',
|
||||||
|
]);
|
||||||
|
expect(statuses).toEqual([
|
||||||
|
'Sending the map…',
|
||||||
|
'Sending Background (1 of 2)…',
|
||||||
|
'Sending Water (2 of 2)…',
|
||||||
|
'Starting the PDF…',
|
||||||
|
'Making the PDF (12%)…',
|
||||||
|
'Making the PDF (75%)…',
|
||||||
|
'Fetching the PDF…',
|
||||||
|
]);
|
||||||
|
// The map is described without its images, and each image is sent as it is.
|
||||||
|
const [, described] = global.fetch.mock.calls[0];
|
||||||
|
expect(JSON.parse(described.body)).toEqual({
|
||||||
|
width: 60, height: 90, dpi: 300, title: 'A quadrangle', bounds: MAP.bounds, sheet: MAP.sheet,
|
||||||
|
layers: ['Background', 'Water'],
|
||||||
|
});
|
||||||
|
expect(global.fetch.mock.calls[2][1].body).toBe(MAP.layers[1].blob);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('says it is waiting when another job is in the way', async () => {
|
||||||
|
fakeServer([...Array(5).fill({status: 'pending'}), {status: 'complete'}]);
|
||||||
|
const statuses = [];
|
||||||
|
await exportMapPdf(MAP, {onStatus: text => statuses.push(text), pollMs: 0});
|
||||||
|
expect(statuses.slice(3)).toEqual([
|
||||||
|
'Starting the PDF…', 'Starting the PDF…', 'Starting the PDF…',
|
||||||
|
'Waiting for another job to finish…', 'Waiting for another job to finish…',
|
||||||
|
'Fetching the PDF…',
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('says why the map was refused', async () => {
|
||||||
|
fakeServer([], {replies: {'POST /map/export': () => reply(400, {error: 'A map of 0x0 pixels can not be exported'})}});
|
||||||
|
await expect(exportMapPdf(MAP, {pollMs: 0})).rejects.toThrow('A map of 0x0 pixels can not be exported');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('gives the PDF without waiting for the server to remove the export', async () => {
|
||||||
|
const pdf = new Blob(['%PDF-']);
|
||||||
|
const calls = fakeServer([{status: 'complete'}], {
|
||||||
|
// The server never answers.
|
||||||
|
pdf, replies: {'DELETE /map/export/abc': () => new Promise(() => undefined)},
|
||||||
|
});
|
||||||
|
expect(await exportMapPdf(MAP, {pollMs: 0})).toBe(pdf);
|
||||||
|
expect(calls.at(-1)).toBe('DELETE /map/export/abc');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('has the server remove what was sent when the export fails', async () => {
|
||||||
|
const calls = fakeServer([{status: 'complete'}], {
|
||||||
|
replies: {'POST /map/export/abc/layer/1': () => Promise.reject(new Error('network'))},
|
||||||
|
});
|
||||||
|
await expect(exportMapPdf(MAP, {pollMs: 0})).rejects.toThrow('Could not reach the server');
|
||||||
|
expect(calls.at(-1)).toBe('DELETE /map/export/abc');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('says why the Job failed', async () => {
|
||||||
|
const calls = fakeServer([{status: 'running', progress: 0}, {status: 'failed', error: 'The layer is 10x10'}]);
|
||||||
|
await expect(exportMapPdf(MAP, {pollMs: 0})).rejects.toThrow('The layer is 10x10');
|
||||||
|
expect(calls).not.toContain('GET /map/export/abc/pdf');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('stops before anything is sent when it was already cancelled', async () => {
|
||||||
|
const calls = fakeServer([{status: 'complete'}]);
|
||||||
|
await expect(exportMapPdf(MAP, {isCancelled: () => true})).rejects.toBeInstanceOf(ExportCancelled);
|
||||||
|
expect(calls).toEqual([]);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('has the server remove what was sent when it is stopped while layers are sent', async () => {
|
||||||
|
const calls = fakeServer([{status: 'complete'}]);
|
||||||
|
// Stopped once the first layer has been sent.
|
||||||
|
const rejected = exportMapPdf(MAP, {pollMs: 0, isCancelled: () => calls.includes('POST /map/export/abc/layer/0')});
|
||||||
|
await expect(rejected).rejects.toBeInstanceOf(ExportCancelled);
|
||||||
|
expect(calls).toEqual(['POST /map/export', 'POST /map/export/abc/layer/0', 'DELETE /map/export/abc']);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('has the server stop the export when it is stopped while the PDF is made', async () => {
|
||||||
|
const calls = fakeServer([{status: 'running', progress: 10}]);
|
||||||
|
let polls = 0;
|
||||||
|
const rejected = exportMapPdf(MAP, {
|
||||||
|
pollMs: 0,
|
||||||
|
// Stopped once the Job has been asked about twice.
|
||||||
|
isCancelled: () => calls.includes('GET /jobs/job-1') && ++polls > 2,
|
||||||
|
});
|
||||||
|
await expect(rejected).rejects.toMatchObject({cancelled: true});
|
||||||
|
// The server cancels the Job of an export which is removed.
|
||||||
|
expect(calls.at(-1)).toBe('DELETE /map/export/abc');
|
||||||
|
expect(calls).not.toContain('GET /map/export/abc/pdf');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('is stopped all the same when the server can not be told', async () => {
|
||||||
|
const calls = fakeServer([{status: 'running', progress: 10}], {
|
||||||
|
replies: {'DELETE /map/export/abc': () => Promise.reject(new Error('network'))},
|
||||||
|
});
|
||||||
|
const rejected = exportMapPdf(MAP, {pollMs: 0, isCancelled: () => calls.includes('GET /jobs/job-1')});
|
||||||
|
await expect(rejected).rejects.toBeInstanceOf(ExportCancelled);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('is stopped in the middle of a request, which the server may never answer', async () => {
|
||||||
|
const abort = new AbortController();
|
||||||
|
let signals = [];
|
||||||
|
const calls = fakeServer([{status: 'complete'}], {
|
||||||
|
replies: {
|
||||||
|
// A layer which is never taken: the request ends when it is stopped, as fetch's does.
|
||||||
|
'POST /map/export/abc/layer/1': () => new Promise((resolve, reject) => {
|
||||||
|
signals = global.fetch.mock.calls.map(([, init]) => init?.signal);
|
||||||
|
abort.signal.addEventListener(
|
||||||
|
'abort', () => reject(Object.assign(new Error('aborted'), {name: 'AbortError'})));
|
||||||
|
abort.abort();
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
});
|
||||||
|
const rejected = exportMapPdf(MAP, {pollMs: 0, signal: abort.signal});
|
||||||
|
await expect(rejected).rejects.toBeInstanceOf(ExportCancelled);
|
||||||
|
// Every request of the export could be stopped; the one which removes it can not.
|
||||||
|
expect(signals).toEqual([abort.signal, abort.signal, abort.signal]);
|
||||||
|
expect(calls.at(-1)).toBe('DELETE /map/export/abc');
|
||||||
|
expect(global.fetch.mock.calls.at(-1)[1].signal).toBeUndefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
test.each([
|
||||||
|
['the Job is asked after', 'GET /jobs/job-1'],
|
||||||
|
['the PDF is fetched', 'GET /map/export/abc/pdf'],
|
||||||
|
])('is stopped in the middle of a request while %s', async (_, request) => {
|
||||||
|
const abort = new AbortController();
|
||||||
|
const calls = fakeServer([{status: 'complete'}], {
|
||||||
|
replies: {
|
||||||
|
[request]: () => new Promise((resolve, reject) => {
|
||||||
|
abort.signal.addEventListener(
|
||||||
|
'abort', () => reject(Object.assign(new Error('aborted'), {name: 'AbortError'})));
|
||||||
|
abort.abort();
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
});
|
||||||
|
await expect(exportMapPdf(MAP, {pollMs: 0, signal: abort.signal})).rejects.toBeInstanceOf(ExportCancelled);
|
||||||
|
// Every request up to the one which was stopped, and that one, could be stopped.
|
||||||
|
const stoppable = global.fetch.mock.calls.slice(0, -1).map(([, init]) => init?.signal);
|
||||||
|
expect(stoppable).toHaveLength(calls.indexOf(request) + 1);
|
||||||
|
expect(stoppable.every(signal => signal === abort.signal)).toBe(true);
|
||||||
|
// It is not asked again once it is stopped; the server is only told to remove the export.
|
||||||
|
expect(calls.filter(call => call === request)).toHaveLength(1);
|
||||||
|
expect(calls.at(-1)).toBe('DELETE /map/export/abc');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a Job which someone else cancelled is a cancelled export', async () => {
|
||||||
|
fakeServer([{status: 'cancelled'}]);
|
||||||
|
await expect(exportMapPdf(MAP, {pollMs: 0})).rejects.toBeInstanceOf(ExportCancelled);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('keeps asking when the server does not answer for a moment', async () => {
|
||||||
|
let failures = 3;
|
||||||
|
const calls = fakeServer([{status: 'complete'}], {
|
||||||
|
replies: {
|
||||||
|
'GET /jobs/job-1': () => {
|
||||||
|
if (failures-- > 0) return Promise.reject(new Error('network'));
|
||||||
|
return reply(200, {job: {status: 'complete'}});
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
await exportMapPdf(MAP, {pollMs: 0});
|
||||||
|
expect(calls.filter(i => i === 'GET /jobs/job-1')).toHaveLength(4);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('asks for the PDF again when the request is lost, and not when it is refused', async () => {
|
||||||
|
const pdf = new Blob(['%PDF-']);
|
||||||
|
let lost = 3;
|
||||||
|
let calls = fakeServer([{status: 'complete'}], {
|
||||||
|
replies: {
|
||||||
|
'GET /map/export/abc/pdf': () => {
|
||||||
|
if (lost === 3) { lost--; return Promise.reject(new Error('network')); }
|
||||||
|
if (lost-- > 0) return reply(502, {error: 'Bad gateway'});
|
||||||
|
return reply(200, pdf);
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
expect(await exportMapPdf(MAP, {pollMs: 0})).toBe(pdf);
|
||||||
|
expect(calls.filter(i => i === 'GET /map/export/abc/pdf')).toHaveLength(4);
|
||||||
|
// The map was drawn, sent and made into a PDF once.
|
||||||
|
expect(calls.filter(i => i === 'POST /map/export/abc/start')).toHaveLength(1);
|
||||||
|
|
||||||
|
calls = fakeServer([{status: 'complete'}], {
|
||||||
|
replies: {'GET /map/export/abc/pdf': () => reply(409, {error: 'The PDF is gone'})},
|
||||||
|
});
|
||||||
|
await expect(exportMapPdf(MAP, {pollMs: 0})).rejects.toThrow('The PDF is gone');
|
||||||
|
expect(calls.filter(i => i === 'GET /map/export/abc/pdf')).toHaveLength(1);
|
||||||
|
|
||||||
|
calls = fakeServer([{status: 'complete'}], {
|
||||||
|
replies: {'GET /map/export/abc/pdf': () => Promise.reject(new Error('network'))},
|
||||||
|
});
|
||||||
|
await expect(exportMapPdf(MAP, {pollMs: 0})).rejects.toThrow('Could not fetch the PDF');
|
||||||
|
expect(calls.filter(i => i === 'GET /map/export/abc/pdf')).toHaveLength(10);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('gives up when the server stops answering, or has forgotten the Job', async () => {
|
||||||
|
fakeServer([], {replies: {'GET /jobs/job-1': () => Promise.reject(new Error('network'))}});
|
||||||
|
await expect(exportMapPdf(MAP, {pollMs: 0})).rejects.toThrow('Could not reach the server');
|
||||||
|
expect(global.fetch.mock.calls.filter(([url]) => String(url).endsWith('/jobs/job-1'))).toHaveLength(10);
|
||||||
|
|
||||||
|
fakeServer([], {replies: {'GET /jobs/job-1': () => reply(404, {error: 'unknown'})}});
|
||||||
|
await expect(exportMapPdf(MAP, {pollMs: 0})).rejects.toThrow('The server forgot the export');
|
||||||
|
});
|
||||||
|
});
|
||||||
32
app/src/api.getSettings.test.js
Normal file
32
app/src/api.getSettings.test.js
Normal file
|
|
@ -0,0 +1,32 @@
|
||||||
|
import {getSettings} from './api';
|
||||||
|
import {settingsFixture} from './test-fixtures';
|
||||||
|
|
||||||
|
describe('getSettings', () => {
|
||||||
|
afterEach(() => {
|
||||||
|
delete global.fetch;
|
||||||
|
});
|
||||||
|
|
||||||
|
it('keeps every setting the API sends', async () => {
|
||||||
|
// getSettings copies each field by name, so a field the API added but nobody listed here vanished
|
||||||
|
// silently (the Sync tab showed no backup drive while one was configured).
|
||||||
|
const sent = settingsFixture({
|
||||||
|
backup_directory: '/media/wrolpi_backup', backup_device_uuid: 'uuid-backup',
|
||||||
|
role: 'secondary', sync_primary_url: 'https://10.0.0.5', sync_window_start: '01:00',
|
||||||
|
sync_window_end: '05:00',
|
||||||
|
});
|
||||||
|
global.fetch = jest.fn(() => Promise.resolve({
|
||||||
|
ok: true, status: 200,
|
||||||
|
json: () => Promise.resolve(sent),
|
||||||
|
clone() {
|
||||||
|
return this;
|
||||||
|
},
|
||||||
|
}));
|
||||||
|
|
||||||
|
const settings = await getSettings();
|
||||||
|
|
||||||
|
const dropped = Object.keys(sent).filter(key => !(key in settings));
|
||||||
|
expect(dropped).toEqual([]);
|
||||||
|
expect(settings.backup_directory).toBe('/media/wrolpi_backup');
|
||||||
|
expect(settings.backup_device_uuid).toBe('uuid-backup');
|
||||||
|
});
|
||||||
|
});
|
||||||
637
app/src/api.js
637
app/src/api.js
|
|
@ -7,6 +7,7 @@ import {
|
||||||
COLLECTIONS_API,
|
COLLECTIONS_API,
|
||||||
DEFAULT_LIMIT,
|
DEFAULT_LIMIT,
|
||||||
Downloaders,
|
Downloaders,
|
||||||
|
REPOS_API,
|
||||||
VIDEOS_API,
|
VIDEOS_API,
|
||||||
ZIM_API
|
ZIM_API
|
||||||
} from "./components/Vars";
|
} from "./components/Vars";
|
||||||
|
|
@ -57,8 +58,8 @@ async function apiCall(url, method, body, ms = 60_000) {
|
||||||
// Request encountered an error.
|
// Request encountered an error.
|
||||||
let copy = response.clone();
|
let copy = response.clone();
|
||||||
const content = await copy.json();
|
const content = await copy.json();
|
||||||
console.error('API error response json', content);
|
|
||||||
const code = content['code'];
|
const code = content['code'];
|
||||||
|
console.error('API error response json', content);
|
||||||
if (response.status === 403 && code === 'WROL_MODE_ENABLED') {
|
if (response.status === 403 && code === 'WROL_MODE_ENABLED') {
|
||||||
toast({
|
toast({
|
||||||
type: 'error',
|
type: 'error',
|
||||||
|
|
@ -187,7 +188,7 @@ export async function tagChannelInfo(channelId, tagName) {
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function searchVideos(offset, limit, channelId, searchStr, order_by, tagNames, headline, censored, deep) {
|
export async function searchVideos(offset, limit, channelId, searchStr, order_by, tagNames, headline, censored, deep, anyTag) {
|
||||||
// Build a search query to retrieve a list of videos from the API
|
// Build a search query to retrieve a list of videos from the API
|
||||||
offset = parseInt(offset || 0);
|
offset = parseInt(offset || 0);
|
||||||
limit = parseInt(limit || DEFAULT_LIMIT);
|
limit = parseInt(limit || DEFAULT_LIMIT);
|
||||||
|
|
@ -211,6 +212,9 @@ export async function searchVideos(offset, limit, channelId, searchStr, order_by
|
||||||
if (deep) {
|
if (deep) {
|
||||||
body['deep'] = true;
|
body['deep'] = true;
|
||||||
}
|
}
|
||||||
|
if (anyTag) {
|
||||||
|
body['any_tag'] = true;
|
||||||
|
}
|
||||||
|
|
||||||
console.debug('searching videos', body);
|
console.debug('searching videos', body);
|
||||||
|
|
||||||
|
|
@ -383,6 +387,12 @@ export async function getSettings() {
|
||||||
const content = await response.json();
|
const content = await response.json();
|
||||||
return {
|
return {
|
||||||
archive_destination: content.archive_destination,
|
archive_destination: content.archive_destination,
|
||||||
|
backup_delete_after_days: content.backup_delete_after_days,
|
||||||
|
backup_device_uuid: content.backup_device_uuid,
|
||||||
|
backup_directory: content.backup_directory,
|
||||||
|
backup_excluded_directories: content.backup_excluded_directories,
|
||||||
|
backup_window_end: content.backup_window_end,
|
||||||
|
backup_window_start: content.backup_window_start,
|
||||||
download_manager_disabled: content.download_manager_disabled,
|
download_manager_disabled: content.download_manager_disabled,
|
||||||
download_manager_stopped: content.download_manager_stopped,
|
download_manager_stopped: content.download_manager_stopped,
|
||||||
download_daily_limit_global: content.download_daily_limit_global,
|
download_daily_limit_global: content.download_daily_limit_global,
|
||||||
|
|
@ -406,13 +416,21 @@ export async function getSettings() {
|
||||||
nav_color: content.nav_color,
|
nav_color: content.nav_color,
|
||||||
media_directory: content.media_directory,
|
media_directory: content.media_directory,
|
||||||
playlists_destination: content.playlists_destination,
|
playlists_destination: content.playlists_destination,
|
||||||
|
repos_destination: content.repos_destination,
|
||||||
require_cookies_unlocked: content.require_cookies_unlocked,
|
require_cookies_unlocked: content.require_cookies_unlocked,
|
||||||
require_media_mounted: content.require_media_mounted,
|
require_media_mounted: content.require_media_mounted,
|
||||||
|
role: content.role,
|
||||||
save_ffprobe_json: content.save_ffprobe_json,
|
save_ffprobe_json: content.save_ffprobe_json,
|
||||||
|
sync_delete_after_days: content.sync_delete_after_days,
|
||||||
|
sync_excluded_directories: content.sync_excluded_directories,
|
||||||
|
sync_primary_url: content.sync_primary_url,
|
||||||
|
sync_window_end: content.sync_window_end,
|
||||||
|
sync_window_start: content.sync_window_start,
|
||||||
tags_directory: content.tags_directory,
|
tags_directory: content.tags_directory,
|
||||||
throttle_on_startup: content.throttle_on_startup,
|
throttle_on_startup: content.throttle_on_startup,
|
||||||
throttle_status: content.throttle_status,
|
throttle_status: content.throttle_status,
|
||||||
timezone: content.timezone,
|
timezone: content.timezone,
|
||||||
|
version: content.version,
|
||||||
videos_destination: content.videos_destination,
|
videos_destination: content.videos_destination,
|
||||||
wrol_mode: content.wrol_mode,
|
wrol_mode: content.wrol_mode,
|
||||||
zims_destination: content.zims_destination,
|
zims_destination: content.zims_destination,
|
||||||
|
|
@ -428,6 +446,57 @@ export async function getSettings() {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Sync: a secondary WROLPi copies its library from its primary.
|
||||||
|
|
||||||
|
export async function saveSyncSettings(settings) {
|
||||||
|
const response = await apiPut(`${API_URI}/sync/settings`, settings);
|
||||||
|
if (!response.ok) {
|
||||||
|
const message = await getErrorMessage(response, 'Could not save sync settings.');
|
||||||
|
toast({type: 'error', title: 'Saving Sync Settings Failed', description: message, time: 5000});
|
||||||
|
}
|
||||||
|
return response;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class PrimaryUnreachableError extends Error {
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The folders directly inside `path`; `source` is 'local' (this WROLPi) or 'primary' (its primary). */
|
||||||
|
export async function getSyncDirectories(path, source) {
|
||||||
|
const response = await apiPost(`${API_URI}/sync/directories`, {path: path || '', source});
|
||||||
|
if (response.ok) {
|
||||||
|
const {directories} = await response.json();
|
||||||
|
return directories;
|
||||||
|
}
|
||||||
|
if (response.status === 502) {
|
||||||
|
const {error} = await response.json();
|
||||||
|
throw new PrimaryUnreachableError(error || 'The primary did not answer');
|
||||||
|
}
|
||||||
|
const message = await getErrorMessage(response, 'Could not list the folders.');
|
||||||
|
throw new Error(message);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function runBackup() {
|
||||||
|
const response = await apiPost(`${API_URI}/sync/backup/run`);
|
||||||
|
if (!response.ok) {
|
||||||
|
const message = await getErrorMessage(response, 'Could not start the backup.');
|
||||||
|
toast({type: 'error', title: 'Backup Failed', description: message, time: 5000});
|
||||||
|
}
|
||||||
|
return response;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function cancelBackup() {
|
||||||
|
return await apiPost(`${API_URI}/sync/backup/cancel`);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function testSync() {
|
||||||
|
const response = await apiGet(`${API_URI}/sync/test`);
|
||||||
|
if (response.ok) {
|
||||||
|
return await response.json();
|
||||||
|
}
|
||||||
|
const message = await getErrorMessage(response, 'Could not reach the primary.');
|
||||||
|
return {ok: false, error: message};
|
||||||
|
}
|
||||||
|
|
||||||
export async function saveSettings(settings) {
|
export async function saveSettings(settings) {
|
||||||
const response = await apiPatch(`${API_URI}/settings`, settings);
|
const response = await apiPatch(`${API_URI}/settings`, settings);
|
||||||
if (!response.ok) {
|
if (!response.ok) {
|
||||||
|
|
@ -522,7 +591,7 @@ export async function getConfigBackups(fileName) {
|
||||||
if (response.ok) {
|
if (response.ok) {
|
||||||
return await response.json();
|
return await response.json();
|
||||||
}
|
}
|
||||||
return {dates: []};
|
// Undefined, not {dates: []}, so the modal can tell a failed fetch from having no backups.
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function postConfigBackupPreview(fileName, backupDate, mode) {
|
export async function postConfigBackupPreview(fileName, backupDate, mode) {
|
||||||
|
|
@ -720,7 +789,7 @@ export async function getInventoryBackups(slug) {
|
||||||
if (response.ok) {
|
if (response.ok) {
|
||||||
return (await response.json())['dates'];
|
return (await response.json())['dates'];
|
||||||
}
|
}
|
||||||
return [];
|
// Undefined, not [], so the modal can tell a failed fetch from having no backups.
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function postInventoryRestorePreview(slug, backupDate, mode) {
|
export async function postInventoryRestorePreview(slug, backupDate, mode) {
|
||||||
|
|
@ -767,7 +836,7 @@ export async function saveCatalog(items) {
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
export async function searchArchives(offset, limit, domain, searchStr, order, tagNames, headline, deep) {
|
export async function searchArchives(offset, limit, domain, searchStr, order, tagNames, headline, deep, anyTag) {
|
||||||
// Build a search query to retrieve a list of videos from the API
|
// Build a search query to retrieve a list of videos from the API
|
||||||
offset = parseInt(offset || 0);
|
offset = parseInt(offset || 0);
|
||||||
limit = parseInt(limit || DEFAULT_LIMIT);
|
limit = parseInt(limit || DEFAULT_LIMIT);
|
||||||
|
|
@ -790,6 +859,9 @@ export async function searchArchives(offset, limit, domain, searchStr, order, ta
|
||||||
if (deep) {
|
if (deep) {
|
||||||
body['deep'] = true;
|
body['deep'] = true;
|
||||||
}
|
}
|
||||||
|
if (anyTag) {
|
||||||
|
body['any_tag'] = true;
|
||||||
|
}
|
||||||
|
|
||||||
console.debug('searching archives', body);
|
console.debug('searching archives', body);
|
||||||
const response = await apiPost(`${ARCHIVES_API}/search`, body);
|
const response = await apiPost(`${ARCHIVES_API}/search`, body);
|
||||||
|
|
@ -927,6 +999,21 @@ export async function getCollectionTagInfo(collectionId, tagName) {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Tag any Collection (and optionally move its directory).
|
||||||
|
export async function tagCollection(collectionId, tagName, directory) {
|
||||||
|
const body = {tag_name: tagName};
|
||||||
|
if (directory) {
|
||||||
|
body['directory'] = directory;
|
||||||
|
}
|
||||||
|
const response = await apiPost(`${COLLECTIONS_API}/${collectionId}/tag`, body);
|
||||||
|
if (response.ok) {
|
||||||
|
return await response.json();
|
||||||
|
}
|
||||||
|
const message = await getErrorMessage(response, 'Unable to tag. See server logs.');
|
||||||
|
toast({type: 'error', title: 'Tag Error', description: message, time: 5000});
|
||||||
|
throw new Error(message);
|
||||||
|
}
|
||||||
|
|
||||||
export async function tagDomain(domainId, tagName, directory) {
|
export async function tagDomain(domainId, tagName, directory) {
|
||||||
const body = {
|
const body = {
|
||||||
tag_name: tagName,
|
tag_name: tagName,
|
||||||
|
|
@ -1259,12 +1346,15 @@ export async function startDownloads() {
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function getDownloaders() {
|
export async function getDownloaders() {
|
||||||
|
// Not toasting because this will happen often. Undefined on any failure, not an empty list, so
|
||||||
|
// the form can say the downloaders could not be fetched.
|
||||||
try {
|
try {
|
||||||
const response = await apiGet(`${API_URI}/downloaders`);
|
const response = await apiGet(`${API_URI}/downloaders`);
|
||||||
// Not toasting because this will happen often.
|
if (response.ok) {
|
||||||
return await response.json();
|
return await response.json();
|
||||||
|
}
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
return {downloaders: []};
|
// The API is down; reported as undefined below.
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -1285,7 +1375,7 @@ export async function deleteDownload(downloadId) {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function filesSearch(offset, limit, searchStr, mimetypes, model, tagNames, headline, months, fromYear, toYear, anyTag, order, suffix, path, deep) {
|
export async function filesSearch(offset, limit, searchStr, mimetypes, model, tagNames, headline, months, fromYear, toYear, anyTag, order, suffix, path, deep, inProgress) {
|
||||||
const body = {search_str: searchStr, offset: parseInt(offset), limit: parseInt(limit), any_tag: anyTag};
|
const body = {search_str: searchStr, offset: parseInt(offset), limit: parseInt(limit), any_tag: anyTag};
|
||||||
if (suffix) {
|
if (suffix) {
|
||||||
body['suffix'] = suffix;
|
body['suffix'] = suffix;
|
||||||
|
|
@ -1320,6 +1410,9 @@ export async function filesSearch(offset, limit, searchStr, mimetypes, model, ta
|
||||||
if (deep) {
|
if (deep) {
|
||||||
body['deep'] = true;
|
body['deep'] = true;
|
||||||
}
|
}
|
||||||
|
if (inProgress) {
|
||||||
|
body['in_progress'] = true;
|
||||||
|
}
|
||||||
console.info('searching files', body);
|
console.info('searching files', body);
|
||||||
const response = await apiPost(`${API_URI}/files/search`, body);
|
const response = await apiPost(`${API_URI}/files/search`, body);
|
||||||
|
|
||||||
|
|
@ -1351,7 +1444,7 @@ export async function flasherSearch(chip, path) {
|
||||||
}
|
}
|
||||||
const message = await getErrorMessage(response, 'Cannot search firmware. See server logs.');
|
const message = await getErrorMessage(response, 'Cannot search firmware. See server logs.');
|
||||||
toast({type: 'error', title: 'Unable to search firmware', description: message, time: 5000});
|
toast({type: 'error', title: 'Unable to search firmware', description: message, time: 5000});
|
||||||
return [null, null];
|
// Undefined, not [null, null], so the picker can tell a failed search from finding nothing.
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function getFlasherConfigs() {
|
export async function getFlasherConfigs() {
|
||||||
|
|
@ -1361,7 +1454,9 @@ export async function getFlasherConfigs() {
|
||||||
const data = await response.json();
|
const data = await response.json();
|
||||||
return data['configurations'] || [];
|
return data['configurations'] || [];
|
||||||
}
|
}
|
||||||
return [];
|
// Undefined, not [], so the page can tell a failed fetch from an empty list.
|
||||||
|
const message = await getErrorMessage(response, 'Could not get saved firmware configurations');
|
||||||
|
toast({type: 'error', title: 'Flasher Error', description: message, time: 5000});
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function saveFlasherConfig(name, files, eraseAll) {
|
export async function saveFlasherConfig(name, files, eraseAll) {
|
||||||
|
|
@ -1565,14 +1660,28 @@ export async function getMapFiles() {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function deleteMapFile(filename) {
|
// A map file is named by its path within the map directory; it may be in a sub-directory.
|
||||||
const response = await apiDelete(`${API_URI}/map/files/${encodeURIComponent(filename)}`);
|
function encodeMapPath(mapPath) {
|
||||||
|
return String(mapPath).split('/').map(encodeURIComponent).join('/');
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function deleteMapFile(mapPath) {
|
||||||
|
const response = await apiDelete(`${API_URI}/map/files/${encodeMapPath(mapPath)}`);
|
||||||
if (!response.ok) {
|
if (!response.ok) {
|
||||||
const message = await getErrorMessage(response, 'Could not delete map file');
|
const message = await getErrorMessage(response, 'Could not delete map file');
|
||||||
toast({type: 'error', title: 'Map Error', description: message, time: 5000});
|
toast({type: 'error', title: 'Map Error', description: message, time: 5000});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Show a map file on the map, or ignore it.
|
||||||
|
export async function setMapFileVisible(mapPath, visible) {
|
||||||
|
const response = await apiPost(`${API_URI}/map/files/visible`, {map_path: mapPath, visible});
|
||||||
|
if (!response.ok) {
|
||||||
|
const message = await getErrorMessage(response, 'Could not change the map file');
|
||||||
|
toast({type: 'error', title: 'Map Error', description: message, time: 5000});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
export async function fetchMapSubscriptions() {
|
export async function fetchMapSubscriptions() {
|
||||||
const response = await apiGet(`${API_URI}/map/subscribe`);
|
const response = await apiGet(`${API_URI}/map/subscribe`);
|
||||||
if (response.ok) {
|
if (response.ok) {
|
||||||
|
|
@ -1603,6 +1712,88 @@ export async function mapUnsubscribe(region) {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Which months of the fallout climatology are kept: {version, months, missing, published}, or null.
|
||||||
|
export async function getFalloutClimatology() {
|
||||||
|
const response = await apiGet(`${API_URI}/map/fallout/climatology`);
|
||||||
|
return response.ok ? await response.json() : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
// One month of the fallout climatology, as kept (gzip bytes), or null.
|
||||||
|
export async function getFalloutClimatologyMonth(month) {
|
||||||
|
const response = await apiGet(`${API_URI}/map/fallout/climatology/${month}`);
|
||||||
|
return response.ok ? await response.arrayBuffer() : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
// The field of forecast winds aloft fetched most recently (the fallout simulator), or null.
|
||||||
|
export async function getLatestFalloutWinds() {
|
||||||
|
const response = await apiGet(`${API_URI}/map/fallout/winds/latest`);
|
||||||
|
if (response.ok) {
|
||||||
|
return (await response.json()).winds;
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
// The saved nuclear targets ([{id, lat, lon, label, created, weapon, yield_kt?, fission_fraction?}]), or
|
||||||
|
// undefined when they could not be fetched.
|
||||||
|
export async function getMapTargets() {
|
||||||
|
const response = await apiGet(`${API_URI}/map/nuclear/targets`);
|
||||||
|
if (response.ok) {
|
||||||
|
return (await response.json()).targets;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function deleteMapTarget(targetId) {
|
||||||
|
const response = await apiDelete(`${API_URI}/map/nuclear/targets/${targetId}`);
|
||||||
|
if (!response.ok) {
|
||||||
|
const message = await getErrorMessage(response, 'Could not delete the target');
|
||||||
|
toast({type: 'error', title: 'Map Error', description: message, time: 5000});
|
||||||
|
}
|
||||||
|
return response.ok;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Save `targets` ([{lat, lon, label, weapon, yield_kt?, fission_fraction?, id?}]) in place of the
|
||||||
|
// saved targets, which are those of `loadedIds` (refused if they are not): the saved targets, or null.
|
||||||
|
export async function saveMapTargets(targets, loadedIds) {
|
||||||
|
const response = await apiPut(`${API_URI}/map/nuclear/targets`, {targets, loaded_ids: loadedIds});
|
||||||
|
if (!response.ok) {
|
||||||
|
const message = await getErrorMessage(response, 'Could not save the targets');
|
||||||
|
toast({type: 'error', title: 'Map Error', description: message, time: 5000});
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
return (await response.json()).targets;
|
||||||
|
}
|
||||||
|
|
||||||
|
// The weather subscription (a forecast around the nuclear targets, downloaded every day): {enabled,
|
||||||
|
// download, targets, spacing, points, seconds, field}, or undefined when it could not be fetched.
|
||||||
|
export async function getWeather() {
|
||||||
|
const response = await apiGet(`${API_URI}/map/weather`);
|
||||||
|
if (response.ok) {
|
||||||
|
return await response.json();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Subscribe to the weather, or not: the subscription as it is then, or null.
|
||||||
|
export async function setWeatherSubscription(enabled) {
|
||||||
|
const response = await apiPut(`${API_URI}/map/weather`, {enabled});
|
||||||
|
if (response.ok) {
|
||||||
|
return await response.json();
|
||||||
|
}
|
||||||
|
const message = await getErrorMessage(response, 'Could not change the weather download');
|
||||||
|
toast({type: 'error', title: 'Map Error', description: message, time: 5000});
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Download the weather now, rather than when it is next due: the subscription as it is then, or null.
|
||||||
|
export async function downloadWeatherNow() {
|
||||||
|
const response = await apiPost(`${API_URI}/map/weather/download`);
|
||||||
|
if (response.ok) {
|
||||||
|
return await response.json();
|
||||||
|
}
|
||||||
|
const message = await getErrorMessage(response, 'Could not download the weather');
|
||||||
|
toast({type: 'error', title: 'Map Error', description: message, time: 5000});
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
export async function getMapPins() {
|
export async function getMapPins() {
|
||||||
const response = await apiGet(`${API_URI}/map/pins`);
|
const response = await apiGet(`${API_URI}/map/pins`);
|
||||||
if (response.ok) {
|
if (response.ok) {
|
||||||
|
|
@ -1649,6 +1840,158 @@ export async function setMapDefaultLocation(lat, lon, zoom) {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Make a PDF of a map from the images of its layers ({name, blob}, from the bottom up). Returns the
|
||||||
|
// PDF (a Blob); throws an Error which says what went wrong.
|
||||||
|
// `bounds` is the west, south, east and north edges of the images, in degrees.
|
||||||
|
// What exportMapPdf throws when the person exporting stopped it: not a failure to be told of.
|
||||||
|
export class ExportCancelled extends Error {
|
||||||
|
constructor() {
|
||||||
|
super('The export was cancelled');
|
||||||
|
this.name = 'ExportCancelled';
|
||||||
|
this.cancelled = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// How many times in a row the server may not answer, while the PDF of an export is made or fetched,
|
||||||
|
// before the export is given up on: the API is busy while it makes a PDF, and a Raspberry Pi more so.
|
||||||
|
const EXPORT_POLL_FAILURES = 10;
|
||||||
|
|
||||||
|
// Make the PDF of a map from the images of its layers (see modules/map/export_job.py). The PDF is a
|
||||||
|
// minute or two of work on a Raspberry Pi, so it is a Job: the map is described, the image of each
|
||||||
|
// layer is sent, the Job is started and watched, and the PDF is fetched when the Job is done.
|
||||||
|
//
|
||||||
|
// onStatus(text): told how far along it is. isCancelled(): asked, between steps, whether to stop;
|
||||||
|
// signal: an AbortSignal which stops it at once, in the middle of a request (an image of a layer
|
||||||
|
// is tens of megabytes, and a request to a server which has stopped answering never ends);
|
||||||
|
// the server is then told to stop the export and remove what was sent. Rejects with
|
||||||
|
// ExportCancelled when it was stopped.
|
||||||
|
//
|
||||||
|
// However it ends, the server is told to remove what it has of the export: the images are a hundred
|
||||||
|
// megabytes and the PDF tens, on a disk which may be an SD card.
|
||||||
|
export async function exportMapPdf(
|
||||||
|
{width, height, dpi, title, bounds, layers, sheet},
|
||||||
|
{onStatus = () => undefined, isCancelled = () => false, signal = undefined, pollMs = 1000} = {},
|
||||||
|
) {
|
||||||
|
const exports = `${API_URI}/map/export`;
|
||||||
|
let exportId = null;
|
||||||
|
// Best effort: the server removes old exports itself, later. An export which is stopped while
|
||||||
|
// it is being described has no id yet to remove it by: what the server made of it is one small
|
||||||
|
// file, which it removes with the old ones.
|
||||||
|
const remove = async () => {
|
||||||
|
if (exportId) await fetch(`${exports}/${exportId}`, {method: 'DELETE'}).catch(() => undefined);
|
||||||
|
};
|
||||||
|
try {
|
||||||
|
return await sendAndFetch();
|
||||||
|
} catch (e) {
|
||||||
|
// A request which was stopped because the export was is not a failure to be told of.
|
||||||
|
throw signal?.aborted ? new ExportCancelled() : e;
|
||||||
|
} finally {
|
||||||
|
// Not waited for: a server which is slow to answer is not to keep a PDF from who made it.
|
||||||
|
remove();
|
||||||
|
}
|
||||||
|
|
||||||
|
async function sendAndFetch() {
|
||||||
|
const send = async (url, init, fallback) => {
|
||||||
|
let response;
|
||||||
|
try {
|
||||||
|
response = await fetch(url, {...init, signal});
|
||||||
|
} catch (e) {
|
||||||
|
throw new Error('Could not reach the server');
|
||||||
|
}
|
||||||
|
if (!response.ok) throw new Error(await getErrorMessage(response, fallback));
|
||||||
|
return response;
|
||||||
|
};
|
||||||
|
const pause = () => new Promise(resolve => setTimeout(resolve, pollMs));
|
||||||
|
// Stopped by the person exporting: removing the export cancels its Job.
|
||||||
|
const stopIfCancelled = async () => {
|
||||||
|
if (isCancelled() || signal?.aborted) throw new ExportCancelled();
|
||||||
|
};
|
||||||
|
|
||||||
|
await stopIfCancelled();
|
||||||
|
onStatus('Sending the map…');
|
||||||
|
const created = await send(exports, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: {'Content-Type': 'application/json'},
|
||||||
|
body: JSON.stringify({width, height, dpi, title, bounds, sheet, layers: layers.map(i => i.name)}),
|
||||||
|
}, 'Could not export the map');
|
||||||
|
exportId = (await created.json()).export_id;
|
||||||
|
|
||||||
|
// One layer a request: together they are more than a request may be, and more than a slow
|
||||||
|
// connection sends in the time a request is given.
|
||||||
|
for (const [index, layer] of layers.entries()) {
|
||||||
|
await stopIfCancelled();
|
||||||
|
onStatus(`Sending ${layer.name} (${index + 1} of ${layers.length})…`);
|
||||||
|
await send(`${exports}/${exportId}/layer/${index}`, {method: 'POST', body: layer.blob},
|
||||||
|
`Could not send ${layer.name}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
await stopIfCancelled();
|
||||||
|
const started = await send(`${exports}/${exportId}/start`, {method: 'POST'}, 'Could not make the PDF');
|
||||||
|
const {job_id: jobId} = await started.json();
|
||||||
|
|
||||||
|
let failures = 0;
|
||||||
|
let waited = 0;
|
||||||
|
while (true) {
|
||||||
|
await stopIfCancelled();
|
||||||
|
let job;
|
||||||
|
try {
|
||||||
|
const response = await fetch(`${API_URI}/jobs/${jobId}`, {signal});
|
||||||
|
if (response.status === 404) throw Object.assign(new Error('The server forgot the export'), {final: true});
|
||||||
|
if (!response.ok) throw new Error('Could not ask how the PDF is coming');
|
||||||
|
job = (await response.json()).job;
|
||||||
|
failures = 0;
|
||||||
|
} catch (e) {
|
||||||
|
if (e.final || ++failures >= EXPORT_POLL_FAILURES) {
|
||||||
|
throw e.final ? e : new Error('Could not reach the server');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (job?.status === 'complete') break;
|
||||||
|
if (job?.status === 'failed') throw new Error(job.error || 'The PDF could not be made');
|
||||||
|
if (job?.status === 'cancelled') throw new ExportCancelled();
|
||||||
|
if (job?.status === 'pending') {
|
||||||
|
// A Job is taken up within a moment, unless another (a video being transcoded) is in its way.
|
||||||
|
onStatus(++waited > 3 ? 'Waiting for another job to finish…' : 'Starting the PDF…');
|
||||||
|
} else if (job) {
|
||||||
|
onStatus(`Making the PDF (${Math.round(job.progress || 0)}%)…`);
|
||||||
|
}
|
||||||
|
await pause();
|
||||||
|
}
|
||||||
|
|
||||||
|
// The PDF is made, and kept for an hour. A request which is lost now is asked again: not to be
|
||||||
|
// the reason all of it is done again.
|
||||||
|
onStatus('Fetching the PDF…');
|
||||||
|
for (failures = 0; ; ) {
|
||||||
|
await stopIfCancelled();
|
||||||
|
let response;
|
||||||
|
try {
|
||||||
|
response = await fetch(`${exports}/${exportId}/pdf`, {signal});
|
||||||
|
} catch (e) {
|
||||||
|
response = null;
|
||||||
|
}
|
||||||
|
if (response?.ok) return await response.blob();
|
||||||
|
// What the server refuses, it will refuse again.
|
||||||
|
if (response && response.status < 500) {
|
||||||
|
throw new Error(await getErrorMessage(response, 'Could not fetch the PDF'));
|
||||||
|
}
|
||||||
|
if (++failures >= EXPORT_POLL_FAILURES) throw new Error('Could not fetch the PDF');
|
||||||
|
await pause();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// What the USGS calls a quadrangle: {name, state, exact}, or null where it has no name (most of the
|
||||||
|
// world), and when it can not be asked. A map is exported without its name as well as with it.
|
||||||
|
export async function getMapQuadName({west, south, east, north}) {
|
||||||
|
try {
|
||||||
|
const response = await apiGet(
|
||||||
|
`${API_URI}/map/quad?west=${west}&south=${south}&east=${east}&north=${north}`);
|
||||||
|
if (!response.ok) return null;
|
||||||
|
return (await response.json()).quad || null;
|
||||||
|
} catch (e) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
export async function searchMap(query, limit = 12, offset = 0, lat = null, lon = null) {
|
export async function searchMap(query, limit = 12, offset = 0, lat = null, lon = null) {
|
||||||
let url = `${API_URI}/map/search?q=${encodeURIComponent(query)}&limit=${limit}&offset=${offset}`;
|
let url = `${API_URI}/map/search?q=${encodeURIComponent(query)}&limit=${limit}&offset=${offset}`;
|
||||||
if (lat !== null && lon !== null) {
|
if (lat !== null && lon !== null) {
|
||||||
|
|
@ -1656,7 +1999,8 @@ export async function searchMap(query, limit = 12, offset = 0, lat = null, lon =
|
||||||
}
|
}
|
||||||
const response = await apiGet(url);
|
const response = await apiGet(url);
|
||||||
if (!response.ok) {
|
if (!response.ok) {
|
||||||
return {results: [], total: 0};
|
// Undefined, not {results: []}, so a failed search is not shown as finding nothing.
|
||||||
|
return undefined;
|
||||||
}
|
}
|
||||||
return await response.json();
|
return await response.json();
|
||||||
}
|
}
|
||||||
|
|
@ -1664,7 +2008,8 @@ export async function searchMap(query, limit = 12, offset = 0, lat = null, lon =
|
||||||
export async function getMapSearchStatus() {
|
export async function getMapSearchStatus() {
|
||||||
const response = await apiGet(`${API_URI}/map/search/status`);
|
const response = await apiGet(`${API_URI}/map/search/status`);
|
||||||
if (!response.ok) {
|
if (!response.ok) {
|
||||||
return {indexed: [], missing: []};
|
// Undefined, not {indexed: [], missing: []}, which read as "no maps are installed".
|
||||||
|
return undefined;
|
||||||
}
|
}
|
||||||
return await response.json();
|
return await response.json();
|
||||||
}
|
}
|
||||||
|
|
@ -1677,8 +2022,8 @@ export async function searchEstimateMap(search_str) {
|
||||||
return {mapPlaces: data.map_places || 0};
|
return {mapPlaces: data.map_places || 0};
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function rebuildMapSearchIndex(filename) {
|
export async function rebuildMapSearchIndex(mapPath) {
|
||||||
const response = await apiPost(`${API_URI}/map/search/rebuild/${encodeURIComponent(filename)}`);
|
const response = await apiPost(`${API_URI}/map/search/rebuild/${encodeMapPath(mapPath)}`);
|
||||||
if (!response.ok) {
|
if (!response.ok) {
|
||||||
const message = await getErrorMessage(response, 'Could not rebuild search index');
|
const message = await getErrorMessage(response, 'Could not rebuild search index');
|
||||||
toast({type: 'error', title: 'Map Error', description: message, time: 5000});
|
toast({type: 'error', title: 'Map Error', description: message, time: 5000});
|
||||||
|
|
@ -1900,13 +2245,31 @@ export async function searchDirectories(path) {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Returns the file worker job id of a queued rename (a directory), or null when the rename is already done.
|
||||||
|
*/
|
||||||
export async function renamePath(path, newName) {
|
export async function renamePath(path, newName) {
|
||||||
const body = {path, new_name: newName};
|
const body = {path, new_name: newName};
|
||||||
const response = await apiPost(`${API_URI}/files/rename`, body);
|
const response = await apiPost(`${API_URI}/files/rename`, body);
|
||||||
if (!response.ok) {
|
if (!response.ok) {
|
||||||
const message = await getErrorMessage(response, 'Failed to rename!');
|
const message = await getErrorMessage(response, 'Failed to rename!');
|
||||||
toast({type: 'error', title: 'Error', description: message, time: 5000});
|
toast({type: 'error', title: 'Error', description: message, time: 5000});
|
||||||
|
return null;
|
||||||
}
|
}
|
||||||
|
const json = await response.json();
|
||||||
|
return json['job_id'] || null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Returns a file worker job's status ('pending', 'complete', or 'failed'), or null if it is unknown.
|
||||||
|
*/
|
||||||
|
export async function fetchFileWorkerJobStatus(jobId) {
|
||||||
|
const response = await apiGet(`${API_URI}/files/jobs/${encodeURIComponent(jobId)}`);
|
||||||
|
if (!response.ok) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
const json = await response.json();
|
||||||
|
return json['status'];
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function movePaths(destination, paths) {
|
export async function movePaths(destination, paths) {
|
||||||
|
|
@ -2044,6 +2407,7 @@ export async function searchSuggestions(search_str) {
|
||||||
domains: content.domains,
|
domains: content.domains,
|
||||||
authors: content.authors || [],
|
authors: content.authors || [],
|
||||||
subjects: content.subjects || [],
|
subjects: content.subjects || [],
|
||||||
|
repos: content.repos || [],
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
console.error('Failed to get file search suggestions!');
|
console.error('Failed to get file search suggestions!');
|
||||||
|
|
@ -2082,8 +2446,8 @@ export async function searchEstimateZims(search_str, tagNames) {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function searchEstimateOthers(tagNames) {
|
export async function searchEstimateOthers(tagNames, searchStr) {
|
||||||
const body = {tag_names: tagNames};
|
const body = {tag_names: tagNames, search_str: searchStr || null};
|
||||||
const response = await apiPost(`${API_URI}/search_other_estimates`, body);
|
const response = await apiPost(`${API_URI}/search_other_estimates`, body);
|
||||||
if (response.ok) {
|
if (response.ok) {
|
||||||
const content = await response.json();
|
const content = await response.json();
|
||||||
|
|
@ -2093,8 +2457,8 @@ export async function searchEstimateOthers(tagNames) {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function searchChannels(tagNames) {
|
export async function searchChannels(tagNames, searchStr) {
|
||||||
const body = {tag_names: tagNames};
|
const body = {tag_names: tagNames, search_str: searchStr};
|
||||||
const response = await apiPost(`${API_URI}/videos/channels/search`, body);
|
const response = await apiPost(`${API_URI}/videos/channels/search`, body);
|
||||||
if (response.ok) {
|
if (response.ok) {
|
||||||
const content = await response.json();
|
const content = await response.json();
|
||||||
|
|
@ -2104,6 +2468,16 @@ export async function searchChannels(tagNames) {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Collections of `kind` whose name matches `searchStr` and/or which have any of the tags.
|
||||||
|
export async function searchCollections(kind, tagNames, searchStr) {
|
||||||
|
const body = {kind, tag_names: tagNames, search_str: searchStr};
|
||||||
|
const response = await apiPost(`${COLLECTIONS_API}/search`, body);
|
||||||
|
if (response.ok) {
|
||||||
|
const content = await response.json();
|
||||||
|
return {collections: content.collections};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
export async function getOutdatedZims() {
|
export async function getOutdatedZims() {
|
||||||
const response = await apiGet(`${API_URI}/zim/outdated`);
|
const response = await apiGet(`${API_URI}/zim/outdated`);
|
||||||
if (response.status === 200) {
|
if (response.status === 200) {
|
||||||
|
|
@ -2170,8 +2544,10 @@ export async function checkUpgrade(force = false) {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function triggerUpgrade() {
|
// `branch` upgrades from that branch; without it the current branch is upgraded.
|
||||||
const response = await apiPost(`${API_URI}/upgrade/start`);
|
export async function triggerUpgrade(branch = null) {
|
||||||
|
const body = branch ? {branch} : undefined;
|
||||||
|
const response = await apiPost(`${API_URI}/upgrade/start`, body);
|
||||||
if (!response.ok) {
|
if (!response.ok) {
|
||||||
const message = await getErrorMessage(response, 'Failed to start upgrade. See server logs.');
|
const message = await getErrorMessage(response, 'Failed to start upgrade. See server logs.');
|
||||||
toast({
|
toast({
|
||||||
|
|
@ -2297,7 +2673,7 @@ export async function getDoc(fileGroupId) {
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
export async function searchDocs(offset, limit, searchStr, order, tagNames, author, subject, mimetype, deep) {
|
export async function searchDocs(offset, limit, searchStr, order, tagNames, author, subject, mimetype, deep, anyTag) {
|
||||||
offset = parseInt(offset || 0);
|
offset = parseInt(offset || 0);
|
||||||
limit = parseInt(limit || DEFAULT_LIMIT);
|
limit = parseInt(limit || DEFAULT_LIMIT);
|
||||||
let body = {offset, limit};
|
let body = {offset, limit};
|
||||||
|
|
@ -2322,6 +2698,9 @@ export async function searchDocs(offset, limit, searchStr, order, tagNames, auth
|
||||||
if (deep) {
|
if (deep) {
|
||||||
body['deep'] = true;
|
body['deep'] = true;
|
||||||
}
|
}
|
||||||
|
if (anyTag) {
|
||||||
|
body['any_tag'] = true;
|
||||||
|
}
|
||||||
|
|
||||||
console.debug('searching docs', body);
|
console.debug('searching docs', body);
|
||||||
const response = await apiPost(`${DOCS_API}/search`, body);
|
const response = await apiPost(`${DOCS_API}/search`, body);
|
||||||
|
|
@ -2438,3 +2817,215 @@ export async function setPlaylistTag(playlistId, tagName, directory) {
|
||||||
toast({type: 'error', title: 'Error', description: message, time: 5000});
|
toast({type: 'error', title: 'Error', description: message, time: 5000});
|
||||||
throw Error(message);
|
throw Error(message);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Bookmarks: a tree of nodes, a node with `children` being a directory.
|
||||||
|
export async function getBookmarks() {
|
||||||
|
const response = await apiGet(`${API_URI}/bookmarks`);
|
||||||
|
if (response.ok) {
|
||||||
|
return (await response.json())['bookmarks'];
|
||||||
|
}
|
||||||
|
throw new Error('Could not fetch bookmarks');
|
||||||
|
}
|
||||||
|
|
||||||
|
async function bookmarksModify(request, fallbackMessage) {
|
||||||
|
const response = await request;
|
||||||
|
if (response.ok) {
|
||||||
|
return response.status === 204 ? null : await response.json();
|
||||||
|
}
|
||||||
|
const message = await getErrorMessage(response, fallbackMessage);
|
||||||
|
toast({type: 'error', title: 'Bookmarks Error', description: message, time: 5000});
|
||||||
|
throw new Error(message);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function addBookmark({name, url, new_tab = false, parent_id = null, position = null}) {
|
||||||
|
const body = {name, url, new_tab, parent_id, position};
|
||||||
|
return await bookmarksModify(apiPost(`${API_URI}/bookmarks`, body), 'Could not add bookmark');
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function addBookmarkDirectory({name, parent_id = null, position = null}) {
|
||||||
|
const body = {name, parent_id, position};
|
||||||
|
return await bookmarksModify(apiPost(`${API_URI}/bookmarks/directory`, body), 'Could not add directory');
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function updateBookmark(nodeId, {name, url, new_tab}) {
|
||||||
|
const body = {name, url, new_tab};
|
||||||
|
return await bookmarksModify(apiPut(`${API_URI}/bookmarks/${nodeId}`, body), 'Could not update bookmark');
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function moveBookmark(nodeId, parent_id, position = null) {
|
||||||
|
const body = {parent_id, position};
|
||||||
|
return await bookmarksModify(apiPost(`${API_URI}/bookmarks/${nodeId}/move`, body), 'Could not move bookmark');
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function deleteBookmark(nodeId) {
|
||||||
|
return await bookmarksModify(apiDelete(`${API_URI}/bookmarks/${nodeId}`), 'Could not delete bookmark');
|
||||||
|
}
|
||||||
|
|
||||||
|
async function reposError(response, fallbackMessage) {
|
||||||
|
const message = await getErrorMessage(response, fallbackMessage);
|
||||||
|
toast({type: 'error', title: 'Repos Error', description: message, time: 5000});
|
||||||
|
throw Error(message);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function fetchRepos() {
|
||||||
|
const response = await apiGet(REPOS_API);
|
||||||
|
if (response.ok) {
|
||||||
|
return (await response.json())['repos'];
|
||||||
|
}
|
||||||
|
await reposError(response, 'Failed to fetch repos.');
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function getRepo(repoId) {
|
||||||
|
const response = await apiGet(`${REPOS_API}/${repoId}`);
|
||||||
|
if (response.ok) {
|
||||||
|
return (await response.json())['repo'];
|
||||||
|
}
|
||||||
|
await reposError(response, 'Failed to fetch repo.');
|
||||||
|
}
|
||||||
|
|
||||||
|
// `repo`: {url, directory?, name?, tag_name?, frequency?, mode?, branch?, description?}
|
||||||
|
export async function createRepo(repo) {
|
||||||
|
const response = await apiPost(REPOS_API, repo);
|
||||||
|
if (response.ok) {
|
||||||
|
return (await response.json())['repo'];
|
||||||
|
}
|
||||||
|
await reposError(response, 'Failed to add repo.');
|
||||||
|
}
|
||||||
|
|
||||||
|
// `changes`: {description?, frequency?, mode?, branch?}. An empty branch follows the remote's default branch.
|
||||||
|
export async function updateRepo(repoId, changes) {
|
||||||
|
const response = await apiPut(`${REPOS_API}/${repoId}`, changes);
|
||||||
|
if (response.ok) {
|
||||||
|
return (await response.json())['repo'];
|
||||||
|
}
|
||||||
|
await reposError(response, 'Failed to update repo.');
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function deleteRepo(repoId, deleteFiles = false) {
|
||||||
|
const response = await apiDelete(`${REPOS_API}/${repoId}?delete_files=${deleteFiles ? 'true' : 'false'}`);
|
||||||
|
if (!response.ok) {
|
||||||
|
await reposError(response, 'Failed to delete repo.');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Download the repo's updates now.
|
||||||
|
export async function updateRepoNow(repoId) {
|
||||||
|
const response = await apiPost(`${REPOS_API}/${repoId}/update`);
|
||||||
|
if (!response.ok) {
|
||||||
|
await reposError(response, 'Failed to start the repo update.');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// One directory of a repo's files: {path, entries: [{name, path, is_dir, size}], readme_path}.
|
||||||
|
export async function getRepoTree(repoId, path) {
|
||||||
|
const query = path ? `?path=${encodeURIComponent(path)}` : '';
|
||||||
|
const response = await apiGet(`${REPOS_API}/${repoId}/tree${query}`);
|
||||||
|
if (response.ok) {
|
||||||
|
return await response.json();
|
||||||
|
}
|
||||||
|
await reposError(response, 'Failed to list the repo files.');
|
||||||
|
}
|
||||||
|
|
||||||
|
// Repos matching the search (name and README) and/or the tags. Each has an escaped `readme_headline`.
|
||||||
|
export async function searchRepos(searchStr, tagNames) {
|
||||||
|
const body = {search_str: searchStr || null, tag_names: tagNames || []};
|
||||||
|
const response = await apiPost(`${REPOS_API}/search`, body);
|
||||||
|
if (response.ok) {
|
||||||
|
const content = await response.json();
|
||||||
|
return {repos: content.repos, total: content.totals.repos};
|
||||||
|
}
|
||||||
|
await reposError(response, 'Failed to search repos.');
|
||||||
|
}
|
||||||
|
|
||||||
|
// The commits of a repo's checked out branch, newest first: {commits: [{sha, author, date, message}], total}.
|
||||||
|
export async function getRepoLog(repoId, offset = 0, limit = 50) {
|
||||||
|
const response = await apiGet(`${REPOS_API}/${repoId}/log?limit=${limit}&offset=${offset}`);
|
||||||
|
if (response.ok) {
|
||||||
|
return await response.json();
|
||||||
|
}
|
||||||
|
await reposError(response, 'Failed to fetch the repo history.');
|
||||||
|
}
|
||||||
|
|
||||||
|
// A ZIP of a repo's checked out files; the browser downloads it.
|
||||||
|
export function repoArchiveURL(repoId) {
|
||||||
|
return `${REPOS_API}/${repoId}/archive.zip`;
|
||||||
|
}
|
||||||
|
|
||||||
|
// What importing the git clone in `directory` (relative to the media directory) would do. Changes nothing.
|
||||||
|
export async function inspectRepoImport(directory, name, tagName, url) {
|
||||||
|
const body = {directory, name: name || null, tag_name: tagName || null, url: url || null};
|
||||||
|
const response = await apiPost(`${REPOS_API}/import/inspect`, body);
|
||||||
|
if (response.ok) {
|
||||||
|
return {inspection: (await response.json())['inspection']};
|
||||||
|
}
|
||||||
|
return {error: await getErrorMessage(response, 'Cannot import this directory.')};
|
||||||
|
}
|
||||||
|
|
||||||
|
// Import an existing git clone as a Repo; it stays where it is. `repo`: {directory, confirm, url?, name?, ...}
|
||||||
|
export async function importRepo(repo) {
|
||||||
|
const response = await apiPost(`${REPOS_API}/import`, repo);
|
||||||
|
if (response.ok) {
|
||||||
|
return (await response.json())['repo'];
|
||||||
|
}
|
||||||
|
await reposError(response, 'Failed to import the repo.');
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Torrents (they reach the Internet only through the VPN) ---
|
||||||
|
|
||||||
|
const TORRENTS_API = `${API_URI}/torrents`;
|
||||||
|
|
||||||
|
async function torrentsRequest(response, fallbackMessage) {
|
||||||
|
if (!response.ok) {
|
||||||
|
throw new Error(await getErrorMessage(response, fallbackMessage));
|
||||||
|
}
|
||||||
|
return response.status === 204 ? null : response;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function getTorrents() {
|
||||||
|
const response = await torrentsRequest(await apiGet(`${TORRENTS_API}/`), 'Failed to get torrents');
|
||||||
|
return await response.json();
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function uploadTorrent(file, destination) {
|
||||||
|
const form = new FormData();
|
||||||
|
form.append('torrent', file);
|
||||||
|
if (destination) {
|
||||||
|
form.append('destination', destination);
|
||||||
|
}
|
||||||
|
const response = await torrentsRequest(await fetch(`${TORRENTS_API}/upload`, {method: 'POST', body: form}),
|
||||||
|
'Failed to add the .torrent file');
|
||||||
|
return await response.json();
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function pauseTorrent(hash) {
|
||||||
|
await torrentsRequest(await apiPost(`${TORRENTS_API}/${hash}/pause`), 'Failed to pause the torrent');
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function resumeTorrent(hash) {
|
||||||
|
await torrentsRequest(await apiPost(`${TORRENTS_API}/${hash}/resume`), 'Failed to resume the torrent');
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function removeTorrent(hash, deleteFiles = false) {
|
||||||
|
await torrentsRequest(await apiDelete(`${TORRENTS_API}/${hash}?delete_files=${deleteFiles ? 'true' : 'false'}`),
|
||||||
|
'Failed to remove the torrent');
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function setTorrentShareLimits(hash, seedRatioLimit, seedTimeLimit) {
|
||||||
|
await torrentsRequest(await apiPut(`${TORRENTS_API}/${hash}/limits`,
|
||||||
|
{seed_ratio_limit: seedRatioLimit, seed_time_limit: seedTimeLimit}), 'Failed to save the limits');
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function setTorrentSpeedLimits(upload, download) {
|
||||||
|
await torrentsRequest(await apiPut(`${TORRENTS_API}/limits`, {upload, download}),
|
||||||
|
'Failed to save the speed limits');
|
||||||
|
}
|
||||||
|
|
||||||
|
export function torrentFileUrl(hash) {
|
||||||
|
return `${TORRENTS_API}/${hash}/torrent`;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function shareTorrent(path, trackers, webSeeds, rememberTrackers = false) {
|
||||||
|
const response = await torrentsRequest(await apiPost(`${TORRENTS_API}/share`,
|
||||||
|
{path, trackers, web_seeds: webSeeds, remember_trackers: rememberTrackers}), 'Failed to share as a torrent');
|
||||||
|
return (await response.json()).job_id;
|
||||||
|
}
|
||||||
|
|
|
||||||
|
|
@ -279,3 +279,44 @@ export async function healthCheck() {
|
||||||
export async function getControllerInfo() {
|
export async function getControllerInfo() {
|
||||||
return controllerFetch('/info');
|
return controllerFetch('/info');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// --- Sync (a secondary WROLPi copying its primary; the Controller runs it, because the API is stopped) ---
|
||||||
|
|
||||||
|
export async function getSyncStatus() {
|
||||||
|
return controllerFetch('/sync/status');
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Start a sync now. Throws with the reason a sync cannot start. */
|
||||||
|
export async function runSync() {
|
||||||
|
return controllerFetch('/sync/run', {method: 'POST'});
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function cancelSync() {
|
||||||
|
return controllerFetch('/sync/cancel', {method: 'POST'});
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- VPN (torrents reach the Internet only through it) ---
|
||||||
|
|
||||||
|
export async function getVpnStatus() {
|
||||||
|
return controllerFetch('/vpn/status');
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function getVpnSettings() {
|
||||||
|
return controllerFetch('/vpn/settings');
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function updateVpnSettings(settings) {
|
||||||
|
return controllerFetch('/vpn/settings', {method: 'POST', body: JSON.stringify(settings)});
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function uploadVpnConfig(filename, content) {
|
||||||
|
return controllerFetch('/vpn/config', {method: 'POST', body: JSON.stringify({filename, content})});
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function deleteVpnConfig() {
|
||||||
|
return controllerFetch('/vpn/config', {method: 'DELETE'});
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function saveVpnAuth(username, password) {
|
||||||
|
return controllerFetch('/vpn/auth', {method: 'POST', body: JSON.stringify({username, password})});
|
||||||
|
}
|
||||||
|
|
|
||||||
|
|
@ -12,8 +12,10 @@ import {
|
||||||
import {Header, Loading, Panel, Statistic, StatisticGroup} from "./ui";
|
import {Header, Loading, Panel, Statistic, StatisticGroup} from "./ui";
|
||||||
import {useStatistics} from "../hooks/customHooks";
|
import {useStatistics} from "../hooks/customHooks";
|
||||||
import {CalculatorsPage} from "./Calculators";
|
import {CalculatorsPage} from "./Calculators";
|
||||||
|
import {BookmarksPage} from "./Bookmarks";
|
||||||
|
|
||||||
function StatisticsPage() {
|
// `statistics` follows useStatistics: null = pending, undefined = fetch failed.
|
||||||
|
export function StatisticsPage() {
|
||||||
useTitle('Statistics');
|
useTitle('Statistics');
|
||||||
|
|
||||||
const {statistics} = useStatistics();
|
const {statistics} = useStatistics();
|
||||||
|
|
@ -25,7 +27,7 @@ function StatisticsPage() {
|
||||||
</>
|
</>
|
||||||
}
|
}
|
||||||
|
|
||||||
if (statistics['global_statistics']) {
|
if (statistics && statistics['global_statistics']) {
|
||||||
let {global_statistics, file_statistics} = statistics;
|
let {global_statistics, file_statistics} = statistics;
|
||||||
const {
|
const {
|
||||||
archive_count,
|
archive_count,
|
||||||
|
|
@ -104,6 +106,7 @@ export function MoreRoute(props) {
|
||||||
<Routes>
|
<Routes>
|
||||||
<Route path='calculators' element={<CalculatorsPage/>}/>
|
<Route path='calculators' element={<CalculatorsPage/>}/>
|
||||||
<Route path='statistics' exact element={<StatisticsPage/>}/>
|
<Route path='statistics' exact element={<StatisticsPage/>}/>
|
||||||
|
<Route path='bookmarks' element={<BookmarksPage/>}/>
|
||||||
</Routes>
|
</Routes>
|
||||||
</PageContainer>
|
</PageContainer>
|
||||||
}
|
}
|
||||||
|
|
|
||||||
453
app/src/components/Bookmarks.js
Normal file
453
app/src/components/Bookmarks.js
Normal file
|
|
@ -0,0 +1,453 @@
|
||||||
|
import React, {useState} from 'react';
|
||||||
|
import {Link} from 'react-router';
|
||||||
|
import {IconBookmark} from '@tabler/icons-react';
|
||||||
|
import {Button, Group, Header, Icon, Menu, Message, Modal, Panel, Select, Table, Text, TextInput, Toggle} from './ui';
|
||||||
|
import {APIButton, PageContainer, useTitle} from './Common';
|
||||||
|
import {isBookmarkDirectory, resolveBookmarkUrl, useBookmarks} from '../contexts/BookmarksContext';
|
||||||
|
import {addBookmark, addBookmarkDirectory, deleteBookmark, moveBookmark, updateBookmark} from '../api';
|
||||||
|
|
||||||
|
export const EDIT_BOOKMARKS_PATH = '/more/bookmarks';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The props that make a Menu.Item open a bookmark: an in-app Link for a path, a plain
|
||||||
|
* anchor for everything else, and a new tab when the bookmark asks for one. A URL that
|
||||||
|
* does not resolve (see resolveBookmarkUrl) gets a disabled item, never a raw href.
|
||||||
|
*/
|
||||||
|
function bookmarkItemProps(node) {
|
||||||
|
const {internal, href} = resolveBookmarkUrl(node.url);
|
||||||
|
if (!href) {
|
||||||
|
return {disabled: true};
|
||||||
|
}
|
||||||
|
const target = node.new_tab ? {target: '_blank', rel: 'noopener noreferrer'} : {};
|
||||||
|
if (internal) {
|
||||||
|
return {component: Link, to: href, ...target};
|
||||||
|
}
|
||||||
|
return {component: 'a', href, ...target};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The items of a bookmarks menu.
|
||||||
|
*
|
||||||
|
* `nested` draws a directory as a flyout (Menu.Sub), which opens beside the menu on hover.
|
||||||
|
* Without it a directory is a labelled, indented run of items instead: the mobile
|
||||||
|
* hamburger is the one place bookmarks are shown where a flyout cannot be hovered. The
|
||||||
|
* indent is in rem: a label is set smaller than an item, so an em indent would put a
|
||||||
|
* directory's label a few pixels left of the items beside it.
|
||||||
|
*/
|
||||||
|
export function BookmarkMenuItems({nodes, nested = true, depth = 0}) {
|
||||||
|
if (!nodes || nodes.length === 0) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
return nodes.map(node => {
|
||||||
|
if (isBookmarkDirectory(node)) {
|
||||||
|
if (nested) {
|
||||||
|
return <Menu.Sub key={node.id}>
|
||||||
|
<Menu.Sub.Target>
|
||||||
|
<Menu.Sub.Item leftSection={<Icon name='folder' size='small'/>}>{node.name}</Menu.Sub.Item>
|
||||||
|
</Menu.Sub.Target>
|
||||||
|
<Menu.Sub.Dropdown>
|
||||||
|
{node.children.length > 0
|
||||||
|
? <BookmarkMenuItems nodes={node.children} nested={nested}/>
|
||||||
|
: <Menu.Item disabled>Empty</Menu.Item>}
|
||||||
|
</Menu.Sub.Dropdown>
|
||||||
|
</Menu.Sub>;
|
||||||
|
}
|
||||||
|
return <React.Fragment key={node.id}>
|
||||||
|
<Menu.Label style={{paddingLeft: `${0.75 + depth}rem`}}>{node.name}</Menu.Label>
|
||||||
|
<BookmarkMenuItems nodes={node.children} nested={false} depth={depth + 1}/>
|
||||||
|
</React.Fragment>;
|
||||||
|
}
|
||||||
|
return <Menu.Item
|
||||||
|
key={node.id}
|
||||||
|
{...bookmarkItemProps(node)}
|
||||||
|
style={nested ? undefined : {paddingLeft: `${0.75 + depth}rem`}}
|
||||||
|
rightSection={node.new_tab ? <Icon name='external' size='small'/> : undefined}
|
||||||
|
>
|
||||||
|
{node.name}
|
||||||
|
</Menu.Item>;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Everything inside a bookmarks dropdown: the bookmarks, then the link to edit them. The
|
||||||
|
* edit link is always there, so a user with no bookmarks yet can find where to add one.
|
||||||
|
*/
|
||||||
|
export function BookmarksMenuContents({nested = true}) {
|
||||||
|
const {bookmarks} = useBookmarks();
|
||||||
|
const nodes = bookmarks || [];
|
||||||
|
return <>
|
||||||
|
<BookmarkMenuItems nodes={nodes} nested={nested}/>
|
||||||
|
{nodes.length > 0 && <Menu.Divider/>}
|
||||||
|
<Menu.Item component={Link} to={EDIT_BOOKMARKS_PATH} leftSection={<Icon name='edit' size='small'/>}>
|
||||||
|
Edit bookmarks
|
||||||
|
</Menu.Item>
|
||||||
|
</>;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Every directory in the tree with its full path, for the "Location" picker. */
|
||||||
|
export function directoryOptions(nodes, prefix = '') {
|
||||||
|
const options = [];
|
||||||
|
for (const node of nodes || []) {
|
||||||
|
if (isBookmarkDirectory(node)) {
|
||||||
|
const label = `${prefix}${node.name}`;
|
||||||
|
options.push({value: String(node.id), label, id: node.id});
|
||||||
|
options.push(...directoryOptions(node.children, `${label} / `));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return options;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The ids of `node` and everything beneath it. */
|
||||||
|
const subtreeIds = (node) => {
|
||||||
|
const ids = [node.id];
|
||||||
|
if (isBookmarkDirectory(node)) {
|
||||||
|
node.children.forEach(child => ids.push(...subtreeIds(child)));
|
||||||
|
}
|
||||||
|
return ids;
|
||||||
|
};
|
||||||
|
|
||||||
|
const ROOT = 'root';
|
||||||
|
|
||||||
|
/** The places a node may live: the top level, and every directory not inside `node`. */
|
||||||
|
export function locationOptions(nodes, node = null) {
|
||||||
|
// A directory cannot be moved into itself or its own children.
|
||||||
|
const excluded = node ? new Set(subtreeIds(node)) : new Set();
|
||||||
|
return [
|
||||||
|
{value: ROOT, label: 'Top level'},
|
||||||
|
...directoryOptions(nodes).filter(i => !excluded.has(i.id)).map(({value, label}) => ({value, label})),
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The form for one node. `node` is null when adding; `directory` says which kind.
|
||||||
|
* `parentId` is where a new node goes, or where an edited one currently lives.
|
||||||
|
*/
|
||||||
|
export function BookmarkNodeModal({open, node, directory, parentId, nodes, onSave, onClose}) {
|
||||||
|
const [name, setName] = useState(node?.name || '');
|
||||||
|
const [url, setUrl] = useState(node?.url || '');
|
||||||
|
const [newTab, setNewTab] = useState(Boolean(node?.new_tab));
|
||||||
|
const [location, setLocation] = useState(parentId === null || parentId === undefined ? ROOT : String(parentId));
|
||||||
|
const [saving, setSaving] = useState(false);
|
||||||
|
|
||||||
|
const locations = locationOptions(nodes, node);
|
||||||
|
|
||||||
|
const valid = name.trim() && (directory || url.trim());
|
||||||
|
const title = node ? (directory ? 'Edit directory' : 'Edit bookmark') : (directory ? 'New directory' : 'New bookmark');
|
||||||
|
|
||||||
|
const handleSave = async () => {
|
||||||
|
if (!valid) return;
|
||||||
|
setSaving(true);
|
||||||
|
try {
|
||||||
|
await onSave({
|
||||||
|
name: name.trim(),
|
||||||
|
url: url.trim(),
|
||||||
|
new_tab: newTab,
|
||||||
|
parent_id: location === ROOT ? null : Number(location),
|
||||||
|
});
|
||||||
|
} finally {
|
||||||
|
setSaving(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
return <Modal open={open} onClose={onClose} size='tiny'>
|
||||||
|
<Modal.Header>{title}</Modal.Header>
|
||||||
|
<Modal.Content>
|
||||||
|
<form onSubmit={e => {
|
||||||
|
e.preventDefault();
|
||||||
|
handleSave();
|
||||||
|
}}>
|
||||||
|
<TextInput
|
||||||
|
autoFocus
|
||||||
|
label='Name'
|
||||||
|
value={name}
|
||||||
|
onChange={e => setName(e.currentTarget.value)}
|
||||||
|
/>
|
||||||
|
{!directory && <TextInput
|
||||||
|
label='URL'
|
||||||
|
style={{marginTop: '1em'}}
|
||||||
|
value={url}
|
||||||
|
onChange={e => setUrl(e.currentTarget.value)}
|
||||||
|
placeholder='/videos, :8096/, or https://example.com'
|
||||||
|
description='A path on this WROLPi (/videos), a port on this host (:8096/ or http://:8096/), or a full URL.'
|
||||||
|
/>}
|
||||||
|
<Select
|
||||||
|
label='Location'
|
||||||
|
style={{marginTop: '1em'}}
|
||||||
|
data={locations}
|
||||||
|
value={location}
|
||||||
|
onChange={value => setLocation(value || ROOT)}
|
||||||
|
allowDeselect={false}
|
||||||
|
/>
|
||||||
|
{!directory && <Toggle
|
||||||
|
style={{marginTop: '1em'}}
|
||||||
|
label='Open in a new tab'
|
||||||
|
checked={newTab}
|
||||||
|
onChange={e => setNewTab(e.currentTarget.checked)}
|
||||||
|
/>}
|
||||||
|
</form>
|
||||||
|
</Modal.Content>
|
||||||
|
<Modal.Actions>
|
||||||
|
<Button role='cancel' onClick={onClose}>Cancel</Button>
|
||||||
|
<Button role='save' disabled={!valid || saving} onClick={handleSave}>Save</Button>
|
||||||
|
</Modal.Actions>
|
||||||
|
</Modal>;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The rows of the editor, one per node, children beneath their directory and indented. */
|
||||||
|
function BookmarkTableRows({nodes, parentId, depth, editable, actions}) {
|
||||||
|
return nodes.map((node, index) => {
|
||||||
|
const directory = isBookmarkDirectory(node);
|
||||||
|
const {href} = directory ? {} : resolveBookmarkUrl(node.url);
|
||||||
|
return <React.Fragment key={node.id}>
|
||||||
|
<Table.Row>
|
||||||
|
<Table.Cell>{String(index + 1).padStart(2, '0')}</Table.Cell>
|
||||||
|
<Table.Cell style={{width: '90px', textAlign: 'center'}}>
|
||||||
|
{directory
|
||||||
|
? <Icon name='folder' size='large'/>
|
||||||
|
: <Icon name={node.new_tab ? 'external' : 'linkify'} size='large'/>}
|
||||||
|
</Table.Cell>
|
||||||
|
<Table.Cell style={{paddingLeft: depth ? `calc(0.75em + ${depth * 1.5}em)` : undefined}}>
|
||||||
|
{directory && <b>{node.name}</b>}
|
||||||
|
{!directory && (href
|
||||||
|
? <a href={href} target={node.new_tab ? '_blank' : undefined} rel='noopener noreferrer'>
|
||||||
|
{node.name}
|
||||||
|
</a>
|
||||||
|
: <span>{node.name}</span>)}
|
||||||
|
{!directory && <Text size='xs' c='dimmed' truncate='end'>{node.url}</Text>}
|
||||||
|
</Table.Cell>
|
||||||
|
{editable && <Table.Cell>
|
||||||
|
<div className='wrolpi-button-row' style={{justifyContent: 'flex-end'}}>
|
||||||
|
<Button icon='arrow up' size='xs' aria-label={`Move ${node.name} up`} disabled={index === 0}
|
||||||
|
onClick={() => actions.move(node, parentId, index - 1)}/>
|
||||||
|
<Button icon='arrow down' size='xs' aria-label={`Move ${node.name} down`}
|
||||||
|
disabled={index === nodes.length - 1}
|
||||||
|
onClick={() => actions.move(node, parentId, index + 1)}/>
|
||||||
|
<Button icon='edit' size='xs' aria-label={`Edit ${node.name}`}
|
||||||
|
onClick={() => actions.edit(node, parentId)}/>
|
||||||
|
{directory
|
||||||
|
? <APIButton
|
||||||
|
role='danger' icon='trash' size='xs' aria-label={`Delete ${node.name}`}
|
||||||
|
confirmContent={`Delete the directory "${node.name}" and everything in it?`}
|
||||||
|
confirmButton='Delete'
|
||||||
|
onClick={() => actions.remove(node)}/>
|
||||||
|
: <Button role='danger' icon='trash' size='xs' aria-label={`Delete ${node.name}`}
|
||||||
|
onClick={() => actions.remove(node)}/>}
|
||||||
|
</div>
|
||||||
|
</Table.Cell>}
|
||||||
|
</Table.Row>
|
||||||
|
{directory && <BookmarkTableRows nodes={node.children} parentId={node.id} depth={depth + 1}
|
||||||
|
editable={editable} actions={actions}/>}
|
||||||
|
</React.Fragment>;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The bookmarks table, in the shape of the playlist items table. `actions` carries
|
||||||
|
* edit/move/remove so the gallery can render it with none of them wired.
|
||||||
|
*/
|
||||||
|
export function BookmarkTable({nodes, editable = true, actions}) {
|
||||||
|
return <Table>
|
||||||
|
<Table.Header>
|
||||||
|
<Table.Row>
|
||||||
|
<Table.HeaderCell>#</Table.HeaderCell>
|
||||||
|
<Table.HeaderCell>Kind</Table.HeaderCell>
|
||||||
|
<Table.HeaderCell>Bookmark</Table.HeaderCell>
|
||||||
|
{editable && <Table.HeaderCell/>}
|
||||||
|
</Table.Row>
|
||||||
|
</Table.Header>
|
||||||
|
<Table.Body>
|
||||||
|
<BookmarkTableRows nodes={nodes} parentId={null} depth={0} editable={editable} actions={actions}/>
|
||||||
|
</Table.Body>
|
||||||
|
</Table>;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The "Add a bookmark" and "Add a directory" forms beneath the table. */
|
||||||
|
export function BookmarkAddForms({nodes, onAddBookmark, onAddDirectory}) {
|
||||||
|
const [url, setUrl] = useState('');
|
||||||
|
const [name, setName] = useState('');
|
||||||
|
const [newTab, setNewTab] = useState(false);
|
||||||
|
const [location, setLocation] = useState(ROOT);
|
||||||
|
const [directoryName, setDirectoryName] = useState('');
|
||||||
|
const [directoryLocation, setDirectoryLocation] = useState(ROOT);
|
||||||
|
const locations = locationOptions(nodes);
|
||||||
|
const parentOf = (value) => value === ROOT ? null : Number(value);
|
||||||
|
|
||||||
|
// The form is cleared only once the server has accepted the node. A refused add has
|
||||||
|
// already shown its toast; the typed URL stays so the user can correct it.
|
||||||
|
const handleAddBookmark = async () => {
|
||||||
|
if (!url.trim() || !name.trim()) return;
|
||||||
|
try {
|
||||||
|
await onAddBookmark({name: name.trim(), url: url.trim(), new_tab: newTab, parent_id: parentOf(location)});
|
||||||
|
} catch (e) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
setUrl('');
|
||||||
|
setName('');
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleAddDirectory = async () => {
|
||||||
|
if (!directoryName.trim()) return;
|
||||||
|
try {
|
||||||
|
await onAddDirectory({name: directoryName.trim(), parent_id: parentOf(directoryLocation)});
|
||||||
|
} catch (e) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
setDirectoryName('');
|
||||||
|
};
|
||||||
|
|
||||||
|
return <>
|
||||||
|
<Header as='h4'>Add a bookmark</Header>
|
||||||
|
<form onSubmit={e => {
|
||||||
|
e.preventDefault();
|
||||||
|
handleAddBookmark();
|
||||||
|
}}>
|
||||||
|
<Group align='flex-end' wrap='wrap'>
|
||||||
|
<TextInput
|
||||||
|
style={{flex: '2 1 300px'}}
|
||||||
|
aria-label='Bookmark URL'
|
||||||
|
placeholder='URL (e.g. /videos, :8096/, or https://example.com)'
|
||||||
|
value={url}
|
||||||
|
onChange={e => setUrl(e.currentTarget.value)}/>
|
||||||
|
<TextInput
|
||||||
|
style={{flex: '1 1 200px'}}
|
||||||
|
aria-label='Bookmark name'
|
||||||
|
placeholder='Name'
|
||||||
|
value={name}
|
||||||
|
onChange={e => setName(e.currentTarget.value)}/>
|
||||||
|
<Select
|
||||||
|
style={{flex: '1 1 160px'}}
|
||||||
|
aria-label='Bookmark location'
|
||||||
|
data={locations}
|
||||||
|
value={location}
|
||||||
|
onChange={value => setLocation(value || ROOT)}
|
||||||
|
allowDeselect={false}/>
|
||||||
|
<Toggle
|
||||||
|
label='New tab'
|
||||||
|
checked={newTab}
|
||||||
|
onChange={e => setNewTab(e.currentTarget.checked)}/>
|
||||||
|
<Button role='primary' type='submit' disabled={!url.trim() || !name.trim()}>Add</Button>
|
||||||
|
</Group>
|
||||||
|
</form>
|
||||||
|
<p style={{marginTop: '0.5em'}}>
|
||||||
|
<Text size='xs' c='dimmed' component='span'>
|
||||||
|
A URL is a path on this WROLPi (/videos), a port on this host (:8096/ or http://:8096/) that
|
||||||
|
works whichever address you reach it by, or a full URL.
|
||||||
|
</Text>
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<Header as='h4'>Add a directory</Header>
|
||||||
|
<form onSubmit={e => {
|
||||||
|
e.preventDefault();
|
||||||
|
handleAddDirectory();
|
||||||
|
}}>
|
||||||
|
<Group align='flex-end' wrap='wrap'>
|
||||||
|
<TextInput
|
||||||
|
style={{flex: '2 1 300px'}}
|
||||||
|
aria-label='Directory name'
|
||||||
|
placeholder='Directory name'
|
||||||
|
value={directoryName}
|
||||||
|
onChange={e => setDirectoryName(e.currentTarget.value)}/>
|
||||||
|
<Select
|
||||||
|
style={{flex: '1 1 160px'}}
|
||||||
|
aria-label='Directory location'
|
||||||
|
data={locations}
|
||||||
|
value={directoryLocation}
|
||||||
|
onChange={value => setDirectoryLocation(value || ROOT)}
|
||||||
|
allowDeselect={false}/>
|
||||||
|
<Button role='primary' type='submit' disabled={!directoryName.trim()}>Add</Button>
|
||||||
|
</Group>
|
||||||
|
</form>
|
||||||
|
</>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function BookmarksPage() {
|
||||||
|
useTitle('Bookmarks');
|
||||||
|
const {bookmarks, refresh} = useBookmarks();
|
||||||
|
// {node, directory, parentId} while the edit modal is open; a `key` remounts the form fresh.
|
||||||
|
const [modal, setModal] = useState(null);
|
||||||
|
const [modalKey, setModalKey] = useState(0);
|
||||||
|
const nodes = bookmarks || [];
|
||||||
|
|
||||||
|
const actions = {
|
||||||
|
edit: (node, parentId) => {
|
||||||
|
setModalKey(k => k + 1);
|
||||||
|
setModal({node, directory: isBookmarkDirectory(node), parentId});
|
||||||
|
},
|
||||||
|
move: async (node, parentId, position) => {
|
||||||
|
try {
|
||||||
|
await moveBookmark(node.id, parentId, position);
|
||||||
|
await refresh();
|
||||||
|
} catch (e) {
|
||||||
|
// Error toast already shown by the API client.
|
||||||
|
}
|
||||||
|
},
|
||||||
|
remove: async (node) => {
|
||||||
|
try {
|
||||||
|
await deleteBookmark(node.id);
|
||||||
|
await refresh();
|
||||||
|
} catch (e) {
|
||||||
|
}
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
// These reject on failure (the API client has already shown the toast) so the add
|
||||||
|
// forms know to keep what was typed.
|
||||||
|
const handleAddBookmark = async (bookmark) => {
|
||||||
|
await addBookmark(bookmark);
|
||||||
|
await refresh();
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleAddDirectory = async (directory) => {
|
||||||
|
await addBookmarkDirectory(directory);
|
||||||
|
await refresh();
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleEditSave = async ({name, url, new_tab, parent_id}) => {
|
||||||
|
const {node, directory, parentId} = modal;
|
||||||
|
try {
|
||||||
|
await updateBookmark(node.id, directory ? {name} : {name, url, new_tab});
|
||||||
|
} catch (e) {
|
||||||
|
return; // Nothing changed; the modal stays open with the toast beside it.
|
||||||
|
}
|
||||||
|
// The rename is committed even if the move is refused, so the nav must show it
|
||||||
|
// either way; only a fully successful edit closes the modal.
|
||||||
|
let moved = true;
|
||||||
|
if (parent_id !== parentId) {
|
||||||
|
try {
|
||||||
|
await moveBookmark(node.id, parent_id);
|
||||||
|
} catch (e) {
|
||||||
|
moved = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
await refresh();
|
||||||
|
if (moved) {
|
||||||
|
setModal(null);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
return <PageContainer>
|
||||||
|
<Panel>
|
||||||
|
<Header as='h1' icon={IconBookmark}>Bookmarks</Header>
|
||||||
|
<p>
|
||||||
|
Bookmarks appear in the Bookmarks menu of the navigation bar. They can point at pages on this
|
||||||
|
WROLPi, at other services running beside it, or anywhere on the web.
|
||||||
|
</p>
|
||||||
|
|
||||||
|
{nodes.length === 0
|
||||||
|
? <Message title='There are no bookmarks yet'>Add a bookmark below.</Message>
|
||||||
|
: <BookmarkTable nodes={nodes} actions={actions}/>}
|
||||||
|
|
||||||
|
<BookmarkAddForms nodes={nodes} onAddBookmark={handleAddBookmark} onAddDirectory={handleAddDirectory}/>
|
||||||
|
</Panel>
|
||||||
|
{modal && <BookmarkNodeModal
|
||||||
|
key={modalKey}
|
||||||
|
open
|
||||||
|
node={modal.node}
|
||||||
|
directory={modal.directory}
|
||||||
|
parentId={modal.parentId}
|
||||||
|
nodes={nodes}
|
||||||
|
onSave={handleEditSave}
|
||||||
|
onClose={() => setModal(null)}
|
||||||
|
/>}
|
||||||
|
</PageContainer>;
|
||||||
|
}
|
||||||
199
app/src/components/Bookmarks.test.js
Normal file
199
app/src/components/Bookmarks.test.js
Normal file
|
|
@ -0,0 +1,199 @@
|
||||||
|
import React from 'react';
|
||||||
|
import {screen} from '@testing-library/react';
|
||||||
|
import userEvent from '@testing-library/user-event';
|
||||||
|
import {render} from '../test-utils';
|
||||||
|
import {BookmarkAddForms, BookmarkNodeModal, BookmarkTable, directoryOptions, locationOptions} from './Bookmarks';
|
||||||
|
import {resolveBookmarkUrl} from '../contexts/BookmarksContext';
|
||||||
|
|
||||||
|
const tree = [
|
||||||
|
{id: 1, name: 'Channels', url: '/videos/channel', new_tab: false},
|
||||||
|
{
|
||||||
|
id: 2, name: 'Services', children: [
|
||||||
|
{id: 3, name: 'Jellyfin', url: ':8096/', new_tab: true},
|
||||||
|
{id: 4, name: 'Radio', children: []},
|
||||||
|
]
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
describe('resolveBookmarkUrl', () => {
|
||||||
|
const location = {protocol: 'https:', hostname: '10.0.0.2', host: '10.0.0.2'};
|
||||||
|
|
||||||
|
it.each([
|
||||||
|
['/videos', {internal: true, href: '/videos'}],
|
||||||
|
[' /videos/channel/3 ', {internal: true, href: '/videos/channel/3'}],
|
||||||
|
// A port on this host takes the page's scheme, or its own when it names one.
|
||||||
|
[':8096/web', {internal: false, href: 'https://10.0.0.2:8096/web'}],
|
||||||
|
[':8096', {internal: false, href: 'https://10.0.0.2:8096'}],
|
||||||
|
['http://:8096/web', {internal: false, href: 'http://10.0.0.2:8096/web'}],
|
||||||
|
['HTTPS://:8085', {internal: false, href: 'https://10.0.0.2:8085'}],
|
||||||
|
['https://example.com/a?b=c', {internal: false, href: 'https://example.com/a?b=c'}],
|
||||||
|
])('resolves %s', (url, expected) => {
|
||||||
|
expect(resolveBookmarkUrl(url, location)).toEqual(expected);
|
||||||
|
});
|
||||||
|
|
||||||
|
it.each([
|
||||||
|
// Paths a browser takes off this host: network paths, backslashes, and control
|
||||||
|
// characters a URL parser strips before deciding.
|
||||||
|
'//evil.com', '///evil.com', '/\\evil.com', '/\\@evil.com', '/\t/evil.com', '/\n/evil.com',
|
||||||
|
// Port forms where the host would become credentials.
|
||||||
|
':8096@evil.com', 'http://:8096@evil.com', ':8096\t@evil.com', ':8096/x@evil.com', ':8096\\evil.com',
|
||||||
|
// Not http(s).
|
||||||
|
'javascript:alert(1)', 'data:text/html,hi', 'ftp://example.com', 'videos', '',
|
||||||
|
])('refuses %j rather than guessing', (url) => {
|
||||||
|
expect(resolveBookmarkUrl(url, location)).toEqual({internal: false, href: null});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('brackets an IPv6 host for a port bookmark', () => {
|
||||||
|
// The browser reports an IPv6 hostname bracketed already.
|
||||||
|
const v6 = {protocol: 'https:', hostname: '[::1]', host: '[::1]'};
|
||||||
|
expect(resolveBookmarkUrl(':8096/web', v6)).toEqual({internal: false, href: 'https://[::1]:8096/web'});
|
||||||
|
expect(resolveBookmarkUrl(':8096', {protocol: 'http:', hostname: '::1', host: '[::1]'}))
|
||||||
|
.toEqual({internal: false, href: 'http://[::1]:8096'});
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('directoryOptions', () => {
|
||||||
|
it('lists every directory with its path, and no bookmarks', () => {
|
||||||
|
expect(directoryOptions(tree)).toEqual([
|
||||||
|
{value: '2', label: 'Services', id: 2},
|
||||||
|
{value: '4', label: 'Services / Radio', id: 4},
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('BookmarkTable', () => {
|
||||||
|
const actions = () => ({edit: jest.fn(), move: jest.fn(), remove: jest.fn()});
|
||||||
|
|
||||||
|
it('renders the tree with resolved links, numbered within each directory', () => {
|
||||||
|
render(<BookmarkTable nodes={tree} actions={actions()}/>);
|
||||||
|
const channels = screen.getByRole('link', {name: 'Channels'});
|
||||||
|
expect(channels).toHaveAttribute('href', '/videos/channel');
|
||||||
|
expect(channels).not.toHaveAttribute('target');
|
||||||
|
const jellyfin = screen.getByRole('link', {name: 'Jellyfin'});
|
||||||
|
expect(jellyfin).toHaveAttribute('href', `${window.location.protocol}//${window.location.hostname}:8096/`);
|
||||||
|
expect(jellyfin).toHaveAttribute('target', '_blank');
|
||||||
|
expect(screen.getByText('Radio')).toBeInTheDocument();
|
||||||
|
// Channels, Services, then Services' two children.
|
||||||
|
const numbers = screen.getAllByRole('row').slice(1).map(row => row.firstChild.textContent);
|
||||||
|
expect(numbers).toEqual(['01', '02', '01', '02']);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('moves a node among its siblings and only within bounds', async () => {
|
||||||
|
const a = actions();
|
||||||
|
render(<BookmarkTable nodes={tree} actions={a}/>);
|
||||||
|
// The first top-level node cannot move up; the last cannot move down.
|
||||||
|
expect(screen.getByRole('button', {name: 'Move Channels up'})).toBeDisabled();
|
||||||
|
expect(screen.getByRole('button', {name: 'Move Services down'})).toBeDisabled();
|
||||||
|
|
||||||
|
await userEvent.click(screen.getByRole('button', {name: 'Move Channels down'}));
|
||||||
|
expect(a.move).toHaveBeenCalledWith(tree[0], null, 1);
|
||||||
|
// A child moves within its directory: parent 2, from index 1 to 0.
|
||||||
|
await userEvent.click(screen.getByRole('button', {name: 'Move Radio up'}));
|
||||||
|
expect(a.move).toHaveBeenCalledWith(tree[1].children[1], 2, 0);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('shows a bookmark whose URL does not resolve as text, not a link', () => {
|
||||||
|
const nodes = [{id: 1, name: 'Bad', url: '//evil.com', new_tab: false}];
|
||||||
|
render(<BookmarkTable nodes={nodes} actions={actions()}/>);
|
||||||
|
expect(screen.queryByRole('link', {name: 'Bad'})).not.toBeInTheDocument();
|
||||||
|
expect(screen.getByText('Bad')).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('edits with the parent the node lives in, and deletes a bookmark without asking', async () => {
|
||||||
|
const a = actions();
|
||||||
|
render(<BookmarkTable nodes={tree} actions={a}/>);
|
||||||
|
await userEvent.click(screen.getByRole('button', {name: 'Edit Jellyfin'}));
|
||||||
|
expect(a.edit).toHaveBeenCalledWith(tree[1].children[0], 2);
|
||||||
|
await userEvent.click(screen.getByRole('button', {name: 'Delete Channels'}));
|
||||||
|
expect(a.remove).toHaveBeenCalledWith(tree[0]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('asks before deleting a directory, since its contents go with it', async () => {
|
||||||
|
const a = actions();
|
||||||
|
render(<BookmarkTable nodes={tree} actions={a}/>);
|
||||||
|
await userEvent.click(screen.getByRole('button', {name: 'Delete Services'}));
|
||||||
|
expect(a.remove).not.toHaveBeenCalled();
|
||||||
|
await userEvent.click(await screen.findByRole('button', {name: 'Delete'}));
|
||||||
|
expect(a.remove).toHaveBeenCalledWith(tree[1]);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('BookmarkAddForms', () => {
|
||||||
|
it('adds a bookmark at the top level and clears the form', async () => {
|
||||||
|
const onAddBookmark = jest.fn();
|
||||||
|
render(<BookmarkAddForms nodes={tree} onAddBookmark={onAddBookmark} onAddDirectory={jest.fn()}/>);
|
||||||
|
const adds = screen.getAllByRole('button', {name: 'Add'});
|
||||||
|
expect(adds[0]).toBeDisabled();
|
||||||
|
|
||||||
|
await userEvent.type(screen.getByLabelText('Bookmark URL'), ':8123/');
|
||||||
|
expect(adds[0]).toBeDisabled();
|
||||||
|
await userEvent.type(screen.getByLabelText('Bookmark name'), 'Home Assistant');
|
||||||
|
await userEvent.click(screen.getByLabelText('New tab'));
|
||||||
|
await userEvent.click(adds[0]);
|
||||||
|
|
||||||
|
expect(onAddBookmark).toHaveBeenCalledWith({name: 'Home Assistant', url: ':8123/', new_tab: true, parent_id: null});
|
||||||
|
expect(screen.getByLabelText('Bookmark URL')).toHaveValue('');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('keeps what was typed when the server refuses the bookmark', async () => {
|
||||||
|
const onAddBookmark = jest.fn().mockRejectedValue(new Error('refused'));
|
||||||
|
render(<BookmarkAddForms nodes={tree} onAddBookmark={onAddBookmark} onAddDirectory={jest.fn()}/>);
|
||||||
|
await userEvent.type(screen.getByLabelText('Bookmark URL'), '//evil.com');
|
||||||
|
await userEvent.type(screen.getByLabelText('Bookmark name'), 'Oops');
|
||||||
|
await userEvent.click(screen.getAllByRole('button', {name: 'Add'})[0]);
|
||||||
|
|
||||||
|
expect(onAddBookmark).toHaveBeenCalled();
|
||||||
|
expect(screen.getByLabelText('Bookmark URL')).toHaveValue('//evil.com');
|
||||||
|
expect(screen.getByLabelText('Bookmark name')).toHaveValue('Oops');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('adds a directory', async () => {
|
||||||
|
const onAddDirectory = jest.fn();
|
||||||
|
render(<BookmarkAddForms nodes={tree} onAddBookmark={jest.fn()} onAddDirectory={onAddDirectory}/>);
|
||||||
|
await userEvent.type(screen.getByLabelText('Directory name'), 'Tools');
|
||||||
|
await userEvent.click(screen.getAllByRole('button', {name: 'Add'})[1]);
|
||||||
|
expect(onAddDirectory).toHaveBeenCalledWith({name: 'Tools', parent_id: null});
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('BookmarkNodeModal', () => {
|
||||||
|
// Mantine's Select scrolls the highlighted option into view; jsdom has no layout.
|
||||||
|
beforeAll(() => {
|
||||||
|
Element.prototype.scrollIntoView = jest.fn();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('saves a new bookmark with its location and new-tab choice', async () => {
|
||||||
|
const onSave = jest.fn();
|
||||||
|
render(<BookmarkNodeModal open node={null} directory={false} parentId={2} nodes={tree}
|
||||||
|
onSave={onSave} onClose={jest.fn()}/>);
|
||||||
|
const save = screen.getByRole('button', {name: 'Save'});
|
||||||
|
expect(save).toBeDisabled();
|
||||||
|
|
||||||
|
await userEvent.type(screen.getByLabelText('Name'), 'Home Assistant');
|
||||||
|
expect(save).toBeDisabled();
|
||||||
|
await userEvent.type(screen.getByLabelText('URL'), ':8123/');
|
||||||
|
await userEvent.click(screen.getByLabelText('Open in a new tab'));
|
||||||
|
await userEvent.click(save);
|
||||||
|
|
||||||
|
expect(onSave).toHaveBeenCalledWith({name: 'Home Assistant', url: ':8123/', new_tab: true, parent_id: 2});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('a directory has no URL or new-tab choice', () => {
|
||||||
|
render(<BookmarkNodeModal open node={tree[1]} directory parentId={null} nodes={tree}
|
||||||
|
onSave={jest.fn()} onClose={jest.fn()}/>);
|
||||||
|
expect(screen.getByLabelText('Name')).toHaveValue('Services');
|
||||||
|
expect(screen.queryByLabelText('URL')).not.toBeInTheDocument();
|
||||||
|
expect(screen.queryByLabelText('Open in a new tab')).not.toBeInTheDocument();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('locationOptions', () => {
|
||||||
|
it('offers the top level and every directory to a new node', () => {
|
||||||
|
expect(locationOptions(tree).map(o => o.label)).toEqual(['Top level', 'Services', 'Services / Radio']);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('never offers a directory itself, or its children', () => {
|
||||||
|
expect(locationOptions(tree, tree[1]).map(o => o.label)).toEqual(['Top level']);
|
||||||
|
expect(locationOptions(tree, tree[1].children[1]).map(o => o.label)).toEqual(['Top level', 'Services']);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
@ -2,7 +2,6 @@ import React from "react";
|
||||||
import {Breadcrumbs, useTitle} from "./Common";
|
import {Breadcrumbs, useTitle} from "./Common";
|
||||||
import {Button, Header, Icon} from "./ui";
|
import {Button, Header, Icon} from "./ui";
|
||||||
import {useCalcQuery} from "../hooks/customHooks";
|
import {useCalcQuery} from "../hooks/customHooks";
|
||||||
import {TemperatureCalculator} from "./calculators/TemperatureCalculator";
|
|
||||||
import {ElectricalCalculators} from "./calculators/ElectricalCalculators";
|
import {ElectricalCalculators} from "./calculators/ElectricalCalculators";
|
||||||
import {DipoleAntennaCalculator} from "./calculators/HamCalculators";
|
import {DipoleAntennaCalculator} from "./calculators/HamCalculators";
|
||||||
import {Link} from "react-router";
|
import {Link} from "react-router";
|
||||||
|
|
@ -14,6 +13,7 @@ import {FoodStorageCalculator} from "./calculators/FoodStorageCalculator";
|
||||||
import {OneTimePadCalculator} from "./calculators/OneTimePadCalculator";
|
import {OneTimePadCalculator} from "./calculators/OneTimePadCalculator";
|
||||||
import {VinDecoderCalculator} from "./calculators/VinDecoderCalculator";
|
import {VinDecoderCalculator} from "./calculators/VinDecoderCalculator";
|
||||||
import {SpeedTestCalculator} from "./calculators/SpeedTestCalculator";
|
import {SpeedTestCalculator} from "./calculators/SpeedTestCalculator";
|
||||||
|
import {SolarCalculator} from "./calculators/SolarCalculator";
|
||||||
|
|
||||||
// Calculators are shown in these titled groups, in this order. Each calculator carries a
|
// Calculators are shown in these titled groups, in this order. Each calculator carries a
|
||||||
// `group` matching one of these names; any calculator whose group is missing/unknown falls
|
// `group` matching one of these names; any calculator whose group is missing/unknown falls
|
||||||
|
|
@ -35,10 +35,10 @@ export const useCalculators = () => {
|
||||||
{key: 'ratio', icon: 'th large', button: 'Ratio', group: 'Engineering', contents: <RatioCalculators/>},
|
{key: 'ratio', icon: 'th large', button: 'Ratio', group: 'Engineering', contents: <RatioCalculators/>},
|
||||||
{key: 'electrical', icon: 'lightning', button: 'Electrical', group: 'Engineering', contents: <ElectricalCalculators/>},
|
{key: 'electrical', icon: 'lightning', button: 'Electrical', group: 'Engineering', contents: <ElectricalCalculators/>},
|
||||||
{key: 'drive', icon: 'cogs', button: 'Drive Ratio', group: 'Engineering', contents: <DriveCalculator/>},
|
{key: 'drive', icon: 'cogs', button: 'Drive Ratio', group: 'Engineering', contents: <DriveCalculator/>},
|
||||||
|
{key: 'solar', icon: 'sun', button: 'Solar', group: 'Engineering', contents: <SolarCalculator/>},
|
||||||
{key: 'water', icon: 'tint', button: 'Water Storage', group: 'Preparedness & Storage', contents: <WaterCalculator/>},
|
{key: 'water', icon: 'tint', button: 'Water Storage', group: 'Preparedness & Storage', contents: <WaterCalculator/>},
|
||||||
{key: 'ration', icon: 'food', button: 'Food Storage', group: 'Preparedness & Storage', contents: <FoodStorageCalculator/>},
|
{key: 'ration', icon: 'food', button: 'Food Storage', group: 'Preparedness & Storage', contents: <FoodStorageCalculator/>},
|
||||||
{key: 'antenna', icon: 'signal', button: 'Antenna', group: 'Radio & Communications', contents: <DipoleAntennaCalculator/>},
|
{key: 'antenna', icon: 'signal', button: 'Antenna', group: 'Radio & Communications', contents: <DipoleAntennaCalculator/>},
|
||||||
{key: 'temperature', icon: 'thermometer', button: 'Temperature', group: 'Tools & Reference', contents: <TemperatureCalculator/>},
|
|
||||||
{key: 'qrCode', icon: 'qrcode', button: 'QR Code', group: 'Tools & Reference', contents: <QRCodeCalculator/>},
|
{key: 'qrCode', icon: 'qrcode', button: 'QR Code', group: 'Tools & Reference', contents: <QRCodeCalculator/>},
|
||||||
{key: 'otp', icon: 'lock', button: 'One Time Pad', title: 'One Time Pad', group: 'Radio & Communications', contents: <OneTimePadCalculator/>},
|
{key: 'otp', icon: 'lock', button: 'One Time Pad', title: 'One Time Pad', group: 'Radio & Communications', contents: <OneTimePadCalculator/>},
|
||||||
{key: 'vin', icon: 'car', button: 'VIN Decoder', title: 'VIN Decoder', group: 'Tools & Reference', contents: <VinDecoderCalculator/>},
|
{key: 'vin', icon: 'car', button: 'VIN Decoder', title: 'VIN Decoder', group: 'Tools & Reference', contents: <VinDecoderCalculator/>},
|
||||||
|
|
|
||||||
|
|
@ -3,6 +3,7 @@ import {IconArrowLeft, IconArrowRight} from '@tabler/icons-react';
|
||||||
import {getArchiveContents, getArchiveMemberUrl} from '../api';
|
import {getArchiveContents, getArchiveMemberUrl} from '../api';
|
||||||
import {IconButton, Label, Loading, Message} from './ui';
|
import {IconButton, Label, Loading, Message} from './ui';
|
||||||
import {useLocalStorage} from './Common';
|
import {useLocalStorage} from './Common';
|
||||||
|
import {usePageProgress} from '../hooks/useFileProgress';
|
||||||
|
|
||||||
const IMAGE_EXTENSIONS = /\.(jpe?g|png|gif|webp|bmp|tiff?)$/i;
|
const IMAGE_EXTENSIONS = /\.(jpe?g|png|gif|webp|bmp|tiff?)$/i;
|
||||||
|
|
||||||
|
|
@ -22,9 +23,20 @@ function flattenEntries(entries, prefix = '') {
|
||||||
return paths;
|
return paths;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function CbzViewer({path}) {
|
/**
|
||||||
|
* @param path The comic book file.
|
||||||
|
* @param progressPath The FileGroup's primary path, to resume and save the reader's page; omit to not track it.
|
||||||
|
* @param fileGroup The FileGroup JSON, which holds the saved page.
|
||||||
|
*/
|
||||||
|
export function CbzViewer({path, progressPath = null, fileGroup = null}) {
|
||||||
const [pages, setPages] = useState(null);
|
const [pages, setPages] = useState(null);
|
||||||
const [currentPage, setCurrentPage] = useState(0);
|
const [currentPage, setCurrentPage] = useState(0);
|
||||||
|
const {initialPage, onPageChange} = usePageProgress(progressPath, fileGroup, {enabled: !!progressPath});
|
||||||
|
// Read when the pages load; a later save must not move the reader.
|
||||||
|
const initialPageRef = useRef(initialPage);
|
||||||
|
initialPageRef.current = initialPage;
|
||||||
|
// The page shown on opening is where the reader already is (or the cover of a finished comic); it is not saved.
|
||||||
|
const justOpenedRef = useRef(true);
|
||||||
const [rtl, setRtl] = useLocalStorage('cbzViewerRtl', false);
|
const [rtl, setRtl] = useLocalStorage('cbzViewerRtl', false);
|
||||||
const [fullscreen, setFullscreen] = useState(false);
|
const [fullscreen, setFullscreen] = useState(false);
|
||||||
const [error, setError] = useState(null);
|
const [error, setError] = useState(null);
|
||||||
|
|
@ -41,8 +53,9 @@ export function CbzViewer({path}) {
|
||||||
.filter(name => IMAGE_EXTENSIONS.test(name))
|
.filter(name => IMAGE_EXTENSIONS.test(name))
|
||||||
.sort();
|
.sort();
|
||||||
const urls = images.map(member => getArchiveMemberUrl(path, member));
|
const urls = images.map(member => getArchiveMemberUrl(path, member));
|
||||||
|
justOpenedRef.current = true;
|
||||||
setPages(urls);
|
setPages(urls);
|
||||||
setCurrentPage(0);
|
setCurrentPage(Math.min(initialPageRef.current, Math.max(urls.length - 1, 0)));
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
setError(e.message || 'Could not read archive contents.');
|
setError(e.message || 'Could not read archive contents.');
|
||||||
}
|
}
|
||||||
|
|
@ -50,6 +63,17 @@ export function CbzViewer({path}) {
|
||||||
load();
|
load();
|
||||||
}, [path]);
|
}, [path]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!pages || pages.length === 0) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (justOpenedRef.current) {
|
||||||
|
justOpenedRef.current = false;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
onPageChange(currentPage, pages.length);
|
||||||
|
}, [currentPage, pages, onPageChange]);
|
||||||
|
|
||||||
const goNext = useCallback(() => {
|
const goNext = useCallback(() => {
|
||||||
setCurrentPage(p => Math.min(p + 1, (pages?.length || 1) - 1));
|
setCurrentPage(p => Math.min(p + 1, (pages?.length || 1) - 1));
|
||||||
}, [pages]);
|
}, [pages]);
|
||||||
|
|
|
||||||
84
app/src/components/CbzViewer.test.js
Normal file
84
app/src/components/CbzViewer.test.js
Normal file
|
|
@ -0,0 +1,84 @@
|
||||||
|
import React from 'react';
|
||||||
|
import {act, fireEvent, screen} from '@testing-library/react';
|
||||||
|
import {renderWithProviders} from '../test-utils';
|
||||||
|
import {CbzViewer} from './CbzViewer';
|
||||||
|
import {getArchiveContents} from '../api';
|
||||||
|
|
||||||
|
jest.mock('../api', () => ({
|
||||||
|
...jest.requireActual('../api'),
|
||||||
|
getArchiveContents: jest.fn(),
|
||||||
|
getArchiveMemberUrl: (path, member) => `/member/${member}`,
|
||||||
|
}));
|
||||||
|
|
||||||
|
const PATH = 'comics/issue.cbz';
|
||||||
|
const PAGES = ['01.jpg', '02.jpg', '03.jpg', '04.jpg'];
|
||||||
|
|
||||||
|
const {fetch: realFetch} = global;
|
||||||
|
const realSendBeacon = navigator.sendBeacon;
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
window.sessionStorage.clear();
|
||||||
|
getArchiveContents.mockResolvedValue({entries: PAGES.map(name => ({name, path: name, is_dir: false}))});
|
||||||
|
navigator.sendBeacon = jest.fn(() => false);
|
||||||
|
global.fetch = jest.fn(() => Promise.resolve({ok: true}));
|
||||||
|
});
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
global.fetch = realFetch;
|
||||||
|
navigator.sendBeacon = realSendBeacon;
|
||||||
|
});
|
||||||
|
|
||||||
|
const saves = () => global.fetch.mock.calls.map(([, init]) => JSON.parse(init.body));
|
||||||
|
|
||||||
|
describe('CbzViewer progress', () => {
|
||||||
|
test('opens at the saved page, and saves the page the reader leaves on', async () => {
|
||||||
|
const fileGroup = {progress: 0.75, position: {kind: 'page', page: 2, updated_at: 1000}};
|
||||||
|
const {unmount} = renderWithProviders(
|
||||||
|
<CbzViewer path={PATH} progressPath={PATH} fileGroup={fileGroup}/>);
|
||||||
|
|
||||||
|
expect(await screen.findByText('3 / 4')).toBeInTheDocument();
|
||||||
|
expect(screen.getByAltText('Page 3')).toHaveAttribute('src', '/member/03.jpg');
|
||||||
|
|
||||||
|
fireEvent.click(screen.getByLabelText('Next page'));
|
||||||
|
expect(screen.getByText('4 / 4')).toBeInTheDocument();
|
||||||
|
|
||||||
|
unmount();
|
||||||
|
expect(saves()).toEqual([expect.objectContaining({
|
||||||
|
file: PATH, progress: 1, final: true, position: expect.objectContaining({kind: 'page', page: 3}),
|
||||||
|
})]);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a saved page past the end opens the last page', async () => {
|
||||||
|
const fileGroup = {progress: 0.5, position: {kind: 'page', page: 40, updated_at: 1000}};
|
||||||
|
renderWithProviders(<CbzViewer path={PATH} progressPath={PATH} fileGroup={fileGroup}/>);
|
||||||
|
expect(await screen.findByText('4 / 4')).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('without a progress path it opens at the first page and saves nothing', async () => {
|
||||||
|
const fileGroup = {progress: 0.75, position: {kind: 'page', page: 2, updated_at: 1000}};
|
||||||
|
const {unmount} = renderWithProviders(<CbzViewer path={PATH} fileGroup={fileGroup}/>);
|
||||||
|
expect(await screen.findByText('1 / 4')).toBeInTheDocument();
|
||||||
|
await act(async () => fireEvent.click(screen.getByLabelText('Next page')));
|
||||||
|
unmount();
|
||||||
|
expect(saves()).toEqual([]);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('opening a comic saves nothing, so a finished comic stays finished', async () => {
|
||||||
|
const fileGroup = {progress: 1, position: null, viewed: new Date(9000).toISOString()};
|
||||||
|
const {unmount} = renderWithProviders(<CbzViewer path={PATH} progressPath={PATH} fileGroup={fileGroup}/>);
|
||||||
|
expect(await screen.findByText('1 / 4')).toBeInTheDocument();
|
||||||
|
unmount();
|
||||||
|
expect(saves()).toEqual([]);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('peeking at the cover keeps the reader\'s place', async () => {
|
||||||
|
const fileGroup = {progress: 0.75, position: {kind: 'page', page: 2, updated_at: 1000}};
|
||||||
|
const {unmount} = renderWithProviders(<CbzViewer path={PATH} progressPath={PATH} fileGroup={fileGroup}/>);
|
||||||
|
expect(await screen.findByText('3 / 4')).toBeInTheDocument();
|
||||||
|
fireEvent.click(screen.getByLabelText('Previous page'));
|
||||||
|
fireEvent.click(screen.getByLabelText('Previous page'));
|
||||||
|
expect(screen.getByText('1 / 4')).toBeInTheDocument();
|
||||||
|
unmount();
|
||||||
|
expect(saves()).toEqual([expect.objectContaining({position: expect.objectContaining({page: 1})})]);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
@ -49,7 +49,7 @@ describe('Channels Page', () => {
|
||||||
{initialEntries: ['/videos/channel/1/edit']}
|
{initialEntries: ['/videos/channel/1/edit']}
|
||||||
);
|
);
|
||||||
cy.wait('@channelFetch');
|
cy.wait('@channelFetch');
|
||||||
cy.wait('@searchDirectories'); // Needed for CircleCi.
|
cy.wait('@searchDirectories'); // Needed in CI.
|
||||||
cy.wait(500);
|
cy.wait(500);
|
||||||
cy.get('input[name="name"]').should('be.visible');
|
cy.get('input[name="name"]').should('be.visible');
|
||||||
cy.get('input[name="name"]').should('have.value', 'Editing Channel');
|
cy.get('input[name="name"]').should('have.value', 'Editing Channel');
|
||||||
|
|
|
||||||
|
|
@ -757,6 +757,18 @@ export function findPosterPath(file) {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** How far the user is through a file, as a bar along the bottom of its poster. A full bar is finished. */
|
||||||
|
export function ViewProgress({progress}) {
|
||||||
|
if (!(progress > 0)) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
const percent = Math.round(Math.min(progress, 1) * 100);
|
||||||
|
return <div className='wrolpi-view-progress' role='progressbar' aria-label='Viewing progress'
|
||||||
|
aria-valuemin={0} aria-valuemax={100} aria-valuenow={percent}>
|
||||||
|
<div className='wrolpi-view-progress-bar' style={{width: `${percent}%`}}/>
|
||||||
|
</div>
|
||||||
|
}
|
||||||
|
|
||||||
export function CardPoster({to, file, overlay}) {
|
export function CardPoster({to, file, overlay}) {
|
||||||
const navigate = useNavigate();
|
const navigate = useNavigate();
|
||||||
|
|
||||||
|
|
@ -785,6 +797,7 @@ export function CardPoster({to, file, overlay}) {
|
||||||
{imageLabel}
|
{imageLabel}
|
||||||
<img alt='poster' src={posterPath}/>
|
<img alt='poster' src={posterPath}/>
|
||||||
{overlay}
|
{overlay}
|
||||||
|
<ViewProgress progress={file.progress}/>
|
||||||
</>;
|
</>;
|
||||||
|
|
||||||
return <div className='wrolpi-card-poster'>
|
return <div className='wrolpi-card-poster'>
|
||||||
|
|
@ -802,6 +815,7 @@ export function CardPoster({to, file, overlay}) {
|
||||||
<div className='wrolpi-card-icon'>
|
<div className='wrolpi-card-icon'>
|
||||||
{imageLabel}
|
{imageLabel}
|
||||||
<FileIcon file={file}/>
|
<FileIcon file={file}/>
|
||||||
|
<ViewProgress progress={file.progress}/>
|
||||||
</div>
|
</div>
|
||||||
</PreviewLink>
|
</PreviewLink>
|
||||||
} else if (!posterPath && to) {
|
} else if (!posterPath && to) {
|
||||||
|
|
@ -810,6 +824,7 @@ export function CardPoster({to, file, overlay}) {
|
||||||
<div className='wrolpi-card-icon' onClick={() => navigate(to)}>
|
<div className='wrolpi-card-icon' onClick={() => navigate(to)}>
|
||||||
{imageLabel}
|
{imageLabel}
|
||||||
<FileIcon file={file}/>
|
<FileIcon file={file}/>
|
||||||
|
<ViewProgress progress={file.progress}/>
|
||||||
</div>
|
</div>
|
||||||
</Link>
|
</Link>
|
||||||
}
|
}
|
||||||
|
|
@ -928,7 +943,10 @@ export function HelpHeader({
|
||||||
// why it cannot be used. `confirmStop` asks before switching off.
|
// why it cannot be used. `confirmStop` asks before switching off.
|
||||||
function SubsystemToggle({label, on, onChange, unsupportedMessage, info = null, disabled = null, confirmStop = null}) {
|
function SubsystemToggle({label, on, onChange, unsupportedMessage, info = null, disabled = null, confirmStop = null}) {
|
||||||
const [confirmOpen, setConfirmOpen] = React.useState(false);
|
const [confirmOpen, setConfirmOpen] = React.useState(false);
|
||||||
|
// null = the status has loaded without this subsystem; undefined = the status has not loaded
|
||||||
|
// yet (or a call is in flight). Both disable the toggle; only the first claims unsupported.
|
||||||
const unsupported = on === null;
|
const unsupported = on === null;
|
||||||
|
const unknown = on === undefined;
|
||||||
|
|
||||||
const handleChange = (checked) => {
|
const handleChange = (checked) => {
|
||||||
if (!checked && confirmStop) {
|
if (!checked && confirmStop) {
|
||||||
|
|
@ -961,11 +979,11 @@ function SubsystemToggle({label, on, onChange, unsupportedMessage, info = null,
|
||||||
</Confirm>}
|
</Confirm>}
|
||||||
<Toggle
|
<Toggle
|
||||||
label={label}
|
label={label}
|
||||||
disabled={disabled === null ? unsupported : disabled}
|
disabled={disabled === null ? (unsupported || unknown) : disabled}
|
||||||
checked={on === true}
|
checked={on === true}
|
||||||
onChange={handleChange}
|
onChange={handleChange}
|
||||||
/>
|
/>
|
||||||
{popup && <InfoPopup content={popup}/>}
|
{popup && <span data-testid='subsystem-popup'><InfoPopup content={popup}/></span>}
|
||||||
</div>;
|
</div>;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -1065,9 +1083,10 @@ export function Toggle({label, checked, disabled, onChange, icon, popupContent =
|
||||||
|
|
||||||
export function DisableDownloadsToggle() {
|
export function DisableDownloadsToggle() {
|
||||||
const [pending, setPending] = React.useState(false);
|
const [pending, setPending] = React.useState(false);
|
||||||
const {status, fetchStatus} = React.useContext(StatusContext);
|
const {status, fetchStatus, loaded} = React.useContext(StatusContext);
|
||||||
|
|
||||||
const {downloads} = status ? status : {downloads: null};
|
// Until the first status poll lands there is no downloads state to show, only a disabled toggle.
|
||||||
|
const downloads = loaded ? status?.downloads : null;
|
||||||
const wrolModeEnabled = useWROLMode();
|
const wrolModeEnabled = useWROLMode();
|
||||||
|
|
||||||
const setDownloads = async (enable) => {
|
const setDownloads = async (enable) => {
|
||||||
|
|
@ -1082,8 +1101,9 @@ export function DisableDownloadsToggle() {
|
||||||
}
|
}
|
||||||
|
|
||||||
const on = downloads && downloads['disabled'] === false && downloads['stopped'] === false;
|
const on = downloads && downloads['disabled'] === false && downloads['stopped'] === false;
|
||||||
|
const label = downloads === null ? 'Downloading' : on === true ? 'Downloading Enabled' : 'Downloading Disabled';
|
||||||
return <Toggle
|
return <Toggle
|
||||||
label={on === true ? 'Downloading Enabled' : 'Downloading Disabled'}
|
label={label}
|
||||||
disabled={wrolModeEnabled || pending || downloads === null}
|
disabled={wrolModeEnabled || pending || downloads === null}
|
||||||
checked={on === true}
|
checked={on === true}
|
||||||
onChange={setDownloads}
|
onChange={setDownloads}
|
||||||
|
|
@ -1160,7 +1180,7 @@ export function mimetypeIconName(mimetype, lowerPath = '') {
|
||||||
return 'file code';
|
return 'file code';
|
||||||
} else if (mimetype.startsWith('application/pdf')) {
|
} else if (mimetype.startsWith('application/pdf')) {
|
||||||
return 'file pdf';
|
return 'file pdf';
|
||||||
} else if (mimetype.startsWith('text/plain')) {
|
} else if (mimetype.startsWith('text/plain') || mimetype.startsWith('text/markdown')) {
|
||||||
return 'file text';
|
return 'file text';
|
||||||
} else if (mimetype.startsWith('image/')) {
|
} else if (mimetype.startsWith('image/')) {
|
||||||
return 'image';
|
return 'image';
|
||||||
|
|
|
||||||
|
|
@ -1121,7 +1121,7 @@ describe('a row of buttons', () => {
|
||||||
* the two had been inline before.
|
* the two had been inline before.
|
||||||
*
|
*
|
||||||
* A row fixes it without touching the stack: the row is the stretched child, and it lays
|
* A row fixes it without touching the stack: the row is the stretched child, and it lays
|
||||||
* its buttons out at their own width. Nine sites, so this scan rather than nine
|
* its buttons out at their own width. Thirteen sites, so this scan rather than thirteen
|
||||||
* assertions -- and a scan because a stretched button is still a working button.
|
* assertions -- and a scan because a stretched button is still a working button.
|
||||||
*/
|
*/
|
||||||
const offenders = [];
|
const offenders = [];
|
||||||
|
|
@ -1140,8 +1140,8 @@ describe('a row of buttons', () => {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Nine renders. Common.js declares it, and a declaration is not a `<BackButton`.
|
// Thirteen renders. Common.js declares it, and a declaration is not a `<BackButton`.
|
||||||
expect(found).toBe(9);
|
expect(found).toBe(13);
|
||||||
|
|
||||||
expect(offenders).toEqual([]);
|
expect(offenders).toEqual([]);
|
||||||
});
|
});
|
||||||
|
|
|
||||||
|
|
@ -38,6 +38,7 @@ import {toast} from "./ui";
|
||||||
import {CollectionTable} from "./collections/CollectionTable";
|
import {CollectionTable} from "./collections/CollectionTable";
|
||||||
import {AddToPlaylistButton} from "./AddToPlaylist";
|
import {AddToPlaylistButton} from "./AddToPlaylist";
|
||||||
import {CbzViewer} from "./CbzViewer";
|
import {CbzViewer} from "./CbzViewer";
|
||||||
|
import {useEpubProgress} from "../hooks/useFileProgress";
|
||||||
import _ from "lodash";
|
import _ from "lodash";
|
||||||
|
|
||||||
function DocsPage() {
|
function DocsPage() {
|
||||||
|
|
@ -165,6 +166,23 @@ function DocsPage() {
|
||||||
</>;
|
</>;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The embedded viewer (the EPUB viewer, or the browser's PDF viewer). An EPUB opens where the user left off,
|
||||||
|
* unless a search result says where (`deepLinked`), and saves their place as they read.
|
||||||
|
*
|
||||||
|
* @param epubProgressPath The FileGroup's primary path when an EPUB is shown and tracked, otherwise null.
|
||||||
|
*/
|
||||||
|
function DocViewerFrame({url, epubProgressPath, fileGroup, deepLinked, title}) {
|
||||||
|
const {iframeRef, resumeCfi} = useEpubProgress(epubProgressPath, fileGroup, {enabled: !!epubProgressPath});
|
||||||
|
const src = resumeCfi && !deepLinked ? `${url}&cfi=${encodeURIComponent(resumeCfi)}` : url;
|
||||||
|
return <iframe
|
||||||
|
ref={iframeRef}
|
||||||
|
src={src}
|
||||||
|
title={title}
|
||||||
|
style={{width: '100%', height: '80vh', border: '1px solid var(--border)'}}
|
||||||
|
/>
|
||||||
|
}
|
||||||
|
|
||||||
function DocPage() {
|
function DocPage() {
|
||||||
const {fileGroupId} = useParams();
|
const {fileGroupId} = useParams();
|
||||||
const navigate = useNavigate();
|
const navigate = useNavigate();
|
||||||
|
|
@ -245,6 +263,8 @@ function DocPage() {
|
||||||
? `/media/${encodeMediaPath(activePath)}${pageParam ? `#page=${encodeURIComponent(pageParam)}` : ''}`
|
? `/media/${encodeMediaPath(activePath)}${pageParam ? `#page=${encodeURIComponent(pageParam)}` : ''}`
|
||||||
: null;
|
: null;
|
||||||
const embedUrl = isEpub ? viewerUrl : pdfSrc;
|
const embedUrl = isEpub ? viewerUrl : pdfSrc;
|
||||||
|
// Progress belongs to the FileGroup; another format of the same book (a PDF beside the EPUB) is not tracked.
|
||||||
|
const trackedPath = String(activePath) === String(docFile.primary_path) ? docFile.primary_path : null;
|
||||||
|
|
||||||
const handleDelete = async (force = false) => {
|
const handleDelete = async (force = false) => {
|
||||||
if (doc && doc.id) {
|
if (doc && doc.id) {
|
||||||
|
|
@ -354,7 +374,7 @@ function DocPage() {
|
||||||
return <>
|
return <>
|
||||||
<div className='wrolpi-button-row'><BackButton/></div>
|
<div className='wrolpi-button-row'><BackButton/></div>
|
||||||
|
|
||||||
{isCbz && activePath && <CbzViewer path={activePath}/>}
|
{isCbz && activePath && <CbzViewer path={activePath} progressPath={trackedPath} fileGroup={docFile}/>}
|
||||||
|
|
||||||
{canEmbed && embedUrl && !isCbz && <div style={{marginBottom: '1em'}}>
|
{canEmbed && embedUrl && !isCbz && <div style={{marginBottom: '1em'}}>
|
||||||
{/*
|
{/*
|
||||||
|
|
@ -364,11 +384,8 @@ function DocPage() {
|
||||||
* re-gates rather than inheriting the last one's reveal.
|
* re-gates rather than inheriting the last one's reveal.
|
||||||
*/}
|
*/}
|
||||||
<MediaGate key={activePath} gated={isPdf && mediaFilterEnabled}>
|
<MediaGate key={activePath} gated={isPdf && mediaFilterEnabled}>
|
||||||
<iframe
|
<DocViewerFrame url={embedUrl} epubProgressPath={isEpub ? trackedPath : null} fileGroup={docFile}
|
||||||
src={embedUrl}
|
deepLinked={!!locParam} title={docFile.title || docFile.name}/>
|
||||||
title={docFile.title || docFile.name}
|
|
||||||
style={{width: '100%', height: '80vh', border: '1px solid var(--border)'}}
|
|
||||||
/>
|
|
||||||
</MediaGate>
|
</MediaGate>
|
||||||
</div>}
|
</div>}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -19,10 +19,15 @@ const source = fs.readFileSync(path.join(__dirname, 'Docs.js'), 'utf8');
|
||||||
|
|
||||||
describe('DocPage embed gating (source contract)', () => {
|
describe('DocPage embed gating (source contract)', () => {
|
||||||
it('wraps the embedded viewer in a MediaGate', () => {
|
it('wraps the embedded viewer in a MediaGate', () => {
|
||||||
// The iframe must not be reachable without passing through the gate.
|
// The iframe must not be reachable without passing through the gate. The gate's only child is the
|
||||||
const embed = source.match(/<MediaGate[^>]*>\s*<iframe/);
|
// viewer frame, and the frame is just the iframe.
|
||||||
|
const embed = source.match(/<MediaGate[^>]*>\s*<DocViewerFrame/);
|
||||||
expect(embed).not.toBeNull();
|
expect(embed).not.toBeNull();
|
||||||
|
|
||||||
|
const frame = source.match(/function DocViewerFrame[\s\S]*?\n}\n/);
|
||||||
|
expect(frame).not.toBeNull();
|
||||||
|
expect(frame[0]).toMatch(/return <iframe/);
|
||||||
|
expect(source.match(/<iframe/g)).toHaveLength(1);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('gates on the live filter state, not on the theme name', () => {
|
it('gates on the live filter state, not on the theme name', () => {
|
||||||
|
|
|
||||||
|
|
@ -1,7 +1,7 @@
|
||||||
import React, {useState} from "react";
|
import React from "react";
|
||||||
import {PageContainer, useTitle} from "./Common";
|
import {PageContainer, useTitle} from "./Common";
|
||||||
import {Button, Header, IconButton, Modal, Panel, Table} from "./ui";
|
import {Button, Header, Panel, Table} from "./ui";
|
||||||
import QRCode from "react-qr-code";
|
import {QRCodeButton} from "./QRCode";
|
||||||
|
|
||||||
const bitcoinAddress = '1mi1ddLSd6LmkuwJd1ttZsKuED724vYjS';
|
const bitcoinAddress = '1mi1ddLSd6LmkuwJd1ttZsKuED724vYjS';
|
||||||
const bitcoinContent = `bitcoin:${bitcoinAddress}`;
|
const bitcoinContent = `bitcoin:${bitcoinAddress}`;
|
||||||
|
|
@ -13,27 +13,8 @@ const moneroAddress = '87jv2NpGb5sbUwk7zYYwEY5RAoh1jRfTo4d1BAewVdJJFKg2bDF2UXtLf
|
||||||
const moneroContent = `monero:${moneroAddress};`
|
const moneroContent = `monero:${moneroAddress};`
|
||||||
|
|
||||||
function CoinQRButton({qrCodeValue, header, buttonColor}) {
|
function CoinQRButton({qrCodeValue, header, buttonColor}) {
|
||||||
const [open, setOpen] = useState(false);
|
return <QRCodeButton value={qrCodeValue} label={`Show ${header} QR code`} header={header}
|
||||||
|
color={buttonColor}/>;
|
||||||
return <>
|
|
||||||
<IconButton icon='qrcode' label={`Show ${header} QR code`} color={buttonColor}
|
|
||||||
onClick={() => setOpen(true)}/>
|
|
||||||
<Modal size='small' closeIcon
|
|
||||||
open={open}
|
|
||||||
onClose={() => setOpen(false)}
|
|
||||||
onOpen={() => setOpen(true)}
|
|
||||||
>
|
|
||||||
<Modal.Header>{header}</Modal.Header>
|
|
||||||
<Modal.Content>
|
|
||||||
{/* `media`: the white field a scanner needs is filtered as a unit by night mode,
|
|
||||||
rather than sitting on screen as a lit panel. */}
|
|
||||||
<div className='media'
|
|
||||||
style={{backgroundColor: '#FFFFFF', display: 'inline-block', padding: '1em'}}>
|
|
||||||
<QRCode value={qrCodeValue} size={300}/>
|
|
||||||
</div>
|
|
||||||
</Modal.Content>
|
|
||||||
</Modal>
|
|
||||||
</>
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function CoinRow({header, qrCodeValue, address, buttonColor}) {
|
function CoinRow({header, qrCodeValue, address, buttonColor}) {
|
||||||
|
|
|
||||||
|
|
@ -127,6 +127,15 @@ describe('<ChannelDownloadForm/>', () => {
|
||||||
shouldBeInvalid('#url_input');
|
shouldBeInvalid('#url_input');
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('can be submitted with a frequency of Once', () => {
|
||||||
|
cy.get('#url_input').type('https://example.com/playlist').wait(500);
|
||||||
|
cy.get('#frequency_select').click();
|
||||||
|
cy.contains('[role="option"]:visible', 'Once').should('be.visible').click({force: true});
|
||||||
|
cy.get('#frequency_select').should('have.value', 'Once');
|
||||||
|
|
||||||
|
cy.get('#download_form_download_button').should('not.be.disabled');
|
||||||
|
});
|
||||||
|
|
||||||
it('can choose different options', () => {
|
it('can choose different options', () => {
|
||||||
/*
|
/*
|
||||||
* `#download_frequency_selector` and `.item` named the old dropdown and its menu rows.
|
* `#download_frequency_selector` and `.item` named the old dropdown and its menu rows.
|
||||||
|
|
|
||||||
|
|
@ -1,5 +1,5 @@
|
||||||
import React, {useState} from "react";
|
import React, {useState} from "react";
|
||||||
import {fetchVideoDownloadDefaults, getDownloaders, postDownload, putDownload} from "../api";
|
import {fetchVideoDownloadDefaults, getDownloaders, getTorrents, postDownload, putDownload, uploadTorrent} from "../api";
|
||||||
import {
|
import {
|
||||||
APIButton,
|
APIButton,
|
||||||
DirectorySearch,
|
DirectorySearch,
|
||||||
|
|
@ -13,8 +13,22 @@ import {
|
||||||
validURL,
|
validURL,
|
||||||
validURLs,
|
validURLs,
|
||||||
} from "./Common";
|
} from "./Common";
|
||||||
import {Button, Group, Header, Icon, Message, MultiSelect, NumberInput, Select, Stack, TextInput, Textarea} from "./ui";
|
import {
|
||||||
|
Button,
|
||||||
|
Group,
|
||||||
|
Header,
|
||||||
|
Icon,
|
||||||
|
Message,
|
||||||
|
MultiSelect,
|
||||||
|
NumberInput,
|
||||||
|
Select,
|
||||||
|
Stack,
|
||||||
|
TextInput,
|
||||||
|
Textarea,
|
||||||
|
toast,
|
||||||
|
} from "./ui";
|
||||||
import {Link} from "react-router";
|
import {Link} from "react-router";
|
||||||
|
import {VPN_SETTINGS_PATH, VpnStateUnknown} from "./admin/VpnSection";
|
||||||
import {TagsSelector} from "../Tags";
|
import {TagsSelector} from "../Tags";
|
||||||
import {
|
import {
|
||||||
commaSeparatedValidator,
|
commaSeparatedValidator,
|
||||||
|
|
@ -247,28 +261,38 @@ export function DownloadFrequencySelector({
|
||||||
}
|
}
|
||||||
|
|
||||||
export function DownloaderSelector({form, name = 'sub_downloader', path = 'sub_downloader'}) {
|
export function DownloaderSelector({form, name = 'sub_downloader', path = 'sub_downloader'}) {
|
||||||
const [downloaders, setDownloaders] = React.useState([]);
|
// null = pending, undefined = could not be fetched, a list = loaded. Until loaded, the select is
|
||||||
|
// disabled and says why, rather than sitting empty as though there were no downloaders.
|
||||||
|
const [downloaders, setDownloaders] = React.useState(null);
|
||||||
|
|
||||||
const fetchDownloaders = async () => {
|
const fetchDownloaders = async () => {
|
||||||
let {downloaders: downloaders_} = await getDownloaders();
|
const result = await getDownloaders();
|
||||||
downloaders_ = downloaders_.map((i) => {
|
if (!result || !Array.isArray(result.downloaders)) {
|
||||||
|
setDownloaders(undefined);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
setDownloaders(result.downloaders.map((i) => {
|
||||||
return {key: i.name, text: i.pretty_name || i.name, value: i.name}
|
return {key: i.name, text: i.pretty_name || i.name, value: i.name}
|
||||||
})
|
}));
|
||||||
setDownloaders(downloaders_);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
React.useEffect(() => {
|
React.useEffect(() => {
|
||||||
fetchDownloaders();
|
fetchDownloaders();
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
|
const placeholder = downloaders === null ? 'Loading downloaders…'
|
||||||
|
: downloaders === undefined ? 'Could not fetch downloaders'
|
||||||
|
: 'Select a downloader';
|
||||||
|
|
||||||
return <SelectField
|
return <SelectField
|
||||||
form={form}
|
form={form}
|
||||||
name={name}
|
name={name}
|
||||||
path={path}
|
path={path}
|
||||||
required
|
required
|
||||||
label='Downloader'
|
label='Downloader'
|
||||||
placeholder='Select a downloader'
|
placeholder={placeholder}
|
||||||
options={downloaders}
|
options={downloaders || []}
|
||||||
|
disabled={!Array.isArray(downloaders)}
|
||||||
/>
|
/>
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -1496,6 +1520,116 @@ export function FilesDownloadForm({
|
||||||
</form>
|
</form>
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// One magnet link or .torrent URL per line.
|
||||||
|
export const validTorrentUrls = (value) => {
|
||||||
|
const lines = (value || '').split(/\r?\n/).map(i => i.trim()).filter(Boolean);
|
||||||
|
return lines.length > 0 && lines.every(i => /^magnet:\?/i.test(i) || /^https?:\/\/\S+$/i.test(i));
|
||||||
|
};
|
||||||
|
|
||||||
|
// The URLs are optional (a .torrent file may be chosen instead); a stable function, as the form registers it.
|
||||||
|
const optionalTorrentUrls = (value) => !(value || '').trim() || validTorrentUrls(value);
|
||||||
|
|
||||||
|
function TorrentVpnStatus() {
|
||||||
|
const [status, setStatus] = React.useState(null);
|
||||||
|
const [failed, setFailed] = React.useState(false);
|
||||||
|
React.useEffect(() => {
|
||||||
|
let cancelled = false;
|
||||||
|
getTorrents()
|
||||||
|
.then(s => !cancelled && setStatus(s))
|
||||||
|
.catch(e => {
|
||||||
|
console.error('Failed to get torrents', e);
|
||||||
|
if (!cancelled) {
|
||||||
|
setFailed(true);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
return () => {
|
||||||
|
cancelled = true;
|
||||||
|
};
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
if (failed) {
|
||||||
|
return <VpnStateUnknown/>;
|
||||||
|
}
|
||||||
|
if (!status) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
const vpn = status.vpn || {};
|
||||||
|
if (vpn.state === 'connected') {
|
||||||
|
return <Message kind='success'>
|
||||||
|
VPN connected{vpn.public_ip ? <> · peers see <b>{vpn.public_ip}</b></> : null}
|
||||||
|
</Message>;
|
||||||
|
}
|
||||||
|
return <Message kind='warning' title='The VPN is not connected'>
|
||||||
|
Torrents only use the VPN. This torrent will start once the VPN connects.{' '}
|
||||||
|
<Link to={VPN_SETTINGS_PATH}>Set up the VPN</Link>
|
||||||
|
</Message>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function TorrentDownloadForm({download, onCancel, actions = DownloadFormButtons}) {
|
||||||
|
const [showMessage, setShowMessage] = React.useState(false);
|
||||||
|
const [file, setFile] = React.useState(null);
|
||||||
|
const fileInput = React.useRef(null);
|
||||||
|
|
||||||
|
const submitter = async (formData) => {
|
||||||
|
const urls = (formData.urls || '').split(/\r?\n/).map(i => i.trim()).filter(Boolean);
|
||||||
|
if (!file && !urls.length) {
|
||||||
|
throw new Error('Enter a magnet link or .torrent URL, or choose a .torrent file');
|
||||||
|
}
|
||||||
|
if (file) {
|
||||||
|
try {
|
||||||
|
await uploadTorrent(file, formData.destination);
|
||||||
|
} catch (e) {
|
||||||
|
// The Download button only changes its icon; say why (postDownload toasts its own failures).
|
||||||
|
toast({type: 'error', title: 'Could not add the .torrent file', description: e.message, time: 6000});
|
||||||
|
throw e;
|
||||||
|
}
|
||||||
|
setFile(null);
|
||||||
|
}
|
||||||
|
if (urls.length) {
|
||||||
|
await postDownload({downloader: Downloaders.Torrent, destination: formData.destination, urls});
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const emptyFormData = {destination: null, urls: ''};
|
||||||
|
|
||||||
|
const form = useForm({
|
||||||
|
submitter,
|
||||||
|
defaultFormData: mergeDeep(emptyFormData, download),
|
||||||
|
emptyFormData,
|
||||||
|
clearPathsOnSuccess: URL_PATHS,
|
||||||
|
onSuccess: async () => setShowMessage(true),
|
||||||
|
});
|
||||||
|
|
||||||
|
return <form onSubmit={(e) => e.preventDefault()}>
|
||||||
|
<Header as='h3' icon='share'>Torrent</Header>
|
||||||
|
<p>Download (and share) torrents of open data. Torrents only use the VPN, so peers never see this WROLPi's own
|
||||||
|
address. Saved in the "torrents" directory unless you choose another.</p>
|
||||||
|
|
||||||
|
<Stack gap='md'>
|
||||||
|
<TorrentVpnStatus/>
|
||||||
|
{/* Optional: a .torrent file may be chosen instead (or as well). */}
|
||||||
|
<UrlsField form={form} label='Magnet links or .torrent URLs' placeholder='magnet:?xt=urn:btih:...'
|
||||||
|
valid={optionalTorrentUrls}/>
|
||||||
|
<div>
|
||||||
|
<input ref={fileInput} type='file' accept='.torrent,application/x-bittorrent'
|
||||||
|
style={{display: 'none'}} data-testid='torrent-file'
|
||||||
|
onChange={e => setFile((e.target.files && e.target.files[0]) || null)}/>
|
||||||
|
<Group gap='sm'>
|
||||||
|
<Button type='button' role='cancel' icon='file' disabled={form.disabled}
|
||||||
|
onClick={() => fileInput.current && fileInput.current.click()}>
|
||||||
|
{file ? 'Choose another .torrent file' : 'Or choose a .torrent file'}
|
||||||
|
</Button>
|
||||||
|
{file && <span>{file.name}</span>}
|
||||||
|
</Group>
|
||||||
|
</div>
|
||||||
|
<DestinationForm form={form}/>
|
||||||
|
{showMessage && <SuccessfulDownloadSubmitMessage/>}
|
||||||
|
{/* Download waits for something to download: a URL or a chosen file. */}
|
||||||
|
{actions({onCancel, form: {...form, ready: form.ready && (!!file || !!(form.formData.urls || '').trim())}})}
|
||||||
|
</Stack>
|
||||||
|
</form>
|
||||||
|
}
|
||||||
|
|
||||||
const suffixValidator = (value) => {
|
const suffixValidator = (value) => {
|
||||||
const error = commaSeparatedValidator(value);
|
const error = commaSeparatedValidator(value);
|
||||||
if (error) {
|
if (error) {
|
||||||
|
|
@ -1649,11 +1783,12 @@ function UrlField({form, required = true, name = 'url', path = 'url', disabled =
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Multiline URLs field: one URL per line. */
|
/** Multiline URLs field: one URL per line. */
|
||||||
function UrlsField({name = 'urls', required, form}) {
|
function UrlsField({name = 'urls', required, form, label = 'URLs', placeholder = 'Enter one URL per line',
|
||||||
|
valid = validURLs}) {
|
||||||
required = required !== undefined;
|
required = required !== undefined;
|
||||||
|
|
||||||
const validator = (value) => {
|
const validator = (value) => {
|
||||||
if (!validURLs(value)) {
|
if (!valid(value)) {
|
||||||
return 'Invalid URLs';
|
return 'Invalid URLs';
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
@ -1677,10 +1812,10 @@ function UrlsField({name = 'urls', required, form}) {
|
||||||
};
|
};
|
||||||
|
|
||||||
return <div>
|
return <div>
|
||||||
<FieldLabel htmlFor='urls_textarea' label='URLs' required={required}/>
|
<FieldLabel htmlFor='urls_textarea' label={label} required={required}/>
|
||||||
<Textarea
|
<Textarea
|
||||||
id='urls_textarea'
|
id='urls_textarea'
|
||||||
placeholder='Enter one URL per line'
|
placeholder={placeholder}
|
||||||
name='urls'
|
name='urls'
|
||||||
minRows={4}
|
minRows={4}
|
||||||
autosize
|
autosize
|
||||||
|
|
@ -1714,6 +1849,7 @@ export function DownloadMenu({onOpen, disabled, initialDownloader, initialUrls})
|
||||||
<Button color='blue' disabled={disabled} onClick={() => localOnOpen('video_channel')}>Channel/Playlist</Button>
|
<Button color='blue' disabled={disabled} onClick={() => localOnOpen('video_channel')}>Channel/Playlist</Button>
|
||||||
<Button disabled={disabled} onClick={() => localOnOpen('rss')}>RSS Feed</Button>
|
<Button disabled={disabled} onClick={() => localOnOpen('rss')}>RSS Feed</Button>
|
||||||
<Button color='grey' disabled={disabled} onClick={() => localOnOpen('file')}>Files</Button>
|
<Button color='grey' disabled={disabled} onClick={() => localOnOpen('file')}>Files</Button>
|
||||||
|
<Button color='grey' disabled={disabled} onClick={() => localOnOpen('torrent')}>Torrent</Button>
|
||||||
<Button role='danger' disabled={disabled} onClick={() => localOnOpen('scrape')}>Scrape</Button>
|
<Button role='danger' disabled={disabled} onClick={() => localOnOpen('scrape')}>Scrape</Button>
|
||||||
</Stack>);
|
</Stack>);
|
||||||
|
|
||||||
|
|
@ -1736,6 +1872,7 @@ export function DownloadMenu({onOpen, disabled, initialDownloader, initialUrls})
|
||||||
video_channel: <ChannelDownloadForm onCancel={clearSelected} download={seed}/>,
|
video_channel: <ChannelDownloadForm onCancel={clearSelected} download={seed}/>,
|
||||||
rss: <RSSDownloadForm onCancel={clearSelected} download={seed}/>,
|
rss: <RSSDownloadForm onCancel={clearSelected} download={seed}/>,
|
||||||
file: <FilesDownloadForm onCancel={clearSelected} download={seed}/>,
|
file: <FilesDownloadForm onCancel={clearSelected} download={seed}/>,
|
||||||
|
torrent: <TorrentDownloadForm onCancel={clearSelected} download={seed}/>,
|
||||||
scrape: <ScrapeFilesDownloadForm onCancel={clearSelected} download={seed}/>
|
scrape: <ScrapeFilesDownloadForm onCancel={clearSelected} download={seed}/>
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -1,8 +1,9 @@
|
||||||
import React from 'react';
|
import React from 'react';
|
||||||
import {render, screen, waitFor} from '@testing-library/react';
|
import {render, screen, waitFor} from '@testing-library/react';
|
||||||
import userEvent from '@testing-library/user-event';
|
import userEvent from '@testing-library/user-event';
|
||||||
import {DestinationForm} from './Download';
|
import {DepthInputForm, DestinationForm} from './Download';
|
||||||
import {createTestForm} from '../test-utils';
|
import {useForm} from '../hooks/useForm';
|
||||||
|
import {createTestForm, renderWithProviders} from '../test-utils';
|
||||||
|
|
||||||
// Mock DirectorySearch component - simplified to avoid useState/useEffect warnings
|
// Mock DirectorySearch component - simplified to avoid useState/useEffect warnings
|
||||||
jest.mock('./Common', () => {
|
jest.mock('./Common', () => {
|
||||||
|
|
@ -251,3 +252,26 @@ describe('DestinationForm', () => {
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
describe('NumberField', () => {
|
||||||
|
// Renders a NumberField against a real useForm: the Mantine NumberInput passes a value (not an
|
||||||
|
// event) to onChange, which used to reach `e.preventDefault()` and throw while typing.
|
||||||
|
function DepthHarness({onData}) {
|
||||||
|
const form = useForm({defaultFormData: {settings: {depth: ''}}, submitter: jest.fn()});
|
||||||
|
onData(form.formData);
|
||||||
|
return <DepthInputForm form={form}/>;
|
||||||
|
}
|
||||||
|
|
||||||
|
it('typing into a NumberField updates the form without throwing', async () => {
|
||||||
|
let latest = null;
|
||||||
|
renderWithProviders(<DepthHarness onData={(d) => latest = d}/>);
|
||||||
|
|
||||||
|
const input = screen.getByRole('textbox', {name: /Depth/});
|
||||||
|
await userEvent.type(input, '3');
|
||||||
|
|
||||||
|
await waitFor(() => {
|
||||||
|
expect(latest.settings.depth).toBe(3);
|
||||||
|
});
|
||||||
|
expect(input).toHaveValue('3');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
|
||||||
43
app/src/components/DownloaderSelector.test.js
Normal file
43
app/src/components/DownloaderSelector.test.js
Normal file
|
|
@ -0,0 +1,43 @@
|
||||||
|
import React from 'react';
|
||||||
|
import {act, render, screen} from '../test-utils';
|
||||||
|
import {createTestForm} from '../test-utils';
|
||||||
|
import {DownloaderSelector} from './Download';
|
||||||
|
import {getDownloaders} from '../api';
|
||||||
|
|
||||||
|
// The RSS form's Downloader select is filled from the API. Until the list arrives, or if it could
|
||||||
|
// not be fetched, the select must say so rather than sit empty as though there were no downloaders.
|
||||||
|
|
||||||
|
jest.mock('../api', () => ({
|
||||||
|
...jest.requireActual('../api'),
|
||||||
|
getDownloaders: jest.fn(),
|
||||||
|
}));
|
||||||
|
|
||||||
|
const makeForm = () => createTestForm({}, {
|
||||||
|
overrides: {getSelectionProps: () => [{value: null, onChange: jest.fn(), disabled: false, error: null}]},
|
||||||
|
});
|
||||||
|
|
||||||
|
beforeEach(() => getDownloaders.mockReset());
|
||||||
|
|
||||||
|
test('pending: the select says it is loading and is disabled', () => {
|
||||||
|
getDownloaders.mockReturnValue(new Promise(() => {
|
||||||
|
}));
|
||||||
|
render(<DownloaderSelector form={makeForm()}/>);
|
||||||
|
const input = screen.getByPlaceholderText('Loading downloaders…');
|
||||||
|
expect(input).toBeDisabled();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('failed: the select says the downloaders could not be fetched', async () => {
|
||||||
|
getDownloaders.mockResolvedValue(undefined);
|
||||||
|
render(<DownloaderSelector form={makeForm()}/>);
|
||||||
|
await act(async () => {
|
||||||
|
});
|
||||||
|
expect(screen.getByPlaceholderText('Could not fetch downloaders')).toBeDisabled();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('loaded: the select offers the downloaders', async () => {
|
||||||
|
getDownloaders.mockResolvedValue({downloaders: [{name: 'video', pretty_name: 'Videos'}]});
|
||||||
|
render(<DownloaderSelector form={makeForm()}/>);
|
||||||
|
await act(async () => {
|
||||||
|
});
|
||||||
|
expect(screen.getByPlaceholderText('Select a downloader')).toBeEnabled();
|
||||||
|
});
|
||||||
1096
app/src/components/FalloutPanel.js
Normal file
1096
app/src/components/FalloutPanel.js
Normal file
File diff suppressed because it is too large
Load diff
746
app/src/components/FalloutPanel.test.js
Normal file
746
app/src/components/FalloutPanel.test.js
Normal file
|
|
@ -0,0 +1,746 @@
|
||||||
|
import {WEAPON_CHOICES} from './FalloutPanel';
|
||||||
|
import {serveFallout} from '../map-shared/fallout/work.js';
|
||||||
|
import {loadTerrainGrid} from './falloutTerrain';
|
||||||
|
|
||||||
|
// No terrain files under Jest, until a test gives a grid.
|
||||||
|
jest.mock('./falloutTerrain', () => ({loadTerrainGrid: jest.fn(async () => null)}));
|
||||||
|
// No forecast (unless a test gives one), past days or fetches under Jest.
|
||||||
|
let mockLatestWinds = null;
|
||||||
|
let mockWeather = {enabled: true, download: {status: 'complete'}, targets: 1, spacing: 1, points: 160, seconds: 61,
|
||||||
|
field: null};
|
||||||
|
const mockWeatherSet = [];
|
||||||
|
jest.mock('../api', () => ({
|
||||||
|
getFalloutClimatology: async () => null,
|
||||||
|
getFalloutClimatologyMonth: async () => null,
|
||||||
|
getWeather: async () => mockWeather,
|
||||||
|
setWeatherSubscription: (enabled) => {
|
||||||
|
mockWeatherSet.push(enabled);
|
||||||
|
return Promise.resolve({...mockWeather, enabled});
|
||||||
|
},
|
||||||
|
downloadWeatherNow: async () => mockWeather,
|
||||||
|
getLatestFalloutWinds: async () => mockLatestWinds,
|
||||||
|
}));
|
||||||
|
|
||||||
|
// Fallout workers serving their tasks (as fallout.worker.js does) here, as a browser's would on
|
||||||
|
// another thread: messages arrive later, copied. `made` are those made since it was emptied.
|
||||||
|
const made = [];
|
||||||
|
const copy = (v) => {
|
||||||
|
if (v instanceof ArrayBuffer) return v.slice(0);
|
||||||
|
if (ArrayBuffer.isView(v)) return v.slice();
|
||||||
|
if (Array.isArray(v)) return v.map(copy);
|
||||||
|
if (v && typeof v === 'object') return Object.fromEntries(Object.entries(v).map(([k, x]) => [k, copy(x)]));
|
||||||
|
return v;
|
||||||
|
};
|
||||||
|
function worker({fail = false} = {}) {
|
||||||
|
const scope = {postMessage: (data) => setTimeout(() => !w.terminated && w.onmessage?.({data}), 0)};
|
||||||
|
serveFallout(scope);
|
||||||
|
const w = {
|
||||||
|
terminated: false, onmessage: null, onerror: null, given: [], kind: null,
|
||||||
|
postMessage(data) {
|
||||||
|
if (data.type === 'start') {
|
||||||
|
w.kind = data.kind;
|
||||||
|
w.start = data;
|
||||||
|
}
|
||||||
|
if (data.type === 'task') w.given.push(data.k);
|
||||||
|
const copied = copy(data);
|
||||||
|
setTimeout(() => {
|
||||||
|
if (w.terminated) return;
|
||||||
|
if (fail && data.type === 'task') w.onerror?.({message: 'No such script'});
|
||||||
|
else scope.onmessage({data: copied});
|
||||||
|
}, 0);
|
||||||
|
},
|
||||||
|
terminate() {
|
||||||
|
w.terminated = true;
|
||||||
|
},
|
||||||
|
};
|
||||||
|
made.push(w);
|
||||||
|
return w;
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('the fallout panel\'s weapons', () => {
|
||||||
|
test('are grouped by country, then a yield of one\'s own', () => {
|
||||||
|
const groups = WEAPON_CHOICES.map((g) => g.group);
|
||||||
|
expect(groups[0]).toBe('United States');
|
||||||
|
expect(groups).toContain('Russia');
|
||||||
|
expect(groups).toContain('Improvised nuclear device');
|
||||||
|
expect(groups[groups.length - 1]).toBe('Other');
|
||||||
|
expect(WEAPON_CHOICES[groups.length - 1].items.map((i) => i.value)).toEqual(['custom']);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('each read differently, by name and yield', () => {
|
||||||
|
const labels = WEAPON_CHOICES.flatMap((g) => g.items.map((i) => i.label));
|
||||||
|
expect(new Set(labels).size).toBe(labels.length);
|
||||||
|
expect(labels).toContain('B61-12 bomb, 0.3 kt, half fission');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('say their yield', () => {
|
||||||
|
const w88 = WEAPON_CHOICES[0].items.find((i) => i.value === 'w88');
|
||||||
|
expect(w88.label).toBe('W88 (Trident II D5), 455 kt, half fission');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('the fallout panel\'s winds', () => {
|
||||||
|
const {windProfile, hourLabel} = require('./FalloutPanel');
|
||||||
|
|
||||||
|
test('fall back to one wind at every height until there is a forecast', () => {
|
||||||
|
const profile = windProfile({direction: 270, speed: 10});
|
||||||
|
expect(profile).toHaveLength(1);
|
||||||
|
expect(profile[0][1]).toBeGreaterThan(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('mark the hour nearest now', () => {
|
||||||
|
expect(hourLabel('2026-11-22T00:00Z', true)).toMatch(/\(now\)$/);
|
||||||
|
expect(hourLabel('2026-11-22T00:00Z', false)).not.toMatch(/now/);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('the fallout of several bursts', () => {
|
||||||
|
const {simulateBursts} = require('./FalloutPanel');
|
||||||
|
const {prepareField} = require('../map-shared/fallout/winds.js');
|
||||||
|
const winds = {profile: [[0, 10, 0]]};
|
||||||
|
const bursts = [
|
||||||
|
{lat: 40, lon: -105, yieldKt: 10, fissionFraction: 0.5},
|
||||||
|
{lat: 40.5, lon: -104, yieldKt: 100, fissionFraction: 0.5},
|
||||||
|
];
|
||||||
|
|
||||||
|
// A forecast over 39-42 N, 106-103 W, every degree, whose wind turns from the west to the
|
||||||
|
// south-west over the hours, on ground rising to the east.
|
||||||
|
const HOURS = ['2026-11-22T00:00Z', '2026-11-22T01:00Z', '2026-11-22T02:00Z'];
|
||||||
|
function forecast() {
|
||||||
|
const points = [];
|
||||||
|
for (const lat of [39, 40, 41, 42]) for (const lon of [-106, -105, -104, -103]) points.push({lat, lon, elevation: 1500 + (lon + 106) * 100});
|
||||||
|
return {
|
||||||
|
source: 'Open-Meteo', fetched_at: '2026-11-22T00:30:00+00:00', spacing: 1, points, hours: HOURS,
|
||||||
|
winds: points.map(() => HOURS.map((_, h) => [[10, 12, 270 - 20 * h], [20000, 30, 260 - 20 * h]])),
|
||||||
|
rain: points.map(() => HOURS.map(() => 0)),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
const fieldWinds = () => ({prepared: prepareField(forecast()), startMs: Date.parse(HOURS[0])});
|
||||||
|
|
||||||
|
test('carries each burst by the winds where it is, from the ground there', async () => {
|
||||||
|
const ran = await simulateBursts(bursts, {winds: fieldWinds(), useTerrain: false});
|
||||||
|
expect(ran.grid.values.some((v) => v > 0)).toBe(true);
|
||||||
|
// Not as one wind would carry them.
|
||||||
|
const one = await simulateBursts(bursts, {winds, useTerrain: false});
|
||||||
|
expect(ran.grid.values.length === one.grid.values.length
|
||||||
|
&& ran.grid.values.every((v, i) => v === one.grid.values[i])).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('is drawn on one grid around the first burst', async () => {
|
||||||
|
const one = await simulateBursts(bursts.slice(0, 1), {winds, useTerrain: false});
|
||||||
|
const both = await simulateBursts(bursts, {winds, useTerrain: false});
|
||||||
|
expect(both.origin).toBe(bursts[0]);
|
||||||
|
const sum = (g) => g.values.reduce((a, v) => a + v, 0) * g.cell ** 2;
|
||||||
|
expect(sum(both.grid)).toBeGreaterThan(sum(one.grid) * 5);
|
||||||
|
expect(both.terrainStatus).toMatch(/terrain is off/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('stops when it is no longer wanted', async () => {
|
||||||
|
expect(await simulateBursts(bursts, {winds, useTerrain: false, cancelled: () => true})).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
const MANY = Array.from({length: 7}, (_, i) => ({lat: 40 + 0.2 * i, lon: -105 + 0.3 * i, yieldKt: 5 * (i + 1), fissionFraction: 0.5}));
|
||||||
|
// Whether two results have the same grid (said quickly: Jest's diff of such arrays takes minutes).
|
||||||
|
const same = (a, b) => a.grid.cell === b.grid.cell && a.grid.values.length === b.grid.values.length
|
||||||
|
&& a.grid.values.every((v, i) => v === b.grid.values[i]);
|
||||||
|
|
||||||
|
test('spreads the bursts over workers, as the page calculates them', async () => {
|
||||||
|
for (const w of [winds, fieldWinds()]) {
|
||||||
|
made.length = 0;
|
||||||
|
const here = await simulateBursts(MANY, {winds: w, useTerrain: false});
|
||||||
|
const heard = [];
|
||||||
|
const spread = await simulateBursts(MANY, {winds: w, useTerrain: false, workers: 3, makeWorker: () => worker(),
|
||||||
|
onProgress: (done, total) => heard.push([done, total])});
|
||||||
|
// The bursts by three workers, then the grid's parts by three more.
|
||||||
|
const burstWorkers = made.filter((x) => x.kind === 'bursts');
|
||||||
|
const gridWorkers = made.filter((x) => x.kind === 'grid');
|
||||||
|
expect(burstWorkers).toHaveLength(3);
|
||||||
|
expect(gridWorkers).toHaveLength(3);
|
||||||
|
expect(burstWorkers.flatMap((x) => x.given).sort()).toEqual([0, 1, 2, 3, 4, 5, 6]);
|
||||||
|
expect(gridWorkers.flatMap((x) => x.given).length).toBeGreaterThan(3);
|
||||||
|
expect(made.every((x) => x.given.length > 0 && x.terminated)).toBe(true);
|
||||||
|
expect(heard[heard.length - 1]).toEqual([7, 7]);
|
||||||
|
expect(same(spread, here)).toBe(true);
|
||||||
|
expect(JSON.stringify(spread.spots) === JSON.stringify(here.spots)).toBe(true);
|
||||||
|
// Given the forecast's arrays, not the forecast as fetched.
|
||||||
|
if (w.prepared) {
|
||||||
|
const {prepared} = burstWorkers[0].start;
|
||||||
|
expect(prepared.u).toBeInstanceOf(Float32Array);
|
||||||
|
expect(prepared.field.winds).toBeUndefined();
|
||||||
|
expect(prepared.field.points).toHaveLength(16);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test('shows its progress every so often, and when all is done', () => {
|
||||||
|
const {everySoOften} = require('./FalloutPanel');
|
||||||
|
jest.useFakeTimers();
|
||||||
|
try {
|
||||||
|
const heard = [];
|
||||||
|
const report = everySoOften((done, total) => heard.push(done));
|
||||||
|
for (let done = 1; done <= 10; done++) {
|
||||||
|
report(done, 10);
|
||||||
|
jest.advanceTimersByTime(30);
|
||||||
|
}
|
||||||
|
// The first, one in every four after it (30 ms apart), and the last.
|
||||||
|
expect(heard).toEqual([1, 5, 9, 10]);
|
||||||
|
} finally {
|
||||||
|
jest.useRealTimers();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test('gives its workers the terrain, when it is read', async () => {
|
||||||
|
// Ground rising to the north-east of the bursts.
|
||||||
|
const nx = 81, ny = 81, step = 0.05;
|
||||||
|
const grid = {west: -107, south: 38, step, nx, ny, values: new Float32Array(nx * ny)};
|
||||||
|
for (let j = 0; j < ny; j++) for (let i = 0; i < nx; i++) grid.values[j * nx + i] = 1500 + 40 * (i + j);
|
||||||
|
loadTerrainGrid.mockImplementation(async () => ({grid, zoom: 9, coverage: 1}));
|
||||||
|
try {
|
||||||
|
const flat = await simulateBursts(MANY, {winds: fieldWinds(), useTerrain: false});
|
||||||
|
const here = await simulateBursts(MANY, {winds: fieldWinds(), useTerrain: true});
|
||||||
|
made.length = 0;
|
||||||
|
const heard = [];
|
||||||
|
const spread = await simulateBursts(MANY, {winds: fieldWinds(), useTerrain: true, workers: 2,
|
||||||
|
makeWorker: () => worker(), onProgress: (done, total) => heard.push([done, total])});
|
||||||
|
expect(here.terrainStatus).toMatch(/Follows the terrain/);
|
||||||
|
expect(same(here, flat)).toBe(false);
|
||||||
|
expect(same(spread, here)).toBe(true);
|
||||||
|
// A pass on flat ground, then another over the terrain, each by its own workers.
|
||||||
|
expect(made.map((x) => x.kind)).toEqual(['bursts', 'bursts', 'grid', 'grid', 'bursts', 'bursts', 'grid', 'grid']);
|
||||||
|
expect(heard[heard.length - 1]).toEqual([14, 14]);
|
||||||
|
} finally {
|
||||||
|
loadTerrainGrid.mockImplementation(async () => null);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test('stops its workers at once when cancelled', async () => {
|
||||||
|
made.length = 0;
|
||||||
|
const controller = new AbortController();
|
||||||
|
const running = simulateBursts(MANY, {winds, useTerrain: false, workers: 3, makeWorker: () => worker(),
|
||||||
|
signal: controller.signal});
|
||||||
|
controller.abort();
|
||||||
|
expect(await running).toBeNull();
|
||||||
|
expect(made).toHaveLength(3);
|
||||||
|
expect(made.every((x) => x.terminated)).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('calculates on the page when its workers fail, or there are none', async () => {
|
||||||
|
made.length = 0;
|
||||||
|
const error = jest.spyOn(console, 'error').mockImplementation(() => null);
|
||||||
|
const here = await simulateBursts(MANY, {winds, useTerrain: false});
|
||||||
|
const ran = await simulateBursts(MANY, {winds, useTerrain: false, workers: 2, makeWorker: () => worker({fail: true})});
|
||||||
|
expect(error).toHaveBeenCalled();
|
||||||
|
error.mockRestore();
|
||||||
|
expect(made.every((x) => x.terminated)).toBe(true);
|
||||||
|
expect(same(ran, here)).toBe(true);
|
||||||
|
const none = await simulateBursts(MANY, {winds, useTerrain: false, workers: 2, makeWorker: () => null});
|
||||||
|
expect(same(none, here)).toBe(true);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('the fallout image', () => {
|
||||||
|
const {imageRows} = require('./FalloutPanel');
|
||||||
|
|
||||||
|
test('takes each row from the grid row at its own latitude', () => {
|
||||||
|
// A grid from 20 to 80 degrees north, around 40: a tenth of a degree a row.
|
||||||
|
const grid = {y0: -20 * 111320, cell: 11132, ny: 600, nx: 1};
|
||||||
|
const rows = imageRows(grid, 40, 600);
|
||||||
|
// The top row is the grid's northernmost, the bottom its southernmost.
|
||||||
|
expect(rows[0]).toBe(599);
|
||||||
|
expect(rows[599]).toBe(0);
|
||||||
|
// Halfway down the image, in Web Mercator, is well north of halfway in latitude (50 degrees).
|
||||||
|
expect(rows[300]).toBeGreaterThan(330);
|
||||||
|
for (let r = 1; r < 600; r++) expect(rows[r]).toBeLessThanOrEqual(rows[r - 1]);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('is the plain grid over a small area', () => {
|
||||||
|
const grid = {y0: -5000, cell: 100, ny: 100, nx: 1};
|
||||||
|
const rows = imageRows(grid, 40, 100);
|
||||||
|
expect(rows[0]).toBe(99);
|
||||||
|
expect(Math.abs(rows[50] - 49)).toBeLessThanOrEqual(1);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('the fallout timeline', () => {
|
||||||
|
const {screen, fireEvent} = require('@testing-library/react');
|
||||||
|
const {renderWithProviders} = require('../test-utils');
|
||||||
|
const {Timeline, HOURS, afterLabel, weakerThanH1} = require('./FalloutPanel');
|
||||||
|
|
||||||
|
test('runs from the first hour to two weeks, in longer steps as it goes', () => {
|
||||||
|
expect(HOURS[0]).toBe(1);
|
||||||
|
expect(HOURS[HOURS.length - 1]).toBe(336);
|
||||||
|
for (let k = 1; k < HOURS.length; k++) expect(HOURS[k]).toBeGreaterThan(HOURS[k - 1]);
|
||||||
|
expect(HOURS.map(afterLabel)).toEqual(['1 hour', '2 hours', '3 hours', '6 hours', '12 hours', '1 day',
|
||||||
|
'2 days', '3 days', '5 days', '1 week', '2 weeks']);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('says how much the fallout has weakened since H+1', () => {
|
||||||
|
// t^-1.2: about 10 times weaker for every 7 times longer.
|
||||||
|
expect(weakerThanH1(7)).toBe('10');
|
||||||
|
expect(weakerThanH1(3)).toBe('3.7');
|
||||||
|
expect(weakerThanH1(48)).toBe('100');
|
||||||
|
expect(weakerThanH1(336)).toBe('1,100');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('says what it shows, and moves and plays the hours', () => {
|
||||||
|
const onAfter = jest.fn(), onPlaying = jest.fn();
|
||||||
|
const {unmount} = renderWithProviders(<Timeline after={1} onAfter={onAfter} playing={false}
|
||||||
|
onPlaying={onPlaying} startMs={null}/>);
|
||||||
|
expect(screen.getByText(/^H\+1: the fallout landed by then\.$/)).toBeTruthy();
|
||||||
|
// Each step of the slider is one of the hours.
|
||||||
|
fireEvent.change(screen.getByLabelText('Time after the bursts'), {target: {value: String(HOURS.indexOf(48))}});
|
||||||
|
expect(onAfter).toHaveBeenCalledWith(48);
|
||||||
|
fireEvent.click(screen.getByLabelText('Play'));
|
||||||
|
expect(onPlaying).toHaveBeenCalledWith(true);
|
||||||
|
|
||||||
|
unmount();
|
||||||
|
renderWithProviders(<Timeline after={6} onAfter={onAfter} playing={true} onPlaying={onPlaying}
|
||||||
|
startMs={Date.parse('2026-11-22T00:00Z')}/>);
|
||||||
|
expect(screen.getByText(/^H\+6, .*: the fallout landed by then, about 8\.6 times weaker than at H\+1\.$/)).toBeTruthy();
|
||||||
|
expect(screen.getByLabelText('Time after the bursts').getAttribute('aria-valuetext')).toBe('6 hours');
|
||||||
|
fireEvent.click(screen.getByLabelText('Pause'));
|
||||||
|
expect(onPlaying).toHaveBeenLastCalledWith(false);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('the total dose view', () => {
|
||||||
|
const {TOTAL_BANDS, DOSE_BANDS, legendHeading, legendText} = require('./FalloutPanel');
|
||||||
|
|
||||||
|
test('has its own bands, each saying what it does to a person', () => {
|
||||||
|
expect(TOTAL_BANDS.map((b) => b.rate)).toEqual([1000, 450, 100, 25, 5]);
|
||||||
|
for (const b of TOTAL_BANDS) expect(b.meaning.length).toBeGreaterThan(5);
|
||||||
|
// The same colors, highest first.
|
||||||
|
expect(TOTAL_BANDS.map((b) => b.color)).toEqual(DOSE_BANDS.map((b) => b.color));
|
||||||
|
});
|
||||||
|
|
||||||
|
test('says what is shown, by the hour', () => {
|
||||||
|
expect(legendHeading('total', 6)).toBe('Total dose outdoors in the first two weeks');
|
||||||
|
expect(legendHeading('rate', 1)).toBe('Dose rate 1 hour after the bursts');
|
||||||
|
expect(legendHeading('rate', 120)).toBe('Dose rate 5 days after the bursts');
|
||||||
|
expect(legendText('total')).toMatch(/outdoors the whole time/);
|
||||||
|
expect(legendText('rate')).toMatch(/landed by then/);
|
||||||
|
expect(legendText('rate')).toMatch(/weakens/);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('the forecast\'s warning', () => {
|
||||||
|
const {forecastShortText} = require('./FalloutPanel');
|
||||||
|
const hourMs = Math.floor(Date.now() / 3600000) * 3600000;
|
||||||
|
const of = (from, count) => ({hours: Array.from({length: count}, (_, h) => new Date(hourMs + (from + h) * 3600000).toISOString())});
|
||||||
|
|
||||||
|
test('says when it is out of date, or ends before the fallout is down, and else nothing', () => {
|
||||||
|
expect(forecastShortText(null, 0)).toBeNull();
|
||||||
|
expect(forecastShortText(of(-30, 10), 9)).toMatch(/out of date.*last hour's winds are held for the whole simulation/);
|
||||||
|
expect(forecastShortText(of(-1, 30), 1)).toMatch(/ends at .*, before all the fallout is down/);
|
||||||
|
expect(forecastShortText(of(-1, 96), 1)).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('says the last hour is held only from when it is, for the hour chosen', () => {
|
||||||
|
// Out of date, but its first hour still has 48 hours of winds after it: none is held.
|
||||||
|
const old = of(-200, 96);
|
||||||
|
expect(forecastShortText(old, 0)).toMatch(/out of date/);
|
||||||
|
expect(forecastShortText(old, 0)).not.toMatch(/held/);
|
||||||
|
expect(forecastShortText(old, 60)).toMatch(/held from then on/);
|
||||||
|
expect(forecastShortText(old, 60)).not.toMatch(/whole simulation/);
|
||||||
|
expect(forecastShortText(old, 95)).toMatch(/held for the whole simulation/);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('the targets simulated', () => {
|
||||||
|
const {withSavedTargets, targetsUnsaved, withWeapon} = require('./FalloutPanel');
|
||||||
|
const saved = [{id: 1, label: 'A', lat: 1, lon: 1, kind: 'target', weapon: 'yars'},
|
||||||
|
{id: 2, label: 'B', lat: 2, lon: 2, kind: 'target', weapon: 'custom', yield_kt: 20, fission_fraction: 1}];
|
||||||
|
const tried = {key: 'new-1', label: 'C', lat: 3, lon: 3, weapon: 'w88'};
|
||||||
|
|
||||||
|
test('are the saved ones once loaded, then those tried out', () => {
|
||||||
|
const loaded = withSavedTargets(saved, [tried]);
|
||||||
|
expect(loaded.map((t) => t.key)).toEqual(['saved-1', 'saved-2', 'new-1']);
|
||||||
|
// Loading again keeps the tried ones once, and the saved ones as saved.
|
||||||
|
expect(withSavedTargets(saved, loaded).map((t) => t.key)).toEqual(['saved-1', 'saved-2', 'new-1']);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('are unsaved when they differ from the saved ones', () => {
|
||||||
|
expect(targetsUnsaved([], saved, false)).toBe(false);
|
||||||
|
expect(targetsUnsaved([tried], saved, false)).toBe(true);
|
||||||
|
const loaded = withSavedTargets(saved, []);
|
||||||
|
expect(targetsUnsaved(loaded, saved, true)).toBe(false);
|
||||||
|
expect(targetsUnsaved(loaded.slice(1), saved, true)).toBe(true);
|
||||||
|
expect(targetsUnsaved([withWeapon(loaded[0], {weapon: 'w88'}), loaded[1]], saved, true)).toBe(true);
|
||||||
|
expect(targetsUnsaved([...loaded, tried], saved, true)).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('take a new weapon in place of the old', () => {
|
||||||
|
expect(withWeapon(saved[1], {weapon: 'w88', fission_fraction: 0.5})).toEqual(
|
||||||
|
{id: 2, label: 'B', lat: 2, lon: 2, kind: 'target', weapon: 'w88', fission_fraction: 0.5});
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('the fallout panel\'s steps', () => {
|
||||||
|
const {screen, fireEvent, waitFor, act, cleanup} = require('@testing-library/react');
|
||||||
|
const {renderWithProviders} = require('../test-utils');
|
||||||
|
const FalloutPanel = require('./FalloutPanel').default;
|
||||||
|
|
||||||
|
// A map which keeps the one image source and layer the panel draws.
|
||||||
|
function fakeMap() {
|
||||||
|
const map = {
|
||||||
|
source: null, layer: false, added: 0,
|
||||||
|
getSource: () => map.source,
|
||||||
|
addSource: (id, s) => {
|
||||||
|
map.added++;
|
||||||
|
map.source = {...s, updateImage: (i) => Object.assign(map.source, i)};
|
||||||
|
},
|
||||||
|
addLayer: () => {
|
||||||
|
map.layer = true;
|
||||||
|
},
|
||||||
|
getLayer: () => map.layer,
|
||||||
|
removeLayer: () => {
|
||||||
|
map.layer = false;
|
||||||
|
},
|
||||||
|
removeSource: () => {
|
||||||
|
map.source = null;
|
||||||
|
},
|
||||||
|
on: () => null, off: () => null,
|
||||||
|
getCenter: () => ({lat: 40, lng: -100}),
|
||||||
|
};
|
||||||
|
return map;
|
||||||
|
}
|
||||||
|
const target = {key: 'saved-1', id: 1, label: 'Somewhere', lat: 40, lon: -100, weapon: 'w88'};
|
||||||
|
let getContext, toDataURL;
|
||||||
|
beforeEach(() => {
|
||||||
|
loadTerrainGrid.mockClear();
|
||||||
|
// jsdom draws no canvas: an image of the right size is all the map is given.
|
||||||
|
getContext = jest.spyOn(HTMLCanvasElement.prototype, 'getContext').mockImplementation(() => ({
|
||||||
|
createImageData: (w, h) => ({data: new Uint8ClampedArray(w * h * 4)}),
|
||||||
|
putImageData: () => null,
|
||||||
|
}));
|
||||||
|
toDataURL = jest.spyOn(HTMLCanvasElement.prototype, 'toDataURL').mockImplementation(() => 'data:');
|
||||||
|
});
|
||||||
|
afterEach(() => {
|
||||||
|
cleanup();
|
||||||
|
getContext.mockRestore();
|
||||||
|
toDataURL.mockRestore();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('ask for targets first, and calculate nothing until there are some', async () => {
|
||||||
|
const map = fakeMap();
|
||||||
|
renderWithProviders(<FalloutPanel map={map} targets={[]} onClose={() => null}/>);
|
||||||
|
expect(screen.getByText('Step 2 of 4: Choose the targets')).toBeTruthy();
|
||||||
|
expect(screen.getByText('No targets yet')).toBeTruthy();
|
||||||
|
expect(screen.getByText(/Right-clicking the map adds one too/)).toBeTruthy();
|
||||||
|
expect(screen.getByRole('button', {name: 'Next: the wind'}).disabled).toBe(true);
|
||||||
|
// The wind is a step of its own.
|
||||||
|
expect(screen.queryByRole('textbox', {name: 'Wind'})).toBeNull();
|
||||||
|
await act(async () => new Promise((r) => setTimeout(r, 60)));
|
||||||
|
expect(map.added).toBe(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('show the targets\' fallout only once the user goes on, hour by hour or in total', async () => {
|
||||||
|
const map = fakeMap();
|
||||||
|
renderWithProviders(<FalloutPanel map={map} targets={[target]} onClose={() => null}/>);
|
||||||
|
expect(screen.getByText('1 target')).toBeTruthy();
|
||||||
|
await act(async () => new Promise((r) => setTimeout(r, 60)));
|
||||||
|
expect(map.added).toBe(0);
|
||||||
|
|
||||||
|
fireEvent.click(screen.getByRole('button', {name: 'Next: the wind'}));
|
||||||
|
expect(screen.getByText('Step 3 of 4: The wind')).toBeTruthy();
|
||||||
|
// Its fields are all shown; the winds a user can choose are the forecast or one wind of their
|
||||||
|
// own, and no test shots' winds.
|
||||||
|
expect(screen.getByRole('checkbox', {name: 'Follow the terrain'})).toBeTruthy();
|
||||||
|
expect(screen.getByRole('textbox', {name: 'Speed (mph)'})).toBeTruthy();
|
||||||
|
Element.prototype.scrollIntoView = Element.prototype.scrollIntoView || (() => null);
|
||||||
|
fireEvent.click(screen.getByRole('textbox', {name: 'Wind'}));
|
||||||
|
const winds = (await screen.findAllByRole('option')).map((o) => o.textContent);
|
||||||
|
expect(winds).toEqual(['Forecast winds aloft', 'One wind at every height']);
|
||||||
|
await act(async () => new Promise((r) => setTimeout(r, 60)));
|
||||||
|
expect(map.added).toBe(0);
|
||||||
|
|
||||||
|
fireEvent.click(screen.getByRole('button', {name: 'Next: the fallout'}));
|
||||||
|
expect(screen.getByText('Step 4 of 4: The fallout')).toBeTruthy();
|
||||||
|
expect(screen.getByRole('button', {name: 'Hour by hour'}).getAttribute('aria-pressed')).toBe('true');
|
||||||
|
expect(screen.getByText('Dose rate 1 hour after the bursts')).toBeTruthy();
|
||||||
|
await waitFor(() => expect(loadTerrainGrid).toHaveBeenCalledTimes(1), {timeout: 20000});
|
||||||
|
await waitFor(() => expect(screen.queryByText(/Calculating/)).toBeNull(), {timeout: 20000});
|
||||||
|
expect(map.layer).toBe(true);
|
||||||
|
|
||||||
|
// A later hour, then the total, which has no timeline.
|
||||||
|
fireEvent.change(screen.getByLabelText('Time after the bursts'), {target: {value: '5'}});
|
||||||
|
expect(screen.getByText('Dose rate 1 day after the bursts')).toBeTruthy();
|
||||||
|
fireEvent.click(screen.getByRole('button', {name: 'Total dose'}));
|
||||||
|
expect(screen.getByText('Total dose outdoors in the first two weeks')).toBeTruthy();
|
||||||
|
expect(screen.queryByLabelText('Time after the bursts')).toBeNull();
|
||||||
|
|
||||||
|
// Back to the wind clears the map; on again, with nothing changed, it is not calculated again.
|
||||||
|
fireEvent.click(screen.getByRole('button', {name: 'Back'}));
|
||||||
|
expect(screen.getByText('Step 3 of 4: The wind')).toBeTruthy();
|
||||||
|
expect(map.layer).toBe(false);
|
||||||
|
fireEvent.click(screen.getByRole('button', {name: 'Back'}));
|
||||||
|
expect(screen.getByText('Step 2 of 4: Choose the targets')).toBeTruthy();
|
||||||
|
fireEvent.click(screen.getByRole('button', {name: 'Next: the wind'}));
|
||||||
|
fireEvent.click(screen.getByRole('button', {name: 'Next: the fallout'}));
|
||||||
|
await waitFor(() => expect(map.layer).toBe(true));
|
||||||
|
expect(screen.queryByText(/Calculating/)).toBeNull();
|
||||||
|
expect(loadTerrainGrid).toHaveBeenCalledTimes(1);
|
||||||
|
}, 60000);
|
||||||
|
|
||||||
|
test('default to the forecast when it has the winds until the fallout is down, else one wind', async () => {
|
||||||
|
Element.prototype.scrollIntoView = Element.prototype.scrollIntoView || (() => null);
|
||||||
|
const windShown = async () => {
|
||||||
|
fireEvent.click(screen.getByRole('button', {name: 'Next: the wind'}));
|
||||||
|
await act(async () => new Promise((r) => setTimeout(r, 20)));
|
||||||
|
return screen.getByRole('textbox', {name: 'Wind'}).value;
|
||||||
|
};
|
||||||
|
// No forecast.
|
||||||
|
renderWithProviders(<FalloutPanel map={fakeMap()} targets={[target]}/>);
|
||||||
|
expect(await windShown()).toBe('One wind at every height');
|
||||||
|
cleanup();
|
||||||
|
|
||||||
|
// A forecast from the hour before now, for 3 days: it has the winds.
|
||||||
|
const hourMs = Math.floor(Date.now() / 3600000) * 3600000;
|
||||||
|
const hours = (count) => Array.from({length: count}, (_, h) => new Date(hourMs + (h - 1) * 3600000).toISOString());
|
||||||
|
const forecastOf = (count) => ({source: 'Open-Meteo', fetched_at: new Date(hourMs).toISOString(), spacing: 3,
|
||||||
|
points: [{lat: 40, lon: -100, elevation: 0}], hours: hours(count),
|
||||||
|
winds: [hours(count).map(() => [[10, 10, 270], [20000, 20, 270]])], rain: [hours(count).map(() => 0)]});
|
||||||
|
mockLatestWinds = forecastOf(72);
|
||||||
|
try {
|
||||||
|
renderWithProviders(<FalloutPanel map={fakeMap()} targets={[target]}/>);
|
||||||
|
expect(await windShown()).toBe('Forecast winds aloft');
|
||||||
|
cleanup();
|
||||||
|
// One ending a day from now does not: the fallout is still coming down then.
|
||||||
|
mockLatestWinds = forecastOf(24);
|
||||||
|
renderWithProviders(<FalloutPanel map={fakeMap()} targets={[target]}/>);
|
||||||
|
expect(await windShown()).toBe('One wind at every height');
|
||||||
|
} finally {
|
||||||
|
mockLatestWinds = null;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test('ask to download the forecast on the wind step, when it is not', async () => {
|
||||||
|
const before = mockWeather;
|
||||||
|
mockWeather = {...before, enabled: false, download: null};
|
||||||
|
try {
|
||||||
|
renderWithProviders(<FalloutPanel map={fakeMap()} targets={[target]}/>);
|
||||||
|
fireEvent.click(screen.getByRole('button', {name: 'Next: the wind'}));
|
||||||
|
await act(async () => new Promise((r) => setTimeout(r, 20)));
|
||||||
|
mockWeatherSet.length = 0;
|
||||||
|
fireEvent.click(screen.getByRole('button', {name: 'Download the forecast every day'}));
|
||||||
|
await act(async () => new Promise((r) => setTimeout(r, 20)));
|
||||||
|
expect(mockWeatherSet).toEqual([true]);
|
||||||
|
expect(screen.queryByRole('button', {name: 'Download the forecast every day'})).toBeNull();
|
||||||
|
} finally {
|
||||||
|
mockWeather = before;
|
||||||
|
}
|
||||||
|
cleanup();
|
||||||
|
// Subscribed: nothing asked.
|
||||||
|
renderWithProviders(<FalloutPanel map={fakeMap()} targets={[target]}/>);
|
||||||
|
fireEvent.click(screen.getByRole('button', {name: 'Next: the wind'}));
|
||||||
|
await act(async () => new Promise((r) => setTimeout(r, 20)));
|
||||||
|
expect(screen.queryByRole('button', {name: 'Download the forecast every day'})).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('warn when the forecast chosen runs out before the fallout is down', async () => {
|
||||||
|
Element.prototype.scrollIntoView = Element.prototype.scrollIntoView || (() => null);
|
||||||
|
const hourMs = Math.floor(Date.now() / 3600000) * 3600000;
|
||||||
|
const hours = Array.from({length: 24}, (_, h) => new Date(hourMs - (100 - h) * 3600000).toISOString());
|
||||||
|
mockLatestWinds = {source: 'Open-Meteo', fetched_at: new Date(hourMs - 100 * 3600000).toISOString(), spacing: 3,
|
||||||
|
points: [{lat: 40, lon: -100, elevation: 0}], hours,
|
||||||
|
winds: [hours.map(() => [[10, 10, 270], [20000, 20, 270]])], rain: [hours.map(() => 0)]};
|
||||||
|
try {
|
||||||
|
renderWithProviders(<FalloutPanel map={fakeMap()} targets={[target]}/>);
|
||||||
|
fireEvent.click(screen.getByRole('button', {name: 'Next: the wind'}));
|
||||||
|
await act(async () => new Promise((r) => setTimeout(r, 20)));
|
||||||
|
// Too old: one wind is chosen for the user.
|
||||||
|
expect(screen.getByRole('textbox', {name: 'Wind'}).value).toBe('One wind at every height');
|
||||||
|
await act(async () => new Promise((r) => setTimeout(r, 50)));
|
||||||
|
fireEvent.click(screen.getByRole('textbox', {name: 'Wind'}));
|
||||||
|
fireEvent.click([...document.querySelectorAll('[role=option]')].find((o) => o.textContent === 'Forecast winds aloft'));
|
||||||
|
expect(screen.getByText(/This forecast is out of date: .*last hour's winds are held/)).toBeTruthy();
|
||||||
|
fireEvent.click(screen.getByRole('button', {name: 'Next: the fallout'}));
|
||||||
|
expect(screen.getByText(/This forecast is out of date/)).toBeTruthy();
|
||||||
|
} finally {
|
||||||
|
mockLatestWinds = null;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test('add a target where the map is clicked next, until stopped', () => {
|
||||||
|
const onPlaceTarget = jest.fn();
|
||||||
|
const {rerender} = renderWithProviders(<FalloutPanel map={fakeMap()} targets={[]}
|
||||||
|
onPlaceTarget={onPlaceTarget}/>);
|
||||||
|
fireEvent.click(screen.getByRole('button', {name: 'Add a target'}));
|
||||||
|
expect(onPlaceTarget).toHaveBeenLastCalledWith(true);
|
||||||
|
rerender(<FalloutPanel map={fakeMap()} targets={[]} placingTarget onPlaceTarget={onPlaceTarget}/>);
|
||||||
|
expect(screen.getByText('Click the map where the target is.')).toBeTruthy();
|
||||||
|
expect(screen.queryByRole('button', {name: 'Add a target'})).toBeNull();
|
||||||
|
fireEvent.click(screen.getByRole('button', {name: 'Stop'}));
|
||||||
|
expect(onPlaceTarget).toHaveBeenLastCalledWith(false);
|
||||||
|
|
||||||
|
// Going on to the wind stops it too.
|
||||||
|
onPlaceTarget.mockClear();
|
||||||
|
rerender(<FalloutPanel map={fakeMap()} targets={[target]} placingTarget onPlaceTarget={onPlaceTarget}/>);
|
||||||
|
fireEvent.click(screen.getByRole('button', {name: 'Next: the wind'}));
|
||||||
|
expect(onPlaceTarget).toHaveBeenCalledWith(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('load the saved targets before saving over them', () => {
|
||||||
|
const onLoad = jest.fn(), onSave = jest.fn();
|
||||||
|
const tried = {key: 'new-1', label: 'Tried', lat: 41, lon: -101, weapon: 'w88'};
|
||||||
|
const {rerender} = renderWithProviders(<FalloutPanel map={fakeMap()} targets={[tried]} savedCount={156}
|
||||||
|
unsaved onLoad={onLoad} onSave={onSave}/>);
|
||||||
|
// Only the target being tried out is simulated until the saved ones are loaded.
|
||||||
|
expect(screen.getByText('1 target')).toBeTruthy();
|
||||||
|
expect(screen.getByText('(not saved)')).toBeTruthy();
|
||||||
|
expect(screen.getByText('Not saved.')).toBeTruthy();
|
||||||
|
const save = screen.getByRole('button', {name: 'Save Targets'});
|
||||||
|
expect(save.disabled).toBe(true);
|
||||||
|
expect(screen.getByText(/Saving replaces the saved targets: load them first/)).toBeTruthy();
|
||||||
|
fireEvent.click(screen.getByRole('button', {name: 'Load Saved Targets (156)'}));
|
||||||
|
expect(onLoad).toHaveBeenCalledTimes(1);
|
||||||
|
|
||||||
|
rerender(<FalloutPanel map={fakeMap()} targets={[target, tried]} savedCount={156} loaded unsaved
|
||||||
|
onLoad={onLoad} onSave={onSave}/>);
|
||||||
|
expect(screen.queryByRole('button', {name: /Load Saved Targets/})).toBeNull();
|
||||||
|
expect(screen.queryByText(/load them first/)).toBeNull();
|
||||||
|
fireEvent.click(screen.getByRole('button', {name: 'Save Targets'}));
|
||||||
|
expect(onSave).toHaveBeenCalledTimes(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('save targets when none are saved, and take one out of the list', () => {
|
||||||
|
const onRemoveTarget = jest.fn();
|
||||||
|
const tried = {key: 'new-1', label: 'Tried', lat: 41, lon: -101, weapon: 'w88'};
|
||||||
|
const {rerender} = renderWithProviders(<FalloutPanel map={fakeMap()} targets={[]} savedCount={0}/>);
|
||||||
|
expect(screen.queryByRole('button', {name: /Load Saved Targets/})).toBeNull();
|
||||||
|
expect(screen.getByRole('button', {name: 'Save Targets'}).disabled).toBe(true);
|
||||||
|
rerender(<FalloutPanel map={fakeMap()} targets={[tried]} savedCount={0} unsaved
|
||||||
|
onRemoveTarget={onRemoveTarget}/>);
|
||||||
|
expect(screen.getByRole('button', {name: 'Save Targets'}).disabled).toBe(false);
|
||||||
|
fireEvent.click(screen.getByRole('button', {name: 'Remove Tried'}));
|
||||||
|
expect(onRemoveTarget).toHaveBeenCalledWith(tried);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('the fallout of past days', () => {
|
||||||
|
const {simulateClimate, CLIMATE_BANDS} = require('./FalloutPanel');
|
||||||
|
const {parseClimatology} = require('../map-shared/fallout/climatology.js');
|
||||||
|
|
||||||
|
// Days on a coarse grid (lat 90..-90 every 30, lon 0..330 every 30), each one wind [east, north].
|
||||||
|
function climate(days) {
|
||||||
|
const header = {version: 1, levels_hpa: [1000, 500], lat: [90, -30, 7], lon: [0, 30, 12],
|
||||||
|
days: days.map((_, k) => `200${k}-05-01`)};
|
||||||
|
const head = new TextEncoder().encode(JSON.stringify(header));
|
||||||
|
const size = 2 * 7 * 12;
|
||||||
|
const bytes = new Uint8Array(10 + head.length + 2 * size + days.length * 2 * size);
|
||||||
|
bytes.set([87, 70, 67, 76], 0);
|
||||||
|
const view = new DataView(bytes.buffer);
|
||||||
|
view.setUint16(4, 1, true);
|
||||||
|
view.setUint32(6, head.length, true);
|
||||||
|
bytes.set(head, 10);
|
||||||
|
let at = 10 + head.length;
|
||||||
|
for (let c = 0; c < size; c++) view.setInt16(at + 2 * c, c < size / 2 ? 100 : 5500, true);
|
||||||
|
at += 2 * size;
|
||||||
|
for (const [e, n] of days) {
|
||||||
|
for (let c = 0; c < size; c++) view.setInt8(at + c, e);
|
||||||
|
for (let c = 0; c < size; c++) view.setInt8(at + size + c, n);
|
||||||
|
at += 2 * size;
|
||||||
|
}
|
||||||
|
return parseClimatology(bytes);
|
||||||
|
}
|
||||||
|
|
||||||
|
test('counts the days each place was reached, for all the bursts at once', async () => {
|
||||||
|
const bursts = [{lat: 30, lon: -120, yieldKt: 10, fissionFraction: 1}, {lat: 31, lon: -118, yieldKt: 10, fissionFraction: 1}];
|
||||||
|
const heard = [];
|
||||||
|
const ran = await simulateClimate(bursts, climate([[10, 0], [10, 0], [0, 10]]),
|
||||||
|
{rate: 1, onProgress: (done, total) => heard.push([done, total])});
|
||||||
|
expect(ran.origin).toBe(bursts[0]);
|
||||||
|
expect(ran.grid.days).toBe(3);
|
||||||
|
const most = ran.grid.values.reduce((a, v) => Math.max(a, v), 0);
|
||||||
|
expect(most).toBeGreaterThan(0.3);
|
||||||
|
expect(most).toBeLessThanOrEqual(1);
|
||||||
|
expect(heard[heard.length - 1]).toEqual([6, 6]);
|
||||||
|
// The bands go from most days to any.
|
||||||
|
expect(CLIMATE_BANDS.map((b) => b.rate)).toEqual([...CLIMATE_BANDS.map((b) => b.rate)].sort((a, b) => b - a));
|
||||||
|
});
|
||||||
|
|
||||||
|
test('stops when cancelled', async () => {
|
||||||
|
const bursts = [{lat: 30, lon: -120, yieldKt: 10, fissionFraction: 1}];
|
||||||
|
expect(await simulateClimate(bursts, climate([[10, 0], [0, 10]]), {cancelled: () => true})).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
const BURSTS = [{lat: 30, lon: -120, yieldKt: 10, fissionFraction: 1}, {lat: 31, lon: -118, yieldKt: 10, fissionFraction: 1}];
|
||||||
|
const DAYS = [[10, 0], [10, 0], [0, 10], [-8, 4], [3, -9]];
|
||||||
|
|
||||||
|
test('spreads the days over workers, and counts them as the page does', async () => {
|
||||||
|
made.length = 0;
|
||||||
|
const clim = climate(DAYS);
|
||||||
|
const here = await simulateClimate(BURSTS, clim, {rate: 1});
|
||||||
|
const heard = [];
|
||||||
|
const spread = await simulateClimate(BURSTS, clim, {rate: 1, workers: 2, makeWorker: () => worker(),
|
||||||
|
onProgress: (done, total) => heard.push([done, total])});
|
||||||
|
expect(made).toHaveLength(2);
|
||||||
|
// Every day given once, to one worker or the other, and both given some.
|
||||||
|
expect(made.flatMap((w) => w.given).sort()).toEqual([0, 1, 2, 3, 4]);
|
||||||
|
expect(made.every((w) => w.given.length > 0)).toBe(true);
|
||||||
|
expect(made.every((w) => w.terminated)).toBe(true);
|
||||||
|
expect(heard[heard.length - 1]).toEqual([10, 10]);
|
||||||
|
expect(spread.grid.days).toBe(5);
|
||||||
|
expect(spread.grid.cell).toBe(here.grid.cell);
|
||||||
|
expect(Array.from(spread.grid.values)).toEqual(Array.from(here.grid.values));
|
||||||
|
});
|
||||||
|
|
||||||
|
test('stops its workers at once when cancelled', async () => {
|
||||||
|
made.length = 0;
|
||||||
|
const controller = new AbortController();
|
||||||
|
const running = simulateClimate(BURSTS, climate(DAYS), {rate: 1, workers: 3, makeWorker: () => worker(),
|
||||||
|
signal: controller.signal});
|
||||||
|
controller.abort();
|
||||||
|
expect(await running).toBeNull();
|
||||||
|
expect(made).toHaveLength(3);
|
||||||
|
expect(made.every((w) => w.terminated)).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('calculates on the page when its workers fail', async () => {
|
||||||
|
made.length = 0;
|
||||||
|
const error = jest.spyOn(console, 'error').mockImplementation(() => null);
|
||||||
|
const clim = climate(DAYS);
|
||||||
|
const here = await simulateClimate(BURSTS, clim, {rate: 1});
|
||||||
|
const ran = await simulateClimate(BURSTS, clim, {rate: 1, workers: 2, makeWorker: () => worker({fail: true})});
|
||||||
|
expect(error).toHaveBeenCalled();
|
||||||
|
error.mockRestore();
|
||||||
|
expect(made.every((w) => w.terminated)).toBe(true);
|
||||||
|
expect(Array.from(ran.grid.values)).toEqual(Array.from(here.grid.values));
|
||||||
|
// And where there are none to be had.
|
||||||
|
const none = await simulateClimate(BURSTS, clim, {rate: 1, workers: 2, makeWorker: () => null});
|
||||||
|
expect(Array.from(none.grid.values)).toEqual(Array.from(here.grid.values));
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
|
||||||
|
describe('the fallout panel\'s progress', () => {
|
||||||
|
const {screen} = require('@testing-library/react');
|
||||||
|
const {renderWithProviders} = require('../test-utils');
|
||||||
|
const {FalloutProgress} = require('./FalloutPanel');
|
||||||
|
|
||||||
|
test('is a bar filled as far as the bursts are calculated', () => {
|
||||||
|
const {unmount} = renderWithProviders(<FalloutProgress busy={true} progress={{done: 1170, total: 4680}}/>);
|
||||||
|
const bar = screen.getByRole('progressbar');
|
||||||
|
expect(bar.getAttribute('aria-valuenow')).toBe('25');
|
||||||
|
expect(screen.getByText('Calculating 1,170 of 4,680')).toBeTruthy();
|
||||||
|
unmount();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('has a button which cancels the calculation', () => {
|
||||||
|
const {fireEvent} = require('@testing-library/react');
|
||||||
|
const onCancel = jest.fn();
|
||||||
|
const {unmount} = renderWithProviders(<FalloutProgress busy={true} progress={{done: 1, total: 2}} onCancel={onCancel}/>);
|
||||||
|
fireEvent.click(screen.getByRole('button', {name: 'Cancel'}));
|
||||||
|
expect(onCancel).toHaveBeenCalledTimes(1);
|
||||||
|
unmount();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('moves without a count until there is one, and is gone when done', () => {
|
||||||
|
const {rerender, unmount} = renderWithProviders(<FalloutProgress busy={true} progress={null}/>);
|
||||||
|
expect(screen.getByRole('progressbar').getAttribute('aria-valuenow')).toBeNull();
|
||||||
|
expect(screen.getByText('Calculating…')).toBeTruthy();
|
||||||
|
rerender(<FalloutProgress busy={false} progress={null}/>);
|
||||||
|
expect(screen.queryByRole('progressbar')).toBeNull();
|
||||||
|
unmount();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
@ -23,7 +23,15 @@ import {
|
||||||
import React, {useContext, useEffect, useState} from "react";
|
import React, {useContext, useEffect, useState} from "react";
|
||||||
import {IconArrowsMove, IconChevronsUp, IconCursorText, IconTags} from "@tabler/icons-react";
|
import {IconArrowsMove, IconChevronsUp, IconCursorText, IconTags} from "@tabler/icons-react";
|
||||||
import {useHotkeys} from "react-hotkeys-hook";
|
import {useHotkeys} from "react-hotkeys-hook";
|
||||||
import {deleteFile, ignoreDirectory, makeDirectory, movePaths, renamePath, unignoreDirectory} from "../api";
|
import {
|
||||||
|
deleteFile,
|
||||||
|
fetchFileWorkerJobStatus,
|
||||||
|
ignoreDirectory,
|
||||||
|
makeDirectory,
|
||||||
|
movePaths,
|
||||||
|
renamePath,
|
||||||
|
unignoreDirectory
|
||||||
|
} from "../api";
|
||||||
import _ from 'lodash';
|
import _ from 'lodash';
|
||||||
import {SortableTable} from "./SortableTable";
|
import {SortableTable} from "./SortableTable";
|
||||||
import {useBrowseFiles, useElementWidth, useMediaDirectory, useWROLMode} from "../hooks/customHooks";
|
import {useBrowseFiles, useElementWidth, useMediaDirectory, useWROLMode} from "../hooks/customHooks";
|
||||||
|
|
@ -33,7 +41,9 @@ import {DragSelectionContext, DragSelectionProvider, SettingsContext, ThemeConte
|
||||||
import {BulkTagModal} from "./BulkTagModal";
|
import {BulkTagModal} from "./BulkTagModal";
|
||||||
import {InlineErrorBoundary} from "./ErrorBoundary";
|
import {InlineErrorBoundary} from "./ErrorBoundary";
|
||||||
import {TaggedDeleteConfirmModal} from "./TaggedDeleteConfirmModal";
|
import {TaggedDeleteConfirmModal} from "./TaggedDeleteConfirmModal";
|
||||||
|
import {ShareTorrentModal} from "./ShareTorrentModal";
|
||||||
import {UploadModal} from "./Upload";
|
import {UploadModal} from "./Upload";
|
||||||
|
import {useFileWorkerStatus} from "../contexts/FileWorkerStatusContext";
|
||||||
|
|
||||||
function depthIndentation(path) {
|
function depthIndentation(path) {
|
||||||
// Repeated spaces for every folder a path is in.
|
// Repeated spaces for every folder a path is in.
|
||||||
|
|
@ -228,11 +238,14 @@ function SkeletonFileRow({depth}) {
|
||||||
// Below this footer width (px) the action buttons are icon-only; at or above it they expand to show labels.
|
// Below this footer width (px) the action buttons are icon-only; at or above it they expand to show labels.
|
||||||
// The eight labeled buttons need ~1020px to fit on a single row; this leaves a small buffer.
|
// The eight labeled buttons need ~1020px to fit on a single row; this leaves a small buffer.
|
||||||
const FOOTER_LABELS_MIN_WIDTH = 1050;
|
const FOOTER_LABELS_MIN_WIDTH = 1050;
|
||||||
|
// How often a queued rename's job is checked.
|
||||||
|
const RENAME_JOB_POLL_MS = 500;
|
||||||
|
|
||||||
export function FileBrowser() {
|
export function FileBrowser() {
|
||||||
const [selectedPaths, setSelectedPaths] = React.useState([]);
|
const [selectedPaths, setSelectedPaths] = React.useState([]);
|
||||||
const [renameOpen, setRenameOpen] = React.useState(false);
|
const [renameOpen, setRenameOpen] = React.useState(false);
|
||||||
const [moveOpen, setMoveOpen] = React.useState(false);
|
const [moveOpen, setMoveOpen] = React.useState(false);
|
||||||
|
const [shareOpen, setShareOpen] = React.useState(false);
|
||||||
const [makeDirectoryOpen, setMakeDirectoryOpen] = React.useState(false);
|
const [makeDirectoryOpen, setMakeDirectoryOpen] = React.useState(false);
|
||||||
const [ignoreDirectoryOpen, setIgnoreDirectoryOpen] = React.useState(false);
|
const [ignoreDirectoryOpen, setIgnoreDirectoryOpen] = React.useState(false);
|
||||||
const [bulkTagOpen, setBulkTagOpen] = React.useState(false);
|
const [bulkTagOpen, setBulkTagOpen] = React.useState(false);
|
||||||
|
|
@ -328,6 +341,46 @@ export function FileBrowser() {
|
||||||
}
|
}
|
||||||
}, [browseFiles]);
|
}, [browseFiles]);
|
||||||
|
|
||||||
|
// A move finishes in the file worker after its request returns (the Files page shows its progress), so fetch
|
||||||
|
// the files again when the file worker is done.
|
||||||
|
const {status: fileWorkerStatus, setFastPolling} = useFileWorkerStatus();
|
||||||
|
const fileWorkerBusy = !!fileWorkerStatus && fileWorkerStatus.status !== 'idle';
|
||||||
|
const fileWorkerWasBusy = React.useRef(false);
|
||||||
|
useEffect(() => {
|
||||||
|
if (fileWorkerWasBusy.current && !fileWorkerBusy) {
|
||||||
|
fetchFiles();
|
||||||
|
}
|
||||||
|
fileWorkerWasBusy.current = fileWorkerBusy;
|
||||||
|
}, [fileWorkerBusy]);
|
||||||
|
|
||||||
|
// A queued rename (a directory) returns its job; wait for that job, rather than inferring it from the file
|
||||||
|
// worker's status (a short job can start and finish between two polls).
|
||||||
|
const mountedRef = React.useRef(true);
|
||||||
|
useEffect(() => () => {
|
||||||
|
mountedRef.current = false;
|
||||||
|
}, []);
|
||||||
|
const afterRename = async (jobId) => {
|
||||||
|
if (!jobId) {
|
||||||
|
await reset();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
setSelectedPaths([]);
|
||||||
|
setFastPolling(true); // Update the progress bar while the rename runs.
|
||||||
|
try {
|
||||||
|
while (mountedRef.current) {
|
||||||
|
await new Promise(resolve => setTimeout(resolve, RENAME_JOB_POLL_MS));
|
||||||
|
if (await fetchFileWorkerJobStatus(jobId) !== 'pending') {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
setFastPolling(false);
|
||||||
|
}
|
||||||
|
if (mountedRef.current) {
|
||||||
|
await reset();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// Clear loading states when file data updates
|
// Clear loading states when file data updates
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (loadingFolders.size > 0) {
|
if (loadingFolders.size > 0) {
|
||||||
|
|
@ -413,7 +466,7 @@ export function FileBrowser() {
|
||||||
onClose={() => setRenameOpen(false)}
|
onClose={() => setRenameOpen(false)}
|
||||||
onPending={setPending}
|
onPending={setPending}
|
||||||
path={selectedPaths[0]}
|
path={selectedPaths[0]}
|
||||||
onSubmit={reset}
|
onSubmit={afterRename}
|
||||||
/> : null}
|
/> : null}
|
||||||
<Button icon={IconArrowsMove}
|
<Button icon={IconArrowsMove}
|
||||||
color='teal'
|
color='teal'
|
||||||
|
|
@ -426,6 +479,13 @@ export function FileBrowser() {
|
||||||
paths={selectedPaths}
|
paths={selectedPaths}
|
||||||
onSubmit={reset}
|
onSubmit={reset}
|
||||||
/> : null}
|
/> : null}
|
||||||
|
<Button icon='share'
|
||||||
|
color='violet'
|
||||||
|
onClick={() => setShareOpen(true)}
|
||||||
|
disabled={wrolModeEnabled || selectedPathsCount !== 1}
|
||||||
|
>{label('Share')}</Button>
|
||||||
|
{selectedPathsCount === 1 ?
|
||||||
|
<ShareTorrentModal open={shareOpen} onClose={() => setShareOpen(false)} path={selectedPaths[0]}/> : null}
|
||||||
<Button
|
<Button
|
||||||
color='blue'
|
color='blue'
|
||||||
onClick={() => setMakeDirectoryOpen(true)}
|
onClick={() => setMakeDirectoryOpen(true)}
|
||||||
|
|
@ -619,15 +679,16 @@ export function RenameModal({open, onClose, path, onSubmit, onPending}) {
|
||||||
if (e) {
|
if (e) {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
}
|
}
|
||||||
|
let jobId = null;
|
||||||
try {
|
try {
|
||||||
console.log(`Renaming: ${path} to ${value}`);
|
console.log(`Renaming: ${path} to ${value}`);
|
||||||
onPending(true);
|
onPending(true);
|
||||||
await renamePath(path, value);
|
jobId = await renamePath(path, value);
|
||||||
} finally {
|
} finally {
|
||||||
onClose();
|
onClose();
|
||||||
onPending(false);
|
onPending(false);
|
||||||
if (onSubmit) {
|
if (onSubmit) {
|
||||||
await onSubmit();
|
await onSubmit(jobId);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -6,10 +6,13 @@ import {FileBrowser, filterBrowseFiles} from './FileBrowser';
|
||||||
import {renderWithProviders} from '../test-utils';
|
import {renderWithProviders} from '../test-utils';
|
||||||
import {SettingsContext} from '../contexts/contexts';
|
import {SettingsContext} from '../contexts/contexts';
|
||||||
import {FilePreviewContext} from './FilePreview';
|
import {FilePreviewContext} from './FilePreview';
|
||||||
|
import {FileWorkerStatusContext} from '../contexts/FileWorkerStatusContext';
|
||||||
|
import {fileWorkerStatusFixture} from '../test-fixtures';
|
||||||
|
|
||||||
// Mock the API functions
|
// Mock the API functions
|
||||||
jest.mock('../api', () => ({
|
jest.mock('../api', () => ({
|
||||||
deleteFile: jest.fn(),
|
deleteFile: jest.fn(),
|
||||||
|
fetchFileWorkerJobStatus: jest.fn(),
|
||||||
ignoreDirectory: jest.fn(),
|
ignoreDirectory: jest.fn(),
|
||||||
makeDirectory: jest.fn(),
|
makeDirectory: jest.fn(),
|
||||||
movePaths: jest.fn(),
|
movePaths: jest.fn(),
|
||||||
|
|
@ -59,8 +62,13 @@ jest.mock('react-dropzone', () => ({
|
||||||
// Import mocked hooks for manipulation
|
// Import mocked hooks for manipulation
|
||||||
import {useBrowseFiles, useElementWidth, useWROLMode} from '../hooks/customHooks';
|
import {useBrowseFiles, useElementWidth, useWROLMode} from '../hooks/customHooks';
|
||||||
|
|
||||||
|
// Set by the wrapper so a test can change the file worker's status, as a poll would.
|
||||||
|
let setFileWorkerStatus;
|
||||||
|
|
||||||
// Create wrapper with all required contexts
|
// Create wrapper with all required contexts
|
||||||
const AllContextsWrapper = ({children}) => {
|
const AllContextsWrapper = ({children}) => {
|
||||||
|
const [fileWorkerStatus, setStatus] = React.useState({status: 'idle'});
|
||||||
|
setFileWorkerStatus = setStatus;
|
||||||
const settingsValue = {
|
const settingsValue = {
|
||||||
settings: {ignored_directories: []},
|
settings: {ignored_directories: []},
|
||||||
fetchSettings: jest.fn(),
|
fetchSettings: jest.fn(),
|
||||||
|
|
@ -71,11 +79,13 @@ const AllContextsWrapper = ({children}) => {
|
||||||
};
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
|
<FileWorkerStatusContext.Provider value={fileWorkerStatusFixture({status: fileWorkerStatus})}>
|
||||||
<SettingsContext.Provider value={settingsValue}>
|
<SettingsContext.Provider value={settingsValue}>
|
||||||
<FilePreviewContext.Provider value={filePreviewValue}>
|
<FilePreviewContext.Provider value={filePreviewValue}>
|
||||||
{children}
|
{children}
|
||||||
</FilePreviewContext.Provider>
|
</FilePreviewContext.Provider>
|
||||||
</SettingsContext.Provider>
|
</SettingsContext.Provider>
|
||||||
|
</FileWorkerStatusContext.Provider>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
@ -399,6 +409,77 @@ describe('FileBrowser', () => {
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
describe('File worker changes', () => {
|
||||||
|
it('fetches the files again when the file worker finishes', async () => {
|
||||||
|
const mockFetchFiles = jest.fn();
|
||||||
|
useBrowseFiles.mockReturnValue({
|
||||||
|
browseFiles: mockBrowseFiles,
|
||||||
|
openFolders: [],
|
||||||
|
setOpenFolders: jest.fn(),
|
||||||
|
fetchFiles: mockFetchFiles,
|
||||||
|
});
|
||||||
|
renderFileBrowser(<FileBrowser/>);
|
||||||
|
|
||||||
|
await act(async () => setFileWorkerStatus({status: 'moving', rename_from: '/media/wrolpi/testdir'}));
|
||||||
|
expect(mockFetchFiles).not.toHaveBeenCalled();
|
||||||
|
|
||||||
|
await act(async () => setFileWorkerStatus({status: 'idle'}));
|
||||||
|
expect(mockFetchFiles).toHaveBeenCalledTimes(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
const renameTestdir = async () => {
|
||||||
|
// Select testdir/ (the second checkbox) and rename it.
|
||||||
|
await act(async () => fireEvent.click(screen.getAllByRole('checkbox')[1]));
|
||||||
|
const renameButton = document.querySelector('.tabler-icon-cursor-text').closest('button');
|
||||||
|
await act(async () => fireEvent.click(renameButton));
|
||||||
|
const nameInput = await screen.findByDisplayValue(/^testdir/);
|
||||||
|
await act(async () => fireEvent.change(nameInput, {target: {value: 'newdir'}}));
|
||||||
|
await act(async () => fireEvent.click(screen.getByRole('button', {name: 'Rename'})));
|
||||||
|
};
|
||||||
|
|
||||||
|
it('fetches the files once a queued rename job is done, even if no poll saw it running', async () => {
|
||||||
|
const mockFetchFiles = jest.fn();
|
||||||
|
const api = require('../api');
|
||||||
|
api.renamePath.mockResolvedValue('move-1234');
|
||||||
|
// The job is still queued at the first check, and done at the second.
|
||||||
|
api.fetchFileWorkerJobStatus.mockResolvedValueOnce('pending').mockResolvedValue('complete');
|
||||||
|
useBrowseFiles.mockReturnValue({
|
||||||
|
browseFiles: mockBrowseFiles,
|
||||||
|
openFolders: [],
|
||||||
|
setOpenFolders: jest.fn(),
|
||||||
|
fetchFiles: mockFetchFiles,
|
||||||
|
});
|
||||||
|
renderFileBrowser(<FileBrowser/>);
|
||||||
|
|
||||||
|
await renameTestdir();
|
||||||
|
expect(api.renamePath).toHaveBeenCalledWith('testdir/', 'newdir');
|
||||||
|
// Nothing is fetched while the rename is only queued.
|
||||||
|
expect(mockFetchFiles).not.toHaveBeenCalled();
|
||||||
|
|
||||||
|
// The file worker's status never left idle; the job is what says the rename is done.
|
||||||
|
await waitFor(() => expect(mockFetchFiles).toHaveBeenCalledTimes(1), {timeout: 3000});
|
||||||
|
expect(api.fetchFileWorkerJobStatus).toHaveBeenCalledWith('move-1234');
|
||||||
|
expect(api.fetchFileWorkerJobStatus).toHaveBeenCalledTimes(2);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('fetches the files right away after a rename that was not queued', async () => {
|
||||||
|
const mockFetchFiles = jest.fn();
|
||||||
|
const api = require('../api');
|
||||||
|
api.renamePath.mockResolvedValue(null);
|
||||||
|
useBrowseFiles.mockReturnValue({
|
||||||
|
browseFiles: mockBrowseFiles,
|
||||||
|
openFolders: [],
|
||||||
|
setOpenFolders: jest.fn(),
|
||||||
|
fetchFiles: mockFetchFiles,
|
||||||
|
});
|
||||||
|
renderFileBrowser(<FileBrowser/>);
|
||||||
|
|
||||||
|
await renameTestdir();
|
||||||
|
expect(mockFetchFiles).toHaveBeenCalledTimes(1);
|
||||||
|
expect(api.fetchFileWorkerJobStatus).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
describe('Delete functionality', () => {
|
describe('Delete functionality', () => {
|
||||||
it('removes deleted directory from openFolders', async () => {
|
it('removes deleted directory from openFolders', async () => {
|
||||||
const mockSetOpenFolders = jest.fn();
|
const mockSetOpenFolders = jest.fn();
|
||||||
|
|
|
||||||
|
|
@ -5,15 +5,16 @@ import {encodeMediaPath, isSupportedArchive, useLocalStorage} from "./Common";
|
||||||
import {getFile, tagFileGroup, untagFileGroup} from "../api";
|
import {getFile, tagFileGroup, untagFileGroup} from "../api";
|
||||||
import {ArchivePreviewContent} from "./ArchivePreview";
|
import {ArchivePreviewContent} from "./ArchivePreview";
|
||||||
import {CbzViewer} from "./CbzViewer";
|
import {CbzViewer} from "./CbzViewer";
|
||||||
import {StlViewer} from "react-stl-viewer";
|
|
||||||
import {Button, ButtonGroup, Header, Icon, IconButton, MediaGate, Menu, Modal, toast} from "./ui";
|
import {Button, ButtonGroup, Header, Icon, IconButton, MediaGate, Menu, Modal, toast} from "./ui";
|
||||||
import {useOneQuery} from "../hooks/customHooks";
|
import {useOneQuery} from "../hooks/customHooks";
|
||||||
|
import {useEpubProgress, useMediaProgress} from "../hooks/useFileProgress";
|
||||||
import {ShareButton} from "./Share";
|
import {ShareButton} from "./Share";
|
||||||
import {AddToPlaylistButton} from "./AddToPlaylist";
|
import {AddToPlaylistButton} from "./AddToPlaylist";
|
||||||
import {pathDirectory} from "./FileBrowser";
|
import {pathDirectory} from "./FileBrowser";
|
||||||
import {InlineErrorBoundary} from "./ErrorBoundary";
|
import {InlineErrorBoundary} from "./ErrorBoundary";
|
||||||
import {useLocation} from "react-router";
|
import {useLocation} from "react-router";
|
||||||
import {ThemeContext} from "../contexts/contexts";
|
import {ThemeContext} from "../contexts/contexts";
|
||||||
|
import {isMarkdownFile, MarkdownPreview} from "./MarkdownPreview";
|
||||||
|
|
||||||
// Routes where file views should not be tracked
|
// Routes where file views should not be tracked
|
||||||
const EXCLUDED_TRACKING_ROUTES = [
|
const EXCLUDED_TRACKING_ROUTES = [
|
||||||
|
|
@ -100,7 +101,7 @@ function getEpubViewerURL(previewFile) {
|
||||||
* A component rather than part of `getIframePreviewModal` because it reads the theme: the
|
* A component rather than part of `getIframePreviewModal` because it reads the theme: the
|
||||||
* modal builders are plain functions called from an event handler, where hooks cannot run.
|
* modal builders are plain functions called from an event handler, where hooks cannot run.
|
||||||
*/
|
*/
|
||||||
export function IframePreview({url, gatePdf}) {
|
export function IframePreview({url, gatePdf, iframeRef}) {
|
||||||
const {isDark, mediaFilterEnabled} = React.useContext(ThemeContext);
|
const {isDark, mediaFilterEnabled} = React.useContext(ThemeContext);
|
||||||
|
|
||||||
/*
|
/*
|
||||||
|
|
@ -116,7 +117,7 @@ export function IframePreview({url, gatePdf}) {
|
||||||
*/
|
*/
|
||||||
return <MediaGate key={url} gated={!!gatePdf && !!mediaFilterEnabled}>
|
return <MediaGate key={url} gated={!!gatePdf && !!mediaFilterEnabled}>
|
||||||
<div className='preview-fit'>
|
<div className='preview-fit'>
|
||||||
<iframe title='textModal' src={url}
|
<iframe title='textModal' src={url} ref={iframeRef}
|
||||||
style={{
|
style={{
|
||||||
height: '100%', width: '100%', border: 'none',
|
height: '100%', width: '100%', border: 'none',
|
||||||
// A same-origin document has no styles of its own; it renders with the
|
// A same-origin document has no styles of its own; it renders with the
|
||||||
|
|
@ -137,6 +138,19 @@ function getIframePreviewModal(previewFile, url, {gatePdf = false} = {}) {
|
||||||
</Modal.Content>
|
</Modal.Content>
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** The EPUB viewer, opened where the user left off. */
|
||||||
|
function EpubPreview({previewFile}) {
|
||||||
|
const path = previewFile.primary_path ?? previewFile.path;
|
||||||
|
const {iframeRef, resumeCfi} = useEpubProgress(path, previewFile);
|
||||||
|
let url = getEpubViewerURL(previewFile);
|
||||||
|
if (resumeCfi) {
|
||||||
|
url = `${url}&cfi=${encodeURIComponent(resumeCfi)}`;
|
||||||
|
}
|
||||||
|
return <Modal.Content>
|
||||||
|
<IframePreview url={url} iframeRef={iframeRef}/>
|
||||||
|
</Modal.Content>
|
||||||
|
}
|
||||||
|
|
||||||
function getImagePreviewModal(previewFile) {
|
function getImagePreviewModal(previewFile) {
|
||||||
const path = previewFile.primary_path ?? previewFile.path;
|
const path = previewFile.primary_path ?? previewFile.path;
|
||||||
const url = getMediaPathURL(previewFile);
|
const url = getMediaPathURL(previewFile);
|
||||||
|
|
@ -156,6 +170,14 @@ function getImagePreviewModal(previewFile) {
|
||||||
</React.Fragment>
|
</React.Fragment>
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** A <video> or <audio> which resumes where the user left off, and saves how far they got. */
|
||||||
|
function PreviewMediaPlayer({as: Element, previewFile, path, style, children}) {
|
||||||
|
const progressHandlers = useMediaProgress(path, previewFile);
|
||||||
|
return <Element controls autoPlay={true} id="player" playsInline={true} style={style} {...progressHandlers}>
|
||||||
|
{children}
|
||||||
|
</Element>
|
||||||
|
}
|
||||||
|
|
||||||
function getVideoPreviewModal(previewFile) {
|
function getVideoPreviewModal(previewFile) {
|
||||||
const url = getMediaPathURL(previewFile);
|
const url = getMediaPathURL(previewFile);
|
||||||
const path = previewFile.primary_path ?? previewFile.path;
|
const path = previewFile.primary_path ?? previewFile.path;
|
||||||
|
|
@ -167,14 +189,10 @@ function getVideoPreviewModal(previewFile) {
|
||||||
<Modal.Content>
|
<Modal.Content>
|
||||||
<Header as='h5'>{path['path']}</Header>
|
<Header as='h5'>{path['path']}</Header>
|
||||||
<div className='preview-fit'>
|
<div className='preview-fit'>
|
||||||
<video controls
|
<PreviewMediaPlayer as='video' previewFile={previewFile} path={path}
|
||||||
autoPlay={true}
|
style={{maxHeight: '100%', maxWidth: '100%'}}>
|
||||||
id="player"
|
|
||||||
playsInline={true}
|
|
||||||
style={{maxHeight: '100%', maxWidth: '100%'}}
|
|
||||||
>
|
|
||||||
<source src={url}/>
|
<source src={url}/>
|
||||||
</video>
|
</PreviewMediaPlayer>
|
||||||
</div>
|
</div>
|
||||||
</Modal.Content>
|
</Modal.Content>
|
||||||
</React.Fragment>
|
</React.Fragment>
|
||||||
|
|
@ -191,19 +209,44 @@ function getAudioPreviewModal(previewFile) {
|
||||||
{name}
|
{name}
|
||||||
</Modal.Header>
|
</Modal.Header>
|
||||||
<Modal.Content>
|
<Modal.Content>
|
||||||
<audio controls
|
<PreviewMediaPlayer as='audio' previewFile={previewFile} path={path}
|
||||||
autoPlay={true}
|
style={{width: '90%', maxWidth: '95%'}}>
|
||||||
id="player"
|
|
||||||
playsInline={true}
|
|
||||||
style={{width: '90%', maxWidth: '95%'}}
|
|
||||||
>
|
|
||||||
<source src={url} type={type}/>
|
<source src={url} type={type}/>
|
||||||
</audio>
|
</PreviewMediaPlayer>
|
||||||
</Modal.Content>
|
</Modal.Content>
|
||||||
</React.Fragment>
|
</React.Fragment>
|
||||||
}
|
}
|
||||||
|
|
||||||
function ThreeMFPreviewModal({previewFile}) {
|
// Each 3D format's loader ships with three, so it always matches the installed three. Every
|
||||||
|
// format is Z-up.
|
||||||
|
const MODEL_FORMATS = {
|
||||||
|
'3mf': {
|
||||||
|
label: '3MF',
|
||||||
|
loader: async () => new (await import('three/examples/jsm/loaders/3MFLoader.js')).ThreeMFLoader(),
|
||||||
|
// A 3MF loads as a group of meshes.
|
||||||
|
toObject: (THREE, group) => group,
|
||||||
|
},
|
||||||
|
stl: {
|
||||||
|
label: 'STL',
|
||||||
|
loader: async () => new (await import('three/examples/jsm/loaders/STLLoader.js')).STLLoader(),
|
||||||
|
// An STL loads as a single geometry.
|
||||||
|
toObject: (THREE, geometry) => new THREE.Mesh(geometry),
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* How far a camera must stand from a sphere of `radius` for the whole sphere to be in view, with
|
||||||
|
* `margin` to spare. The narrower of the vertical and horizontal fields of view decides: a tall,
|
||||||
|
* narrow viewer is limited by its width.
|
||||||
|
*/
|
||||||
|
export function modelCameraDistance(radius, verticalFovDegrees, aspect, margin = 1.02) {
|
||||||
|
const halfVertical = (verticalFovDegrees * Math.PI) / 360;
|
||||||
|
const halfHorizontal = Math.atan(Math.tan(halfVertical) * aspect);
|
||||||
|
return (radius / Math.sin(Math.min(halfVertical, halfHorizontal))) * margin;
|
||||||
|
}
|
||||||
|
|
||||||
|
function ModelPreviewModal({previewFile, format}) {
|
||||||
|
const {label, loader: getLoader, toObject} = MODEL_FORMATS[format];
|
||||||
const containerRef = React.useRef(null);
|
const containerRef = React.useRef(null);
|
||||||
const [dimensions, setDimensions] = React.useState(null);
|
const [dimensions, setDimensions] = React.useState(null);
|
||||||
const [error, setError] = React.useState(null);
|
const [error, setError] = React.useState(null);
|
||||||
|
|
@ -212,7 +255,7 @@ function ThreeMFPreviewModal({previewFile}) {
|
||||||
const name = path.replace(/^.*[\\\/]/, '');
|
const name = path.replace(/^.*[\\\/]/, '');
|
||||||
|
|
||||||
React.useEffect(() => {
|
React.useEffect(() => {
|
||||||
// Imperative three.js viewer — mirrors react-stl-viewer behavior for .3mf files.
|
// Imperative three.js viewer.
|
||||||
let cancelled = false;
|
let cancelled = false;
|
||||||
const container = containerRef.current;
|
const container = containerRef.current;
|
||||||
if (!container) return;
|
if (!container) return;
|
||||||
|
|
@ -224,12 +267,12 @@ function ThreeMFPreviewModal({previewFile}) {
|
||||||
try {
|
try {
|
||||||
THREE = await import('three');
|
THREE = await import('three');
|
||||||
const {OrbitControls} = await import('three/examples/jsm/controls/OrbitControls.js');
|
const {OrbitControls} = await import('three/examples/jsm/controls/OrbitControls.js');
|
||||||
const {ThreeMFLoader} = await import('three/examples/jsm/loaders/3MFLoader.js');
|
const {toCreasedNormals} = await import('three/examples/jsm/utils/BufferGeometryUtils.js');
|
||||||
|
const loader = await getLoader();
|
||||||
if (cancelled) return;
|
if (cancelled) return;
|
||||||
|
|
||||||
scene = new THREE.Scene();
|
scene = new THREE.Scene();
|
||||||
// Transparent background so the modal/theme color shows through,
|
// Transparent background so the modal/theme color shows through.
|
||||||
// matching react-stl-viewer's behavior.
|
|
||||||
|
|
||||||
const width = container.clientWidth || 1;
|
const width = container.clientWidth || 1;
|
||||||
const height = container.clientHeight || 1;
|
const height = container.clientHeight || 1;
|
||||||
|
|
@ -243,32 +286,40 @@ function ThreeMFPreviewModal({previewFile}) {
|
||||||
renderer.setSize(width, height);
|
renderer.setSize(width, height);
|
||||||
container.appendChild(renderer.domElement);
|
container.appendChild(renderer.domElement);
|
||||||
|
|
||||||
scene.add(new THREE.AmbientLight(0xffffff, 0.6));
|
// Sky above, darker ground below, so top and bottom read differently. The headlight
|
||||||
const dirLight = new THREE.DirectionalLight(0xffffff, 0.8);
|
// follows the camera, so whichever side the user orbits to is lit; it shines from a
|
||||||
dirLight.position.set(1, 1, 1);
|
// little above and left of the camera so faces turned toward the viewer still shade
|
||||||
scene.add(dirLight);
|
// differently.
|
||||||
const dirLight2 = new THREE.DirectionalLight(0xffffff, 0.4);
|
scene.add(new THREE.HemisphereLight(0xffffff, 0x404040, 2));
|
||||||
dirLight2.position.set(-1, -1, -1);
|
const headlight = new THREE.DirectionalLight(0xffffff, 2.5);
|
||||||
scene.add(dirLight2);
|
scene.add(headlight);
|
||||||
|
const headlightOffset = new THREE.Vector3();
|
||||||
|
|
||||||
controls = new OrbitControls(camera, renderer.domElement);
|
controls = new OrbitControls(camera, renderer.domElement);
|
||||||
controls.enableDamping = true;
|
controls.enableDamping = true;
|
||||||
|
|
||||||
const loader = new ThreeMFLoader();
|
|
||||||
loader.load(
|
loader.load(
|
||||||
url,
|
url,
|
||||||
(group) => {
|
(result) => {
|
||||||
if (cancelled) return;
|
if (cancelled) return;
|
||||||
|
const group = toObject(THREE, result);
|
||||||
loadedGroup = group;
|
loadedGroup = group;
|
||||||
|
// STL and 3MF are Z-up (the 3D printing convention) and three is Y-up, so
|
||||||
|
// stand the model upright: model Z reads as Height, model Y as Length.
|
||||||
|
group.rotation.x = -Math.PI / 2;
|
||||||
|
|
||||||
// Match react-stl-viewer's violet so 3MFs without authored
|
// One violet for every model, so models without authored materials
|
||||||
// materials are visible against either theme's background.
|
// are visible against either theme's background.
|
||||||
// 3MF geometry often lacks vertex normals — compute them so
|
// Geometry may lack vertex normals (3MF stores none) — compute them so
|
||||||
// MeshPhongMaterial can shade faces instead of rendering flat black.
|
// MeshPhongMaterial can shade faces instead of rendering flat black.
|
||||||
|
// Creased: curves are smoothed, but an edge sharper than 30 degrees stays
|
||||||
|
// sharp, so flat faces do not shade into their neighbors.
|
||||||
group.traverse((obj) => {
|
group.traverse((obj) => {
|
||||||
if (obj.isMesh) {
|
if (obj.isMesh) {
|
||||||
if (obj.geometry && !obj.geometry.attributes.normal) {
|
if (obj.geometry && !obj.geometry.attributes.normal) {
|
||||||
obj.geometry.computeVertexNormals();
|
const creased = toCreasedNormals(obj.geometry, Math.PI / 6);
|
||||||
|
obj.geometry.dispose();
|
||||||
|
obj.geometry = creased;
|
||||||
}
|
}
|
||||||
obj.material = new THREE.MeshPhongMaterial({
|
obj.material = new THREE.MeshPhongMaterial({
|
||||||
color: 0x7353a8,
|
color: 0x7353a8,
|
||||||
|
|
@ -279,7 +330,9 @@ function ThreeMFPreviewModal({previewFile}) {
|
||||||
|
|
||||||
scene.add(group);
|
scene.add(group);
|
||||||
|
|
||||||
// Frame the model: center it, then pull camera back along Z by bounding radius.
|
// Frame the model: center it, then view it from the front, raised and a little
|
||||||
|
// to the right, far enough back that its bounding sphere (every point of it)
|
||||||
|
// fills the viewer.
|
||||||
const box = new THREE.Box3().setFromObject(group);
|
const box = new THREE.Box3().setFromObject(group);
|
||||||
const size = new THREE.Vector3();
|
const size = new THREE.Vector3();
|
||||||
const center = new THREE.Vector3();
|
const center = new THREE.Vector3();
|
||||||
|
|
@ -287,11 +340,11 @@ function ThreeMFPreviewModal({previewFile}) {
|
||||||
box.getCenter(center);
|
box.getCenter(center);
|
||||||
group.position.sub(center);
|
group.position.sub(center);
|
||||||
|
|
||||||
const boundingRadius = Math.max(size.x, size.y, size.z) / 2 || 1;
|
const boundingRadius = size.length() / 2 || 1;
|
||||||
const fitDistance = boundingRadius / Math.tan((Math.PI * camera.fov) / 360);
|
const distance = modelCameraDistance(boundingRadius, camera.fov, camera.aspect);
|
||||||
camera.position.set(0, 0, fitDistance * 2.2);
|
camera.position.set(0.6, 0.5, 1).normalize().multiplyScalar(distance);
|
||||||
camera.near = Math.max(0.1, fitDistance / 1000);
|
camera.near = distance / 100;
|
||||||
camera.far = fitDistance * 100;
|
camera.far = distance * 100;
|
||||||
camera.updateProjectionMatrix();
|
camera.updateProjectionMatrix();
|
||||||
controls.target.set(0, 0, 0);
|
controls.target.set(0, 0, 0);
|
||||||
controls.update();
|
controls.update();
|
||||||
|
|
@ -305,14 +358,17 @@ function ThreeMFPreviewModal({previewFile}) {
|
||||||
},
|
},
|
||||||
undefined,
|
undefined,
|
||||||
(err) => {
|
(err) => {
|
||||||
console.error('Failed to load 3MF', err);
|
console.error(`Failed to load ${label}`, err);
|
||||||
if (!cancelled) setError('Failed to load 3MF file.');
|
if (!cancelled) setError(`Failed to load ${label} file.`);
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
|
|
||||||
const animate = () => {
|
const animate = () => {
|
||||||
animationId = requestAnimationFrame(animate);
|
animationId = requestAnimationFrame(animate);
|
||||||
controls.update();
|
controls.update();
|
||||||
|
headlightOffset.set(-0.4, 0.6, 0).applyQuaternion(camera.quaternion)
|
||||||
|
.multiplyScalar(camera.position.length());
|
||||||
|
headlight.position.copy(camera.position).add(headlightOffset);
|
||||||
renderer.render(scene, camera);
|
renderer.render(scene, camera);
|
||||||
};
|
};
|
||||||
animate();
|
animate();
|
||||||
|
|
@ -326,8 +382,8 @@ function ThreeMFPreviewModal({previewFile}) {
|
||||||
});
|
});
|
||||||
resizeObserver.observe(container);
|
resizeObserver.observe(container);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.error('3MF viewer init failed', err);
|
console.error(`${label} viewer init failed`, err);
|
||||||
if (!cancelled) setError('Failed to initialize 3MF viewer.');
|
if (!cancelled) setError(`Failed to initialize ${label} viewer.`);
|
||||||
}
|
}
|
||||||
})();
|
})();
|
||||||
|
|
||||||
|
|
@ -355,7 +411,7 @@ function ThreeMFPreviewModal({previewFile}) {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
}, [url]);
|
}, [url, label, getLoader, toObject]);
|
||||||
|
|
||||||
return <React.Fragment>
|
return <React.Fragment>
|
||||||
<Modal.Header>{name}</Modal.Header>
|
<Modal.Header>{name}</Modal.Header>
|
||||||
|
|
@ -380,35 +436,12 @@ function ThreeMFPreviewModal({previewFile}) {
|
||||||
</React.Fragment>
|
</React.Fragment>
|
||||||
}
|
}
|
||||||
|
|
||||||
function STLPreviewModal({previewFile}) {
|
export function ThreeMFPreviewModal({previewFile}) {
|
||||||
const [dimensions, setDimensions] = React.useState(null);
|
return <ModelPreviewModal previewFile={previewFile} format='3mf'/>;
|
||||||
const url = getMediaPathURL(previewFile);
|
}
|
||||||
const path = previewFile.primary_path ?? previewFile.path;
|
|
||||||
const name = path.replace(/^.*[\\\/]/, '');
|
export function STLPreviewModal({previewFile}) {
|
||||||
return <React.Fragment>
|
return <ModelPreviewModal previewFile={previewFile} format='stl'/>;
|
||||||
<Modal.Header>{name}</Modal.Header>
|
|
||||||
<Modal.Content>
|
|
||||||
{dimensions && <div style={{marginBottom: '1em', textAlign: 'center'}}>
|
|
||||||
<b>Width:</b> {dimensions.width.toFixed(2)}
|
|
||||||
{' | '}
|
|
||||||
<b>Height:</b> {dimensions.height.toFixed(2)}
|
|
||||||
{' | '}
|
|
||||||
<b>Length:</b> {dimensions.length.toFixed(2)}
|
|
||||||
{' | '}
|
|
||||||
<b>Bounding Radius:</b> {dimensions.boundingRadius.toFixed(2)}
|
|
||||||
</div>}
|
|
||||||
<InlineErrorBoundary>
|
|
||||||
<div className='preview-fit'>
|
|
||||||
<StlViewer orbitControls shadows
|
|
||||||
url={url}
|
|
||||||
style={{height: '100%', width: '100%'}}
|
|
||||||
modelProps={{color: '#7353a8'}}
|
|
||||||
onFinishLoading={(dims) => setDimensions(dims)}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
</InlineErrorBoundary>
|
|
||||||
</Modal.Content>
|
|
||||||
</React.Fragment>
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function getGenericPreviewModal(previewFile) {
|
function getGenericPreviewModal(previewFile) {
|
||||||
|
|
@ -441,6 +474,9 @@ export function FilePreviewProvider({children}) {
|
||||||
const [previewQuery, setPreviewQuery] = useOneQuery('preview');
|
const [previewQuery, setPreviewQuery] = useOneQuery('preview');
|
||||||
const [errorModalOpen, setErrorModalOpen] = React.useState(false);
|
const [errorModalOpen, setErrorModalOpen] = React.useState(false);
|
||||||
const location = useLocation();
|
const location = useLocation();
|
||||||
|
// The path of the open preview that has been marked viewed. One opening is one view, however
|
||||||
|
// many times previewFile is replaced while it is open (re-fetching after tagging, for example).
|
||||||
|
const trackedPathRef = React.useRef(null);
|
||||||
|
|
||||||
// Determine if tracking should be skipped based on current route
|
// Determine if tracking should be skipped based on current route
|
||||||
const skipTracking = shouldSkipTracking(location.pathname);
|
const skipTracking = shouldSkipTracking(location.pathname);
|
||||||
|
|
@ -470,7 +506,8 @@ export function FilePreviewProvider({children}) {
|
||||||
const initPreviewFile = async () => {
|
const initPreviewFile = async () => {
|
||||||
// Get simple information about the file, preview the file.
|
// Get simple information about the file, preview the file.
|
||||||
try {
|
try {
|
||||||
const file = await getFile(previewQuery, skipTracking);
|
// Not a view; the preview effect marks the file viewed once it is displayed.
|
||||||
|
const file = await getFile(previewQuery, true);
|
||||||
setPreviewFile(file);
|
setPreviewFile(file);
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
console.error(e);
|
console.error(e);
|
||||||
|
|
@ -495,7 +532,7 @@ export function FilePreviewProvider({children}) {
|
||||||
// Get the file again with its Tags.
|
// Get the file again with its Tags.
|
||||||
const {path, primary_path} = previewFile;
|
const {path, primary_path} = previewFile;
|
||||||
try {
|
try {
|
||||||
const file = await getFile(primary_path ?? path, skipTracking);
|
const file = await getFile(primary_path ?? path, true);
|
||||||
setPreviewFile(file);
|
setPreviewFile(file);
|
||||||
} finally {
|
} finally {
|
||||||
await handleCallbacks();
|
await handleCallbacks();
|
||||||
|
|
@ -562,6 +599,7 @@ export function FilePreviewProvider({children}) {
|
||||||
setPreviewModal(<Modal size='fullscreen'
|
setPreviewModal(<Modal size='fullscreen'
|
||||||
open={true}
|
open={true}
|
||||||
onClose={e => handleClose(e)}
|
onClose={e => handleClose(e)}
|
||||||
|
classNames={{content: 'file-preview-modal-content'}}
|
||||||
>
|
>
|
||||||
{pathContent}
|
{pathContent}
|
||||||
<Modal.Actions>
|
<Modal.Actions>
|
||||||
|
|
@ -585,6 +623,9 @@ export function FilePreviewProvider({children}) {
|
||||||
|
|
||||||
React.useEffect(() => {
|
React.useEffect(() => {
|
||||||
setPreviewModal(null);
|
setPreviewModal(null);
|
||||||
|
if (_.isEmpty(previewFile)) {
|
||||||
|
trackedPathRef.current = null;
|
||||||
|
}
|
||||||
if (previewFile && !_.isObject(previewFile)) {
|
if (previewFile && !_.isObject(previewFile)) {
|
||||||
console.error(`Unknown previewFile type: ${typeof previewFile}`);
|
console.error(`Unknown previewFile type: ${typeof previewFile}`);
|
||||||
toast({
|
toast({
|
||||||
|
|
@ -607,6 +648,9 @@ export function FilePreviewProvider({children}) {
|
||||||
if (mimetype.startsWith('text/') && size > MAXIMUM_TEXT_SIZE) {
|
if (mimetype.startsWith('text/') && size > MAXIMUM_TEXT_SIZE) {
|
||||||
// Large text files should be downloaded.
|
// Large text files should be downloaded.
|
||||||
window.open(downloadURL);
|
window.open(downloadURL);
|
||||||
|
} else if (isMarkdownFile(mimetype, lowerPath)) {
|
||||||
|
setModalContent(<Modal.Content><MarkdownPreview url={url}/></Modal.Content>, url, downloadURL, path,
|
||||||
|
taggable);
|
||||||
} else if (mimetype.startsWith('text/') || mimetype.startsWith('application/json')) {
|
} else if (mimetype.startsWith('text/') || mimetype.startsWith('application/json')) {
|
||||||
setModalContent(getIframePreviewModal(previewFile), url, downloadURL, path, taggable);
|
setModalContent(getIframePreviewModal(previewFile), url, downloadURL, path, taggable);
|
||||||
} else if (mimetype.startsWith('video/')) {
|
} else if (mimetype.startsWith('video/')) {
|
||||||
|
|
@ -615,7 +659,7 @@ export function FilePreviewProvider({children}) {
|
||||||
setModalContent(getAudioPreviewModal(previewFile), url, downloadURL, path, taggable);
|
setModalContent(getAudioPreviewModal(previewFile), url, downloadURL, path, taggable);
|
||||||
} else if (mimetype.startsWith('application/epub')) {
|
} else if (mimetype.startsWith('application/epub')) {
|
||||||
const viewerURL = getEpubViewerURL(previewFile);
|
const viewerURL = getEpubViewerURL(previewFile);
|
||||||
setModalContent(getIframePreviewModal(previewFile, viewerURL), viewerURL, downloadURL, path, taggable);
|
setModalContent(<EpubPreview previewFile={previewFile}/>, viewerURL, downloadURL, path, taggable);
|
||||||
} else if (mimetype.startsWith('application/pdf')) {
|
} else if (mimetype.startsWith('application/pdf')) {
|
||||||
setModalContent(getIframePreviewModal(previewFile, null, {gatePdf: true}), url, downloadURL, path, taggable);
|
setModalContent(getIframePreviewModal(previewFile, null, {gatePdf: true}), url, downloadURL, path, taggable);
|
||||||
} else if (mimetype.startsWith('image/')) {
|
} else if (mimetype.startsWith('image/')) {
|
||||||
|
|
@ -637,7 +681,9 @@ export function FilePreviewProvider({children}) {
|
||||||
<OpenInSlicerButton previewFile={previewFile}/>);
|
<OpenInSlicerButton previewFile={previewFile}/>);
|
||||||
} else if (mimetype.includes('cbz') || mimetype.includes('cbr') || mimetype.includes('comicbook+zip') || mimetype.includes('comicbook-rar')
|
} else if (mimetype.includes('cbz') || mimetype.includes('cbr') || mimetype.includes('comicbook+zip') || mimetype.includes('comicbook-rar')
|
||||||
|| lowerPath.endsWith('.cbz') || lowerPath.endsWith('.cbr') || lowerPath.endsWith('.cbt') || lowerPath.endsWith('.cb7')) {
|
|| lowerPath.endsWith('.cbz') || lowerPath.endsWith('.cbr') || lowerPath.endsWith('.cbt') || lowerPath.endsWith('.cb7')) {
|
||||||
setModalContent(<Modal.Content><CbzViewer path={path}/></Modal.Content>, null, downloadURL, path, taggable);
|
setModalContent(<Modal.Content>
|
||||||
|
<CbzViewer path={path} progressPath={path} fileGroup={previewFile}/>
|
||||||
|
</Modal.Content>, null, downloadURL, path, taggable);
|
||||||
} else if (isSupportedArchive(mimetype, lowerPath)) {
|
} else if (isSupportedArchive(mimetype, lowerPath)) {
|
||||||
setModalContent(<ArchivePreviewContent previewFile={previewFile}/>, null, downloadURL, path, taggable);
|
setModalContent(<ArchivePreviewContent previewFile={previewFile}/>, null, downloadURL, path, taggable);
|
||||||
} else {
|
} else {
|
||||||
|
|
@ -646,7 +692,8 @@ export function FilePreviewProvider({children}) {
|
||||||
}
|
}
|
||||||
|
|
||||||
// Trigger tracking for the file view (unless on an excluded route)
|
// Trigger tracking for the file view (unless on an excluded route)
|
||||||
if (!skipTracking) {
|
if (!skipTracking && trackedPathRef.current !== path) {
|
||||||
|
trackedPathRef.current = path;
|
||||||
getFile(path).catch(e => {
|
getFile(path).catch(e => {
|
||||||
console.error(e);
|
console.error(e);
|
||||||
console.error('Failed to get file to set FileGroup.viewed');
|
console.error('Failed to get file to set FileGroup.viewed');
|
||||||
|
|
|
||||||
|
|
@ -101,6 +101,26 @@ describe('preview gate remounting (source contract)', () => {
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
describe('markdown preview routing (source contract)', () => {
|
||||||
|
/*
|
||||||
|
* Markdown is text/*, so the generic text branch would also accept it and show it raw in an
|
||||||
|
* iframe. The markdown branch has to be tested first for the formatted view to be reachable.
|
||||||
|
*/
|
||||||
|
const fs = require('fs');
|
||||||
|
const path = require('path');
|
||||||
|
const source = fs.readFileSync(path.join(__dirname, 'FilePreview.js'), 'utf8');
|
||||||
|
|
||||||
|
test('markdown is routed to MarkdownPreview before the generic text preview', () => {
|
||||||
|
const markdownBranch = source.indexOf('} else if (isMarkdownFile(mimetype, lowerPath)) {');
|
||||||
|
const textBranch = source.indexOf("} else if (mimetype.startsWith('text/') || mimetype.startsWith('application/json')) {");
|
||||||
|
|
||||||
|
expect(markdownBranch).toBeGreaterThan(-1);
|
||||||
|
expect(textBranch).toBeGreaterThan(-1);
|
||||||
|
expect(markdownBranch).toBeLessThan(textBranch);
|
||||||
|
expect(source.slice(markdownBranch, textBranch)).toContain('<MarkdownPreview url={url}/>');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
describe('IframePreview color scheme', () => {
|
describe('IframePreview color scheme', () => {
|
||||||
/*
|
/*
|
||||||
* The previewed file is a bare document with no styles of its own, so it renders with the
|
* The previewed file is a bare document with no styles of its own, so it renders with the
|
||||||
|
|
|
||||||
80
app/src/components/FilePreviewTracking.test.js
Normal file
80
app/src/components/FilePreviewTracking.test.js
Normal file
|
|
@ -0,0 +1,80 @@
|
||||||
|
import React from 'react';
|
||||||
|
import {act, waitFor} from '@testing-library/react';
|
||||||
|
import {renderWithProviders} from '../test-utils';
|
||||||
|
import {FilePreviewContext, FilePreviewProvider} from './FilePreview';
|
||||||
|
import {getFile} from '../api';
|
||||||
|
|
||||||
|
jest.mock('../api', () => ({
|
||||||
|
...jest.requireActual('../api'),
|
||||||
|
getFile: jest.fn(),
|
||||||
|
tagFileGroup: jest.fn(),
|
||||||
|
untagFileGroup: jest.fn(),
|
||||||
|
}));
|
||||||
|
|
||||||
|
const imageFile = {primary_path: 'pictures/cat.png', mimetype: 'image/png', size: 100, taggable: true, tags: []};
|
||||||
|
|
||||||
|
/** getFile calls that would mark the file viewed (skipTracking not set). */
|
||||||
|
const trackedCalls = () => getFile.mock.calls.filter(([, skipTracking]) => !skipTracking);
|
||||||
|
|
||||||
|
/** Exposes the provider's context so a test can open a preview the way PreviewLink does. */
|
||||||
|
let context;
|
||||||
|
const ContextSpy = () => {
|
||||||
|
context = React.useContext(FilePreviewContext);
|
||||||
|
return null;
|
||||||
|
};
|
||||||
|
|
||||||
|
const renderProvider = (preview = null) => renderWithProviders(
|
||||||
|
<FilePreviewProvider><ContextSpy/></FilePreviewProvider>,
|
||||||
|
{
|
||||||
|
route: '/files',
|
||||||
|
query: {searchParams: new URLSearchParams(preview ? {preview} : {}), updateQuery: jest.fn()},
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
describe('FilePreview view tracking', () => {
|
||||||
|
beforeEach(() => {
|
||||||
|
getFile.mockReset();
|
||||||
|
getFile.mockResolvedValue(imageFile);
|
||||||
|
context = null;
|
||||||
|
});
|
||||||
|
|
||||||
|
test('opening a preview from the URL marks the file viewed once', async () => {
|
||||||
|
renderProvider(imageFile.primary_path);
|
||||||
|
|
||||||
|
await waitFor(() => expect(getFile).toHaveBeenCalled());
|
||||||
|
await waitFor(() => expect(context.previewModal).not.toBeNull());
|
||||||
|
expect(trackedCalls()).toHaveLength(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('opening a preview from a link marks the file viewed once', async () => {
|
||||||
|
renderProvider();
|
||||||
|
|
||||||
|
act(() => context.setPreviewFile(imageFile));
|
||||||
|
|
||||||
|
await waitFor(() => expect(trackedCalls()).toHaveLength(1));
|
||||||
|
expect(getFile).toHaveBeenCalledTimes(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('refreshing the open file (after tagging) is not another view', async () => {
|
||||||
|
renderProvider();
|
||||||
|
act(() => context.setPreviewFile(imageFile));
|
||||||
|
await waitFor(() => expect(trackedCalls()).toHaveLength(1));
|
||||||
|
|
||||||
|
// localFetchFile replaces previewFile with the re-fetched file after a tag change.
|
||||||
|
act(() => context.setPreviewFile({...imageFile, tags: ['animals']}));
|
||||||
|
await waitFor(() => expect(context.previewFile.tags).toEqual(['animals']));
|
||||||
|
|
||||||
|
expect(trackedCalls()).toHaveLength(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('closing and reopening the same file is another view', async () => {
|
||||||
|
renderProvider();
|
||||||
|
act(() => context.setPreviewFile(imageFile));
|
||||||
|
await waitFor(() => expect(trackedCalls()).toHaveLength(1));
|
||||||
|
|
||||||
|
act(() => context.setPreviewFile(null));
|
||||||
|
act(() => context.setPreviewFile(imageFile));
|
||||||
|
|
||||||
|
await waitFor(() => expect(trackedCalls()).toHaveLength(2));
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
@ -481,6 +481,9 @@ export function DocSearchFilterButton({size = 'medium'}) {
|
||||||
return <SearchFilter filters={docMimetypeFilterOptions} size={size}/>
|
return <SearchFilter filters={docMimetypeFilterOptions} size={size}/>
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// The search relevance sort; see `SearchFilterModal`.
|
||||||
|
const RANK_ORDER = 'rank';
|
||||||
|
|
||||||
// The app-wide default page size (matches usePages' fallback); used to reset Results Per Page on Clear All.
|
// The app-wide default page size (matches usePages' fallback); used to reset Results Per Page on Clear All.
|
||||||
const DEFAULT_SEARCH_LIMIT = 24;
|
const DEFAULT_SEARCH_LIMIT = 24;
|
||||||
|
|
||||||
|
|
@ -540,7 +543,8 @@ export function SearchFilterModal(
|
||||||
// Seed the drafts from the URL each time the modal is opened.
|
// Seed the drafts from the URL each time the modal is opened.
|
||||||
React.useEffect(() => {
|
React.useEffect(() => {
|
||||||
if (open) {
|
if (open) {
|
||||||
setDraftSort(sort || null);
|
// Rank has no direction here; an old `-rank` link becomes `rank` when the modal closes.
|
||||||
|
setDraftSort(sort === `-${RANK_ORDER}` ? RANK_ORDER : (sort || null));
|
||||||
setDraftFilter(filter || null);
|
setDraftFilter(filter || null);
|
||||||
setDraftTags(activeTags || []);
|
setDraftTags(activeTags || []);
|
||||||
setDraftAnyTag(anyTag || false);
|
setDraftAnyTag(anyTag || false);
|
||||||
|
|
@ -614,17 +618,19 @@ export function SearchFilterModal(
|
||||||
setDraftDeep(false);
|
setDraftDeep(false);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Sort section (operates on the draft).
|
// Sort section (operates on the draft). Rank has no direction: `rank` is always the most relevant first
|
||||||
|
// (`-rank` would be the least relevant first), and a sort chosen after it starts descending.
|
||||||
const sortKey = draftSort ? draftSort.replace(/^-/, '') : (sorts ? sorts[0]['value'] : null);
|
const sortKey = draftSort ? draftSort.replace(/^-/, '') : (sorts ? sorts[0]['value'] : null);
|
||||||
const desc = draftSort ? draftSort.startsWith('-') : true;
|
const isRank = sortKey === RANK_ORDER;
|
||||||
|
const desc = draftSort && !isRank ? draftSort.startsWith('-') : true;
|
||||||
const sortButtons = sorts && sorts.map(o =>
|
const sortButtons = sorts && sorts.map(o =>
|
||||||
<Button key={o['value']}
|
<Button key={o['value']}
|
||||||
color={o['value'] === sortKey ? 'violet' : undefined}
|
color={o['value'] === sortKey ? 'violet' : undefined}
|
||||||
onClick={() => setDraftSort(desc ? `-${o['value']}` : o['value'])}
|
onClick={() => setDraftSort(o['value'] === RANK_ORDER || !desc ? o['value'] : `-${o['value']}`)}
|
||||||
style={{margin: '0.2em'}}
|
style={{margin: '0.2em'}}
|
||||||
>{o['text']}</Button>
|
>{o['text']}</Button>
|
||||||
);
|
);
|
||||||
const directionToggle = <Button icon={desc ? IconSortDescending : IconSortAscending}
|
const directionToggle = isRank ? null : <Button icon={desc ? IconSortDescending : IconSortAscending}
|
||||||
onClick={() => {
|
onClick={() => {
|
||||||
const base = sortKey || sorts[0]['value'];
|
const base = sortKey || sorts[0]['value'];
|
||||||
setDraftSort(desc ? base : `-${base}`);
|
setDraftSort(desc ? base : `-${base}`);
|
||||||
|
|
@ -658,7 +664,7 @@ export function SearchFilterModal(
|
||||||
<Stack gap='lg'>
|
<Stack gap='lg'>
|
||||||
{sorts &&
|
{sorts &&
|
||||||
<SearchFilterSection header='Sort By'>
|
<SearchFilterSection header='Sort By'>
|
||||||
<div style={{marginBottom: '1em'}}>{directionToggle}</div>
|
{directionToggle && <div style={{marginBottom: '1em'}}>{directionToggle}</div>}
|
||||||
<div>{sortButtons}</div>
|
<div>{sortButtons}</div>
|
||||||
</SearchFilterSection>}
|
</SearchFilterSection>}
|
||||||
|
|
||||||
|
|
@ -915,7 +921,12 @@ export function FilesSearchView({
|
||||||
</>
|
</>
|
||||||
}
|
}
|
||||||
|
|
||||||
function getPhaseLabel(status) {
|
function getPhaseLabel(status, renameFrom) {
|
||||||
|
if (renameFrom && (status === 'planning' || status === 'moving')) {
|
||||||
|
// A directory rename is a move of the directory's contents.
|
||||||
|
const name = renameFrom.split('/').filter(Boolean).pop();
|
||||||
|
return `Rename ${name}: ${status === 'planning' ? 'Planning' : 'Moving'}`;
|
||||||
|
}
|
||||||
switch (status) {
|
switch (status) {
|
||||||
case 'counting':
|
case 'counting':
|
||||||
return 'Counting';
|
return 'Counting';
|
||||||
|
|
@ -1037,8 +1048,8 @@ export function RefreshSteps({progress}) {
|
||||||
</div>
|
</div>
|
||||||
}
|
}
|
||||||
|
|
||||||
function RefreshProgressBar({status, operation_total, operation_processed, operation_percent, error}) {
|
function RefreshProgressBar({status, operation_total, operation_processed, operation_percent, error, rename_from}) {
|
||||||
const phaseLabel = getPhaseLabel(status);
|
const phaseLabel = getPhaseLabel(status, rename_from);
|
||||||
|
|
||||||
if (!phaseLabel) {
|
if (!phaseLabel) {
|
||||||
return null;
|
return null;
|
||||||
|
|
@ -1064,7 +1075,7 @@ export function FilesRefreshProgress() {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
const {status, operation_total, operation_processed, operation_percent, error} = progress;
|
const {status, operation_total, operation_processed, operation_percent, error, rename_from} = progress;
|
||||||
|
|
||||||
// Show Steps component AND progress bar for global refresh operations
|
// Show Steps component AND progress bar for global refresh operations
|
||||||
if (isGlobalRefresh(progress)) {
|
if (isGlobalRefresh(progress)) {
|
||||||
|
|
@ -1080,13 +1091,14 @@ export function FilesRefreshProgress() {
|
||||||
</>;
|
</>;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Show just progress bar for other operations (moves, reorganize, targeted refresh)
|
// Show just progress bar for other operations (moves, renames, reorganize, targeted refresh)
|
||||||
return <RefreshProgressBar
|
return <RefreshProgressBar
|
||||||
status={status}
|
status={status}
|
||||||
operation_total={operation_total}
|
operation_total={operation_total}
|
||||||
operation_processed={operation_processed}
|
operation_processed={operation_processed}
|
||||||
operation_percent={operation_percent}
|
operation_percent={operation_percent}
|
||||||
error={error}
|
error={error}
|
||||||
|
rename_from={rename_from}
|
||||||
/>;
|
/>;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
44
app/src/components/FilesRefreshProgress.test.js
Normal file
44
app/src/components/FilesRefreshProgress.test.js
Normal file
|
|
@ -0,0 +1,44 @@
|
||||||
|
import React from 'react';
|
||||||
|
import {screen} from '@testing-library/react';
|
||||||
|
import {FilesRefreshProgress} from './Files';
|
||||||
|
import {renderWithProviders} from '../test-utils';
|
||||||
|
import {fileWorkerStatusFixture} from '../test-fixtures';
|
||||||
|
import {FileWorkerStatusContext} from '../contexts/FileWorkerStatusContext';
|
||||||
|
|
||||||
|
const renderProgress = (status) => renderWithProviders(
|
||||||
|
<FileWorkerStatusContext.Provider value={fileWorkerStatusFixture({status})}>
|
||||||
|
<FilesRefreshProgress/>
|
||||||
|
</FileWorkerStatusContext.Provider>
|
||||||
|
);
|
||||||
|
|
||||||
|
const moving = {
|
||||||
|
status: 'moving',
|
||||||
|
task_type: 'move',
|
||||||
|
destination: '/media/wrolpi/3d models/Tools',
|
||||||
|
operation_total: 109,
|
||||||
|
operation_processed: 40,
|
||||||
|
operation_percent: 36,
|
||||||
|
error: null,
|
||||||
|
};
|
||||||
|
|
||||||
|
describe('FilesRefreshProgress', () => {
|
||||||
|
it('labels a move', () => {
|
||||||
|
renderProgress({...moving, rename_from: null});
|
||||||
|
expect(screen.getByText('Move: Moving (40 / 109)')).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('labels a directory rename with the renamed directory', () => {
|
||||||
|
renderProgress({...moving, rename_from: '/media/wrolpi/3d models/tools'});
|
||||||
|
expect(screen.getByText('Rename tools: Moving (40 / 109)')).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('labels a directory rename that is planning', () => {
|
||||||
|
renderProgress({...moving, status: 'planning', operation_total: 0, rename_from: '/media/wrolpi/3d models/tools'});
|
||||||
|
expect(screen.getByText('Rename tools: Planning')).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('shows nothing while idle', () => {
|
||||||
|
renderProgress({...moving, status: 'idle'});
|
||||||
|
expect(screen.queryByText(/Move|Rename/)).not.toBeInTheDocument();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
@ -3,7 +3,7 @@ import {Route, Routes} from "react-router";
|
||||||
import {ESPLoader, Transport} from "esptool-js";
|
import {ESPLoader, Transport} from "esptool-js";
|
||||||
import {useDropzone} from "react-dropzone";
|
import {useDropzone} from "react-dropzone";
|
||||||
import _ from "lodash";
|
import _ from "lodash";
|
||||||
import {encodeMediaPath, humanFileSize, PageContainer, useTitle} from "./Common";
|
import {encodeMediaPath, ErrorMessage, humanFileSize, PageContainer, useTitle} from "./Common";
|
||||||
import {
|
import {
|
||||||
Button,
|
Button,
|
||||||
Checkbox,
|
Checkbox,
|
||||||
|
|
@ -17,6 +17,7 @@ import {
|
||||||
Message,
|
Message,
|
||||||
Modal,
|
Modal,
|
||||||
Panel,
|
Panel,
|
||||||
|
Placeholder,
|
||||||
Progress,
|
Progress,
|
||||||
Select,
|
Select,
|
||||||
Stack,
|
Stack,
|
||||||
|
|
@ -269,7 +270,8 @@ export function FlasherPage() {
|
||||||
|
|
||||||
// Media-directory firmware picker.
|
// Media-directory firmware picker.
|
||||||
const [mediaFilter, setMediaFilter] = useState('');
|
const [mediaFilter, setMediaFilter] = useState('');
|
||||||
const [mediaResults, setMediaResults] = useState([]);
|
// null = not searched yet, undefined = the search failed, a list = the server's results.
|
||||||
|
const [mediaResults, setMediaResults] = useState(null);
|
||||||
const [mediaLoading, setMediaLoading] = useState(false);
|
const [mediaLoading, setMediaLoading] = useState(false);
|
||||||
// When set (e.g. "ESP32-S2"), the picker only shows firmware for that chip (detected from the device).
|
// When set (e.g. "ESP32-S2"), the picker only shows firmware for that chip (detected from the device).
|
||||||
const [deviceChip, setDeviceChip] = useState(null);
|
const [deviceChip, setDeviceChip] = useState(null);
|
||||||
|
|
@ -297,8 +299,12 @@ export function FlasherPage() {
|
||||||
// Which firmware-source tab is active (controlled so a file drop can switch to "Add from computer").
|
// Which firmware-source tab is active (controlled so a file drop can switch to "Add from computer").
|
||||||
const [activeTab, setActiveTab] = useState(TAB_SAVED);
|
const [activeTab, setActiveTab] = useState(TAB_SAVED);
|
||||||
|
|
||||||
// Saved firmware configurations (flasher.yaml).
|
// Saved firmware configurations (flasher.yaml). null = pending, undefined = fetch failed,
|
||||||
const [savedConfigs, setSavedConfigs] = useState([]);
|
// [] = none saved; the "No saved configurations yet." message is only for the last.
|
||||||
|
const [savedConfigs, setSavedConfigs] = useState(null);
|
||||||
|
// Only the newest configs request may write state: a save or delete refetches while the mount
|
||||||
|
// request may still be in flight.
|
||||||
|
const savedConfigsGen = useRef(0);
|
||||||
const [saveModalOpen, setSaveModalOpen] = useState(false);
|
const [saveModalOpen, setSaveModalOpen] = useState(false);
|
||||||
const [saveName, setSaveName] = useState('');
|
const [saveName, setSaveName] = useState('');
|
||||||
|
|
||||||
|
|
@ -388,14 +394,15 @@ export function FlasherPage() {
|
||||||
const fetchMediaFirmware = React.useCallback(async (pathFilter, chip) => {
|
const fetchMediaFirmware = React.useCallback(async (pathFilter, chip) => {
|
||||||
setMediaLoading(true);
|
setMediaLoading(true);
|
||||||
try {
|
try {
|
||||||
const [fileGroups] = await flasherSearch(chip || null, pathFilter || null);
|
const result = await flasherSearch(chip || null, pathFilter || null);
|
||||||
setMediaResults(fileGroups || []);
|
// The api helper returns undefined (and toasts) on a non-OK response.
|
||||||
|
setMediaResults(result ? result[0] || [] : undefined);
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
// Surface connectivity errors instead of showing the empty "no firmware found" state, which would
|
// Surface connectivity errors instead of showing the empty "no firmware found" state, which would
|
||||||
// be indistinguishable from genuinely having no firmware.
|
// be indistinguishable from genuinely having no firmware.
|
||||||
setError(e && e.message ? e.message : String(e));
|
setError(e && e.message ? e.message : String(e));
|
||||||
setBootHint(false);
|
setBootHint(false);
|
||||||
setMediaResults([]);
|
setMediaResults(undefined);
|
||||||
} finally {
|
} finally {
|
||||||
setMediaLoading(false);
|
setMediaLoading(false);
|
||||||
}
|
}
|
||||||
|
|
@ -424,7 +431,19 @@ export function FlasherPage() {
|
||||||
|
|
||||||
// Saved firmware configurations.
|
// Saved firmware configurations.
|
||||||
const fetchSavedConfigs = React.useCallback(async () => {
|
const fetchSavedConfigs = React.useCallback(async () => {
|
||||||
setSavedConfigs(await getFlasherConfigs());
|
const gen = ++savedConfigsGen.current;
|
||||||
|
try {
|
||||||
|
const configs = await getFlasherConfigs();
|
||||||
|
if (gen === savedConfigsGen.current) {
|
||||||
|
// The api helper returns undefined on a non-OK response.
|
||||||
|
setSavedConfigs(configs ?? undefined);
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
console.error(e);
|
||||||
|
if (gen === savedConfigsGen.current) {
|
||||||
|
setSavedConfigs(undefined);
|
||||||
|
}
|
||||||
|
}
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
|
|
@ -750,8 +769,10 @@ export function FlasherPage() {
|
||||||
onChange={(e) => handleMediaFilterChange(e.currentTarget.value)}
|
onChange={(e) => handleMediaFilterChange(e.currentTarget.value)}
|
||||||
/>
|
/>
|
||||||
<div style={{marginTop: '1em', overflowX: 'auto'}}>
|
<div style={{marginTop: '1em', overflowX: 'auto'}}>
|
||||||
{mediaLoading
|
{mediaLoading || mediaResults === null
|
||||||
? <Loading/>
|
? <Loading/>
|
||||||
|
: mediaResults === undefined
|
||||||
|
? <ErrorMessage>Could not search firmware.</ErrorMessage>
|
||||||
: (mediaResults.length === 0
|
: (mediaResults.length === 0
|
||||||
? <p style={{opacity: 0.7}}>
|
? <p style={{opacity: 0.7}}>
|
||||||
No <code>.bin</code> firmware found
|
No <code>.bin</code> firmware found
|
||||||
|
|
@ -812,7 +833,9 @@ export function FlasherPage() {
|
||||||
Configure the firmware files and offsets, then save them as a named set to re-flash later
|
Configure the firmware files and offsets, then save them as a named set to re-flash later
|
||||||
(e.g. a Meshtastic T-Deck: firmware at <code>0x0</code>, littlefs at <code>0xc90000</code>).
|
(e.g. a Meshtastic T-Deck: firmware at <code>0x0</code>, littlefs at <code>0xc90000</code>).
|
||||||
</p>
|
</p>
|
||||||
{savedConfigs.length > 0
|
{savedConfigs === null && <Placeholder lines={2}/>}
|
||||||
|
{savedConfigs === undefined && <ErrorMessage>Could not fetch saved configurations.</ErrorMessage>}
|
||||||
|
{Array.isArray(savedConfigs) && (savedConfigs.length > 0
|
||||||
? <Panel style={{padding: 0}}>
|
? <Panel style={{padding: 0}}>
|
||||||
{savedConfigs.map((configuration, index) => <div
|
{savedConfigs.map((configuration, index) => <div
|
||||||
key={configuration.name}
|
key={configuration.name}
|
||||||
|
|
@ -846,7 +869,7 @@ export function FlasherPage() {
|
||||||
onClick={() => handleDeleteConfig(configuration.name)}/>
|
onClick={() => handleDeleteConfig(configuration.name)}/>
|
||||||
</div>)}
|
</div>)}
|
||||||
</Panel>
|
</Panel>
|
||||||
: <p style={{opacity: 0.7}}>No saved configurations yet.</p>}
|
: <p style={{opacity: 0.7}}>No saved configurations yet.</p>)}
|
||||||
</>;
|
</>;
|
||||||
|
|
||||||
return <div {...getRootProps()}>
|
return <div {...getRootProps()}>
|
||||||
|
|
|
||||||
|
|
@ -265,6 +265,43 @@ describe('FlasherPage', () => {
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// The Saved Firmwares tab is the default tab. "No saved configurations yet." may only appear once the
|
||||||
|
// server confirmed there are none; a pending or failed fetch must not read as an empty list.
|
||||||
|
it('shows a placeholder, not "no saved configurations", while the configs load', () => {
|
||||||
|
Object.defineProperty(global.navigator, 'serial', {value: {}, configurable: true});
|
||||||
|
getFlasherConfigs.mockReturnValue(new Promise(() => {
|
||||||
|
}));
|
||||||
|
const {container} = render(<FlasherPage/>);
|
||||||
|
expect(container.querySelector('.wrolpi-placeholder')).toBeInTheDocument();
|
||||||
|
expect(screen.queryAllByText('No saved configurations yet.')).toHaveLength(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('shows an error, not "no saved configurations", when the configs fetch failed', async () => {
|
||||||
|
Object.defineProperty(global.navigator, 'serial', {value: {}, configurable: true});
|
||||||
|
getFlasherConfigs.mockResolvedValue(undefined);
|
||||||
|
render(<FlasherPage/>);
|
||||||
|
expect((await screen.findAllByText(/Could not fetch saved configurations/)).length).toBeGreaterThan(0);
|
||||||
|
expect(screen.queryAllByText('No saved configurations yet.')).toHaveLength(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('shows "no saved configurations" once the server confirmed there are none', async () => {
|
||||||
|
Object.defineProperty(global.navigator, 'serial', {value: {}, configurable: true});
|
||||||
|
render(<FlasherPage/>);
|
||||||
|
expect((await screen.findAllByText('No saved configurations yet.')).length).toBeGreaterThan(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
// "No .bin firmware found" may only appear once the server searched and found none.
|
||||||
|
it('shows an error, not "no firmware found", when the firmware search failed', async () => {
|
||||||
|
Object.defineProperty(global.navigator, 'serial', {value: {}, configurable: true});
|
||||||
|
// The api helper returns undefined on a non-OK response.
|
||||||
|
flasherSearch.mockResolvedValue(undefined);
|
||||||
|
render(<FlasherPage/>);
|
||||||
|
await waitFor(() => expect(flasherSearch).toHaveBeenCalled());
|
||||||
|
switchTab('Choose from your WROLPi');
|
||||||
|
expect((await screen.findAllByText(/Could not search firmware/)).length).toBeGreaterThan(0);
|
||||||
|
expect(screen.queryAllByText(/firmware found/)).toHaveLength(0);
|
||||||
|
});
|
||||||
|
|
||||||
// PageContainer renders both the mobile and desktop breakpoints (fresnel Media), so each label appears twice.
|
// PageContainer renders both the mobile and desktop breakpoints (fresnel Media), so each label appears twice.
|
||||||
it('warns when Web Serial is unavailable', () => {
|
it('warns when Web Serial is unavailable', () => {
|
||||||
delete global.navigator.serial;
|
delete global.navigator.serial;
|
||||||
|
|
|
||||||
|
|
@ -1,4 +1,4 @@
|
||||||
import React, {useEffect, useState} from "react";
|
import React, {useEffect, useRef, useState} from "react";
|
||||||
import {
|
import {
|
||||||
APIButton,
|
APIButton,
|
||||||
ErrorMessage,
|
ErrorMessage,
|
||||||
|
|
@ -11,41 +11,46 @@ import {
|
||||||
} from "./Common";
|
} from "./Common";
|
||||||
import {Route, Routes, useNavigate} from "react-router";
|
import {Route, Routes, useNavigate} from "react-router";
|
||||||
import {
|
import {
|
||||||
deleteMapFile, deleteMapPin, fetchMapSubscriptions, getMapFiles, getMapPins,
|
deleteMapFile, deleteMapPin, deleteMapTarget, fetchMapSubscriptions, getMapFiles, getMapPins, getMapTargets,
|
||||||
mapSubscribe, mapUnsubscribe, rebuildMapSearchIndex, updateMapPin
|
mapSubscribe, mapUnsubscribe, rebuildMapSearchIndex, setMapFileVisible, updateMapPin
|
||||||
} from "../api";
|
} from "../api";
|
||||||
import {Button, Divider, Group, Header, Icon, Modal, Table, TextInput} from "./ui";
|
import {targetWeapon} from "../map-shared/fallout/targets.js";
|
||||||
|
import {formatYieldAndFission} from "../map-shared/fallout/weapons.js";
|
||||||
|
import {Button, Divider, Group, Header, Icon, Modal, Table, TextInput, Toggle} from "./ui";
|
||||||
import {SortableTable} from "./SortableTable";
|
import {SortableTable} from "./SortableTable";
|
||||||
import {Media, StatusContext} from "../contexts/contexts";
|
import {Media, StatusContext} from "../contexts/contexts";
|
||||||
import {MAP_VIEWER_URI} from "./Vars";
|
import {MAP_VIEWER_URI} from "./Vars";
|
||||||
import MapViewer from "./MapViewer";
|
import MapViewer from "./MapViewer";
|
||||||
|
import {WeatherSection} from "./MapWeather";
|
||||||
import {AddToPlaylistButton} from "./AddToPlaylist";
|
import {AddToPlaylistButton} from "./AddToPlaylist";
|
||||||
|
import {solarCalculatorPath} from "./calculators/solar";
|
||||||
import maplibregl from "maplibre-gl";
|
import maplibregl from "maplibre-gl";
|
||||||
import {Protocol} from "pmtiles";
|
import {Protocol} from "pmtiles";
|
||||||
import layers from "protomaps-themes-base";
|
import layers from "protomaps-themes-base";
|
||||||
|
import {planMapFiles, pmtilesUrl} from "./mapOverlays";
|
||||||
|
import {MapAtak} from "./MapAtak";
|
||||||
|
|
||||||
// Ensure PMTiles protocol is registered (may already be registered by MapViewer).
|
// Ensure PMTiles protocol is registered (may already be registered by MapViewer).
|
||||||
try { maplibregl.addProtocol("pmtiles", new Protocol().tile); } catch (e) { /* already registered */ }
|
try { maplibregl.addProtocol("pmtiles", new Protocol().tile); } catch (e) { /* already registered */ }
|
||||||
|
|
||||||
const MAP_OVERVIEW_URL = "/blobs/map-overview.pmtiles";
|
const MAP_OVERVIEW_URL = "/blobs/map-overview.pmtiles";
|
||||||
|
|
||||||
// Detect full planet files: "planet-20260329.pmtiles" or bare date like "20260329.pmtiles".
|
// How the map draws a file (the API's `kind`).
|
||||||
function isPlanetFile(name) {
|
const MAP_FILE_KINDS = {
|
||||||
if (name.startsWith("planet-")) return true;
|
basemap: 'Basemap',
|
||||||
return /^\d{8}\.pmtiles$/.test(name);
|
overlay: 'Overlay',
|
||||||
}
|
terrain: 'Terrain',
|
||||||
|
unknown: 'Unreadable',
|
||||||
|
};
|
||||||
|
|
||||||
// Resolve the best available base map source for preview maps.
|
// Resolve the best available base map source for preview maps.
|
||||||
// Checks for a user's planet file first, falls back to the overview blob.
|
// Checks for a user's planet file first, falls back to the overview blob.
|
||||||
async function getPreviewMapSource() {
|
async function getPreviewMapSource() {
|
||||||
try {
|
try {
|
||||||
const data = await getMapFiles();
|
const data = await getMapFiles();
|
||||||
if (data?.files) {
|
const {planet} = planMapFiles(data?.files);
|
||||||
for (const f of data.files) {
|
if (planet) {
|
||||||
if (isPlanetFile(f.name)) {
|
return {type: 'vector', url: pmtilesUrl(planet.path)};
|
||||||
return {type: 'vector', url: `pmtiles:///media/map/${f.name}`};
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
} catch (e) { /* ignore */ }
|
} catch (e) { /* ignore */ }
|
||||||
return {type: 'vector', url: `pmtiles://${MAP_OVERVIEW_URL}`};
|
return {type: 'vector', url: `pmtiles://${MAP_OVERVIEW_URL}`};
|
||||||
|
|
@ -284,11 +289,15 @@ function MapCatalogRow({item, subscribedRegions, fetchData}) {
|
||||||
|
|
||||||
function ManageMap() {
|
function ManageMap() {
|
||||||
const [files, setFiles] = useState(null);
|
const [files, setFiles] = useState(null);
|
||||||
const [catalog, setCatalog] = useState([]);
|
// null = pending, undefined = fetch failed, [] = no regions in the catalog.
|
||||||
|
const [catalog, setCatalog] = useState(null);
|
||||||
const [subscriptions, setSubscriptions] = useState([]);
|
const [subscriptions, setSubscriptions] = useState([]);
|
||||||
const [allRegionsOpen, setAllRegionsOpen] = useState(false);
|
const [allRegionsOpen, setAllRegionsOpen] = useState(false);
|
||||||
const {status} = React.useContext(StatusContext);
|
const {status} = React.useContext(StatusContext);
|
||||||
const searchBuilding = status?.flags?.map_search_building;
|
const searchBuilding = status?.flags?.map_search_building;
|
||||||
|
// Only the newest subscriptions request may write state: a subscribe or unsubscribe refetches
|
||||||
|
// while the mount request may still be in flight.
|
||||||
|
const subscriptionsGen = useRef(0);
|
||||||
|
|
||||||
const fetchFiles = async () => {
|
const fetchFiles = async () => {
|
||||||
try {
|
try {
|
||||||
|
|
@ -303,14 +312,24 @@ function ManageMap() {
|
||||||
};
|
};
|
||||||
|
|
||||||
const fetchSubscriptionData = async () => {
|
const fetchSubscriptionData = async () => {
|
||||||
|
const gen = ++subscriptionsGen.current;
|
||||||
try {
|
try {
|
||||||
const data = await fetchMapSubscriptions();
|
const data = await fetchMapSubscriptions();
|
||||||
|
if (gen !== subscriptionsGen.current) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
if (data) {
|
if (data) {
|
||||||
setCatalog(data.catalog || []);
|
setCatalog(data.catalog || []);
|
||||||
setSubscriptions(data.subscriptions || []);
|
setSubscriptions(data.subscriptions || []);
|
||||||
|
} else {
|
||||||
|
// The api helper already toasted the non-OK response.
|
||||||
|
setCatalog(undefined);
|
||||||
}
|
}
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
console.error(e);
|
console.error(e);
|
||||||
|
if (gen === subscriptionsGen.current) {
|
||||||
|
setCatalog(undefined);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
@ -328,30 +347,51 @@ function ManageMap() {
|
||||||
|
|
||||||
// --- Files table ---
|
// --- Files table ---
|
||||||
const fileHeaders = [
|
const fileHeaders = [
|
||||||
{key: 'name', text: 'File', sortBy: i => i.name.toLowerCase()},
|
{key: 'name', text: 'File', sortBy: i => i.map_path.toLowerCase()},
|
||||||
|
{key: 'kind', text: 'Type', sortBy: i => i.kind || ''},
|
||||||
{key: 'size', text: 'Size', sortBy: i => i.size || 0},
|
{key: 'size', text: 'Size', sortBy: i => i.size || 0},
|
||||||
{key: 'search', text: 'Search', sortBy: null},
|
{key: 'search', text: 'Search', sortBy: null},
|
||||||
{key: 'actions', text: '', sortBy: null},
|
{key: 'actions', text: '', sortBy: null},
|
||||||
|
{key: 'visible', text: 'Visible', sortBy: i => (i.visible === false ? 0 : 1)},
|
||||||
];
|
];
|
||||||
|
|
||||||
const handleBuildSearch = async (filename) => {
|
const handleBuildSearch = async (mapPath) => {
|
||||||
await rebuildMapSearchIndex(filename);
|
await rebuildMapSearchIndex(mapPath);
|
||||||
await fetchFiles();
|
await fetchFiles();
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const handleVisible = async (file, visible) => {
|
||||||
|
try {
|
||||||
|
await setMapFileVisible(file.map_path, visible);
|
||||||
|
} finally {
|
||||||
|
await fetchFiles();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
const fileRowFunc = (file) => {
|
const fileRowFunc = (file) => {
|
||||||
return <Table.Row key={file.name}>
|
return <Table.Row key={file.map_path}>
|
||||||
<Table.Cell>{file.name}</Table.Cell>
|
<Table.Cell>
|
||||||
|
{/* A file in a sub-directory is shown with its directory. */}
|
||||||
|
{file.map_path}
|
||||||
|
{file.title && file.title !== file.name.replace(/\.pmtiles$/, '') && <div style={{fontSize: '0.75rem', color: 'var(--muted)'}}
|
||||||
|
title={file.description || undefined}>{file.title}</div>}
|
||||||
|
</Table.Cell>
|
||||||
|
<Table.Cell>
|
||||||
|
{MAP_FILE_KINDS[file.kind] || ''}
|
||||||
|
{/* A style beside the file says how it is drawn. */}
|
||||||
|
{file.kind === 'overlay' && file.style_path ? ' (styled)' : ''}
|
||||||
|
</Table.Cell>
|
||||||
<Table.Cell>{humanFileSize(file.size)}</Table.Cell>
|
<Table.Cell>{humanFileSize(file.size)}</Table.Cell>
|
||||||
<Table.Cell>
|
<Table.Cell>
|
||||||
{file.name.startsWith('terrain')
|
{/* A search index is built from a basemap's places; other files have none. */}
|
||||||
|
{file.kind !== 'basemap'
|
||||||
? null
|
? null
|
||||||
: file.has_search_index
|
: file.has_search_index
|
||||||
? <Button size='xs' icon='check' disabled role='save'>Built</Button>
|
? <Button size='xs' icon='check' disabled role='save'>Built</Button>
|
||||||
: <APIButton size='xs' icon='search'
|
: <APIButton size='xs' icon='search'
|
||||||
disabled={searchBuilding}
|
disabled={searchBuilding}
|
||||||
loading={searchBuilding}
|
loading={searchBuilding}
|
||||||
onClick={() => handleBuildSearch(file.name)}>
|
onClick={() => handleBuildSearch(file.map_path)}>
|
||||||
{searchBuilding ? 'Building...' : 'Build'}
|
{searchBuilding ? 'Building...' : 'Build'}
|
||||||
</APIButton>
|
</APIButton>
|
||||||
}
|
}
|
||||||
|
|
@ -362,16 +402,24 @@ function ManageMap() {
|
||||||
size='xs'
|
size='xs'
|
||||||
confirmContent='Delete this map file?'
|
confirmContent='Delete this map file?'
|
||||||
confirmButton='Delete'
|
confirmButton='Delete'
|
||||||
onClick={() => handleDelete(file.name)}
|
onClick={() => handleDelete(file.map_path)}
|
||||||
>
|
>
|
||||||
Delete
|
Delete
|
||||||
</APIButton>
|
</APIButton>
|
||||||
</Table.Cell>
|
</Table.Cell>
|
||||||
|
<Table.Cell>
|
||||||
|
<Toggle
|
||||||
|
aria-label={`Show ${file.map_path} on the map`}
|
||||||
|
title='Show this file on the map, or ignore it.'
|
||||||
|
checked={file.visible !== false}
|
||||||
|
onChange={(e) => handleVisible(file, e.currentTarget.checked)}
|
||||||
|
/>
|
||||||
|
</Table.Cell>
|
||||||
</Table.Row>;
|
</Table.Row>;
|
||||||
};
|
};
|
||||||
|
|
||||||
const emptyRow = <Table.Row>
|
const emptyRow = <Table.Row>
|
||||||
<Table.Cell colSpan={4}>No PMTiles map files were found in <b>map/</b></Table.Cell>
|
<Table.Cell colSpan={6}>No PMTiles map files were found in <b>map/</b></Table.Cell>
|
||||||
</Table.Row>;
|
</Table.Row>;
|
||||||
|
|
||||||
// --- Catalog table ---
|
// --- Catalog table ---
|
||||||
|
|
@ -397,6 +445,8 @@ function ManageMap() {
|
||||||
</>;
|
</>;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const catalogLoaded = Array.isArray(catalog);
|
||||||
|
|
||||||
/*
|
/*
|
||||||
* A fragment, not a `PageContainer`. `MapRoute` already provides the page chrome -- a
|
* A fragment, not a `PageContainer`. `MapRoute` already provides the page chrome -- a
|
||||||
* `wrolpi-stack` wrapper with its own top margin -- so a second one put this page a further
|
* `wrolpi-stack` wrapper with its own top margin -- so a second one put this page a further
|
||||||
|
|
@ -410,7 +460,7 @@ function ManageMap() {
|
||||||
tableHeaders={fileHeaders}
|
tableHeaders={fileHeaders}
|
||||||
data={files}
|
data={files}
|
||||||
rowFunc={fileRowFunc}
|
rowFunc={fileRowFunc}
|
||||||
rowKey='name'
|
rowKey='map_path'
|
||||||
defaultSortColumn='name'
|
defaultSortColumn='name'
|
||||||
emptyRow={emptyRow}
|
emptyRow={emptyRow}
|
||||||
/>
|
/>
|
||||||
|
|
@ -419,18 +469,26 @@ function ManageMap() {
|
||||||
|
|
||||||
<div style={{display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '0.5em'}}>
|
<div style={{display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '0.5em'}}>
|
||||||
<Header as='h3'>Map Subscriptions</Header>
|
<Header as='h3'>Map Subscriptions</Header>
|
||||||
<Button size='xs' icon='globe' onClick={() => setAllRegionsOpen(true)}>View All Regions</Button>
|
{/* A pending or failed catalog is not "zero regions": the preview waits for one. The
|
||||||
|
modal is mounted only then, so it receives the state array itself and its map is
|
||||||
|
not rebuilt by a fresh `[]` on every status tick. */}
|
||||||
|
<Button size='xs' icon='globe' disabled={!catalogLoaded} onClick={() => setAllRegionsOpen(true)}>
|
||||||
|
View All Regions
|
||||||
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<AllRegionsPreviewModal catalog={catalog} open={allRegionsOpen} onClose={() => setAllRegionsOpen(false)}/>
|
{catalogLoaded && <AllRegionsPreviewModal catalog={catalog} open={allRegionsOpen}
|
||||||
|
onClose={() => setAllRegionsOpen(false)}/>}
|
||||||
|
|
||||||
<SortableTable
|
{catalog === undefined
|
||||||
|
? <ErrorMessage>Could not fetch map subscriptions</ErrorMessage>
|
||||||
|
: <SortableTable
|
||||||
tableHeaders={catalogHeaders}
|
tableHeaders={catalogHeaders}
|
||||||
data={catalog}
|
data={catalog}
|
||||||
rowFunc={catalogRowFunc}
|
rowFunc={catalogRowFunc}
|
||||||
rowKey='region'
|
rowKey='region'
|
||||||
defaultSortColumn='name'
|
defaultSortColumn='name'
|
||||||
/>
|
/>}
|
||||||
|
|
||||||
<InfoMessage storageName='hint_map_subscribe'>
|
<InfoMessage storageName='hint_map_subscribe'>
|
||||||
<div style={{fontWeight: 600, marginBottom: 4}}>How to get map files</div>
|
<div style={{fontWeight: 600, marginBottom: 4}}>How to get map files</div>
|
||||||
|
|
@ -447,6 +505,10 @@ function ManageMap() {
|
||||||
</p>
|
</p>
|
||||||
</InfoMessage>
|
</InfoMessage>
|
||||||
|
|
||||||
|
<Divider/>
|
||||||
|
|
||||||
|
<WeatherSection/>
|
||||||
|
|
||||||
<HandPointMessage>
|
<HandPointMessage>
|
||||||
<p>You can also view the map at <a href={MAP_VIEWER_URI}>{MAP_VIEWER_URI}</a></p>
|
<p>You can also view the map at <a href={MAP_VIEWER_URI}>{MAP_VIEWER_URI}</a></p>
|
||||||
</HandPointMessage>
|
</HandPointMessage>
|
||||||
|
|
@ -497,17 +559,29 @@ function PinEditRow({pin, onSave, onCancel}) {
|
||||||
}
|
}
|
||||||
|
|
||||||
function MapPins() {
|
function MapPins() {
|
||||||
const [pins, setPins] = useState([]);
|
// null = pending, undefined = fetch failed, [] = no pins. The empty row invites the user to
|
||||||
|
// add one, so it may only appear for a confirmed empty list.
|
||||||
|
const [pins, setPins] = useState(null);
|
||||||
const [filter, setFilter] = useState('');
|
const [filter, setFilter] = useState('');
|
||||||
const [editingId, setEditingId] = useState(null);
|
const [editingId, setEditingId] = useState(null);
|
||||||
const navigate = useNavigate();
|
const navigate = useNavigate();
|
||||||
|
// Only the newest pins request may write state: an edit or delete refetches while the mount
|
||||||
|
// request may still be in flight.
|
||||||
|
const pinsGen = useRef(0);
|
||||||
|
|
||||||
const fetchPins = async () => {
|
const fetchPins = async () => {
|
||||||
|
const gen = ++pinsGen.current;
|
||||||
try {
|
try {
|
||||||
const data = await getMapPins();
|
const data = await getMapPins();
|
||||||
if (data) setPins(data.pins || []);
|
if (gen === pinsGen.current) {
|
||||||
|
// The api helper returns undefined on a non-OK response.
|
||||||
|
setPins(data ? data.pins || [] : undefined);
|
||||||
|
}
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
console.error(e);
|
console.error(e);
|
||||||
|
if (gen === pinsGen.current) {
|
||||||
|
setPins(undefined);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
@ -531,6 +605,9 @@ function MapPins() {
|
||||||
navigate(`/map?lat=${pin.lat}&lon=${pin.lon}&z=14`);
|
navigate(`/map?lat=${pin.lat}&lon=${pin.lon}&z=14`);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const solarButton = (pin) => <Button size='xs' icon='sun' aria-label={`Solar estimate for ${pin.label}`}
|
||||||
|
onClick={() => navigate(solarCalculatorPath(pin.lat, pin.lon))}/>;
|
||||||
|
|
||||||
// --- Desktop headers and row ---
|
// --- Desktop headers and row ---
|
||||||
const fullHeaders = [
|
const fullHeaders = [
|
||||||
{key: 'color', text: '', sortBy: i => i.color},
|
{key: 'color', text: '', sortBy: i => i.color},
|
||||||
|
|
@ -564,10 +641,11 @@ function MapPins() {
|
||||||
</Table.Cell>
|
</Table.Cell>
|
||||||
<Table.Cell>{pin.created}</Table.Cell>
|
<Table.Cell>{pin.created}</Table.Cell>
|
||||||
<Table.Cell>
|
<Table.Cell>
|
||||||
{/* See PinEditRow: a Group so the three controls line up and are spaced. */}
|
{/* See PinEditRow: a Group so the controls line up and are spaced. */}
|
||||||
<Group gap='xs' wrap='nowrap'>
|
<Group gap='xs' wrap='nowrap'>
|
||||||
<Button size='xs' icon='edit' aria-label={`Edit ${pin.label}`}
|
<Button size='xs' icon='edit' aria-label={`Edit ${pin.label}`}
|
||||||
onClick={() => setEditingId(pin.id)}/>
|
onClick={() => setEditingId(pin.id)}/>
|
||||||
|
{solarButton(pin)}
|
||||||
<AddToPlaylistButton
|
<AddToPlaylistButton
|
||||||
size='xs'
|
size='xs'
|
||||||
icon='list'
|
icon='list'
|
||||||
|
|
@ -610,6 +688,8 @@ function MapPins() {
|
||||||
<div style={{fontSize: '0.6875rem', color: 'var(--muted)'}}>{pin.lat.toFixed(4)}, {pin.lon.toFixed(4)}</div>
|
<div style={{fontSize: '0.6875rem', color: 'var(--muted)'}}>{pin.lat.toFixed(4)}, {pin.lon.toFixed(4)}</div>
|
||||||
</Table.Cell>
|
</Table.Cell>
|
||||||
<Table.Cell>
|
<Table.Cell>
|
||||||
|
<Group gap='xs' wrap='nowrap'>
|
||||||
|
{solarButton(pin)}
|
||||||
<APIButton
|
<APIButton
|
||||||
size='xs'
|
size='xs'
|
||||||
role='danger'
|
role='danger'
|
||||||
|
|
@ -619,6 +699,7 @@ function MapPins() {
|
||||||
confirmButton='Delete'
|
confirmButton='Delete'
|
||||||
onClick={() => handleDelete(pin.id)}
|
onClick={() => handleDelete(pin.id)}
|
||||||
/>
|
/>
|
||||||
|
</Group>
|
||||||
</Table.Cell>
|
</Table.Cell>
|
||||||
</Table.Row>;
|
</Table.Row>;
|
||||||
};
|
};
|
||||||
|
|
@ -627,8 +708,13 @@ function MapPins() {
|
||||||
<Table.Cell colSpan={5}>No pins. Right-click on the map to add one.</Table.Cell>
|
<Table.Cell colSpan={5}>No pins. Right-click on the map to add one.</Table.Cell>
|
||||||
</Table.Row>;
|
</Table.Row>;
|
||||||
|
|
||||||
|
if (pins === undefined) {
|
||||||
|
return <ErrorMessage>Could not fetch map pins</ErrorMessage>;
|
||||||
|
}
|
||||||
|
|
||||||
const lowerFilter = filter.toLowerCase();
|
const lowerFilter = filter.toLowerCase();
|
||||||
const filteredPins = lowerFilter
|
// Pending (null) passes through so SortableTable shows its placeholder.
|
||||||
|
const filteredPins = lowerFilter && pins
|
||||||
? pins.filter(p =>
|
? pins.filter(p =>
|
||||||
(p.label || '').toLowerCase().includes(lowerFilter) ||
|
(p.label || '').toLowerCase().includes(lowerFilter) ||
|
||||||
`${p.lat.toFixed(4)}, ${p.lon.toFixed(4)}`.includes(lowerFilter)
|
`${p.lat.toFixed(4)}, ${p.lon.toFixed(4)}`.includes(lowerFilter)
|
||||||
|
|
@ -665,6 +751,103 @@ function MapPins() {
|
||||||
emptyRow={emptyRow}
|
emptyRow={emptyRow}
|
||||||
/>
|
/>
|
||||||
</Media>
|
</Media>
|
||||||
|
<MapTargets filter={lowerFilter}/>
|
||||||
|
</>;
|
||||||
|
}
|
||||||
|
|
||||||
|
// The saved nuclear targets (map_nuclear.yaml), apart from the pins: what each is and where, and
|
||||||
|
// deleting one. `filter` (lower case) matches a name or coordinates.
|
||||||
|
export function MapTargets({filter = ''}) {
|
||||||
|
// null = pending, undefined = fetch failed, [] = no targets.
|
||||||
|
const [targets, setTargets] = useState(null);
|
||||||
|
const navigate = useNavigate();
|
||||||
|
const gen = useRef(0);
|
||||||
|
|
||||||
|
const fetchTargets = async () => {
|
||||||
|
const mine = ++gen.current;
|
||||||
|
const saved = await getMapTargets();
|
||||||
|
if (mine === gen.current) setTargets(saved);
|
||||||
|
};
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
fetchTargets();
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const handleDelete = async (targetId) => {
|
||||||
|
await deleteMapTarget(targetId);
|
||||||
|
await fetchTargets();
|
||||||
|
};
|
||||||
|
|
||||||
|
const weaponOf = (target) => {
|
||||||
|
const chosen = targetWeapon(target);
|
||||||
|
return `${chosen.weapon ? chosen.weapon.name : 'A yield of my own'}, `
|
||||||
|
+ formatYieldAndFission(chosen.yieldKt, chosen.fissionFraction);
|
||||||
|
};
|
||||||
|
const place = (target) => {
|
||||||
|
const to = `/map?lat=${target.lat}&lon=${target.lon}&z=10`;
|
||||||
|
return <a href={to} onClick={(e) => {
|
||||||
|
e.preventDefault();
|
||||||
|
navigate(to);
|
||||||
|
}}>{target.lat.toFixed(4)}, {target.lon.toFixed(4)}</a>;
|
||||||
|
};
|
||||||
|
const deleteButton = (target) => <APIButton
|
||||||
|
size='xs'
|
||||||
|
role='danger'
|
||||||
|
icon='trash'
|
||||||
|
aria-label={`Delete ${target.label}`}
|
||||||
|
confirmContent='Delete this target?'
|
||||||
|
confirmButton='Delete'
|
||||||
|
onClick={() => handleDelete(target.id)}
|
||||||
|
/>;
|
||||||
|
|
||||||
|
const fullHeaders = [
|
||||||
|
{key: 'label', text: 'Target', sortBy: i => i.label.toLowerCase()},
|
||||||
|
{key: 'weapon', text: 'Weapon', sortBy: i => targetWeapon(i).yieldKt},
|
||||||
|
{key: 'coords', text: 'Coordinates', sortBy: i => i.lat},
|
||||||
|
{key: 'created', text: 'Created', sortBy: i => i.created},
|
||||||
|
{key: 'actions', text: '', sortBy: null},
|
||||||
|
];
|
||||||
|
const fullRowFunc = (target) => <Table.Row key={target.id}>
|
||||||
|
<Table.Cell><span aria-hidden>☢ </span>{target.label}</Table.Cell>
|
||||||
|
<Table.Cell>{weaponOf(target)}</Table.Cell>
|
||||||
|
<Table.Cell>{place(target)}</Table.Cell>
|
||||||
|
<Table.Cell>{target.created}</Table.Cell>
|
||||||
|
<Table.Cell>{deleteButton(target)}</Table.Cell>
|
||||||
|
</Table.Row>;
|
||||||
|
|
||||||
|
const mobileHeaders = [
|
||||||
|
{key: 'label', text: 'Target', sortBy: i => i.label.toLowerCase()},
|
||||||
|
{key: 'actions', text: '', sortBy: null},
|
||||||
|
];
|
||||||
|
const mobileRowFunc = (target) => <Table.Row key={target.id}>
|
||||||
|
<Table.Cell>
|
||||||
|
<span aria-hidden>☢ </span>{target.label}
|
||||||
|
<div style={{fontSize: '0.6875rem', color: 'var(--muted)'}}>{weaponOf(target)}</div>
|
||||||
|
<div style={{fontSize: '0.6875rem'}}>{place(target)}</div>
|
||||||
|
</Table.Cell>
|
||||||
|
<Table.Cell>{deleteButton(target)}</Table.Cell>
|
||||||
|
</Table.Row>;
|
||||||
|
|
||||||
|
const emptyRow = <Table.Row>
|
||||||
|
<Table.Cell colSpan={5}>No targets. Turn on nuclear mode (☢) on the map to add and save some.</Table.Cell>
|
||||||
|
</Table.Row>;
|
||||||
|
|
||||||
|
const shown = filter && targets
|
||||||
|
? targets.filter(t => (t.label || '').toLowerCase().includes(filter) ||
|
||||||
|
`${t.lat.toFixed(4)}, ${t.lon.toFixed(4)}`.includes(filter))
|
||||||
|
: targets;
|
||||||
|
return <>
|
||||||
|
<Header as='h3'>Nuclear Targets</Header>
|
||||||
|
{targets === undefined ? <ErrorMessage>Could not fetch the nuclear targets</ErrorMessage> : <>
|
||||||
|
<Media at='mobile'>
|
||||||
|
<SortableTable tableHeaders={mobileHeaders} data={shown} rowFunc={mobileRowFunc} rowKey='id'
|
||||||
|
defaultSortColumn='label' emptyRow={emptyRow}/>
|
||||||
|
</Media>
|
||||||
|
<Media greaterThanOrEqual='tablet'>
|
||||||
|
<SortableTable tableHeaders={fullHeaders} data={shown} rowFunc={fullRowFunc} rowKey='id'
|
||||||
|
defaultSortColumn='label' emptyRow={emptyRow}/>
|
||||||
|
</Media>
|
||||||
|
</>}
|
||||||
</>;
|
</>;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -678,6 +861,8 @@ export function MapRoute() {
|
||||||
const links = [
|
const links = [
|
||||||
{text: 'Map', to: '/map', key: 'map', end: true},
|
{text: 'Map', to: '/map', key: 'map', end: true},
|
||||||
{text: 'Pins', to: '/map/pins', key: 'pins'},
|
{text: 'Pins', to: '/map/pins', key: 'pins'},
|
||||||
|
// Manage (and Statistics, on pages which have one) are the last tabs.
|
||||||
|
{text: 'ATAK', to: '/map/atak', key: 'atak'},
|
||||||
{text: 'Manage', to: '/map/manage', key: 'manage'},
|
{text: 'Manage', to: '/map/manage', key: 'manage'},
|
||||||
];
|
];
|
||||||
|
|
||||||
|
|
@ -688,6 +873,7 @@ export function MapRoute() {
|
||||||
<Routes>
|
<Routes>
|
||||||
<Route path='/' exact element={<MapPage/>}/>
|
<Route path='/' exact element={<MapPage/>}/>
|
||||||
<Route path='pins' exact element={<MapPins/>}/>
|
<Route path='pins' exact element={<MapPins/>}/>
|
||||||
|
<Route path='atak' exact element={<MapAtak/>}/>
|
||||||
<Route path='manage' exact element={<ManageMap/>}/>
|
<Route path='manage' exact element={<ManageMap/>}/>
|
||||||
</Routes>
|
</Routes>
|
||||||
</div>
|
</div>
|
||||||
|
|
|
||||||
229
app/src/components/MapAtak.js
Normal file
229
app/src/components/MapAtak.js
Normal file
|
|
@ -0,0 +1,229 @@
|
||||||
|
// The map's ATAK tab: how to use this WROLPi's map in ATAK (Android) and iTAK (iPhone), and what the
|
||||||
|
// tile service (tiles/, wrolpi-tiles) is doing.
|
||||||
|
import React, {useCallback, useEffect, useRef, useState} from "react";
|
||||||
|
import {APIButton, ErrorMessage, humanFileSize, InfoMessage} from "./Common";
|
||||||
|
import {Group, Header, Panel, Table} from "./ui";
|
||||||
|
import {QRCodeButton} from "./QRCode";
|
||||||
|
|
||||||
|
// How often the status is asked for while the tab is open.
|
||||||
|
const STATUS_INTERVAL_MS = 5000;
|
||||||
|
|
||||||
|
// The map source over plain HTTP: no certificate is needed, so it works on any phone.
|
||||||
|
export function httpMapSourceUrl(hostname = window.location.hostname) {
|
||||||
|
return `http://${hostname}:8088/tiles/wrolpi.xml`;
|
||||||
|
}
|
||||||
|
|
||||||
|
// The map source over HTTPS: the phone must trust this WROLPi's certificate authority.
|
||||||
|
export function httpsMapSourceUrl(origin = window.location.origin) {
|
||||||
|
return `${origin}/tiles/wrolpi.xml`;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Whether this page was opened on the WROLPi itself (or through Docker's localhost): then the map
|
||||||
|
// source addresses name this computer, and a phone can not open them.
|
||||||
|
export function isLoopback(hostname = window.location.hostname) {
|
||||||
|
return hostname === 'localhost' || hostname === '127.0.0.1' || hostname === '[::1]' || hostname === '::1';
|
||||||
|
}
|
||||||
|
|
||||||
|
// Remove the tiles the tile service keeps; they are drawn again when a phone next asks for them.
|
||||||
|
export async function clearTileCache() {
|
||||||
|
const response = await fetch('/tiles/cache/clear', {method: 'POST'});
|
||||||
|
if (!response.ok) {
|
||||||
|
throw new Error(`Could not clear the kept tiles: ${response.status}`);
|
||||||
|
}
|
||||||
|
return await response.json();
|
||||||
|
}
|
||||||
|
|
||||||
|
// The status of the tile service, and a function which asks for it now. The status is null while
|
||||||
|
// the first request is pending, undefined when the service did not answer.
|
||||||
|
//
|
||||||
|
// Only the newest request may write the status: a slow answer which settles after a newer poll (or
|
||||||
|
// after the refresh which follows clearing the kept tiles) would put an older status back.
|
||||||
|
export function useTileStatus(interval = STATUS_INTERVAL_MS) {
|
||||||
|
const [status, setStatus] = useState(null);
|
||||||
|
// Each request's number; a request writes only while it is the newest. Unmounting makes every
|
||||||
|
// request in flight old.
|
||||||
|
const generation = useRef(0);
|
||||||
|
|
||||||
|
const fetchStatus = useCallback(async () => {
|
||||||
|
const mine = ++generation.current;
|
||||||
|
let data;
|
||||||
|
try {
|
||||||
|
const response = await fetch('/tiles/status');
|
||||||
|
data = response.ok ? await response.json() : undefined;
|
||||||
|
} catch (e) {
|
||||||
|
data = undefined;
|
||||||
|
}
|
||||||
|
if (mine === generation.current) setStatus(data);
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
// The counter itself (not a DOM node): on unmount every request in flight becomes old.
|
||||||
|
const requests = generation;
|
||||||
|
fetchStatus();
|
||||||
|
const timer = setInterval(fetchStatus, interval);
|
||||||
|
return () => {
|
||||||
|
requests.current++;
|
||||||
|
clearInterval(timer);
|
||||||
|
};
|
||||||
|
}, [interval, fetchStatus]);
|
||||||
|
|
||||||
|
return [status, fetchStatus];
|
||||||
|
}
|
||||||
|
|
||||||
|
function MapSourceRow({label, name, url, note}) {
|
||||||
|
return <Table.Row>
|
||||||
|
<Table.Cell>
|
||||||
|
<b>{label}</b>
|
||||||
|
<div style={{fontSize: '0.8125rem', color: 'var(--muted)'}}>{note} Called <b>{name}</b> in the app.</div>
|
||||||
|
</Table.Cell>
|
||||||
|
<Table.Cell style={{wordBreak: 'break-all'}}><a href={url}>{url}</a></Table.Cell>
|
||||||
|
<Table.Cell>
|
||||||
|
<Group gap='xs' wrap='nowrap'>
|
||||||
|
<APIButton icon='copy' aria-label={`Copy ${label} map source address`}
|
||||||
|
onClick={() => navigator.clipboard.writeText(url)}/>
|
||||||
|
<QRCodeButton value={url} color='violet' label={`Show ${label} map source QR code`}
|
||||||
|
header={`Scan with the phone to download the ${label} map source`}>
|
||||||
|
<p style={{wordBreak: 'break-all'}}>{url}</p>
|
||||||
|
</QRCodeButton>
|
||||||
|
</Group>
|
||||||
|
</Table.Cell>
|
||||||
|
</Table.Row>;
|
||||||
|
}
|
||||||
|
|
||||||
|
function HowTo() {
|
||||||
|
return <Panel>
|
||||||
|
<Header as='h3'>Use this map in ATAK or iTAK</Header>
|
||||||
|
<p>
|
||||||
|
ATAK (Android) and iTAK (iPhone) can draw this WROLPi's map while the phone is on this
|
||||||
|
WROLPi's network, and download an area of it to use when it is not.
|
||||||
|
</p>
|
||||||
|
{isLoopback() && <InfoMessage>
|
||||||
|
This page was opened on this computer ({window.location.hostname}), so these addresses only
|
||||||
|
work here. On the phone, open this page (or these addresses) with this WROLPi's address on
|
||||||
|
your network or its hotspot instead.
|
||||||
|
</InfoMessage>}
|
||||||
|
<Table>
|
||||||
|
<Table.Body>
|
||||||
|
<MapSourceRow label='HTTP' name='WROLPi Map' url={httpMapSourceUrl()}
|
||||||
|
note='Works on any phone, nothing to install.'/>
|
||||||
|
<MapSourceRow label='HTTPS' name='WROLPi Map (HTTPS)' url={httpsMapSourceUrl()}
|
||||||
|
note="Only once the phone trusts this WROLPi's certificate."/>
|
||||||
|
</Table.Body>
|
||||||
|
</Table>
|
||||||
|
<ol>
|
||||||
|
<li>On the phone, open a map source address above in its browser (or scan its QR code);
|
||||||
|
it downloads a small file.
|
||||||
|
</li>
|
||||||
|
<li>Open that file with ATAK or iTAK (or import it with the app's import tool).</li>
|
||||||
|
<li>Choose <b>WROLPi Map</b> (or <b>WROLPi Map (HTTPS)</b>) in the app's list of maps.</li>
|
||||||
|
<li>To use the map away from this WROLPi, download an area of it with the app's map
|
||||||
|
download tool while still connected.
|
||||||
|
</li>
|
||||||
|
</ol>
|
||||||
|
<p>
|
||||||
|
For HTTPS, the phone must first install and trust{' '}
|
||||||
|
<a href='/ca.crt'>this WROLPi's certificate</a>. On an iPhone, after installing it, turn
|
||||||
|
it on in Settings, General, About, Certificate Trust Settings.
|
||||||
|
</p>
|
||||||
|
<p style={{color: 'var(--muted)'}}>
|
||||||
|
The map is of the map files on the Manage tab. Map data © OpenStreetMap contributors.
|
||||||
|
</p>
|
||||||
|
</Panel>;
|
||||||
|
}
|
||||||
|
|
||||||
|
function secondsAgo(timestamp) {
|
||||||
|
const seconds = Math.max(0, Math.round(Date.now() / 1000 - timestamp));
|
||||||
|
if (seconds < 60) return `${seconds}s ago`;
|
||||||
|
if (seconds < 3600) return `${Math.round(seconds / 60)}m ago`;
|
||||||
|
return `${Math.round(seconds / 3600)}h ago`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function TileServiceStatus({status, refresh}) {
|
||||||
|
if (status === null) {
|
||||||
|
return <Panel><Header as='h3'>Tile service</Header><p>Loading...</p></Panel>;
|
||||||
|
}
|
||||||
|
if (status === undefined) {
|
||||||
|
return <Panel>
|
||||||
|
<Header as='h3'>Tile service</Header>
|
||||||
|
<ErrorMessage>The tile service is not running. Start <b>wrolpi-tiles</b> on the
|
||||||
|
Controller page.</ErrorMessage>
|
||||||
|
</Panel>;
|
||||||
|
}
|
||||||
|
|
||||||
|
const basemaps = status.maps.length;
|
||||||
|
const cache = status.cache;
|
||||||
|
return <Panel>
|
||||||
|
<Header as='h3'>Tile service</Header>
|
||||||
|
{!status.renderer && <ErrorMessage>The tile service cannot draw tiles: its renderer (mapli) is not
|
||||||
|
installed.</ErrorMessage>}
|
||||||
|
{basemaps === 0 && <InfoMessage>There are no map files; download some on the Manage tab.</InfoMessage>}
|
||||||
|
<Table>
|
||||||
|
<Table.Body>
|
||||||
|
<Table.Row>
|
||||||
|
<Table.Cell>Map files</Table.Cell>
|
||||||
|
<Table.Cell>{basemaps}</Table.Cell>
|
||||||
|
</Table.Row>
|
||||||
|
<Table.Row>
|
||||||
|
<Table.Cell>Tiles sent</Table.Cell>
|
||||||
|
<Table.Cell>{status.tiles_per_second} per second (last minute)</Table.Cell>
|
||||||
|
</Table.Row>
|
||||||
|
<Table.Row>
|
||||||
|
<Table.Cell>Waiting to be drawn</Table.Cell>
|
||||||
|
<Table.Cell>{status.queued_blocks + status.drawing_blocks} blocks of 16 tiles</Table.Cell>
|
||||||
|
</Table.Row>
|
||||||
|
<Table.Row>
|
||||||
|
<Table.Cell>Kept tiles</Table.Cell>
|
||||||
|
<Table.Cell>
|
||||||
|
{cache.enabled
|
||||||
|
? <Group gap='sm'>
|
||||||
|
<span>{humanFileSize(cache.bytes)} of {humanFileSize(cache.max_bytes)}</span>
|
||||||
|
<APIButton
|
||||||
|
size='xs'
|
||||||
|
role='danger'
|
||||||
|
icon='trash'
|
||||||
|
disabled={!cache.bytes}
|
||||||
|
confirmHeader='Clear kept tiles?'
|
||||||
|
confirmContent={'The tiles this WROLPi keeps are removed, and drawn again when a ' +
|
||||||
|
'phone next asks for them. Maps already downloaded to phones are not ' +
|
||||||
|
'changed: a phone keeps its own copy.'}
|
||||||
|
confirmButton='Clear'
|
||||||
|
onClick={async () => {
|
||||||
|
await clearTileCache();
|
||||||
|
await refresh();
|
||||||
|
}}
|
||||||
|
>Clear</APIButton>
|
||||||
|
</Group>
|
||||||
|
: 'Not kept'}
|
||||||
|
</Table.Cell>
|
||||||
|
</Table.Row>
|
||||||
|
</Table.Body>
|
||||||
|
</Table>
|
||||||
|
<Header as='h4'>Phones (last day)</Header>
|
||||||
|
{status.clients.length === 0
|
||||||
|
? <p>No phone has asked for tiles.</p>
|
||||||
|
: <Table>
|
||||||
|
<Table.Header>
|
||||||
|
<Table.Row>
|
||||||
|
<Table.HeaderCell>Address</Table.HeaderCell>
|
||||||
|
<Table.HeaderCell>Tiles</Table.HeaderCell>
|
||||||
|
<Table.HeaderCell>Last tile</Table.HeaderCell>
|
||||||
|
</Table.Row>
|
||||||
|
</Table.Header>
|
||||||
|
<Table.Body>
|
||||||
|
{status.clients.map(client => <Table.Row key={client.client}>
|
||||||
|
<Table.Cell>{client.client}</Table.Cell>
|
||||||
|
<Table.Cell>{client.tiles}</Table.Cell>
|
||||||
|
<Table.Cell>{secondsAgo(client.last_seen)}</Table.Cell>
|
||||||
|
</Table.Row>)}
|
||||||
|
</Table.Body>
|
||||||
|
</Table>}
|
||||||
|
</Panel>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function MapAtak() {
|
||||||
|
const [status, refresh] = useTileStatus();
|
||||||
|
return <>
|
||||||
|
<HowTo/>
|
||||||
|
<TileServiceStatus status={status} refresh={refresh}/>
|
||||||
|
</>;
|
||||||
|
}
|
||||||
188
app/src/components/MapAtak.test.js
Normal file
188
app/src/components/MapAtak.test.js
Normal file
|
|
@ -0,0 +1,188 @@
|
||||||
|
import React from 'react';
|
||||||
|
import {act, fireEvent, renderHook, screen, waitFor, within} from '@testing-library/react';
|
||||||
|
import {mockFetch, renderWithProviders} from '../test-utils';
|
||||||
|
import {humanFileSize} from './Common';
|
||||||
|
import {clearTileCache, httpMapSourceUrl, httpsMapSourceUrl, isLoopback, MapAtak, useTileStatus} from './MapAtak';
|
||||||
|
|
||||||
|
const STATUS = {
|
||||||
|
renderer: true,
|
||||||
|
processes: 2,
|
||||||
|
max_zoom: 17,
|
||||||
|
maps: ['/opt/wrolpi-blobs/map-overview.pmtiles', '/media/wrolpi/map/mexico.pmtiles'],
|
||||||
|
style_id: 'abc',
|
||||||
|
queued_blocks: 3,
|
||||||
|
drawing_blocks: 2,
|
||||||
|
tiles_per_second: 31.5,
|
||||||
|
block_ms: 310,
|
||||||
|
cache: {enabled: true, bytes: 25 * 1024 * 1024, max_bytes: 1024 * 1024 * 1024},
|
||||||
|
stats: {},
|
||||||
|
clients: [{client: '192.0.2.34', tiles: 578, first_seen: 0, last_seen: Date.now() / 1000 - 30, queued_blocks: 0}],
|
||||||
|
};
|
||||||
|
|
||||||
|
describe('MapAtak', () => {
|
||||||
|
const realFetch = global.fetch;
|
||||||
|
afterEach(() => {
|
||||||
|
global.fetch = realFetch;
|
||||||
|
});
|
||||||
|
|
||||||
|
it('builds the map source addresses from how the browser reached this WROLPi', () => {
|
||||||
|
expect(httpMapSourceUrl('192.0.2.8')).toBe('http://192.0.2.8:8088/tiles/wrolpi.xml');
|
||||||
|
expect(httpsMapSourceUrl('https://wrolpi.local')).toBe('https://wrolpi.local/tiles/wrolpi.xml');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('shows the map sources and what the tile service is doing', async () => {
|
||||||
|
global.fetch = mockFetch(STATUS);
|
||||||
|
renderWithProviders(<MapAtak/>);
|
||||||
|
|
||||||
|
expect(screen.getByText(httpMapSourceUrl())).toHaveAttribute('href', httpMapSourceUrl());
|
||||||
|
expect(screen.getByText(httpsMapSourceUrl())).toHaveAttribute('href', httpsMapSourceUrl());
|
||||||
|
expect(screen.getByText("this WROLPi's certificate")).toHaveAttribute('href', '/ca.crt');
|
||||||
|
// Both apps take an area offline (tested with iTAK on an iPhone).
|
||||||
|
expect(screen.getByText(/download an area of it with the app's map download tool/)).toBeInTheDocument();
|
||||||
|
|
||||||
|
expect(await screen.findByText('31.5 per second (last minute)')).toBeInTheDocument();
|
||||||
|
expect(global.fetch).toHaveBeenCalledWith('/tiles/status');
|
||||||
|
expect(screen.getByText('5 blocks of 16 tiles')).toBeInTheDocument();
|
||||||
|
expect(screen.getByText(`${humanFileSize(25 * 1024 * 1024)} of ${humanFileSize(1024 * 1024 * 1024)}`))
|
||||||
|
.toBeInTheDocument();
|
||||||
|
expect(screen.getByText('192.0.2.34')).toBeInTheDocument();
|
||||||
|
expect(screen.getByText('578')).toBeInTheDocument();
|
||||||
|
expect(screen.getByText('30s ago')).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('shows a QR code of each map source address for the phone to scan', async () => {
|
||||||
|
global.fetch = mockFetch(STATUS);
|
||||||
|
renderWithProviders(<MapAtak/>);
|
||||||
|
await screen.findByText('31.5 per second (last minute)');
|
||||||
|
|
||||||
|
for (const [label, url] of [['HTTP', httpMapSourceUrl()], ['HTTPS', httpsMapSourceUrl()]]) {
|
||||||
|
fireEvent.click(screen.getByRole('button', {name: `Show ${label} map source QR code`}));
|
||||||
|
const dialog = await screen.findByRole('dialog');
|
||||||
|
// react-qr-code renders an svg titled with its value.
|
||||||
|
expect(within(dialog).getByTitle(url)).toBeInTheDocument();
|
||||||
|
expect(within(dialog).getByText(`Scan with the phone to download the ${label} map source`))
|
||||||
|
.toBeInTheDocument();
|
||||||
|
fireEvent.keyDown(dialog, {key: 'Escape'});
|
||||||
|
await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument());
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
it('says when the tile service is not running', async () => {
|
||||||
|
global.fetch = jest.fn(() => Promise.reject(new Error('connection refused')));
|
||||||
|
renderWithProviders(<MapAtak/>);
|
||||||
|
expect(await screen.findByText(/The tile service is not running/)).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('says when there are no map files', async () => {
|
||||||
|
global.fetch = mockFetch({...STATUS, maps: [], clients: []});
|
||||||
|
renderWithProviders(<MapAtak/>);
|
||||||
|
expect(await screen.findByText(/There are no map files/)).toBeInTheDocument();
|
||||||
|
expect(screen.getByText('No phone has asked for tiles.')).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('clears the kept tiles after asking, then shows the new size', async () => {
|
||||||
|
let bytes = 25 * 1024 * 1024;
|
||||||
|
global.fetch = jest.fn(async (url, options) => {
|
||||||
|
if (url === '/tiles/cache/clear') {
|
||||||
|
expect(options).toEqual({method: 'POST'});
|
||||||
|
const freed = bytes;
|
||||||
|
bytes = 0;
|
||||||
|
return {ok: true, status: 200, json: async () => ({freed_bytes: freed})};
|
||||||
|
}
|
||||||
|
return {ok: true, status: 200, json: async () => ({...STATUS, cache: {...STATUS.cache, bytes}})};
|
||||||
|
});
|
||||||
|
renderWithProviders(<MapAtak/>);
|
||||||
|
await screen.findByText('31.5 per second (last minute)');
|
||||||
|
|
||||||
|
fireEvent.click(screen.getByRole('button', {name: /Clear/}));
|
||||||
|
// Nothing is removed until it is confirmed.
|
||||||
|
expect(await screen.findByText(/a phone keeps its own copy/)).toBeInTheDocument();
|
||||||
|
expect(global.fetch).not.toHaveBeenCalledWith('/tiles/cache/clear', expect.anything());
|
||||||
|
|
||||||
|
const dialog = screen.getByRole('dialog');
|
||||||
|
fireEvent.click(within(dialog).getByRole('button', {name: 'Clear'}));
|
||||||
|
await waitFor(() => expect(global.fetch).toHaveBeenCalledWith('/tiles/cache/clear', {method: 'POST'}));
|
||||||
|
expect(await screen.findByText(`${humanFileSize(0)} of ${humanFileSize(1024 * 1024 * 1024)}`))
|
||||||
|
.toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('cannot clear when no tiles are kept', async () => {
|
||||||
|
global.fetch = mockFetch({...STATUS, cache: {...STATUS.cache, bytes: 0}});
|
||||||
|
renderWithProviders(<MapAtak/>);
|
||||||
|
await screen.findByText('31.5 per second (last minute)');
|
||||||
|
expect(screen.getByRole('button', {name: /Clear/})).toBeDisabled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('clearTileCache fails loudly when the service refuses', async () => {
|
||||||
|
global.fetch = jest.fn(async () => ({ok: false, status: 502, json: async () => ({})}));
|
||||||
|
await expect(clearTileCache()).rejects.toThrow('502');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('names each map source as the app will list it', async () => {
|
||||||
|
global.fetch = mockFetch(STATUS);
|
||||||
|
renderWithProviders(<MapAtak/>);
|
||||||
|
await screen.findByText('31.5 per second (last minute)');
|
||||||
|
// The tile service names the HTTPS source differently (tiles/service.py).
|
||||||
|
expect(screen.getAllByText('WROLPi Map').length).toBeGreaterThanOrEqual(1);
|
||||||
|
expect(screen.getAllByText('WROLPi Map (HTTPS)').length).toBeGreaterThanOrEqual(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('says when the addresses only work on this computer', async () => {
|
||||||
|
expect(isLoopback('localhost')).toBe(true);
|
||||||
|
expect(isLoopback('127.0.0.1')).toBe(true);
|
||||||
|
expect(isLoopback('[::1]')).toBe(true);
|
||||||
|
expect(isLoopback('wrolpi.local')).toBe(false);
|
||||||
|
expect(isLoopback('192.0.2.8')).toBe(false);
|
||||||
|
|
||||||
|
// jsdom's page is on localhost.
|
||||||
|
global.fetch = mockFetch(STATUS);
|
||||||
|
renderWithProviders(<MapAtak/>);
|
||||||
|
expect(screen.getByText(/these addresses only\s+work here/)).toBeInTheDocument();
|
||||||
|
await screen.findByText('31.5 per second (last minute)');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('does not put an older status back over a newer one', async () => {
|
||||||
|
// The first request is slow and its answer old. A newer one (as Clear's refresh makes) is
|
||||||
|
// answered first. The old answer settles last, and must not undo the newer.
|
||||||
|
let answerFirst;
|
||||||
|
let calls = 0;
|
||||||
|
global.fetch = jest.fn(() => {
|
||||||
|
calls++;
|
||||||
|
if (calls === 1) {
|
||||||
|
return new Promise(resolve => {
|
||||||
|
answerFirst = () => resolve({ok: true, status: 200, json: async () => STATUS});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return Promise.resolve({ok: true, status: 200,
|
||||||
|
json: async () => ({...STATUS, cache: {...STATUS.cache, bytes: 0}})});
|
||||||
|
});
|
||||||
|
const {result} = renderHook(() => useTileStatus(60000));
|
||||||
|
await waitFor(() => expect(calls).toBe(1));
|
||||||
|
|
||||||
|
await act(async () => {
|
||||||
|
await result.current[1](); // the newer request
|
||||||
|
});
|
||||||
|
expect(result.current[0].cache.bytes).toBe(0);
|
||||||
|
|
||||||
|
await act(async () => {
|
||||||
|
answerFirst(); // the older one settles last
|
||||||
|
});
|
||||||
|
expect(result.current[0].cache.bytes).toBe(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('polls the status while open', async () => {
|
||||||
|
jest.useFakeTimers();
|
||||||
|
try {
|
||||||
|
global.fetch = mockFetch(STATUS);
|
||||||
|
const {unmount} = renderWithProviders(<MapAtak/>);
|
||||||
|
await waitFor(() => expect(global.fetch).toHaveBeenCalledTimes(1));
|
||||||
|
jest.advanceTimersByTime(5000);
|
||||||
|
await waitFor(() => expect(global.fetch).toHaveBeenCalledTimes(2));
|
||||||
|
unmount();
|
||||||
|
jest.advanceTimersByTime(20000);
|
||||||
|
expect(global.fetch).toHaveBeenCalledTimes(2);
|
||||||
|
} finally {
|
||||||
|
jest.useRealTimers();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
63
app/src/components/MapPoiPopup.test.js
Normal file
63
app/src/components/MapPoiPopup.test.js
Normal file
|
|
@ -0,0 +1,63 @@
|
||||||
|
import {poiPopupHtml} from './mapPoiPopup';
|
||||||
|
|
||||||
|
// Clicking a POI on the map opens a popup built from attributes already in the pmtiles
|
||||||
|
// file: the name, its category (kind), sub-category (kind_detail), and elevation.
|
||||||
|
|
||||||
|
const feature = (properties) => ({properties});
|
||||||
|
|
||||||
|
test('name, kind, detail and elevation are all shown, humanized', () => {
|
||||||
|
const html = poiPopupHtml([feature({
|
||||||
|
name: 'Flattop Mountain', kind: 'peak', kind_detail: 'volcano', elevation: 1070,
|
||||||
|
})]);
|
||||||
|
expect(html).toContain('Flattop Mountain');
|
||||||
|
expect(html).toContain('Peak');
|
||||||
|
expect(html).toContain('Volcano');
|
||||||
|
expect(html).toContain('1070 m');
|
||||||
|
expect(html).toContain('3510 ft');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('missing attributes are left out rather than shown as undefined', () => {
|
||||||
|
const html = poiPopupHtml([feature({name: 'Franz', kind: 'bakery'})]);
|
||||||
|
expect(html).toContain('Franz');
|
||||||
|
expect(html).toContain('Bakery');
|
||||||
|
expect(html).not.toContain('undefined');
|
||||||
|
expect(html).not.toContain('Elevation');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('kind_detail of "none" is not shown', () => {
|
||||||
|
const html = poiPopupHtml([feature({name: 'West High', kind: 'school', kind_detail: 'none'})]);
|
||||||
|
expect(html).not.toContain('none');
|
||||||
|
expect(html).not.toContain('None');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('the same feature at several min_zoom levels appears once', () => {
|
||||||
|
const html = poiPopupHtml([
|
||||||
|
feature({name: 'Westchester Lagoon', kind: 'water', min_zoom: 12}),
|
||||||
|
feature({name: 'Westchester Lagoon', kind: 'water', min_zoom: 14}),
|
||||||
|
]);
|
||||||
|
expect(html.match(/Westchester Lagoon/g)).toHaveLength(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('feature properties are HTML escaped', () => {
|
||||||
|
const html = poiPopupHtml([feature({name: '<img src=x onerror=alert(1)>', kind: 'a&b'})]);
|
||||||
|
expect(html).not.toContain('<img');
|
||||||
|
expect(html).toContain('<img');
|
||||||
|
expect(html).toContain('A&b');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a point feature shows its own coordinates, lat then lon', () => {
|
||||||
|
const html = poiPopupHtml([{
|
||||||
|
properties: {name: 'Peak Two', kind: 'peak'},
|
||||||
|
geometry: {type: 'Point', coordinates: [-149.67301, 61.08571]},
|
||||||
|
}], {lng: -149.5, lat: 61.0});
|
||||||
|
expect(html).toContain('61.08571, -149.67301');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a feature without a point falls back to the clicked location', () => {
|
||||||
|
const html = poiPopupHtml([feature({name: 'Lagoon', kind: 'water'})], {lng: -149.5, lat: 61.0});
|
||||||
|
expect(html).toContain('61.00000, -149.50000');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('no features gives no popup', () => {
|
||||||
|
expect(poiPopupHtml([])).toBeNull();
|
||||||
|
});
|
||||||
|
|
@ -102,6 +102,7 @@ const CATALOG = [
|
||||||
|
|
||||||
jest.mock('../api', () => ({
|
jest.mock('../api', () => ({
|
||||||
...jest.requireActual('../api'),
|
...jest.requireActual('../api'),
|
||||||
|
getWeather: async () => ({enabled: false, download: null, targets: 0, field: null}),
|
||||||
getMapFiles: jest.fn(),
|
getMapFiles: jest.fn(),
|
||||||
fetchMapSubscriptions: jest.fn(),
|
fetchMapSubscriptions: jest.fn(),
|
||||||
getMapPins: jest.fn(),
|
getMapPins: jest.fn(),
|
||||||
|
|
@ -213,16 +214,47 @@ describe('a single region preview', () => {
|
||||||
|
|
||||||
describe('the basemap source', () => {
|
describe('the basemap source', () => {
|
||||||
it("uses the user's planet file when they have one", async () => {
|
it("uses the user's planet file when they have one", async () => {
|
||||||
await renderManage({files: [{name: '20260329.pmtiles', size: 134e9}]});
|
await renderManage({
|
||||||
|
files: [
|
||||||
|
{
|
||||||
|
name: '20260329.pmtiles', path: 'map/planet/20260329.pmtiles',
|
||||||
|
map_path: 'planet/20260329.pmtiles', kind: 'basemap', visible: true, size: 134e9,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
});
|
||||||
await userEvent.click(screen.getByRole('button', {name: 'View All Regions'}));
|
await userEvent.click(screen.getByRole('button', {name: 'View All Regions'}));
|
||||||
await waitFor(() => expect(constructed).toHaveLength(1));
|
await waitFor(() => expect(constructed).toHaveLength(1));
|
||||||
|
|
||||||
const {sources} = constructed[0].options.style;
|
const {sources} = constructed[0].options.style;
|
||||||
expect(sources.basemap.url).toBe('pmtiles:///media/map/20260329.pmtiles');
|
// The file is used where it is, here in a sub-directory of the map directory.
|
||||||
|
expect(sources.basemap.url).toBe('pmtiles:///media/map/planet/20260329.pmtiles');
|
||||||
});
|
});
|
||||||
|
|
||||||
it('falls back to the overview blob when there is no planet file', async () => {
|
it('falls back to the overview blob when there is no planet file', async () => {
|
||||||
await renderManage({files: [{name: 'us-west-20260329.pmtiles', size: 5e9}]});
|
await renderManage({
|
||||||
|
files: [
|
||||||
|
{
|
||||||
|
name: 'us-west-20260329.pmtiles', path: 'map/us-west-20260329.pmtiles',
|
||||||
|
map_path: 'us-west-20260329.pmtiles', kind: 'basemap', visible: true, size: 5e9,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
});
|
||||||
|
await userEvent.click(screen.getByRole('button', {name: 'View All Regions'}));
|
||||||
|
await waitFor(() => expect(constructed).toHaveLength(1));
|
||||||
|
|
||||||
|
const {sources} = constructed[0].options.style;
|
||||||
|
expect(sources.basemap.url).toBe('pmtiles:///blobs/map-overview.pmtiles');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('falls back to the overview blob when the planet file is ignored', async () => {
|
||||||
|
await renderManage({
|
||||||
|
files: [
|
||||||
|
{
|
||||||
|
name: '20260329.pmtiles', path: 'map/20260329.pmtiles',
|
||||||
|
map_path: '20260329.pmtiles', kind: 'basemap', visible: false, size: 134e9,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
});
|
||||||
await userEvent.click(screen.getByRole('button', {name: 'View All Regions'}));
|
await userEvent.click(screen.getByRole('button', {name: 'View All Regions'}));
|
||||||
await waitFor(() => expect(constructed).toHaveLength(1));
|
await waitFor(() => expect(constructed).toHaveLength(1));
|
||||||
|
|
||||||
|
|
|
||||||
263
app/src/components/MapQuadPicker.js
Normal file
263
app/src/components/MapQuadPicker.js
Normal file
|
|
@ -0,0 +1,263 @@
|
||||||
|
import React, {useEffect, useRef, useState} from "react";
|
||||||
|
import {Button, Checkbox, Group, Radio} from "./ui";
|
||||||
|
import {EXPORT_DPI, EXPORT_DPIS} from "./mapExport";
|
||||||
|
import {EXPORT_LOOKS, PRINT_LOOK} from "./mapPrintStyle";
|
||||||
|
import {
|
||||||
|
EMPTY_FEATURES,
|
||||||
|
QUAD_MIN_ZOOM,
|
||||||
|
quadAt,
|
||||||
|
quadGridLines,
|
||||||
|
quadLabel,
|
||||||
|
quadPolygon,
|
||||||
|
quadSize,
|
||||||
|
quadTitle,
|
||||||
|
} from "./mapQuads";
|
||||||
|
|
||||||
|
// What the ids of the picker's layers and sources start with: they are of the app, not of the map.
|
||||||
|
export const QUAD_LAYER_PREFIX = "quad-";
|
||||||
|
const GRID_SOURCE = "quad-grid";
|
||||||
|
const SELECTED_SOURCE = "quad-selected";
|
||||||
|
// The picker's own layers, in the order they are drawn (all above the map's).
|
||||||
|
const QUAD_LAYERS = [
|
||||||
|
{
|
||||||
|
id: "quad-grid-lines", type: "line", source: GRID_SOURCE,
|
||||||
|
paint: {"line-color": "#e8590c", "line-width": 1.5, "line-opacity": 0.8},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: "quad-selected-fill", type: "fill", source: SELECTED_SOURCE,
|
||||||
|
paint: {"fill-color": "#e8590c", "fill-opacity": 0.2},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: "quad-selected-outline", type: "line", source: SELECTED_SOURCE,
|
||||||
|
paint: {"line-color": "#e8590c", "line-width": 3.5},
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
export function formatDistance(meters, scaleUnit) {
|
||||||
|
return scaleUnit === "imperial"
|
||||||
|
? `${(meters / 1609.344).toFixed(1)} mi`
|
||||||
|
: `${(meters / 1000).toFixed(1)} km`;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function formatSheet(millimeters, scaleUnit) {
|
||||||
|
return scaleUnit === "imperial"
|
||||||
|
? `${(millimeters / 25.4).toFixed(1)} in`
|
||||||
|
: `${(millimeters / 10).toFixed(1)} cm`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function selectedFeatures(quad) {
|
||||||
|
return quad ? {type: "FeatureCollection", features: [quadPolygon(quad)]} : EMPTY_FEATURES;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Draws the grid of 1:24,000 quadrangles over the map while the user chooses one to export.
|
||||||
|
//
|
||||||
|
// The grid and the chosen quadrangle are layers of the map, which a change of its style removes; they
|
||||||
|
// are put back whenever the style has loaded.
|
||||||
|
//
|
||||||
|
// onExport(quad, {sheet, dpi, name}): make the PDF; `sheet` is whether the map is to be on a sheet,
|
||||||
|
// with a margin, a grid and scale bars, `dpi` is how sharp it is to be, and `name` is what the USGS
|
||||||
|
// calls the quadrangle ({name, state, exact}), or null.
|
||||||
|
//
|
||||||
|
// fetchName(quad): asks for that name; it resolves to null where there is none.
|
||||||
|
//
|
||||||
|
// look, onLook(look): the look the map is exported in (see mapPrintStyle.js), and what is told when
|
||||||
|
// another is chosen. The map is shown in it, so what is seen is what is exported.
|
||||||
|
//
|
||||||
|
// While the PDF is being made `status` says how far along it is, and nothing else can be chosen;
|
||||||
|
// Cancel then stops it (onCancel()) and does not close the picker. `error` says why the last one
|
||||||
|
// could not be made.
|
||||||
|
export default function MapQuadPicker({
|
||||||
|
map, scaleUnit, initialQuad = null, onExport, onCancel, onClose, fetchName, status = null, error = null,
|
||||||
|
look = null, onLook = null,
|
||||||
|
}) {
|
||||||
|
const busy = status !== null;
|
||||||
|
const busyRef = useRef(busy);
|
||||||
|
busyRef.current = busy;
|
||||||
|
const [selected, setSelected] = useState(initialQuad);
|
||||||
|
const selectedRef = useRef(initialQuad);
|
||||||
|
// Whether the map is zoomed in far enough for the grid to be drawn.
|
||||||
|
const [gridShown, setGridShown] = useState(true);
|
||||||
|
const [sheet, setSheet] = useState(true);
|
||||||
|
const [dpi, setDpi] = useState(EXPORT_DPI);
|
||||||
|
// What the chosen quadrangle is called: {id, name} once it is known, for the quadrangle it is of.
|
||||||
|
const [named, setNamed] = useState(null);
|
||||||
|
const name = selected && named?.id === selected.id ? named.name : null;
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!selected || !fetchName) return;
|
||||||
|
let current = true;
|
||||||
|
Promise.resolve(fetchName(selected))
|
||||||
|
.then(found => current && setNamed({id: selected.id, name: found || null}))
|
||||||
|
.catch(() => current && setNamed({id: selected.id, name: null}));
|
||||||
|
// An answer for a quadrangle which is no longer the chosen one is not used.
|
||||||
|
return () => {
|
||||||
|
current = false;
|
||||||
|
};
|
||||||
|
}, [selected, fetchName]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!map) return;
|
||||||
|
|
||||||
|
const drawGrid = () => {
|
||||||
|
const source = map.getSource(GRID_SOURCE);
|
||||||
|
if (!source) return;
|
||||||
|
const bounds = map.getBounds();
|
||||||
|
const grid = map.getZoom() >= QUAD_MIN_ZOOM
|
||||||
|
? quadGridLines({
|
||||||
|
west: bounds.getWest(), south: bounds.getSouth(),
|
||||||
|
east: bounds.getEast(), north: bounds.getNorth(),
|
||||||
|
})
|
||||||
|
: null;
|
||||||
|
source.setData(grid || EMPTY_FEATURES);
|
||||||
|
setGridShown(grid !== null);
|
||||||
|
};
|
||||||
|
|
||||||
|
const drawSelected = () => {
|
||||||
|
const source = map.getSource(SELECTED_SOURCE);
|
||||||
|
if (source) source.setData(selectedFeatures(selectedRef.current));
|
||||||
|
};
|
||||||
|
|
||||||
|
const addLayers = () => {
|
||||||
|
if (!map.getSource(GRID_SOURCE)) map.addSource(GRID_SOURCE, {type: "geojson", data: EMPTY_FEATURES});
|
||||||
|
if (!map.getSource(SELECTED_SOURCE)) {
|
||||||
|
map.addSource(SELECTED_SOURCE, {type: "geojson", data: EMPTY_FEATURES});
|
||||||
|
}
|
||||||
|
for (const layer of QUAD_LAYERS) {
|
||||||
|
if (!map.getLayer(layer.id)) map.addLayer(layer);
|
||||||
|
}
|
||||||
|
drawGrid();
|
||||||
|
drawSelected();
|
||||||
|
};
|
||||||
|
|
||||||
|
const choose = (e) => {
|
||||||
|
// The quadrangle being exported stays the chosen one.
|
||||||
|
if (busyRef.current) return;
|
||||||
|
const quad = quadAt(e.lngLat.lng, e.lngLat.lat);
|
||||||
|
// Choosing the chosen quadrangle again lets go of it.
|
||||||
|
const next = quad && selectedRef.current?.id === quad.id ? null : quad;
|
||||||
|
selectedRef.current = next;
|
||||||
|
setSelected(next);
|
||||||
|
drawSelected();
|
||||||
|
};
|
||||||
|
|
||||||
|
addLayers();
|
||||||
|
map.on("style.load", addLayers);
|
||||||
|
map.on("moveend", drawGrid);
|
||||||
|
map.on("click", choose);
|
||||||
|
|
||||||
|
return () => {
|
||||||
|
map.off("style.load", addLayers);
|
||||||
|
map.off("moveend", drawGrid);
|
||||||
|
map.off("click", choose);
|
||||||
|
try {
|
||||||
|
for (const layer of [...QUAD_LAYERS].reverse()) {
|
||||||
|
if (map.getLayer(layer.id)) map.removeLayer(layer.id);
|
||||||
|
}
|
||||||
|
for (const source of [GRID_SOURCE, SELECTED_SOURCE]) {
|
||||||
|
if (map.getSource(source)) map.removeSource(source);
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
// The map itself is gone, and its layers with it.
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}, [map]);
|
||||||
|
|
||||||
|
const size = selected ? quadSize(selected) : null;
|
||||||
|
|
||||||
|
// Part of the app's interface over the map, like the layer control: plain, token-colored chrome.
|
||||||
|
const panelStyle = {
|
||||||
|
position: "absolute",
|
||||||
|
bottom: "2.5rem",
|
||||||
|
left: "50%",
|
||||||
|
transform: "translateX(-50%)",
|
||||||
|
zIndex: 1000,
|
||||||
|
background: "var(--panel)",
|
||||||
|
border: "1px solid var(--border)",
|
||||||
|
color: "var(--text)",
|
||||||
|
padding: "0.625rem 0.75rem",
|
||||||
|
fontSize: "0.8125rem",
|
||||||
|
width: "max-content",
|
||||||
|
maxWidth: "calc(100% - 1.25rem)",
|
||||||
|
};
|
||||||
|
|
||||||
|
return <div style={panelStyle} role="region" aria-label="Export a 1:24,000 map">
|
||||||
|
<div style={{fontWeight: 600, paddingBottom: "0.25rem"}}>Export a 1:24,000 map</div>
|
||||||
|
{selected
|
||||||
|
? <div>
|
||||||
|
{name && <div data-testid="quad-name" style={{fontWeight: 600}}>{quadTitle(name)}</div>}
|
||||||
|
<div data-testid="quad-label">{quadLabel(selected)}</div>
|
||||||
|
<div style={{color: "var(--muted)"}} data-testid="quad-size">
|
||||||
|
{formatDistance(size.widthMeters, scaleUnit)} × {formatDistance(size.heightMeters, scaleUnit)}
|
||||||
|
{" on the ground, "}
|
||||||
|
{formatSheet(size.sheetWidthMm, scaleUnit)} × {formatSheet(size.sheetHeightMm, scaleUnit)}
|
||||||
|
{" printed"}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
: <div>
|
||||||
|
{gridShown
|
||||||
|
? "Click a quadrangle on the map to choose it."
|
||||||
|
: "Zoom in to see the quadrangles."}
|
||||||
|
</div>}
|
||||||
|
<Checkbox
|
||||||
|
size="xs"
|
||||||
|
style={{paddingTop: "0.5rem"}}
|
||||||
|
label="Margins, grid and scale bars"
|
||||||
|
checked={sheet}
|
||||||
|
disabled={busy}
|
||||||
|
onChange={e => setSheet(e.currentTarget.checked)}
|
||||||
|
/>
|
||||||
|
<Radio.Group
|
||||||
|
size="xs"
|
||||||
|
style={{paddingTop: "0.5rem"}}
|
||||||
|
aria-label="Sharpness"
|
||||||
|
value={String(dpi)}
|
||||||
|
onChange={value => setDpi(Number(value))}
|
||||||
|
>
|
||||||
|
<Group gap="md">
|
||||||
|
{EXPORT_DPIS.map(value => <Radio
|
||||||
|
key={value}
|
||||||
|
size="xs"
|
||||||
|
value={String(value)}
|
||||||
|
label={`${value} DPI`}
|
||||||
|
disabled={busy}
|
||||||
|
/>)}
|
||||||
|
</Group>
|
||||||
|
</Radio.Group>
|
||||||
|
{look && onLook && <Radio.Group
|
||||||
|
size="xs"
|
||||||
|
style={{paddingTop: "0.5rem"}}
|
||||||
|
aria-label="Colors"
|
||||||
|
value={look}
|
||||||
|
onChange={onLook}
|
||||||
|
>
|
||||||
|
<Group gap="md">
|
||||||
|
{EXPORT_LOOKS.map(({value, label}) => <Radio
|
||||||
|
key={value}
|
||||||
|
size="xs"
|
||||||
|
value={value}
|
||||||
|
label={label}
|
||||||
|
disabled={busy}
|
||||||
|
/>)}
|
||||||
|
</Group>
|
||||||
|
</Radio.Group>}
|
||||||
|
{look === PRINT_LOOK && onLook && <div style={{paddingTop: "0.25rem", color: "var(--muted)"}}>
|
||||||
|
Its colors can be changed under Layers.
|
||||||
|
</div>}
|
||||||
|
{status && <div role="status" style={{paddingTop: "0.25rem"}}>{status}</div>}
|
||||||
|
{error && !status && <div role="alert" style={{paddingTop: "0.25rem", color: "var(--danger, #c92a2a)"}}>
|
||||||
|
{error}
|
||||||
|
</div>}
|
||||||
|
<div style={{display: "flex", gap: "0.5rem", justifyContent: "flex-end", paddingTop: "0.5rem"}}>
|
||||||
|
<Button role="cancel" size="xs" disabled={busy && !onCancel} onClick={busy ? onCancel : onClose}>
|
||||||
|
{error && !busy ? "Close" : "Cancel"}
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
role="primary"
|
||||||
|
size="xs"
|
||||||
|
disabled={!selected || !onExport || busy}
|
||||||
|
loading={busy}
|
||||||
|
onClick={() => onExport(selected, {sheet, dpi, name})}
|
||||||
|
>Export PDF</Button>
|
||||||
|
</div>
|
||||||
|
</div>;
|
||||||
|
}
|
||||||
315
app/src/components/MapQuadPicker.test.js
Normal file
315
app/src/components/MapQuadPicker.test.js
Normal file
|
|
@ -0,0 +1,315 @@
|
||||||
|
import React from 'react';
|
||||||
|
import {act, fireEvent, screen, waitFor} from '@testing-library/react';
|
||||||
|
import {renderUI} from '../test-utils';
|
||||||
|
import MapQuadPicker, {formatDistance, formatSheet} from './MapQuadPicker';
|
||||||
|
import {quadAt} from './mapQuads';
|
||||||
|
|
||||||
|
// As much of a MapLibre map as the picker uses.
|
||||||
|
class FakeMap {
|
||||||
|
constructor({zoom = 12, bounds = {west: -105.175, south: 40.26, east: -104.925, north: 40.4}} = {}) {
|
||||||
|
this.zoom = zoom;
|
||||||
|
this.bounds = bounds;
|
||||||
|
this.sources = {};
|
||||||
|
this.layers = [];
|
||||||
|
this.handlers = {};
|
||||||
|
}
|
||||||
|
|
||||||
|
on(event, handler) {
|
||||||
|
(this.handlers[event] = this.handlers[event] || []).push(handler);
|
||||||
|
}
|
||||||
|
|
||||||
|
off(event, handler) {
|
||||||
|
this.handlers[event] = (this.handlers[event] || []).filter(i => i !== handler);
|
||||||
|
}
|
||||||
|
|
||||||
|
fire(event, data) {
|
||||||
|
for (const handler of [...(this.handlers[event] || [])]) handler(data);
|
||||||
|
}
|
||||||
|
|
||||||
|
addSource(id, source) {
|
||||||
|
this.sources[id] = {data: source.data, setData(data) { this.data = data; }};
|
||||||
|
}
|
||||||
|
|
||||||
|
getSource(id) {
|
||||||
|
return this.sources[id];
|
||||||
|
}
|
||||||
|
|
||||||
|
removeSource(id) {
|
||||||
|
delete this.sources[id];
|
||||||
|
}
|
||||||
|
|
||||||
|
addLayer(layer) {
|
||||||
|
this.layers.push(layer);
|
||||||
|
}
|
||||||
|
|
||||||
|
getLayer(id) {
|
||||||
|
return this.layers.find(i => i.id === id);
|
||||||
|
}
|
||||||
|
|
||||||
|
removeLayer(id) {
|
||||||
|
this.layers = this.layers.filter(i => i.id !== id);
|
||||||
|
}
|
||||||
|
|
||||||
|
getZoom() {
|
||||||
|
return this.zoom;
|
||||||
|
}
|
||||||
|
|
||||||
|
getBounds() {
|
||||||
|
const {west, south, east, north} = this.bounds;
|
||||||
|
return {getWest: () => west, getSouth: () => south, getEast: () => east, getNorth: () => north};
|
||||||
|
}
|
||||||
|
|
||||||
|
// What a style change does: every layer and source is gone, then the new style has loaded.
|
||||||
|
changeStyle() {
|
||||||
|
this.sources = {};
|
||||||
|
this.layers = [];
|
||||||
|
this.fire('style.load');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const click = (map, lng, lat) => act(() => map.fire('click', {lngLat: {lng, lat}}));
|
||||||
|
const gridLines = map => map.getSource('quad-grid').data.features[0]?.geometry.coordinates || [];
|
||||||
|
const selectedIds = map => map.getSource('quad-selected').data.features.map(f => f.properties.id);
|
||||||
|
const BERTHOUD = quadAt(-105.0595, 40.31);
|
||||||
|
|
||||||
|
function renderPicker(map, props = {}) {
|
||||||
|
const onClose = jest.fn();
|
||||||
|
const result = renderUI(<MapQuadPicker map={map} scaleUnit="metric" onClose={onClose} {...props}/>);
|
||||||
|
return {...result, onClose};
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('choosing a quadrangle to export', () => {
|
||||||
|
test('the grid is drawn over the view, above the layers of the map', () => {
|
||||||
|
const map = new FakeMap();
|
||||||
|
map.layers.push({id: 'roads'});
|
||||||
|
renderPicker(map);
|
||||||
|
|
||||||
|
expect(gridLines(map)).toHaveLength(7);
|
||||||
|
expect(map.layers.map(l => l.id))
|
||||||
|
.toEqual(['roads', 'quad-grid-lines', 'quad-selected-fill', 'quad-selected-outline']);
|
||||||
|
expect(screen.getByText('Click a quadrangle on the map to choose it.')).toBeInTheDocument();
|
||||||
|
expect(screen.getByRole('button', {name: 'Export PDF'})).toBeDisabled();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('the grid follows the map', () => {
|
||||||
|
const map = new FakeMap();
|
||||||
|
renderPicker(map);
|
||||||
|
map.bounds = {west: -105.175, south: 40.26, east: -104.925, north: 40.6};
|
||||||
|
act(() => map.fire('moveend'));
|
||||||
|
expect(gridLines(map)).toHaveLength(8);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('there is no grid when zoomed out, and the user is told to zoom in', () => {
|
||||||
|
const map = new FakeMap({zoom: 5});
|
||||||
|
renderPicker(map);
|
||||||
|
expect(gridLines(map)).toEqual([]);
|
||||||
|
expect(screen.getByText('Zoom in to see the quadrangles.')).toBeInTheDocument();
|
||||||
|
|
||||||
|
map.zoom = 9;
|
||||||
|
act(() => map.fire('moveend'));
|
||||||
|
expect(gridLines(map)).toHaveLength(7);
|
||||||
|
expect(screen.getByText('Click a quadrangle on the map to choose it.')).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a click chooses the quadrangle under it, and says what it is', () => {
|
||||||
|
const map = new FakeMap();
|
||||||
|
renderPicker(map);
|
||||||
|
click(map, -105.0595, 40.31);
|
||||||
|
|
||||||
|
expect(selectedIds(map)).toEqual([BERTHOUD.id]);
|
||||||
|
expect(screen.getByTestId('quad-label')).toHaveTextContent('40°15′N 105°07′30″W');
|
||||||
|
expect(screen.getByTestId('quad-size'))
|
||||||
|
.toHaveTextContent('10.6 km × 13.9 km on the ground, 44.3 cm × 57.8 cm printed');
|
||||||
|
|
||||||
|
// Another click chooses another; there is one at a time.
|
||||||
|
click(map, -104.925, 40.4);
|
||||||
|
expect(selectedIds(map)).toEqual([quadAt(-104.925, 40.4).id]);
|
||||||
|
expect(screen.getByTestId('quad-label')).toHaveTextContent('40°22′30″N 105°00′W');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a click on the chosen quadrangle lets go of it', () => {
|
||||||
|
const map = new FakeMap();
|
||||||
|
renderPicker(map);
|
||||||
|
click(map, -105.0595, 40.31);
|
||||||
|
click(map, -105.075, 40.3);
|
||||||
|
expect(selectedIds(map)).toEqual([]);
|
||||||
|
expect(screen.queryByTestId('quad-label')).not.toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('can start with a quadrangle already chosen', () => {
|
||||||
|
const map = new FakeMap();
|
||||||
|
renderPicker(map, {initialQuad: BERTHOUD});
|
||||||
|
expect(selectedIds(map)).toEqual([BERTHOUD.id]);
|
||||||
|
expect(screen.getByTestId('quad-label')).toHaveTextContent('40°15′N 105°07′30″W');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('the size is in the units of the map', () => {
|
||||||
|
renderPicker(new FakeMap(), {initialQuad: BERTHOUD, scaleUnit: 'imperial'});
|
||||||
|
expect(screen.getByTestId('quad-size'))
|
||||||
|
.toHaveTextContent('6.6 mi × 8.6 mi on the ground, 17.4 in × 22.8 in printed');
|
||||||
|
expect(formatDistance(1609.344, 'imperial')).toBe('1.0 mi');
|
||||||
|
expect(formatSheet(254, 'metric')).toBe('25.4 cm');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('the grid and the choice are put back when the style of the map changes', () => {
|
||||||
|
const map = new FakeMap();
|
||||||
|
renderPicker(map);
|
||||||
|
click(map, -105.0595, 40.31);
|
||||||
|
|
||||||
|
act(() => map.changeStyle());
|
||||||
|
expect(map.layers.map(l => l.id)).toEqual(['quad-grid-lines', 'quad-selected-fill', 'quad-selected-outline']);
|
||||||
|
expect(gridLines(map)).toHaveLength(7);
|
||||||
|
expect(selectedIds(map)).toEqual([BERTHOUD.id]);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('exports the chosen quadrangle', () => {
|
||||||
|
const onExport = jest.fn();
|
||||||
|
renderPicker(new FakeMap(), {initialQuad: BERTHOUD, onExport});
|
||||||
|
fireEvent.click(screen.getByRole('button', {name: 'Export PDF'}));
|
||||||
|
expect(onExport).toHaveBeenCalledWith(BERTHOUD, {sheet: true, dpi: 300, name: null});
|
||||||
|
});
|
||||||
|
|
||||||
|
test('while the PDF is being made, Cancel stops it and the picker stays', () => {
|
||||||
|
const onCancel = jest.fn();
|
||||||
|
const {onClose} = renderPicker(new FakeMap(), {
|
||||||
|
initialQuad: BERTHOUD, onExport: jest.fn(), onCancel, status: 'Making the PDF (40%)…',
|
||||||
|
});
|
||||||
|
const cancel = screen.getByRole('button', {name: 'Cancel'});
|
||||||
|
expect(cancel).toBeEnabled();
|
||||||
|
fireEvent.click(cancel);
|
||||||
|
expect(onCancel).toHaveBeenCalledTimes(1);
|
||||||
|
expect(onClose).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('when nothing is being made, Cancel closes the picker', () => {
|
||||||
|
const onCancel = jest.fn();
|
||||||
|
const {onClose} = renderPicker(new FakeMap(), {initialQuad: BERTHOUD, onExport: jest.fn(), onCancel});
|
||||||
|
fireEvent.click(screen.getByRole('button', {name: 'Cancel'}));
|
||||||
|
expect(onClose).toHaveBeenCalledTimes(1);
|
||||||
|
expect(onCancel).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('exports the map alone when the sheet is turned off', () => {
|
||||||
|
const onExport = jest.fn();
|
||||||
|
renderPicker(new FakeMap(), {initialQuad: BERTHOUD, onExport});
|
||||||
|
const sheet = screen.getByRole('checkbox', {name: 'Margins, grid and scale bars'});
|
||||||
|
expect(sheet).toBeChecked();
|
||||||
|
fireEvent.click(sheet);
|
||||||
|
fireEvent.click(screen.getByRole('button', {name: 'Export PDF'}));
|
||||||
|
expect(onExport).toHaveBeenCalledWith(BERTHOUD, {sheet: false, dpi: 300, name: null});
|
||||||
|
});
|
||||||
|
|
||||||
|
test('exports a sharper map when one is asked for', () => {
|
||||||
|
const onExport = jest.fn();
|
||||||
|
renderPicker(new FakeMap(), {initialQuad: BERTHOUD, onExport});
|
||||||
|
expect(screen.getByRole('radio', {name: '300 DPI'})).toBeChecked();
|
||||||
|
fireEvent.click(screen.getByRole('radio', {name: '400 DPI'}));
|
||||||
|
fireEvent.click(screen.getByRole('button', {name: 'Export PDF'}));
|
||||||
|
expect(onExport).toHaveBeenCalledWith(BERTHOUD, {sheet: true, dpi: 400, name: null});
|
||||||
|
});
|
||||||
|
|
||||||
|
test('the look the map is exported in is chosen, and not while a map is exported', () => {
|
||||||
|
const onLook = jest.fn();
|
||||||
|
const {unmount} = renderPicker(new FakeMap(), {initialQuad: BERTHOUD, look: 'print', onLook});
|
||||||
|
expect(screen.getByRole('radio', {name: 'Print'})).toBeChecked();
|
||||||
|
fireEvent.click(screen.getByRole('radio', {name: 'Dark'}));
|
||||||
|
expect(onLook).toHaveBeenCalledWith('dark');
|
||||||
|
unmount();
|
||||||
|
|
||||||
|
renderPicker(new FakeMap(), {
|
||||||
|
initialQuad: BERTHOUD, look: 'dark', onLook, status: 'Drawing Water (1 of 12)…',
|
||||||
|
});
|
||||||
|
expect(screen.getByRole('radio', {name: 'Dark'})).toBeChecked();
|
||||||
|
expect(screen.getByRole('radio', {name: 'Light'})).toBeDisabled();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('there is no look to choose where none is given', () => {
|
||||||
|
renderPicker(new FakeMap(), {initialQuad: BERTHOUD});
|
||||||
|
expect(screen.queryByRole('radio', {name: 'Print'})).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('says what the USGS calls the quadrangle, and exports it by that name', async () => {
|
||||||
|
const named = {name: 'Berthoud', state: 'Colorado', exact: true};
|
||||||
|
const fetchName = jest.fn().mockResolvedValue(named);
|
||||||
|
const onExport = jest.fn();
|
||||||
|
renderPicker(new FakeMap(), {initialQuad: BERTHOUD, onExport, fetchName});
|
||||||
|
expect(await screen.findByTestId('quad-name')).toHaveTextContent('Berthoud, Colorado');
|
||||||
|
expect(fetchName).toHaveBeenCalledWith(BERTHOUD);
|
||||||
|
// Where it is, is still said.
|
||||||
|
expect(screen.getByTestId('quad-label')).toHaveTextContent('40°15′N 105°07′30″W');
|
||||||
|
fireEvent.click(screen.getByRole('button', {name: 'Export PDF'}));
|
||||||
|
expect(onExport).toHaveBeenCalledWith(BERTHOUD, {sheet: true, dpi: 300, name: named});
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a quadrangle the USGS has no name for goes by where it is', async () => {
|
||||||
|
const fetchName = jest.fn().mockResolvedValue(null);
|
||||||
|
const onExport = jest.fn();
|
||||||
|
renderPicker(new FakeMap(), {initialQuad: BERTHOUD, onExport, fetchName});
|
||||||
|
await waitFor(() => expect(fetchName).toHaveBeenCalled());
|
||||||
|
expect(screen.queryByTestId('quad-name')).toBeNull();
|
||||||
|
fireEvent.click(screen.getByRole('button', {name: 'Export PDF'}));
|
||||||
|
expect(onExport).toHaveBeenCalledWith(BERTHOUD, {sheet: true, dpi: 300, name: null});
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a name which can not be asked for is no name', async () => {
|
||||||
|
const fetchName = jest.fn().mockRejectedValue(new Error('offline'));
|
||||||
|
renderPicker(new FakeMap(), {initialQuad: BERTHOUD, fetchName});
|
||||||
|
await waitFor(() => expect(fetchName).toHaveBeenCalled());
|
||||||
|
expect(screen.queryByTestId('quad-name')).toBeNull();
|
||||||
|
expect(screen.getByTestId('quad-label')).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('the name of one quadrangle is not shown for another', async () => {
|
||||||
|
let answer;
|
||||||
|
const fetchName = jest.fn()
|
||||||
|
.mockImplementationOnce(() => new Promise(resolve => {
|
||||||
|
answer = resolve;
|
||||||
|
}))
|
||||||
|
.mockResolvedValue({name: 'Windsor', state: 'Colorado', exact: true});
|
||||||
|
const map = new FakeMap();
|
||||||
|
renderPicker(map, {initialQuad: BERTHOUD, fetchName});
|
||||||
|
// Another quadrangle is chosen before the first is named.
|
||||||
|
act(() => map.fire('click', {lngLat: {lng: -104.925, lat: 40.4}}));
|
||||||
|
expect(await screen.findByTestId('quad-name')).toHaveTextContent('Windsor, Colorado');
|
||||||
|
await act(async () => answer({name: 'Berthoud', state: 'Colorado', exact: true}));
|
||||||
|
expect(screen.getByTestId('quad-name')).toHaveTextContent('Windsor, Colorado');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('while the PDF is being made it says how far along it is, and the choice stays', () => {
|
||||||
|
const map = new FakeMap();
|
||||||
|
const onExport = jest.fn();
|
||||||
|
renderPicker(map, {initialQuad: BERTHOUD, onExport, status: 'Drawing Water (2 of 13)…'});
|
||||||
|
|
||||||
|
expect(screen.getByRole('status')).toHaveTextContent('Drawing Water (2 of 13)…');
|
||||||
|
expect(screen.getByRole('button', {name: 'Export PDF'})).toBeDisabled();
|
||||||
|
// An export which can not be stopped has no way to stop it.
|
||||||
|
expect(screen.getByRole('button', {name: 'Cancel'})).toBeDisabled();
|
||||||
|
|
||||||
|
// A click on the map does not choose another quadrangle.
|
||||||
|
click(map, -104.925, 40.4);
|
||||||
|
expect(selectedIds(map)).toEqual([BERTHOUD.id]);
|
||||||
|
expect(screen.getByTestId('quad-label')).toHaveTextContent('40°15′N 105°07′30″W');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('says why the PDF could not be made, and it can be tried again', () => {
|
||||||
|
const onExport = jest.fn();
|
||||||
|
renderPicker(new FakeMap(), {initialQuad: BERTHOUD, onExport, error: 'Could not reach the server'});
|
||||||
|
expect(screen.getByRole('alert')).toHaveTextContent('Could not reach the server');
|
||||||
|
fireEvent.click(screen.getByRole('button', {name: 'Export PDF'}));
|
||||||
|
expect(onExport).toHaveBeenCalledWith(BERTHOUD, {sheet: true, dpi: 300, name: null});
|
||||||
|
expect(screen.getByRole('button', {name: 'Close'})).toBeEnabled();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('leaves nothing on the map when it is closed', () => {
|
||||||
|
const map = new FakeMap();
|
||||||
|
map.layers.push({id: 'roads'});
|
||||||
|
const {onClose, unmount} = renderPicker(map);
|
||||||
|
fireEvent.click(screen.getByRole('button', {name: 'Cancel'}));
|
||||||
|
expect(onClose).toHaveBeenCalled();
|
||||||
|
|
||||||
|
unmount();
|
||||||
|
expect(map.layers.map(l => l.id)).toEqual(['roads']);
|
||||||
|
expect(map.sources).toEqual({});
|
||||||
|
expect(Object.values(map.handlers).flat()).toEqual([]);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
@ -2,7 +2,7 @@ import React, {useEffect, useState} from "react";
|
||||||
import {Link, useNavigate} from "react-router";
|
import {Link, useNavigate} from "react-router";
|
||||||
import {getMapSearchStatus, searchMap} from "../api";
|
import {getMapSearchStatus, searchMap} from "../api";
|
||||||
import {Card, CardGroup, Header, Loading, Panel} from "./ui";
|
import {Card, CardGroup, Header, Loading, Panel} from "./ui";
|
||||||
import {Paginator} from "./Common";
|
import {ErrorMessage, Paginator} from "./Common";
|
||||||
import {useLatestRequest, usePages} from "../hooks/customHooks";
|
import {useLatestRequest, usePages} from "../hooks/customHooks";
|
||||||
import {QueryContext} from "../contexts/contexts";
|
import {QueryContext} from "../contexts/contexts";
|
||||||
import {MAP_VIEWER_URI} from "./Vars";
|
import {MAP_VIEWER_URI} from "./Vars";
|
||||||
|
|
@ -68,17 +68,25 @@ export function MapSearchView() {
|
||||||
const {offset, limit, activePage, setPage, totalPages, setTotal} = usePages(12);
|
const {offset, limit, activePage, setPage, totalPages, setTotal} = usePages(12);
|
||||||
// useLatestRequest discards stale responses and catches errors, so rapid pagination
|
// useLatestRequest discards stale responses and catches errors, so rapid pagination
|
||||||
// can't show out-of-order results and a network failure can't leave the spinner stuck.
|
// can't show out-of-order results and a network failure can't leave the spinner stuck.
|
||||||
const {data, sendRequest, loading} = useLatestRequest(300);
|
// Loading from the first render: a query of two or more characters always sends a request (below),
|
||||||
|
// so this settles, and the shorter-query branches render before the loading check.
|
||||||
|
const {data, sendRequest, loading} = useLatestRequest(300, true);
|
||||||
|
// null = unknown (pending, or the status could not be fetched), otherwise whether any map is
|
||||||
|
// installed. Only a real status may claim that no maps are installed.
|
||||||
const [hasMaps, setHasMaps] = useState(null);
|
const [hasMaps, setHasMaps] = useState(null);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
let cancelled = false;
|
let cancelled = false;
|
||||||
(async () => {
|
(async () => {
|
||||||
|
try {
|
||||||
const status = await getMapSearchStatus();
|
const status = await getMapSearchStatus();
|
||||||
if (!cancelled) {
|
if (!cancelled && status) {
|
||||||
const installed = (status.indexed || []).length + (status.missing || []).length;
|
const installed = (status.indexed || []).length + (status.missing || []).length;
|
||||||
setHasMaps(installed > 0);
|
setHasMaps(installed > 0);
|
||||||
}
|
}
|
||||||
|
} catch (e) {
|
||||||
|
console.error(e);
|
||||||
|
}
|
||||||
})();
|
})();
|
||||||
return () => {
|
return () => {
|
||||||
cancelled = true;
|
cancelled = true;
|
||||||
|
|
@ -106,12 +114,22 @@ export function MapSearchView() {
|
||||||
</Panel>;
|
</Panel>;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (!searchStr) {
|
||||||
|
return <Panel><Header as="h4">Enter a search query to find map locations.</Header></Panel>;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (searchStr.length < 2) {
|
||||||
|
return <Panel><Header as="h4">Enter at least two characters to find map locations.</Header></Panel>;
|
||||||
|
}
|
||||||
|
|
||||||
if (loading) {
|
if (loading) {
|
||||||
return <Panel><Loading/></Panel>;
|
return <Panel><Loading/></Panel>;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!searchStr) {
|
// Settled with no data: the request failed (the api helper returns undefined on a non-OK
|
||||||
return <Panel><Header as="h4">Enter a search query to find map locations.</Header></Panel>;
|
// response, and useLatestRequest leaves null when it throws).
|
||||||
|
if (data == null) {
|
||||||
|
return <Panel><ErrorMessage>Could not search the map.</ErrorMessage></Panel>;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (results.length === 0) {
|
if (results.length === 0) {
|
||||||
|
|
|
||||||
61
app/src/components/MapSearchView.test.js
Normal file
61
app/src/components/MapSearchView.test.js
Normal file
|
|
@ -0,0 +1,61 @@
|
||||||
|
import React from 'react';
|
||||||
|
import {render, screen} from '../test-utils';
|
||||||
|
import {MapSearchView} from './MapSearchView';
|
||||||
|
import {getMapSearchStatus, searchMap} from '../api';
|
||||||
|
|
||||||
|
// The map search tab says "No map locations found" only when the server searched and found none,
|
||||||
|
// and "No maps are installed" only when the server said so. A failed request is an error.
|
||||||
|
|
||||||
|
jest.mock('../api', () => ({
|
||||||
|
...jest.requireActual('../api'),
|
||||||
|
getMapSearchStatus: jest.fn(),
|
||||||
|
searchMap: jest.fn(),
|
||||||
|
}));
|
||||||
|
|
||||||
|
const NOT_FOUND = /No map locations found/;
|
||||||
|
const NO_MAPS = /No maps are installed/;
|
||||||
|
const FAILED = /Could not search the map/;
|
||||||
|
|
||||||
|
const renderAt = (q) => render(<MapSearchView/>, {query: {searchParams: new URLSearchParams({q})}});
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
getMapSearchStatus.mockReset();
|
||||||
|
searchMap.mockReset();
|
||||||
|
getMapSearchStatus.mockResolvedValue({indexed: ['utah'], missing: []});
|
||||||
|
});
|
||||||
|
|
||||||
|
test('found nothing: says so', async () => {
|
||||||
|
searchMap.mockResolvedValue({results: [], total: 0});
|
||||||
|
renderAt('camp');
|
||||||
|
expect(await screen.findByText(NOT_FOUND)).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a failed search shows an error, not "No map locations found"', async () => {
|
||||||
|
searchMap.mockResolvedValue(undefined);
|
||||||
|
renderAt('camp');
|
||||||
|
expect(await screen.findByText(FAILED)).toBeInTheDocument();
|
||||||
|
expect(screen.queryByText(NOT_FOUND)).not.toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a failed status check does not claim no maps are installed', async () => {
|
||||||
|
getMapSearchStatus.mockResolvedValue(undefined);
|
||||||
|
searchMap.mockResolvedValue({results: [], total: 0});
|
||||||
|
renderAt('camp');
|
||||||
|
expect(await screen.findByText(NOT_FOUND)).toBeInTheDocument();
|
||||||
|
expect(screen.queryByText(NO_MAPS)).not.toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a thrown status check does not claim no maps are installed', async () => {
|
||||||
|
getMapSearchStatus.mockRejectedValue(new Error('down'));
|
||||||
|
searchMap.mockResolvedValue({results: [], total: 0});
|
||||||
|
renderAt('camp');
|
||||||
|
expect(await screen.findByText(NOT_FOUND)).toBeInTheDocument();
|
||||||
|
expect(screen.queryByText(NO_MAPS)).not.toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('the server saying no maps are installed is shown', async () => {
|
||||||
|
getMapSearchStatus.mockResolvedValue({indexed: [], missing: []});
|
||||||
|
searchMap.mockResolvedValue({results: [], total: 0});
|
||||||
|
renderAt('camp');
|
||||||
|
expect(await screen.findByText(NO_MAPS)).toBeInTheDocument();
|
||||||
|
});
|
||||||
362
app/src/components/MapTables.test.js
Normal file
362
app/src/components/MapTables.test.js
Normal file
|
|
@ -0,0 +1,362 @@
|
||||||
|
import React from 'react';
|
||||||
|
import {act, fireEvent, screen} from '@testing-library/react';
|
||||||
|
import {Route, Routes} from 'react-router';
|
||||||
|
import {renderWithProviders as render} from '../test-utils';
|
||||||
|
import {MapRoute} from './Map';
|
||||||
|
|
||||||
|
// What the map's Pins and Manage tabs show while their lists are still loading, when the
|
||||||
|
// fetch failed, and when the server confirmed the list is empty. The empty messages invite
|
||||||
|
// the user to act ("Right-click on the map to add one"), so they may only appear for a
|
||||||
|
// confirmed empty list.
|
||||||
|
|
||||||
|
jest.mock('maplibre-gl', () => ({
|
||||||
|
__esModule: true,
|
||||||
|
default: {Map: class {
|
||||||
|
}, addProtocol: jest.fn(), Marker: class {
|
||||||
|
}},
|
||||||
|
}));
|
||||||
|
jest.mock('pmtiles', () => ({
|
||||||
|
__esModule: true, Protocol: class {
|
||||||
|
tile = jest.fn();
|
||||||
|
},
|
||||||
|
}));
|
||||||
|
jest.mock('protomaps-themes-base', () => ({__esModule: true, default: () => []}));
|
||||||
|
jest.mock('./MapViewer', () => ({__esModule: true, default: () => null}));
|
||||||
|
|
||||||
|
jest.mock('../api', () => ({
|
||||||
|
...jest.requireActual('../api'),
|
||||||
|
getMapFiles: jest.fn(),
|
||||||
|
fetchMapSubscriptions: jest.fn(),
|
||||||
|
getMapPins: jest.fn(),
|
||||||
|
getMapTargets: jest.fn(),
|
||||||
|
getWeather: jest.fn(),
|
||||||
|
setWeatherSubscription: jest.fn(),
|
||||||
|
downloadWeatherNow: jest.fn(),
|
||||||
|
deleteMapTarget: jest.fn(),
|
||||||
|
setMapFileVisible: jest.fn(),
|
||||||
|
rebuildMapSearchIndex: jest.fn(),
|
||||||
|
}));
|
||||||
|
|
||||||
|
const api = require('../api');
|
||||||
|
|
||||||
|
const pending = () => new Promise(() => {
|
||||||
|
});
|
||||||
|
const NO_PINS = /No pins\. Right-click/;
|
||||||
|
const NO_RESULTS = /^No results$/;
|
||||||
|
const WEATHER_OFF = {enabled: false, download: null, targets: 3, spacing: 1, points: 160, seconds: 61, field: null};
|
||||||
|
|
||||||
|
// The pins page renders one table per breakpoint through `Media`, so the real media provider is
|
||||||
|
// needed; the queries below tolerate either variant being in the tree.
|
||||||
|
const renderAt = (route) => render(
|
||||||
|
<Routes><Route path='/map/*' element={<MapRoute/>}/></Routes>,
|
||||||
|
{route, withMedia: true},
|
||||||
|
);
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
jest.clearAllMocks();
|
||||||
|
// The media provider reads matchMedia; the global stub's implementation is reset between
|
||||||
|
// tests, so give it one here. Only the computer breakpoint (1024px) matches, so the
|
||||||
|
// provider reports a desktop viewport and the pins page renders its desktop table.
|
||||||
|
window.matchMedia = jest.fn().mockImplementation(query => ({
|
||||||
|
matches: query.includes('1024'), media: query, onchange: null,
|
||||||
|
addListener: jest.fn(), removeListener: jest.fn(),
|
||||||
|
addEventListener: jest.fn(), removeEventListener: jest.fn(), dispatchEvent: jest.fn(),
|
||||||
|
}));
|
||||||
|
api.getMapFiles.mockResolvedValue({files: []});
|
||||||
|
api.fetchMapSubscriptions.mockResolvedValue({catalog: [], subscriptions: []});
|
||||||
|
api.getMapPins.mockResolvedValue({pins: []});
|
||||||
|
api.getMapTargets.mockResolvedValue([]);
|
||||||
|
api.deleteMapTarget.mockResolvedValue(true);
|
||||||
|
api.getWeather.mockResolvedValue(WEATHER_OFF);
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('the Pins tab', () => {
|
||||||
|
test('pending: shows a placeholder, not "No pins"', () => {
|
||||||
|
api.getMapPins.mockReturnValue(pending());
|
||||||
|
const {container} = renderAt('/map/pins');
|
||||||
|
expect(container.querySelector('.wrolpi-placeholder')).toBeInTheDocument();
|
||||||
|
expect(screen.queryAllByText(NO_PINS)).toHaveLength(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('failed: shows an error, not "No pins"', async () => {
|
||||||
|
// The api helper returns undefined on a non-OK response.
|
||||||
|
api.getMapPins.mockResolvedValue(undefined);
|
||||||
|
renderAt('/map/pins');
|
||||||
|
await act(async () => {
|
||||||
|
});
|
||||||
|
expect(screen.getByText(/Could not fetch map pins/)).toBeInTheDocument();
|
||||||
|
expect(screen.queryAllByText(NO_PINS)).toHaveLength(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('empty: shows "No pins"', async () => {
|
||||||
|
renderAt('/map/pins');
|
||||||
|
await act(async () => {
|
||||||
|
});
|
||||||
|
expect(screen.getAllByText(NO_PINS).length).toBeGreaterThan(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('loaded: lists the pins', async () => {
|
||||||
|
api.getMapPins.mockResolvedValue({pins: [{id: 1, lat: 40.1, lon: -111.2, label: 'Camp', color: '#f00'}]});
|
||||||
|
renderAt('/map/pins');
|
||||||
|
await act(async () => {
|
||||||
|
});
|
||||||
|
expect(screen.getAllByText('Camp').length).toBeGreaterThan(0);
|
||||||
|
expect(screen.queryAllByText(NO_PINS)).toHaveLength(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a pin opens the Solar calculator at its location', async () => {
|
||||||
|
api.getMapPins.mockResolvedValue({pins: [{id: 1, lat: 40.12346, lon: -111.2, label: 'Camp', color: '#f00'}]});
|
||||||
|
renderAt('/map/pins');
|
||||||
|
await act(async () => {
|
||||||
|
});
|
||||||
|
fireEvent.click(screen.getAllByRole('button', {name: 'Solar estimate for Camp'})[0]);
|
||||||
|
expect(window.location.pathname).toBe('/more/calculators');
|
||||||
|
expect(window.location.search).toBe('?calc=solar&lat=40.1235&lon=-111.2');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('the Pins tab\'s nuclear targets', () => {
|
||||||
|
const {within} = require('@testing-library/react');
|
||||||
|
const targets = [
|
||||||
|
{id: 1, lat: 40.1, lon: -111.2, label: 'Base', created: '2026-11-24', weapon: 'w88', fission_fraction: 0.5},
|
||||||
|
{id: 2, lat: 41, lon: -112, label: 'Depot', created: '2026-11-24', weapon: 'custom', yield_kt: 20,
|
||||||
|
fission_fraction: 1},
|
||||||
|
];
|
||||||
|
|
||||||
|
test('are listed in their own table, apart from the pins', async () => {
|
||||||
|
api.getMapPins.mockResolvedValue({pins: [{id: 1, lat: 40.1, lon: -111.2, label: 'Camp', color: '#f00'}]});
|
||||||
|
api.getMapTargets.mockResolvedValue(targets);
|
||||||
|
renderAt('/map/pins');
|
||||||
|
await act(async () => {
|
||||||
|
});
|
||||||
|
const tables = screen.getAllByRole('table');
|
||||||
|
expect(tables).toHaveLength(2);
|
||||||
|
const [pinsTable, table] = tables;
|
||||||
|
expect(within(pinsTable).queryByText('Base')).toBeNull();
|
||||||
|
expect(within(pinsTable).getByText('Camp')).toBeTruthy();
|
||||||
|
expect(within(table).queryByText('Camp')).toBeNull();
|
||||||
|
expect(within(table).getByText('Base')).toBeTruthy();
|
||||||
|
expect(within(table).getByText(/W88.*455 kt, half fission/)).toBeTruthy();
|
||||||
|
expect(within(table).getByText(/A yield of my own, 20 kt/)).toBeTruthy();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('says when there are none, and when they could not be fetched', async () => {
|
||||||
|
const {unmount} = renderAt('/map/pins');
|
||||||
|
await act(async () => {
|
||||||
|
});
|
||||||
|
expect(screen.getAllByText(/No targets\. Turn on nuclear mode/).length).toBeGreaterThan(0);
|
||||||
|
unmount();
|
||||||
|
api.getMapTargets.mockResolvedValue(undefined);
|
||||||
|
renderAt('/map/pins');
|
||||||
|
await act(async () => {
|
||||||
|
});
|
||||||
|
expect(screen.getByText('Could not fetch the nuclear targets')).toBeTruthy();
|
||||||
|
expect(screen.queryAllByText(/No targets\./)).toHaveLength(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('delete one, and are fetched again', async () => {
|
||||||
|
api.getMapTargets.mockResolvedValueOnce(targets).mockResolvedValueOnce(targets.slice(1));
|
||||||
|
renderAt('/map/pins');
|
||||||
|
await act(async () => {
|
||||||
|
});
|
||||||
|
fireEvent.click(screen.getAllByRole('button', {name: 'Delete Base'})[0]);
|
||||||
|
// The delete is confirmed first.
|
||||||
|
await act(async () => {
|
||||||
|
fireEvent.click(await screen.findByRole('button', {name: 'Delete'}));
|
||||||
|
});
|
||||||
|
expect(api.deleteMapTarget).toHaveBeenCalledWith(1);
|
||||||
|
expect(api.getMapTargets).toHaveBeenCalledTimes(2);
|
||||||
|
expect(screen.queryAllByText('Base')).toHaveLength(0);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('the Manage tab subscriptions table', () => {
|
||||||
|
test('pending: shows a placeholder, not "No results"', async () => {
|
||||||
|
api.fetchMapSubscriptions.mockReturnValue(pending());
|
||||||
|
const {container} = renderAt('/map/manage');
|
||||||
|
await act(async () => {
|
||||||
|
});
|
||||||
|
// The files table has loaded (empty); the subscriptions table is still pending.
|
||||||
|
expect(container.querySelector('.wrolpi-placeholder')).toBeInTheDocument();
|
||||||
|
expect(screen.queryByText(NO_RESULTS)).not.toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('failed: shows an error, not "No results"', async () => {
|
||||||
|
api.fetchMapSubscriptions.mockResolvedValue(undefined);
|
||||||
|
renderAt('/map/manage');
|
||||||
|
await act(async () => {
|
||||||
|
});
|
||||||
|
expect(screen.getByText(/Could not fetch map subscriptions/)).toBeInTheDocument();
|
||||||
|
expect(screen.queryByText(NO_RESULTS)).not.toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('empty: shows "No results"', async () => {
|
||||||
|
renderAt('/map/manage');
|
||||||
|
await act(async () => {
|
||||||
|
});
|
||||||
|
expect(screen.getByText(NO_RESULTS)).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
// The "View All Regions" preview draws the catalog; a pending or failed catalog must not be
|
||||||
|
// previewed as zero regions.
|
||||||
|
test('pending: the regions preview is disabled', async () => {
|
||||||
|
api.fetchMapSubscriptions.mockReturnValue(pending());
|
||||||
|
renderAt('/map/manage');
|
||||||
|
await act(async () => {
|
||||||
|
});
|
||||||
|
expect(screen.getByRole('button', {name: 'View All Regions'})).toBeDisabled();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('failed: the regions preview is disabled', async () => {
|
||||||
|
api.fetchMapSubscriptions.mockResolvedValue(undefined);
|
||||||
|
renderAt('/map/manage');
|
||||||
|
await act(async () => {
|
||||||
|
});
|
||||||
|
expect(screen.getByRole('button', {name: 'View All Regions'})).toBeDisabled();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('loaded: the regions preview is enabled', async () => {
|
||||||
|
renderAt('/map/manage');
|
||||||
|
await act(async () => {
|
||||||
|
});
|
||||||
|
expect(screen.getByRole('button', {name: 'View All Regions'})).toBeEnabled();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('the Manage tab files table', () => {
|
||||||
|
const mapFile = (map_path, kind, extra = {}) => ({
|
||||||
|
name: map_path.split('/').pop(), map_path, path: `map/${map_path}`, kind,
|
||||||
|
size: 1024, visible: true, has_search_index: false, title: null, ...extra,
|
||||||
|
});
|
||||||
|
const FILES = [
|
||||||
|
mapFile('us-west.pmtiles', 'basemap', {title: 'Protomaps Basemap'}),
|
||||||
|
mapFile('extras/features.pmtiles', 'overlay', {title: 'Topographic Features'}),
|
||||||
|
mapFile('terrain-planet.pmtiles', 'terrain'),
|
||||||
|
mapFile('broken.pmtiles', 'unknown'),
|
||||||
|
];
|
||||||
|
const rowOf = (text) => screen.getByText(text).closest('tr');
|
||||||
|
const cellsOf = (text) => [...rowOf(text).querySelectorAll('td')].map(td => td.textContent);
|
||||||
|
|
||||||
|
const renderFiles = async (files = FILES) => {
|
||||||
|
api.getMapFiles.mockResolvedValue({files});
|
||||||
|
renderAt('/map/manage');
|
||||||
|
await act(async () => {
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
test('a file is listed with its directory, its own name, and how the map draws it', async () => {
|
||||||
|
await renderFiles();
|
||||||
|
expect(cellsOf('extras/features.pmtiles').slice(0, 2))
|
||||||
|
.toEqual(['extras/features.pmtilesTopographic Features', 'Overlay']);
|
||||||
|
expect(cellsOf('us-west.pmtiles')[1]).toBe('Basemap');
|
||||||
|
expect(cellsOf('terrain-planet.pmtiles')[1]).toBe('Terrain');
|
||||||
|
expect(cellsOf('broken.pmtiles')[1]).toBe('Unreadable');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('only a basemap offers a search index', async () => {
|
||||||
|
await renderFiles();
|
||||||
|
const builds = screen.getAllByRole('button', {name: 'Build'});
|
||||||
|
expect(builds).toHaveLength(1);
|
||||||
|
expect(rowOf('us-west.pmtiles')).toContainElement(builds[0]);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('the search index of a file in a sub-directory is built by its path', async () => {
|
||||||
|
await renderFiles([mapFile('regions/oregon.pmtiles', 'basemap')]);
|
||||||
|
await act(async () => {
|
||||||
|
fireEvent.click(screen.getByRole('button', {name: 'Build'}));
|
||||||
|
});
|
||||||
|
expect(api.rebuildMapSearchIndex).toHaveBeenCalledWith('regions/oregon.pmtiles');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a file is ignored with its toggle, and the list is fetched again', async () => {
|
||||||
|
await renderFiles();
|
||||||
|
const toggle = screen.getByRole('switch', {name: 'Show extras/features.pmtiles on the map'});
|
||||||
|
expect(toggle).toBeChecked();
|
||||||
|
|
||||||
|
api.getMapFiles.mockResolvedValue({
|
||||||
|
files: FILES.map(f => f.kind === 'overlay' ? {...f, visible: false} : f),
|
||||||
|
});
|
||||||
|
const before = api.getMapFiles.mock.calls.length;
|
||||||
|
await act(async () => {
|
||||||
|
fireEvent.click(toggle);
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(api.setMapFileVisible).toHaveBeenCalledWith('extras/features.pmtiles', false);
|
||||||
|
expect(api.getMapFiles.mock.calls.length).toBe(before + 1);
|
||||||
|
// Only the ignored file's toggle is off.
|
||||||
|
expect(screen.getByRole('switch', {name: 'Show extras/features.pmtiles on the map'})).not.toBeChecked();
|
||||||
|
expect(screen.getByRole('switch', {name: 'Show us-west.pmtiles on the map'})).toBeChecked();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('an ignored file is shown again with its toggle', async () => {
|
||||||
|
await renderFiles([mapFile('satellite.pmtiles', 'overlay', {visible: false})]);
|
||||||
|
const toggle = screen.getByRole('switch', {name: 'Show satellite.pmtiles on the map'});
|
||||||
|
expect(toggle).not.toBeChecked();
|
||||||
|
await act(async () => {
|
||||||
|
fireEvent.click(toggle);
|
||||||
|
});
|
||||||
|
expect(api.setMapFileVisible).toHaveBeenCalledWith('satellite.pmtiles', true);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('the Manage tab\'s weather', () => {
|
||||||
|
const hour = 3600000;
|
||||||
|
const field = (fromHours, toHours) => ({
|
||||||
|
fetched_at: new Date().toISOString(), spacing: 1, points: 160, size: 5 * 1024 * 1024,
|
||||||
|
first_hour: new Date(Date.now() + fromHours * hour).toISOString(),
|
||||||
|
last_hour: new Date(Date.now() + toHours * hour).toISOString(),
|
||||||
|
});
|
||||||
|
|
||||||
|
test('is turned on with its toggle, and says what it downloads', async () => {
|
||||||
|
api.setWeatherSubscription.mockResolvedValue({...WEATHER_OFF, enabled: true,
|
||||||
|
download: {status: 'new', next_download: null, last_successful_download: null}});
|
||||||
|
renderAt('/map/manage');
|
||||||
|
await act(async () => {
|
||||||
|
});
|
||||||
|
expect(screen.getByText('Weather')).toBeInTheDocument();
|
||||||
|
expect(screen.getByText(/Around 3 targets: 160 places every 1°, which takes about 2 minutes/)).toBeInTheDocument();
|
||||||
|
expect(screen.getByText('No forecast has been downloaded.')).toBeInTheDocument();
|
||||||
|
expect(screen.queryByRole('button', {name: 'Download now'})).toBeNull();
|
||||||
|
await act(async () => {
|
||||||
|
fireEvent.click(screen.getByRole('switch', {name: /Download the weather forecast from Open-Meteo/}));
|
||||||
|
});
|
||||||
|
expect(api.setWeatherSubscription).toHaveBeenCalledWith(true);
|
||||||
|
expect(screen.getByText('Downloading the forecast…')).toBeInTheDocument();
|
||||||
|
expect(screen.getByRole('button', {name: 'Download now'})).toBeDisabled();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('shows the forecast kept, and whether it is recent enough for bursts now', async () => {
|
||||||
|
const done = {status: 'complete', last_successful_download: new Date().toISOString(),
|
||||||
|
next_download: new Date(Date.now() + 24 * hour).toISOString()};
|
||||||
|
api.getWeather.mockResolvedValue({...WEATHER_OFF, enabled: true, download: done, field: field(-5, 90)});
|
||||||
|
api.downloadWeatherNow.mockResolvedValue({...WEATHER_OFF, enabled: true, download: {...done, status: 'new'}});
|
||||||
|
const {unmount} = renderAt('/map/manage');
|
||||||
|
await act(async () => {
|
||||||
|
});
|
||||||
|
expect(screen.getByText(/Forecast kept: .* 160 places every 1°, 5.0 MB/)).toBeInTheDocument();
|
||||||
|
expect(screen.getByText(/It has the winds for bursts now/)).toBeInTheDocument();
|
||||||
|
expect(screen.getByText(/Last downloaded .*\. Next /)).toBeInTheDocument();
|
||||||
|
await act(async () => {
|
||||||
|
fireEvent.click(screen.getByRole('button', {name: 'Download now'}));
|
||||||
|
});
|
||||||
|
expect(api.downloadWeatherNow).toHaveBeenCalled();
|
||||||
|
unmount();
|
||||||
|
|
||||||
|
// Ending a day from now: too old for bursts now.
|
||||||
|
api.getWeather.mockResolvedValue({...WEATHER_OFF, enabled: true,
|
||||||
|
download: {status: 'failed', error: 'The forecast service answered HTTP 500'}, field: field(-60, 24)});
|
||||||
|
renderAt('/map/manage');
|
||||||
|
await act(async () => {
|
||||||
|
});
|
||||||
|
expect(screen.getByText(/It is too old for bursts now/)).toBeInTheDocument();
|
||||||
|
expect(screen.getByText(/The last download failed: The forecast service answered HTTP 500/)).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('says when there are no targets to download around', async () => {
|
||||||
|
api.getWeather.mockResolvedValue({...WEATHER_OFF, targets: 0, spacing: null, points: null});
|
||||||
|
renderAt('/map/manage');
|
||||||
|
await act(async () => {
|
||||||
|
});
|
||||||
|
expect(screen.getByText(/No nuclear targets are saved/)).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
});
|
||||||
File diff suppressed because it is too large
Load diff
45
app/src/components/MapViewer.test.js
Normal file
45
app/src/components/MapViewer.test.js
Normal file
|
|
@ -0,0 +1,45 @@
|
||||||
|
import React from 'react';
|
||||||
|
import {renderWithProviders as render} from '../test-utils';
|
||||||
|
import MapViewer from './MapViewer';
|
||||||
|
|
||||||
|
// MapLibre needs WebGL, which jsdom lacks; these tests only cover what the viewer does to the URL.
|
||||||
|
jest.mock('maplibre-gl', () => ({
|
||||||
|
__esModule: true,
|
||||||
|
default: {Map: class {
|
||||||
|
}, addProtocol: jest.fn(), Marker: class {
|
||||||
|
}, Popup: class {
|
||||||
|
}},
|
||||||
|
}));
|
||||||
|
jest.mock('maplibre-gl/dist/maplibre-gl.css', () => ({}));
|
||||||
|
jest.mock('pmtiles', () => ({
|
||||||
|
__esModule: true, Protocol: class {
|
||||||
|
tile = jest.fn();
|
||||||
|
},
|
||||||
|
}));
|
||||||
|
jest.mock('protomaps-themes-base', () => ({__esModule: true, default: () => []}));
|
||||||
|
jest.mock('@acalcutt/maplibre-contour-pmtiles', () => ({__esModule: true, default: {}}));
|
||||||
|
jest.mock('../api', () => ({
|
||||||
|
...jest.requireActual('../api'),
|
||||||
|
// Never resolves: the map never initializes, which these tests do not need.
|
||||||
|
getMapFiles: jest.fn(() => new Promise(() => {
|
||||||
|
})),
|
||||||
|
getMapPins: jest.fn(() => new Promise(() => {
|
||||||
|
})),
|
||||||
|
}));
|
||||||
|
|
||||||
|
describe('the map position in the URL', () => {
|
||||||
|
test('is removed when the map closes', () => {
|
||||||
|
const {unmount} = render(<MapViewer/>, {route: '/map?lat=40&lon=-105&z=8&layer=a'});
|
||||||
|
unmount();
|
||||||
|
expect(window.location.pathname).toBe('/map');
|
||||||
|
expect(window.location.search).toBe('?layer=a');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('is not removed from the page the map navigated to', () => {
|
||||||
|
// "Calculate Solar Performance" navigates to a page whose own lat/lon must survive the map closing.
|
||||||
|
const {unmount} = render(<MapViewer/>, {route: '/map?lat=40&lon=-105&z=8'});
|
||||||
|
window.history.pushState({}, '', '/more/calculators?calc=solar&lat=40.0154&lon=-105.2705');
|
||||||
|
unmount();
|
||||||
|
expect(window.location.search).toBe('?calc=solar&lat=40.0154&lon=-105.2705');
|
||||||
|
});
|
||||||
|
});
|
||||||
491
app/src/components/MapViewerOverlays.test.js
Normal file
491
app/src/components/MapViewerOverlays.test.js
Normal file
|
|
@ -0,0 +1,491 @@
|
||||||
|
import React from 'react';
|
||||||
|
import {act, fireEvent, screen, waitFor} from '@testing-library/react';
|
||||||
|
import {renderWithProviders as render} from '../test-utils';
|
||||||
|
import MapViewer from './MapViewer';
|
||||||
|
import {STORAGE_KEY_OVERLAYS} from './mapOverlays';
|
||||||
|
|
||||||
|
// How the viewer draws the map files it is given: which become the basemap, which are offered as
|
||||||
|
// overlays in the layer control, and what the control's checkboxes do to the map's layers.
|
||||||
|
|
||||||
|
/*
|
||||||
|
* MapLibre needs WebGL, which jsdom lacks, so it is mocked down to the surface MapViewer uses.
|
||||||
|
* A constructed map keeps the style it was given, and the visibility of each of its layers as
|
||||||
|
* `setLayoutProperty` changes it -- the two things these tests read.
|
||||||
|
*/
|
||||||
|
const constructed = [];
|
||||||
|
|
||||||
|
jest.mock('maplibre-gl', () => {
|
||||||
|
class FakeMap {
|
||||||
|
constructor(options) {
|
||||||
|
this.options = options;
|
||||||
|
this.style = options.style;
|
||||||
|
this.center = {lat: 0, lng: 0};
|
||||||
|
this.moves = [];
|
||||||
|
this.listeners = [];
|
||||||
|
this.controls = [];
|
||||||
|
constructed.push(this);
|
||||||
|
}
|
||||||
|
|
||||||
|
on(event, callback) {
|
||||||
|
// MapLibre fires `load` asynchronously once the style resolves.
|
||||||
|
if (event === 'load') setTimeout(() => callback(), 0);
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
once(event, callback) {
|
||||||
|
this.listeners.push({event, callback});
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
off(event, callback) {
|
||||||
|
this.listeners = this.listeners.filter(i => i.event !== event || i.callback !== callback);
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
getStyle() {
|
||||||
|
return this.style;
|
||||||
|
}
|
||||||
|
|
||||||
|
setStyle(style) {
|
||||||
|
this.style = style;
|
||||||
|
// MapLibre puts a style which only differs from the one it has in place, and says so,
|
||||||
|
// before this returns.
|
||||||
|
const waiting = this.listeners.filter(i => i.event === 'style.load');
|
||||||
|
this.listeners = this.listeners.filter(i => i.event !== 'style.load');
|
||||||
|
waiting.forEach(i => i.callback());
|
||||||
|
}
|
||||||
|
|
||||||
|
getLayer(id) {
|
||||||
|
return this.style.layers.find(l => l.id === id);
|
||||||
|
}
|
||||||
|
|
||||||
|
setLayoutProperty(id, name, value) {
|
||||||
|
const layer = this.getLayer(id);
|
||||||
|
layer.layout = {...layer.layout, [name]: value};
|
||||||
|
}
|
||||||
|
|
||||||
|
visibility(id) {
|
||||||
|
return this.getLayer(id)?.layout?.visibility ?? 'visible';
|
||||||
|
}
|
||||||
|
|
||||||
|
getCanvas() {
|
||||||
|
return global.document.createElement('canvas');
|
||||||
|
}
|
||||||
|
|
||||||
|
getCenter() {
|
||||||
|
return this.center;
|
||||||
|
}
|
||||||
|
|
||||||
|
getZoom() {
|
||||||
|
return 2;
|
||||||
|
}
|
||||||
|
|
||||||
|
setCenter(center) {
|
||||||
|
this.moves.push(center);
|
||||||
|
this.center = center;
|
||||||
|
}
|
||||||
|
|
||||||
|
setZoom() {
|
||||||
|
}
|
||||||
|
|
||||||
|
addControl(control) {
|
||||||
|
// A control of the viewer's own (not one of MapLibre's) is put on the page.
|
||||||
|
if (typeof control?.onAdd === 'function') {
|
||||||
|
this.controls.push(global.document.body.appendChild(control.onAdd(this)));
|
||||||
|
}
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
removeControl() {
|
||||||
|
}
|
||||||
|
|
||||||
|
remove() {
|
||||||
|
this.controls.forEach(control => control.remove());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class Control {
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
__esModule: true,
|
||||||
|
default: {
|
||||||
|
Map: FakeMap, addProtocol: jest.fn(), Marker: Control, Popup: Control,
|
||||||
|
NavigationControl: Control, FullscreenControl: Control, ScaleControl: Control,
|
||||||
|
GeolocateControl: Control,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
});
|
||||||
|
jest.mock('maplibre-gl/dist/maplibre-gl.css', () => ({}));
|
||||||
|
jest.mock('pmtiles', () => ({
|
||||||
|
__esModule: true, Protocol: class {
|
||||||
|
tile = jest.fn();
|
||||||
|
},
|
||||||
|
}));
|
||||||
|
// The basemap theme: a layer of each kind the tests care about, for whichever source asks.
|
||||||
|
jest.mock('protomaps-themes-base', () => ({
|
||||||
|
__esModule: true,
|
||||||
|
default: (source) => [
|
||||||
|
{id: 'earth', type: 'fill', source},
|
||||||
|
{id: 'water', type: 'fill', source},
|
||||||
|
{id: 'places_locality', type: 'symbol', source},
|
||||||
|
],
|
||||||
|
// The printed map: the same layers, in colors of its own.
|
||||||
|
namedTheme: () => ({}),
|
||||||
|
layersWithCustomTheme: (source) => [
|
||||||
|
{id: 'earth', type: 'fill', source, paint: {'fill-color': 'print'}},
|
||||||
|
{id: 'water', type: 'fill', source},
|
||||||
|
{id: 'places_locality', type: 'symbol', source},
|
||||||
|
],
|
||||||
|
}));
|
||||||
|
// Choosing a quadrangle draws on the map, which is not what is looked at here.
|
||||||
|
jest.mock('./MapQuadPicker', () => ({onClose}) => <button onClick={onClose}>Close the picker</button>);
|
||||||
|
// Contours are generated in the browser from the terrain file; only the URL of that source matters here.
|
||||||
|
jest.mock('@acalcutt/maplibre-contour-pmtiles', () => ({
|
||||||
|
__esModule: true,
|
||||||
|
default: {
|
||||||
|
DemSource: class {
|
||||||
|
setupMaplibre() {
|
||||||
|
}
|
||||||
|
|
||||||
|
contourProtocolUrl() {
|
||||||
|
return 'dem-contour://{z}/{x}/{y}';
|
||||||
|
}
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}));
|
||||||
|
jest.mock('../api', () => ({
|
||||||
|
...jest.requireActual('../api'),
|
||||||
|
getMapFiles: jest.fn(),
|
||||||
|
getMapPins: jest.fn(),
|
||||||
|
}));
|
||||||
|
|
||||||
|
const api = require('../api');
|
||||||
|
|
||||||
|
const mapFile = (map_path, kind, extra = {}) => ({
|
||||||
|
name: map_path.split('/').pop(), map_path, path: `map/${map_path}`, kind,
|
||||||
|
tile_type: 'mvt', size: 1024, visible: true, vector_layers: [], ...extra,
|
||||||
|
});
|
||||||
|
const layer = (id, geometry) => ({id, geometry, minzoom: 0, maxzoom: 8, description: null});
|
||||||
|
|
||||||
|
const PLANET = mapFile('20260329.pmtiles', 'basemap', {size: 134e9});
|
||||||
|
const REGION = mapFile('regions/oregon.pmtiles', 'basemap');
|
||||||
|
// An overlay with a layer named like one of the basemap's.
|
||||||
|
const FEATURES = mapFile('extras/features.pmtiles', 'overlay', {
|
||||||
|
title: 'Topographic Features', description: 'Topographic features', min_zoom: 0, max_zoom: 8,
|
||||||
|
vector_layers: [layer('water', 'Polygon'), layer('power_lines', 'LineString'), layer('towers', 'Point')],
|
||||||
|
});
|
||||||
|
const SATELLITE = mapFile('satellite.pmtiles', 'overlay', {tile_type: 'jpeg'});
|
||||||
|
|
||||||
|
const WATER = 'overlay:extras/features.pmtiles:water:fill';
|
||||||
|
const POWER_LINES = 'overlay:extras/features.pmtiles:power_lines:line';
|
||||||
|
const TOWERS = 'overlay:extras/features.pmtiles:towers:circle';
|
||||||
|
const RASTER = 'overlay:satellite.pmtiles:raster';
|
||||||
|
|
||||||
|
/** Render the viewer with these map files, and open its layer control. Returns the map. */
|
||||||
|
const renderViewer = async (files) => {
|
||||||
|
api.getMapFiles.mockResolvedValue({files});
|
||||||
|
render(<MapViewer/>, {route: '/map'});
|
||||||
|
await waitFor(() => expect(constructed).toHaveLength(1));
|
||||||
|
// The layer control appears once the map has loaded; it starts collapsed.
|
||||||
|
fireEvent.click(await screen.findByTitle('Layers'));
|
||||||
|
return constructed[0];
|
||||||
|
};
|
||||||
|
|
||||||
|
const click = async (element) => {
|
||||||
|
await act(async () => {
|
||||||
|
fireEvent.click(element);
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
constructed.length = 0;
|
||||||
|
localStorage.clear();
|
||||||
|
jest.clearAllMocks();
|
||||||
|
api.getMapPins.mockResolvedValue({pins: []});
|
||||||
|
// The layer control asks whether this is a narrow screen; the global stub's implementation is
|
||||||
|
// reset between tests.
|
||||||
|
window.matchMedia = jest.fn().mockImplementation(query => ({
|
||||||
|
matches: false, media: query, onchange: null,
|
||||||
|
addListener: jest.fn(), removeListener: jest.fn(),
|
||||||
|
addEventListener: jest.fn(), removeEventListener: jest.fn(), dispatchEvent: jest.fn(),
|
||||||
|
}));
|
||||||
|
// The overview blob is only asked for when there is no planet file.
|
||||||
|
global.fetch = jest.fn().mockResolvedValue({ok: true});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('which files the viewer draws', () => {
|
||||||
|
test('a planet file is the basemap, and an overlay is drawn with it', async () => {
|
||||||
|
const map = await renderViewer([PLANET, REGION, FEATURES]);
|
||||||
|
expect(Object.keys(map.style.sources)).toEqual(['20260329.pmtiles', 'overlay:extras/features.pmtiles']);
|
||||||
|
// The overlay is drawn as itself, not with the basemap theme.
|
||||||
|
expect(map.style.layers.filter(l => l.source === 'overlay:extras/features.pmtiles').map(l => l.id))
|
||||||
|
.toEqual([WATER, POWER_LINES, TOWERS]);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('files are fetched from where they are, sub-directories included', async () => {
|
||||||
|
const map = await renderViewer([REGION, FEATURES]);
|
||||||
|
expect(map.style.sources['regions/oregon.pmtiles'].url).toBe('pmtiles:///media/map/regions/oregon.pmtiles');
|
||||||
|
expect(map.style.sources['overlay:extras/features.pmtiles'].url)
|
||||||
|
.toBe('pmtiles:///media/map/extras/features.pmtiles');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('an ignored file is neither drawn nor offered', async () => {
|
||||||
|
const map = await renderViewer([{...PLANET, visible: false}, REGION, {...FEATURES, visible: false}, SATELLITE]);
|
||||||
|
// Without the planet file the regional basemap (over the overview) is drawn.
|
||||||
|
expect(Object.keys(map.style.sources))
|
||||||
|
.toEqual(['map-overview', 'regions/oregon.pmtiles', 'overlay:satellite.pmtiles']);
|
||||||
|
expect(screen.queryByLabelText('Topographic Features')).not.toBeInTheDocument();
|
||||||
|
expect(screen.getByLabelText('satellite')).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('no overlays, no Overlays section', async () => {
|
||||||
|
await renderViewer([PLANET]);
|
||||||
|
expect(screen.queryByText('Overlays')).not.toBeInTheDocument();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('an overlay in the layer control', () => {
|
||||||
|
test('is named by the file, and starts hidden', async () => {
|
||||||
|
const map = await renderViewer([PLANET, FEATURES, SATELLITE]);
|
||||||
|
expect(screen.getByText('Overlays')).toBeInTheDocument();
|
||||||
|
expect(screen.getByLabelText('Topographic Features')).not.toBeChecked();
|
||||||
|
expect(screen.getByLabelText('satellite')).not.toBeChecked();
|
||||||
|
expect([WATER, POWER_LINES, TOWERS, RASTER].map(id => map.visibility(id)))
|
||||||
|
.toEqual(['none', 'none', 'none', 'none']);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('is drawn when it is turned on, and that is remembered', async () => {
|
||||||
|
const map = await renderViewer([PLANET, FEATURES, SATELLITE]);
|
||||||
|
await click(screen.getByLabelText('Topographic Features'));
|
||||||
|
|
||||||
|
// The basemap draws water already, so the file's own is left off.
|
||||||
|
expect([WATER, POWER_LINES, TOWERS].map(id => map.visibility(id))).toEqual(['none', 'visible', 'visible']);
|
||||||
|
// The other overlay is untouched.
|
||||||
|
expect(map.visibility(RASTER)).toBe('none');
|
||||||
|
expect(JSON.parse(localStorage.getItem(STORAGE_KEY_OVERLAYS)))
|
||||||
|
.toEqual({'extras/features.pmtiles': {enabled: true}});
|
||||||
|
|
||||||
|
await click(screen.getByLabelText('Topographic Features'));
|
||||||
|
expect([WATER, POWER_LINES, TOWERS].map(id => map.visibility(id))).toEqual(['none', 'none', 'none']);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('is drawn from the start when it was turned on before', async () => {
|
||||||
|
localStorage.setItem(STORAGE_KEY_OVERLAYS, JSON.stringify({
|
||||||
|
'extras/features.pmtiles': {enabled: true, layers: {towers: false}},
|
||||||
|
}));
|
||||||
|
const map = await renderViewer([PLANET, FEATURES]);
|
||||||
|
expect(screen.getByLabelText('Topographic Features')).toBeChecked();
|
||||||
|
expect([WATER, POWER_LINES, TOWERS].map(id => map.visibility(id))).toEqual(['none', 'visible', 'none']);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('each layer of a vector file has its own checkbox', async () => {
|
||||||
|
const map = await renderViewer([PLANET, FEATURES]);
|
||||||
|
await click(screen.getByLabelText('Topographic Features'));
|
||||||
|
await click(screen.getByRole('button', {name: 'Show layers of Topographic Features'}));
|
||||||
|
|
||||||
|
// A layer of something the basemap draws starts unchecked, and can be checked.
|
||||||
|
expect(screen.getByLabelText('water')).not.toBeChecked();
|
||||||
|
expect(screen.getByLabelText('power_lines')).toBeChecked();
|
||||||
|
await click(screen.getByLabelText('water'));
|
||||||
|
expect(screen.getByLabelText('water')).toBeChecked();
|
||||||
|
|
||||||
|
await click(screen.getByLabelText('towers'));
|
||||||
|
expect([WATER, POWER_LINES, TOWERS].map(id => map.visibility(id))).toEqual(['visible', 'visible', 'none']);
|
||||||
|
|
||||||
|
await click(screen.getByText('None'));
|
||||||
|
expect([WATER, POWER_LINES, TOWERS].map(id => map.visibility(id))).toEqual(['none', 'none', 'none']);
|
||||||
|
expect(screen.getByLabelText('power_lines')).not.toBeChecked();
|
||||||
|
|
||||||
|
await click(screen.getByText('All'));
|
||||||
|
expect([WATER, POWER_LINES, TOWERS].map(id => map.visibility(id))).toEqual(['visible', 'visible', 'visible']);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a raster file has no layers to choose from', async () => {
|
||||||
|
const map = await renderViewer([PLANET, SATELLITE]);
|
||||||
|
expect(screen.queryByRole('button', {name: /layers of satellite/})).not.toBeInTheDocument();
|
||||||
|
await click(screen.getByLabelText('satellite'));
|
||||||
|
expect(map.visibility(RASTER)).toBe('visible');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('the basemap layer groups', () => {
|
||||||
|
test("do not show or hide an overlay's layer of the same name", async () => {
|
||||||
|
const map = await renderViewer([PLANET, FEATURES]);
|
||||||
|
await click(screen.getByLabelText('Topographic Features'));
|
||||||
|
await click(screen.getByRole('button', {name: 'Show layers of Topographic Features'}));
|
||||||
|
await click(screen.getByLabelText('water'));
|
||||||
|
expect(map.visibility('water')).toBe('visible');
|
||||||
|
expect(map.visibility(WATER)).toBe('visible');
|
||||||
|
|
||||||
|
// Hide the basemap's water: the overlay's `water` layer stays.
|
||||||
|
await click(screen.getByLabelText('Water'));
|
||||||
|
expect(map.visibility('water')).toBe('none');
|
||||||
|
expect(map.visibility(WATER)).toBe('visible');
|
||||||
|
|
||||||
|
// Hide the overlay, then show the basemap's water: the overlay's stays hidden.
|
||||||
|
await click(screen.getByLabelText('Topographic Features'));
|
||||||
|
await click(screen.getByLabelText('Water'));
|
||||||
|
expect(map.visibility('water')).toBe('visible');
|
||||||
|
expect(map.visibility(WATER)).toBe('none');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('an overlay with a style beside it', () => {
|
||||||
|
const STYLED = {...FEATURES, style_path: 'map/extras/style.json'};
|
||||||
|
const STYLE = {
|
||||||
|
version: 8,
|
||||||
|
sources: {features: {type: 'vector', url: 'https://example.com/features.json'}},
|
||||||
|
layers: [
|
||||||
|
{id: 'background', type: 'background'},
|
||||||
|
{id: 'lines', type: 'line', source: 'features', 'source-layer': 'power_lines'},
|
||||||
|
{
|
||||||
|
id: 'towers', type: 'symbol', source: 'features', 'source-layer': 'towers',
|
||||||
|
layout: {'icon-image': 'tower', 'text-field': ['get', 'name'], 'text-font': ['Roboto Bold']},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
};
|
||||||
|
const STYLED_LINES = 'overlay:extras/features.pmtiles:power_lines:lines';
|
||||||
|
const STYLED_TOWERS = 'overlay:extras/features.pmtiles:towers:towers';
|
||||||
|
|
||||||
|
// The style is fetched from the media directory; the overview blob is asked for with HEAD.
|
||||||
|
const serveStyle = (style) => {
|
||||||
|
global.fetch = jest.fn(async (url) => {
|
||||||
|
if (String(url).endsWith('style.json')) {
|
||||||
|
if (!style) return {ok: false};
|
||||||
|
return {ok: true, json: async () => style};
|
||||||
|
}
|
||||||
|
return {ok: true};
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
test("is drawn with that style and the map's own icons", async () => {
|
||||||
|
serveStyle(STYLE);
|
||||||
|
const map = await renderViewer([PLANET, STYLED]);
|
||||||
|
expect(global.fetch).toHaveBeenCalledWith('/media/map/extras/style.json');
|
||||||
|
|
||||||
|
const overlayLayers = map.style.layers.filter(l => l.source === 'overlay:extras/features.pmtiles');
|
||||||
|
expect(overlayLayers.map(l => l.id)).toEqual([STYLED_LINES, STYLED_TOWERS]);
|
||||||
|
expect(map.getLayer(STYLED_TOWERS).layout['icon-image']).toBe('overlay-icons:tower');
|
||||||
|
expect(map.getLayer(STYLED_TOWERS).layout['text-font']).toEqual(['Noto Sans Medium']);
|
||||||
|
// The basemap keeps its sprite; the overlay icons are beside it.
|
||||||
|
expect(map.style.sprite).toEqual([
|
||||||
|
{id: 'default', url: `${window.location.origin}/map-assets/sprites/light`},
|
||||||
|
{id: 'overlay-icons', url: `${window.location.origin}/map-assets/sprites/overlay-icons`},
|
||||||
|
]);
|
||||||
|
// Nothing of the style's own sources reaches the map.
|
||||||
|
expect(JSON.stringify(map.style)).not.toContain('example.com');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('starts hidden, and offers only the layers its style draws', async () => {
|
||||||
|
serveStyle(STYLE);
|
||||||
|
const map = await renderViewer([PLANET, STYLED]);
|
||||||
|
expect([STYLED_LINES, STYLED_TOWERS].map(id => map.visibility(id))).toEqual(['none', 'none']);
|
||||||
|
|
||||||
|
await click(screen.getByLabelText('Topographic Features'));
|
||||||
|
expect([STYLED_LINES, STYLED_TOWERS].map(id => map.visibility(id))).toEqual(['visible', 'visible']);
|
||||||
|
|
||||||
|
await click(screen.getByRole('button', {name: 'Show layers of Topographic Features'}));
|
||||||
|
// The style has no layer for the file's `water`.
|
||||||
|
expect(screen.queryByLabelText('water')).not.toBeInTheDocument();
|
||||||
|
await click(screen.getByLabelText('towers'));
|
||||||
|
expect([STYLED_LINES, STYLED_TOWERS].map(id => map.visibility(id))).toEqual(['visible', 'none']);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('says how many layers of the style could not be used', async () => {
|
||||||
|
serveStyle({
|
||||||
|
...STYLE,
|
||||||
|
layers: [...STYLE.layers, {id: 'bad', type: 'line', source: 'features', 'source-layer': 'water', paint: {'line-width': 'wide'}}],
|
||||||
|
});
|
||||||
|
const map = await renderViewer([PLANET, STYLED]);
|
||||||
|
await click(screen.getByRole('button', {name: 'Show layers of Topographic Features'}));
|
||||||
|
expect(screen.getByText('1 style layer skipped')).toBeInTheDocument();
|
||||||
|
expect(map.style.layers.filter(l => l.source === 'overlay:extras/features.pmtiles').map(l => l.id))
|
||||||
|
.toEqual([STYLED_LINES, STYLED_TOWERS]);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('is drawn generically when the style cannot be fetched', async () => {
|
||||||
|
serveStyle(null);
|
||||||
|
const map = await renderViewer([PLANET, STYLED]);
|
||||||
|
expect(map.style.layers.filter(l => l.source === 'overlay:extras/features.pmtiles').map(l => l.id))
|
||||||
|
.toEqual([WATER, POWER_LINES, TOWERS]);
|
||||||
|
// The overlay icons are only asked for when a style names them.
|
||||||
|
expect(map.style.sprite).toBe(`${window.location.origin}/map-assets/sprites/light`);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('the text of the map', () => {
|
||||||
|
// The fonts the map has glyphs for (modules/map/static/fonts).
|
||||||
|
const FONTS = ['Noto Sans Regular', 'Noto Sans Medium', 'Noto Sans Italic'];
|
||||||
|
const TERRAIN = mapFile('terrain-planet.pmtiles', 'terrain', {tile_type: 'webp'});
|
||||||
|
|
||||||
|
test('contour labels are drawn in a font the map has', async () => {
|
||||||
|
const map = await renderViewer([PLANET, TERRAIN]);
|
||||||
|
const labels = map.getLayer('contour-labels');
|
||||||
|
expect(labels.layout['text-field']).toBeDefined();
|
||||||
|
// Without a font MapLibre asks for its default, which the map does not have.
|
||||||
|
expect(labels.layout['text-font']).toBeDefined();
|
||||||
|
expect(FONTS).toEqual(expect.arrayContaining(labels.layout['text-font']));
|
||||||
|
});
|
||||||
|
|
||||||
|
test('every layer with text names a font the map has', async () => {
|
||||||
|
const map = await renderViewer([PLANET, TERRAIN, FEATURES]);
|
||||||
|
const textLayers = map.style.layers.filter(l => l.layout?.['text-field'] !== undefined);
|
||||||
|
expect(textLayers.map(l => l.id)).toContain('contour-labels');
|
||||||
|
for (const textLayer of textLayers) {
|
||||||
|
expect([textLayer.id, textLayer.layout['text-font']]).toEqual([textLayer.id, expect.any(Array)]);
|
||||||
|
expect(FONTS).toEqual(expect.arrayContaining(textLayer.layout['text-font']));
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('the look the map is exported in', () => {
|
||||||
|
const earthColor = map => map.getLayer('earth').paint?.['fill-color'];
|
||||||
|
|
||||||
|
test('is how the map is shown while a quadrangle is chosen, where it is and with what is off still off', async () => {
|
||||||
|
const map = await renderViewer([PLANET]);
|
||||||
|
await click(screen.getByLabelText('Water'));
|
||||||
|
expect(map.visibility('water')).toBe('none');
|
||||||
|
// The map has been moved since it was made.
|
||||||
|
map.center = {lat: 40.3, lng: -105.06};
|
||||||
|
|
||||||
|
await click(screen.getByTitle('Export a 1:24,000 map'));
|
||||||
|
expect(earthColor(map)).toBe('print');
|
||||||
|
expect(map.visibility('water')).toBe('none');
|
||||||
|
// Moved again, while the quadrangle is chosen.
|
||||||
|
map.center = {lat: 61.2, lng: -149.9};
|
||||||
|
|
||||||
|
await click(screen.getByText('Close the picker'));
|
||||||
|
expect(earthColor(map)).toBeUndefined();
|
||||||
|
expect(map.visibility('water')).toBe('none');
|
||||||
|
// Changing the look never moves the map.
|
||||||
|
expect(map.moves).toEqual([]);
|
||||||
|
expect(map.center).toEqual({lat: 61.2, lng: -149.9});
|
||||||
|
});
|
||||||
|
|
||||||
|
test('has colors which are chosen where its layers are, while a quadrangle is chosen', async () => {
|
||||||
|
const map = await renderViewer([PLANET]);
|
||||||
|
// The map on the screen has no colors to choose.
|
||||||
|
expect(screen.queryByLabelText('Water: color when printed')).not.toBeInTheDocument();
|
||||||
|
|
||||||
|
await click(screen.getByTitle('Export a 1:24,000 map'));
|
||||||
|
const water = screen.getByLabelText('Water: color when printed');
|
||||||
|
expect(water).toHaveValue('#a9d4f2');
|
||||||
|
expect(screen.queryByText('Reset colors')).not.toBeInTheDocument();
|
||||||
|
await act(async () => {
|
||||||
|
fireEvent.change(water, {target: {value: '#ff00ff'}});
|
||||||
|
});
|
||||||
|
expect(screen.getByLabelText('Water: color when printed')).toHaveValue('#ff00ff');
|
||||||
|
expect(JSON.parse(localStorage.getItem('wrolpi-map-print-colors'))).toEqual({water: '#ff00ff'});
|
||||||
|
// The map was drawn again, where it was.
|
||||||
|
expect(earthColor(map)).toBe('print');
|
||||||
|
expect(map.moves).toEqual([]);
|
||||||
|
|
||||||
|
await click(screen.getByText('Reset colors'));
|
||||||
|
expect(screen.getByLabelText('Water: color when printed')).toHaveValue('#a9d4f2');
|
||||||
|
expect(localStorage.getItem('wrolpi-map-print-colors')).toBeNull();
|
||||||
|
|
||||||
|
await click(screen.getByText('Close the picker'));
|
||||||
|
expect(screen.queryByLabelText('Water: color when printed')).not.toBeInTheDocument();
|
||||||
|
});
|
||||||
|
});
|
||||||
112
app/src/components/MapWeather.js
Normal file
112
app/src/components/MapWeather.js
Normal file
|
|
@ -0,0 +1,112 @@
|
||||||
|
import React, {useCallback, useEffect, useState} from "react";
|
||||||
|
import {downloadWeatherNow, getWeather, setWeatherSubscription} from "../api";
|
||||||
|
import {ErrorMessage, humanFileSize} from "./Common";
|
||||||
|
import {Button, Header, Toggle} from "./ui";
|
||||||
|
import {LANDING_HOURS} from "../map-shared/fallout/winds.js";
|
||||||
|
|
||||||
|
// The weather subscription: a forecast of the winds aloft around the saved nuclear targets,
|
||||||
|
// downloaded every day (a recurring Download), for the fallout simulator.
|
||||||
|
|
||||||
|
// How often (ms) the subscription is asked again while it downloads.
|
||||||
|
const REFRESH_MS = 10000;
|
||||||
|
|
||||||
|
// Whether a download of the weather is waiting or running.
|
||||||
|
export const weatherDownloading = (weather) => ['new', 'pending'].includes(weather?.download?.status);
|
||||||
|
|
||||||
|
// The weather subscription, asked again while it downloads: {weather (null while pending, undefined
|
||||||
|
// when it could not be fetched), downloading, setEnabled(enabled), downloadNow()}.
|
||||||
|
export function useWeather() {
|
||||||
|
const [weather, setWeather] = useState(null);
|
||||||
|
const refresh = useCallback(async () => setWeather(await getWeather()), []);
|
||||||
|
useEffect(() => {
|
||||||
|
refresh();
|
||||||
|
}, [refresh]);
|
||||||
|
const downloading = weatherDownloading(weather);
|
||||||
|
useEffect(() => {
|
||||||
|
if (!downloading) return;
|
||||||
|
const timer = setInterval(refresh, REFRESH_MS);
|
||||||
|
return () => clearInterval(timer);
|
||||||
|
}, [downloading, refresh]);
|
||||||
|
const setEnabled = async (enabled) => {
|
||||||
|
const changed = await setWeatherSubscription(enabled);
|
||||||
|
if (changed) setWeather(changed);
|
||||||
|
};
|
||||||
|
const downloadNow = async () => {
|
||||||
|
const changed = await downloadWeatherNow();
|
||||||
|
if (changed) setWeather(changed);
|
||||||
|
};
|
||||||
|
return {weather, downloading, setEnabled, downloadNow};
|
||||||
|
}
|
||||||
|
|
||||||
|
// Whether the forecast kept (`field`, as the subscription tells it) has the winds for bursts now,
|
||||||
|
// until all their fallout is down.
|
||||||
|
export function fieldCoversNow(field, when = new Date()) {
|
||||||
|
if (!field) return false;
|
||||||
|
const first = Date.parse(field.first_hour), last = Date.parse(field.last_hour);
|
||||||
|
return first <= when.getTime() + 3600000 && last >= when.getTime() + LANDING_HOURS * 3600000;
|
||||||
|
}
|
||||||
|
|
||||||
|
// About how long a download takes, as the user reads it.
|
||||||
|
export const downloadTime = (seconds) => !seconds || seconds < 60 ? "about a minute"
|
||||||
|
: `about ${Math.round(seconds / 60) + 1} minutes`;
|
||||||
|
|
||||||
|
const when = (time) => time ? new Date(time).toLocaleString(undefined, {
|
||||||
|
weekday: "short", month: "short", day: "numeric", hour: "numeric", minute: "2-digit",
|
||||||
|
}) : null;
|
||||||
|
|
||||||
|
// The Manage tab's section for the weather subscription: turning it on or off, what it downloads,
|
||||||
|
// how its downloads have gone, and the forecast kept.
|
||||||
|
export function WeatherSection() {
|
||||||
|
const {weather, downloading, setEnabled, downloadNow} = useWeather();
|
||||||
|
const muted = {color: "var(--muted)", fontSize: "0.875rem"};
|
||||||
|
const warning = {color: "var(--warning)", fontSize: "0.875rem"};
|
||||||
|
const header = <Header as='h3'>Weather</Header>;
|
||||||
|
if (weather === undefined) return <>{header}<ErrorMessage>Could not fetch the weather subscription</ErrorMessage></>;
|
||||||
|
if (!weather) return header;
|
||||||
|
const {download, field} = weather;
|
||||||
|
const failed = download && ['failed', 'deferred'].includes(download.status) && download.error;
|
||||||
|
return <>
|
||||||
|
{header}
|
||||||
|
<Toggle label="Download the weather forecast from Open-Meteo every day" checked={weather.enabled}
|
||||||
|
onChange={(e) => setEnabled(e.currentTarget.checked)}/>
|
||||||
|
<div style={muted}>
|
||||||
|
The winds aloft, hour by hour for four days, around the saved nuclear targets: the fallout simulator
|
||||||
|
carries fallout by them. Open-Meteo is told only places on whole degrees, never a target.
|
||||||
|
</div>
|
||||||
|
{weather.targets === 0
|
||||||
|
? <div style={warning}>
|
||||||
|
No nuclear targets are saved, so there is nowhere to download the forecast around. Save some in
|
||||||
|
nuclear mode (☢) on the map.
|
||||||
|
</div>
|
||||||
|
: <div style={muted}>
|
||||||
|
Around {weather.targets === 1 ? "1 target" : `${weather.targets} targets`}: {weather.points} places
|
||||||
|
every {weather.spacing}°, which takes {downloadTime(weather.seconds)} to download.
|
||||||
|
</div>}
|
||||||
|
{weather.enabled && <div style={{marginTop: "0.5rem"}}>
|
||||||
|
{downloading && <div>Downloading the forecast…</div>}
|
||||||
|
{download?.last_successful_download && <div style={muted}>
|
||||||
|
Last downloaded {when(download.last_successful_download)}.
|
||||||
|
{download.next_download && !downloading && ` Next ${when(download.next_download)}.`}
|
||||||
|
</div>}
|
||||||
|
{failed && <div style={warning}>The last download failed: {download.error}</div>}
|
||||||
|
<Button size='xs' style={{marginTop: "0.25rem"}} disabled={downloading || weather.targets === 0}
|
||||||
|
onClick={downloadNow}>Download now</Button>
|
||||||
|
</div>}
|
||||||
|
<div style={{marginTop: "0.5rem"}}>
|
||||||
|
{field
|
||||||
|
? <>
|
||||||
|
<div>
|
||||||
|
Forecast kept: {when(field.first_hour)} to {when(field.last_hour)}, {field.points} places
|
||||||
|
every {field.spacing}°, {humanFileSize(field.size)}.
|
||||||
|
</div>
|
||||||
|
{fieldCoversNow(field)
|
||||||
|
? <div style={muted}>It has the winds for bursts now, until their fallout is down.</div>
|
||||||
|
: <div style={warning}>
|
||||||
|
It is too old for bursts now: their fallout comes down over {LANDING_HOURS} hours, past
|
||||||
|
its end. {weather.enabled ? "Download it again." : "Turn on the download to get a new one."}
|
||||||
|
</div>}
|
||||||
|
</>
|
||||||
|
: <div style={muted}>No forecast has been downloaded.</div>}
|
||||||
|
</div>
|
||||||
|
</>;
|
||||||
|
}
|
||||||
170
app/src/components/MarkdownPreview.js
Normal file
170
app/src/components/MarkdownPreview.js
Normal file
|
|
@ -0,0 +1,170 @@
|
||||||
|
import React from "react";
|
||||||
|
import MarkdownIt from "markdown-it";
|
||||||
|
import DOMPurify from "dompurify";
|
||||||
|
import {useLocalStorage} from "./Common";
|
||||||
|
import {Button, ButtonGroup, Loading, Message} from "./ui";
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Raw HTML in the file is escaped, not parsed: markdown files arrive with downloads, and the preview
|
||||||
|
* renders on the API's origin. `validateLink` (on by default) refuses javascript:, vbscript:, file:,
|
||||||
|
* and non-image data: URLs. DOMPurify runs anyway, so neither guard is the only one.
|
||||||
|
*/
|
||||||
|
const markdown = new MarkdownIt({html: false, linkify: true});
|
||||||
|
|
||||||
|
// A URL with a scheme (https:, mailto:, ...) points somewhere other than the media directory.
|
||||||
|
const URL_WITH_SCHEME = /^[a-z][a-z0-9+.-]*:/i;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Resolve a URL written in a markdown file against the file's own media URL, the way a browser
|
||||||
|
* would resolve it against a document in that directory.
|
||||||
|
*
|
||||||
|
* Returns the URL unchanged if it is not relative, or null if it climbs out of the media directory;
|
||||||
|
* only media is served relative to a file.
|
||||||
|
*/
|
||||||
|
function resolveRelativeURL(url, fileURL) {
|
||||||
|
if (!url || URL_WITH_SCHEME.test(url) || url.startsWith('/') || url.startsWith('#')) {
|
||||||
|
return url;
|
||||||
|
}
|
||||||
|
const resolved = new URL(url, new URL(fileURL, window.location.origin));
|
||||||
|
if (!resolved.pathname.startsWith('/media/')) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
return resolved.pathname + resolved.search + resolved.hash;
|
||||||
|
}
|
||||||
|
|
||||||
|
function rewriteURL(token, attr, fileURL) {
|
||||||
|
const url = token.attrGet(attr);
|
||||||
|
if (url === null) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const resolved = resolveRelativeURL(url, fileURL);
|
||||||
|
if (resolved === null) {
|
||||||
|
token.attrs = token.attrs.filter(([name]) => name !== attr);
|
||||||
|
} else {
|
||||||
|
token.attrSet(attr, resolved);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function openInNewTab(token) {
|
||||||
|
const href = token.attrGet('href');
|
||||||
|
// Following a link would close the preview; a fragment stays within the document.
|
||||||
|
if (href && !href.startsWith('#')) {
|
||||||
|
token.attrSet('target', '_blank');
|
||||||
|
token.attrSet('rel', 'noopener noreferrer');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** An image the preview may load: one served by this WROLPi, or embedded in the file. */
|
||||||
|
function isLocalImage(src) {
|
||||||
|
return !src || src.startsWith('data:') || (src.startsWith('/') && !src.startsWith('//'));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Replace an image from another site with a link to it. Loading it would tell that site who is
|
||||||
|
* reading the file and when (a tracking pixel), so the reader chooses whether to follow it.
|
||||||
|
*
|
||||||
|
* Inside a link (a README badge) the image becomes the outer link's text; links cannot nest.
|
||||||
|
*/
|
||||||
|
function replaceRemoteImage(state, image, insideLink) {
|
||||||
|
const src = image.attrGet('src');
|
||||||
|
const text = new state.Token('text', '', 0);
|
||||||
|
text.content = image.content || src;
|
||||||
|
if (insideLink) {
|
||||||
|
return [text];
|
||||||
|
}
|
||||||
|
const linkOpen = new state.Token('link_open', 'a', 1);
|
||||||
|
linkOpen.attrSet('href', src);
|
||||||
|
openInNewTab(linkOpen);
|
||||||
|
return [linkOpen, text, new state.Token('link_close', 'a', -1)];
|
||||||
|
}
|
||||||
|
|
||||||
|
markdown.core.ruler.push('wrolpi_media_urls', (state) => {
|
||||||
|
const {fileURL} = state.env;
|
||||||
|
for (const token of state.tokens) {
|
||||||
|
if (!token.children) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let insideLink = false;
|
||||||
|
token.children = token.children.flatMap(child => {
|
||||||
|
if (child.type === 'image') {
|
||||||
|
rewriteURL(child, 'src', fileURL);
|
||||||
|
return isLocalImage(child.attrGet('src')) ? [child] : replaceRemoteImage(state, child, insideLink);
|
||||||
|
} else if (child.type === 'link_open') {
|
||||||
|
insideLink = true;
|
||||||
|
rewriteURL(child, 'href', fileURL);
|
||||||
|
openInNewTab(child);
|
||||||
|
} else if (child.type === 'link_close') {
|
||||||
|
insideLink = false;
|
||||||
|
}
|
||||||
|
return [child];
|
||||||
|
});
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
/** Render markdown to sanitized HTML. Relative URLs resolve against `fileURL`, the file's /media/ URL. */
|
||||||
|
export function renderMarkdown(text, fileURL) {
|
||||||
|
const html = markdown.render(text, {fileURL});
|
||||||
|
return DOMPurify.sanitize(html, {ADD_ATTR: ['target']});
|
||||||
|
}
|
||||||
|
|
||||||
|
export function isMarkdownFile(mimetype, lowerPath) {
|
||||||
|
// By suffix too, so a markdown file whose stored type is still text/plain (or a language libmagic
|
||||||
|
// guessed) is not shown raw; the 2026_10_05_1200 migration retags those rows, a refresh does not.
|
||||||
|
return mimetype.startsWith('text/markdown')
|
||||||
|
|| (mimetype.startsWith('text/') && (lowerPath.endsWith('.md') || lowerPath.endsWith('.markdown')));
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Preview a markdown file, formatted or as its raw source. */
|
||||||
|
export function MarkdownPreview({url}) {
|
||||||
|
const [formatted, setFormatted] = useLocalStorage('markdownPreviewFormatted', true);
|
||||||
|
const [text, setText] = React.useState(null);
|
||||||
|
const [error, setError] = React.useState(null);
|
||||||
|
|
||||||
|
React.useEffect(() => {
|
||||||
|
const controller = new AbortController();
|
||||||
|
setText(null);
|
||||||
|
setError(null);
|
||||||
|
fetch(url, {signal: controller.signal})
|
||||||
|
.then(response => {
|
||||||
|
if (!response.ok) {
|
||||||
|
throw new Error(`${response.status} ${response.statusText}`);
|
||||||
|
}
|
||||||
|
return response.text();
|
||||||
|
})
|
||||||
|
.then(setText)
|
||||||
|
.catch(e => {
|
||||||
|
if (e.name !== 'AbortError') {
|
||||||
|
console.error(e);
|
||||||
|
setError(e.message);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
return () => controller.abort();
|
||||||
|
}, [url]);
|
||||||
|
|
||||||
|
const html = React.useMemo(() => text === null ? null : renderMarkdown(text, url), [text, url]);
|
||||||
|
|
||||||
|
let body;
|
||||||
|
if (error) {
|
||||||
|
body = <Message kind='error' title='Could not load file'>{error}</Message>;
|
||||||
|
} else if (text === null) {
|
||||||
|
body = <Loading/>;
|
||||||
|
} else if (formatted) {
|
||||||
|
body = <div className='markdown-body' dangerouslySetInnerHTML={{__html: html}}/>;
|
||||||
|
} else {
|
||||||
|
body = <pre className='markdown-raw' data-testid='markdown-raw'>{text}</pre>;
|
||||||
|
}
|
||||||
|
|
||||||
|
return <>
|
||||||
|
<ButtonGroup>
|
||||||
|
<Button size='small' variant={formatted ? 'filled' : 'default'} onClick={() => setFormatted(true)}>
|
||||||
|
Formatted
|
||||||
|
</Button>
|
||||||
|
<Button size='small' variant={formatted ? 'default' : 'filled'} onClick={() => setFormatted(false)}>
|
||||||
|
Raw
|
||||||
|
</Button>
|
||||||
|
</ButtonGroup>
|
||||||
|
<div className='markdown-preview'>
|
||||||
|
{body}
|
||||||
|
</div>
|
||||||
|
</>
|
||||||
|
}
|
||||||
198
app/src/components/MarkdownPreview.test.js
Normal file
198
app/src/components/MarkdownPreview.test.js
Normal file
|
|
@ -0,0 +1,198 @@
|
||||||
|
import React from 'react';
|
||||||
|
import {fireEvent, screen, waitFor} from '@testing-library/react';
|
||||||
|
import {isMarkdownFile, MarkdownPreview, renderMarkdown} from './MarkdownPreview';
|
||||||
|
import {renderUI} from '../test-utils';
|
||||||
|
|
||||||
|
const FILE_URL = '/media/notes/water/storage.md';
|
||||||
|
|
||||||
|
/** Render markdown into a detached element so assertions read the DOM, not the HTML string. */
|
||||||
|
const renderToDOM = (text, fileURL = FILE_URL) => {
|
||||||
|
const div = document.createElement('div');
|
||||||
|
div.innerHTML = renderMarkdown(text, fileURL);
|
||||||
|
return div;
|
||||||
|
};
|
||||||
|
|
||||||
|
describe('renderMarkdown', () => {
|
||||||
|
test('formats headings, emphasis, lists, code, and tables', () => {
|
||||||
|
const div = renderToDOM([
|
||||||
|
'# Water',
|
||||||
|
'',
|
||||||
|
'Rotate *every* barrel.',
|
||||||
|
'',
|
||||||
|
'- one',
|
||||||
|
'- two',
|
||||||
|
'',
|
||||||
|
'```',
|
||||||
|
'boil 1 minute',
|
||||||
|
'```',
|
||||||
|
'',
|
||||||
|
'| a | b |',
|
||||||
|
'|---|---|',
|
||||||
|
'| 1 | 2 |',
|
||||||
|
].join('\n'));
|
||||||
|
|
||||||
|
expect(div.querySelector('h1').textContent).toBe('Water');
|
||||||
|
expect(div.querySelector('em').textContent).toBe('every');
|
||||||
|
expect(div.querySelectorAll('ul li')).toHaveLength(2);
|
||||||
|
expect(div.querySelector('pre code').textContent).toBe('boil 1 minute\n');
|
||||||
|
expect(div.querySelectorAll('table td')).toHaveLength(2);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('raw HTML in the file is shown as text, never parsed', () => {
|
||||||
|
const div = renderToDOM('<script>alert(1)</script>\n\n<img src=x onerror="alert(2)">');
|
||||||
|
|
||||||
|
expect(div.querySelector('script')).toBeNull();
|
||||||
|
expect(div.querySelector('img')).toBeNull();
|
||||||
|
expect(div.textContent).toContain('<script>alert(1)</script>');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('script URLs are not turned into links', () => {
|
||||||
|
const div = renderToDOM('[click](javascript:alert(1))');
|
||||||
|
|
||||||
|
expect(div.querySelector('a')).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('relative images resolve against the markdown file directory', () => {
|
||||||
|
const div = renderToDOM('\n\n');
|
||||||
|
|
||||||
|
const [pump, tank] = div.querySelectorAll('img');
|
||||||
|
expect(pump.getAttribute('src')).toBe('/media/notes/water/images/hand%20pump.png');
|
||||||
|
expect(tank.getAttribute('src')).toBe('/media/notes/tank.jpg');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('relative links resolve against the markdown file directory and open a new tab', () => {
|
||||||
|
const a = renderToDOM('[filters](filters.md#ceramic)').querySelector('a');
|
||||||
|
|
||||||
|
expect(a.getAttribute('href')).toBe('/media/notes/water/filters.md#ceramic');
|
||||||
|
expect(a.getAttribute('target')).toBe('_blank');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a relative URL that climbs out of the media directory is dropped', () => {
|
||||||
|
const div = renderToDOM('[api](../../../api/status)\n\n');
|
||||||
|
|
||||||
|
expect(div.querySelector('a').hasAttribute('href')).toBe(false);
|
||||||
|
expect(div.querySelector('img').hasAttribute('src')).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
test.each([
|
||||||
|
['https://tracker.example/pixel.gif'],
|
||||||
|
['http://tracker.example/pixel.gif'],
|
||||||
|
// Protocol-relative: starts with a slash, but loads from another host.
|
||||||
|
['//tracker.example/pixel.gif'],
|
||||||
|
])('an image from another site (%s) is not loaded, it becomes a link', (src) => {
|
||||||
|
const div = renderToDOM(``);
|
||||||
|
|
||||||
|
expect(div.querySelector('img')).toBeNull();
|
||||||
|
const a = div.querySelector('a');
|
||||||
|
expect(a.getAttribute('href')).toBe(src);
|
||||||
|
expect(a.textContent).toBe('pixel');
|
||||||
|
expect(a.getAttribute('target')).toBe('_blank');
|
||||||
|
expect(a.getAttribute('rel')).toBe('noopener noreferrer');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('an image from another site with no alt text is labeled by its URL', () => {
|
||||||
|
const a = renderToDOM('').querySelector('a');
|
||||||
|
|
||||||
|
expect(a.textContent).toBe('https://example.com/a.png');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('an image from another site inside a link becomes the link text, not a nested link', () => {
|
||||||
|
// The badge pattern common in READMEs.
|
||||||
|
const div = renderToDOM('[](https://ci.example/project)');
|
||||||
|
|
||||||
|
expect(div.querySelector('img')).toBeNull();
|
||||||
|
const links = div.querySelectorAll('a');
|
||||||
|
expect(links).toHaveLength(1);
|
||||||
|
expect(links[0].getAttribute('href')).toBe('https://ci.example/project');
|
||||||
|
expect(links[0].textContent).toBe('build status');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('media and embedded data images still load', () => {
|
||||||
|
const [media, data] = renderToDOM('\n\n')
|
||||||
|
.querySelectorAll('img');
|
||||||
|
|
||||||
|
expect(media.getAttribute('src')).toBe('/media/x/a.png');
|
||||||
|
expect(data.getAttribute('src')).toBe('data:image/png;base64,AAAA');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('external links open in a new tab without an opener', () => {
|
||||||
|
const a = renderToDOM('<https://example.com/page>').querySelector('a');
|
||||||
|
|
||||||
|
expect(a.getAttribute('href')).toBe('https://example.com/page');
|
||||||
|
expect(a.getAttribute('target')).toBe('_blank');
|
||||||
|
expect(a.getAttribute('rel')).toBe('noopener noreferrer');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('absolute and fragment URLs are left alone', () => {
|
||||||
|
const [root, fragment] = renderToDOM('[root](/files)\n\n[top](#top)').querySelectorAll('a');
|
||||||
|
|
||||||
|
expect(root.getAttribute('href')).toBe('/files');
|
||||||
|
expect(fragment.getAttribute('href')).toBe('#top');
|
||||||
|
expect(fragment.hasAttribute('target')).toBe(false);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('MarkdownPreview', () => {
|
||||||
|
const SOURCE = '# Water storage\n\nRotate *every* six months.\n';
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
window.localStorage.clear();
|
||||||
|
global.fetch = jest.fn(() => Promise.resolve({
|
||||||
|
ok: true,
|
||||||
|
text: () => Promise.resolve(SOURCE),
|
||||||
|
}));
|
||||||
|
});
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
delete global.fetch;
|
||||||
|
});
|
||||||
|
|
||||||
|
test('fetches the file and shows it formatted', async () => {
|
||||||
|
renderUI(<MarkdownPreview url={FILE_URL}/>);
|
||||||
|
|
||||||
|
const heading = await screen.findByRole('heading', {name: 'Water storage'});
|
||||||
|
expect(heading.tagName).toBe('H1');
|
||||||
|
expect(global.fetch).toHaveBeenCalledWith(FILE_URL, expect.anything());
|
||||||
|
});
|
||||||
|
|
||||||
|
test('Raw shows the unformatted source, and the choice is remembered', async () => {
|
||||||
|
const {unmount} = renderUI(<MarkdownPreview url={FILE_URL}/>);
|
||||||
|
await screen.findByRole('heading', {name: 'Water storage'});
|
||||||
|
|
||||||
|
fireEvent.click(screen.getByRole('button', {name: 'Raw'}));
|
||||||
|
|
||||||
|
expect(screen.queryByRole('heading')).toBeNull();
|
||||||
|
expect(screen.getByTestId('markdown-raw').textContent).toBe(SOURCE);
|
||||||
|
|
||||||
|
// The next preview opens in the mode the reader chose last.
|
||||||
|
unmount();
|
||||||
|
renderUI(<MarkdownPreview url={FILE_URL}/>);
|
||||||
|
await waitFor(() => expect(screen.getByTestId('markdown-raw').textContent).toBe(SOURCE));
|
||||||
|
expect(screen.queryByRole('heading')).toBeNull();
|
||||||
|
|
||||||
|
fireEvent.click(screen.getByRole('button', {name: 'Formatted'}));
|
||||||
|
expect(screen.getByRole('heading', {name: 'Water storage'})).toBeTruthy();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a failed fetch shows an error instead of loading forever', async () => {
|
||||||
|
global.fetch = jest.fn(() => Promise.resolve({ok: false, status: 404, statusText: 'Not Found'}));
|
||||||
|
|
||||||
|
renderUI(<MarkdownPreview url={FILE_URL}/>);
|
||||||
|
|
||||||
|
expect(await screen.findByText(/404 Not Found/)).toBeTruthy();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('isMarkdownFile', () => {
|
||||||
|
test.each([
|
||||||
|
['text/markdown', 'notes/a.md', true],
|
||||||
|
// A stored type from before text/markdown existed; refresh does not retag unchanged files.
|
||||||
|
['text/plain', 'notes/a.md', true],
|
||||||
|
['text/plain', 'notes/a.markdown', true],
|
||||||
|
['text/plain', 'notes/a.txt', false],
|
||||||
|
// A suffix alone is not enough; a binary file named .md is not markdown.
|
||||||
|
['application/octet-stream', 'notes/a.md', false],
|
||||||
|
])('%s %s -> %s', (mimetype, lowerPath, expected) => {
|
||||||
|
expect(isMarkdownFile(mimetype, lowerPath)).toBe(expected);
|
||||||
|
});
|
||||||
|
});
|
||||||
179
app/src/components/ModelPreview.test.js
Normal file
179
app/src/components/ModelPreview.test.js
Normal file
|
|
@ -0,0 +1,179 @@
|
||||||
|
// The 3D previews render the real loaders against the installed three. Only the WebGL renderer is
|
||||||
|
// faked (jsdom has no WebGL); parsing, meshing and framing all run, and the dimensions line is
|
||||||
|
// only shown once a model has been loaded.
|
||||||
|
import React from 'react';
|
||||||
|
import {act, screen, waitFor} from '@testing-library/react';
|
||||||
|
import {renderWithProviders} from '../test-utils';
|
||||||
|
import {modelCameraDistance, STLPreviewModal, ThreeMFPreviewModal} from './FilePreview';
|
||||||
|
import {zipSync} from 'three/examples/jsm/libs/fflate.module.js';
|
||||||
|
|
||||||
|
jest.mock('three', () => {
|
||||||
|
const actual = jest.requireActual('three');
|
||||||
|
|
||||||
|
class FakeWebGLRenderer {
|
||||||
|
constructor() {
|
||||||
|
this.domElement = global.document.createElement('canvas');
|
||||||
|
}
|
||||||
|
|
||||||
|
setClearColor() {
|
||||||
|
}
|
||||||
|
|
||||||
|
setPixelRatio() {
|
||||||
|
}
|
||||||
|
|
||||||
|
setSize() {
|
||||||
|
}
|
||||||
|
|
||||||
|
render() {
|
||||||
|
}
|
||||||
|
|
||||||
|
dispose() {
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return {...actual, WebGLRenderer: FakeWebGLRenderer};
|
||||||
|
});
|
||||||
|
|
||||||
|
// One right triangle, legs of 2 along X and 1 along Y.
|
||||||
|
const ASCII_STL = `solid ASCII
|
||||||
|
facet normal 0 0 1
|
||||||
|
outer loop
|
||||||
|
vertex 0 0 0
|
||||||
|
vertex 2 0 0
|
||||||
|
vertex 0 1 0
|
||||||
|
endloop
|
||||||
|
endfacet
|
||||||
|
endsolid
|
||||||
|
`;
|
||||||
|
|
||||||
|
function binaryStl() {
|
||||||
|
// 80-byte header, uint32 triangle count, then one 50-byte triangle: normal, three vertices.
|
||||||
|
const buffer = new ArrayBuffer(84 + 50);
|
||||||
|
const view = new DataView(buffer);
|
||||||
|
view.setUint32(80, 1, true);
|
||||||
|
const floats = [0, 0, 1, 0, 0, 0, 2, 0, 0, 0, 1, 0];
|
||||||
|
floats.forEach((value, i) => view.setFloat32(84 + i * 4, value, true));
|
||||||
|
return buffer;
|
||||||
|
}
|
||||||
|
|
||||||
|
function threeMF() {
|
||||||
|
const model = `<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<model unit="millimeter" xmlns="http://schemas.microsoft.com/3dmanufacturing/core/2015/02">
|
||||||
|
<resources>
|
||||||
|
<object id="1" type="model">
|
||||||
|
<mesh>
|
||||||
|
<vertices>
|
||||||
|
<vertex x="0" y="0" z="0"/>
|
||||||
|
<vertex x="2" y="0" z="0"/>
|
||||||
|
<vertex x="0" y="1" z="0"/>
|
||||||
|
</vertices>
|
||||||
|
<triangles>
|
||||||
|
<triangle v1="0" v2="1" v3="2"/>
|
||||||
|
</triangles>
|
||||||
|
</mesh>
|
||||||
|
</object>
|
||||||
|
</resources>
|
||||||
|
<build>
|
||||||
|
<item objectid="1"/>
|
||||||
|
</build>
|
||||||
|
</model>`;
|
||||||
|
const rels = `<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">
|
||||||
|
<Relationship Target="/3D/3dmodel.model" Id="rel0"
|
||||||
|
Type="http://schemas.microsoft.com/3dmanufacturing/2013/01/3dmodel"/>
|
||||||
|
</Relationships>`;
|
||||||
|
// Copy into this realm's Uint8Array: fflate tells files from folders with `instanceof`, and
|
||||||
|
// Node's TextEncoder returns a Uint8Array from another realm than jsdom's.
|
||||||
|
const bytes = (text) => Uint8Array.from(new TextEncoder().encode(text));
|
||||||
|
const zipped = zipSync({'_rels/.rels': bytes(rels), '3D/3dmodel.model': bytes(model)});
|
||||||
|
return zipped.buffer.slice(zipped.byteOffset, zipped.byteOffset + zipped.byteLength);
|
||||||
|
}
|
||||||
|
|
||||||
|
function serve(body) {
|
||||||
|
const bytes = typeof body === 'string' ? new TextEncoder().encode(body).buffer : body;
|
||||||
|
global.fetch = jest.fn(async () => ({
|
||||||
|
ok: true,
|
||||||
|
status: 200,
|
||||||
|
statusText: 'OK',
|
||||||
|
headers: new Headers(),
|
||||||
|
arrayBuffer: async () => bytes,
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
global.ResizeObserver = class {
|
||||||
|
observe() {
|
||||||
|
}
|
||||||
|
|
||||||
|
disconnect() {
|
||||||
|
}
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
delete global.fetch;
|
||||||
|
});
|
||||||
|
|
||||||
|
// The triangle spans 2 along X and 1 along Y, and is flat in Z; its bounding radius is half the
|
||||||
|
// box diagonal. Which extent reads as Height depends on how the viewer orients the model.
|
||||||
|
async function expectTriangleDimensions({height, length}) {
|
||||||
|
await waitFor(() => expect(screen.getByText(/Width:/)).toBeInTheDocument(), {timeout: 5000});
|
||||||
|
const line = screen.getByText(/Width:/).closest('div').textContent;
|
||||||
|
expect(line).toContain('Width: 2.00');
|
||||||
|
expect(line).toContain(`Height: ${height}`);
|
||||||
|
expect(line).toContain(`Length: ${length}`);
|
||||||
|
expect(line).toContain('Bounding Radius: 1.12');
|
||||||
|
}
|
||||||
|
|
||||||
|
// Models are Z-up, so the flat triangle lies down: its Y extent reads as Length.
|
||||||
|
const TRIANGLE_DIMENSIONS = {height: '0.00', length: '1.00'};
|
||||||
|
|
||||||
|
describe('STL preview', () => {
|
||||||
|
it('loads an ASCII STL file', async () => {
|
||||||
|
serve(ASCII_STL);
|
||||||
|
await act(async () => renderWithProviders(<STLPreviewModal previewFile={{path: 'models/part.stl'}}/>));
|
||||||
|
await expectTriangleDimensions(TRIANGLE_DIMENSIONS);
|
||||||
|
// three's FileLoader fetches a Request.
|
||||||
|
expect(global.fetch.mock.calls[0][0].url).toContain('/media/models/part.stl');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('loads a binary STL file', async () => {
|
||||||
|
serve(binaryStl());
|
||||||
|
await act(async () => renderWithProviders(<STLPreviewModal previewFile={{path: 'models/part.stl'}}/>));
|
||||||
|
await expectTriangleDimensions(TRIANGLE_DIMENSIONS);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('3MF preview', () => {
|
||||||
|
it('loads a 3MF file', async () => {
|
||||||
|
serve(threeMF());
|
||||||
|
await act(async () => renderWithProviders(<ThreeMFPreviewModal previewFile={{path: 'models/part.3mf'}}/>));
|
||||||
|
await expectTriangleDimensions(TRIANGLE_DIMENSIONS);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('modelCameraDistance', () => {
|
||||||
|
// Half the angle a sphere of `radius` fills when seen from `distance`.
|
||||||
|
const sphereHalfAngle = (radius, distance) => Math.asin(radius / distance);
|
||||||
|
const halfVertical = (fov) => (fov * Math.PI) / 360;
|
||||||
|
const halfHorizontal = (fov, aspect) => Math.atan(Math.tan(halfVertical(fov)) * aspect);
|
||||||
|
|
||||||
|
it.each([
|
||||||
|
['a wide viewer', 2],
|
||||||
|
['a square viewer', 1],
|
||||||
|
['a tall, narrow viewer', 0.5],
|
||||||
|
])('fits the whole bounding sphere in %s, with little to spare', (_, aspect) => {
|
||||||
|
const radius = 24;
|
||||||
|
const fov = 50;
|
||||||
|
const distance = modelCameraDistance(radius, fov, aspect);
|
||||||
|
const narrowest = Math.min(halfVertical(fov), halfHorizontal(fov, aspect));
|
||||||
|
// Every point of the sphere is in view...
|
||||||
|
expect(sphereHalfAngle(radius, distance)).toBeLessThanOrEqual(narrowest);
|
||||||
|
// ...and the sphere fills at least 90% of the narrower field of view.
|
||||||
|
expect(sphereHalfAngle(radius, distance)).toBeGreaterThan(narrowest * 0.9);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('stands back in proportion to the model', () => {
|
||||||
|
expect(modelCameraDistance(10, 50, 1.5)).toBeCloseTo(modelCameraDistance(1, 50, 1.5) * 10);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
@ -21,6 +21,8 @@ import {HELP_VIEWER_URI, NAME, navColorHexMap} from "./Vars";
|
||||||
import {useOverflowNav} from "../hooks/useOverflowNav";
|
import {useOverflowNav} from "../hooks/useOverflowNav";
|
||||||
import {defaultNavColor, navBarStyle, useNavColors} from "../themes/navColors";
|
import {defaultNavColor, navBarStyle, useNavColors} from "../themes/navColors";
|
||||||
import _ from "lodash";
|
import _ from "lodash";
|
||||||
|
import {BookmarksMenuContents, EDIT_BOOKMARKS_PATH} from "./Bookmarks";
|
||||||
|
import {VPN_SETTINGS_PATH} from "./admin/VpnSection";
|
||||||
|
|
||||||
function updateFavicon(colorName) {
|
function updateFavicon(colorName) {
|
||||||
// Fall back to violet if invalid color
|
// Fall back to violet if invalid color
|
||||||
|
|
@ -60,16 +62,24 @@ const allLinks = [
|
||||||
{text: 'Files', to: '/files', key: 'files'},
|
{text: 'Files', to: '/files', key: 'files'},
|
||||||
{text: 'Playlists', to: '/playlists', key: 'playlists'},
|
{text: 'Playlists', to: '/playlists', key: 'playlists'},
|
||||||
{text: 'Zim', to: '/zim', key: 'zim'},
|
{text: 'Zim', to: '/zim', key: 'zim'},
|
||||||
|
{text: 'Repos', to: '/repos', key: 'repos'},
|
||||||
{text: 'Inventory', to: '/inventory', key: 'inventory'},
|
{text: 'Inventory', to: '/inventory', key: 'inventory'},
|
||||||
// No `end` on these two: a tab stays current for the pages beneath it, and `end` would
|
// No `end` on these two: a tab stays current for the pages beneath it, and `end` would
|
||||||
// drop the mark the moment either grows a sub-page.
|
// drop the mark the moment either grows a sub-page.
|
||||||
{to: '/more/calculators', text: 'Calculators', key: 'calculators'},
|
{to: '/more/calculators', text: 'Calculators', key: 'calculators'},
|
||||||
|
// The user's bookmarks, read from BookmarksContext when rendered. No `to`: it is a
|
||||||
|
// menu, and its items are not sections of the app.
|
||||||
|
{text: 'Bookmarks', key: 'bookmarks', bookmarks: true},
|
||||||
{text: 'Flasher', to: '/flasher', key: 'flasher'},
|
{text: 'Flasher', to: '/flasher', key: 'flasher'},
|
||||||
|
{text: 'Extension', to: '/extension', key: 'extension'},
|
||||||
{to: '/more/statistics', text: 'Statistics', key: 'statistics'},
|
{to: '/more/statistics', text: 'Statistics', key: 'statistics'},
|
||||||
];
|
];
|
||||||
|
|
||||||
function MenuLink({link}) {
|
function MenuLink({link}) {
|
||||||
// A top-level tab rendered directly in the bar (not inside a dropdown).
|
// A top-level tab rendered directly in the bar (not inside a dropdown).
|
||||||
|
if (link.bookmarks) {
|
||||||
|
return <BookmarksDropdown link={link}/>
|
||||||
|
}
|
||||||
if (link.links) {
|
if (link.links) {
|
||||||
return <DropdownLinks link={link}/>
|
return <DropdownLinks link={link}/>
|
||||||
}
|
}
|
||||||
|
|
@ -85,13 +95,31 @@ function MenuLink({link}) {
|
||||||
</NavLink>
|
</NavLink>
|
||||||
}
|
}
|
||||||
|
|
||||||
function DropdownMenuItem({link}) {
|
function DropdownMenuItem({link, nested = true}) {
|
||||||
// An item inside a Menu.Dropdown: the mobile hamburger menu, or the desktop
|
// An item inside a Menu.Dropdown: the mobile hamburger menu, or the desktop
|
||||||
// "More" overflow menu.
|
// "More" overflow menu. `nested` allows flyout submenus, which the hamburger
|
||||||
|
// declines: a flyout opens on hover, and a phone has none.
|
||||||
|
if (link.bookmarks) {
|
||||||
|
if (nested) {
|
||||||
|
return <Menu.Sub>
|
||||||
|
<Menu.Sub.Target>
|
||||||
|
<Menu.Sub.Item>{link.text}</Menu.Sub.Item>
|
||||||
|
</Menu.Sub.Target>
|
||||||
|
<Menu.Sub.Dropdown>
|
||||||
|
<BookmarksMenuContents nested/>
|
||||||
|
</Menu.Sub.Dropdown>
|
||||||
|
</Menu.Sub>
|
||||||
|
}
|
||||||
|
return <React.Fragment>
|
||||||
|
<Menu.Divider/>
|
||||||
|
<Menu.Label>{link.text}</Menu.Label>
|
||||||
|
<BookmarksMenuContents nested={false}/>
|
||||||
|
<Menu.Divider/>
|
||||||
|
</React.Fragment>
|
||||||
|
}
|
||||||
if (link.links) {
|
if (link.links) {
|
||||||
// Mantine's Menu does not nest submenus without extra plumbing; a labelled,
|
// A labelled, indented group stands in for a submenu here. No current data uses
|
||||||
// indented group stands in for one. No current data uses this path (no
|
// this path (no allLinks entry has its own `links`).
|
||||||
// allLinks entry has its own `links`).
|
|
||||||
return <React.Fragment>
|
return <React.Fragment>
|
||||||
<Menu.Label>{link.text}</Menu.Label>
|
<Menu.Label>{link.text}</Menu.Label>
|
||||||
{link.links.map(l => <DropdownMenuItem key={l.key} link={l}/>)}
|
{link.links.map(l => <DropdownMenuItem key={l.key} link={l}/>)}
|
||||||
|
|
@ -141,6 +169,11 @@ NavDropdownTrigger.displayName = 'NavDropdownTrigger';
|
||||||
* the hooks that would answer it cannot be called in a loop.
|
* the hooks that would answer it cannot be called in a loop.
|
||||||
*/
|
*/
|
||||||
export const isLinkActive = (pathname, link) => {
|
export const isLinkActive = (pathname, link) => {
|
||||||
|
// The Bookmarks menu owns only its editor page: a bookmark pointing at /videos does
|
||||||
|
// not make the menu own the Videos section.
|
||||||
|
if (link.bookmarks) {
|
||||||
|
return pathname === EDIT_BOOKMARKS_PATH || pathname.startsWith(`${EDIT_BOOKMARKS_PATH}/`);
|
||||||
|
}
|
||||||
// An off-site link (Help) is never the current section.
|
// An off-site link (Help) is never the current section.
|
||||||
if (!link.to || /^[a-z]+:\/\//i.test(link.to)) return false;
|
if (!link.to || /^[a-z]+:\/\//i.test(link.to)) return false;
|
||||||
const to = link.to.length > 1 ? link.to.replace(/\/+$/, '') : link.to;
|
const to = link.to.length > 1 ? link.to.replace(/\/+$/, '') : link.to;
|
||||||
|
|
@ -175,6 +208,24 @@ function DropdownLinks({link}) {
|
||||||
</Menu>
|
</Menu>
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The Bookmarks tab: a dropdown that opens on hover as well as on click, holding the
|
||||||
|
* user's bookmarks and the link to edit them. Marked current on the editor page only
|
||||||
|
* (see isLinkActive).
|
||||||
|
*/
|
||||||
|
function BookmarksDropdown({link}) {
|
||||||
|
const {pathname} = useLocation();
|
||||||
|
const holdsCurrent = isLinkActive(pathname, link);
|
||||||
|
return <Menu position='bottom-start' withinPortal trigger='click-hover' openDelay={100} closeDelay={200}>
|
||||||
|
<Menu.Target>
|
||||||
|
<NavDropdownTrigger text={link.text} className={holdsCurrent ? 'active' : undefined}/>
|
||||||
|
</Menu.Target>
|
||||||
|
<Menu.Dropdown>
|
||||||
|
<BookmarksMenuContents nested/>
|
||||||
|
</Menu.Dropdown>
|
||||||
|
</Menu>
|
||||||
|
}
|
||||||
|
|
||||||
function MobileMenu({links}) {
|
function MobileMenu({links}) {
|
||||||
// The mobile hamburger menu: an icon-only trigger holding every link.
|
// The mobile hamburger menu: an icon-only trigger holding every link.
|
||||||
return <Menu position='bottom-end' withinPortal>
|
return <Menu position='bottom-end' withinPortal>
|
||||||
|
|
@ -182,7 +233,7 @@ function MobileMenu({links}) {
|
||||||
<IconButton icon={IconMenu2} label='Menu' variant='subtle'/>
|
<IconButton icon={IconMenu2} label='Menu' variant='subtle'/>
|
||||||
</Menu.Target>
|
</Menu.Target>
|
||||||
<Menu.Dropdown>
|
<Menu.Dropdown>
|
||||||
{links.map(link => <DropdownMenuItem key={link.key} link={link}/>)}
|
{links.map(link => <DropdownMenuItem key={link.key} link={link} nested={false}/>)}
|
||||||
</Menu.Dropdown>
|
</Menu.Dropdown>
|
||||||
</Menu>
|
</Menu>
|
||||||
}
|
}
|
||||||
|
|
@ -425,11 +476,25 @@ export function NavBar() {
|
||||||
</Tooltip>;
|
</Tooltip>;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Torrents only reach the Internet through the VPN; while it is not connected they are stopped. Shown only when
|
||||||
|
// there are torrents, so a WROLPi which does not use them never sees it.
|
||||||
|
const torrents = status && status.torrents;
|
||||||
|
let torrentsIcon;
|
||||||
|
if (torrents && torrents.count > 0 && torrents.vpn_state !== 'connected') {
|
||||||
|
const label = torrents.vpn_state === 'wrol_mode'
|
||||||
|
? 'Torrents are stopped: WROL Mode is on'
|
||||||
|
: 'Torrents are stopped: the VPN is not connected';
|
||||||
|
const icon = <Icon data-testid='torrentsVpnIcon' name='share' size='large'
|
||||||
|
style={{color: colorVar(lowWarningColor)}} label={label}/>;
|
||||||
|
torrentsIcon = <Tooltip label={label}><Link to={VPN_SETTINGS_PATH}>{icon}</Link></Tooltip>;
|
||||||
|
}
|
||||||
|
|
||||||
const icons = <React.Fragment>
|
const icons = <React.Fragment>
|
||||||
<NavIconWrapper>{apiDownIcon}</NavIconWrapper>
|
<NavIconWrapper>{apiDownIcon}</NavIconWrapper>
|
||||||
<NavIconWrapper>{processingIcon}</NavIconWrapper>
|
<NavIconWrapper>{processingIcon}</NavIconWrapper>
|
||||||
<NavIconWrapper>{upgradeIcon}</NavIconWrapper>
|
<NavIconWrapper>{upgradeIcon}</NavIconWrapper>
|
||||||
<NavIconWrapper>{driveHealthIcon}</NavIconWrapper>
|
<NavIconWrapper>{driveHealthIcon}</NavIconWrapper>
|
||||||
|
<NavIconWrapper>{torrentsIcon}</NavIconWrapper>
|
||||||
<NavIconWrapper>{powerIcon}</NavIconWrapper>
|
<NavIconWrapper>{powerIcon}</NavIconWrapper>
|
||||||
<NavIconWrapper>{warningIcon}</NavIconWrapper>
|
<NavIconWrapper>{warningIcon}</NavIconWrapper>
|
||||||
<NavIconWrapper><ShareButton asIcon/></NavIconWrapper>
|
<NavIconWrapper><ShareButton asIcon/></NavIconWrapper>
|
||||||
|
|
|
||||||
|
|
@ -231,3 +231,126 @@ describe('NavBar current tab', () => {
|
||||||
expect(ruleBody('\\.mantine-Menu-item\\.active')).toMatch(/background:|font-weight:/);
|
expect(ruleBody('\\.mantine-Menu-item\\.active')).toMatch(/background:|font-weight:/);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
describe('NavBar bookmarks', () => {
|
||||||
|
const {BookmarksContext} = require('../contexts/BookmarksContext');
|
||||||
|
const bookmarks = [
|
||||||
|
{id: 1, name: 'Channels', url: '/videos/channel', new_tab: false},
|
||||||
|
{id: 2, name: 'Services', children: [{id: 3, name: 'Jellyfin', url: ':8096/', new_tab: true}]},
|
||||||
|
];
|
||||||
|
const renderWithBookmarks = (route, nodes) => render(<NavBar/>, {
|
||||||
|
route,
|
||||||
|
withMedia: true,
|
||||||
|
contexts: [
|
||||||
|
[FileWorkerStatusContext, fileWorkerStatus],
|
||||||
|
[BookmarksContext, {bookmarks: nodes, error: null, refresh: jest.fn()}],
|
||||||
|
],
|
||||||
|
});
|
||||||
|
|
||||||
|
it('Extension follows Flasher', () => {
|
||||||
|
renderNav('/');
|
||||||
|
const texts = [...document.querySelectorAll('#global_navbar .wrolpi-navbar-link')]
|
||||||
|
.map(el => el.textContent.trim());
|
||||||
|
expect(texts[texts.indexOf('Flasher') + 1]).toBe('Extension');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('sits between Calculators and Flasher', () => {
|
||||||
|
renderNav('/');
|
||||||
|
const texts = [...document.querySelectorAll('#global_navbar .wrolpi-navbar-link')]
|
||||||
|
.map(el => el.textContent.trim());
|
||||||
|
const at = texts.indexOf('Bookmarks');
|
||||||
|
expect(at).toBeGreaterThan(0);
|
||||||
|
expect(texts[at - 1]).toBe('Calculators');
|
||||||
|
expect(texts[at + 1]).toBe('Flasher');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('opens on click with the bookmarks, a directory flyout, and the edit link', async () => {
|
||||||
|
useRealRects();
|
||||||
|
renderWithBookmarks('/', bookmarks);
|
||||||
|
|
||||||
|
await userEvent.click(screen.getByRole('button', {name: /Bookmarks/}));
|
||||||
|
|
||||||
|
const channels = await screen.findByRole('menuitem', {name: 'Channels'});
|
||||||
|
expect(channels).toHaveAttribute('href', '/videos/channel');
|
||||||
|
expect(channels).not.toHaveAttribute('target');
|
||||||
|
// A directory is a submenu; its bookmarks appear once it is hovered.
|
||||||
|
expect(screen.queryByRole('menuitem', {name: 'Jellyfin'})).not.toBeInTheDocument();
|
||||||
|
await userEvent.hover(screen.getByRole('menuitem', {name: 'Services'}));
|
||||||
|
// `hidden`: the flyout is placed by floating-ui, which jsdom cannot lay out, so it
|
||||||
|
// stays hidden to accessibility queries even though it has rendered.
|
||||||
|
const jellyfin = await screen.findByRole('menuitem', {name: 'Jellyfin', hidden: true});
|
||||||
|
expect(jellyfin).toHaveAttribute('href', `${window.location.protocol}//${window.location.hostname}:8096/`);
|
||||||
|
expect(jellyfin).toHaveAttribute('target', '_blank');
|
||||||
|
expect(screen.getByRole('menuitem', {name: 'Edit bookmarks', hidden: true})).toHaveAttribute('href', '/more/bookmarks');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('offers the edit link even with no bookmarks, so the feature can be found', async () => {
|
||||||
|
useRealRects();
|
||||||
|
renderWithBookmarks('/', []);
|
||||||
|
|
||||||
|
await userEvent.click(screen.getByRole('button', {name: /Bookmarks/}));
|
||||||
|
|
||||||
|
expect(await screen.findByRole('menuitem', {name: 'Edit bookmarks'})).toBeInTheDocument();
|
||||||
|
expect(screen.getAllByRole('menuitem')).toHaveLength(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('is marked current on the editor page, and never for a bookmark pointing at a section', () => {
|
||||||
|
renderWithBookmarks('/more/bookmarks', bookmarks);
|
||||||
|
expect(screen.getByRole('button', {name: /Bookmarks/})).toHaveClass('active');
|
||||||
|
expect(currentTab()).toEqual([]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('marks More when the editor page is folded inside it', () => {
|
||||||
|
useBarWidth(200);
|
||||||
|
renderWithBookmarks('/more/bookmarks', bookmarks);
|
||||||
|
expect(screen.getByRole('button', {name: /More/})).toHaveClass('active');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('does not own the section a bookmark points at', () => {
|
||||||
|
renderWithBookmarks('/videos/channel', bookmarks);
|
||||||
|
expect(screen.getByRole('button', {name: /Bookmarks/})).not.toHaveClass('active');
|
||||||
|
expect(currentTab()).toEqual(['Videos']);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('lists bookmarks as a labelled group in the mobile menu', async () => {
|
||||||
|
useViewport('mobile');
|
||||||
|
useRealRects();
|
||||||
|
renderWithBookmarks('/', bookmarks);
|
||||||
|
|
||||||
|
await userEvent.click(screen.getByRole('button', {name: 'Menu'}));
|
||||||
|
|
||||||
|
expect(await screen.findByRole('menuitem', {name: 'Channels'})).toBeInTheDocument();
|
||||||
|
// No flyout on a phone: the directory's bookmarks are listed directly.
|
||||||
|
expect(screen.getByRole('menuitem', {name: 'Jellyfin'})).toBeInTheDocument();
|
||||||
|
expect(screen.getByText('Services')).toBeInTheDocument();
|
||||||
|
expect(screen.getByRole('menuitem', {name: 'Edit bookmarks'})).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('NavBar torrents warning', () => {
|
||||||
|
const {statusFixture} = require('../test-fixtures');
|
||||||
|
const renderWithTorrents = (torrents) => render(<NavBar/>, {
|
||||||
|
route: '/',
|
||||||
|
withMedia: true,
|
||||||
|
status: {status: statusFixture({torrents})},
|
||||||
|
contexts: [[FileWorkerStatusContext, fileWorkerStatus]],
|
||||||
|
});
|
||||||
|
|
||||||
|
it('warns when torrents exist but the VPN they use is not connected', () => {
|
||||||
|
renderWithTorrents({count: 2, vpn_state: 'connecting', running: true});
|
||||||
|
expect(screen.getAllByLabelText('Torrents are stopped: the VPN is not connected').length).toBeGreaterThan(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('says when WROL Mode stopped them', () => {
|
||||||
|
renderWithTorrents({count: 1, vpn_state: 'wrol_mode', running: true});
|
||||||
|
expect(screen.getAllByLabelText('Torrents are stopped: WROL Mode is on').length).toBeGreaterThan(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('is silent while the VPN is connected, or without torrents', () => {
|
||||||
|
const {unmount} = renderWithTorrents({count: 2, vpn_state: 'connected', running: true});
|
||||||
|
expect(screen.queryByTestId('torrentsVpnIcon')).not.toBeInTheDocument();
|
||||||
|
unmount();
|
||||||
|
renderWithTorrents({count: 0, vpn_state: 'stopped', running: false});
|
||||||
|
expect(screen.queryByTestId('torrentsVpnIcon')).not.toBeInTheDocument();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
|
||||||
174
app/src/components/OtherSearchView.test.js
Normal file
174
app/src/components/OtherSearchView.test.js
Normal file
|
|
@ -0,0 +1,174 @@
|
||||||
|
import React from 'react';
|
||||||
|
import {act, render, screen} from '../test-utils';
|
||||||
|
import {OtherSearchView} from './Search';
|
||||||
|
import {searchChannels, searchCollections, searchRepos} from '../api';
|
||||||
|
|
||||||
|
// What the search page's Other tab shows for each state of useSearchChannels. "No Channels"
|
||||||
|
// must only appear once the server has confirmed there are none.
|
||||||
|
|
||||||
|
jest.mock('../api', () => ({
|
||||||
|
...jest.requireActual('../api'),
|
||||||
|
searchChannels: jest.fn(),
|
||||||
|
searchCollections: jest.fn(),
|
||||||
|
searchRepos: jest.fn(),
|
||||||
|
}));
|
||||||
|
|
||||||
|
const NO_CHANNELS = /No Channels/;
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
searchChannels.mockReset();
|
||||||
|
searchRepos.mockReset();
|
||||||
|
searchRepos.mockResolvedValue({repos: [], total: 0});
|
||||||
|
searchCollections.mockReset();
|
||||||
|
searchCollections.mockResolvedValue({collections: []});
|
||||||
|
});
|
||||||
|
|
||||||
|
test('pending: shows a loader, not "No Channels"', () => {
|
||||||
|
searchChannels.mockReturnValue(new Promise(() => {
|
||||||
|
}));
|
||||||
|
const {container} = render(<OtherSearchView loading={false}/>);
|
||||||
|
expect(container.querySelector('.wrolpi-loading')).toBeInTheDocument();
|
||||||
|
expect(screen.queryByText(NO_CHANNELS)).not.toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('failed: shows an error, not "No Channels"', async () => {
|
||||||
|
searchChannels.mockResolvedValue(undefined);
|
||||||
|
const spy = jest.spyOn(console, 'error').mockImplementation(() => {
|
||||||
|
});
|
||||||
|
try {
|
||||||
|
render(<OtherSearchView loading={false}/>);
|
||||||
|
await act(async () => {
|
||||||
|
});
|
||||||
|
expect(screen.getByText(/Could not fetch the channels/)).toBeInTheDocument();
|
||||||
|
expect(screen.queryByText(NO_CHANNELS)).not.toBeInTheDocument();
|
||||||
|
} finally {
|
||||||
|
spy.mockRestore();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test('empty: shows "No Channels"', async () => {
|
||||||
|
searchChannels.mockResolvedValue({channels: []});
|
||||||
|
render(<OtherSearchView loading={false}/>);
|
||||||
|
await act(async () => {
|
||||||
|
});
|
||||||
|
expect(screen.getByText(NO_CHANNELS)).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('loaded: lists the channels', async () => {
|
||||||
|
searchChannels.mockResolvedValue({channels: [{id: 1, name: 'Cooking'}]});
|
||||||
|
render(<OtherSearchView loading={false}/>);
|
||||||
|
await act(async () => {
|
||||||
|
});
|
||||||
|
expect(screen.getByText('Cooking')).toBeInTheDocument();
|
||||||
|
expect(screen.queryByText(NO_CHANNELS)).not.toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('Repos', () => {
|
||||||
|
test('pending: the Repos section loads while Channels are shown', async () => {
|
||||||
|
searchChannels.mockResolvedValue({channels: []});
|
||||||
|
searchRepos.mockReturnValue(new Promise(() => {
|
||||||
|
}));
|
||||||
|
const {container} = render(<OtherSearchView loading={false}/>);
|
||||||
|
await act(async () => {
|
||||||
|
});
|
||||||
|
expect(screen.getByText(NO_CHANNELS)).toBeInTheDocument();
|
||||||
|
expect(container.querySelector('.wrolpi-loading')).toBeInTheDocument();
|
||||||
|
expect(screen.queryByText('No Repos')).not.toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('empty: shows "No Repos"', async () => {
|
||||||
|
searchChannels.mockResolvedValue({channels: []});
|
||||||
|
render(<OtherSearchView loading={false}/>);
|
||||||
|
await act(async () => {
|
||||||
|
});
|
||||||
|
expect(screen.getByText('No Repos')).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('failed: shows an error only in the Repos section', async () => {
|
||||||
|
searchChannels.mockResolvedValue({channels: [{id: 1, name: 'Cooking'}]});
|
||||||
|
searchRepos.mockRejectedValue(new Error('boom'));
|
||||||
|
const spy = jest.spyOn(console, 'error').mockImplementation(() => {
|
||||||
|
});
|
||||||
|
try {
|
||||||
|
render(<OtherSearchView loading={false}/>);
|
||||||
|
await act(async () => {
|
||||||
|
});
|
||||||
|
expect(screen.getByText('Cooking')).toBeInTheDocument();
|
||||||
|
expect(screen.getByText(/Could not fetch the repos/)).toBeInTheDocument();
|
||||||
|
} finally {
|
||||||
|
spy.mockRestore();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test('loaded: lists repos by the search, with their README headline', async () => {
|
||||||
|
searchChannels.mockResolvedValue({channels: []});
|
||||||
|
searchRepos.mockResolvedValue({
|
||||||
|
total: 1, repos: [{
|
||||||
|
id: 7, name: 'kiwix-tools', tag_name: null,
|
||||||
|
// The server escapes the README; only the highlight is markup.
|
||||||
|
readme_headline: 'Serve <b>Zim</b> files <script>',
|
||||||
|
}],
|
||||||
|
});
|
||||||
|
const searchParams = new URLSearchParams('q=zim&tag=Software');
|
||||||
|
const {container} = render(<OtherSearchView loading={false}/>, {query: {searchParams}});
|
||||||
|
await act(async () => {
|
||||||
|
});
|
||||||
|
expect(searchRepos).toHaveBeenCalledWith('zim', ['Software']);
|
||||||
|
expect(screen.getByText('kiwix-tools').closest('a')).toHaveAttribute('href', '/repos/7');
|
||||||
|
expect(container.querySelector('u').textContent).toBe('Zim');
|
||||||
|
expect(container.querySelector('script')).toBeNull();
|
||||||
|
expect(screen.getByText(/files <script>/)).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
// Domains and Playlists are Collections searched by kind.
|
||||||
|
describe.each([
|
||||||
|
['domain', 'Domains', 'example.com', '/archives?domain=example.com'],
|
||||||
|
['playlist', 'Playlists', 'Road Trip', '/playlists/3'],
|
||||||
|
])('%s Collections', (kind, title, name, href) => {
|
||||||
|
const collectionsOf = (wanted, collections) => (k) => Promise.resolve({collections: k === wanted ? collections : []});
|
||||||
|
|
||||||
|
test(`empty: shows "No ${title}"`, async () => {
|
||||||
|
searchChannels.mockResolvedValue({channels: []});
|
||||||
|
render(<OtherSearchView loading={false}/>, {query: {searchParams: new URLSearchParams('q=nothing')}});
|
||||||
|
await act(async () => {
|
||||||
|
});
|
||||||
|
expect(screen.getByText(`No ${title}`)).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('nothing to search by: shows none without fetching', async () => {
|
||||||
|
searchChannels.mockResolvedValue({channels: []});
|
||||||
|
render(<OtherSearchView loading={false}/>);
|
||||||
|
await act(async () => {
|
||||||
|
});
|
||||||
|
expect(screen.getByText(`No ${title}`)).toBeInTheDocument();
|
||||||
|
expect(searchCollections).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
test(`failed: shows an error only in the ${title} section`, async () => {
|
||||||
|
searchChannels.mockResolvedValue({channels: [{id: 1, name: 'Cooking'}]});
|
||||||
|
searchCollections.mockImplementation(k => k === kind ? Promise.reject(new Error('boom')) : Promise.resolve({collections: []}));
|
||||||
|
const spy = jest.spyOn(console, 'error').mockImplementation(() => {
|
||||||
|
});
|
||||||
|
try {
|
||||||
|
render(<OtherSearchView loading={false}/>, {query: {searchParams: new URLSearchParams('q=x')}});
|
||||||
|
await act(async () => {
|
||||||
|
});
|
||||||
|
expect(screen.getByText('Cooking')).toBeInTheDocument();
|
||||||
|
expect(screen.getByText(new RegExp(`Could not fetch the ${title.toLowerCase()}`))).toBeInTheDocument();
|
||||||
|
} finally {
|
||||||
|
spy.mockRestore();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test('loaded: lists them by the search and tags, linked', async () => {
|
||||||
|
searchChannels.mockResolvedValue({channels: []});
|
||||||
|
searchCollections.mockImplementation(collectionsOf(kind, [{id: 3, name, kind, tag_name: null}]));
|
||||||
|
const searchParams = new URLSearchParams('q=road&tag=News');
|
||||||
|
render(<OtherSearchView loading={false}/>, {query: {searchParams}});
|
||||||
|
await act(async () => {
|
||||||
|
});
|
||||||
|
expect(searchCollections).toHaveBeenCalledWith(kind, ['News'], 'road');
|
||||||
|
expect(screen.getByText(name).closest('a')).toHaveAttribute('href', href);
|
||||||
|
});
|
||||||
|
});
|
||||||
37
app/src/components/QRCode.js
Normal file
37
app/src/components/QRCode.js
Normal file
|
|
@ -0,0 +1,37 @@
|
||||||
|
// QR codes for a phone to scan: the code itself, a modal which shows one, and a button which opens it.
|
||||||
|
import React, {useState} from "react";
|
||||||
|
import QRCode from "react-qr-code";
|
||||||
|
import {IconButton, Modal} from "./ui";
|
||||||
|
|
||||||
|
// A scannable QR code of `value`. `style` adds to (or replaces) the white field around it.
|
||||||
|
export function QRCodeImage({value, size = 300, style}) {
|
||||||
|
// `media`: a QR code needs real black-on-white contrast to scan, so its white field is filtered
|
||||||
|
// as a unit by night mode rather than sitting on screen as a lit panel.
|
||||||
|
return <div className='media'
|
||||||
|
style={{display: 'inline-block', backgroundColor: '#ffffff', padding: '1em', ...style}}>
|
||||||
|
<QRCode value={value} size={size} title={value}/>
|
||||||
|
</div>;
|
||||||
|
}
|
||||||
|
|
||||||
|
// A modal which shows a QR code of `value`, then `children` (if any) beneath it.
|
||||||
|
export function QRCodeModal({open, onClose, header, value, children}) {
|
||||||
|
return <Modal size='small' open={open} onClose={onClose} closeIcon>
|
||||||
|
{header && <Modal.Header>{header}</Modal.Header>}
|
||||||
|
<Modal.Content>
|
||||||
|
<QRCodeImage value={value}/>
|
||||||
|
{children}
|
||||||
|
</Modal.Content>
|
||||||
|
</Modal>;
|
||||||
|
}
|
||||||
|
|
||||||
|
// A QR code icon button which opens a QRCodeModal of `value`. `label` names the button; the modal's
|
||||||
|
// header defaults to it.
|
||||||
|
export function QRCodeButton({value, label, header, color, size, children}) {
|
||||||
|
const [open, setOpen] = useState(false);
|
||||||
|
return <>
|
||||||
|
<IconButton icon='qrcode' label={label} color={color} size={size} onClick={() => setOpen(true)}/>
|
||||||
|
<QRCodeModal open={open} onClose={() => setOpen(false)} header={header ?? label} value={value}>
|
||||||
|
{children}
|
||||||
|
</QRCodeModal>
|
||||||
|
</>;
|
||||||
|
}
|
||||||
39
app/src/components/QRCode.test.js
Normal file
39
app/src/components/QRCode.test.js
Normal file
|
|
@ -0,0 +1,39 @@
|
||||||
|
import React from 'react';
|
||||||
|
import {fireEvent, screen, waitFor, within} from '@testing-library/react';
|
||||||
|
import {renderWithProviders} from '../test-utils';
|
||||||
|
import {QRCodeButton, QRCodeImage} from './QRCode';
|
||||||
|
|
||||||
|
describe('QRCode', () => {
|
||||||
|
it('draws the code on a white field which night mode filters as a unit', () => {
|
||||||
|
renderWithProviders(<QRCodeImage value='https://example.com/a' size={128}/>);
|
||||||
|
// react-qr-code titles its svg with the value.
|
||||||
|
const svg = screen.getByTitle('https://example.com/a').closest('svg');
|
||||||
|
expect(svg).toHaveAttribute('height', '128');
|
||||||
|
const field = svg.parentElement;
|
||||||
|
expect(field).toHaveClass('media');
|
||||||
|
expect(field).toHaveStyle({backgroundColor: '#ffffff'});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('opens a modal of the code from its button, then closes it', async () => {
|
||||||
|
renderWithProviders(<QRCodeButton value='WIFI:S:x;;' label='Show the code' header='Scan this'>
|
||||||
|
<p>Beneath the code</p>
|
||||||
|
</QRCodeButton>);
|
||||||
|
expect(screen.queryByRole('dialog')).not.toBeInTheDocument();
|
||||||
|
|
||||||
|
fireEvent.click(screen.getByRole('button', {name: 'Show the code'}));
|
||||||
|
const dialog = await screen.findByRole('dialog');
|
||||||
|
expect(within(dialog).getByText('Scan this')).toBeInTheDocument();
|
||||||
|
expect(within(dialog).getByTitle('WIFI:S:x;;')).toBeInTheDocument();
|
||||||
|
expect(within(dialog).getByText('Beneath the code')).toBeInTheDocument();
|
||||||
|
|
||||||
|
fireEvent.keyDown(dialog, {key: 'Escape'});
|
||||||
|
await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument());
|
||||||
|
});
|
||||||
|
|
||||||
|
it('titles the modal with the button label when no header is given', async () => {
|
||||||
|
renderWithProviders(<QRCodeButton value='x' label='Join the hotspot'/>);
|
||||||
|
fireEvent.click(screen.getByRole('button', {name: 'Join the hotspot'}));
|
||||||
|
const dialog = await screen.findByRole('dialog');
|
||||||
|
expect(within(dialog).getByText('Join the hotspot')).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
});
|
||||||
1062
app/src/components/Repos.js
Normal file
1062
app/src/components/Repos.js
Normal file
File diff suppressed because it is too large
Load diff
394
app/src/components/Repos.test.js
Normal file
394
app/src/components/Repos.test.js
Normal file
|
|
@ -0,0 +1,394 @@
|
||||||
|
import React from 'react';
|
||||||
|
import {Route, Routes} from 'react-router';
|
||||||
|
import {act, fireEvent, render, screen, waitFor, within} from '../test-utils';
|
||||||
|
import {
|
||||||
|
RepoEditPage,
|
||||||
|
RepoImportPage,
|
||||||
|
repoNameFromURL,
|
||||||
|
RepoNewPage,
|
||||||
|
ReposPage,
|
||||||
|
RepoViewPage,
|
||||||
|
safeRepoHref,
|
||||||
|
} from './Repos';
|
||||||
|
import {
|
||||||
|
createRepo, deleteRepo, fetchRepos, getFile, getRepo, getRepoLog, getRepoTree, importRepo, inspectRepoImport,
|
||||||
|
updateRepo,
|
||||||
|
} from '../api';
|
||||||
|
import {FilePreviewContext} from './FilePreview';
|
||||||
|
|
||||||
|
jest.mock('../api', () => ({
|
||||||
|
...jest.requireActual('../api'),
|
||||||
|
createRepo: jest.fn(),
|
||||||
|
deleteRepo: jest.fn(),
|
||||||
|
fetchRepos: jest.fn(),
|
||||||
|
getFile: jest.fn(),
|
||||||
|
getRepo: jest.fn(),
|
||||||
|
getRepoLog: jest.fn(),
|
||||||
|
getRepoTree: jest.fn(),
|
||||||
|
importRepo: jest.fn(),
|
||||||
|
inspectRepoImport: jest.fn(),
|
||||||
|
updateRepo: jest.fn(),
|
||||||
|
}));
|
||||||
|
|
||||||
|
// The directory picker searches the server; picking a directory is all these specs need.
|
||||||
|
jest.mock('./Common', () => ({
|
||||||
|
...jest.requireActual('./Common'),
|
||||||
|
DirectorySearch: ({onSelect}) => <button type='button' onClick={() => onSelect('code/kiwix-tools')}>
|
||||||
|
Pick directory
|
||||||
|
</button>,
|
||||||
|
}));
|
||||||
|
|
||||||
|
// The README is fetched from the media server; its rendering is MarkdownPreview's own spec.
|
||||||
|
jest.mock('./MarkdownPreview', () => ({
|
||||||
|
...jest.requireActual('./MarkdownPreview'),
|
||||||
|
MarkdownPreview: ({url}) => <div data-testid='markdown-preview'>{url}</div>,
|
||||||
|
}));
|
||||||
|
|
||||||
|
const repoFixture = (overrides = {}) => ({
|
||||||
|
id: 1, collection_id: 10, name: 'kiwix-tools', tag_name: null, description: null,
|
||||||
|
url: 'https://github.com/kiwix/kiwix-tools', mode: 'full', branch: null, default_branch: 'main',
|
||||||
|
head_sha: '3f9c2a1e7b', head_message: 'Fix the mimetype', head_date: '2026-09-30T14:02:00Z',
|
||||||
|
size: 1000, directory: 'repos/kiwix-tools', frequency: 604800, download_error: null,
|
||||||
|
...overrides,
|
||||||
|
});
|
||||||
|
|
||||||
|
const treeFixture = {
|
||||||
|
path: '',
|
||||||
|
readme_path: 'README.md',
|
||||||
|
entries: [
|
||||||
|
{name: 'src', path: 'src', is_dir: true, size: null},
|
||||||
|
{name: 'README.md', path: 'README.md', is_dir: false, size: 120},
|
||||||
|
],
|
||||||
|
};
|
||||||
|
|
||||||
|
const flush = () => act(async () => {
|
||||||
|
});
|
||||||
|
|
||||||
|
beforeEach(() => jest.clearAllMocks());
|
||||||
|
|
||||||
|
describe('safeRepoHref', () => {
|
||||||
|
it('only links https URLs', () => {
|
||||||
|
expect(safeRepoHref('https://github.com/a/b')).toBe('https://github.com/a/b');
|
||||||
|
expect(safeRepoHref('javascript:alert(1)')).toBeNull();
|
||||||
|
expect(safeRepoHref('http://github.com/a/b')).toBeNull();
|
||||||
|
expect(safeRepoHref('file:///etc/passwd')).toBeNull();
|
||||||
|
expect(safeRepoHref('not a url')).toBeNull();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('repoNameFromURL', () => {
|
||||||
|
it('is the last path segment, without .git or a branch', () => {
|
||||||
|
expect(repoNameFromURL('https://github.com/kiwix/kiwix-tools.git')).toBe('kiwix-tools');
|
||||||
|
expect(repoNameFromURL('https://github.com/kiwix/kiwix-tools/tree/dev')).toBe('kiwix-tools');
|
||||||
|
expect(repoNameFromURL('https://gitlab.com/group/sub/project/')).toBe('project');
|
||||||
|
expect(repoNameFromURL('nope')).toBe('');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('ReposPage', () => {
|
||||||
|
it('lists repos, linking each to its page', async () => {
|
||||||
|
fetchRepos.mockResolvedValue([
|
||||||
|
repoFixture(),
|
||||||
|
repoFixture({id: 2, name: 'gone', download_error: 'git ls-remote failed', head_sha: null}),
|
||||||
|
]);
|
||||||
|
render(<ReposPage/>, {route: '/repos'});
|
||||||
|
await flush();
|
||||||
|
expect(screen.getAllByText('kiwix-tools')[0].closest('a')).toHaveAttribute('href', '/repos/1');
|
||||||
|
expect(screen.getAllByText('gone')[0].closest('a')).toHaveAttribute('href', '/repos/2');
|
||||||
|
expect(screen.getByText('New Repo').closest('a')).toHaveAttribute('href', '/repos/new');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('shows a repo which is never updated', async () => {
|
||||||
|
fetchRepos.mockResolvedValue([repoFixture({frequency: 0})]);
|
||||||
|
render(<ReposPage/>, {route: '/repos'});
|
||||||
|
await flush();
|
||||||
|
expect(screen.getAllByText('Never').length).toBeGreaterThan(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('explains an empty list', async () => {
|
||||||
|
fetchRepos.mockResolvedValue([]);
|
||||||
|
render(<ReposPage/>, {route: '/repos'});
|
||||||
|
await flush();
|
||||||
|
expect(screen.getByText(/No repos yet/)).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
function renderViewPage({repo, tree = treeFixture, query = {}, setPreviewFile = jest.fn()} = {}) {
|
||||||
|
getRepo.mockResolvedValue(repo);
|
||||||
|
getRepoTree.mockResolvedValue(tree);
|
||||||
|
return render(<Routes><Route path='/repos/:repoId' element={<RepoViewPage/>}/></Routes>, {
|
||||||
|
route: '/repos/1',
|
||||||
|
query,
|
||||||
|
contexts: [[FilePreviewContext, {setPreviewFile}]],
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('RepoViewPage', () => {
|
||||||
|
it('shows the latest commit, the files, and the README', async () => {
|
||||||
|
renderViewPage({repo: repoFixture()});
|
||||||
|
await flush();
|
||||||
|
expect(getRepoTree).toHaveBeenCalledWith('1', '');
|
||||||
|
expect(screen.getByText('3f9c2a1')).toBeInTheDocument();
|
||||||
|
expect(screen.getByText('Fix the mimetype')).toBeInTheDocument();
|
||||||
|
expect(screen.getByText('main')).toBeInTheDocument();
|
||||||
|
expect(screen.getByText('(default)')).toBeInTheDocument();
|
||||||
|
expect(screen.getByText('https://github.com/kiwix/kiwix-tools').closest('a'))
|
||||||
|
.toHaveAttribute('href', 'https://github.com/kiwix/kiwix-tools');
|
||||||
|
expect(screen.getByText('src')).toBeInTheDocument();
|
||||||
|
expect(screen.getByTestId('markdown-preview')).toHaveTextContent('/media/repos/kiwix-tools/README.md');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('opens a directory through the URL, and a file in the preview', async () => {
|
||||||
|
const updateQuery = jest.fn();
|
||||||
|
const setPreviewFile = jest.fn();
|
||||||
|
const file = {path: 'repos/kiwix-tools/README.md', mimetype: 'text/markdown', size: 120};
|
||||||
|
getFile.mockResolvedValue(file);
|
||||||
|
renderViewPage({repo: repoFixture(), query: {updateQuery}, setPreviewFile});
|
||||||
|
await flush();
|
||||||
|
|
||||||
|
fireEvent.click(screen.getByText('src'));
|
||||||
|
expect(updateQuery).toHaveBeenCalledWith({path: 'src'}, false);
|
||||||
|
|
||||||
|
fireEvent.click(screen.getAllByText('README.md')[0]);
|
||||||
|
await flush();
|
||||||
|
expect(getFile).toHaveBeenCalledWith('repos/kiwix-tools/README.md', true);
|
||||||
|
expect(setPreviewFile).toHaveBeenCalledWith(file);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('lists the directory in the URL, with a way back up', async () => {
|
||||||
|
const tree = {path: 'src/lib', readme_path: null, entries: [{name: 'a.c', path: 'src/lib/a.c', is_dir: false}]};
|
||||||
|
const updateQuery = jest.fn();
|
||||||
|
renderViewPage({repo: repoFixture(), tree, query: {searchParams: new URLSearchParams('path=src/lib'), updateQuery}});
|
||||||
|
await flush();
|
||||||
|
expect(getRepoTree).toHaveBeenCalledWith('1', 'src/lib');
|
||||||
|
expect(screen.queryByTestId('markdown-preview')).not.toBeInTheDocument();
|
||||||
|
|
||||||
|
fireEvent.click(screen.getByText('..'));
|
||||||
|
expect(updateQuery).toHaveBeenCalledWith({path: 'src'}, false);
|
||||||
|
// The breadcrumb's root.
|
||||||
|
fireEvent.click(screen.getAllByText('kiwix-tools').find(i => i.tagName === 'BUTTON'));
|
||||||
|
expect(updateQuery).toHaveBeenCalledWith({path: ''}, false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('offers a ZIP of the files', async () => {
|
||||||
|
renderViewPage({repo: repoFixture()});
|
||||||
|
await flush();
|
||||||
|
const link = screen.getByText('Download ZIP').closest('a');
|
||||||
|
expect(link).toHaveAttribute('href', expect.stringMatching(/\/api\/repos\/1\/archive\.zip$/));
|
||||||
|
expect(link).toHaveAttribute('download');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('shows the history instead of the files', async () => {
|
||||||
|
getRepoLog.mockResolvedValue({
|
||||||
|
total: 51,
|
||||||
|
commits: [{sha: 'abcdef1234', author: 'Ada', date: '2026-09-30T14:02:00Z', message: 'Fix the mimetype'}],
|
||||||
|
});
|
||||||
|
const updateQuery = jest.fn();
|
||||||
|
renderViewPage({repo: repoFixture(), query: {searchParams: new URLSearchParams('view=history'), updateQuery}});
|
||||||
|
await flush();
|
||||||
|
|
||||||
|
expect(getRepoLog).toHaveBeenCalledWith(1, 0, 50);
|
||||||
|
expect(getRepoTree).not.toHaveBeenCalled();
|
||||||
|
expect(screen.getByText('51 commits')).toBeInTheDocument();
|
||||||
|
expect(screen.getByText('abcdef1')).toBeInTheDocument();
|
||||||
|
expect(screen.getByText('Ada')).toBeInTheDocument();
|
||||||
|
|
||||||
|
// The next page is appended.
|
||||||
|
getRepoLog.mockResolvedValue({
|
||||||
|
total: 51,
|
||||||
|
commits: [{sha: '0123456789', author: 'Ben', date: '2026-09-01T00:00:00Z', message: 'Older'}],
|
||||||
|
});
|
||||||
|
fireEvent.click(screen.getByText('Load more'));
|
||||||
|
await flush();
|
||||||
|
expect(getRepoLog).toHaveBeenLastCalledWith(1, 1, 50);
|
||||||
|
expect(screen.getByText('abcdef1')).toBeInTheDocument();
|
||||||
|
expect(screen.getByText('0123456')).toBeInTheDocument();
|
||||||
|
|
||||||
|
fireEvent.click(screen.getByText('Files'));
|
||||||
|
expect(updateQuery).toHaveBeenCalledWith({view: null}, false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('explains a repo that is not downloaded yet', async () => {
|
||||||
|
renderViewPage({repo: repoFixture({head_sha: null, head_message: null, head_date: null})});
|
||||||
|
await flush();
|
||||||
|
expect(screen.getByText('Not downloaded yet')).toBeInTheDocument();
|
||||||
|
expect(getRepoTree).not.toHaveBeenCalled();
|
||||||
|
expect(screen.queryByText('Download ZIP')).not.toBeInTheDocument();
|
||||||
|
expect(screen.queryByText('History')).not.toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('keeps showing the files when the last update failed', async () => {
|
||||||
|
renderViewPage({repo: repoFixture({download_error: 'Traceback...\nDownloadError: git ls-remote failed (128)'})});
|
||||||
|
await flush();
|
||||||
|
expect(screen.getByText('The last update failed')).toBeInTheDocument();
|
||||||
|
expect(screen.getByText(/git ls-remote failed/)).toBeInTheDocument();
|
||||||
|
expect(screen.getByText('src')).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('says a repo which is never updated is only updated on request', async () => {
|
||||||
|
renderViewPage({repo: repoFixture({frequency: 0, download_error: 'git ls-remote failed (128)'})});
|
||||||
|
await flush();
|
||||||
|
expect(screen.getByText('The last update failed')).toBeInTheDocument();
|
||||||
|
expect(screen.getByText(/never updated automatically/)).toBeInTheDocument();
|
||||||
|
expect(screen.queryByText(/will be tried again/)).not.toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('never links an upstream that is not https', async () => {
|
||||||
|
renderViewPage({repo: repoFixture({url: 'javascript:alert(1)'})});
|
||||||
|
await flush();
|
||||||
|
expect(screen.queryByText('javascript:alert(1)')).not.toBeInTheDocument();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('RepoNewPage', () => {
|
||||||
|
it('adds a repo, then opens it', async () => {
|
||||||
|
createRepo.mockResolvedValue(repoFixture({id: 5}));
|
||||||
|
render(<Routes>
|
||||||
|
<Route path='/repos/new' element={<RepoNewPage/>}/>
|
||||||
|
<Route path='/repos/:repoId' element={<div>repo page</div>}/>
|
||||||
|
</Routes>, {route: '/repos/new'});
|
||||||
|
|
||||||
|
const add = screen.getByText('Add Repo').closest('button');
|
||||||
|
expect(add).toBeDisabled();
|
||||||
|
fireEvent.change(screen.getByLabelText(/URL/), {target: {value: 'git@github.com:a/b'}});
|
||||||
|
expect(add).toBeDisabled();
|
||||||
|
expect(screen.getByText('Must be an https:// URL')).toBeInTheDocument();
|
||||||
|
|
||||||
|
fireEvent.change(screen.getByLabelText(/URL/), {target: {value: 'https://github.com/kiwix/kiwix-tools'}});
|
||||||
|
expect(screen.getByPlaceholderText('kiwix-tools')).toBeInTheDocument();
|
||||||
|
fireEvent.change(screen.getByLabelText('Branch'), {target: {value: ' dev '}});
|
||||||
|
fireEvent.click(screen.getByText('Pick directory'));
|
||||||
|
fireEvent.click(add);
|
||||||
|
await flush();
|
||||||
|
|
||||||
|
expect(createRepo).toHaveBeenCalledWith({
|
||||||
|
url: 'https://github.com/kiwix/kiwix-tools', name: null, tag_name: null, frequency: 604800,
|
||||||
|
mode: 'full', branch: 'dev', submodules: false, description: null, directory: 'code/kiwix-tools',
|
||||||
|
});
|
||||||
|
expect(screen.getByText('repo page')).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('RepoEditPage', () => {
|
||||||
|
function renderEditPage(repo) {
|
||||||
|
getRepo.mockResolvedValue(repo);
|
||||||
|
return render(<Routes>
|
||||||
|
<Route path='/repos/:repoId/edit' element={<RepoEditPage/>}/>
|
||||||
|
<Route path='/repos' element={<div>repos page</div>}/>
|
||||||
|
</Routes>, {route: '/repos/1/edit'});
|
||||||
|
}
|
||||||
|
|
||||||
|
it('saves the settings', async () => {
|
||||||
|
updateRepo.mockResolvedValue(repoFixture());
|
||||||
|
renderEditPage(repoFixture({branch: 'dev', description: 'Tools'}));
|
||||||
|
await flush();
|
||||||
|
expect(screen.getByLabelText('Branch')).toHaveValue('dev');
|
||||||
|
|
||||||
|
expect(screen.getByLabelText('Include submodules')).not.toBeChecked();
|
||||||
|
|
||||||
|
fireEvent.change(screen.getByLabelText('Branch'), {target: {value: ''}});
|
||||||
|
fireEvent.click(screen.getByLabelText('Include submodules'));
|
||||||
|
fireEvent.click(screen.getByText('Save'));
|
||||||
|
await flush();
|
||||||
|
expect(updateRepo).toHaveBeenCalledWith('1', {
|
||||||
|
description: 'Tools', frequency: 604800, mode: 'full', branch: '', submodules: true,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('keeps a repo which is never updated', async () => {
|
||||||
|
updateRepo.mockResolvedValue(repoFixture({frequency: 0}));
|
||||||
|
renderEditPage(repoFixture({frequency: 0}));
|
||||||
|
await flush();
|
||||||
|
expect(screen.getByDisplayValue('Never')).toBeInTheDocument();
|
||||||
|
fireEvent.click(screen.getByText('Save'));
|
||||||
|
await flush();
|
||||||
|
expect(updateRepo).toHaveBeenCalledWith('1', expect.objectContaining({frequency: 0}));
|
||||||
|
});
|
||||||
|
|
||||||
|
it('deletes the repo, and its files only when asked', async () => {
|
||||||
|
deleteRepo.mockResolvedValue(undefined);
|
||||||
|
renderEditPage(repoFixture());
|
||||||
|
await flush();
|
||||||
|
|
||||||
|
fireEvent.click(screen.getByText('Delete'));
|
||||||
|
const dialog = await screen.findByRole('dialog');
|
||||||
|
fireEvent.click(within(dialog).getByLabelText(/Also delete its files/));
|
||||||
|
fireEvent.click(within(dialog).getByText('Delete'));
|
||||||
|
await flush();
|
||||||
|
expect(deleteRepo).toHaveBeenCalledWith('1', true);
|
||||||
|
expect(screen.getByText('repos page')).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('RepoImportPage', () => {
|
||||||
|
const inspection = (overrides = {}) => ({
|
||||||
|
directory: 'code/kiwix-tools', origin: 'git@github.com:kiwix/kiwix-tools.git',
|
||||||
|
url: 'https://github.com/kiwix/kiwix-tools', name: 'kiwix-tools', branch: 'main',
|
||||||
|
head_sha: 'abcdef1234', head_message: 'Local work', head_date: '2026-09-30T14:02:00Z', local_commits: 2,
|
||||||
|
shallow: false, ignored: false,
|
||||||
|
...overrides,
|
||||||
|
});
|
||||||
|
|
||||||
|
function renderImportPage() {
|
||||||
|
return render(<Routes>
|
||||||
|
<Route path='/repos/import' element={<RepoImportPage/>}/>
|
||||||
|
<Route path='/repos/:repoId' element={<div>repo page</div>}/>
|
||||||
|
</Routes>, {route: '/repos/import'});
|
||||||
|
}
|
||||||
|
|
||||||
|
it('inspects the directory, warns about local commits, and imports once confirmed', async () => {
|
||||||
|
inspectRepoImport.mockResolvedValue({inspection: inspection()});
|
||||||
|
importRepo.mockResolvedValue(repoFixture({id: 9}));
|
||||||
|
renderImportPage();
|
||||||
|
|
||||||
|
fireEvent.click(screen.getByText('Pick directory'));
|
||||||
|
expect(await screen.findByText('2 commits are not on the remote')).toBeInTheDocument();
|
||||||
|
expect(inspectRepoImport).toHaveBeenCalledWith('code/kiwix-tools', '', null, '');
|
||||||
|
// Inspected again with the URL the import will use.
|
||||||
|
await waitFor(() => expect(inspectRepoImport).toHaveBeenCalledWith('code/kiwix-tools', '', null,
|
||||||
|
'https://github.com/kiwix/kiwix-tools'));
|
||||||
|
expect(screen.getByText('git@github.com:kiwix/kiwix-tools.git')).toBeInTheDocument();
|
||||||
|
expect(screen.getByText(/Its files are indexed/)).toBeInTheDocument();
|
||||||
|
// The URL comes from the origin.
|
||||||
|
expect(screen.getByLabelText(/^URL/)).toHaveValue('https://github.com/kiwix/kiwix-tools');
|
||||||
|
|
||||||
|
const button = screen.getByText('Import').closest('button');
|
||||||
|
expect(button).toBeDisabled();
|
||||||
|
fireEvent.click(screen.getByLabelText(/I understand/));
|
||||||
|
expect(button).toBeEnabled();
|
||||||
|
fireEvent.click(button);
|
||||||
|
await flush();
|
||||||
|
|
||||||
|
expect(importRepo).toHaveBeenCalledWith({
|
||||||
|
directory: 'code/kiwix-tools', confirm: true, url: 'https://github.com/kiwix/kiwix-tools', name: null,
|
||||||
|
tag_name: null, frequency: 604800, mode: 'full', branch: null, submodules: false,
|
||||||
|
});
|
||||||
|
expect(screen.getByText('repo page')).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('asks for the URL when the clone has no https origin', async () => {
|
||||||
|
inspectRepoImport.mockResolvedValue({inspection: inspection({origin: null, url: null, local_commits: 0})});
|
||||||
|
renderImportPage();
|
||||||
|
fireEvent.click(screen.getByText('Pick directory'));
|
||||||
|
expect(await screen.findByText(/no https:\/\/ origin/)).toBeInTheDocument();
|
||||||
|
fireEvent.click(screen.getByLabelText(/I understand/));
|
||||||
|
expect(screen.getByText('Import').closest('button')).toBeDisabled();
|
||||||
|
fireEvent.change(screen.getByLabelText(/^URL/), {target: {value: 'https://github.com/kiwix/kiwix-tools'}});
|
||||||
|
expect(screen.getByText('Import').closest('button')).toBeEnabled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('explains a directory which cannot be imported', async () => {
|
||||||
|
inspectRepoImport.mockResolvedValue({error: 'code/kiwix-tools is not a git clone'});
|
||||||
|
renderImportPage();
|
||||||
|
fireEvent.click(screen.getByText('Pick directory'));
|
||||||
|
expect(await screen.findByText('code/kiwix-tools is not a git clone')).toBeInTheDocument();
|
||||||
|
expect(screen.queryByText('Import')).not.toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('says when the files are not indexed', async () => {
|
||||||
|
inspectRepoImport.mockResolvedValue({inspection: inspection({ignored: true})});
|
||||||
|
renderImportPage();
|
||||||
|
fireEvent.click(screen.getByText('Pick directory'));
|
||||||
|
expect(await screen.findByText(/Its files are not indexed/)).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
@ -1,17 +1,27 @@
|
||||||
import React, {useState} from "react";
|
import React, {useState} from "react";
|
||||||
import {Link, Route, Routes, useLocation, useNavigate} from "react-router";
|
import {Link, Route, Routes, useLocation, useNavigate} from "react-router";
|
||||||
import {FilesSearchView, SearchViewButton} from "./Files";
|
import {FilesSearchView, SearchViewButton} from "./Files";
|
||||||
import {useLatestRequest, usePages, useSearchChannels, useSearchDate, useSearchDeep, useSearchFilter} from "../hooks/customHooks";
|
import {
|
||||||
|
useLatestRequest,
|
||||||
|
usePages,
|
||||||
|
useSearchChannels,
|
||||||
|
useSearchDate,
|
||||||
|
useSearchDeep,
|
||||||
|
useSearchFilter,
|
||||||
|
useSearchCollections,
|
||||||
|
useSearchRepos,
|
||||||
|
} from "../hooks/customHooks";
|
||||||
import {ShortcutHint} from "./ShortcutHint";
|
import {ShortcutHint} from "./ShortcutHint";
|
||||||
import {ZimSearchView} from "./Zim";
|
import {ZimSearchView} from "./Zim";
|
||||||
import {MapSearchView} from "./MapSearchView";
|
import {MapSearchView} from "./MapSearchView";
|
||||||
import {searchEstimateFiles, searchEstimateMap, searchEstimateOthers, searchEstimateZims, searchSuggestions} from "../api";
|
import {searchEstimateFiles, searchEstimateMap, searchEstimateOthers, searchEstimateZims, searchSuggestions} from "../api";
|
||||||
import {filterToMimetypes, fuzzyMatch, normalizeEstimate, SearchResultsInput, TabLinks} from "./Common";
|
import {ErrorMessage, filterToMimetypes, fuzzyMatch, normalizeEstimate, SearchResultsInput, TabLinks} from "./Common";
|
||||||
import _ from "lodash";
|
import _ from "lodash";
|
||||||
import {TagsContext} from "../Tags";
|
import {TagsContext} from "../Tags";
|
||||||
import {Accordion, Header, Icon, Label, Loading, Panel, Stack} from "./ui";
|
import {Accordion, Header, Icon, Label, Loading, Panel, Stack} from "./ui";
|
||||||
import {QueryContext} from "../contexts/contexts";
|
import {QueryContext} from "../contexts/contexts";
|
||||||
import {KeyboardShortcutsContext} from "../contexts/KeyboardShortcutsContext";
|
import {KeyboardShortcutsContext} from "../contexts/KeyboardShortcutsContext";
|
||||||
|
import {HeadlineText} from "./Headline";
|
||||||
|
|
||||||
const SUGGESTED_APPS = [
|
const SUGGESTED_APPS = [
|
||||||
{location: '/admin', title: 'Downloads', description: 'View and control your downloads'},
|
{location: '/admin', title: 'Downloads', description: 'View and control your downloads'},
|
||||||
|
|
@ -39,11 +49,6 @@ const SUGGESTED_APPS = [
|
||||||
{location: '/videos/channel', title: 'Channels', description: 'View the Channels of your Videos'},
|
{location: '/videos/channel', title: 'Channels', description: 'View the Channels of your Videos'},
|
||||||
{location: '/zim', title: 'Zim', description: 'View your Zims'},
|
{location: '/zim', title: 'Zim', description: 'View your Zims'},
|
||||||
{location: '/zim/manage', title: 'Manage Zim', description: 'Manage your Zims'},
|
{location: '/zim/manage', title: 'Manage Zim', description: 'Manage your Zims'},
|
||||||
{
|
|
||||||
location: '/more/calculators?calc=temperature',
|
|
||||||
title: 'Temperature Calculator',
|
|
||||||
description: 'Convert Celsius, Fahrenheit, Kelvin'
|
|
||||||
},
|
|
||||||
{
|
{
|
||||||
location: '/more/calculators?calc=electrical',
|
location: '/more/calculators?calc=electrical',
|
||||||
title: 'Electrical Calculator',
|
title: 'Electrical Calculator',
|
||||||
|
|
@ -81,7 +86,9 @@ export const useSearch = (defaultLimit = 48, totalPages = 0, emptySearch = false
|
||||||
// archive/video/doc/etc.
|
// archive/video/doc/etc.
|
||||||
const model_ = searchParams.get('model') || model;
|
const model_ = searchParams.get('model') || model;
|
||||||
|
|
||||||
const anySearch = (!datesIsEmpty) || searchStr || (activeTags && activeTags.length > 0) || filter || model;
|
const anyTag = searchParams.get('anyTag') === 'true';
|
||||||
|
const anySearch = (!datesIsEmpty) || searchStr || (activeTags && activeTags.length > 0) || anyTag || filter
|
||||||
|
|| model;
|
||||||
const isEmpty = !anySearch;
|
const isEmpty = !anySearch;
|
||||||
|
|
||||||
const setSearchStr = (value) => {
|
const setSearchStr = (value) => {
|
||||||
|
|
@ -111,7 +118,6 @@ export const useSearch = (defaultLimit = 48, totalPages = 0, emptySearch = false
|
||||||
setTags(newTags);
|
setTags(newTags);
|
||||||
}
|
}
|
||||||
|
|
||||||
const anyTag = searchParams.get('anyTag') === 'true';
|
|
||||||
const setAnyTag = (value) => {
|
const setAnyTag = (value) => {
|
||||||
updateQuery({tag: [], anyTag: value ? 'true' : null});
|
updateQuery({tag: [], anyTag: value ? 'true' : null});
|
||||||
}
|
}
|
||||||
|
|
@ -131,12 +137,15 @@ export const useSearch = (defaultLimit = 48, totalPages = 0, emptySearch = false
|
||||||
}
|
}
|
||||||
|
|
||||||
export function useSuggestions(searchStr, tagNames, filter, anyTag) {
|
export function useSuggestions(searchStr, tagNames, filter, anyTag) {
|
||||||
|
// The general groups are null until the suggestion request returns: an empty list means the
|
||||||
|
// server found none, and the dropdown may say "No results" only for that.
|
||||||
const defaultSuggestions = {
|
const defaultSuggestions = {
|
||||||
fileGroups: [],
|
fileGroups: [],
|
||||||
channels: [],
|
channels: null,
|
||||||
domains: [],
|
domains: null,
|
||||||
authors: [],
|
authors: null,
|
||||||
subjects: [],
|
subjects: null,
|
||||||
|
repos: null,
|
||||||
zimsEstimates: [],
|
zimsEstimates: [],
|
||||||
}
|
}
|
||||||
const [suggestions, setSuggestions] = React.useState(defaultSuggestions);
|
const [suggestions, setSuggestions] = React.useState(defaultSuggestions);
|
||||||
|
|
@ -150,7 +159,8 @@ export function useSuggestions(searchStr, tagNames, filter, anyTag) {
|
||||||
const {data: mapData, sendRequest: sendMapRequest, loading: mapLoading} = useLatestRequest(500);
|
const {data: mapData, sendRequest: sendMapRequest, loading: mapLoading} = useLatestRequest(500);
|
||||||
|
|
||||||
React.useEffect(() => {
|
React.useEffect(() => {
|
||||||
if (searchStr || (tagNames && tagNames.length > 0)) {
|
const hasTags = tagNames && tagNames.length > 0;
|
||||||
|
if (searchStr || hasTags || anyTag) {
|
||||||
const mimetypes = filterToMimetypes(filter);
|
const mimetypes = filterToMimetypes(filter);
|
||||||
setSuggestions(defaultSuggestions);
|
setSuggestions(defaultSuggestions);
|
||||||
if (searchStr && searchStr.length > 0) {
|
if (searchStr && searchStr.length > 0) {
|
||||||
|
|
@ -160,8 +170,11 @@ export function useSuggestions(searchStr, tagNames, filter, anyTag) {
|
||||||
}
|
}
|
||||||
// The files estimate always uses deep search server-side, so users know results are possible.
|
// The files estimate always uses deep search server-side, so users know results are possible.
|
||||||
sendFilesRequest(async () => await searchEstimateFiles(searchStr, tagNames, mimetypes, months, dateRange, anyTag));
|
sendFilesRequest(async () => await searchEstimateFiles(searchStr, tagNames, mimetypes, months, dateRange, anyTag));
|
||||||
|
if (searchStr || hasTags) {
|
||||||
|
// Zims and the Other tab have no "any tag" search; they need a search string or tag names.
|
||||||
sendZimRequest(async () => await searchEstimateZims(searchStr, tagNames));
|
sendZimRequest(async () => await searchEstimateZims(searchStr, tagNames));
|
||||||
sendOtherRequest(async () => await searchEstimateOthers(tagNames));
|
sendOtherRequest(async () => await searchEstimateOthers(tagNames, searchStr));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}, [
|
}, [
|
||||||
searchStr,
|
searchStr,
|
||||||
|
|
@ -183,6 +196,7 @@ export function useSuggestions(searchStr, tagNames, filter, anyTag) {
|
||||||
domains: generalData.domains,
|
domains: generalData.domains,
|
||||||
authors: generalData.authors,
|
authors: generalData.authors,
|
||||||
subjects: generalData.subjects,
|
subjects: generalData.subjects,
|
||||||
|
repos: generalData.repos,
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
@ -310,6 +324,13 @@ export function useSearchSuggestions(defaultSearchStr, defaultTagNames, anyTag)
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
if (newSuggestions.repos && newSuggestions.repos.length > 0) {
|
||||||
|
results.repos = {
|
||||||
|
name: 'Repos', results: newSuggestions.repos.map(i => {
|
||||||
|
return {type: 'repo', title: i.name, id: i.id, location: `/repos/${i.id}`}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
if (newSuggestions.authors && newSuggestions.authors.length > 0) {
|
if (newSuggestions.authors && newSuggestions.authors.length > 0) {
|
||||||
results.authors = {
|
results.authors = {
|
||||||
name: 'Authors', results: newSuggestions.authors.map(i => {
|
name: 'Authors', results: newSuggestions.authors.map(i => {
|
||||||
|
|
@ -401,10 +422,11 @@ export function useSearchSuggestions(defaultSearchStr, defaultTagNames, anyTag)
|
||||||
zims: zimSum,
|
zims: zimSum,
|
||||||
otherSum: otherSum,
|
otherSum: otherSum,
|
||||||
mapPlaces: newSuggestions.mapPlaces || 0,
|
mapPlaces: newSuggestions.mapPlaces || 0,
|
||||||
channels: newSuggestions.channels.length,
|
channels: newSuggestions.channels?.length,
|
||||||
domains: newSuggestions.domains.length,
|
domains: newSuggestions.domains?.length,
|
||||||
authors: newSuggestions.authors?.length,
|
authors: newSuggestions.authors?.length,
|
||||||
subjects: newSuggestions.subjects?.length,
|
subjects: newSuggestions.subjects?.length,
|
||||||
|
repos: newSuggestions.repos?.length,
|
||||||
tags: matchingTags?.length,
|
tags: matchingTags?.length,
|
||||||
apps: matchingApps?.length,
|
apps: matchingApps?.length,
|
||||||
});
|
});
|
||||||
|
|
@ -541,31 +563,99 @@ function SearchChannelPreview({channel}) {
|
||||||
</div>
|
</div>
|
||||||
}
|
}
|
||||||
|
|
||||||
function OtherSearchView({loading}) {
|
function SearchCollectionPreview({collection, to}) {
|
||||||
const {searchParams} = React.useContext(QueryContext);
|
const {SingleTag} = React.useContext(TagsContext);
|
||||||
const [activeValue, setActiveValue] = React.useState('channels');
|
return <div>
|
||||||
const activeTags = searchParams.getAll('tag');
|
<span style={{display: 'inline-flex', alignItems: 'center', gap: 8, flexWrap: 'wrap'}}>
|
||||||
const {channels, loading: channelsLoading} = useSearchChannels(activeTags);
|
<Link to={to}>{collection.name}</Link>
|
||||||
|
{collection.tag_name && <SingleTag name={collection.tag_name}/>}
|
||||||
if (loading || channelsLoading) {
|
</span>
|
||||||
return <Panel><Loading/></Panel>
|
</div>
|
||||||
}
|
}
|
||||||
|
|
||||||
return <Accordion value={activeValue} onChange={setActiveValue}>
|
function SearchRepoPreview({repo}) {
|
||||||
<Accordion.Item value='channels'>
|
const {SingleTag} = React.useContext(TagsContext);
|
||||||
|
return <div>
|
||||||
|
<span style={{display: 'inline-flex', alignItems: 'center', gap: 8, flexWrap: 'wrap'}}>
|
||||||
|
<Link to={`/repos/${repo.id}`}>{repo.name}</Link>
|
||||||
|
{repo.tag_name && <SingleTag name={repo.tag_name}/>}
|
||||||
|
</span>
|
||||||
|
{/* The server escapes the README; only its <b> highlights are markup. */}
|
||||||
|
{repo.readme_headline && <div><small><HeadlineText headline={repo.readme_headline}/></small></div>}
|
||||||
|
</div>
|
||||||
|
}
|
||||||
|
|
||||||
|
function OtherSearchSection({value, title, items, preview, emptyText, errorText}) {
|
||||||
|
let body;
|
||||||
|
if (items === null) {
|
||||||
|
body = <Loading/>;
|
||||||
|
} else if (items === undefined) {
|
||||||
|
body = <ErrorMessage>{errorText}</ErrorMessage>;
|
||||||
|
} else {
|
||||||
|
body = <Stack gap='xs'>{!_.isEmpty(items) ? items.map(preview) : emptyText}</Stack>;
|
||||||
|
}
|
||||||
|
return <Accordion.Item value={value}>
|
||||||
<Accordion.Control>
|
<Accordion.Control>
|
||||||
<span style={{display: 'inline-flex', alignItems: 'center', gap: 8}}>
|
<span style={{display: 'inline-flex', alignItems: 'center', gap: 8}}>
|
||||||
<Header as='h3' style={{margin: 0}}>Channels</Header>
|
<Header as='h3' style={{margin: 0}}>{title}</Header>
|
||||||
<Label>{normalizeEstimate(channels.length)}</Label>
|
{Array.isArray(items) && <Label>{normalizeEstimate(items.length)}</Label>}
|
||||||
</span>
|
</span>
|
||||||
</Accordion.Control>
|
</Accordion.Control>
|
||||||
<Accordion.Panel>
|
<Accordion.Panel>{body}</Accordion.Panel>
|
||||||
<Stack gap='xs'>
|
|
||||||
{!_.isEmpty(channels) ?
|
|
||||||
channels.map(i => <SearchChannelPreview key={i.id} channel={i}/>)
|
|
||||||
: 'No Channels'}
|
|
||||||
</Stack>
|
|
||||||
</Accordion.Panel>
|
|
||||||
</Accordion.Item>
|
</Accordion.Item>
|
||||||
|
}
|
||||||
|
|
||||||
|
// Each section's items follow useSearchChannels, useSearchCollections, or useSearchRepos: null = pending,
|
||||||
|
// undefined = fetch failed, [] = none.
|
||||||
|
export function OtherSearchView({loading}) {
|
||||||
|
const {searchParams} = React.useContext(QueryContext);
|
||||||
|
const [activeValues, setActiveValues] = React.useState(['channels', 'domains', 'playlists', 'repos']);
|
||||||
|
const activeTags = searchParams.getAll('tag');
|
||||||
|
const searchStr = searchParams.get('q') || '';
|
||||||
|
const {channels, loading: channelsLoading} = useSearchChannels(activeTags, searchStr);
|
||||||
|
const {collections: domains} = useSearchCollections('domain', searchStr, activeTags);
|
||||||
|
const {collections: playlists} = useSearchCollections('playlist', searchStr, activeTags);
|
||||||
|
const {repos} = useSearchRepos(searchStr, activeTags);
|
||||||
|
|
||||||
|
if (loading || channelsLoading || channels === null) {
|
||||||
|
return <Panel><Loading/></Panel>
|
||||||
|
} else if (channels === undefined) {
|
||||||
|
return <Panel><ErrorMessage>Could not fetch the channels.</ErrorMessage></Panel>
|
||||||
|
}
|
||||||
|
|
||||||
|
return <Accordion multiple value={activeValues} onChange={setActiveValues}>
|
||||||
|
<OtherSearchSection
|
||||||
|
value='channels'
|
||||||
|
title='Channels'
|
||||||
|
items={channels}
|
||||||
|
preview={i => <SearchChannelPreview key={i.id} channel={i}/>}
|
||||||
|
emptyText='No Channels'
|
||||||
|
errorText='Could not fetch the channels.'
|
||||||
|
/>
|
||||||
|
<OtherSearchSection
|
||||||
|
value='domains'
|
||||||
|
title='Domains'
|
||||||
|
items={domains}
|
||||||
|
preview={i => <SearchCollectionPreview key={i.id} collection={i}
|
||||||
|
to={`/archives?domain=${encodeURIComponent(i.name)}`}/>}
|
||||||
|
emptyText='No Domains'
|
||||||
|
errorText='Could not fetch the domains.'
|
||||||
|
/>
|
||||||
|
<OtherSearchSection
|
||||||
|
value='playlists'
|
||||||
|
title='Playlists'
|
||||||
|
items={playlists}
|
||||||
|
preview={i => <SearchCollectionPreview key={i.id} collection={i} to={`/playlists/${i.id}`}/>}
|
||||||
|
emptyText='No Playlists'
|
||||||
|
errorText='Could not fetch the playlists.'
|
||||||
|
/>
|
||||||
|
<OtherSearchSection
|
||||||
|
value='repos'
|
||||||
|
title='Repos'
|
||||||
|
items={repos}
|
||||||
|
preview={i => <SearchRepoPreview key={i.id} repo={i}/>}
|
||||||
|
emptyText='No Repos'
|
||||||
|
errorText='Could not fetch the repos.'
|
||||||
|
/>
|
||||||
</Accordion>
|
</Accordion>
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -94,6 +94,41 @@ describe('SearchFilterButton', () => {
|
||||||
expect(spy.mock.calls[0][0]).toMatchObject({order: '-size'});
|
expect(spy.mock.calls[0][0]).toMatchObject({order: '-size'});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('Rank always sorts the most relevant first, and has no direction', async () => {
|
||||||
|
const rankOrders = [{value: 'rank', text: 'Rank'}, ...videoOrders];
|
||||||
|
const spy = jest.fn();
|
||||||
|
// The previous sort was descending; Rank must not inherit it as `-rank` (least relevant first).
|
||||||
|
renderButton({sorts: rankOrders}, {order: '-size'}, spy);
|
||||||
|
fireEvent.click(screen.getByText('Filter'));
|
||||||
|
fireEvent.click(await screen.findByText('Rank'));
|
||||||
|
expect(screen.queryByText('Descending')).toBeNull();
|
||||||
|
expect(screen.queryByText('Ascending')).toBeNull();
|
||||||
|
fireEvent.click(screen.getByText('Done'));
|
||||||
|
expect(spy).toHaveBeenCalledTimes(1);
|
||||||
|
expect(spy.mock.calls[0][0]).toMatchObject({order: 'rank'});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('Done rewrites an old `-rank` link to the most relevant first', async () => {
|
||||||
|
const rankOrders = [{value: 'rank', text: 'Rank'}, ...videoOrders];
|
||||||
|
const spy = jest.fn();
|
||||||
|
renderButton({sorts: rankOrders}, {order: '-rank'}, spy);
|
||||||
|
fireEvent.click(screen.getByText('Filter'));
|
||||||
|
fireEvent.click(await screen.findByText('Done'));
|
||||||
|
expect(spy).toHaveBeenCalledTimes(1);
|
||||||
|
expect(spy.mock.calls[0][0]).toMatchObject({order: 'rank'});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('a sort chosen after Rank is descending', async () => {
|
||||||
|
const rankOrders = [{value: 'rank', text: 'Rank'}, ...videoOrders];
|
||||||
|
const spy = jest.fn();
|
||||||
|
renderButton({sorts: rankOrders}, {order: 'rank'}, spy);
|
||||||
|
fireEvent.click(screen.getByText('Filter'));
|
||||||
|
fireEvent.click(await screen.findByText('Size'));
|
||||||
|
expect(screen.getByText('Descending')).toBeInTheDocument();
|
||||||
|
fireEvent.click(screen.getByText('Done'));
|
||||||
|
expect(spy.mock.calls[0][0]).toMatchObject({order: '-size'});
|
||||||
|
});
|
||||||
|
|
||||||
it('Clear All resets results-per-page to the default on close', async () => {
|
it('Clear All resets results-per-page to the default on close', async () => {
|
||||||
const spy = jest.fn();
|
const spy = jest.fn();
|
||||||
renderButton({sorts: videoOrders}, {l: '96'}, spy);
|
renderButton({sorts: videoOrders}, {l: '96'}, spy);
|
||||||
|
|
|
||||||
159
app/src/components/SearchSuggestions.test.js
Normal file
159
app/src/components/SearchSuggestions.test.js
Normal file
|
|
@ -0,0 +1,159 @@
|
||||||
|
import React from 'react';
|
||||||
|
import {act, render, screen} from '../test-utils';
|
||||||
|
import {useSearchSuggestions} from './Search';
|
||||||
|
import {TagsContext} from '../Tags';
|
||||||
|
import {tagsContextFixture} from '../test-fixtures';
|
||||||
|
import {
|
||||||
|
searchEstimateFiles, searchEstimateMap, searchEstimateOthers, searchEstimateZims, searchSuggestions,
|
||||||
|
} from '../api';
|
||||||
|
|
||||||
|
// The global search dropdown's groups are built from useSuggestions. A "Channels: No results" row
|
||||||
|
// may only appear once the suggestion request has come back empty, never before the user has
|
||||||
|
// typed, and never while the request is pending.
|
||||||
|
|
||||||
|
jest.mock('../api', () => ({
|
||||||
|
...jest.requireActual('../api'),
|
||||||
|
searchSuggestions: jest.fn(),
|
||||||
|
searchEstimateFiles: jest.fn(),
|
||||||
|
searchEstimateMap: jest.fn(),
|
||||||
|
searchEstimateOthers: jest.fn(),
|
||||||
|
searchEstimateZims: jest.fn(),
|
||||||
|
}));
|
||||||
|
|
||||||
|
const DEBOUNCE = 500;
|
||||||
|
const pending = () => new Promise(() => {
|
||||||
|
});
|
||||||
|
|
||||||
|
let hook;
|
||||||
|
|
||||||
|
function Probe() {
|
||||||
|
hook = useSearchSuggestions('', [], false);
|
||||||
|
return <pre data-testid='results'>{JSON.stringify(hook.suggestionsResults)}</pre>;
|
||||||
|
}
|
||||||
|
|
||||||
|
const results = () => JSON.parse(screen.getByTestId('results').textContent);
|
||||||
|
|
||||||
|
const renderProbe = () => render(<Probe/>, {
|
||||||
|
contexts: [[TagsContext, tagsContextFixture({fuzzyMatchTagsByName: () => []})]],
|
||||||
|
});
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
jest.useFakeTimers();
|
||||||
|
searchEstimateFiles.mockReturnValue(pending());
|
||||||
|
searchEstimateMap.mockReturnValue(pending());
|
||||||
|
searchEstimateOthers.mockReturnValue(pending());
|
||||||
|
searchEstimateZims.mockReturnValue(pending());
|
||||||
|
});
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
jest.useRealTimers();
|
||||||
|
jest.clearAllMocks();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('no Channels group before anything has been searched', () => {
|
||||||
|
searchSuggestions.mockReturnValue(pending());
|
||||||
|
renderProbe();
|
||||||
|
expect(results().channels).toBeUndefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('no Channels group while the suggestion request is pending', () => {
|
||||||
|
searchSuggestions.mockReturnValue(pending());
|
||||||
|
renderProbe();
|
||||||
|
act(() => {
|
||||||
|
hook.setSearchStr('foo');
|
||||||
|
});
|
||||||
|
expect(results().channels).toBeUndefined();
|
||||||
|
|
||||||
|
act(() => {
|
||||||
|
jest.advanceTimersByTime(DEBOUNCE);
|
||||||
|
});
|
||||||
|
expect(searchSuggestions).toHaveBeenCalledWith('foo');
|
||||||
|
expect(results().channels).toBeUndefined();
|
||||||
|
expect(hook.loading).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a Channels "No results" row once the server said there are none', async () => {
|
||||||
|
let resolve;
|
||||||
|
searchSuggestions.mockReturnValue(new Promise(res => resolve = res));
|
||||||
|
renderProbe();
|
||||||
|
act(() => {
|
||||||
|
hook.setSearchStr('foo');
|
||||||
|
});
|
||||||
|
act(() => {
|
||||||
|
jest.advanceTimersByTime(DEBOUNCE);
|
||||||
|
});
|
||||||
|
await act(async () => {
|
||||||
|
resolve({channels: [], domains: [], authors: [], subjects: []});
|
||||||
|
});
|
||||||
|
expect(results().channels.results).toEqual([{title: 'No results'}]);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('Channels rows once the server found some', async () => {
|
||||||
|
let resolve;
|
||||||
|
searchSuggestions.mockReturnValue(new Promise(res => resolve = res));
|
||||||
|
renderProbe();
|
||||||
|
act(() => {
|
||||||
|
hook.setSearchStr('foo');
|
||||||
|
});
|
||||||
|
act(() => {
|
||||||
|
jest.advanceTimersByTime(DEBOUNCE);
|
||||||
|
});
|
||||||
|
await act(async () => {
|
||||||
|
resolve({channels: [{id: 3, name: 'Food'}], domains: [], authors: [], subjects: []});
|
||||||
|
});
|
||||||
|
expect(results().channels.results.map(i => i.title)).toEqual(['Food']);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('Repos rows link to each repo, and the Other estimate gets the search', async () => {
|
||||||
|
let resolve;
|
||||||
|
searchSuggestions.mockReturnValue(new Promise(res => resolve = res));
|
||||||
|
renderProbe();
|
||||||
|
act(() => {
|
||||||
|
hook.setSearchStr('kiwix');
|
||||||
|
});
|
||||||
|
act(() => {
|
||||||
|
jest.advanceTimersByTime(DEBOUNCE);
|
||||||
|
});
|
||||||
|
await act(async () => {
|
||||||
|
resolve({channels: [], domains: [], authors: [], subjects: [], repos: [{id: 4, name: 'kiwix-tools'}]});
|
||||||
|
});
|
||||||
|
expect(results().repos.results).toEqual([{type: 'repo', title: 'kiwix-tools', id: 4, location: '/repos/4'}]);
|
||||||
|
// Repos count toward the Other tab by their name and README, not only by tag.
|
||||||
|
expect(searchEstimateOthers).toHaveBeenCalledWith([], 'kiwix');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('no Repos group when none match', async () => {
|
||||||
|
let resolve;
|
||||||
|
searchSuggestions.mockReturnValue(new Promise(res => resolve = res));
|
||||||
|
renderProbe();
|
||||||
|
act(() => {
|
||||||
|
hook.setSearchStr('foo');
|
||||||
|
});
|
||||||
|
act(() => {
|
||||||
|
jest.advanceTimersByTime(DEBOUNCE);
|
||||||
|
});
|
||||||
|
await act(async () => {
|
||||||
|
resolve({channels: [], domains: [], authors: [], subjects: [], repos: []});
|
||||||
|
});
|
||||||
|
expect(results().repos).toBeUndefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
function AnyTagProbe() {
|
||||||
|
hook = useSearchSuggestions('', [], true);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
test('Any Tag alone counts the tagged files, without a search string', () => {
|
||||||
|
render(<AnyTagProbe/>, {
|
||||||
|
contexts: [[TagsContext, tagsContextFixture({fuzzyMatchTagsByName: () => []})]],
|
||||||
|
});
|
||||||
|
act(() => {
|
||||||
|
jest.advanceTimersByTime(DEBOUNCE);
|
||||||
|
});
|
||||||
|
expect(searchEstimateFiles).toHaveBeenCalledTimes(1);
|
||||||
|
expect(searchEstimateFiles.mock.calls[0][5]).toBe(true);
|
||||||
|
// Zims and the Other tab cannot search by "any tag"; without a search string they have nothing to count.
|
||||||
|
expect(searchEstimateZims).not.toHaveBeenCalled();
|
||||||
|
expect(searchEstimateOthers).not.toHaveBeenCalled();
|
||||||
|
expect(searchSuggestions).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Add table
Add a link
Reference in a new issue