mirror of
https://github.com/rommapp/romm.git
synced 2026-11-30 02:22:44 +01:00
Merge remote-tracking branch 'origin/master' into chore/dpdm-circular-deps
# Conflicts: # docs/FRONTEND_ARCHITECTURE.md
This commit is contained in:
156
.claude/skills/draft-announcement/SKILL.md
Normal file
156
.claude/skills/draft-announcement/SKILL.md
Normal file
@@ -0,0 +1,156 @@
|
||||
---
|
||||
name: draft-announcement
|
||||
description: Draft the Discord release announcement for a RomM release, from the release notes plus an interview about community news. Use when asked to "write the Discord announcement for 5.3.0", "draft the announcement post", "announce the beta in Discord", or to refresh an announcement draft. Interviews the user for the things no diff contains (new team members, third-party apps to spotlight, milestones, events, Discord housekeeping), writes in the house voice, and never posts to Discord.
|
||||
argument-hint: "[version to announce, e.g. 5.3.0 | nothing to infer it]"
|
||||
---
|
||||
|
||||
# Drafting a Discord announcement
|
||||
|
||||
The release notes say what shipped. The announcement says why anyone should care,
|
||||
in RomM's voice, in one Discord message. It is a short, warm, slightly unhinged
|
||||
post: a hook, the few features worth naming, the community news, a pointer to the
|
||||
notes, a sign-off.
|
||||
|
||||
Half the content is not in the repository. **Interview the user for it.** Never
|
||||
invent a contributor, an app, a milestone, a link or a handle.
|
||||
|
||||
Write the draft to the session scratchpad and print it. **Never** post to Discord,
|
||||
and never write into the maintainer's announcement archive (see section 1).
|
||||
|
||||
---
|
||||
|
||||
## 1. Read before you write
|
||||
|
||||
`$ARGUMENTS` is the version. If empty, take the newest tag and confirm it.
|
||||
|
||||
The release notes are the feature source.
|
||||
|
||||
```bash
|
||||
TAG=5.3.0
|
||||
gh release view "$TAG" --json body --jq .body # the notes for this release
|
||||
# for a release not yet published, use the draft in the scratchpad
|
||||
```
|
||||
|
||||
Past announcements are the voice source, and a Discord post is not in the repo, so
|
||||
they exist only wherever the maintainer archives them. Ask where that is if you do
|
||||
not already know, and treat it as **read only**: drafts go to the scratchpad.
|
||||
|
||||
Read the **two most recent** before drafting. They set the current voice, and they
|
||||
tell you which third-party apps were already spotlighted. An app highlighted in
|
||||
either one does not get spotlighted again.
|
||||
|
||||
From the notes, pull:
|
||||
|
||||
- the Highlights, as candidate features to name,
|
||||
- every `> [!WARNING]` and `> [!CAUTION]`, which **must** survive into the
|
||||
announcement (`4.1.0` led with the mandatory `config.yml`, `4.0.0` led with the
|
||||
RCE advisory),
|
||||
- a rough PR count and whether the release is mostly fixes, which decides the hook.
|
||||
|
||||
## 2. Interview the user, one step at a time
|
||||
|
||||
The community news is names, URLs and handles that only the user has, so it gets
|
||||
**typed, not picked**. Ask **one question per message** and wait for the answer
|
||||
before asking the next. Never send the whole questionnaire as a numbered list, and
|
||||
never collect the content answers as checkbox options.
|
||||
|
||||
Number every step and say how many there are ("Step 2 of 6"), so the user can see
|
||||
where the interview ends. Each step states exactly which fields you need, and how
|
||||
to skip it. Take "skip", "none" or "n/a" as an answer, move on without arguing, and
|
||||
drop that item from the draft.
|
||||
|
||||
| # | Step | Ask for |
|
||||
| --- | ------------------ | --------------------------------------------------------------------------------------------------------------- |
|
||||
| 1 | Features | print the Highlights you found as a numbered list, ask which get named prose; the rest become bullets |
|
||||
| 2 | App spotlight | name, repo URL, author's handle, one line on what it does. List the apps already spotlighted so nothing repeats |
|
||||
| 3 | Team or role news | handle, what they built or do, what changes now (joined the team, project gone official, new Experts) |
|
||||
| 4 | Milestone or event | what it is, the number or date, and the link |
|
||||
| 5 | Anything else | housekeeping, a call to action, a beta bug-report ask; the exact wording they want |
|
||||
| 6 | Pings and shape | the only genuinely multiple-choice step, so one `AskUserQuestion` call: who gets pinged, and one message or two |
|
||||
|
||||
Ask for a handle as it is written in Discord, since `@Covin` and `@Covin90` are not
|
||||
interchangeable. Never offer a sample answer that could be mistaken for a real one:
|
||||
no invented app names, no placeholder URLs, no guessed star counts.
|
||||
|
||||
If steps 2 through 5 all come back empty, drop the Community news section. Several
|
||||
releases (`4.3.0`, `4.4.0`) have none, and a padded one reads worse than none.
|
||||
|
||||
Skip a step only when the answer is already on the table, and say so rather than
|
||||
silently dropping it: a user who opened with "announce 5.3.0, spotlight `<app>`" has
|
||||
answered step 2 already.
|
||||
|
||||
## 3. The shape
|
||||
|
||||
Always, in this order:
|
||||
|
||||
1. **Hook.** One or two sentences, opening on something _timely_. Check today's
|
||||
date first and use it: the season, a holiday, the month, or a self-aware nod to
|
||||
the last release. `3.6.0` served Thanksgiving turkey, `3.10.0` opened on the
|
||||
summer heat, `3.7.0` on the new year, `4.9.0` on being the last `4.x`, `5.1.0`
|
||||
on arriving sooner than anyone expected. Then `@everyone` (if pinging), the
|
||||
version in backticks, and what the release is _about_. Never open cold with
|
||||
"version X is out". Keep the reference light and skip a holiday that is not
|
||||
widely shared, and do not assert a date you have not checked ("the equinox is
|
||||
today") when "the days are getting shorter" carries the same warmth.
|
||||
2. **Any upgrade warning**, immediately after the hook. Imperative, and what to do,
|
||||
not why.
|
||||
3. **The features**, in one of two shapes:
|
||||
- **Bullet list** for a release carried by a long tail (`5.1.0`, `4.3.0`): one
|
||||
sentence of setup, then five to nine bullets of three to six words each.
|
||||
- **`###` section per feature** for a release with two to five real headliners
|
||||
(`3.10.0`, `4.4.0`, `3.5.0`): a heading and two or three sentences, saying what
|
||||
it does and the one thing needed to use it. Close with an `Other notable
|
||||
features:` bullet list when there is a tail.
|
||||
4. **`## Community news`** (`### Community updates` also appears; match the last
|
||||
one). Team additions first, then app spotlights, then milestones and events, then
|
||||
housekeeping and calls to action.
|
||||
5. **The pointer.** "More details on each of these features, and a complete list of
|
||||
changes, can be found in the [release notes](url)." Link the tag URL.
|
||||
6. **Sign-off.** "See you soon!", optionally with `:mario_here_we_go:`.
|
||||
|
||||
## 4. Voice
|
||||
|
||||
- Second person, present tense, contractions. Talking to friends, not users.
|
||||
- One idea per sentence, and short paragraphs. Nothing here is a manual.
|
||||
- Enthusiasm is earned by specifics, not adjectives. Name the feature, don't call
|
||||
it revolutionary. No claim the release notes do not support.
|
||||
- Emphasis is _italics_ on a single word, sparingly. Bold is for the thing that
|
||||
will break someone's install.
|
||||
- Backticks for versions, env vars, config keys, filenames.
|
||||
- Credit by name every time: the contributor for a feature, the author for an app.
|
||||
- No em-dashes. No AI throat-clearing, no "we're excited to announce" twice in one
|
||||
post, no bullet list of benefits.
|
||||
|
||||
## 5. Discord mechanics
|
||||
|
||||
- **2000 characters**, hard. Past announcements run 1300 to 2100; treat 1800 as the
|
||||
target and count before handing over (`wc -m`).
|
||||
- Over the limit, pick one: split at a section boundary into message 1 (hook plus
|
||||
features) and message 2 (community news plus sign-off), marking the split in the
|
||||
draft; or do what `3.7.0` did and post a three-line teaser pointing at the GitHub
|
||||
notes. Say which you did and why.
|
||||
- `##`, `###`, `**bold**`, `*italics*`, `` `code` ``, `> quote`, `-`/`*` bullets and
|
||||
`[text](url)` all render. Tables, images and HTML do not.
|
||||
- `@everyone` goes in the first sentence or not at all.
|
||||
- Custom emoji only from ones this server is known to have:
|
||||
`:mario_here_we_go:` (the usual sign-off), `:linkEz:`, `:linkLove:`, `:peepoAlert:`,
|
||||
`:snakeSalute:`, `:excuseme:`, `:okay:`, `:linuxNootNoot:`. Anything else renders as
|
||||
literal text, so use plain unicode (🎊 👉 ⚠️ 🔥) instead of guessing a shortcode.
|
||||
- Role pings (`@Expert`, `@Alpha Tester`, `@Beta Tester`) only when the user asked
|
||||
for them, spelled as they gave them.
|
||||
|
||||
## 6. Before handing it over
|
||||
|
||||
- Every feature named appears in the release notes.
|
||||
- The hook opens on something timely, and the reference matches today's date.
|
||||
- Every warning and caution in the notes appears in the announcement.
|
||||
- Every handle, repo URL and number came from the user or from the notes, never
|
||||
from you, and every URL is one you have actually seen.
|
||||
- No app spotlighted in either of the last two announcements.
|
||||
- The release notes link ends in the tag being announced.
|
||||
- Under 2000 characters, or split deliberately.
|
||||
- No em-dashes, no invented emoji shortcodes.
|
||||
|
||||
Write to `<scratchpad>/<tag>-announcement.md`, print it, and say what still needs a
|
||||
human: a screenshot or GIF to attach, a link the user has not given you, a name you
|
||||
could not confirm.
|
||||
69
.claude/skills/draft-announcement/template.md
Normal file
69
.claude/skills/draft-announcement/template.md
Normal file
@@ -0,0 +1,69 @@
|
||||
# Discord announcement skeletons
|
||||
|
||||
Pick a shape by how many real headliners the release has, drop any section with no
|
||||
content, and stay under 2000 characters. Bare URLs and loose headings inside the
|
||||
skeletons are deliberate: Discord renders them, not GitHub.
|
||||
|
||||
## Bullet shape (a long tail of changes)
|
||||
|
||||
```text
|
||||
@everyone <one or two sentences: the version in backticks, the angle, what this
|
||||
release is about>
|
||||
|
||||
<only if the release notes carry a warning:>
|
||||
⚠️ <what the reader must do before upgrading, imperative, bold the breaking part>
|
||||
|
||||
<A couple of the bigger items are also included, like:>
|
||||
|
||||
- <Feature, three to six words>
|
||||
- <Feature>
|
||||
- <Feature>
|
||||
- <Feature>
|
||||
- <Feature>
|
||||
|
||||
## Community news
|
||||
|
||||
<New team member: who they are, what they built, link, what changes now.>
|
||||
|
||||
<App spotlight: [Name](repo url) by @author, one sentence on what it does and who
|
||||
it is for. Not an app spotlighted in the last two announcements.>
|
||||
|
||||
<Milestone, event, press, or a call to action with the exact wording the user gave.>
|
||||
|
||||
More details on each of these features, and a complete list of changes, can be
|
||||
found in the [release notes](https://github.com/rommapp/romm/releases/tag/X.Y.Z).
|
||||
|
||||
See you soon! :mario_here_we_go:
|
||||
```
|
||||
|
||||
## Section shape (two to five real headliners)
|
||||
|
||||
```text
|
||||
@everyone <hook>
|
||||
|
||||
<only if the release notes carry a warning:>
|
||||
⚠️ <what the reader must do before upgrading, imperative, bold the breaking part>
|
||||
|
||||
### <Feature name>
|
||||
|
||||
<What it does, second person, two or three sentences. Then the one thing needed
|
||||
to use it: the `config.yml` key, the setting, the caveat.>
|
||||
|
||||
### <Feature name>
|
||||
|
||||
<Same.>
|
||||
|
||||
Other notable features:
|
||||
|
||||
- <Feature>
|
||||
- <Feature>
|
||||
|
||||
## Community news
|
||||
|
||||
<As above.>
|
||||
|
||||
More details on each of these features, and a complete list of changes, can be
|
||||
found in the [release notes](https://github.com/rommapp/romm/releases/tag/X.Y.Z).
|
||||
|
||||
See you soon! :mario_here_we_go:
|
||||
```
|
||||
@@ -142,10 +142,11 @@ mypy wanting explicit annotations on `__init__` attributes
|
||||
|
||||
Run from `frontend/`:
|
||||
|
||||
1. `npm run typecheck` — zero errors (`vue-tsc --noEmit`).
|
||||
2. `npm run lint` _(if present)_ / ESLint clean. Trunk also runs ESLint + Prettier in CI.
|
||||
3. `npm run test` — zero failures (Vitest + happy-dom; runs unit tests **and** every `/lib` story's `play()` via `composeStories`).
|
||||
4. `npm run build` — zero failures (CI sanity check).
|
||||
1. `npm run typecheck`: zero errors (`vue-tsc --noEmit`).
|
||||
2. `npm run typecheck:scripts`: zero errors (`tsc -p tsconfig.node.json`, covers `scripts/`).
|
||||
3. `npm run lint` _(if present)_ / ESLint clean. Trunk also runs ESLint + Prettier in CI.
|
||||
4. `npm run test`: zero failures (Vitest + happy-dom; runs unit tests **and** every `/lib` story's `play()` via `composeStories`).
|
||||
5. `npm run build`: zero failures (CI sanity check).
|
||||
|
||||
**If you touched the backend API:** start the backend, run `npm run generate`, then re-`typecheck`.
|
||||
|
||||
|
||||
16
.github/resources/aikido-badge.svg
vendored
16
.github/resources/aikido-badge.svg
vendored
@@ -1,16 +0,0 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="288.99" height="67">
|
||||
<g fill="none" fill-rule="evenodd">
|
||||
<rect width="286.99" height="65" x="1" y="1" fill="#5948e9" stroke="#5948e9" stroke-width="2" rx="8" />
|
||||
<g fill="#fff" transform="translate(17, 14) scale(2.2222)">
|
||||
<path d="M15.9961 0H0V5.65188H15.9961V0Z" />
|
||||
<path d="M0 10.953C4.5507 6.83365 11.4453 6.83364 15.9961 10.953V17.9968L15.9929 18L7.99803 9.88536L0.00313606 18L0 17.9968V10.953Z" />
|
||||
</g>
|
||||
<!-- -->
|
||||
<text fill="#fff" font-family="Arial" font-size="21" font-weight="bold">
|
||||
<tspan x="70" y="51">Secured with Aikido</tspan>
|
||||
</text>
|
||||
<text fill="#fff" font-family="Arial" font-size="12" font-weight="bold">
|
||||
<tspan x="70" y="26">OPEN SOURCE SECURITY</tspan>
|
||||
</text>
|
||||
</g>
|
||||
</svg>
|
||||
|
Before Width: | Height: | Size: 797 B |
5
.github/workflows/build.yml
vendored
5
.github/workflows/build.yml
vendored
@@ -125,6 +125,10 @@ jobs:
|
||||
labels: ${{ steps.meta-slim.outputs.labels }}
|
||||
target: slim-image
|
||||
outputs: type=image,name=${{ env.DIGEST_IMAGE }},push-by-digest=true,name-canonical=true,push=true
|
||||
# Both stages run `apk upgrade` off a fixed base digest, so nothing in
|
||||
# them changes between releases and the cache would serve the package
|
||||
# set of whenever the layer was first built.
|
||||
no-cache-filters: python-runtime,production-stage
|
||||
# Deliberately not seeded from the preview cache: those layers are
|
||||
# built from PR head content and must not reach a release image.
|
||||
cache-from: type=registry,ref=${{ env.CACHE_IMAGE }}:release-${{ matrix.arch }}
|
||||
@@ -144,6 +148,7 @@ jobs:
|
||||
labels: ${{ steps.meta.outputs.labels }}
|
||||
target: full-image
|
||||
outputs: type=image,name=${{ env.DIGEST_IMAGE }},push-by-digest=true,name-canonical=true,push=true
|
||||
no-cache-filters: python-runtime,production-stage
|
||||
cache-from: type=registry,ref=${{ env.CACHE_IMAGE }}:release-${{ matrix.arch }}
|
||||
cache-to: type=registry,ref=${{ env.CACHE_IMAGE }}:release-${{ matrix.arch }},mode=max
|
||||
build-args: |
|
||||
|
||||
2
.github/workflows/copilot-setup-steps.yml
vendored
2
.github/workflows/copilot-setup-steps.yml
vendored
@@ -27,7 +27,7 @@ jobs:
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
|
||||
- name: Install uv
|
||||
uses: astral-sh/setup-uv@bec219d24cd3e171d82865faccec33120bb574f4 # v10.1.0
|
||||
uses: astral-sh/setup-uv@c18668ad3cf93ea998bef934396af7bb5c839dc7 # v10.2.0
|
||||
|
||||
- name: Install Python
|
||||
run: uv python install
|
||||
|
||||
5
.github/workflows/e2e.yml
vendored
5
.github/workflows/e2e.yml
vendored
@@ -22,7 +22,8 @@ on:
|
||||
- uv.lock
|
||||
- .python-version
|
||||
|
||||
permissions: read-all
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
e2e:
|
||||
@@ -68,7 +69,7 @@ jobs:
|
||||
sudo apt-get install -y libmariadb3 libmariadb-dev
|
||||
|
||||
- name: Install uv
|
||||
uses: astral-sh/setup-uv@bec219d24cd3e171d82865faccec33120bb574f4 # v10.1.0
|
||||
uses: astral-sh/setup-uv@c18668ad3cf93ea998bef934396af7bb5c839dc7 # v10.2.0
|
||||
|
||||
- name: Install python
|
||||
run: uv python install
|
||||
|
||||
3
.github/workflows/frontend-v1-frozen.yml
vendored
3
.github/workflows/frontend-v1-frozen.yml
vendored
@@ -16,7 +16,8 @@ on:
|
||||
- "frontend/src/console/**"
|
||||
- "frontend/src/layouts/**"
|
||||
|
||||
permissions: read-all
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
check-v1-frozen:
|
||||
|
||||
3
.github/workflows/frontend.yml
vendored
3
.github/workflows/frontend.yml
vendored
@@ -10,7 +10,8 @@ on:
|
||||
paths:
|
||||
- "frontend/**"
|
||||
|
||||
permissions: read-all
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
test:
|
||||
|
||||
5
.github/workflows/i18n.yml
vendored
5
.github/workflows/i18n.yml
vendored
@@ -5,7 +5,8 @@ on:
|
||||
paths:
|
||||
- "frontend/src/locales/**/*.json"
|
||||
|
||||
permissions: read-all
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
check-translations:
|
||||
@@ -16,7 +17,7 @@ jobs:
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
|
||||
- name: Install uv
|
||||
uses: astral-sh/setup-uv@bec219d24cd3e171d82865faccec33120bb574f4 # v10.1.0
|
||||
uses: astral-sh/setup-uv@c18668ad3cf93ea998bef934396af7bb5c839dc7 # v10.2.0
|
||||
|
||||
- name: Install python
|
||||
run: uv python install
|
||||
|
||||
13
.github/workflows/migrations.yml
vendored
13
.github/workflows/migrations.yml
vendored
@@ -9,14 +9,12 @@ on:
|
||||
- uv.lock
|
||||
- .python-version
|
||||
|
||||
permissions: read-all
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
migrate-postgres:
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
checks: write
|
||||
pull-requests: write
|
||||
services:
|
||||
postgres:
|
||||
image: postgres:18
|
||||
@@ -41,7 +39,7 @@ jobs:
|
||||
sudo apt-get install -y libmariadb3 libmariadb-dev
|
||||
|
||||
- name: Install uv
|
||||
uses: astral-sh/setup-uv@bec219d24cd3e171d82865faccec33120bb574f4 # v10.1.0
|
||||
uses: astral-sh/setup-uv@c18668ad3cf93ea998bef934396af7bb5c839dc7 # v10.2.0
|
||||
|
||||
- name: Install python
|
||||
run: uv python install
|
||||
@@ -68,9 +66,6 @@ jobs:
|
||||
# migration SQL that a default utf8mb4 server accepts (issue #4350).
|
||||
name: migrate-mariadb (${{ matrix.mariadb }}, ${{ matrix.collation }})
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
checks: write
|
||||
pull-requests: write
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
@@ -98,7 +93,7 @@ jobs:
|
||||
sudo apt-get install -y libmariadb3 libmariadb-dev
|
||||
|
||||
- name: Install uv
|
||||
uses: astral-sh/setup-uv@bec219d24cd3e171d82865faccec33120bb574f4 # v10.1.0
|
||||
uses: astral-sh/setup-uv@c18668ad3cf93ea998bef934396af7bb5c839dc7 # v10.2.0
|
||||
|
||||
- name: Install python
|
||||
run: uv python install
|
||||
|
||||
8
.github/workflows/pytest.yml
vendored
8
.github/workflows/pytest.yml
vendored
@@ -22,14 +22,12 @@ on:
|
||||
- Dockerfile
|
||||
- docker/Dockerfile
|
||||
|
||||
permissions: read-all
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
pytest:
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
checks: write
|
||||
pull-requests: write
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
@@ -70,7 +68,7 @@ jobs:
|
||||
sudo apt-get install -y libmariadb3 libmariadb-dev 7zip
|
||||
|
||||
- name: Install uv
|
||||
uses: astral-sh/setup-uv@bec219d24cd3e171d82865faccec33120bb574f4 # v10.1.0
|
||||
uses: astral-sh/setup-uv@c18668ad3cf93ea998bef934396af7bb5c839dc7 # v10.2.0
|
||||
|
||||
- name: Install python
|
||||
run: |
|
||||
|
||||
3
.github/workflows/trunk-check.yml
vendored
3
.github/workflows/trunk-check.yml
vendored
@@ -10,7 +10,8 @@ concurrency:
|
||||
group: ${{ github.head_ref || github.run_id }}
|
||||
cancel-in-progress: true
|
||||
|
||||
permissions: read-all
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
trunk_check:
|
||||
|
||||
10
.github/workflows/typecheck.yml
vendored
10
.github/workflows/typecheck.yml
vendored
@@ -10,14 +10,12 @@ on:
|
||||
paths:
|
||||
- "frontend/**"
|
||||
|
||||
permissions: read-all
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
typecheck:
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
checks: write
|
||||
pull-requests: write
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
@@ -37,6 +35,10 @@ jobs:
|
||||
run: npm run typecheck
|
||||
working-directory: frontend
|
||||
|
||||
- name: Run scripts typecheck
|
||||
run: npm run typecheck:scripts
|
||||
working-directory: frontend
|
||||
|
||||
- name: Lockfile lint
|
||||
run: |
|
||||
[ -z "$(jq -r '.packages | to_entries[] | select((.key | contains("node_modules")) and (.value.resolved | contains("git+ssh") | not) and (.value | has("resolved") and has("integrity") | not)) | .key' < package-lock.json)" ]
|
||||
|
||||
8
.github/workflows/update-hltb-api-url.yml
vendored
8
.github/workflows/update-hltb-api-url.yml
vendored
@@ -8,18 +8,20 @@ on:
|
||||
- cron: "0 6 * * 1"
|
||||
|
||||
permissions:
|
||||
contents: write
|
||||
pull-requests: write
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
update-hltb-api-url:
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: write # For create-pull-request to push the branch
|
||||
pull-requests: write # For create-pull-request to open the PR
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
|
||||
- name: Install uv
|
||||
uses: astral-sh/setup-uv@bec219d24cd3e171d82865faccec33120bb574f4 # v10.1.0
|
||||
uses: astral-sh/setup-uv@c18668ad3cf93ea998bef934396af7bb5c839dc7 # v10.2.0
|
||||
|
||||
- name: Install python
|
||||
run: |
|
||||
|
||||
@@ -53,6 +53,7 @@ These live in `.claude/skills/` and carry the detailed rules. Invoke the one tha
|
||||
| `pr-ready` | Before opening a PR - the four passes in order: `security-audit`, `code-review xhigh --fix`, `simplify`, `review-polish`. Not auto-invoked. |
|
||||
| `address-bot-reviews` | After Greptile and Copilot review a PR - triage each finding, fix what holds up, reply with the fix or the reason, and resolve the threads. Not auto-invoked. |
|
||||
| `draft-release-notes` | Drafting the GitHub release notes for a release, stable or alpha/beta, from the diff since the previous stable tag. |
|
||||
| `draft-announcement` | Drafting the Discord announcement for a release, from the release notes plus an interview about community news. Not auto-invoked. |
|
||||
|
||||
---
|
||||
|
||||
@@ -99,6 +100,7 @@ uv run alembic upgrade head # apply migrations
|
||||
npm install # install (Node 24)
|
||||
npm run dev # dev server :3000
|
||||
npm run typecheck # vue-tsc
|
||||
npm run typecheck:scripts # tsc on the Node/Vite tooling in scripts/
|
||||
npm run test # vitest (+ Storybook play() tests)
|
||||
npm run test:e2e # playwright (needs a running app + seeded e2e users)
|
||||
npm run build # production build
|
||||
|
||||
@@ -144,7 +144,6 @@ These companies support us by providing their tools for free:
|
||||
<div align="center">
|
||||
<div dir="auto">
|
||||
<a href="https://www.greptile.com/?utm_source=oss_badge&utm_medium=readme&utm_campaign=greptile_for_open_source" target="_blank" rel="noopener noreferrer"><img src=".github/resources/greptile-badge.svg" alt="Greptile" width="250" height="58"/></a>
|
||||
<a href="https://www.aikido.dev/" target="_blank" rel="noopener noreferrer"><img src=".github/resources/aikido-badge.svg" alt="Aikido" width="250" height="58"/></a>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
@@ -919,7 +919,17 @@ class ConfigManager:
|
||||
f"Invalid config.yml: {config_key}.{key} must be a non-empty string"
|
||||
)
|
||||
sys.exit(3)
|
||||
normalized[str(key).lower()] = value
|
||||
folded = str(key).lower()
|
||||
# One key covers `PSX` and `psx` alike, so a second spelling of the
|
||||
# same folder silently replaces the first.
|
||||
if folded in normalized and normalized[folded] != value:
|
||||
log.warning(
|
||||
f"{config_key}.{key} replaces a case variant of the same "
|
||||
f"folder name: {hl(normalized[folded])} is dropped for "
|
||||
f"{hl(value)}, since folder names are matched "
|
||||
"case-insensitively"
|
||||
)
|
||||
normalized[folded] = value
|
||||
|
||||
return normalized
|
||||
|
||||
@@ -1401,9 +1411,11 @@ class ConfigManager:
|
||||
def add_platform_binding(self, fs_slug: str, slug: str) -> None:
|
||||
fs_slug = fs_slug.lower()
|
||||
platform_bindings = self.config.PLATFORMS_BINDING
|
||||
if fs_slug in platform_bindings:
|
||||
log.warning(f"Binding for {hl(fs_slug)} already exists")
|
||||
bound = platform_bindings.get(fs_slug)
|
||||
if bound == slug:
|
||||
return None
|
||||
if bound:
|
||||
log.info(f"Rebinding {hl(fs_slug)} from {hl(bound)} to {hl(slug)}")
|
||||
|
||||
platform_bindings[fs_slug] = slug
|
||||
self.config.PLATFORMS_BINDING = platform_bindings
|
||||
@@ -1423,9 +1435,11 @@ class ConfigManager:
|
||||
def add_platform_version(self, fs_slug: str, slug: str) -> None:
|
||||
fs_slug = fs_slug.lower()
|
||||
platform_versions = self.config.PLATFORMS_VERSIONS
|
||||
if fs_slug in platform_versions:
|
||||
log.warning(f"Version for {hl(fs_slug)} already exists")
|
||||
parent = platform_versions.get(fs_slug)
|
||||
if parent == slug:
|
||||
return None
|
||||
if parent:
|
||||
log.info(f"Reparenting {hl(fs_slug)} from {hl(parent)} to {hl(slug)}")
|
||||
|
||||
platform_versions[fs_slug] = slug
|
||||
self.config.PLATFORMS_VERSIONS = platform_versions
|
||||
|
||||
@@ -18,6 +18,7 @@ from endpoints.responses.config import ConfigResponse
|
||||
from exceptions.config_exceptions import ConfigNotWritableException
|
||||
from handler.auth.constants import Scope
|
||||
from handler.database import db_rom_handler
|
||||
from handler.filesystem import fs_platform_handler
|
||||
from logger.logger import log
|
||||
from utils.router import APIRouter
|
||||
|
||||
@@ -169,6 +170,19 @@ def get_config(request: Request) -> ConfigResponse:
|
||||
)
|
||||
|
||||
|
||||
async def _reject_ambiguous_folder(fs_slug: str) -> None:
|
||||
"""Refuse a mapping that several folders on disk would share."""
|
||||
ambiguous = await fs_platform_handler.find_ambiguous_folders(fs_slug)
|
||||
if ambiguous:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_409_CONFLICT,
|
||||
detail=(
|
||||
f"Folders {', '.join(ambiguous)} differ only by case and share a "
|
||||
"single mapping. Rename one to map them to different platforms."
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
@protected_route(router.post, "/system/platforms", [Scope.PLATFORMS_WRITE])
|
||||
async def add_platform_binding(
|
||||
request: Request, payload: PlatformBindingPayload
|
||||
@@ -177,6 +191,7 @@ async def add_platform_binding(
|
||||
|
||||
fs_slug = payload.fs_slug
|
||||
slug = payload.slug
|
||||
await _reject_ambiguous_folder(fs_slug)
|
||||
|
||||
try:
|
||||
cm.add_platform_binding(fs_slug, slug)
|
||||
@@ -208,6 +223,7 @@ async def add_platform_version(
|
||||
|
||||
fs_slug = payload.fs_slug
|
||||
slug = payload.slug
|
||||
await _reject_ambiguous_folder(fs_slug)
|
||||
|
||||
try:
|
||||
cm.add_platform_version(fs_slug, slug)
|
||||
|
||||
@@ -192,10 +192,15 @@ def _swappable_disc_file_ids(rom: Rom) -> set[int]:
|
||||
return {f.id for f in playlist_files(rom.files)}
|
||||
|
||||
|
||||
async def _session_status(platform: str, request: Request) -> dict[str, Any]:
|
||||
"""Whether the caller still holds this platform's session, and if not, why
|
||||
it ended. Read-only, so it is safe to poll."""
|
||||
candidates = containers_for_platform(platform)
|
||||
async def _session_status(
|
||||
platform: str,
|
||||
request: Request,
|
||||
candidates: list[ResolvedContainer] | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""Whether the caller holds a session among `candidates` (the platform's first
|
||||
pool by default), and if not, why it ended. Read-only, so it is safe to poll."""
|
||||
if candidates is None:
|
||||
candidates = containers_for_platform(platform)
|
||||
if not candidates:
|
||||
raise HTTPException(
|
||||
status_code=404,
|
||||
@@ -648,7 +653,7 @@ async def claim_session(
|
||||
The ROM's filesystem path is derived server-side from its database row -
|
||||
the client only supplies a ROM id, never a path.
|
||||
Returns 404 if the ROM doesn't exist or no container serves its platform.
|
||||
Returns 409 if every container serving the platform is occupied.
|
||||
Returns 409 if every container in the platform's first pool is occupied.
|
||||
Returns 428 if the container's pre-existing memory card needs a decision.
|
||||
"""
|
||||
rom = db_rom_handler.get_rom(req.rom_id)
|
||||
@@ -668,9 +673,8 @@ async def claim_session(
|
||||
detail=f"No streaming container configured for platform '{platform}'",
|
||||
)
|
||||
|
||||
# Pool members are interchangeable on emulator and card sync (enforced by
|
||||
# containers_for_platform), so the pre-claim validation below holds for
|
||||
# whichever one the walk ends up winning.
|
||||
# Pool members are interchangeable (`ResolvedContainer.interchangeable_with`),
|
||||
# so the pre-claim validation below holds for whichever one the walk wins.
|
||||
reference = candidates[0]
|
||||
|
||||
# Validate the resume pick before claiming so a bad state_id cannot
|
||||
@@ -933,7 +937,11 @@ async def save_and_exit_session(
|
||||
|
||||
|
||||
@protected_route(router.post, "/sessions/{platform}/heartbeat", [Scope.ROMS_USER_WRITE])
|
||||
async def heartbeat_session(request: Request, platform: str) -> SessionStatusSchema:
|
||||
async def heartbeat_session(
|
||||
request: Request,
|
||||
platform: str,
|
||||
container_key: str | None = Query(default=None, alias="container", max_length=300),
|
||||
) -> SessionStatusSchema:
|
||||
"""Refresh the session's liveness stamp and report whether it still exists.
|
||||
|
||||
The frontend calls this every ~30s while a session is active. A session
|
||||
@@ -943,28 +951,32 @@ async def heartbeat_session(request: Request, platform: str) -> SessionStatusSch
|
||||
Reports `ended` rather than raising 404 when the caller no longer holds the
|
||||
session, so a force-released player learns why on the poll they are already
|
||||
making rather than watching a dead stream.
|
||||
|
||||
`container` names the claim to refresh, needed for a desktop on a container
|
||||
outside the platform's first pool.
|
||||
"""
|
||||
candidates = containers_for_platform(platform)
|
||||
if not candidates:
|
||||
raise HTTPException(
|
||||
status_code=404,
|
||||
detail=f"No streaming container configured for platform '{platform}'",
|
||||
)
|
||||
found = await access.find_session_for_user(candidates, request.user.id)
|
||||
user_id = request.user.id
|
||||
# A named claim answers for itself: another session the caller holds on the
|
||||
# platform is not the one this client is beating.
|
||||
candidates = (
|
||||
[access.named_container(platform, container_key)]
|
||||
if container_key is not None
|
||||
else containers_for_platform(platform)
|
||||
)
|
||||
found = await access.find_session_for_user(candidates, user_id)
|
||||
if found is None:
|
||||
return SessionStatusSchema(**await _session_status(platform, request))
|
||||
return SessionStatusSchema(
|
||||
**await _session_status(platform, request, candidates)
|
||||
)
|
||||
_, session_key, _ = found
|
||||
|
||||
# Merging rather than writing the copy read above keeps a swap that landed
|
||||
# in between; refusing a draining session keeps a heartbeat from making a
|
||||
# container that is already being torn down look live. Either returns None,
|
||||
# meaning the claim is gone and reporting "active" would leave the client
|
||||
# beating a session it no longer holds.
|
||||
# Merging keeps a swap that landed since the read. Refusing a draining or
|
||||
# re-claimed session returns None, so the client stops beating a dead claim.
|
||||
try:
|
||||
refreshed = await mutate_session(
|
||||
session_key,
|
||||
{"last_seen": datetime.now(timezone.utc).isoformat()},
|
||||
require=lambda s: not s.get("draining"),
|
||||
require=lambda s: not s.get("draining") and s.get("user_id") == user_id,
|
||||
)
|
||||
except StreamingSessionContended:
|
||||
# A key too busy to write is a key that exists, so the session is live
|
||||
@@ -972,7 +984,9 @@ async def heartbeat_session(request: Request, platform: str) -> SessionStatusSch
|
||||
log.warning("heartbeat could not stamp contended session %s", session_key)
|
||||
return SessionStatusSchema(status="active", platform=platform)
|
||||
if refreshed is None:
|
||||
return SessionStatusSchema(**await _session_status(platform, request))
|
||||
return SessionStatusSchema(
|
||||
**await _session_status(platform, request, candidates)
|
||||
)
|
||||
await lifecycle.refresh_session_activity(session_key, refreshed)
|
||||
return SessionStatusSchema(status="active", platform=platform)
|
||||
|
||||
|
||||
@@ -16,6 +16,11 @@ from starlette.responses import PlainTextResponse, Response
|
||||
from starlette.types import ASGIApp, Message, Receive, Scope, Send
|
||||
|
||||
|
||||
def _session_authenticated(request: Request) -> bool:
|
||||
"""Whether the session, resolved and maybe cleared upstream, names a user."""
|
||||
return bool((request.scope.get("session") or {}).get("sub"))
|
||||
|
||||
|
||||
class CSRFMiddleware:
|
||||
def __init__(
|
||||
self,
|
||||
@@ -60,9 +65,10 @@ class CSRFMiddleware:
|
||||
|
||||
request = Request(scope, receive)
|
||||
|
||||
# Skip CSRF check if Authorization header is present
|
||||
# HybridAuthBackend resolves the session before this header, so a
|
||||
# session-authenticated request runs as the cookie's owner, not the bearer's.
|
||||
auth_scheme = request.headers.get("Authorization", "").split(" ", 1)[0].lower()
|
||||
if auth_scheme == "bearer" or auth_scheme == "basic":
|
||||
if auth_scheme in ("bearer", "basic") and not _session_authenticated(request):
|
||||
await self.app(scope, receive, send)
|
||||
return None
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@ import functools
|
||||
from collections.abc import Sequence
|
||||
from datetime import datetime
|
||||
|
||||
from sqlalchemy import delete, or_, select, update
|
||||
from sqlalchemy import delete, func, or_, select, update
|
||||
from sqlalchemy.orm import Query, Session, selectinload
|
||||
|
||||
from decorators.database import begin_session
|
||||
@@ -103,7 +103,15 @@ class DBPlatformsHandler(DBBaseHandler):
|
||||
query: Query = None, # type: ignore
|
||||
session: Session = None, # type: ignore
|
||||
) -> Platform | None:
|
||||
return session.scalar(query.filter_by(fs_slug=fs_slug).limit(1))
|
||||
platform = session.scalar(query.filter_by(fs_slug=fs_slug).limit(1))
|
||||
if platform:
|
||||
return platform
|
||||
|
||||
# Folder names are matched case-insensitively everywhere else, so a
|
||||
# folder renamed only in case is the same platform, not a new one.
|
||||
return session.scalar(
|
||||
query.filter(func.lower(Platform.fs_slug) == fs_slug.lower()).limit(1)
|
||||
)
|
||||
|
||||
@begin_session
|
||||
@with_firmware
|
||||
|
||||
@@ -77,3 +77,22 @@ class FSPlatformsHandler(FSHandler):
|
||||
platforms = self._exclude_platforms(platforms)
|
||||
|
||||
return platforms
|
||||
|
||||
async def find_ambiguous_folders(self, fs_slug: str) -> list[str]:
|
||||
"""The folders a single config mapping would cover, when it covers several.
|
||||
|
||||
Folder names key the config case-insensitively, so siblings differing
|
||||
only by case (which only a case-sensitive filesystem allows) share one
|
||||
entry and cannot be mapped apart.
|
||||
|
||||
Args:
|
||||
fs_slug: The folder name a mapping is being written for.
|
||||
|
||||
Returns:
|
||||
The matching folders, sorted, or empty when the name is unambiguous.
|
||||
"""
|
||||
folded = fs_slug.lower()
|
||||
matches = sorted(
|
||||
folder for folder in await self.get_platforms() if folder.lower() == folded
|
||||
)
|
||||
return matches if len(matches) > 1 else []
|
||||
|
||||
@@ -80,7 +80,11 @@ from models.user import User
|
||||
from utils import emoji
|
||||
from utils.audio_tags import persist_embedded_cover, remove_persisted_cover
|
||||
from utils.filesystem import sanitize_filename
|
||||
from utils.platform_aliases import resolve_fs_slug, resolve_platform_slug
|
||||
from utils.platform_aliases import (
|
||||
resolve_fs_folder,
|
||||
resolve_fs_slug,
|
||||
resolve_platform_slug,
|
||||
)
|
||||
|
||||
LOGGER_MODULE_NAME = {"module_name": "scan"}
|
||||
|
||||
@@ -292,7 +296,11 @@ async def scan_platform(
|
||||
if platform:
|
||||
known_fs_slug = resolve_fs_slug(platform.slug, cnfg)
|
||||
if known_fs_slug:
|
||||
platform_attrs["fs_slug"] = known_fs_slug
|
||||
# `resolve_fs_slug` answers with a lowercased config key, but
|
||||
# every path is built from the folder's own casing.
|
||||
platform_attrs["fs_slug"] = (
|
||||
resolve_fs_folder(known_fs_slug, fs_platforms) or known_fs_slug
|
||||
)
|
||||
|
||||
platform_attrs["slug"] = resolve_platform_slug(fs_slug, cnfg)
|
||||
|
||||
|
||||
@@ -10,6 +10,7 @@ from handler.streaming.config import (
|
||||
ResolvedContainer,
|
||||
containers_by_key,
|
||||
containers_for_platform,
|
||||
entry_for_platform,
|
||||
)
|
||||
from handler.streaming.session_store import get_live_session
|
||||
from models.rom import Rom
|
||||
@@ -106,30 +107,37 @@ async def find_session_for_user(
|
||||
return None
|
||||
|
||||
|
||||
def named_container(platform: str, container_key: str) -> ResolvedContainer:
|
||||
"""A container serving a platform, found by key so one in a later pool stays
|
||||
reachable. Raises 404 when the key names no such container."""
|
||||
candidate = entry_for_platform(containers_by_key().get(container_key, []), platform)
|
||||
if candidate is None:
|
||||
raise HTTPException(
|
||||
status_code=404,
|
||||
detail=f"No streaming container '{container_key}' for platform '{platform}'",
|
||||
)
|
||||
return candidate
|
||||
|
||||
|
||||
async def resolve_named_container(
|
||||
platform: str, container_key: str
|
||||
) -> tuple[ResolvedContainer, str, dict[str, Any] | None]:
|
||||
"""One named container serving a platform, plus whatever session it holds.
|
||||
"""A named container plus whatever session it holds.
|
||||
|
||||
Returns (container, session_key, session), the session being None when the
|
||||
container is free or draining. Raises 404 when the key names no container
|
||||
serving this platform.
|
||||
container is free or draining.
|
||||
"""
|
||||
for candidate in containers_for_platform(platform):
|
||||
session_key = candidate.key
|
||||
if session_key != container_key:
|
||||
continue
|
||||
return candidate, session_key, await get_live_session(session_key)
|
||||
raise HTTPException(
|
||||
status_code=404,
|
||||
detail=f"No streaming container '{container_key}' for platform '{platform}'",
|
||||
return (
|
||||
named_container(platform, container_key),
|
||||
container_key,
|
||||
await get_live_session(container_key),
|
||||
)
|
||||
|
||||
|
||||
async def resolve_owned_session(
|
||||
platform: str, request: Request
|
||||
) -> tuple[ResolvedContainer, str, dict[str, Any]]:
|
||||
"""Find the caller's session among the platform's containers.
|
||||
"""Find the caller's session in the platform's first pool.
|
||||
|
||||
Returns (container, session_key, session). Raises 404 when the platform has
|
||||
no configured container or nothing is active, 403 when every active session
|
||||
|
||||
@@ -3,12 +3,15 @@
|
||||
The raw YAML is loose: a container may serve one platform or a map of them, and
|
||||
may leave its broker host to be derived. Resolution is memoized until the config
|
||||
changes, so an unusable container is reported once rather than once per lookup.
|
||||
A platform's containers form pools of interchangeable members, and a game claim
|
||||
only walks the first.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import secrets
|
||||
from collections.abc import Iterable, Sequence
|
||||
from dataclasses import dataclass
|
||||
from typing import Any
|
||||
from urllib.parse import urlparse, urlunparse
|
||||
@@ -517,38 +520,63 @@ def resolve_containers() -> tuple[ResolvedContainer, ...]:
|
||||
for row, platform in _platform_entries(dict(entry)):
|
||||
resolved.append(_resolve_one(row, platform, entry.get("label")))
|
||||
|
||||
_warn_about_later_pools(resolved)
|
||||
_cache_fingerprint = fingerprint
|
||||
_cached = tuple(resolved)
|
||||
return _cached
|
||||
|
||||
|
||||
def containers_for_platform(platform: str) -> list[ResolvedContainer]:
|
||||
"""Every container serving a platform, in config order.
|
||||
def _pools(containers: Iterable[ResolvedContainer]) -> list[list[ResolvedContainer]]:
|
||||
"""Group containers into pools of interchangeable members. A pool sits at its
|
||||
first member's config position, and members keep config order."""
|
||||
pools: list[list[ResolvedContainer]] = []
|
||||
for container in containers:
|
||||
pool = next((p for p in pools if p[0].interchangeable_with(container)), None)
|
||||
if pool is None:
|
||||
pools.append([container])
|
||||
else:
|
||||
pool.append(container)
|
||||
return pools
|
||||
|
||||
More than one entry is a pool and the claim takes the first free one, so a
|
||||
container that disagrees with the head on emulator or card sync is not a
|
||||
pool member and is left out.
|
||||
"""
|
||||
lower = platform.lower()
|
||||
candidates: list[ResolvedContainer] = []
|
||||
for container in resolve_containers():
|
||||
if container.platform.lower() != lower:
|
||||
continue
|
||||
if not container.key:
|
||||
# Nothing to dial, so a claim would have nowhere to go. The fleet
|
||||
# view still lists it, which is where the operator sees why.
|
||||
continue
|
||||
if candidates and not candidates[0].interchangeable_with(container):
|
||||
|
||||
def _pools_by_platform(
|
||||
resolved: Iterable[ResolvedContainer],
|
||||
) -> dict[str, list[list[ResolvedContainer]]]:
|
||||
"""Every platform's pools, keyed by the lowercased platform."""
|
||||
by_platform: dict[str, list[ResolvedContainer]] = {}
|
||||
for container in resolved:
|
||||
# Nothing to dial, so a claim would have nowhere to go. The fleet view
|
||||
# still lists it, which is where the operator sees why.
|
||||
if container.key:
|
||||
by_platform.setdefault(container.platform.lower(), []).append(container)
|
||||
return {platform: _pools(members) for platform, members in by_platform.items()}
|
||||
|
||||
|
||||
def _warn_about_later_pools(resolved: Sequence[ResolvedContainer]) -> None:
|
||||
"""Name every container a game claim can never reach, once per config."""
|
||||
for pools in _pools_by_platform(resolved).values():
|
||||
later = [c.key for pool in pools[1:] for c in pool]
|
||||
if later:
|
||||
log.warning(
|
||||
"container for platform '%s' disagrees with the first one on "
|
||||
"emulator, memory card sync or protocol, so it is not a pool "
|
||||
"member, skipping: %s",
|
||||
platform,
|
||||
container.key,
|
||||
"containers for platform '%s' disagree on emulator, memory card "
|
||||
"sync, save picker or protocol, so game claims only use the first "
|
||||
"pool; never claimed for a game: %s",
|
||||
pools[0][0].platform,
|
||||
", ".join(later),
|
||||
)
|
||||
continue
|
||||
candidates.append(container)
|
||||
return candidates
|
||||
|
||||
|
||||
def pools_for_platform(platform: str) -> list[list[ResolvedContainer]]:
|
||||
"""Every container serving a platform, grouped into pools. A container that
|
||||
matches no other is a pool of one."""
|
||||
return _pools_by_platform(resolve_containers()).get(platform.lower(), [])
|
||||
|
||||
|
||||
def containers_for_platform(platform: str) -> list[ResolvedContainer]:
|
||||
"""The platform's first pool, which a game claim walks for the first free
|
||||
container, in config order."""
|
||||
pools = pools_for_platform(platform)
|
||||
return pools[0] if pools else []
|
||||
|
||||
|
||||
def containers_by_key() -> dict[str, list[ResolvedContainer]]:
|
||||
@@ -560,6 +588,14 @@ def containers_by_key() -> dict[str, list[ResolvedContainer]]:
|
||||
return grouped
|
||||
|
||||
|
||||
def entry_for_platform(
|
||||
entries: Sequence[ResolvedContainer], platform: str
|
||||
) -> ResolvedContainer | None:
|
||||
"""The record among one container's entries that serves this platform."""
|
||||
lower = platform.lower()
|
||||
return next((e for e in entries if e.platform.lower() == lower), None)
|
||||
|
||||
|
||||
def container_for_session(
|
||||
grouped: dict[str, list[ResolvedContainer]], container_key: str, platform: Any
|
||||
) -> ResolvedContainer | None:
|
||||
@@ -569,21 +605,14 @@ def container_for_session(
|
||||
entries = grouped.get(container_key)
|
||||
if not entries:
|
||||
return None
|
||||
if isinstance(platform, str):
|
||||
lower = platform.lower()
|
||||
for entry in entries:
|
||||
if entry.platform.lower() == lower:
|
||||
return entry
|
||||
return entries[0]
|
||||
entry = entry_for_platform(entries, platform) if isinstance(platform, str) else None
|
||||
return entry or entries[0]
|
||||
|
||||
|
||||
def configured_emulator(platform: str) -> str:
|
||||
"""The emulator a configured container serves this platform with, if any."""
|
||||
lower = platform.lower()
|
||||
for container in resolve_containers():
|
||||
if container.platform.lower() == lower:
|
||||
return container.emulator
|
||||
return ""
|
||||
entry = entry_for_platform(resolve_containers(), platform)
|
||||
return entry.emulator if entry else ""
|
||||
|
||||
|
||||
def streaming_enabled() -> bool:
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import logging
|
||||
import os
|
||||
from contextlib import contextmanager
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
@@ -16,6 +17,22 @@ from config.config_manager import (
|
||||
)
|
||||
|
||||
|
||||
@contextmanager
|
||||
def capture_romm_logs(caplog, level=logging.WARNING):
|
||||
"""Capture the `romm` logger, whose records never reach caplog on their own.
|
||||
|
||||
It sets `propagate = False`, so caplog's handler has to be attached to it
|
||||
directly rather than to the root logger.
|
||||
"""
|
||||
romm_logger = logging.getLogger("romm")
|
||||
romm_logger.addHandler(caplog.handler)
|
||||
try:
|
||||
with caplog.at_level(level, logger="romm"):
|
||||
yield caplog
|
||||
finally:
|
||||
romm_logger.removeHandler(caplog.handler)
|
||||
|
||||
|
||||
def test_config_loader():
|
||||
loader = ConfigManager(
|
||||
os.path.join(Path(__file__).resolve().parent, "fixtures", "config/config.yml")
|
||||
@@ -524,15 +541,8 @@ def test_legacy_streaming_container_logs_deprecation_warning(caplog, tmp_path):
|
||||
" broker_host: http://192.168.1.51:8000\n"
|
||||
" label: PCSX2\n"
|
||||
)
|
||||
# The "romm" logger has propagate=False, so caplog's handler must be
|
||||
# added directly to it rather than relying on root-logger propagation.
|
||||
romm_logger = logging.getLogger("romm")
|
||||
romm_logger.addHandler(caplog.handler)
|
||||
try:
|
||||
with caplog.at_level(logging.WARNING, logger="romm"):
|
||||
loader = ConfigManager(str(config_file))
|
||||
finally:
|
||||
romm_logger.removeHandler(caplog.handler)
|
||||
with capture_romm_logs(caplog):
|
||||
loader = ConfigManager(str(config_file))
|
||||
|
||||
assert loader.config.STREAMING_CONTAINERS
|
||||
assert "deprecated" in caplog.text
|
||||
@@ -552,13 +562,8 @@ def test_webstation_streaming_container_does_not_warn(caplog, tmp_path):
|
||||
" platforms:\n"
|
||||
" ps2: pcsx2\n"
|
||||
)
|
||||
romm_logger = logging.getLogger("romm")
|
||||
romm_logger.addHandler(caplog.handler)
|
||||
try:
|
||||
with caplog.at_level(logging.WARNING, logger="romm"):
|
||||
ConfigManager(str(config_file))
|
||||
finally:
|
||||
romm_logger.removeHandler(caplog.handler)
|
||||
with capture_romm_logs(caplog):
|
||||
ConfigManager(str(config_file))
|
||||
|
||||
assert "deprecated" not in caplog.text
|
||||
|
||||
@@ -630,6 +635,48 @@ def test_platform_binding_lookup_ignores_case(tmp_path):
|
||||
assert loader.config.PLATFORMS_BINDING == {}
|
||||
|
||||
|
||||
def test_case_variant_folder_keys_collapse_with_a_warning(caplog, tmp_path):
|
||||
"""One key covers both, so the dropped mapping must not vanish silently."""
|
||||
with capture_romm_logs(caplog):
|
||||
loader = _write_config(
|
||||
tmp_path, ' platforms:\n PSX: "ps2"\n psx: "psx"\n'
|
||||
)
|
||||
|
||||
assert loader.config.PLATFORMS_BINDING == {"psx": "psx"}
|
||||
assert "case variant" in caplog.text
|
||||
assert "ps2" in caplog.text
|
||||
|
||||
|
||||
def test_identical_case_variant_mappings_do_not_warn(caplog, tmp_path):
|
||||
with capture_romm_logs(caplog):
|
||||
loader = _write_config(
|
||||
tmp_path, ' platforms:\n PSX: "psx"\n psx: "psx"\n'
|
||||
)
|
||||
|
||||
assert loader.config.PLATFORMS_BINDING == {"psx": "psx"}
|
||||
assert "case variant" not in caplog.text
|
||||
|
||||
|
||||
def test_rebinding_a_folder_replaces_the_existing_platform(tmp_path):
|
||||
loader = _write_config(tmp_path, ' platforms:\n GameCube: "ngc"\n')
|
||||
|
||||
loader.add_platform_binding("GameCube", "wii")
|
||||
|
||||
assert loader.config.PLATFORMS_BINDING == {"gamecube": "wii"}
|
||||
reloaded = ConfigManager(loader.config_file)
|
||||
assert reloaded.config.PLATFORMS_BINDING == {"gamecube": "wii"}
|
||||
|
||||
|
||||
def test_reparenting_a_folder_replaces_the_existing_version(tmp_path):
|
||||
loader = _write_config(tmp_path, ' versions:\n NAOMI: "arcade"\n')
|
||||
|
||||
loader.add_platform_version("naomi", "dc")
|
||||
|
||||
assert loader.config.PLATFORMS_VERSIONS == {"naomi": "dc"}
|
||||
reloaded = ConfigManager(loader.config_file)
|
||||
assert reloaded.config.PLATFORMS_VERSIONS == {"naomi": "dc"}
|
||||
|
||||
|
||||
def _write_emulatorjs_config(tmp_path: Path, emulatorjs_block: str) -> ConfigManager:
|
||||
config_file = tmp_path / "config.yml"
|
||||
config_file.write_text(f"emulatorjs:\n{emulatorjs_block}")
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
from unittest.mock import patch
|
||||
from unittest.mock import AsyncMock, patch
|
||||
|
||||
from fastapi import status
|
||||
|
||||
@@ -87,6 +87,46 @@ def test_add_platform_version_payload_shape(client, access_token: str):
|
||||
add_platform_version.assert_called_once_with("n64", "1.0")
|
||||
|
||||
|
||||
def test_mapping_a_folder_with_a_case_variant_sibling_is_rejected(
|
||||
client, access_token: str
|
||||
):
|
||||
"""One config key covers both, so the write would remap the sibling too."""
|
||||
with (
|
||||
patch(
|
||||
"endpoints.configs.fs_platform_handler.find_ambiguous_folders",
|
||||
AsyncMock(return_value=["PSX", "psx"]),
|
||||
),
|
||||
patch.object(cm, "add_platform_binding") as add_platform_binding,
|
||||
):
|
||||
response = client.post(
|
||||
"/api/config/system/platforms",
|
||||
headers={"Authorization": f"Bearer {access_token}"},
|
||||
json={"fs_slug": "PSX", "slug": "ps2"},
|
||||
)
|
||||
|
||||
assert response.status_code == status.HTTP_409_CONFLICT
|
||||
assert "differ only by case" in response.json()["detail"]
|
||||
add_platform_binding.assert_not_called()
|
||||
|
||||
|
||||
def test_mapping_a_folder_whose_name_is_unique_is_allowed(client, access_token: str):
|
||||
with (
|
||||
patch(
|
||||
"endpoints.configs.fs_platform_handler.find_ambiguous_folders",
|
||||
AsyncMock(return_value=[]),
|
||||
),
|
||||
patch.object(cm, "add_platform_binding") as add_platform_binding,
|
||||
):
|
||||
response = client.post(
|
||||
"/api/config/system/platforms",
|
||||
headers={"Authorization": f"Bearer {access_token}"},
|
||||
json={"fs_slug": "Nintendo 64", "slug": "n64"},
|
||||
)
|
||||
|
||||
assert response.status_code == status.HTTP_200_OK
|
||||
add_platform_binding.assert_called_once_with("Nintendo 64", "n64")
|
||||
|
||||
|
||||
def test_add_exclusion_payload_shape(client, access_token: str):
|
||||
with patch.object(cm, "add_exclusion") as add_exclusion:
|
||||
response = client.post(
|
||||
|
||||
@@ -54,6 +54,7 @@ from handler.streaming.config import (
|
||||
ResolvedContainer,
|
||||
_derive_broker_host,
|
||||
emulator_display_label,
|
||||
pools_for_platform,
|
||||
reset_cache,
|
||||
resolve_entry,
|
||||
)
|
||||
@@ -536,7 +537,7 @@ def test_clears_stale_saves_has_no_picker_to_gate_on_a_legacy_container(caplog):
|
||||
assert "clears_stale_saves" in caplog.text
|
||||
|
||||
|
||||
def test_a_container_that_disagrees_on_clearing_saves_is_not_a_pool_member(caplog):
|
||||
def test_a_container_that_disagrees_on_clearing_saves_is_a_pool_of_its_own(caplog):
|
||||
"""The picker is advertised from the head of the pool, so a member that
|
||||
keeps its own newer files would take the pick and silently discard it."""
|
||||
first = {
|
||||
@@ -562,7 +563,7 @@ def test_a_container_that_disagrees_on_clearing_saves_is_not_a_pool_member(caplo
|
||||
finally:
|
||||
romm_logger.removeHandler(caplog.handler)
|
||||
assert [c.clears_stale_saves for c in candidates] == [True]
|
||||
assert "not a pool" in caplog.text
|
||||
assert "never claimed for a game" in caplog.text
|
||||
|
||||
|
||||
def test_legacy_containers_still_pool_under_an_inert_clearing_flag():
|
||||
@@ -1223,6 +1224,22 @@ def test_pool_409s_only_once_every_container_is_held(
|
||||
assert "2 containers" in r3.json()["detail"]["message"]
|
||||
|
||||
|
||||
def test_a_claim_never_lands_in_a_later_pool(
|
||||
client, access_token, viewer_access_token, rom: Rom
|
||||
):
|
||||
"""Only the first pool matches the settings a claim is validated against,
|
||||
so a later pool stays out of reach even when it is the only one free."""
|
||||
later = {**_pool_member(rom, 1), "emulator": "other"}
|
||||
with _streaming(_pool_member(rom, 0), later):
|
||||
r1 = _claim_ok(client, access_token, rom.id)
|
||||
r2 = _claim_ok(client, viewer_access_token, rom.id)
|
||||
assert _session_raw(later) is None
|
||||
assert len(pools_for_platform(rom.platform_slug)) == 2
|
||||
assert r1.status_code == 202
|
||||
assert r1.json()["container"] == _key_of(_pool_member(rom, 0))
|
||||
assert r2.status_code == 409
|
||||
|
||||
|
||||
def test_a_pool_does_not_roll_its_own_holder_onto_a_second_container(
|
||||
client, access_token, rom: Rom
|
||||
):
|
||||
@@ -1405,6 +1422,103 @@ def test_admin_release_rejects_a_container_that_serves_another_platform(
|
||||
assert r.status_code == 404
|
||||
|
||||
|
||||
def _in_a_later_ps2_pool() -> dict:
|
||||
"""A second webstation that disagrees with `_webstation()` on the ps2
|
||||
emulator, so it forms a later ps2 pool."""
|
||||
return _webstation(
|
||||
host="http://192.168.1.11:3000",
|
||||
broker_host="http://192.168.1.11:8000",
|
||||
platforms={"ps2": "play", "ngc": "dolphin"},
|
||||
)
|
||||
|
||||
|
||||
def test_admin_release_ends_a_session_on_a_container_in_a_later_pool(
|
||||
client, access_token
|
||||
):
|
||||
"""A game claim never reaches a later pool, but an admin can still end a
|
||||
session there by naming the container."""
|
||||
later = _in_a_later_ps2_pool()
|
||||
with _streaming(_webstation(), later):
|
||||
key = _key_of(later)
|
||||
assert key not in [c.key for c in streaming.containers_for_platform("ps2")]
|
||||
assert _desktop(client, access_token, key)[0].status_code == 200
|
||||
with patch("handler.streaming.commands.stop", return_value=None):
|
||||
r = client.delete(
|
||||
"/api/streaming/sessions/ps2",
|
||||
params={"container": key},
|
||||
headers=_auth(access_token),
|
||||
)
|
||||
assert r.status_code == 200
|
||||
assert r.json()["status"] == "released"
|
||||
assert _session_raw(later) is None
|
||||
|
||||
|
||||
def test_heartbeat_naming_the_container_refreshes_a_desktop_in_a_later_pool(
|
||||
client, access_token
|
||||
):
|
||||
"""The platform's lookup only walks the first pool, so only the named key
|
||||
keeps this desktop claim fresh."""
|
||||
later = _in_a_later_ps2_pool()
|
||||
with _streaming(_webstation(), later):
|
||||
key = _key_of(later)
|
||||
assert _desktop(client, access_token, key)[0].status_code == 200
|
||||
_age_session_on(later, session_store._STREAMING_SESSION_STALE_SECONDS + 60)
|
||||
r = client.post(
|
||||
"/api/streaming/sessions/ps2/heartbeat",
|
||||
params={"container": key},
|
||||
headers=_auth(access_token),
|
||||
)
|
||||
session = json.loads(_session_raw(later))
|
||||
assert r.status_code == 200
|
||||
assert r.json()["status"] == "active"
|
||||
assert not session_store.session_is_stale(session)
|
||||
|
||||
|
||||
def test_heartbeat_naming_a_released_container_reports_ended(client, access_token):
|
||||
"""A session the caller holds on another of the platform's containers must
|
||||
not answer for the named one."""
|
||||
later = _in_a_later_ps2_pool()
|
||||
with _streaming(_webstation(), later):
|
||||
key = _key_of(later)
|
||||
assert (
|
||||
_desktop(client, access_token, _key_of(_webstation()))[0].status_code == 200
|
||||
)
|
||||
assert _desktop(client, access_token, key)[0].status_code == 200
|
||||
with patch("handler.streaming.commands.stop", return_value=None):
|
||||
released = client.delete(
|
||||
"/api/streaming/sessions/ps2",
|
||||
params={"container": key},
|
||||
headers=_auth(access_token),
|
||||
)
|
||||
assert released.status_code == 200
|
||||
r = client.post(
|
||||
"/api/streaming/sessions/ps2/heartbeat",
|
||||
params={"container": key},
|
||||
headers=_auth(access_token),
|
||||
)
|
||||
assert r.status_code == 200
|
||||
assert r.json()["status"] == "ended"
|
||||
|
||||
|
||||
def test_heartbeat_naming_a_container_leaves_another_users_session_alone(
|
||||
client, access_token, viewer_access_token
|
||||
):
|
||||
later = _in_a_later_ps2_pool()
|
||||
with _streaming(_webstation(), later):
|
||||
key = _key_of(later)
|
||||
assert _desktop(client, access_token, key)[0].status_code == 200
|
||||
_age_session_on(later, session_store._STREAMING_SESSION_STALE_SECONDS + 60)
|
||||
r = client.post(
|
||||
"/api/streaming/sessions/ps2/heartbeat",
|
||||
params={"container": key},
|
||||
headers=_auth(viewer_access_token),
|
||||
)
|
||||
session = json.loads(_session_raw(later))
|
||||
assert r.status_code == 200
|
||||
assert r.json()["status"] == "ended"
|
||||
assert session_store.session_is_stale(session)
|
||||
|
||||
|
||||
def test_status_finds_the_termination_on_whichever_container_held_it(
|
||||
client, access_token, viewer_access_token, rom: Rom
|
||||
):
|
||||
@@ -1445,9 +1559,9 @@ def test_heartbeat_refreshes_the_session_on_the_container_that_holds_it(
|
||||
assert after > before
|
||||
|
||||
|
||||
def test_a_container_that_disagrees_on_the_emulator_is_not_a_pool_member(caplog):
|
||||
def test_a_container_that_disagrees_on_the_emulator_is_a_later_pool(caplog):
|
||||
"""Pool members file states and cards in one place, so an entry naming a
|
||||
different emulator is a separate setup rather than a spare container."""
|
||||
different emulator is a pool of its own rather than a spare container."""
|
||||
first = {
|
||||
"platform": "ps2",
|
||||
"host": "http://192.168.1.10:3000",
|
||||
@@ -1457,16 +1571,35 @@ def test_a_container_that_disagrees_on_the_emulator_is_not_a_pool_member(caplog)
|
||||
second = {**first, "host": "http://192.168.1.11:3000"}
|
||||
second["broker_host"] = "http://192.168.1.11:8000"
|
||||
second["emulator"] = "play"
|
||||
third = {
|
||||
**first,
|
||||
"host": "http://192.168.1.12:3000",
|
||||
"broker_host": "http://192.168.1.12:8000",
|
||||
}
|
||||
romm_logger = logging.getLogger("romm")
|
||||
romm_logger.addHandler(caplog.handler)
|
||||
try:
|
||||
with _streaming(first, second):
|
||||
with _streaming(first, second, third):
|
||||
with caplog.at_level(logging.WARNING, logger="romm"):
|
||||
pools = pools_for_platform("ps2")
|
||||
candidates = streaming.containers_for_platform("ps2")
|
||||
finally:
|
||||
romm_logger.removeHandler(caplog.handler)
|
||||
assert [c.emulator for c in candidates] == ["pcsx2"]
|
||||
assert "not a pool" in caplog.text
|
||||
assert [[c.emulator for c in pool] for pool in pools] == [
|
||||
["pcsx2", "pcsx2"],
|
||||
["play"],
|
||||
]
|
||||
assert candidates == pools[0]
|
||||
# Once per config, not once per lookup.
|
||||
assert caplog.text.count("never claimed for a game") == 1
|
||||
assert _key_of(second) in caplog.text
|
||||
|
||||
|
||||
def test_a_lone_container_is_a_pool_of_one(rom: Rom):
|
||||
member = _pool_member(rom, 0)
|
||||
with _streaming(member):
|
||||
pools = pools_for_platform(rom.platform_slug)
|
||||
assert [[c.key for c in pool] for pool in pools] == [[_key_of(member)]]
|
||||
|
||||
|
||||
def test_webstation_pool_members_at_different_subfolders_are_still_a_pool(caplog):
|
||||
@@ -1498,7 +1631,7 @@ def test_webstation_pool_members_at_different_subfolders_are_still_a_pool(caplog
|
||||
"http://192.168.1.10:8000",
|
||||
"http://192.168.1.11:8000",
|
||||
]
|
||||
assert "not a pool" not in caplog.text
|
||||
assert "never claimed for a game" not in caplog.text
|
||||
|
||||
|
||||
def test_a_proxied_host_disagreeing_with_its_subfolder_cannot_be_claimed(caplog):
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import asyncio
|
||||
import re
|
||||
from typing import Any
|
||||
|
||||
from itsdangerous import URLSafeSerializer
|
||||
from starlette.applications import Starlette
|
||||
@@ -10,9 +11,10 @@ from starlette.requests import Request
|
||||
from starlette.responses import JSONResponse, PlainTextResponse
|
||||
from starlette.routing import Route
|
||||
from starlette.testclient import TestClient
|
||||
from starlette.types import ASGIApp, Receive, Scope, Send
|
||||
|
||||
from config import ROMM_AUTH_SECRET_KEY
|
||||
from handler.auth.constants import ALGORITHM
|
||||
from handler.auth.constants import ALGORITHM, SESSION_COOKIE_NAME
|
||||
from handler.auth.middleware.csrf_middleware import CSRFMiddleware
|
||||
from handler.auth.middleware.session_middleware import SessionMiddleware
|
||||
from models.user import User
|
||||
@@ -58,6 +60,30 @@ def create_test_app(**csrf_kwargs) -> Starlette:
|
||||
return Starlette(routes=routes, middleware=middleware)
|
||||
|
||||
|
||||
def create_session_app(session: dict[str, Any]) -> Starlette:
|
||||
"""A CSRF app behind a resolved session, as `main.py` orders them."""
|
||||
|
||||
class StubSessionMiddleware:
|
||||
def __init__(self, app: ASGIApp) -> None:
|
||||
self.app = app
|
||||
|
||||
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
|
||||
scope["session"] = dict(session)
|
||||
await self.app(scope, receive, send)
|
||||
|
||||
async def post_handler(request: Request) -> JSONResponse:
|
||||
return JSONResponse({"status": "success"})
|
||||
|
||||
return Starlette(
|
||||
routes=[Route("/post", post_handler, methods=["POST"])],
|
||||
middleware=[
|
||||
Middleware(StubSessionMiddleware),
|
||||
Middleware(AuthenticationMiddleware, backend=BasicAuthBackend()),
|
||||
Middleware(CSRFMiddleware, secret="test-secret"),
|
||||
],
|
||||
)
|
||||
|
||||
|
||||
class TestCSRFMiddleware:
|
||||
def test_csrf_cookie_set_on_first_get(self) -> None:
|
||||
"""A GET request should set the CSRF cookie if none exists."""
|
||||
@@ -203,6 +229,22 @@ class TestCSRFMiddleware:
|
||||
resp = client.post("/post", headers={"Authorization": "Bearer token"})
|
||||
assert resp.status_code == 200
|
||||
|
||||
def test_authenticated_session_keeps_csrf_on_despite_auth_header(self) -> None:
|
||||
"""The session authenticates first, so the header must not exempt it."""
|
||||
client = TestClient(create_session_app({"iss": "romm:auth", "sub": "victim"}))
|
||||
client.cookies.set(SESSION_COOKIE_NAME, "live-session-id")
|
||||
|
||||
resp = client.post("/post", headers={"Authorization": "Bearer anything"})
|
||||
assert resp.status_code == 403
|
||||
|
||||
def test_stale_session_still_lets_the_auth_header_through(self) -> None:
|
||||
"""A cookie the session store rejected leaves the header as the credential."""
|
||||
client = TestClient(create_session_app({}))
|
||||
client.cookies.set(SESSION_COOKIE_NAME, "expired-session-id")
|
||||
|
||||
resp = client.post("/post", headers={"Authorization": "Bearer token"})
|
||||
assert resp.status_code == 200
|
||||
|
||||
def test_non_http_scope_bypass(self) -> None:
|
||||
"""WebSocket (or other non-HTTP) scopes should pass through."""
|
||||
# Manual ASGI call; TestClient doesn't expose WebSocket easily
|
||||
|
||||
@@ -2,6 +2,32 @@ from handler.database import db_platform_handler
|
||||
from models.platform import Platform
|
||||
|
||||
|
||||
def test_lookup_finds_a_folder_renamed_only_in_case():
|
||||
"""A rescan must reuse the row, not add a second platform beside it."""
|
||||
stored = db_platform_handler.add_platform(
|
||||
Platform(name="N64", slug="n64", fs_slug="nintendo 64")
|
||||
)
|
||||
|
||||
found = db_platform_handler.get_platform_by_fs_slug("Nintendo 64")
|
||||
|
||||
assert found is not None
|
||||
assert found.id == stored.id
|
||||
|
||||
|
||||
def test_lookup_returns_the_exactly_named_folder_when_one_exists():
|
||||
"""The exact spelling is tried first, for backends that can tell them apart.
|
||||
|
||||
MariaDB and MySQL match case-insensitively by collation, so only the
|
||||
exactly-named row is asserted here; PostgreSQL additionally distinguishes
|
||||
the sibling.
|
||||
"""
|
||||
exact = db_platform_handler.add_platform(
|
||||
Platform(name="PlayStation", slug="psx", fs_slug="psx")
|
||||
)
|
||||
|
||||
assert db_platform_handler.get_platform_by_fs_slug("psx").id == exact.id
|
||||
|
||||
|
||||
def test_rescan_preserves_user_authored_fields(platform):
|
||||
"""A rescan merges a freshly built Platform over the existing row.
|
||||
|
||||
|
||||
@@ -205,6 +205,24 @@ class TestFSPlatformsHandler:
|
||||
assert "n64" in result
|
||||
assert "psx" not in result
|
||||
|
||||
async def test_find_ambiguous_folders_reports_case_variant_siblings(
|
||||
self, handler: FSPlatformsHandler
|
||||
):
|
||||
"""One config key covers both, so they cannot be mapped apart."""
|
||||
with patch.object(handler, "get_platforms", return_value=["PSX", "n64", "psx"]):
|
||||
assert await handler.find_ambiguous_folders("psx") == ["PSX", "psx"]
|
||||
assert await handler.find_ambiguous_folders("PSX") == ["PSX", "psx"]
|
||||
|
||||
async def test_find_ambiguous_folders_ignores_an_unshared_name(
|
||||
self, handler: FSPlatformsHandler
|
||||
):
|
||||
with patch.object(
|
||||
handler, "get_platforms", return_value=["Nintendo 64", "psx"]
|
||||
):
|
||||
assert await handler.find_ambiguous_folders("Nintendo 64") == []
|
||||
assert await handler.find_ambiguous_folders("nintendo 64") == []
|
||||
assert await handler.find_ambiguous_folders("absent") == []
|
||||
|
||||
async def test_get_platforms_calls_list_directories_with_correct_path(
|
||||
self, handler: FSPlatformsHandler, config
|
||||
):
|
||||
|
||||
@@ -18,6 +18,11 @@ NGINX_UPSTREAM_IDLE_TIMEOUT = 60
|
||||
# pool is off entirely and the timeout invariant stops meaning anything.
|
||||
NGINX_UPSTREAM_KEEPALIVE_SINCE = (1, 29, 7)
|
||||
|
||||
# njs 0.9.7 dropped the "js vm init njs" notice it logged on every start. nginx
|
||||
# 1.30.0 also shipped builds bundling njs 0.9.6, so 1.30.1 is the first release
|
||||
# that never logs it.
|
||||
NJS_QUIET_STARTUP_SINCE = (1, 30, 1)
|
||||
|
||||
REQUIRED_GZIP_TYPES = [
|
||||
"application/wasm", # EmulatorJS, js-dos and FAKE-08 cores
|
||||
"image/svg+xml", # player logos and favicons
|
||||
@@ -47,16 +52,32 @@ def test_compressible_types_are_gzipped(gzip_types: set[str], media_type: str) -
|
||||
assert media_type in gzip_types, f"{media_type} would be served uncompressed"
|
||||
|
||||
|
||||
def test_nginx_defaults_upstream_keepalive_on() -> None:
|
||||
def _format(version: tuple[int, ...]) -> str:
|
||||
return ".".join(str(part) for part in version)
|
||||
|
||||
|
||||
def _nginx_version() -> tuple[int, ...]:
|
||||
match = re.search(r"^ARG NGINX_VERSION=(\S+)", DOCKERFILE.read_text(), re.M)
|
||||
assert match, "docker/Dockerfile is missing an ARG NGINX_VERSION pin"
|
||||
version = tuple(int(part) for part in match.group(1).split("."))
|
||||
return tuple(int(part) for part in match.group(1).split("."))
|
||||
|
||||
|
||||
def test_nginx_defaults_upstream_keepalive_on() -> None:
|
||||
version = _nginx_version()
|
||||
assert version >= NGINX_UPSTREAM_KEEPALIVE_SINCE, (
|
||||
f"nginx {match.group(1)} does not pool upstream connections by default, "
|
||||
f"nginx {_format(version)} does not pool upstream connections by default, "
|
||||
f"so every API request opens a new one"
|
||||
)
|
||||
|
||||
|
||||
def test_nginx_starts_without_the_njs_notice() -> None:
|
||||
version = _nginx_version()
|
||||
assert version >= NJS_QUIET_STARTUP_SINCE, (
|
||||
f"nginx {_format(version)} bundles an njs that logs a 'js vm init njs' "
|
||||
f"notice on every start, because the config imports a VM at the http level"
|
||||
)
|
||||
|
||||
|
||||
def test_gunicorn_outlives_nginx_upstream_idle_timeout() -> None:
|
||||
assert _init_script_keepalive() > NGINX_UPSTREAM_IDLE_TIMEOUT
|
||||
|
||||
|
||||
@@ -7,6 +7,7 @@ from config.config_manager import Config
|
||||
from utils.platform_aliases import (
|
||||
PLATFORM_FS_ALIASES,
|
||||
PLATFORM_SLUG_FOLDERS,
|
||||
resolve_fs_folder,
|
||||
resolve_fs_slug,
|
||||
resolve_platform_slug,
|
||||
)
|
||||
@@ -85,6 +86,23 @@ def test_slug_reached_by_several_folders_has_no_reverse():
|
||||
assert resolve_fs_slug("my-custom-slug", _config()) is None
|
||||
|
||||
|
||||
def test_resolves_a_config_key_to_the_folder_on_disk():
|
||||
"""Config keys are lowercased; paths need the folder's own casing."""
|
||||
assert resolve_fs_folder("nintendo 64", ["Nintendo 64", "psx"]) == "Nintendo 64"
|
||||
|
||||
|
||||
def test_resolves_a_folder_that_is_not_on_disk_to_nothing():
|
||||
assert resolve_fs_folder("nintendo 64", ["psx"]) is None
|
||||
|
||||
|
||||
def test_two_folders_differing_only_by_case_each_resolve_to_themselves():
|
||||
"""A case-sensitive filesystem allows both; neither may claim the other."""
|
||||
folders = ["PSX", "psx"]
|
||||
|
||||
assert resolve_fs_folder("psx", folders) == "psx"
|
||||
assert resolve_fs_folder("PSX", folders) == "PSX"
|
||||
|
||||
|
||||
def test_reverse_map_agrees_with_alias_table():
|
||||
for slug, fs_slug in PLATFORM_SLUG_FOLDERS.items():
|
||||
assert PLATFORM_FS_ALIASES[fs_slug].value == slug
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Iterable
|
||||
from typing import TYPE_CHECKING, Final
|
||||
|
||||
from utils.platform_slugs import UniversalPlatformSlug as UPS
|
||||
@@ -190,3 +191,23 @@ def resolve_fs_slug(slug: str, config: Config) -> str | None:
|
||||
if bound == slug:
|
||||
return fs_slug
|
||||
return PLATFORM_SLUG_FOLDERS.get(slug)
|
||||
|
||||
|
||||
def resolve_fs_folder(fs_slug: str, fs_platforms: Iterable[str]) -> str | None:
|
||||
"""Resolve a folder name to the one on disk it names, ignoring case.
|
||||
|
||||
Config keys are lowercased, but paths are built from the folder's own
|
||||
casing. An exact match wins, so on a case-sensitive filesystem two folders
|
||||
differing only by case each still resolve to themselves.
|
||||
|
||||
Returns:
|
||||
The folder as it is spelled on disk, or None when none matches.
|
||||
"""
|
||||
folded = fs_slug.lower()
|
||||
fallback: str | None = None
|
||||
for folder in fs_platforms:
|
||||
if folder == fs_slug:
|
||||
return folder
|
||||
if fallback is None and folder.lower() == folded:
|
||||
fallback = folder
|
||||
return fallback
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
# Stages:
|
||||
# - python-runtime: Patch the Python image's libraries before they ship
|
||||
# - frontend-build: Build frontend
|
||||
# - backend-build: Build backend environment
|
||||
# - backend-dev-build: Similar to `backend-build`, but also compiles and installs development dependencies
|
||||
@@ -14,15 +15,15 @@
|
||||
|
||||
|
||||
# ARGUMENT DECLARATIONS
|
||||
ARG ALPINE_VERSION=3.23
|
||||
ARG ALPINE_SHA256=25109184c71bdad752c8312a8623239686a9a2071e8825f20acb8f2198c3f659
|
||||
ARG ALPINE_VERSION=3.24
|
||||
ARG ALPINE_SHA256=294b683cb724975bec92580e1e685676bd4b50bda910ddb8c51d4cabeaec77e6
|
||||
# Pins the base image tag, so it cannot read ../.python-version; keep the two in sync.
|
||||
ARG PYTHON_VERSION=3.14
|
||||
ARG PYTHON_ALPINE_SHA256=8caa2adfeb414dfe68d8b257f7aea9e205a400521c2b13b2d2e5e731fb8e70e5
|
||||
ARG PYTHON_ALPINE_SHA256=9e9fde4d32eedce0b661d9ab91e826b62dddf28e928c230ec55f1866cac66b01
|
||||
ARG NODE_VERSION=24.16
|
||||
ARG NODE_ALPINE_SHA256=2bdb65ed1dab192432bc31c95f94155ca5ad7fc1392fb7eb7526ab682fa5bf14
|
||||
ARG NGINX_VERSION=1.29.8
|
||||
ARG NGINX_SHA256=5616878291a2eed594aee8db4dade5878cf7edcb475e59193904b198d9b830de
|
||||
ARG NODE_ALPINE_SHA256=21f403ab171f2dc89bad4dd69d7721bfd15f084ccb46cdd225f31f2bc59b5c9a
|
||||
ARG NGINX_VERSION=1.30.5
|
||||
ARG NGINX_SHA256=a5f2157a0302eb0c5e300415effb63a9e70ed1eb9c107283819bf6d149ab607c
|
||||
ARG UV_VERSION=0.12.13
|
||||
ARG UV_SHA256=eb47c391d3a252d9d912270dd2b5e234af5493e92039fedb483f1dd1cb5659ce
|
||||
|
||||
@@ -30,6 +31,15 @@ ARG UV_SHA256=eb47c391d3a252d9d912270dd2b5e234af5493e92039fedb483f1dd1cb5659ce
|
||||
FROM python:${PYTHON_VERSION}-alpine${ALPINE_VERSION}@sha256:${PYTHON_ALPINE_SHA256} AS python-alias
|
||||
|
||||
|
||||
# PATCHED PYTHON RUNTIME
|
||||
# production-stage copies /usr/lib from here over its own, so these libraries
|
||||
# need the same patches, or the stale ones land in the final image. Kept apart
|
||||
# from python-alias so that busting this layer's cache (see `no-cache-filters`
|
||||
# in build.yml) does not also rebuild the venv and the sigil bindings.
|
||||
FROM python-alias AS python-runtime
|
||||
RUN apk upgrade --no-cache
|
||||
|
||||
|
||||
# FRONTEND BUILD
|
||||
# Built on the native build platform: the output (/front/dist) is static JS/CSS,
|
||||
# fully architecture-independent, so there is no need to emulate the target arch.
|
||||
@@ -217,7 +227,9 @@ RUN git clone https://github.com/evanmiller/mod_zip.git && \
|
||||
FROM nginx:${NGINX_VERSION}-alpine${ALPINE_VERSION}@sha256:${NGINX_SHA256} AS production-stage
|
||||
ARG WEBSERVER_FOLDER=/var/www/html
|
||||
|
||||
RUN apk add --no-cache \
|
||||
# Alpine backports security fixes to its repo faster than the base image is
|
||||
# rebuilt, so the digest pin alone leaves known-vulnerable packages in the image.
|
||||
RUN apk upgrade --no-cache && apk add --no-cache \
|
||||
bash \
|
||||
libarchive-tools \
|
||||
libmagic \
|
||||
@@ -234,11 +246,11 @@ RUN apk add --no-cache \
|
||||
# TODO: Replace with a bundled installation of Python using `uv`, when it is supported.
|
||||
# Related issue: https://github.com/astral-sh/uv/issues/7865
|
||||
ARG PYTHON_VERSION
|
||||
COPY --from=python-alias /usr/lib/* /usr/lib/
|
||||
COPY --from=python-alias /usr/local/bin/* /usr/local/bin/
|
||||
COPY --from=python-alias /usr/local/include/python${PYTHON_VERSION} /usr/local/include/python${PYTHON_VERSION}
|
||||
COPY --from=python-alias /usr/local/lib/libpython* /usr/local/lib/
|
||||
COPY --from=python-alias /usr/local/lib/python${PYTHON_VERSION} /usr/local/lib/python${PYTHON_VERSION}
|
||||
COPY --from=python-runtime /usr/lib/* /usr/lib/
|
||||
COPY --from=python-runtime /usr/local/bin/* /usr/local/bin/
|
||||
COPY --from=python-runtime /usr/local/include/python${PYTHON_VERSION} /usr/local/include/python${PYTHON_VERSION}
|
||||
COPY --from=python-runtime /usr/local/lib/libpython* /usr/local/lib/
|
||||
COPY --from=python-runtime /usr/local/lib/python${PYTHON_VERSION} /usr/local/lib/python${PYTHON_VERSION}
|
||||
|
||||
COPY --from=rahasher-build /RALibretro/bin64/RAHasher /usr/bin/RAHasher
|
||||
COPY --from=nginx-build ./nginx/objs/ngx_http_zip_module.so /usr/lib/nginx/modules/
|
||||
|
||||
@@ -123,7 +123,8 @@ frontend/
|
||||
├── index.html # HTML entry point (<div id="app">)
|
||||
├── package.json # Dependencies & scripts
|
||||
├── vite.config.js # Vite build config with plugins
|
||||
├── tsconfig.json # TypeScript configuration
|
||||
├── tsconfig.json # Vue app TypeScript (vue-tsc)
|
||||
├── tsconfig.node.json # Node/Vite tooling TypeScript (tsc -p)
|
||||
├── eslint.config.js # ESLint flat config
|
||||
├── .nvmrc # Node 24
|
||||
│
|
||||
@@ -1099,14 +1100,15 @@ Procedural SVG generation for:
|
||||
|
||||
### Scripts
|
||||
|
||||
| Script | Command | Purpose |
|
||||
| ----------- | ---------------------------- | ---------------------------------------- |
|
||||
| `dev` | `vite --host` | Development server |
|
||||
| `build` | `vite build` | Production build |
|
||||
| `preview` | `vite preview` | Preview production build |
|
||||
| `typecheck` | `vue-tsc --noEmit` | TypeScript validation |
|
||||
| `generate` | `openapi-typescript-codegen` | Generate types from backend OpenAPI |
|
||||
| `lint` | `eslint` | Lint `.vue`, `.js`, `.ts`; import cycles |
|
||||
| Script | Command | Purpose |
|
||||
| ------------------- | ------------------------------------ | ------------------------------------------------------ |
|
||||
| `dev` | `vite --host` | Development server |
|
||||
| `build` | `vite build` | Production build |
|
||||
| `preview` | `vite preview` | Preview production build |
|
||||
| `typecheck` | `vue-tsc --noEmit` | App SFCs (`tsconfig.json`) |
|
||||
| `typecheck:scripts` | `tsc --noEmit -p tsconfig.node.json` | Node/Vite tooling in `scripts/` (`tsconfig.node.json`) |
|
||||
| `generate` | `openapi-typescript-codegen` | Generate types from backend OpenAPI |
|
||||
| `lint` | `eslint` | Lint `.vue`, `.js`, `.ts`; import cycles |
|
||||
|
||||
### OpenAPI Code Generation
|
||||
|
||||
|
||||
@@ -1,11 +0,0 @@
|
||||
# Browser support baseline for the RomM frontend. Matches Tailwind v4's
|
||||
# minimum targets. This is the single source of truth for browser support:
|
||||
# vite.config.js derives Lightning CSS's `build.cssTarget` from it (so the
|
||||
# production build prefixes/down-levels CSS for exactly these browsers), and
|
||||
# any other tooling reads the same file. Expressed as floors, not pinned
|
||||
# versions, and the actual version data comes from caniuse-lite.
|
||||
chrome >= 111
|
||||
edge >= 111
|
||||
firefox >= 128
|
||||
safari >= 16.4
|
||||
ios_saf >= 16.4
|
||||
1
frontend/package-lock.json
generated
1
frontend/package-lock.json
generated
@@ -52,7 +52,6 @@
|
||||
"@vue/test-utils": "^2.4.9",
|
||||
"@vue/tsconfig": "^0.9.1",
|
||||
"axe-core": "^4.12.1",
|
||||
"browserslist": "^4.28.8",
|
||||
"eslint": "^10.0.3",
|
||||
"eslint-config-prettier": "^10.1.8",
|
||||
"eslint-import-resolver-typescript": "^4.4.5",
|
||||
|
||||
@@ -27,6 +27,7 @@
|
||||
"build": "vite build",
|
||||
"preview": "vite preview",
|
||||
"typecheck": "vue-tsc --noEmit",
|
||||
"typecheck:scripts": "tsc --noEmit -p tsconfig.node.json",
|
||||
"generate": "openapi --input http://127.0.0.1:3000/openapi.json --output ./src/__generated__ --client axios --useOptions --useUnionTypes --exportServices false --exportSchemas false --exportCore false",
|
||||
"test": "vitest run",
|
||||
"test:watch": "vitest",
|
||||
@@ -81,7 +82,6 @@
|
||||
"@vue/test-utils": "^2.4.9",
|
||||
"@vue/tsconfig": "^0.9.1",
|
||||
"axe-core": "^4.12.1",
|
||||
"browserslist": "^4.28.8",
|
||||
"eslint": "^10.0.3",
|
||||
"eslint-config-prettier": "^10.1.8",
|
||||
"eslint-import-resolver-typescript": "^4.4.5",
|
||||
|
||||
@@ -36,13 +36,10 @@ const availableFolders = computed(() => {
|
||||
}
|
||||
|
||||
// Exclude folders that are already mapped as either an alias or a variant.
|
||||
const isBound = Object.keys(configStore.config.PLATFORMS_BINDING).includes(
|
||||
folder,
|
||||
return (
|
||||
!configStore.getPlatformBinding(folder) &&
|
||||
!configStore.getPlatformVersion(folder)
|
||||
);
|
||||
const isVersion = Object.keys(
|
||||
configStore.config.PLATFORMS_VERSIONS,
|
||||
).includes(folder);
|
||||
return !isBound && !isVersion;
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
<script setup lang="ts">
|
||||
/** @deprecated v1 UI; superseded by `v2/components/Settings/FolderMappingsSection.vue`. */
|
||||
import type { Emitter } from "mitt";
|
||||
import { storeToRefs } from "pinia";
|
||||
import { computed, inject, onMounted, ref } from "vue";
|
||||
@@ -39,8 +40,6 @@ const HEADERS = [
|
||||
const mappings = computed<Row[]>(() => {
|
||||
const result: Row[] = [];
|
||||
const folders = heartbeat.value?.FILESYSTEM?.FS_PLATFORMS || [];
|
||||
const bindings = config.value.PLATFORMS_BINDING || {};
|
||||
const versions = config.value.PLATFORMS_VERSIONS || {};
|
||||
const autoSlugByFs: Record<string, string | undefined> = {};
|
||||
|
||||
for (const p of supportedPlatforms.value) {
|
||||
@@ -48,21 +47,32 @@ const mappings = computed<Row[]>(() => {
|
||||
}
|
||||
|
||||
for (const folder of folders) {
|
||||
if (bindings[folder]) {
|
||||
const slug = bindings[folder];
|
||||
const platform = supportedPlatforms.value.find((p) => p.slug === slug);
|
||||
const displayName = platform?.display_name || platform?.name || slug;
|
||||
result.push({ fsSlug: folder, slug, displayName, type: "alias" });
|
||||
const binding = configStore.getPlatformBinding(folder);
|
||||
if (binding) {
|
||||
const platform = supportedPlatforms.value.find((p) => p.slug === binding);
|
||||
const displayName = platform?.display_name || platform?.name || binding;
|
||||
result.push({
|
||||
fsSlug: folder,
|
||||
slug: binding,
|
||||
displayName,
|
||||
type: "alias",
|
||||
});
|
||||
continue;
|
||||
}
|
||||
if (versions[folder]) {
|
||||
const slug = versions[folder];
|
||||
const platform = supportedPlatforms.value.find((p) => p.slug === slug);
|
||||
const displayName = platform?.display_name || platform?.name || slug;
|
||||
result.push({ fsSlug: folder, slug, displayName, type: "variant" });
|
||||
const version = configStore.getPlatformVersion(folder);
|
||||
if (version) {
|
||||
const platform = supportedPlatforms.value.find((p) => p.slug === version);
|
||||
const displayName = platform?.display_name || platform?.name || version;
|
||||
result.push({
|
||||
fsSlug: folder,
|
||||
slug: version,
|
||||
displayName,
|
||||
type: "variant",
|
||||
});
|
||||
continue;
|
||||
}
|
||||
const auto = autoSlugByFs[folder];
|
||||
// Platform slugs are lowercase; the folder on disk may not be.
|
||||
const auto = autoSlugByFs[folder.toLowerCase()];
|
||||
if (auto) {
|
||||
const platform = supportedPlatforms.value.find((p) => p.slug === auto);
|
||||
const displayName = platform?.display_name || platform?.name || auto;
|
||||
|
||||
@@ -27,6 +27,7 @@
|
||||
"selection-unfavorite": "Премахни от любими",
|
||||
"selection-unfavorite-success": "{n} са премахнати от любими",
|
||||
"sort-ascending": "Сортирай възходящо",
|
||||
"sort-by": "Сортирай по",
|
||||
"sort-descending": "Сортирай низходящо",
|
||||
"view-flat": "Плосък изглед",
|
||||
"view-grid": "Решетка",
|
||||
|
||||
@@ -27,6 +27,7 @@
|
||||
"selection-unfavorite": "Odebrat z oblíbených",
|
||||
"selection-unfavorite-success": "{n} odebráno z oblíbených",
|
||||
"sort-ascending": "Seřadit vzestupně",
|
||||
"sort-by": "Seřadit podle",
|
||||
"sort-descending": "Seřadit sestupně",
|
||||
"view-flat": "Plochý pohled",
|
||||
"view-grid": "Mřížka",
|
||||
|
||||
@@ -27,6 +27,7 @@
|
||||
"selection-unfavorite": "Aus Favoriten entfernen",
|
||||
"selection-unfavorite-success": "{n} aus Favoriten entfernt",
|
||||
"sort-ascending": "Aufsteigend sortieren",
|
||||
"sort-by": "Sortieren nach",
|
||||
"sort-descending": "Absteigend sortieren",
|
||||
"view-flat": "Flache Ansicht",
|
||||
"view-grid": "Raster",
|
||||
|
||||
@@ -27,6 +27,7 @@
|
||||
"selection-unfavorite": "Remove from favourites",
|
||||
"selection-unfavorite-success": "{n} removed from favourites",
|
||||
"sort-ascending": "Sort ascending",
|
||||
"sort-by": "Sort by",
|
||||
"sort-descending": "Sort descending",
|
||||
"view-flat": "Flat view",
|
||||
"view-grid": "Grid",
|
||||
|
||||
@@ -27,6 +27,7 @@
|
||||
"selection-unfavorite": "Remove from favorites",
|
||||
"selection-unfavorite-success": "{n} removed from favorites",
|
||||
"sort-ascending": "Sort ascending",
|
||||
"sort-by": "Sort by",
|
||||
"sort-descending": "Sort descending",
|
||||
"view-flat": "Flat view",
|
||||
"view-grid": "Grid",
|
||||
|
||||
@@ -27,6 +27,7 @@
|
||||
"selection-unfavorite": "Quitar de favoritos",
|
||||
"selection-unfavorite-success": "{n} quitados de favoritos",
|
||||
"sort-ascending": "Orden ascendente",
|
||||
"sort-by": "Ordenar por",
|
||||
"sort-descending": "Orden descendente",
|
||||
"view-flat": "Vista plana",
|
||||
"view-grid": "Cuadrícula",
|
||||
|
||||
@@ -27,6 +27,7 @@
|
||||
"selection-unfavorite": "Retirer des favoris",
|
||||
"selection-unfavorite-success": "{n} retiré(s) des favoris",
|
||||
"sort-ascending": "Trier par ordre croissant",
|
||||
"sort-by": "Trier par",
|
||||
"sort-descending": "Trier par ordre décroissant",
|
||||
"view-flat": "Vue à plat",
|
||||
"view-grid": "Grille",
|
||||
|
||||
@@ -27,6 +27,7 @@
|
||||
"selection-unfavorite": "Eltávolítás a kedvencek közül",
|
||||
"selection-unfavorite-success": "{n} eltávolítva a kedvencek közül",
|
||||
"sort-ascending": "Növekvő sorrend",
|
||||
"sort-by": "Rendezés szerint",
|
||||
"sort-descending": "Csökkenő sorrend",
|
||||
"view-flat": "Sima nézet",
|
||||
"view-grid": "Rács",
|
||||
|
||||
@@ -27,6 +27,7 @@
|
||||
"selection-unfavorite": "Rimuovi dai preferiti",
|
||||
"selection-unfavorite-success": "{n} rimossi dai preferiti",
|
||||
"sort-ascending": "Ordina in ordine crescente",
|
||||
"sort-by": "Ordina per",
|
||||
"sort-descending": "Ordina in ordine decrescente",
|
||||
"view-flat": "Vista piatta",
|
||||
"view-grid": "Griglia",
|
||||
|
||||
@@ -27,6 +27,7 @@
|
||||
"selection-unfavorite": "お気に入りから削除",
|
||||
"selection-unfavorite-success": "{n}件をお気に入りから削除しました",
|
||||
"sort-ascending": "昇順に並び替え",
|
||||
"sort-by": "並び替え基準",
|
||||
"sort-descending": "降順に並び替え",
|
||||
"view-flat": "フラット表示",
|
||||
"view-grid": "グリッド",
|
||||
|
||||
@@ -27,6 +27,7 @@
|
||||
"selection-unfavorite": "즐겨찾기에서 제거",
|
||||
"selection-unfavorite-success": "{n}개를 즐겨찾기에서 제거했습니다",
|
||||
"sort-ascending": "오름차순 정렬",
|
||||
"sort-by": "정렬 기준",
|
||||
"sort-descending": "내림차순 정렬",
|
||||
"view-flat": "단일 보기",
|
||||
"view-grid": "그리드",
|
||||
|
||||
@@ -27,6 +27,7 @@
|
||||
"selection-unfavorite": "Usuń z ulubionych",
|
||||
"selection-unfavorite-success": "{n} usunięto z ulubionych",
|
||||
"sort-ascending": "Sortuj rosnąco",
|
||||
"sort-by": "Sortuj według",
|
||||
"sort-descending": "Sortuj malejąco",
|
||||
"view-flat": "Widok płaski",
|
||||
"view-grid": "Siatka",
|
||||
|
||||
@@ -27,6 +27,7 @@
|
||||
"selection-unfavorite": "Remover dos favoritos",
|
||||
"selection-unfavorite-success": "{n} removido(s) dos favoritos",
|
||||
"sort-ascending": "Ordenar crescente",
|
||||
"sort-by": "Ordenar por",
|
||||
"sort-descending": "Ordenar decrescente",
|
||||
"view-flat": "Visualização plana",
|
||||
"view-grid": "Grade",
|
||||
|
||||
@@ -27,6 +27,7 @@
|
||||
"selection-unfavorite": "Elimină din favorite",
|
||||
"selection-unfavorite-success": "{n} eliminate din favorite",
|
||||
"sort-ascending": "Sortează crescător",
|
||||
"sort-by": "Sortează după",
|
||||
"sort-descending": "Sortează descrescător",
|
||||
"view-flat": "Vizualizare plată",
|
||||
"view-grid": "Grilă",
|
||||
|
||||
@@ -27,6 +27,7 @@
|
||||
"selection-unfavorite": "Убрать из избранного",
|
||||
"selection-unfavorite-success": "{n} удалено из избранного",
|
||||
"sort-ascending": "Сортировать по возрастанию",
|
||||
"sort-by": "Сортировать по",
|
||||
"sort-descending": "Сортировать по убыванию",
|
||||
"view-flat": "Плоский вид",
|
||||
"view-grid": "Сетка",
|
||||
|
||||
@@ -27,6 +27,7 @@
|
||||
"selection-unfavorite": "Favorilerden kaldır",
|
||||
"selection-unfavorite-success": "{n} favorilerden kaldırıldı",
|
||||
"sort-ascending": "Artan sırala",
|
||||
"sort-by": "Sıralama ölçütü",
|
||||
"sort-descending": "Azalan sırala",
|
||||
"view-flat": "Düz görünüm",
|
||||
"view-grid": "Izgara",
|
||||
|
||||
@@ -27,6 +27,7 @@
|
||||
"selection-unfavorite": "从喜好中移除",
|
||||
"selection-unfavorite-success": "已从喜好中移除 {n} 个",
|
||||
"sort-ascending": "升序排列",
|
||||
"sort-by": "排序方式",
|
||||
"sort-descending": "降序排列",
|
||||
"view-flat": "平铺视图",
|
||||
"view-grid": "网格",
|
||||
|
||||
@@ -27,6 +27,7 @@
|
||||
"selection-unfavorite": "從喜好中移除",
|
||||
"selection-unfavorite-success": "已從喜好中移除 {n} 個",
|
||||
"sort-ascending": "升冪排序",
|
||||
"sort-by": "排序方式",
|
||||
"sort-descending": "降冪排序",
|
||||
"view-flat": "平面檢視",
|
||||
"view-grid": "網格",
|
||||
|
||||
@@ -1,7 +1,24 @@
|
||||
import { createPinia, setActivePinia } from "pinia";
|
||||
import { beforeAll, describe, expect, it } from "vitest";
|
||||
import { beforeAll, describe, expect, it, vi } from "vitest";
|
||||
import i18n, { localesReady } from "@/locales";
|
||||
import router from "@/plugins/router";
|
||||
import router, { ROUTES } from "@/plugins/router";
|
||||
import storeAuth from "@/stores/auth";
|
||||
import storeRoms, { type DetailedRom } from "@/stores/roms";
|
||||
import type { User } from "@/stores/users";
|
||||
|
||||
const { getRom } = vi.hoisted(() => ({ getRom: vi.fn() }));
|
||||
|
||||
vi.mock("@/services/api/rom", () => ({
|
||||
default: { getRom },
|
||||
}));
|
||||
|
||||
function makeRom(overrides: Partial<DetailedRom> = {}): DetailedRom {
|
||||
return {
|
||||
id: 1,
|
||||
name: "Chrono Trigger",
|
||||
...overrides,
|
||||
} as unknown as DetailedRom;
|
||||
}
|
||||
|
||||
describe("route titles", () => {
|
||||
beforeAll(async () => {
|
||||
@@ -25,3 +42,26 @@ describe("route titles", () => {
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("the rom route", () => {
|
||||
beforeAll(async () => {
|
||||
setActivePinia(createPinia());
|
||||
await localesReady;
|
||||
});
|
||||
|
||||
// A play page writes saves server-side and then navigates here, so an id
|
||||
// matching the route is not proof the store's copy is current.
|
||||
it("re-reads a rom the store already holds", async () => {
|
||||
const roms = storeRoms();
|
||||
storeAuth().setCurrentUser({ id: 1 } as User);
|
||||
roms.setCurrentRom(makeRom({ id: 9, name: "before the session" }));
|
||||
getRom.mockResolvedValue({
|
||||
data: makeRom({ id: 9, name: "after the session" }),
|
||||
});
|
||||
|
||||
await router.push({ name: ROUTES.ROM, params: { rom: 9 } });
|
||||
|
||||
expect(getRom).toHaveBeenCalledWith({ romId: 9 });
|
||||
expect(roms.currentRom?.name).toBe("after the session");
|
||||
});
|
||||
});
|
||||
|
||||
@@ -204,18 +204,15 @@ const routes = [
|
||||
beforeEnter: (async (to, _from, next) => {
|
||||
const romsStore = storeRoms();
|
||||
|
||||
if (
|
||||
!romsStore.currentRom ||
|
||||
romsStore.currentRom.id !== parseInt(to.params.rom as string)
|
||||
) {
|
||||
try {
|
||||
const data = await romApi.getRom({
|
||||
romId: parseInt(to.params.rom as string),
|
||||
});
|
||||
romsStore.setCurrentRom(data.data);
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
}
|
||||
// Read the ROM on every entry, a matching id included: a play page
|
||||
// writes saves server-side, then navigates here to hand the tab back.
|
||||
try {
|
||||
const data = await romApi.getRom({
|
||||
romId: parseInt(to.params.rom as string),
|
||||
});
|
||||
romsStore.setCurrentRom(data.data);
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
}
|
||||
next();
|
||||
}) as NavigationGuardWithThis<undefined>,
|
||||
|
||||
@@ -22,7 +22,7 @@ async function addPlatformBindConfig({
|
||||
}
|
||||
|
||||
async function deletePlatformBindConfig({ fsSlug }: { fsSlug: string }) {
|
||||
return api.delete(`/config/system/platforms/${fsSlug}`);
|
||||
return api.delete(`/config/system/platforms/${encodeURIComponent(fsSlug)}`);
|
||||
}
|
||||
|
||||
async function addPlatformVersionConfig({
|
||||
@@ -39,7 +39,7 @@ async function addPlatformVersionConfig({
|
||||
}
|
||||
|
||||
async function deletePlatformVersionConfig({ fsSlug }: { fsSlug: string }) {
|
||||
return api.delete(`/config/system/versions/${fsSlug}`);
|
||||
return api.delete(`/config/system/versions/${encodeURIComponent(fsSlug)}`);
|
||||
}
|
||||
|
||||
async function addExclusion({
|
||||
@@ -65,7 +65,9 @@ async function deleteExclusion({
|
||||
exclusionValue: string;
|
||||
exclusionType: string;
|
||||
}) {
|
||||
return api.delete(`/config/exclude/${exclusionType}/${exclusionValue}`);
|
||||
return api.delete(
|
||||
`/config/exclude/${exclusionType}/${encodeURIComponent(exclusionValue)}`,
|
||||
);
|
||||
}
|
||||
|
||||
async function updateScanSettings(payload: ScanSettingsPayload) {
|
||||
|
||||
@@ -151,8 +151,12 @@ async function saveAndExit(platform: string, slot = 0, wait = true) {
|
||||
});
|
||||
}
|
||||
|
||||
async function heartbeatSession(platform: string) {
|
||||
return api.post<SessionStatus>(`/streaming/sessions/${platform}/heartbeat`);
|
||||
async function heartbeatSession(platform: string, container?: string) {
|
||||
return api.post<SessionStatus>(
|
||||
`/streaming/sessions/${platform}/heartbeat`,
|
||||
undefined,
|
||||
{ params: { container } },
|
||||
);
|
||||
}
|
||||
|
||||
async function sessionStatus(platform: string) {
|
||||
|
||||
@@ -8,6 +8,12 @@ import api from "@/services/api";
|
||||
|
||||
export type Config = ConfigResponse;
|
||||
|
||||
// The backend lowercases folder names before writing them to config.yml, so
|
||||
// every read and write of a mapping normalizes the on-disk name the same way.
|
||||
function normalizeFsSlug(fsSlug: string): string {
|
||||
return fsSlug.toLowerCase();
|
||||
}
|
||||
|
||||
const defaultConfig = {
|
||||
CONFIG_FILE_MOUNTED: false,
|
||||
CONFIG_FILE_WRITABLE: false,
|
||||
@@ -66,17 +72,23 @@ export default defineStore("config", {
|
||||
return this.config;
|
||||
}
|
||||
},
|
||||
getPlatformBinding(fsSlug: string): string | undefined {
|
||||
return this.config.PLATFORMS_BINDING[normalizeFsSlug(fsSlug)];
|
||||
},
|
||||
addPlatformBinding(fsSlug: string, slug: string) {
|
||||
this.config.PLATFORMS_BINDING[fsSlug] = slug;
|
||||
this.config.PLATFORMS_BINDING[normalizeFsSlug(fsSlug)] = slug;
|
||||
},
|
||||
removePlatformBinding(fsSlug: string) {
|
||||
delete this.config.PLATFORMS_BINDING[fsSlug];
|
||||
delete this.config.PLATFORMS_BINDING[normalizeFsSlug(fsSlug)];
|
||||
},
|
||||
getPlatformVersion(fsSlug: string): string | undefined {
|
||||
return this.config.PLATFORMS_VERSIONS[normalizeFsSlug(fsSlug)];
|
||||
},
|
||||
addPlatformVersion(fsSlug: string, slug: string) {
|
||||
this.config.PLATFORMS_VERSIONS[fsSlug] = slug;
|
||||
this.config.PLATFORMS_VERSIONS[normalizeFsSlug(fsSlug)] = slug;
|
||||
},
|
||||
removePlatformVersion(fsSlug: string) {
|
||||
delete this.config.PLATFORMS_VERSIONS[fsSlug];
|
||||
delete this.config.PLATFORMS_VERSIONS[normalizeFsSlug(fsSlug)];
|
||||
},
|
||||
addExclusion(exclusionType: ExclusionType, exclusionValue: string) {
|
||||
this.config[exclusionType].push(exclusionValue);
|
||||
|
||||
@@ -322,11 +322,10 @@ export default defineStore("roms", {
|
||||
this.continuePlayingRoms = this.continuePlayingRoms.map((value) =>
|
||||
value.id === rom.id ? rom : value,
|
||||
);
|
||||
// Keep `currentRom` in sync too — otherwise an optimistic mutation
|
||||
// Keep `currentRom` in sync too, otherwise an optimistic mutation
|
||||
// on a SimpleRom from the gallery (status toggle from a GameCard
|
||||
// badge, favourite, …) leaves the detail view rendering stale
|
||||
// `rom_user` data, since the rom-route `beforeEnter` skips its
|
||||
// refetch when `currentRom.id` already matches. Spread merges the
|
||||
// `rom_user` data until the next route entry. Spread merges the
|
||||
// SimpleRom shape over the cached DetailedRom so detailed-only
|
||||
// fields (metadatum, screenshots, related games, …) survive.
|
||||
if (this.currentRom?.id === rom.id) {
|
||||
|
||||
@@ -302,10 +302,11 @@ export const useStreamingStore = defineStore("streaming", () => {
|
||||
*/
|
||||
async function heartbeatSession(
|
||||
platform: string,
|
||||
container?: string,
|
||||
): Promise<SessionStatus | null> {
|
||||
if (!platform) return null;
|
||||
try {
|
||||
const { data } = await streamingApi.heartbeatSession(platform);
|
||||
const { data } = await streamingApi.heartbeatSession(platform, container);
|
||||
return data;
|
||||
} catch (err) {
|
||||
console.warn("[streaming] Could not heartbeat session:", err);
|
||||
|
||||
@@ -48,6 +48,7 @@ import GameListSkeletonRow from "@/v2/components/Gallery/GameListSkeletonRow.vue
|
||||
import SelectionBar from "@/v2/components/Gallery/SelectionBar.vue";
|
||||
import {
|
||||
getListMinWidth,
|
||||
getSortOptions,
|
||||
isListSortKey,
|
||||
LIST_HEADER_HEIGHT_PX,
|
||||
type ListSortKey,
|
||||
@@ -59,6 +60,7 @@ import { useDebugMode } from "@/v2/composables/useDebugMode";
|
||||
import { useGalleryCoverRatios } from "@/v2/composables/useGalleryCoverRatios";
|
||||
import { useGalleryFilterUrl } from "@/v2/composables/useGalleryFilterUrl";
|
||||
import { useGalleryMode } from "@/v2/composables/useGalleryMode";
|
||||
import { useGalleryOrderUrl } from "@/v2/composables/useGalleryOrderUrl";
|
||||
import { useGallerySelectAll } from "@/v2/composables/useGallerySelectAll";
|
||||
import { useGalleryViewModeUrl } from "@/v2/composables/useGalleryViewModeUrl";
|
||||
import {
|
||||
@@ -125,6 +127,7 @@ defineSlots<{
|
||||
}>();
|
||||
|
||||
useGalleryFilterUrl();
|
||||
useGalleryOrderUrl();
|
||||
useGalleryViewModeUrl();
|
||||
|
||||
const { t } = useI18n();
|
||||
@@ -619,10 +622,10 @@ function setSearch(value: string) {
|
||||
}, 300);
|
||||
}
|
||||
|
||||
// ── List-mode sort ────────────────────────────────────────────────
|
||||
// Header click → store order params → invalidate + bootstrap metadata.
|
||||
// The grid-mode sort goes through the same path (toolbar dropdown), so
|
||||
// no separate code path; list just exposes the click affordance.
|
||||
// ── Sort ──────────────────────────────────────────────────────────
|
||||
// Both affordances (list column headers, grid direction toggle) only
|
||||
// write the store; `useGalleryOrderUrl` mirrors it to the URL and the
|
||||
// watch below owns the refetch.
|
||||
const listSortKey = computed<ListSortKey | null>(() => {
|
||||
const key = orderBy.value;
|
||||
return isListSortKey(key) ? key : null;
|
||||
@@ -631,20 +634,19 @@ const listSortKey = computed<ListSortKey | null>(() => {
|
||||
function onListSort(payload: { key: ListSortKey; dir: "asc" | "desc" }) {
|
||||
galleryRoms.setOrderBy(payload.key);
|
||||
galleryRoms.setOrderDir(payload.dir);
|
||||
galleryRoms.invalidateWindows();
|
||||
void galleryRoms.fetchInitialMetadata();
|
||||
}
|
||||
|
||||
// Grid-mode direction toggle — wires the toolbar asc/desc into the
|
||||
// same `orderDir` the list column-header sort writes to, then triggers
|
||||
// the same invalidate+refetch path. Sort axis stays whatever the list
|
||||
// last set (default "name"); grid only exposes direction.
|
||||
function onGridSortDir(dir: "asc" | "desc") {
|
||||
if (galleryRoms.orderDir === dir) return;
|
||||
galleryRoms.setOrderDir(dir);
|
||||
// The toolbar's sort axes, matching the list column headers.
|
||||
const sortOptions = computed(() => getSortOptions(props.showPlatformColumn));
|
||||
|
||||
// Watching the store rather than refetching inside the handlers also
|
||||
// covers the URL-driven writes (back/forward, a pasted link). The
|
||||
// initial URL hydration runs before this watch is set up, so it does
|
||||
// not echo here.
|
||||
watch([orderBy, orderDir], () => {
|
||||
galleryRoms.invalidateWindows();
|
||||
void galleryRoms.fetchInitialMetadata();
|
||||
}
|
||||
});
|
||||
|
||||
// ── Scroll restoration ─────────────────────────────────────────────
|
||||
async function applyRestoredScroll() {
|
||||
@@ -661,14 +663,12 @@ function saveCurrentScroll(routeFullPath: string) {
|
||||
if (root) scrollRestoration.save(routeFullPath, root.scrollTop);
|
||||
}
|
||||
|
||||
onBeforeRouteUpdate((_to, from) => {
|
||||
onBeforeRouteUpdate((to, from) => {
|
||||
saveCurrentScroll(from.fullPath);
|
||||
// Switching to a different gallery context (Platform A → B, Search
|
||||
// query change that routes, Collection open) — the selection is
|
||||
// bound to the previous context and would read as stale items if
|
||||
// carried over. Filter / sort changes inside the same view do NOT
|
||||
// route, so they keep the selection intact (matches the rule of
|
||||
// "filter, select more, filter again").
|
||||
// Search, filters, sort and view mode live in the query, so they
|
||||
// navigate without leaving the gallery and keep the selection. Only a
|
||||
// path change is a real context switch, where it would read as stale.
|
||||
if (to.path === from.path) return;
|
||||
gallerySelection.clear();
|
||||
});
|
||||
onBeforeRouteLeave((_to, from) => {
|
||||
@@ -837,6 +837,8 @@ defineExpose({
|
||||
:layout="layout"
|
||||
:position="toolbarPosition"
|
||||
:sort-dir="orderDir"
|
||||
:sort-key="listSortKey"
|
||||
:sort-key-items="sortOptions"
|
||||
show-search
|
||||
:search="searchInput"
|
||||
:search-placeholder="searchPlaceholder"
|
||||
@@ -845,7 +847,8 @@ defineExpose({
|
||||
:filter-active-count="filterActiveCount"
|
||||
@update:group-by="groupBy = $event"
|
||||
@update:layout="layout = $event"
|
||||
@update:sort-dir="onGridSortDir"
|
||||
@update:sort-dir="galleryRoms.setOrderDir"
|
||||
@update:sort-key="galleryRoms.setOrderBy"
|
||||
@update:search="setSearch"
|
||||
@click:filter="filterDrawerOpen = true"
|
||||
/>
|
||||
@@ -854,8 +857,8 @@ defineExpose({
|
||||
|
||||
<!-- LIST COLUMN HEADER — sticky below the toolbar in list mode.
|
||||
Shares `LIST_GRID_TEMPLATE` with every GameListRow underneath
|
||||
so columns align. Header click cycles asc/desc → store
|
||||
orderBy/orderDir → invalidate + bootstrap metadata. -->
|
||||
so columns align. Header click cycles asc/desc into the
|
||||
store's orderBy/orderDir. -->
|
||||
<GameListHeader
|
||||
v-if="layout === 'list'"
|
||||
class="r-v2-shell__list-header"
|
||||
@@ -958,11 +961,14 @@ defineExpose({
|
||||
:layout="layout"
|
||||
:position="toolbarPosition"
|
||||
:sort-dir="orderDir"
|
||||
:sort-key="listSortKey"
|
||||
:sort-key-items="sortOptions"
|
||||
show-filter
|
||||
:filter-active-count="filterActiveCount"
|
||||
@update:group-by="groupBy = $event"
|
||||
@update:layout="layout = $event"
|
||||
@update:sort-dir="onGridSortDir"
|
||||
@update:sort-dir="galleryRoms.setOrderDir"
|
||||
@update:sort-key="galleryRoms.setOrderBy"
|
||||
@click:filter="filterDrawerOpen = true"
|
||||
/>
|
||||
|
||||
|
||||
@@ -16,7 +16,17 @@ vi.mock("@/v2/composables/useInputModality", () => ({
|
||||
useInputModality: () => ({ modality }),
|
||||
}));
|
||||
|
||||
function mountToolbar(props: Record<string, unknown> = {}) {
|
||||
// The sort-axis control lives inside an RMenu, so its entries only exist
|
||||
// once the menu renders its slots.
|
||||
const RMenuPassthrough = {
|
||||
name: "RMenuPassthrough",
|
||||
template: `<div><slot name="activator" :props="{}" /><slot /></div>`,
|
||||
};
|
||||
|
||||
function mountToolbar(
|
||||
props: Record<string, unknown> = {},
|
||||
menuStub: boolean | typeof RMenuPassthrough = true,
|
||||
) {
|
||||
return mount(GalleryToolbar, {
|
||||
attachTo: document.body,
|
||||
props: { groupBy: "none", layout: "grid", showSearch: true, ...props },
|
||||
@@ -25,13 +35,33 @@ function mountToolbar(props: Record<string, unknown> = {}) {
|
||||
RBadge: true,
|
||||
RBtn: true,
|
||||
RIcon: true,
|
||||
RMenu: true,
|
||||
RMenu: menuStub,
|
||||
RSliderBtnGroup: true,
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
const SORT_OPTIONS = [
|
||||
{ key: "name", label: "Title" },
|
||||
{ key: "fs_size_bytes", label: "Size" },
|
||||
] as const;
|
||||
|
||||
function mountWithSortOptions(props: Record<string, unknown> = {}) {
|
||||
return mountToolbar(
|
||||
{ sortKey: "name", sortKeyItems: SORT_OPTIONS, ...props },
|
||||
RMenuPassthrough,
|
||||
);
|
||||
}
|
||||
|
||||
function sortItems(wrapper: ReturnType<typeof mountWithSortOptions>) {
|
||||
return wrapper
|
||||
.findAllComponents({ name: "RMenuItem" })
|
||||
.filter((item) =>
|
||||
SORT_OPTIONS.some((option) => option.label === item.props("label")),
|
||||
);
|
||||
}
|
||||
|
||||
describe("GalleryToolbar search autofocus", () => {
|
||||
it("leaves the search field unfocused by default", () => {
|
||||
const wrapper = mountToolbar();
|
||||
@@ -56,3 +86,65 @@ describe("GalleryToolbar search autofocus", () => {
|
||||
wrapper.unmount();
|
||||
});
|
||||
});
|
||||
|
||||
describe("GalleryToolbar sort axis", () => {
|
||||
it("emits the picked axis so grid mode can change the sort key", async () => {
|
||||
const wrapper = mountWithSortOptions();
|
||||
|
||||
const size = sortItems(wrapper).find(
|
||||
(item) => item.props("label") === "Size",
|
||||
);
|
||||
expect(size).toBeTruthy();
|
||||
await size!.trigger("click");
|
||||
|
||||
expect(wrapper.emitted("update:sortKey")).toEqual([["fs_size_bytes"]]);
|
||||
wrapper.unmount();
|
||||
});
|
||||
|
||||
it("marks the active axis", () => {
|
||||
const wrapper = mountWithSortOptions({ sortKey: "fs_size_bytes" });
|
||||
|
||||
const variants = Object.fromEntries(
|
||||
sortItems(wrapper).map((item) => [
|
||||
item.props("label"),
|
||||
item.props("variant"),
|
||||
]),
|
||||
);
|
||||
|
||||
expect(variants).toMatchObject({ Size: "active", Title: "default" });
|
||||
wrapper.unmount();
|
||||
});
|
||||
|
||||
// Index views (Platforms / Collections) sort their own tiles and pass
|
||||
// no axes; the control must not paint an empty menu for them.
|
||||
it("hides the control when no axes are offered", () => {
|
||||
const withAxes = mountWithSortOptions();
|
||||
const menusWithAxes = withAxes.findAllComponents(RMenuPassthrough).length;
|
||||
withAxes.unmount();
|
||||
|
||||
const wrapper = mountWithSortOptions({ sortKeyItems: [] });
|
||||
|
||||
expect(wrapper.findAllComponents(RMenuPassthrough)).toHaveLength(
|
||||
menusWithAxes - 1,
|
||||
);
|
||||
expect(sortItems(wrapper)).toHaveLength(0);
|
||||
wrapper.unmount();
|
||||
});
|
||||
|
||||
// List mode sorts through the column headers, so the toolbar's axis
|
||||
// button has to stand down rather than offer a second, competing control.
|
||||
it("disables the activator in list mode only", () => {
|
||||
const activatorDisabled = (layout: string) => {
|
||||
const wrapper = mountWithSortOptions({ layout });
|
||||
const disabled = wrapper
|
||||
.findComponent(RMenuPassthrough)
|
||||
.findComponent({ name: "RBtn" })
|
||||
.attributes("disabled");
|
||||
wrapper.unmount();
|
||||
return disabled;
|
||||
};
|
||||
|
||||
expect(activatorDisabled("list")).toBe("true");
|
||||
expect(activatorDisabled("grid")).toBe("false");
|
||||
});
|
||||
});
|
||||
|
||||
@@ -29,6 +29,7 @@ import type {
|
||||
} from "@/v2/composables/useGalleryMode";
|
||||
import { useInputModality } from "@/v2/composables/useInputModality";
|
||||
import { shouldAutofocusSearch } from "@/v2/utils/autofocus";
|
||||
import type { ListSortKey, SortOption } from "./listColumns";
|
||||
|
||||
defineOptions({ inheritAttrs: false });
|
||||
|
||||
@@ -76,6 +77,12 @@ const props = withDefaults(
|
||||
/** Direction toggle for grid-mode sort. Disabled in list mode
|
||||
* (list-mode sort is driven by the column-header clicks). */
|
||||
sortDir?: Ref<"asc" | "desc"> | "asc" | "desc";
|
||||
/** Active sort axis. `null` when the gallery is ordered by a key the
|
||||
* selector doesn't offer, which leaves no entry highlighted. */
|
||||
sortKey?: Ref<ListSortKey | null> | ListSortKey | null;
|
||||
/** Axes for the sort selector. Empty hides the control, as on index
|
||||
* views, which sort their tiles themselves. */
|
||||
sortKeyItems?: readonly SortOption[];
|
||||
/** Show the search field on the left. v-model:search controls its value. */
|
||||
showSearch?: boolean;
|
||||
search?: string;
|
||||
@@ -103,6 +110,8 @@ const props = withDefaults(
|
||||
// substitute downstream through `effectiveGroupByItems`.
|
||||
groupByItems: () => [],
|
||||
sortDir: "asc",
|
||||
sortKey: null,
|
||||
sortKeyItems: () => [],
|
||||
showSearch: false,
|
||||
search: "",
|
||||
searchPlaceholder: "",
|
||||
@@ -117,6 +126,7 @@ const emit = defineEmits<{
|
||||
(e: "update:groupBy", value: GroupByMode): void;
|
||||
(e: "update:layout", value: LayoutMode): void;
|
||||
(e: "update:sortDir", value: "asc" | "desc"): void;
|
||||
(e: "update:sortKey", value: ListSortKey): void;
|
||||
(e: "update:search", value: string): void;
|
||||
(e: "update:segmentFilter", payload: { key: string; value: string }): void;
|
||||
(e: "click:filter"): void;
|
||||
@@ -132,6 +142,7 @@ function toValue<T>(source: Ref<T> | T): T {
|
||||
const groupByValue = computed(() => toValue(props.groupBy));
|
||||
const layoutValue = computed(() => toValue(props.layout));
|
||||
const sortDirValue = computed(() => toValue(props.sortDir));
|
||||
const sortKeyValue = computed(() => toValue(props.sortKey));
|
||||
|
||||
const layoutItems = computed(() => [
|
||||
{
|
||||
@@ -213,6 +224,10 @@ function setSortDir(value: "asc" | "desc") {
|
||||
emit("update:sortDir", value);
|
||||
}
|
||||
|
||||
function setSortKey(value: ListSortKey) {
|
||||
emit("update:sortKey", value);
|
||||
}
|
||||
|
||||
function setSearch(value: string) {
|
||||
emit("update:search", value);
|
||||
}
|
||||
@@ -302,6 +317,34 @@ const { smAndUp } = useBreakpoint();
|
||||
@update:model-value="setGroupBy"
|
||||
/>
|
||||
|
||||
<!-- A menu, not a slider: too many axes for the segmented pattern
|
||||
the neighbouring clusters use. -->
|
||||
<RMenu
|
||||
v-if="smAndUp && sortKeyItems.length > 0"
|
||||
location="bottom end"
|
||||
:offset="8"
|
||||
width="220px"
|
||||
>
|
||||
<template #activator="{ props: activatorProps }">
|
||||
<RBtn
|
||||
v-bind="activatorProps"
|
||||
variant="outlined"
|
||||
surface
|
||||
icon="mdi-sort"
|
||||
rounded="circle"
|
||||
:disabled="layoutValue === 'list'"
|
||||
:aria-label="t('gallery.sort-by')"
|
||||
/>
|
||||
</template>
|
||||
<RMenuItem
|
||||
v-for="item in sortKeyItems"
|
||||
:key="item.key"
|
||||
:label="item.label"
|
||||
:variant="sortKeyValue === item.key ? 'active' : 'default'"
|
||||
@click="setSortKey(item.key)"
|
||||
/>
|
||||
</RMenu>
|
||||
|
||||
<RSliderBtnGroup
|
||||
v-if="smAndUp"
|
||||
:model-value="sortDirValue"
|
||||
@@ -365,6 +408,17 @@ const { smAndUp } = useBreakpoint();
|
||||
/>
|
||||
<RDivider />
|
||||
</template>
|
||||
<template v-if="sortKeyItems.length > 0">
|
||||
<RMenuItem
|
||||
v-for="item in sortKeyItems"
|
||||
:key="item.key"
|
||||
:label="item.label"
|
||||
:variant="sortKeyValue === item.key ? 'active' : 'default'"
|
||||
:disabled="layoutValue === 'list'"
|
||||
@click="setSortKey(item.key)"
|
||||
/>
|
||||
<RDivider />
|
||||
</template>
|
||||
<RMenuItem
|
||||
:label="t('gallery.sort-ascending')"
|
||||
icon="mdi-sort-ascending"
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
getListColumns,
|
||||
getSortOptions,
|
||||
isListSortKey,
|
||||
isSortableColumn,
|
||||
} from "@/v2/components/Gallery/listColumns";
|
||||
@@ -24,3 +25,34 @@ describe("list column sort keys", () => {
|
||||
expect(isListSortKey("last_played")).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("grid-mode sort options", () => {
|
||||
it("offers exactly the axes the list headers make clickable", () => {
|
||||
expect(getSortOptions(true).map((option) => option.key)).toEqual([
|
||||
"name",
|
||||
"platform_id",
|
||||
"fs_size_bytes",
|
||||
"created_at",
|
||||
"first_release_date",
|
||||
"average_rating",
|
||||
"hltb_main_story",
|
||||
]);
|
||||
});
|
||||
|
||||
it("labels each axis with its column header", () => {
|
||||
const labels = new Map(
|
||||
getListColumns(true)
|
||||
.filter(isSortableColumn)
|
||||
.map((column) => [column.key, column.label]),
|
||||
);
|
||||
for (const option of getSortOptions(true)) {
|
||||
expect(option.label).toBe(labels.get(option.key));
|
||||
}
|
||||
});
|
||||
|
||||
it("drops the platform axis on single-platform surfaces", () => {
|
||||
const keys = getSortOptions(false).map((option) => option.key);
|
||||
expect(keys).not.toContain("platform_id");
|
||||
expect(keys).toContain("name");
|
||||
});
|
||||
});
|
||||
|
||||
@@ -226,10 +226,24 @@ export function isSortableColumn(
|
||||
return column.sortable;
|
||||
}
|
||||
|
||||
/** A sort axis offered by the toolbar's grid-mode selector. */
|
||||
export interface SortOption {
|
||||
key: ListSortKey;
|
||||
label: string;
|
||||
}
|
||||
|
||||
/** Sort axes for the grid-mode selector, derived from the same columns
|
||||
* list mode makes clickable so the two surfaces can't drift. */
|
||||
export function getSortOptions(showPlatform: boolean): readonly SortOption[] {
|
||||
return getListColumns(showPlatform)
|
||||
.filter(isSortableColumn)
|
||||
.map(({ key, label }) => ({ key, label }));
|
||||
}
|
||||
|
||||
// The sort keys list mode can toggle, read off the columns themselves so a
|
||||
// sortable column cannot go missing from them.
|
||||
const LIST_SORT_KEYS: ReadonlySet<string> = new Set<string>(
|
||||
LIST_COLUMNS.filter(isSortableColumn).map((column) => column.key),
|
||||
getSortOptions(true).map((option) => option.key),
|
||||
);
|
||||
|
||||
/** Whether the gallery's current order key is one list mode can sort by. */
|
||||
|
||||
@@ -0,0 +1,160 @@
|
||||
import { flushPromises, mount } from "@vue/test-utils";
|
||||
import { createPinia, setActivePinia } from "pinia";
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import storeAuth from "@/stores/auth";
|
||||
import storeConfig from "@/stores/config";
|
||||
import storeHeartbeat from "@/stores/heartbeat";
|
||||
import FolderMappingsSection from "./FolderMappingsSection.vue";
|
||||
|
||||
const {
|
||||
getSupportedPlatforms,
|
||||
addPlatformBindConfig,
|
||||
deletePlatformBindConfig,
|
||||
addPlatformVersionConfig,
|
||||
deletePlatformVersionConfig,
|
||||
apiGet,
|
||||
} = vi.hoisted(() => ({
|
||||
getSupportedPlatforms: vi.fn(),
|
||||
addPlatformBindConfig: vi.fn(),
|
||||
deletePlatformBindConfig: vi.fn(),
|
||||
addPlatformVersionConfig: vi.fn(),
|
||||
deletePlatformVersionConfig: vi.fn(),
|
||||
apiGet: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("@/services/api", () => ({ default: { get: apiGet } }));
|
||||
vi.mock("@/services/api/platform", () => ({
|
||||
default: { getSupportedPlatforms },
|
||||
}));
|
||||
vi.mock("@/services/api/config", () => ({
|
||||
default: {
|
||||
addPlatformBindConfig,
|
||||
deletePlatformBindConfig,
|
||||
addPlatformVersionConfig,
|
||||
deletePlatformVersionConfig,
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("vue-i18n", () => ({
|
||||
useI18n: () => ({ t: (key: string) => key }),
|
||||
}));
|
||||
|
||||
vi.mock("@/v2/composables/useSnackbar", () => ({
|
||||
useSnackbar: () => ({ success: vi.fn(), error: vi.fn() }),
|
||||
}));
|
||||
vi.mock("@/v2/composables/usePlatformIconCache", () => ({
|
||||
prefetchPlatformIcons: vi.fn(),
|
||||
}));
|
||||
|
||||
const N64 = { id: 1, slug: "n64", name: "Nintendo 64", display_name: "N64" };
|
||||
const PS2 = { id: 2, slug: "ps2", name: "PlayStation 2", display_name: "PS2" };
|
||||
|
||||
interface Row {
|
||||
fsSlug: string;
|
||||
slug?: string;
|
||||
displayName?: string;
|
||||
type: "alias" | "variant" | "auto" | null;
|
||||
}
|
||||
|
||||
// Exposes the built rows and renders the Platform cell the edit actions hang off.
|
||||
const RTableStub = {
|
||||
name: "RTable",
|
||||
props: ["items"],
|
||||
template:
|
||||
'<div><slot v-for="row in items" name="cell.platform" :row="row" /></div>',
|
||||
};
|
||||
|
||||
async function mountWith(folders: string[]) {
|
||||
const heartbeat = storeHeartbeat();
|
||||
heartbeat.value.FILESYSTEM.FS_PLATFORMS = folders;
|
||||
vi.spyOn(heartbeat, "fetchHeartbeat").mockResolvedValue(heartbeat.value);
|
||||
|
||||
const wrapper = mount(FolderMappingsSection, {
|
||||
global: {
|
||||
stubs: {
|
||||
RTable: RTableStub,
|
||||
RBtn: true,
|
||||
RDialog: true,
|
||||
RIcon: true,
|
||||
RTextField: true,
|
||||
PlatformSelect: true,
|
||||
CachedPlatformIcon: true,
|
||||
},
|
||||
},
|
||||
});
|
||||
await flushPromises();
|
||||
|
||||
return {
|
||||
wrapper,
|
||||
rows: wrapper.findComponent(RTableStub).props("items") as Row[],
|
||||
};
|
||||
}
|
||||
|
||||
describe("FolderMappingsSection", () => {
|
||||
beforeEach(() => {
|
||||
setActivePinia(createPinia());
|
||||
getSupportedPlatforms.mockReset();
|
||||
getSupportedPlatforms.mockResolvedValue({ data: [N64, PS2] });
|
||||
addPlatformBindConfig.mockReset().mockResolvedValue(undefined);
|
||||
deletePlatformBindConfig.mockReset().mockResolvedValue(undefined);
|
||||
addPlatformVersionConfig.mockReset().mockResolvedValue(undefined);
|
||||
deletePlatformVersionConfig.mockReset().mockResolvedValue(undefined);
|
||||
// A refetch echoes the config back, so it neither clears nor changes it.
|
||||
apiGet.mockReset();
|
||||
apiGet.mockImplementation(() =>
|
||||
Promise.resolve({ data: { ...storeConfig().config } }),
|
||||
);
|
||||
|
||||
storeAuth().user = { oauth_scopes: ["platforms.write"] } as never;
|
||||
storeConfig().config.CONFIG_FILE_WRITABLE = true;
|
||||
});
|
||||
|
||||
// config.yml stores "Nintendo 64" under the key "nintendo 64".
|
||||
it("shows a binding written for a folder whose name is not lowercase", async () => {
|
||||
storeConfig().config.PLATFORMS_BINDING = { "nintendo 64": "n64" };
|
||||
|
||||
const { rows } = await mountWith(["Nintendo 64"]);
|
||||
|
||||
expect(rows).toEqual([
|
||||
{
|
||||
fsSlug: "Nintendo 64",
|
||||
slug: "n64",
|
||||
displayName: "N64",
|
||||
type: "alias",
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("shows a version written for a folder whose name is not lowercase", async () => {
|
||||
storeConfig().config.PLATFORMS_VERSIONS = { "playstation 2": "ps2" };
|
||||
|
||||
const { rows } = await mountWith(["PlayStation 2"]);
|
||||
|
||||
expect(rows[0]).toMatchObject({ slug: "ps2", type: "variant" });
|
||||
});
|
||||
|
||||
it("marks a folder matching a platform slug as auto-detected whatever its case", async () => {
|
||||
const { rows } = await mountWith(["PS2"]);
|
||||
|
||||
expect(rows[0]).toMatchObject({ slug: "ps2", type: "auto" });
|
||||
});
|
||||
|
||||
// A bare add on a folder that already has a binding is a no-op server-side.
|
||||
it("replaces the binding when a mapped folder is pointed at another platform", async () => {
|
||||
storeConfig().config.PLATFORMS_BINDING = { "nintendo 64": "n64" };
|
||||
|
||||
const { wrapper } = await mountWith(["Nintendo 64"]);
|
||||
wrapper
|
||||
.findComponent({ name: "FolderMappingPlatformCell" })
|
||||
.vm.$emit("select", "ps2");
|
||||
await flushPromises();
|
||||
|
||||
expect(deletePlatformBindConfig).toHaveBeenCalledWith({
|
||||
fsSlug: "Nintendo 64",
|
||||
});
|
||||
expect(addPlatformBindConfig).toHaveBeenCalledWith({
|
||||
fsSlug: "Nintendo 64",
|
||||
slug: "ps2",
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -70,36 +70,35 @@ const TYPE_ORDER: Record<NonNullable<RowType> | "none", number> = {
|
||||
const mappings = computed<Row[]>(() => {
|
||||
const rows: Row[] = [];
|
||||
const folders = heartbeat.value?.FILESYSTEM?.FS_PLATFORMS || [];
|
||||
const bindings = config.value.PLATFORMS_BINDING || {};
|
||||
const versions = config.value.PLATFORMS_VERSIONS || {};
|
||||
const autoSlug: Record<string, string | undefined> = {};
|
||||
|
||||
for (const p of supportedPlatforms.value) autoSlug[p.slug] = p.slug;
|
||||
|
||||
for (const folder of folders) {
|
||||
if (bindings[folder]) {
|
||||
const slug = bindings[folder];
|
||||
const platform = supportedPlatforms.value.find((p) => p.slug === slug);
|
||||
const binding = configStore.getPlatformBinding(folder);
|
||||
if (binding) {
|
||||
const platform = supportedPlatforms.value.find((p) => p.slug === binding);
|
||||
rows.push({
|
||||
fsSlug: folder,
|
||||
slug,
|
||||
displayName: platform?.display_name || platform?.name || slug,
|
||||
slug: binding,
|
||||
displayName: platform?.display_name || platform?.name || binding,
|
||||
type: "alias",
|
||||
});
|
||||
continue;
|
||||
}
|
||||
if (versions[folder]) {
|
||||
const slug = versions[folder];
|
||||
const platform = supportedPlatforms.value.find((p) => p.slug === slug);
|
||||
const version = configStore.getPlatformVersion(folder);
|
||||
if (version) {
|
||||
const platform = supportedPlatforms.value.find((p) => p.slug === version);
|
||||
rows.push({
|
||||
fsSlug: folder,
|
||||
slug,
|
||||
displayName: platform?.display_name || platform?.name || slug,
|
||||
slug: version,
|
||||
displayName: platform?.display_name || platform?.name || version,
|
||||
type: "variant",
|
||||
});
|
||||
continue;
|
||||
}
|
||||
const auto = autoSlug[folder];
|
||||
// Platform slugs are lowercase; the folder on disk may not be.
|
||||
const auto = autoSlug[folder.toLowerCase()];
|
||||
if (auto) {
|
||||
const platform = supportedPlatforms.value.find((p) => p.slug === auto);
|
||||
rows.push({
|
||||
|
||||
@@ -109,11 +109,21 @@ async function release(container: AdminStreamingContainer): Promise<void> {
|
||||
}
|
||||
}
|
||||
|
||||
function sessionLabel(container: AdminStreamingContainer): string {
|
||||
function sessionState(container: AdminStreamingContainer): string {
|
||||
const session = container.session;
|
||||
if (!session) return t("settings.streaming-idle");
|
||||
if (session.desktop) return t("settings.streaming-desktop-session");
|
||||
return session.rom_name ?? t("settings.streaming-unknown-game");
|
||||
return [
|
||||
session.desktop
|
||||
? t("settings.streaming-desktop-session")
|
||||
: (session.rom_name ?? t("settings.streaming-unknown-game")),
|
||||
session.claimed_at &&
|
||||
t("settings.streaming-since", {
|
||||
time: formatTimestamp(session.claimed_at, locale.value),
|
||||
}),
|
||||
session.username && t("settings.streaming-by", { user: session.username }),
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join(" ");
|
||||
}
|
||||
|
||||
onMounted(load);
|
||||
@@ -172,43 +182,33 @@ onMounted(load);
|
||||
{{ t("settings.streaming-unusable") }}
|
||||
</span>
|
||||
<span v-else class="r-v2-streaming__state">
|
||||
{{ sessionLabel(container) }}
|
||||
<template v-if="container.session?.claimed_at">
|
||||
{{
|
||||
t("settings.streaming-since", {
|
||||
time: formatTimestamp(container.session.claimed_at, locale),
|
||||
})
|
||||
}}
|
||||
</template>
|
||||
<template v-if="container.session?.username">
|
||||
{{
|
||||
t("settings.streaming-by", { user: container.session.username })
|
||||
}}
|
||||
</template>
|
||||
{{ sessionState(container) }}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<RBtn
|
||||
v-if="container.supports_desktop"
|
||||
variant="outlined"
|
||||
density="compact"
|
||||
prepend-icon="mdi-desktop-classic"
|
||||
:disabled="!container.configured || !!container.session"
|
||||
@click="openDesktop(container)"
|
||||
>
|
||||
{{ t("settings.streaming-open-desktop") }}
|
||||
</RBtn>
|
||||
<RBtn
|
||||
variant="text"
|
||||
density="compact"
|
||||
color="error"
|
||||
prepend-icon="mdi-stop"
|
||||
:disabled="!container.session"
|
||||
:loading="releasing === container.container"
|
||||
@click="release(container)"
|
||||
>
|
||||
{{ t("settings.streaming-release") }}
|
||||
</RBtn>
|
||||
<div class="r-v2-streaming__actions">
|
||||
<RBtn
|
||||
v-if="container.supports_desktop"
|
||||
variant="outlined"
|
||||
density="compact"
|
||||
prepend-icon="mdi-desktop-classic"
|
||||
:disabled="!container.configured || !!container.session"
|
||||
@click="openDesktop(container)"
|
||||
>
|
||||
{{ t("settings.streaming-open-desktop") }}
|
||||
</RBtn>
|
||||
<RBtn
|
||||
variant="text"
|
||||
density="compact"
|
||||
color="error"
|
||||
prepend-icon="mdi-stop"
|
||||
:disabled="!container.session"
|
||||
:loading="releasing === container.container"
|
||||
@click="release(container)"
|
||||
>
|
||||
{{ t("settings.streaming-release") }}
|
||||
</RBtn>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
</SettingsSection>
|
||||
@@ -221,7 +221,8 @@ onMounted(load);
|
||||
}
|
||||
|
||||
.r-v2-streaming__row {
|
||||
display: flex;
|
||||
display: grid;
|
||||
grid-template-columns: auto minmax(0, 1fr) auto;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
padding: 12px 16px;
|
||||
@@ -233,7 +234,6 @@ onMounted(load);
|
||||
|
||||
.r-v2-streaming__icon {
|
||||
color: var(--r-color-fg-muted);
|
||||
flex-shrink: 0;
|
||||
}
|
||||
.r-v2-streaming__icon--busy {
|
||||
color: var(--r-color-brand-primary);
|
||||
@@ -243,8 +243,6 @@ onMounted(load);
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 2px;
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.r-v2-streaming__name {
|
||||
@@ -256,11 +254,25 @@ onMounted(load);
|
||||
.r-v2-streaming__state {
|
||||
font-size: var(--r-font-size-xs);
|
||||
color: var(--r-color-fg-muted);
|
||||
}
|
||||
.r-v2-streaming__meta {
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.r-v2-streaming__actions {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
/* On a phone the actions drop under the details instead of squeezing them out. */
|
||||
html[data-bp~="xs"] .r-v2-streaming__actions {
|
||||
grid-column: 2 / -1;
|
||||
}
|
||||
|
||||
.r-v2-streaming__warning {
|
||||
font-size: var(--r-font-size-xs);
|
||||
color: var(--r-color-danger-fg);
|
||||
|
||||
180
frontend/src/v2/composables/useGalleryOrderUrl/index.test.ts
Normal file
180
frontend/src/v2/composables/useGalleryOrderUrl/index.test.ts
Normal file
@@ -0,0 +1,180 @@
|
||||
import { flushPromises, mount } from "@vue/test-utils";
|
||||
import { createPinia, setActivePinia } from "pinia";
|
||||
import { beforeEach, describe, expect, it } from "vitest";
|
||||
import { createApp, h, nextTick } from "vue";
|
||||
import {
|
||||
createMemoryHistory,
|
||||
createRouter,
|
||||
type Router,
|
||||
RouterView,
|
||||
} from "vue-router";
|
||||
import storeGalleryRoms from "@/v2/stores/galleryRoms";
|
||||
import { useGalleryOrderUrl } from "./index";
|
||||
|
||||
const Blank = { template: "<div />" };
|
||||
|
||||
const Host = {
|
||||
setup() {
|
||||
useGalleryOrderUrl();
|
||||
},
|
||||
template: "<div />",
|
||||
};
|
||||
|
||||
async function mountAt(router: Router, path: string) {
|
||||
await router.push(path);
|
||||
await router.isReady();
|
||||
const wrapper = mount(Host, { global: { plugins: [router] } });
|
||||
await nextTick();
|
||||
return wrapper;
|
||||
}
|
||||
|
||||
function makeRouter() {
|
||||
return createRouter({
|
||||
history: createMemoryHistory(),
|
||||
routes: [
|
||||
{ path: "/platform/:platform", name: "platform", component: Blank },
|
||||
],
|
||||
});
|
||||
}
|
||||
|
||||
/** `patchQuery` batches its writes into a `nextTick` callback, and the
|
||||
* `router.replace` it then issues resolves asynchronously. */
|
||||
async function flushQueryWrite() {
|
||||
await nextTick();
|
||||
await flushPromises();
|
||||
}
|
||||
|
||||
describe("useGalleryOrderUrl", () => {
|
||||
beforeEach(() => {
|
||||
setActivePinia(createPinia());
|
||||
});
|
||||
|
||||
it("hydrates the store from the URL before the first fetch", async () => {
|
||||
const router = makeRouter();
|
||||
await mountAt(router, "/platform/1?orderBy=fs_size_bytes&orderDir=desc");
|
||||
|
||||
const gallery = storeGalleryRoms();
|
||||
expect(gallery.orderBy).toBe("fs_size_bytes");
|
||||
expect(gallery.orderDir).toBe("desc");
|
||||
});
|
||||
|
||||
it("falls back to the default sort for missing or unknown params", async () => {
|
||||
const gallery = storeGalleryRoms();
|
||||
gallery.setOrderBy("created_at");
|
||||
gallery.setOrderDir("desc");
|
||||
|
||||
const router = makeRouter();
|
||||
await mountAt(router, "/platform/1?orderBy=not_a_column");
|
||||
|
||||
expect(gallery.orderBy).toBe("name");
|
||||
expect(gallery.orderDir).toBe("asc");
|
||||
});
|
||||
|
||||
it("writes a column-header sort into the query", async () => {
|
||||
const router = makeRouter();
|
||||
await mountAt(router, "/platform/1");
|
||||
const gallery = storeGalleryRoms();
|
||||
|
||||
gallery.setOrderBy("average_rating");
|
||||
gallery.setOrderDir("desc");
|
||||
await flushQueryWrite();
|
||||
|
||||
expect(router.currentRoute.value.query).toMatchObject({
|
||||
orderBy: "average_rating",
|
||||
orderDir: "desc",
|
||||
});
|
||||
});
|
||||
|
||||
// Grid mode exposes only the direction toggle, so a direction-only
|
||||
// write has to reach the URL on its own.
|
||||
it("writes a direction-only change into the query", async () => {
|
||||
const router = makeRouter();
|
||||
await mountAt(router, "/platform/1");
|
||||
const gallery = storeGalleryRoms();
|
||||
|
||||
gallery.setOrderDir("desc");
|
||||
await flushQueryWrite();
|
||||
|
||||
expect(router.currentRoute.value.query.orderDir).toBe("desc");
|
||||
expect(router.currentRoute.value.query.orderBy).toBeUndefined();
|
||||
});
|
||||
|
||||
it("drops the params when the sort returns to the default", async () => {
|
||||
const router = makeRouter();
|
||||
await mountAt(router, "/platform/1?orderBy=created_at&orderDir=desc");
|
||||
const gallery = storeGalleryRoms();
|
||||
|
||||
gallery.setOrderBy("name");
|
||||
gallery.setOrderDir("asc");
|
||||
await flushQueryWrite();
|
||||
|
||||
expect(router.currentRoute.value.query.orderBy).toBeUndefined();
|
||||
expect(router.currentRoute.value.query.orderDir).toBeUndefined();
|
||||
});
|
||||
|
||||
it("follows the URL back to the previous sort on back-navigation", async () => {
|
||||
const router = makeRouter();
|
||||
await mountAt(router, "/platform/1?orderBy=created_at&orderDir=desc");
|
||||
const gallery = storeGalleryRoms();
|
||||
|
||||
await router.push("/platform/1?orderBy=hltb_main_story&orderDir=asc");
|
||||
await flushPromises();
|
||||
expect(gallery.orderBy).toBe("hltb_main_story");
|
||||
|
||||
router.back();
|
||||
await flushPromises();
|
||||
expect(gallery.orderBy).toBe("created_at");
|
||||
expect(gallery.orderDir).toBe("desc");
|
||||
});
|
||||
|
||||
it("leaves unrelated query params alone", async () => {
|
||||
const router = makeRouter();
|
||||
await mountAt(router, "/platform/1?search=zelda&layout=list");
|
||||
const gallery = storeGalleryRoms();
|
||||
|
||||
gallery.setOrderDir("desc");
|
||||
await flushQueryWrite();
|
||||
|
||||
expect(router.currentRoute.value.query).toMatchObject({
|
||||
search: "zelda",
|
||||
layout: "list",
|
||||
orderDir: "desc",
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
// `main.ts` mounts without awaiting `router.isReady()`, so setup-only
|
||||
// hydration holds solely because RouterView withholds the matched component
|
||||
// until the initial navigation resolves.
|
||||
describe("useGalleryOrderUrl on a cold load", () => {
|
||||
beforeEach(() => {
|
||||
setActivePinia(createPinia());
|
||||
});
|
||||
|
||||
it("sees the URL in setup() without awaiting router.isReady", async () => {
|
||||
const seenAtSetup: string[] = [];
|
||||
const GalleryView = {
|
||||
setup() {
|
||||
useGalleryOrderUrl();
|
||||
seenAtSetup.push(storeGalleryRoms().orderBy);
|
||||
return () => h("div");
|
||||
},
|
||||
};
|
||||
|
||||
const history = createMemoryHistory();
|
||||
history.replace("/platform/1?orderBy=average_rating&orderDir=desc");
|
||||
const router = createRouter({
|
||||
history,
|
||||
routes: [{ path: "/platform/:platform", component: GalleryView }],
|
||||
});
|
||||
|
||||
const app = createApp({ render: () => h(RouterView) });
|
||||
app.use(router);
|
||||
app.mount(document.createElement("div"));
|
||||
await flushPromises();
|
||||
|
||||
expect(seenAtSetup).toEqual(["average_rating"]);
|
||||
expect(storeGalleryRoms().orderDir).toBe("desc");
|
||||
app.unmount();
|
||||
});
|
||||
});
|
||||
61
frontend/src/v2/composables/useGalleryOrderUrl/index.ts
Normal file
61
frontend/src/v2/composables/useGalleryOrderUrl/index.ts
Normal file
@@ -0,0 +1,61 @@
|
||||
// useGalleryOrderUrl - bookmarkable gallery sort via URL query params.
|
||||
//
|
||||
// ?orderBy=fs_size_bytes (omitted at "name", the default)
|
||||
// ?orderDir=desc (omitted at "asc", the default)
|
||||
//
|
||||
// An unrecognised or absent param resolves to the default, so a link
|
||||
// without them lands on the same sort whatever the last gallery left in
|
||||
// the store. Hydration runs during setup, before the shell registers its
|
||||
// refetch watch, so the first fetch carries the params without echoing.
|
||||
import { storeToRefs } from "pinia";
|
||||
import { watch } from "vue";
|
||||
import { useRoute, useRouter } from "vue-router";
|
||||
import storeGalleryRoms, {
|
||||
DEFAULT_ORDER_BY,
|
||||
DEFAULT_ORDER_DIR,
|
||||
type GalleryOrderDir,
|
||||
type GalleryOrderKey,
|
||||
isGalleryOrderDir,
|
||||
isGalleryOrderKey,
|
||||
} from "@/v2/stores/galleryRoms";
|
||||
import { syncQueryParam } from "@/v2/utils/routeQuery";
|
||||
|
||||
function parseOrderBy(value: unknown): GalleryOrderKey {
|
||||
return typeof value === "string" && isGalleryOrderKey(value)
|
||||
? value
|
||||
: DEFAULT_ORDER_BY;
|
||||
}
|
||||
|
||||
function parseOrderDir(value: unknown): GalleryOrderDir {
|
||||
return typeof value === "string" && isGalleryOrderDir(value)
|
||||
? value
|
||||
: DEFAULT_ORDER_DIR;
|
||||
}
|
||||
|
||||
export function useGalleryOrderUrl() {
|
||||
const route = useRoute();
|
||||
const router = useRouter();
|
||||
const galleryRoms = storeGalleryRoms();
|
||||
const { orderBy, orderDir } = storeToRefs(galleryRoms);
|
||||
|
||||
function applyFromUrl() {
|
||||
const by = parseOrderBy(route.query.orderBy);
|
||||
const dir = parseOrderDir(route.query.orderDir);
|
||||
if (by !== orderBy.value) galleryRoms.setOrderBy(by);
|
||||
if (dir !== orderDir.value) galleryRoms.setOrderDir(dir);
|
||||
}
|
||||
|
||||
applyFromUrl();
|
||||
|
||||
watch(() => [route.query.orderBy, route.query.orderDir], applyFromUrl);
|
||||
|
||||
// Drop the param when the value is the default, which keeps URLs clean.
|
||||
watch([orderBy, orderDir], ([by, dir]) => {
|
||||
syncQueryParam(router, "orderBy", by === DEFAULT_ORDER_BY ? undefined : by);
|
||||
syncQueryParam(
|
||||
router,
|
||||
"orderDir",
|
||||
dir === DEFAULT_ORDER_DIR ? undefined : dir,
|
||||
);
|
||||
});
|
||||
}
|
||||
@@ -26,7 +26,7 @@ import {
|
||||
type LayoutMode,
|
||||
useGalleryMode,
|
||||
} from "@/v2/composables/useGalleryMode";
|
||||
import { patchQuery } from "@/v2/utils/routeQuery";
|
||||
import { syncQueryParam } from "@/v2/utils/routeQuery";
|
||||
|
||||
const VALID_GROUP_BY: readonly GroupByMode[] = [
|
||||
"letter",
|
||||
@@ -67,20 +67,11 @@ export function useGalleryViewModeUrl() {
|
||||
watch(() => route.query.group, applyFromUrl);
|
||||
watch(() => route.query.layout, applyFromUrl);
|
||||
|
||||
function syncQuery(key: "group" | "layout", value: string | undefined) {
|
||||
const current =
|
||||
typeof route.query[key] === "string"
|
||||
? (route.query[key] as string)
|
||||
: undefined;
|
||||
if (value === current) return;
|
||||
patchQuery(router, { [key]: value });
|
||||
}
|
||||
|
||||
// Drop the param when the value is the default — keeps URLs clean.
|
||||
watch(groupBy, (next) => {
|
||||
syncQuery("group", next === "none" ? undefined : next);
|
||||
syncQueryParam(router, "group", next === "none" ? undefined : next);
|
||||
});
|
||||
watch(layout, (next) => {
|
||||
syncQuery("layout", next === "grid" ? undefined : next);
|
||||
syncQueryParam(router, "layout", next === "grid" ? undefined : next);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -398,7 +398,9 @@ export function useGalleryVirtualItems(opts: Options) {
|
||||
void (opts.ratioVersion ? opts.ratioVersion.value : 0);
|
||||
const ratioAt = makeRatioAt();
|
||||
|
||||
if (opts.groupBy.value === "letter") {
|
||||
// A non-lexical sort (size, rating, a date) gets no server char index,
|
||||
// so grouping would have no headers to build and would render nothing.
|
||||
if (opts.groupBy.value === "letter" && ranges.length > 0) {
|
||||
// Header + own flow-packed rows per letter (rows restart per letter).
|
||||
for (const range of ranges) {
|
||||
items.push(shareHeader(range.letter));
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { computed, ref } from "vue";
|
||||
import { useGalleryVirtualItems } from "./index";
|
||||
|
||||
// The backend only indexes letters for a lexically ordered result, so sorting
|
||||
// the grid by size / rating / a date ships an empty `char_index`.
|
||||
function build(charIndex: Record<string, number>) {
|
||||
const { virtualItems } = useGalleryVirtualItems({
|
||||
layout: ref("grid" as const),
|
||||
groupBy: ref("letter" as const),
|
||||
total: ref(5),
|
||||
charIndex: ref(charIndex),
|
||||
columns: ref(3),
|
||||
loadingInitial: computed(() => false),
|
||||
emptyMessage: ref("empty"),
|
||||
rowWidth: 600,
|
||||
});
|
||||
return virtualItems.value;
|
||||
}
|
||||
|
||||
describe("grid grouping without a char index", () => {
|
||||
it("groups under letter headers when the server indexed them", () => {
|
||||
const items = build({ a: 0, b: 3 });
|
||||
|
||||
expect(items.filter((it) => it.kind === "letter-header")).toHaveLength(2);
|
||||
expect(items.some((it) => it.kind === "row")).toBe(true);
|
||||
});
|
||||
|
||||
it("falls back to flat rows instead of rendering nothing", () => {
|
||||
const items = build({});
|
||||
|
||||
expect(items.filter((it) => it.kind === "row").length).toBeGreaterThan(0);
|
||||
expect(items.filter((it) => it.kind === "letter-header")).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
@@ -44,17 +44,34 @@ export type SimpleRom = SimpleRomSchema;
|
||||
* `RomUser`, so this includes fields that aren't direct properties of
|
||||
* `SimpleRomSchema` (e.g. `first_release_date` lives on RomMetadata).
|
||||
* Keep this in sync with the columns the gallery surface exposes. */
|
||||
export type GalleryOrderKey =
|
||||
| "name"
|
||||
| "fs_name"
|
||||
| "platform_id"
|
||||
| "fs_size_bytes"
|
||||
| "created_at"
|
||||
| "updated_at"
|
||||
| "first_release_date"
|
||||
| "average_rating"
|
||||
| "hltb_main_story"
|
||||
| "last_played";
|
||||
const GALLERY_ORDER_KEYS = [
|
||||
"name",
|
||||
"fs_name",
|
||||
"platform_id",
|
||||
"fs_size_bytes",
|
||||
"created_at",
|
||||
"updated_at",
|
||||
"first_release_date",
|
||||
"average_rating",
|
||||
"hltb_main_story",
|
||||
"last_played",
|
||||
] as const;
|
||||
|
||||
export type GalleryOrderKey = (typeof GALLERY_ORDER_KEYS)[number];
|
||||
|
||||
export type GalleryOrderDir = "asc" | "desc";
|
||||
|
||||
export const DEFAULT_ORDER_BY: GalleryOrderKey = "name";
|
||||
export const DEFAULT_ORDER_DIR: GalleryOrderDir = "asc";
|
||||
|
||||
/** Narrows an untrusted string (a URL query param) to a sort key. */
|
||||
export function isGalleryOrderKey(value: string): value is GalleryOrderKey {
|
||||
return (GALLERY_ORDER_KEYS as readonly string[]).includes(value);
|
||||
}
|
||||
|
||||
export function isGalleryOrderDir(value: string): value is GalleryOrderDir {
|
||||
return value === "asc" || value === "desc";
|
||||
}
|
||||
|
||||
type GalleryFilterStore = ExtractPiniaStoreType<typeof storeGalleryFilter>;
|
||||
|
||||
@@ -224,7 +241,7 @@ interface State {
|
||||
// Order params — gallery-list scoped (separate from v1's localStorage
|
||||
// keys so v1/v2 don't fight over the same value).
|
||||
orderBy: GalleryOrderKey;
|
||||
orderDir: "asc" | "desc";
|
||||
orderDir: GalleryOrderDir;
|
||||
}
|
||||
|
||||
const defaults = (): State => ({
|
||||
@@ -243,8 +260,8 @@ const defaults = (): State => ({
|
||||
initialFetching: false,
|
||||
metadataLoaded: false,
|
||||
selectingAll: false,
|
||||
orderBy: "name",
|
||||
orderDir: "asc",
|
||||
orderBy: DEFAULT_ORDER_BY,
|
||||
orderDir: DEFAULT_ORDER_DIR,
|
||||
});
|
||||
|
||||
function alignToWindow(offset: number): number {
|
||||
@@ -289,7 +306,7 @@ export default defineStore("v2GalleryRoms", {
|
||||
setOrderBy(key: GalleryOrderKey) {
|
||||
this.orderBy = key;
|
||||
},
|
||||
setOrderDir(dir: "asc" | "desc") {
|
||||
setOrderDir(dir: GalleryOrderDir) {
|
||||
this.orderDir = dir;
|
||||
},
|
||||
|
||||
|
||||
@@ -45,3 +45,16 @@ export function patchQuery(
|
||||
void router.replace({ query });
|
||||
});
|
||||
}
|
||||
|
||||
/** Write one URL-backed value, `undefined` dropping the param. The compare
|
||||
* against the live query is what stops a loop with the watcher reading it. */
|
||||
export function syncQueryParam(
|
||||
router: QueryRouter,
|
||||
key: string,
|
||||
value: string | undefined,
|
||||
): void {
|
||||
const raw = router.currentRoute.value.query[key];
|
||||
const current = typeof raw === "string" ? raw : undefined;
|
||||
if (value === current) return;
|
||||
patchQuery(router, { [key]: value });
|
||||
}
|
||||
|
||||
@@ -28,10 +28,10 @@ const {
|
||||
getRoms: vi.fn(),
|
||||
getVirtualCollection: vi.fn(),
|
||||
push: vi.fn(),
|
||||
routeGuards: [] as ((to: {
|
||||
name: string;
|
||||
params: Record<string, string>;
|
||||
}) => unknown)[],
|
||||
routeGuards: [] as ((
|
||||
to: { name: string; path: string; params: Record<string, string> },
|
||||
from: { name: string; path: string; params: Record<string, string> },
|
||||
) => unknown)[],
|
||||
snackbarError: vi.fn(),
|
||||
snackbarInfo: vi.fn(),
|
||||
}));
|
||||
@@ -150,6 +150,34 @@ async function mountView() {
|
||||
return wrapper;
|
||||
}
|
||||
|
||||
/** Drive the captured route guards the way vue-router does: both `to` and
|
||||
* `from`, each carrying the path the guard compares. */
|
||||
/** A sort / filter / search change: same path, new query. */
|
||||
function runQueryOnlyGuards() {
|
||||
const at = {
|
||||
name: routeState.name,
|
||||
path: `/collection/${routeState.params.collection}`,
|
||||
params: { ...routeState.params },
|
||||
};
|
||||
routeGuards.forEach((guard) => guard({ ...at }, { ...at }));
|
||||
}
|
||||
|
||||
function runRouteGuards(name: string, collection: string) {
|
||||
const from = {
|
||||
name: routeState.name,
|
||||
path: `/collection/${routeState.params.collection}`,
|
||||
params: { ...routeState.params },
|
||||
};
|
||||
routeState.name = name;
|
||||
routeState.params = { collection };
|
||||
const to = {
|
||||
name,
|
||||
path: `/collection/${collection}`,
|
||||
params: { collection },
|
||||
};
|
||||
routeGuards.forEach((guard) => guard(to, from));
|
||||
}
|
||||
|
||||
describe("Collection view random rom", () => {
|
||||
beforeEach(() => {
|
||||
setActivePinia(createPinia());
|
||||
@@ -245,10 +273,7 @@ describe("Collection view random rom", () => {
|
||||
const wrapper = await mountView();
|
||||
await wrapper.get("button.random").trigger("click");
|
||||
|
||||
routeState.params = { collection: "2" };
|
||||
routeGuards.forEach((guard) =>
|
||||
guard({ name: "collection", params: { collection: "2" } }),
|
||||
);
|
||||
runRouteGuards("collection", "2");
|
||||
await flushPromises();
|
||||
|
||||
resolvePick({ data: rom(42) });
|
||||
@@ -270,10 +295,7 @@ describe("Collection view random rom", () => {
|
||||
const wrapper = await mountView();
|
||||
await wrapper.get("button.random").trigger("click");
|
||||
|
||||
routeState.params = { collection: "2" };
|
||||
routeGuards.forEach((guard) =>
|
||||
guard({ name: "collection", params: { collection: "2" } }),
|
||||
);
|
||||
runRouteGuards("collection", "2");
|
||||
await flushPromises();
|
||||
|
||||
failPick(new Error("boom"));
|
||||
@@ -420,11 +442,10 @@ describe("Collection view freshness", () => {
|
||||
vi.spyOn(galleryRoms, "fetchInitialMetadata").mockResolvedValue();
|
||||
const wrapper = mount(CollectionView);
|
||||
|
||||
routeState.params = { collection: "2" };
|
||||
getCollection.mockResolvedValueOnce({
|
||||
data: { ...collection(2), rom_count: 22 },
|
||||
});
|
||||
await routeGuards[0]?.({ name: "collection", params: { collection: "2" } });
|
||||
runRouteGuards("collection", "2");
|
||||
await flushPromises();
|
||||
|
||||
settleFirst({ data: { ...collection(1), rom_count: 11 } });
|
||||
@@ -454,3 +475,19 @@ describe("Collection view freshness", () => {
|
||||
expect(wrapper.get(".rom-count").text()).toBe("9000");
|
||||
});
|
||||
});
|
||||
|
||||
describe("Collection view query-only navigation", () => {
|
||||
it("does not re-read or reset the collection when only the query changes", async () => {
|
||||
const galleryRoms = storeGalleryRoms();
|
||||
const wrapper = await mountView();
|
||||
getCollection.mockClear();
|
||||
const resetGallery = vi.spyOn(galleryRoms, "resetGallery");
|
||||
|
||||
runQueryOnlyGuards();
|
||||
await flushPromises();
|
||||
|
||||
expect(getCollection).not.toHaveBeenCalled();
|
||||
expect(resetGallery).not.toHaveBeenCalled();
|
||||
expect(wrapper.get(".rom-count").text()).toBe("9000");
|
||||
});
|
||||
});
|
||||
|
||||
@@ -262,7 +262,11 @@ onMounted(() => {
|
||||
loadForRoute(kindFromRoute(route.name), String(route.params.collection));
|
||||
});
|
||||
|
||||
onBeforeRouteUpdate((to) => {
|
||||
onBeforeRouteUpdate((to, from) => {
|
||||
// `loadForRoute` resets the gallery, so running it for a query-only
|
||||
// change (sort, filters, search) would blank and re-bootstrap the
|
||||
// collection already on screen.
|
||||
if (to.path === from.path) return;
|
||||
loadForRoute(kindFromRoute(to.name), String(to.params.collection));
|
||||
});
|
||||
|
||||
|
||||
@@ -21,10 +21,20 @@ const {
|
||||
getRoms: vi.fn(),
|
||||
getPlatform: vi.fn(),
|
||||
push: vi.fn(),
|
||||
routeGuards: [] as ((to: {
|
||||
name: string;
|
||||
params: Record<string, string>;
|
||||
}) => unknown)[],
|
||||
routeGuards: [] as ((
|
||||
to: {
|
||||
name: string;
|
||||
path: string;
|
||||
params: Record<string, string>;
|
||||
query?: Record<string, string>;
|
||||
},
|
||||
from: {
|
||||
name: string;
|
||||
path: string;
|
||||
params: Record<string, string>;
|
||||
query?: Record<string, string>;
|
||||
},
|
||||
) => unknown)[],
|
||||
snackbarError: vi.fn(),
|
||||
snackbarInfo: vi.fn(),
|
||||
}));
|
||||
@@ -149,12 +159,35 @@ function deferRandomRomFailure() {
|
||||
}
|
||||
|
||||
/** Moves the view to another platform the way the router would. */
|
||||
/** A sort / filter / search change: same path, new query. */
|
||||
async function navigateQueryOnly(query: Record<string, string>) {
|
||||
const from = {
|
||||
name: routeState.name,
|
||||
path: routeState.path,
|
||||
params: { ...routeState.params },
|
||||
query: { ...routeState.query },
|
||||
};
|
||||
routeState.query = query;
|
||||
const to = { ...from, query };
|
||||
routeGuards.forEach((guard) => guard(to, from));
|
||||
await flushPromises();
|
||||
}
|
||||
|
||||
async function navigateTo(platformId: number) {
|
||||
// vue-router hands guards both sides, each with the path they compare.
|
||||
const from = {
|
||||
name: routeState.name,
|
||||
path: routeState.path,
|
||||
params: { ...routeState.params },
|
||||
};
|
||||
routeState.params = { platform: String(platformId) };
|
||||
routeState.path = `/platform/${platformId}`;
|
||||
routeGuards.forEach((guard) =>
|
||||
guard({ name: "platform", params: { platform: String(platformId) } }),
|
||||
);
|
||||
const to = {
|
||||
name: "platform",
|
||||
path: routeState.path,
|
||||
params: { platform: String(platformId) },
|
||||
};
|
||||
routeGuards.forEach((guard) => guard(to, from));
|
||||
await flushPromises();
|
||||
}
|
||||
|
||||
@@ -329,3 +362,17 @@ describe("Platform view random rom", () => {
|
||||
expect(push).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
|
||||
// Sorting writes the URL, so it reaches this view's route guard. Reloading
|
||||
// the platform there costs a request per sort click and, on Collection, a
|
||||
// full gallery reset.
|
||||
describe("Platform view query-only navigation", () => {
|
||||
it("does not reload the platform when only the query changes", async () => {
|
||||
await mountView();
|
||||
getPlatform.mockClear();
|
||||
|
||||
await navigateQueryOnly({ orderBy: "fs_size_bytes", orderDir: "desc" });
|
||||
|
||||
expect(getPlatform).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -340,10 +340,12 @@ onMounted(() => {
|
||||
loadForId(Number(route.params.platform));
|
||||
});
|
||||
|
||||
onBeforeRouteUpdate((to) => {
|
||||
onBeforeRouteUpdate((to, from) => {
|
||||
// Shell saves the previous route's scroll automatically via its own
|
||||
// beforeRouteUpdate guard (runs before this one); we just trigger
|
||||
// the new platform's load.
|
||||
// the new platform's load. A query-only change (sort, filters,
|
||||
// search) stays on this platform and must not reload it.
|
||||
if (to.path === from.path) return;
|
||||
if (to.name === "platform") loadForId(Number(to.params.platform));
|
||||
});
|
||||
|
||||
|
||||
135
frontend/src/v2/views/Player/Desktop.test.ts
Normal file
135
frontend/src/v2/views/Player/Desktop.test.ts
Normal file
@@ -0,0 +1,135 @@
|
||||
import { flushPromises, mount, type VueWrapper } from "@vue/test-utils";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { defineComponent } from "vue";
|
||||
import Desktop from "./Desktop.vue";
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
claimDesktop: vi.fn(),
|
||||
releaseSession: vi.fn(),
|
||||
releaseSessionKeepalive: vi.fn(),
|
||||
heartbeatSession: vi.fn(),
|
||||
heartbeatTick: null as (() => Promise<void>) | null,
|
||||
routeLeave: null as (() => Promise<boolean> | boolean) | null,
|
||||
}));
|
||||
|
||||
vi.mock("vue-i18n", () => ({
|
||||
useI18n: () => ({ t: (key: string) => key }),
|
||||
}));
|
||||
|
||||
vi.mock("vue-router", () => ({
|
||||
onBeforeRouteLeave: (guard: () => Promise<boolean>) => {
|
||||
mocks.routeLeave = guard;
|
||||
},
|
||||
useRoute: () => ({ query: { container: "WEBSTATION-DEV" } }),
|
||||
useRouter: () => ({ push: vi.fn() }),
|
||||
}));
|
||||
|
||||
vi.mock("@vueuse/core", async (importOriginal) => ({
|
||||
...(await importOriginal<typeof import("@vueuse/core")>()),
|
||||
// The beat is driven by hand; the pagehide listener stays real.
|
||||
useIntervalFn: (tick: () => Promise<void>) => {
|
||||
mocks.heartbeatTick = tick;
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("@/plugins/router", () => ({
|
||||
ROUTES: { ADMINISTRATION: "administration" },
|
||||
}));
|
||||
|
||||
vi.mock("@/services/api/streaming", () => ({
|
||||
default: {
|
||||
claimDesktop: mocks.claimDesktop,
|
||||
releaseSession: mocks.releaseSession,
|
||||
releaseSessionKeepalive: mocks.releaseSessionKeepalive,
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("@/stores/streaming", () => ({
|
||||
useStreamingStore: () => ({ heartbeatSession: mocks.heartbeatSession }),
|
||||
}));
|
||||
|
||||
vi.mock("@/v2/composables/useConfirm", () => ({
|
||||
useConfirm: () => () => Promise.resolve(true),
|
||||
}));
|
||||
|
||||
vi.mock("@/v2/composables/usePageTitle", () => ({ usePageTitle: vi.fn() }));
|
||||
|
||||
const StreamStageStub = defineComponent({
|
||||
props: { active: { type: Boolean, default: false } },
|
||||
setup(_, { expose }) {
|
||||
expose({
|
||||
leaveFullscreen: () => Promise.resolve(),
|
||||
focusStream: () => {},
|
||||
});
|
||||
return () => null;
|
||||
},
|
||||
});
|
||||
|
||||
// The view listens on window, so a mount left standing would answer the next
|
||||
// test's pagehide too.
|
||||
let mounted: VueWrapper | null = null;
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
mounted?.unmount();
|
||||
mounted = null;
|
||||
});
|
||||
|
||||
async function openDesktop(): Promise<VueWrapper> {
|
||||
mocks.claimDesktop.mockResolvedValue({
|
||||
data: { host: "http://webstation-dev:8080", label: "PS2", platform: "ps2" },
|
||||
});
|
||||
mounted = mount(Desktop, {
|
||||
shallow: true,
|
||||
global: { stubs: { StreamStage: StreamStageStub } },
|
||||
});
|
||||
await flushPromises();
|
||||
return mounted;
|
||||
}
|
||||
|
||||
function streamIsLive(wrapper: VueWrapper): boolean | undefined {
|
||||
return wrapper.findComponent(StreamStageStub).props("active");
|
||||
}
|
||||
|
||||
describe("Desktop heartbeats", () => {
|
||||
it("beats for the container it claimed", async () => {
|
||||
// Unnamed, the beat only reaches the platform's first pool.
|
||||
const wrapper = await openDesktop();
|
||||
mocks.heartbeatSession.mockResolvedValue({ status: "active" });
|
||||
|
||||
await mocks.heartbeatTick?.();
|
||||
|
||||
expect(mocks.heartbeatSession).toHaveBeenCalledWith(
|
||||
"ps2",
|
||||
"WEBSTATION-DEV",
|
||||
);
|
||||
expect(streamIsLive(wrapper)).toBe(true);
|
||||
});
|
||||
|
||||
it("stops the stream when the beat reports the session ended", async () => {
|
||||
const wrapper = await openDesktop();
|
||||
mocks.heartbeatSession.mockResolvedValue({ status: "ended" });
|
||||
|
||||
await mocks.heartbeatTick?.();
|
||||
await flushPromises();
|
||||
|
||||
expect(streamIsLive(wrapper)).toBe(false);
|
||||
});
|
||||
|
||||
it("releases nothing once the beat ended the claim", async () => {
|
||||
// The claim is gone, so an exit must not hand back whoever holds the
|
||||
// container next.
|
||||
await openDesktop();
|
||||
mocks.heartbeatSession.mockResolvedValue({ status: "ended" });
|
||||
|
||||
await mocks.heartbeatTick?.();
|
||||
window.dispatchEvent(new Event("pagehide"));
|
||||
|
||||
expect(await mocks.routeLeave?.()).toBe(true);
|
||||
expect(mocks.releaseSessionKeepalive).not.toHaveBeenCalled();
|
||||
expect(mocks.releaseSession).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -15,6 +15,7 @@ import { useI18n } from "vue-i18n";
|
||||
import { onBeforeRouteLeave, useRoute, useRouter } from "vue-router";
|
||||
import { ROUTES } from "@/plugins/router";
|
||||
import streamingApi from "@/services/api/streaming";
|
||||
import { useStreamingStore } from "@/stores/streaming";
|
||||
import StreamStage from "@/v2/components/Player/StreamStage.vue";
|
||||
import { useConfirm } from "@/v2/composables/useConfirm";
|
||||
import { usePageTitle } from "@/v2/composables/usePageTitle";
|
||||
@@ -23,6 +24,7 @@ const { t } = useI18n();
|
||||
const route = useRoute();
|
||||
const router = useRouter();
|
||||
const confirm = useConfirm();
|
||||
const streamingStore = useStreamingStore();
|
||||
|
||||
const containerKey = computed(() => String(route.query.container ?? ""));
|
||||
|
||||
@@ -95,13 +97,17 @@ async function release(): Promise<boolean> {
|
||||
// stale window, and nothing else here touches the claim.
|
||||
const HEARTBEAT_MS = 30_000;
|
||||
|
||||
useIntervalFn(() => {
|
||||
if (!holdsClaim.value || !platform.value) return;
|
||||
void streamingApi
|
||||
.heartbeatSession(platform.value)
|
||||
.catch((err) =>
|
||||
console.warn("[streaming] Could not heartbeat the desktop session:", err),
|
||||
);
|
||||
useIntervalFn(async () => {
|
||||
if (!holdsClaim.value) return;
|
||||
const status = await streamingStore.heartbeatSession(
|
||||
platform.value,
|
||||
containerKey.value,
|
||||
);
|
||||
// Ended elsewhere: dropping the claim keeps a later exit from releasing
|
||||
// whoever holds the container next.
|
||||
if (status?.status !== "ended") return;
|
||||
holdsClaim.value = false;
|
||||
state.value = "exited";
|
||||
}, HEARTBEAT_MS);
|
||||
|
||||
function backToAdministration(): void {
|
||||
|
||||
30
frontend/test/devCssPrefixing.test.ts
Normal file
30
frontend/test/devCssPrefixing.test.ts
Normal file
@@ -0,0 +1,30 @@
|
||||
import path from "node:path";
|
||||
import { createServer, type ViteDevServer } from "vite";
|
||||
import { afterAll, beforeAll, describe, expect, it } from "vitest";
|
||||
|
||||
// The dev server is the only place this is observable: CI's e2e run serves a
|
||||
// production build, and vitest.config.ts never loads vite.config.js, so a
|
||||
// dropped `css.transformer` would leave every other check green.
|
||||
describe("dev server CSS", () => {
|
||||
let server: ViteDevServer;
|
||||
|
||||
beforeAll(async () => {
|
||||
server = await createServer({
|
||||
configFile: path.resolve(process.cwd(), "vite.config.js"),
|
||||
server: { middlewareMode: true },
|
||||
logLevel: "error",
|
||||
});
|
||||
}, 60_000);
|
||||
|
||||
afterAll(async () => {
|
||||
await server?.close();
|
||||
});
|
||||
|
||||
it("generates vendor prefixes, not only on the build's minify path", async () => {
|
||||
const result = await server.transformRequest(
|
||||
"/test/fixtures/prefix-probe.css",
|
||||
);
|
||||
expect(result?.code).toMatch(/-webkit-backdrop-filter:\s*blur\(1px\)/);
|
||||
expect(result?.code).toMatch(/[^-]backdrop-filter:\s*blur\(1px\)/);
|
||||
});
|
||||
});
|
||||
5
frontend/test/fixtures/prefix-probe.css
vendored
Normal file
5
frontend/test/fixtures/prefix-probe.css
vendored
Normal file
@@ -0,0 +1,5 @@
|
||||
/* Probed by test/devCssPrefixing.test.ts. `backdrop-filter` needs a
|
||||
`-webkit-` prefix below Safari 18.4, and the build targets cover it. */
|
||||
.prefix-probe {
|
||||
backdrop-filter: blur(1px);
|
||||
}
|
||||
12
frontend/tsconfig.node.json
Normal file
12
frontend/tsconfig.node.json
Normal file
@@ -0,0 +1,12 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "esnext",
|
||||
"module": "esnext",
|
||||
"moduleResolution": "bundler",
|
||||
"strict": true,
|
||||
"noEmit": true,
|
||||
"skipLibCheck": true,
|
||||
"types": ["node"]
|
||||
},
|
||||
"include": ["scripts/**/*.ts"]
|
||||
}
|
||||
@@ -1,6 +1,5 @@
|
||||
import tailwindcss from "@tailwindcss/vite";
|
||||
import vue from "@vitejs/plugin-vue";
|
||||
import browserslist from "browserslist";
|
||||
import { URL, fileURLToPath } from "node:url";
|
||||
import { defineConfig, loadEnv } from "vite";
|
||||
import mkcert from "vite-plugin-mkcert";
|
||||
@@ -58,43 +57,6 @@ const VUETIFY_COMPONENTS = [
|
||||
"vuetify/components/VWindow",
|
||||
];
|
||||
|
||||
// Maps browserslist browser ids to the esbuild-style ids that Vite's
|
||||
// `build.cssTarget` understands. Engines not listed here (and_chr, samsung,
|
||||
// kaios, ...) share a rendering engine with one of these or track "latest",
|
||||
// so skipping them does not change the emitted prefixes.
|
||||
const BROWSERSLIST_TO_ESBUILD = {
|
||||
chrome: "chrome",
|
||||
edge: "edge",
|
||||
firefox: "firefox",
|
||||
ios_saf: "ios",
|
||||
opera: "opera",
|
||||
safari: "safari",
|
||||
};
|
||||
|
||||
// Translate the shared `.browserslistrc` baseline into Vite's CSS target
|
||||
// format. Vite 8 minifies CSS with Lightning CSS, which auto-prefixes and
|
||||
// down-levels from the standard property based on browser targets, but on the
|
||||
// minify path it only reads `build.cssTarget` (esbuild-style ids), never
|
||||
// `css.lightningcss.targets`. Deriving it here keeps `.browserslistrc` the
|
||||
// single source of truth. Without targets Lightning CSS drops the generated
|
||||
// `-webkit-backdrop-filter`, breaking every glass/blur surface in Safari.
|
||||
function cssTargetsFromBrowserslist() {
|
||||
const lowest = {};
|
||||
for (const entry of browserslist()) {
|
||||
const [id, range] = entry.split(" ");
|
||||
const name = BROWSERSLIST_TO_ESBUILD[id];
|
||||
if (!name) continue;
|
||||
const version = range.split("-")[0]; // "16.4-16.5" -> "16.4"
|
||||
const asNumber = Number.parseFloat(version);
|
||||
if (lowest[name] === undefined || asNumber < lowest[name].asNumber) {
|
||||
lowest[name] = { asNumber, version };
|
||||
}
|
||||
}
|
||||
return Object.entries(lowest).map(
|
||||
([name, { version }]) => `${name}${version}`,
|
||||
);
|
||||
}
|
||||
|
||||
// https://vitejs.dev/config/
|
||||
export default defineConfig(({ mode }) => {
|
||||
// Load ENV variables from the parent directory and the current directory.
|
||||
@@ -113,16 +75,10 @@ export default defineConfig(({ mode }) => {
|
||||
include: VUETIFY_COMPONENTS,
|
||||
},
|
||||
build: {
|
||||
target: "esnext",
|
||||
// AudioWorklet.addModule is only dependable with a real URL, and Vite
|
||||
// inlines any asset under 4KB as a data: URI, so keep the worklet out.
|
||||
assetsInlineLimit: (filePath) =>
|
||||
filePath.endsWith("pico8AudioWorklet.js") ? false : undefined,
|
||||
// Browser targets for CSS (prefixing + down-leveling) come from the
|
||||
// shared `.browserslistrc`. Never hand-write a `-webkit-` twin next to a
|
||||
// standard property: Lightning CSS collapses the pair to whichever is
|
||||
// declared last, so let it generate the prefixes from these targets.
|
||||
cssTarget: cssTargetsFromBrowserslist(),
|
||||
},
|
||||
plugins: [
|
||||
tailwindcss(),
|
||||
@@ -157,6 +113,11 @@ export default defineConfig(({ mode }) => {
|
||||
hosts: ["localhost", "127.0.0.1", "romm.dev"],
|
||||
}),
|
||||
],
|
||||
// Prefixes dev too, not just the build's minify path. Never hand-write a
|
||||
// `-webkit-` twin: Lightning CSS keeps only the last of the pair.
|
||||
css: {
|
||||
transformer: "lightningcss",
|
||||
},
|
||||
define: {
|
||||
"process.env": {},
|
||||
__VUE_PROD_HYDRATION_MISMATCH_DETAILS__: true,
|
||||
|
||||
Reference in New Issue
Block a user