Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2ef30458a4 | ||
|
|
7bcbcf59dd | ||
|
|
484907439a | ||
|
|
15559ecc90 | ||
|
|
0c56acd806 | ||
|
|
1b7364a2aa | ||
|
|
f384bc6e16 | ||
|
|
76869fabec | ||
|
|
6824c92fa0 |
No files matched your search
@@ -7,7 +7,13 @@ body:
|
||||
attributes:
|
||||
value: |
|
||||
Cảm ơn bạn đã báo lỗi. / Thanks for reporting.
|
||||
Báo lỗi gửi từ nút "Báo lỗi" trên trang sẽ tự điền các mục dưới đây.
|
||||
Nhanh hơn: nút "Báo lỗi" ngay trên trang gửi kèm trang và môi trường đang dùng (báo cáo đó đi
|
||||
vào một repo riêng, không hiện ở đây). / Quicker: the "Report a problem" button on the page
|
||||
itself sends the page and environment along (those reports go to a private repository and
|
||||
do not show up here).
|
||||
Dự án đang ở chế độ bảo trì: form này dành cho lỗi, không dành cho đề xuất tính năng — xem
|
||||
CONTRIBUTING.md. / The project is in maintenance mode: this form is for bugs, not feature
|
||||
requests — see CONTRIBUTING.md.
|
||||
- type: textarea
|
||||
id: description
|
||||
attributes:
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
# Maintenance mode (CONTRIBUTING.md): issues are for bugs, accessibility and language problems.
|
||||
# Questions and ideas go to Discussions; security problems are reported privately.
|
||||
blank_issues_enabled: false
|
||||
contact_links:
|
||||
- name: Question or idea · Câu hỏi hoặc ý tưởng
|
||||
url: https://github.com/poli0981/poli0981-dev/discussions
|
||||
about: >-
|
||||
The project is in maintenance mode and takes no new features — ask or talk ideas over in
|
||||
Discussions. · Dự án đang ở chế độ bảo trì, không nhận tính năng mới — hỏi hoặc trao đổi
|
||||
ý tưởng trong Discussions.
|
||||
- name: Security vulnerability · Lỗ hổng bảo mật
|
||||
url: https://github.com/poli0981/poli0981-dev/security/policy
|
||||
about: Report it privately, never in a public issue. · Báo riêng, không mở issue công khai.
|
||||
@@ -0,0 +1,46 @@
|
||||
name: Lỗi ngôn ngữ / Language problem
|
||||
description: >-
|
||||
Lỗi chính tả gây hiểu nhầm, câu chữ không hợp văn hoá hay giọng địa phương (tiếng Việt hoặc tiếng
|
||||
Anh). / A misleading typo, or wording that does not fit the culture or local voice (Vietnamese or
|
||||
English).
|
||||
title: "[language] "
|
||||
labels: ["language"]
|
||||
body:
|
||||
- type: markdown
|
||||
attributes:
|
||||
value: |
|
||||
Cảm ơn bạn! Mỗi báo cáo một chỗ (hoặc một nhóm chỗ cùng một lỗi). / Thanks! One report per
|
||||
place, or per group of places with the same problem.
|
||||
- type: input
|
||||
id: page
|
||||
attributes:
|
||||
label: Trang / Page
|
||||
description: Đường dẫn trang, hoặc file nếu bạn biết. / The page's URL, or the file if you know it.
|
||||
placeholder: "https://poli0981.dev/blog/…"
|
||||
validations:
|
||||
required: true
|
||||
- type: dropdown
|
||||
id: language
|
||||
attributes:
|
||||
label: Ngôn ngữ / Language
|
||||
options:
|
||||
- Tiếng Việt / Vietnamese
|
||||
- Tiếng Anh / English
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: current
|
||||
attributes:
|
||||
label: Câu hiện tại / Current text
|
||||
description: Chép nguyên văn. / Copy it exactly.
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: suggestion
|
||||
attributes:
|
||||
label: Đề xuất sửa và lý do / Suggested wording and why
|
||||
description: >-
|
||||
Vì sao câu hiện tại gây hiểu nhầm hoặc không hợp? / Why is the current text misleading or a
|
||||
poor fit?
|
||||
validations:
|
||||
required: true
|
||||
@@ -2,6 +2,17 @@
|
||||
|
||||
<!-- One or two sentences. Link the issue if there is one. -->
|
||||
|
||||
## Kind of change
|
||||
|
||||
The project is in maintenance mode ([CONTRIBUTING.md](https://github.com/poli0981/poli0981-dev/blob/main/CONTRIBUTING.md)):
|
||||
new features are not accepted, and a `feat:` pull request is closed automatically.
|
||||
|
||||
- [ ] Dependency update
|
||||
- [ ] Security fix (High/Critical advisory, or a runtime vulnerability)
|
||||
- [ ] Major language, runtime or framework upgrade
|
||||
- [ ] Bug fix — including UI/UX and accessibility
|
||||
- [ ] Language fix — a misleading typo, or wording that does not fit
|
||||
|
||||
## Checks
|
||||
|
||||
- [ ] `npm run format:check`, `npm run lint`, `npm run check`, `npm run typecheck`, `npm test`
|
||||
|
||||
@@ -102,6 +102,11 @@ jobs:
|
||||
- name: Third-party notices
|
||||
run: npm run gen-notices -- --check
|
||||
|
||||
# The same policy over every package in package-lock.json, transitive dependencies and
|
||||
# each platform's binaries included; anything outside it needs a per-package review.
|
||||
- name: Licences (whole dependency tree)
|
||||
run: npm run check-licenses
|
||||
|
||||
# Fail if any changed image under src/assets/ still carries GPS or a camera serial.
|
||||
- name: Check EXIF (changed images)
|
||||
env:
|
||||
@@ -183,7 +188,7 @@ jobs:
|
||||
# quality gate and fails with it, so a red gate is visible on the PR; on main it only
|
||||
# reports (the gate there is a trend, not a merge decision).
|
||||
- name: SonarCloud scan
|
||||
uses: SonarSource/sonarqube-scan-action@e805d875275f728fac1885b413934be6d7c63f65 # v8.4.1
|
||||
uses: SonarSource/sonarqube-scan-action@59202af334b4ba7b5db01b701b8e79f8b3bef0f4 # v8.5.0
|
||||
env:
|
||||
SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }}
|
||||
with:
|
||||
|
||||
@@ -31,7 +31,7 @@ jobs:
|
||||
# show up under Security → Code scanning, and a finding still fails the run.
|
||||
# PR runs skip the upload — Dependabot PRs get a read-only token, so the upload
|
||||
# step would fail there for a reason unrelated to the scan itself.
|
||||
uses: google/osv-scanner-action/.github/workflows/osv-scanner-reusable.yml@b1d267aea5211fa648d9d442fa64b90dbdcbdd36 # v2.7.0
|
||||
uses: google/osv-scanner-action/.github/workflows/osv-scanner-reusable.yml@32d3cd482bdadfb38b186c0ad1b031902d55d932 # v2.7.1
|
||||
permissions:
|
||||
actions: read
|
||||
contents: read
|
||||
|
||||
@@ -0,0 +1,87 @@
|
||||
name: Qodana
|
||||
|
||||
# JetBrains Qodana (Qodana for JS, WebStorm's inspections) over the whole repository: on every
|
||||
# PR, on main and by hand. Settings live in qodana.yaml. Results go to Qodana Cloud (the
|
||||
# project token is the QODANA_TOKEN secret) and, for main, to GitHub code scanning as SARIF.
|
||||
#
|
||||
# Advisory, not required: the main ruleset requires only `build`, and Dependabot and fork PRs
|
||||
# get no secrets, so they skip this job like the SonarCloud one in ci.yml.
|
||||
on:
|
||||
pull_request:
|
||||
push:
|
||||
branches: [main]
|
||||
paths-ignore: ["poli0981.dev-docs/**", "*.md", "LICENSE"]
|
||||
workflow_dispatch:
|
||||
|
||||
# Explicit — a missing block makes GitHub default every scope to `none`.
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
concurrency:
|
||||
group: ${{ github.workflow }}-${{ github.ref }}
|
||||
# Cancel superseded PR runs; let main runs finish.
|
||||
cancel-in-progress: ${{ github.ref != 'refs/heads/main' }}
|
||||
|
||||
jobs:
|
||||
qodana:
|
||||
if: >-
|
||||
github.event_name != 'pull_request' ||
|
||||
(github.event.pull_request.head.repo.full_name == github.repository &&
|
||||
github.actor != 'dependabot[bot]')
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 30
|
||||
permissions:
|
||||
contents: read
|
||||
checks: write # problem annotations on the commit
|
||||
pull-requests: write # the summary comment on PRs
|
||||
security-events: write # SARIF upload (main and manual runs)
|
||||
steps:
|
||||
# Pinned to commit SHAs like every other workflow here; Dependabot keeps them current.
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
# The PR's own head commit, not the merge preview, so Qodana Cloud links to it.
|
||||
ref: ${{ github.event.pull_request.head.sha || github.sha }}
|
||||
fetch-depth: 0
|
||||
submodules: recursive
|
||||
persist-credentials: false
|
||||
|
||||
- uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0
|
||||
with:
|
||||
node-version-file: .nvmrc
|
||||
cache: npm
|
||||
|
||||
# Same rules as ci.yml: no dependency lifecycle script runs in CI, and any lockfile
|
||||
# package with an install script must be on package.json#allowScripts.
|
||||
- name: Install
|
||||
run: npm ci --ignore-scripts
|
||||
|
||||
- name: Install scripts allow-listed
|
||||
run: npm run check-install-scripts
|
||||
|
||||
# Gitignored, generated types the TypeScript service needs to resolve imports of
|
||||
# cloudflare:workers, astro:content and friends.
|
||||
- name: Generate types
|
||||
run: |
|
||||
npm run types
|
||||
npm run types:widgets
|
||||
npm run astro -- sync
|
||||
|
||||
- name: Qodana scan
|
||||
uses: JetBrains/qodana-action@13e3acbbaeb2cbfc37893b98e74594985edf42eb # v2026.2.4
|
||||
env:
|
||||
QODANA_TOKEN: ${{ secrets.QODANA_TOKEN }}
|
||||
QODANA_ENDPOINT: https://qodana.cloud
|
||||
with:
|
||||
# Whole repository every time (it is small), so the quality gate in qodana.yaml
|
||||
# always judges the full picture rather than the files a PR happens to touch.
|
||||
pr-mode: false
|
||||
upload-result: true
|
||||
|
||||
# Like the OSV scan: main and manual runs only, so PR runs don't open code-scanning
|
||||
# alerts for code that may never merge.
|
||||
- name: Upload SARIF to code scanning
|
||||
if: ${{ !cancelled() && github.event_name != 'pull_request' }}
|
||||
uses: github/codeql-action/upload-sarif@33d7b85da1a04171e211befe2c739303b9a4c066 # v4.39.3
|
||||
with:
|
||||
sarif_file: ${{ runner.temp }}/qodana/results/qodana.sarif.json
|
||||
category: qodana
|
||||
@@ -0,0 +1,83 @@
|
||||
name: Triage
|
||||
|
||||
# Maintenance mode (CONTRIBUTING.md): an issue or pull request asking for a new feature is
|
||||
# labelled `enhancement` + `out-of-scope`, answered in both languages and closed. The rules
|
||||
# live in scripts/triage.mjs (unit-tested); this only wires them to GitHub. The owner's own
|
||||
# items, bots, and anything labelled `maintenance-exception` are left alone.
|
||||
#
|
||||
# pull_request_target runs with this repository's token, so it must never run a pull
|
||||
# request's code. Nothing is checked out at all: the script reads scripts/triage.mjs from the
|
||||
# default branch through the API and imports it from memory.
|
||||
on:
|
||||
issues:
|
||||
types: [opened, reopened, edited, labeled]
|
||||
pull_request_target:
|
||||
types: [opened, reopened, edited, labeled]
|
||||
# Dry run on main: classify a title and print the decision, writing nothing.
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
title:
|
||||
description: "Title to classify"
|
||||
required: true
|
||||
kind:
|
||||
description: "issue or pull_request"
|
||||
default: issue
|
||||
|
||||
permissions: {}
|
||||
|
||||
concurrency:
|
||||
group: triage-${{ github.event.issue.number || github.event.pull_request.number || github.run_id }}
|
||||
cancel-in-progress: false
|
||||
|
||||
jobs:
|
||||
triage:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 5
|
||||
permissions:
|
||||
contents: read
|
||||
issues: write
|
||||
pull-requests: write
|
||||
steps:
|
||||
- name: Label and close feature requests
|
||||
uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0
|
||||
with:
|
||||
script: |
|
||||
const { data: file } = await github.rest.repos.getContent({
|
||||
...context.repo,
|
||||
path: "scripts/triage.mjs",
|
||||
ref: context.payload.repository.default_branch,
|
||||
});
|
||||
const source = file.content.replaceAll("\n", "");
|
||||
const { decide, closingComment, LABELS } = await import(
|
||||
`data:text/javascript;base64,${source}`
|
||||
);
|
||||
|
||||
if (context.eventName === "workflow_dispatch") {
|
||||
const { title, kind } = context.payload.inputs;
|
||||
const verdict = decide({ title, labels: [], author: "someone", association: "NONE" });
|
||||
core.notice(`${kind} "${title}": ${verdict.action} (${verdict.reason})`);
|
||||
return;
|
||||
}
|
||||
|
||||
const item = context.payload.issue ?? context.payload.pull_request;
|
||||
const kind = context.payload.pull_request ? "pull_request" : "issue";
|
||||
const verdict = decide({
|
||||
title: item.title,
|
||||
labels: (item.labels ?? []).map((label) => label.name),
|
||||
author: item.user.login,
|
||||
association: item.author_association,
|
||||
sender: context.payload.sender?.login,
|
||||
owner: context.repo.owner,
|
||||
state: item.state,
|
||||
});
|
||||
core.info(`#${item.number}: ${verdict.action} (${verdict.reason})`);
|
||||
if (verdict.action !== "close") return;
|
||||
|
||||
const target = { ...context.repo, issue_number: item.number };
|
||||
await github.rest.issues.addLabels({ ...target, labels: [LABELS.feature, LABELS.closed] });
|
||||
await github.rest.issues.createComment({ ...target, body: closingComment(kind) });
|
||||
if (kind === "pull_request") {
|
||||
await github.rest.pulls.update({ ...context.repo, pull_number: item.number, state: "closed" });
|
||||
} else {
|
||||
await github.rest.issues.update({ ...target, state: "closed", state_reason: "not_planned" });
|
||||
}
|
||||
@@ -67,6 +67,17 @@ has not been audited by a third party, and this is not a claim of conformance.
|
||||
WCAG 2.5.8 through the space around them.
|
||||
- **Reading.** Stories have their own settings: three text sizes and a paper, sepia or dark
|
||||
background.
|
||||
- **Content warnings.** A labelled post, chapter or album opens with a banner that names its
|
||||
labels (horror, violence, politics…) in words, not by colour or icon alone. For the visual
|
||||
labels, images in the page are blurred until "Show images" is ticked. That control is a real
|
||||
checkbox, and the blur is plain CSS, so it works from the keyboard and without JavaScript.
|
||||
Blurring is a courtesy layer, not access control: the images are still downloaded.
|
||||
- **Age check.** An age-rated text is folded inside a `<details>` element. With JavaScript, its
|
||||
summary asks for the reader's age in a native modal `<dialog>`: focus starts on "No", Esc
|
||||
cancels and never counts as "yes", and focus returns to the summary. If the reader says no,
|
||||
focus moves to a line that explains why and offers to choose again. Nothing pops up on its own.
|
||||
Without JavaScript the summary opens the text. The answer stays in the browser
|
||||
(`localStorage`); see the privacy policy.
|
||||
|
||||
## Tested with
|
||||
|
||||
|
||||
+76
-1
@@ -7,6 +7,80 @@ and are not listed here.
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
## [2.3.0] — 2026-11-21
|
||||
|
||||
The last feature release: from here on the project is in **maintenance mode**
|
||||
([`CONTRIBUTING.md`](CONTRIBUTING.md)).
|
||||
|
||||
### Added
|
||||
|
||||
- **Content labels, an age check and blurred images.** Posts, chapters and albums — and single
|
||||
gallery photos — can carry labels from a fixed list (horror, blood, jump scares, violence,
|
||||
self-harm, death, politics, religion, strong language, flashing lights, spoilers) and an age
|
||||
rating (13+, 16+, 18+).
|
||||
- A banner names the labels in the page's language.
|
||||
- For the visual labels, images are blurred until "Show images" is ticked. That is a real
|
||||
checkbox, and the blur is plain CSS, so it works from the keyboard and without JavaScript.
|
||||
- An age-rated text stays folded until the reader confirms their age in a native dialog. It
|
||||
never pops up on its own, and Esc never means "yes". The answer stays in the browser
|
||||
(`localStorage`: an age threshold, never a birth date).
|
||||
- Cards, the photo viewer, RSS descriptions and OG cards carry the warning too. The privacy
|
||||
policy (§6) lists the new local-storage item
|
||||
([#138](https://github.com/poli0981/poli0981-dev/pull/138)).
|
||||
- **The admin publishes on its own.** Every save or delete starts the publish workflow; bursts
|
||||
coalesce. The admin now follows a change until it is actually live: the build records the
|
||||
content commit it was made from (`version.content` in `/api/health`), and the publish bar
|
||||
shows building / waiting for review / merged and deploying / live / failed. The editor and
|
||||
gallery manager set labels, age ratings and per-photo labels
|
||||
([#137](https://github.com/poli0981/poli0981-dev/pull/137)).
|
||||
- **Qodana** (JetBrains, Qodana for JS) on every pull request and on `main`, with a zero-problem
|
||||
quality gate. Results go to Qodana Cloud and, for `main`, to code scanning
|
||||
([#135](https://github.com/poli0981/poli0981-dev/pull/135)).
|
||||
- **Licence check over the whole dependency tree**: every package in `package-lock.json`, with
|
||||
reviews per package instead of per licence. A package with no licence fails CI (#135).
|
||||
- Maintenance-mode governance:
|
||||
- `CONTRIBUTING.md`, in Vietnamese and English;
|
||||
- a language-problem issue form, with blank issues off and questions sent to Discussions;
|
||||
- a "kind of change" checklist in the pull request template;
|
||||
- a triage workflow that labels and closes new-feature requests.
|
||||
|
||||
### Changed
|
||||
|
||||
- Admin commits in the public content repository no longer carry the admin's email address; the
|
||||
private audit log keeps who did what (#137).
|
||||
- The admin's checks now match the content schema, so a save cannot queue a failing build:
|
||||
chapters are positive whole numbers, `cover` and `coverMedia` exclude each other, and an album
|
||||
must be a slug that already has photos (#137).
|
||||
- Deleting an image is refused while the **live** site's content still uses it, not only while
|
||||
`main` does (#137).
|
||||
- The post page uses the cover's alt text when one is set (#138); the editor has a field for it,
|
||||
and the media picker takes alt text for uploads (#137).
|
||||
- One-shot stories (`stories/<slug>.md`) can be created and edited in the admin (#137).
|
||||
- Dependencies, keeping the three-day cooldown: astro 7.4.12, @astrojs/cloudflare 14.4.8,
|
||||
@astrojs/svelte 9.1.6, jose 6.2.17, marked 18.2.1, wrangler 4.164.0, eslint 10.15.0,
|
||||
typescript-eslint 8.73.0, prettier 3.10.1, prettier-plugin-svelte 4.2.0 (14 Svelte files
|
||||
reformatted; the rendered markup is unchanged), playwright 1.65.1, knip 6.45.1
|
||||
([#134](https://github.com/poli0981/poli0981-dev/pull/134),
|
||||
[#136](https://github.com/poli0981/poli0981-dev/pull/136)). The SonarQube scan action is at 8.5.0
|
||||
and the OSV-Scanner workflow at 2.7.1 ([#127](https://github.com/poli0981/poli0981-dev/pull/127),
|
||||
[#128](https://github.com/poli0981/poli0981-dev/pull/128)).
|
||||
|
||||
### Fixed
|
||||
|
||||
- In the editor, Ctrl/⌘+S while typing in a tags field saved the previous tags (#137).
|
||||
- Qodana's first findings (#135):
|
||||
- the smoke test's forged Access token is built at run time instead of sitting in the source
|
||||
as a token literal;
|
||||
- redundant escapes in a Markdown-to-text regex;
|
||||
- a single-character alternation in the CSP check;
|
||||
- a heading table keyed by a mixed-script property name.
|
||||
|
||||
### Security
|
||||
|
||||
- deepmerge GHSA-gcqx-w48m-w2h4 (alias CVE-2026-93753) was withdrawn on 2026-11-16, and its
|
||||
Dependabot alert is closed. The OSV-Scanner ignore entries for it are gone (#134).
|
||||
- Node.js 26.13.1 (security release of 2026-11-10) is what CI and the build use (`.nvmrc` = 26).
|
||||
|
||||
## [2.2.0] — 2026-11-10
|
||||
|
||||
### Added
|
||||
@@ -218,7 +292,8 @@ The public launch is tagged `v1-launch`; the 1.x changes after it were not tagge
|
||||
- **2026-10** — Custom Worker entry in front of every page; Workers Rate Limiting; Web Analytics;
|
||||
topic email aliases; R2 media; the Turnstile gate; the admin at `admin.poli0981.dev`.
|
||||
|
||||
[Unreleased]: https://github.com/poli0981/poli0981-dev/compare/v2.2.0...HEAD
|
||||
[Unreleased]: https://github.com/poli0981/poli0981-dev/compare/v2.3.0...HEAD
|
||||
[2.3.0]: https://github.com/poli0981/poli0981-dev/compare/v2.2.0...v2.3.0
|
||||
[2.2.0]: https://github.com/poli0981/poli0981-dev/compare/v2.1.2...v2.2.0
|
||||
[2.1.2]: https://github.com/poli0981/poli0981-dev/compare/v2.1.1...v2.1.2
|
||||
[2.1.1]: https://github.com/poli0981/poli0981-dev/compare/v2.1.0...v2.1.1
|
||||
|
||||
@@ -0,0 +1,84 @@
|
||||
# Contributing
|
||||
|
||||
> **Tiếng Việt ở bên dưới.** / Vietnamese below.
|
||||
|
||||
## Maintenance mode
|
||||
|
||||
Since **v2.3.0 (November 2026)** this project is in **maintenance mode**. The site is complete; it
|
||||
is kept healthy, but **no new features are being added**. Only these changes are accepted:
|
||||
|
||||
1. **Dependency updates** on the regular schedule (Dependabot weekly, a combined update about
|
||||
once a month, always after a 3-day cooldown).
|
||||
2. **Security**: a dependency advisory of **High or Critical** severity, or a serious
|
||||
vulnerability in the runtime itself (Node.js, the Workers runtime), fixed as soon as
|
||||
possible — together with a feature only when the owner judges it truly necessary.
|
||||
3. **Major language, runtime or framework upgrades**: Node.js 26 → 28, TypeScript 7.1 replacing
|
||||
the TypeScript 6 API alias, the next Astro or Svelte major, and the like.
|
||||
4. **Bugs**: anything that does not work as intended, including **UI/UX** glitches and
|
||||
**accessibility** barriers ([ACCESSIBILITY.md](ACCESSIBILITY.md)).
|
||||
5. **Language**: spelling mistakes that could mislead, and wording that does not fit the culture
|
||||
or the local voice, in Vietnamese or English.
|
||||
|
||||
**Not accepted: new features.** An issue or pull request asking for one is labelled
|
||||
`enhancement` + `out-of-scope` and closed automatically
|
||||
([`.github/workflows/triage.yml`](.github/workflows/triage.yml)). If it was closed by mistake,
|
||||
reply on it and the owner will take another look; an exception the owner accepts carries the
|
||||
`maintenance-exception` label. Ideas are still welcome in
|
||||
[Discussions](https://github.com/poli0981/poli0981-dev/discussions), without any promise.
|
||||
|
||||
### How to report
|
||||
|
||||
- **A problem on the website**: the "Báo lỗi / Report a problem" button on the page itself, or the
|
||||
bug report form under [Issues](https://github.com/poli0981/poli0981-dev/issues/new/choose).
|
||||
- **An accessibility barrier**: the accessibility form under Issues.
|
||||
- **A spelling or wording problem**: the language form under Issues.
|
||||
- **A security vulnerability**: privately — see [SECURITY.md](SECURITY.md). Never in a public
|
||||
issue.
|
||||
|
||||
### Pull requests
|
||||
|
||||
Welcome for the five kinds of change above. Keep one change per pull request, follow the checks
|
||||
in the [pull request template](.github/pull_request_template.md), and run the commands listed in
|
||||
[README.md](README.md#commands) before opening it. CI must be green — `build` is required, and
|
||||
the SonarCloud and Qodana gates have to pass too. Commits on `main` are signed.
|
||||
|
||||
---
|
||||
|
||||
## Chế độ bảo trì
|
||||
|
||||
Từ **v2.3.0 (tháng 11/2026)**, dự án ở **chế độ bảo trì**. Trang web đã hoàn chỉnh; repo vẫn được giữ
|
||||
cho khoẻ mạnh nhưng **không thêm tính năng mới**. Chỉ nhận những thay đổi sau:
|
||||
|
||||
1. **Cập nhật dependency** định kỳ (Dependabot hằng tuần, gộp một lần khoảng mỗi tháng, luôn sau
|
||||
3 ngày "nguội").
|
||||
2. **Bảo mật**: lỗ hổng trong dependency ở mức **High hoặc Critical**, hoặc lỗ hổng nghiêm trọng của
|
||||
chính runtime (Node.js, Workers runtime) — sửa sớm nhất có thể; kèm tính năng chỉ khi chủ repo
|
||||
đánh giá là thật sự cần thiết.
|
||||
3. **Nâng cấp lớn ngôn ngữ, runtime, framework**: Node.js 26 → 28, TypeScript 7.1 thay alias API
|
||||
TypeScript 6, bản major tiếp theo của Astro hay Svelte…
|
||||
4. **Lỗi**: mọi thứ không chạy đúng ý định, gồm cả lỗi **UI/UX** và rào cản **accessibility**
|
||||
([ACCESSIBILITY.md](ACCESSIBILITY.md)).
|
||||
5. **Ngôn ngữ**: lỗi chính tả có thể gây hiểu nhầm, câu chữ không hợp văn hoá hay giọng địa phương,
|
||||
ở cả tiếng Việt lẫn tiếng Anh.
|
||||
|
||||
**Không nhận: tính năng mới.** Issue hoặc pull request đề xuất tính năng sẽ được gắn nhãn
|
||||
`enhancement` + `out-of-scope` và tự động đóng
|
||||
([`.github/workflows/triage.yml`](.github/workflows/triage.yml)). Nếu bị đóng nhầm, hãy trả lời ngay
|
||||
trong đó — chủ repo sẽ xem lại; ngoại lệ được chấp nhận mang nhãn `maintenance-exception`. Ý tưởng
|
||||
vẫn có thể trao đổi trong [Discussions](https://github.com/poli0981/poli0981-dev/discussions), không
|
||||
cam kết sẽ làm.
|
||||
|
||||
### Báo lỗi ở đâu
|
||||
|
||||
- **Lỗi trên trang web**: nút "Báo lỗi" ngay trên trang, hoặc form báo lỗi trong
|
||||
[Issues](https://github.com/poli0981/poli0981-dev/issues/new/choose).
|
||||
- **Rào cản accessibility**: form accessibility trong Issues.
|
||||
- **Lỗi chính tả, câu chữ**: form ngôn ngữ trong Issues.
|
||||
- **Lỗ hổng bảo mật**: báo riêng — xem [SECURITY.md](SECURITY.md). Không mở issue công khai.
|
||||
|
||||
### Pull request
|
||||
|
||||
Hoan nghênh cho năm loại thay đổi ở trên. Mỗi pull request một thay đổi, làm theo các mục kiểm tra
|
||||
trong [mẫu pull request](.github/pull_request_template.md), chạy các lệnh trong
|
||||
[README.md](README.md#commands) trước khi mở. CI phải xanh — `build` là bắt buộc, cổng SonarCloud
|
||||
và Qodana cũng phải qua. Commit trên `main` có chữ ký.
|
||||
@@ -2,7 +2,9 @@
|
||||
|
||||
[](https://github.com/poli0981/poli0981-dev/actions/workflows/ci.yml)
|
||||
[](https://sonarcloud.io/summary/new_code?id=poli0981_poli0981-dev)
|
||||
[](https://github.com/poli0981/poli0981-dev/actions/workflows/qodana.yml)
|
||||
[](LICENSE)
|
||||
[](CONTRIBUTING.md#maintenance-mode)
|
||||
|
||||
The personal site of Kokone (SkullMute) — dev portfolio, blog, short fiction and a hub for
|
||||
the SkullMute channel, in Vietnamese and English. Live at **[poli0981.dev](https://poli0981.dev)**.
|
||||
@@ -10,6 +12,17 @@ the SkullMute channel, in Vietnamese and English. Live at **[poli0981.dev](https
|
||||
> Trang cá nhân của Kokone (SkullMute): dự án, blog, truyện ngắn và kênh SkullMute — song ngữ
|
||||
> Việt/Anh. Tài liệu thiết kế đầy đủ (tiếng Việt) nằm trong [`poli0981.dev-docs/`](poli0981.dev-docs/00_INDEX.md).
|
||||
|
||||
## Status
|
||||
|
||||
**Maintenance mode since v2.3.0 (November 2026).** The site is complete. It still gets
|
||||
dependency updates, security fixes (High/Critical advisories, runtime vulnerabilities), major
|
||||
runtime and framework upgrades, bug fixes (UI/UX and accessibility included) and language fixes,
|
||||
but no new features. Issues and pull requests asking for one are closed automatically. Details:
|
||||
[`CONTRIBUTING.md`](CONTRIBUTING.md).
|
||||
|
||||
> **Trạng thái:** chế độ bảo trì từ v2.3.0 — chỉ cập nhật dependency, vá bảo mật, nâng cấp
|
||||
> runtime/framework, sửa lỗi (cả UI/UX, accessibility) và sửa lỗi ngôn ngữ; không thêm tính năng mới.
|
||||
|
||||
## Stack
|
||||
|
||||
| Layer | Choice |
|
||||
@@ -20,7 +33,7 @@ the SkullMute channel, in Vietnamese and English. Live at **[poli0981.dev](https
|
||||
| Content | Markdown/MDX in [`poli0981/content`](https://github.com/poli0981/content) (git submodule `src/content`) |
|
||||
| Search | Pagefind (built after `astro build`) |
|
||||
| Tooling | Node 26 · TypeScript 7 (`tsc`) next to TypeScript 6 (astro check, typescript-eslint) · `node:test` · ESLint · Prettier · knip |
|
||||
| Quality | SonarCloud quality gate · CodeQL · OSV-Scanner · Snyk · Dependabot (3-day cooldown) · axe-core accessibility gate |
|
||||
| Quality | SonarCloud quality gate · Qodana · CodeQL · OSV-Scanner · Snyk · Dependabot (3-day cooldown) · axe-core gate · licence check |
|
||||
|
||||
## How it fits together
|
||||
|
||||
@@ -83,9 +96,11 @@ pipeline: [`08_CI_CD.md`](poli0981.dev-docs/08_CI_CD.md); changes per release: [
|
||||
## Admin
|
||||
|
||||
`admin.poli0981.dev` is the owner's editor: write and edit posts (commits to the content repo),
|
||||
upload images (transformed once into AVIF/WebP and stored in R2), manage gallery albums,
|
||||
publish (opens a submodule-bump PR that CI must pass), review an audit log and manage the IP
|
||||
denylist. It sits behind Cloudflare Access, and the Worker independently verifies the Access
|
||||
upload images (transformed once into AVIF/WebP and stored in R2), manage gallery albums, set
|
||||
content labels and age ratings, review an audit log and manage the IP denylist. Every save or
|
||||
delete publishes itself: it starts a submodule-bump PR that CI must pass, which then merges and
|
||||
deploys, and the admin follows it until the change is live (`/api/health` reports the content
|
||||
commit too). It sits behind Cloudflare Access, and the Worker independently verifies the Access
|
||||
JWT (≤ 24 hours old) and an email allowlist on every request.
|
||||
|
||||
## Security
|
||||
|
||||
+8
-1
@@ -36,13 +36,20 @@ Only the currently deployed site (`main` → Cloudflare Workers) is supported. R
|
||||
tagged (`v2.0.0` onwards, see [`CHANGELOG.md`](CHANGELOG.md)) for reference only — there are
|
||||
no backports. `https://poli0981.dev/api/health` reports the version and commit that is live.
|
||||
|
||||
The project is in maintenance mode ([`CONTRIBUTING.md`](CONTRIBUTING.md)), and security work
|
||||
is the first thing it keeps doing: a dependency advisory of High or Critical severity, or a
|
||||
serious vulnerability in Node.js or the Workers runtime, is fixed and deployed as soon as
|
||||
possible, outside the regular update schedule.
|
||||
|
||||
## What the site actually handles
|
||||
|
||||
Useful context when judging impact — the site is static and stores almost nothing:
|
||||
|
||||
- No visitor accounts or logins, no ad or analytics trackers. The only cookie is
|
||||
`__Host-gate`, a signed 48-hour pass set after the Turnstile bot check (expiry, random
|
||||
value and HMAC — no identifier; see `src/lib/gate/`).
|
||||
value and HMAC — no identifier; see `src/lib/gate/`). Preferences, and the answer to the age
|
||||
check on age-rated pages (an age threshold, never a birth date), stay in the browser's
|
||||
`localStorage` and are never sent to the site.
|
||||
- User-submitted input: the bug-report form (Turnstile-gated, schema-validated, size-capped,
|
||||
forwarded to an issue in a **private** repository and a Discord webhook) and the bot-check
|
||||
token exchange at `/api/gate`. Both are rate-limited per client.
|
||||
|
||||
@@ -74,9 +74,11 @@ inventory is `package-lock.json`; platform binaries are covered in prose below.
|
||||
|
||||
## Licenses outside the standard allowlist
|
||||
|
||||
**MPL-2.0** — 3 package(s): `@axe-core/playwright`, `@resvg/resvg-js`, `satori`
|
||||
**MPL-2.0** — 3 package(s):
|
||||
|
||||
> Reviewed: File-level copyleft. satori and @resvg/resvg-js are used unmodified as build-time tools and never shipped to the browser, so no source-disclosure obligation is triggered.
|
||||
- `@axe-core/playwright` — reviewed: File-level copyleft. Runs only in the accessibility tests (tests/a11y); never shipped.
|
||||
- `@resvg/resvg-js` — reviewed: File-level copyleft. Used unmodified at build time to draw the OG cards (scripts/gen-og.mjs); never shipped to the browser or the Worker.
|
||||
- `satori` — reviewed: File-level copyleft. Used unmodified at build time to draw the OG cards (scripts/gen-og.mjs); never shipped to the browser or the Worker.
|
||||
|
||||
<!-- END GENERATED -->
|
||||
|
||||
@@ -108,8 +110,8 @@ Not packages — listed for transparency:
|
||||
- **Discord** — a webhook receiving bug-report notifications.
|
||||
- **YouTube, Steam and GitHub public APIs** — read by the widgets cron worker; visitors' browsers
|
||||
never call them (images are mirrored and served from the site).
|
||||
- **SonarCloud, CodeQL, OSV-Scanner, Snyk** — code and dependency analysis in CI; nothing they do
|
||||
reaches the running site.
|
||||
- **SonarCloud, Qodana (JetBrains), CodeQL, OSV-Scanner, Snyk** — code and dependency analysis in
|
||||
CI; nothing they do reaches the running site.
|
||||
|
||||
## Fonts
|
||||
|
||||
|
||||
+22
-1
@@ -5,6 +5,7 @@ import svelte from "@astrojs/svelte";
|
||||
import mdx from "@astrojs/mdx";
|
||||
import sitemap from "@astrojs/sitemap";
|
||||
import tailwindcss from "@tailwindcss/vite";
|
||||
import { execFileSync } from "node:child_process";
|
||||
import { existsSync } from "node:fs";
|
||||
import { rename, rmdir } from "node:fs/promises";
|
||||
import { DEFAULT_LOCALE, LOCALES } from "./src/i18n/routing.ts";
|
||||
@@ -71,6 +72,23 @@ const CF_BEACON_DEFAULT =
|
||||
// "what is live?" maps straight to a commit.
|
||||
const BUILD_COMMIT = process.env.WORKERS_CI_COMMIT_SHA ?? process.env.GITHUB_SHA ?? null;
|
||||
|
||||
// The poli0981/content commit this build's src/content points at: the gitlink recorded in
|
||||
// HEAD, so it is right even when the submodule checkout itself is missing or dirty. The admin
|
||||
// compares it with the content repo's head to tell "merged" from "live"; /api/health reports
|
||||
// it next to the site commit. null when git or the gitlink isn't there.
|
||||
function contentCommit() {
|
||||
try {
|
||||
const sha = execFileSync("git", ["rev-parse", "HEAD:src/content"], {
|
||||
encoding: "utf8",
|
||||
stdio: ["ignore", "pipe", "ignore"],
|
||||
}).trim();
|
||||
return /^[0-9a-f]{40}$/.test(sha) ? sha : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
const CONTENT_COMMIT = contentCommit();
|
||||
|
||||
// https://astro.build/config
|
||||
export default defineConfig({
|
||||
site: "https://poli0981.dev",
|
||||
@@ -166,7 +184,10 @@ export default defineConfig({
|
||||
// Tailwind v4 is wired through the Vite plugin (NOT the legacy @astrojs/tailwind).
|
||||
vite: {
|
||||
plugins: [tailwindcss()],
|
||||
define: { __BUILD_COMMIT__: JSON.stringify(BUILD_COMMIT) },
|
||||
define: {
|
||||
__BUILD_COMMIT__: JSON.stringify(BUILD_COMMIT),
|
||||
__CONTENT_COMMIT__: JSON.stringify(CONTENT_COMMIT),
|
||||
},
|
||||
},
|
||||
|
||||
// Self-hosted fonts via the built-in Fonts API. Subsets include `vietnamese`.
|
||||
|
||||
Vendored
+4
@@ -12,6 +12,10 @@ draft: true
|
||||
translationKey add the SAME value to the vi and en file to pair them for hreflang
|
||||
updated optional, YYYY-MM-DD — adds dateModified to the BlogPosting schema
|
||||
cover optional, path relative to this file; Astro validates it exists
|
||||
contentWarning optional labels from src/lib/content-labels.ts, e.g. [politics] — a banner;
|
||||
the visual ones (horror, blood, violence…) also blur the post's images
|
||||
ageRating optional "13+" | "16+" | "18+" — the text stays folded until the reader
|
||||
confirms their age
|
||||
draft: true hidden in production, visible in `npm run dev`. Flip when ready.
|
||||
-->
|
||||
|
||||
|
||||
Vendored
+6
-1
@@ -7,6 +7,7 @@ series: "{{SERIES}}"
|
||||
chapter: 1
|
||||
status: ongoing
|
||||
contentWarning: []
|
||||
# ageRating: "16+"
|
||||
tags: []
|
||||
draft: true
|
||||
---
|
||||
@@ -16,7 +17,11 @@ draft: true
|
||||
series in one folder, e.g. stories/dem-khong-tieng/chuong-01.md
|
||||
chapter integer, consecutive; drives prev/next links and ordering
|
||||
status ongoing | complete | dropped
|
||||
contentWarning e.g. [horror, violence] — renders a warning gate before the text
|
||||
contentWarning labels from src/lib/content-labels.ts, e.g. [horror, violence]: a warning
|
||||
banner; horror, blood, jumpscare, violence, self-harm and death also
|
||||
blur the images
|
||||
ageRating "13+" | "16+" | "18+" (optional): the text stays folded until the
|
||||
reader confirms their age (remembered in their browser only)
|
||||
-->
|
||||
|
||||
Chương bắt đầu ở đây.
|
||||
+10
-17
@@ -2,20 +2,13 @@
|
||||
# (.github/workflows/osv-scanner.yml scans package-lock.json at the repo root).
|
||||
#
|
||||
# Every entry needs a reason and an ignoreUntil date, so an ignore expires on
|
||||
# its own and the weekly scan turns red again for another look.
|
||||
|
||||
# deepmerge <= 4.3.1: mergeObject() can return objects with a poisoned prototype.
|
||||
# No patched release exists (4.3.1 is the latest, from 2023). The only path to it
|
||||
# is @astrojs/svelte → @sveltejs/vite-plugin-svelte, which merges this repo's own
|
||||
# Svelte/Vite config at build time. Nothing from a visitor or the network reaches
|
||||
# it, and it is not part of the Worker bundle. Recheck when vite-plugin-svelte
|
||||
# drops deepmerge or a fixed version ships.
|
||||
[[IgnoredVulns]]
|
||||
id = "GHSA-gcqx-w48m-w2h4"
|
||||
ignoreUntil = 2027-02-09
|
||||
reason = "Build-time only (vite-plugin-svelte merges our own config); no patched deepmerge release exists."
|
||||
|
||||
[[IgnoredVulns]]
|
||||
id = "CVE-2026-93753"
|
||||
ignoreUntil = 2027-02-09
|
||||
reason = "Alias of GHSA-gcqx-w48m-w2h4 (deepmerge); same reasoning."
|
||||
# its own and the weekly scan turns red again for another look:
|
||||
#
|
||||
# [[IgnoredVulns]]
|
||||
# id = "GHSA-xxxx-xxxx-xxxx"
|
||||
# ignoreUntil = 2027-01-31
|
||||
# reason = "Why it cannot reach a visitor, and what would make it go away."
|
||||
#
|
||||
# No entries today. The last one, deepmerge GHSA-gcqx-w48m-w2h4 (alias
|
||||
# CVE-2026-93753), was removed on 2026-11-21: the advisory was withdrawn on
|
||||
# 2026-11-16 and OSV no longer reports deepmerge 4.3.1.
|
||||
Generated
+790
-953
File diff suppressed because it is too large.
Load diff
+16
-15
@@ -24,6 +24,7 @@
|
||||
"test:coverage": "node --import ./tests/support/register.mjs --test --experimental-test-coverage --test-coverage-include=\"src/**/*.ts\" --test-coverage-include=\"workers/widgets/src/**/*.ts\" --test-coverage-exclude=\"**/*.d.ts\" --test-coverage-exclude=\"src/lib/easter.ts\" --test-coverage-exclude=\"src/content.config.ts\" --test-coverage-lines=80 --test-reporter=spec --test-reporter-destination=stdout --test-reporter=lcov --test-reporter-destination=coverage/lcov.info \"tests/**/*.test.ts\"",
|
||||
"test:a11y": "node --test --test-concurrency=1 \"tests/a11y/*.spec.ts\"",
|
||||
"gen-notices": "node scripts/gen-notices.mjs",
|
||||
"check-licenses": "node scripts/check-licenses.mjs",
|
||||
"new:post": "node scripts/new-post.mjs",
|
||||
"gen-og": "node scripts/gen-og.mjs",
|
||||
"preview": "astro preview",
|
||||
@@ -50,15 +51,15 @@
|
||||
}
|
||||
},
|
||||
"dependencies": {
|
||||
"@astrojs/cloudflare": "^14.4.6",
|
||||
"@astrojs/mdx": "^8.1.3",
|
||||
"@astrojs/cloudflare": "^14.4.8",
|
||||
"@astrojs/mdx": "^8.1.6",
|
||||
"@astrojs/rss": "^4.0.19",
|
||||
"@astrojs/sitemap": "^3.7.4",
|
||||
"@astrojs/svelte": "^9.1.2",
|
||||
"@astrojs/sitemap": "^3.7.5",
|
||||
"@astrojs/svelte": "^9.1.6",
|
||||
"@tailwindcss/vite": "^4.3.5",
|
||||
"astro": "^7.4.7",
|
||||
"jose": "^6.2.15",
|
||||
"marked": "^18.1.3",
|
||||
"astro": "^7.4.12",
|
||||
"jose": "^6.2.17",
|
||||
"marked": "^18.2.1",
|
||||
"sharp": "^0.35.5",
|
||||
"svelte": "^5.57.3",
|
||||
"tailwindcss": "^4.3.5",
|
||||
@@ -71,22 +72,22 @@
|
||||
"@resvg/resvg-js": "^2.6.2",
|
||||
"@types/node": "^26.6.6",
|
||||
"@typescript/native": "npm:typescript@^7.0.2",
|
||||
"eslint": "^10.14.0",
|
||||
"eslint": "^10.15.0",
|
||||
"eslint-plugin-astro": "^3.2.1",
|
||||
"eslint-plugin-svelte": "^3.24.0",
|
||||
"eslint-plugin-svelte": "^3.24.1",
|
||||
"exifr": "^7.1.3",
|
||||
"knip": "^6.44.1",
|
||||
"knip": "^6.45.1",
|
||||
"lefthook": "^2.2.2",
|
||||
"pagefind": "^1.6.0",
|
||||
"playwright": "^1.65.0",
|
||||
"prettier": "^3.9.10",
|
||||
"playwright": "^1.65.1",
|
||||
"prettier": "^3.10.1",
|
||||
"prettier-plugin-astro": "^0.14.1",
|
||||
"prettier-plugin-svelte": "^4.1.1",
|
||||
"prettier-plugin-svelte": "^4.2.0",
|
||||
"prettier-plugin-tailwindcss": "^0.8.1",
|
||||
"satori": "^0.63.2",
|
||||
"satori-html": "^0.3.2",
|
||||
"typescript": "~6.0.3",
|
||||
"typescript-eslint": "~8.72.1",
|
||||
"wrangler": "^4.158.0"
|
||||
"typescript-eslint": "~8.73.0",
|
||||
"wrangler": "^4.164.0"
|
||||
}
|
||||
}
|
||||
@@ -55,6 +55,10 @@
|
||||
| D18 | Báo lỗi (10/2026) | Issue tạo ở repo **private** `poli0981/site-reports` (repo site đã public) — `10` §4 |
|
||||
| D19 | Phát hành | Tag `vX.Y.Z` có ký GPG + GitHub Release + `CHANGELOG.md`; deploy vẫn là "merge `main`" (`08` §8) |
|
||||
| D20 | Trợ năng (11/2026, v2.2.0) | Mục tiêu **WCAG 2.2 AA** — kim chỉ nam, không tự nhận đã được kiểm định. Tuyên bố cho khách ở `/legal/accessibility` (song ngữ, repo content); `ACCESSIBILITY.md` ở root là bản của repo kèm ghi chú cho người sửa code (trang site thắng nếu lệch). Rào cản báo về `accessibility@` hoặc nút "Báo lỗi". Cổng tự động: `npm run test:a11y` (axe-core + bàn phím + reflow + forced-colors, Playwright lái Chrome có sẵn) chạy trong check bắt buộc `build` (`08` §0, checklist ở `03` §8) — ngoại lệ có chủ đích của D17 "không thêm deps cho test" |
|
||||
| D21 | Chế độ bảo trì (11/2026, v2.3.0) | Không thêm tính năng mới. Chỉ nhận: deps định kỳ · vá bảo mật (High/Critical, lỗ hổng runtime) · nâng cấp lớn ngôn ngữ/runtime/framework · sửa lỗi (UI/UX, a11y) · sửa lỗi ngôn ngữ. Bot `triage.yml` gắn `enhancement` + `out-of-scope` và đóng đề xuất tính năng; ngoại lệ = nhãn `maintenance-exception` (`CONTRIBUTING.md`, `17` §0) |
|
||||
| D22 | Nhãn nội dung & tuổi (11/2026) | `contentWarning` từ danh sách cố định 11 nhãn (`src/lib/content-labels.ts`) cho blog/truyện/album/từng ảnh + `ageRating` 13+/16+/18+. Banner; ảnh mờ bằng CSS (`:has()`, chạy khi tắt JS); hỏi tuổi bằng `<dialog>` gốc, không tự bật, câu trả lời chỉ ở localStorage `ageGate` (mốc tuổi, không ngày sinh) — Privacy §6 (`04` §2) |
|
||||
| D23 | Xuất bản tự động (11/2026) | Mỗi lần lưu/xoá trong admin tự dispatch `content-bump.yml`; build ghi `__CONTENT_COMMIT__` ⇒ `/api/health` có `version.content`, admin phân biệt "đã merge" với "đã lên web". Điều kiện: Workers Builds deploy `main` (`07` §9) |
|
||||
| D24 | Chất lượng (11/2026) | Thêm **Qodana** (Ultimate, Qodana for JS, ngưỡng 0) cạnh SonarCloud. License: kiểm toàn bộ `package-lock.json`, ngoại lệ theo **gói** có lý do (`scripts/license-policy.mjs`) — license audit của Qodana cần Ultimate Plus nên không dùng (`08` §0) |
|
||||
|
||||
## Cách dùng suite
|
||||
|
||||
|
||||
@@ -69,9 +69,9 @@ poli0981-dev/
|
||||
│ └── styles/ # global.css (token), prose.css, admin.css
|
||||
├── tests/ # node:test + support/ (stub astro:*, fake KV/R2/GitHub…) · a11y/ (*.spec.ts: axe-core + bàn phím qua Playwright)
|
||||
├── workers/widgets/ # worker cron riêng (wrangler.jsonc riêng)
|
||||
├── .github/ # ci.yml, content-bump.yml, lighthouse.yml, osv-scanner.yml, dependabot.yml, ISSUE_TEMPLATE/ (bug_report, accessibility), pull_request_template.md
|
||||
├── astro.config.mjs · wrangler.jsonc · sonar-project.properties · lefthook.yml · knip.json
|
||||
└── LICENSE (GPL-3.0) · CONTENT-LICENSE.md · DISCLAIMER.md · THIRD-PARTY-NOTICES.md · SECURITY.md · ACCESSIBILITY.md · CHANGELOG.md
|
||||
├── .github/ # ci.yml, content-bump.yml, lighthouse.yml, osv-scanner.yml, qodana.yml, triage.yml, dependabot.yml, ISSUE_TEMPLATE/ (config, bug_report, accessibility, language), pull_request_template.md
|
||||
├── astro.config.mjs · wrangler.jsonc · sonar-project.properties · qodana.yaml · lefthook.yml · knip.json
|
||||
└── LICENSE (GPL-3.0) · CONTENT-LICENSE.md · DISCLAIMER.md · THIRD-PARTY-NOTICES.md · SECURITY.md · ACCESSIBILITY.md · CONTRIBUTING.md · CHANGELOG.md
|
||||
```
|
||||
|
||||
## 4. Rendering & routing
|
||||
|
||||
@@ -112,10 +112,11 @@ Token `--scrollbar-thumb` / `--scrollbar-thumb-hover` / `--scrollbar-track` khai
|
||||
| Header / MobileTabBar / Footer | .astro | TabBar: Home·Blog·Truyện·Menu, ẩn ≥768px; nav chính của header hiện từ 960px (dưới đó dùng nút menu — bản EN cần ~900px) |
|
||||
| ThemeToggle, LangSwitch | island nhỏ / .astro | ThemeToggle 3 trạng thái (§6); LangSwitch nhận href đã giải bản dịch từ BaseLayout |
|
||||
| ScrollbarToggle | island nhỏ (footer, chỉ hiện khi `pointer: fine`) | switch `role="switch"`; localStorage `scrollbar=hidden` → `html[data-scrollbar="hidden"]`, áp trước first paint cùng bootstrap theme |
|
||||
| PostCard / StoryCard / ProjectCard | .astro | StoryCard có badge status + CW |
|
||||
| PostCard / StoryCard / ProjectCard | .astro | StoryCard có badge status + nhãn đã dịch + mốc tuổi; PostCard/GalleryCard: bìa mờ khi có nhãn làm mờ |
|
||||
| Prose | .astro + `src/styles/prose.css` | typography cho nội dung md; cùng stylesheet dùng cho preview trong admin |
|
||||
| ReadingControls | island | cỡ chữ (3 mức, localStorage `reader`), theme giấy/sepia/tối, progress bar 2px |
|
||||
| ContentWarning | .astro | banner `--horror`, bấm để mở nội dung |
|
||||
| ContentNotice | .astro | banner `--horror` nêu mọi nhãn (`src/lib/content-labels.ts`); nhãn làm mờ ⇒ ô "Hiện ảnh" (checkbox + CSS `:has()`, chạy khi tắt JS); vùng bài mang `data-cw-blur` |
|
||||
| AgeGate | .astro | nội dung có `ageRating` nằm trong `<details>`; có JS ⇒ `<dialog>` hỏi tuổi (Esc = huỷ), trả lời lưu localStorage `ageGate` (`src/lib/age-gate.ts`) |
|
||||
| Lightbox | island | vuốt được, lazy; thumbnail là link tới ảnh lớn (chạy được khi tắt JS) |
|
||||
| SearchModal | island | Pagefind, mở bằng `/` hoặc nút; ARIA combobox (`aria-activedescendant`), báo lỗi khi không tải được index |
|
||||
| MenuSheet | island | dialog modal, bẫy focus, trả focus về nút mở |
|
||||
|
||||
@@ -25,6 +25,8 @@ const base = z.object({
|
||||
tags: z.array(z.string()).default([]),
|
||||
cover: image().optional(),
|
||||
draft: z.boolean().default(false),
|
||||
contentWarning: z.array(z.enum(LABEL_IDS)).default([]), // nhãn: src/lib/content-labels.ts
|
||||
ageRating: z.enum(["13+","16+","18+"]).optional(), // có ⇒ hỏi tuổi trước khi hiện
|
||||
});
|
||||
|
||||
blog: base // tags gợi ý: dev-log, diary, share, gaming
|
||||
@@ -32,7 +34,6 @@ stories: base.extend({
|
||||
series: z.string().optional(),
|
||||
chapter: z.number().int().positive().optional(),
|
||||
status: z.enum(['ongoing','complete','dropped']).default('ongoing'),
|
||||
contentWarning: z.array(z.string()).default([]), // vd: ['horror','blood']
|
||||
})
|
||||
projects: z.object({ name, tagline, lang, stack: z.array(z.string()),
|
||||
repo: z.string().url().optional(), url: z.string().url().optional(),
|
||||
@@ -46,6 +47,22 @@ gallery: z.object({ title, lang, date, description: z.string().optional(),
|
||||
|
||||
Alt text ảnh gallery: file `src/assets/gallery/<album>/captions.json` (`{"IMG_001.avif": {"vi":"...","en":"..."}}`) — build fail nếu thiếu key.
|
||||
|
||||
### Nhãn nội dung & giới hạn tuổi (v2.3.0)
|
||||
|
||||
- **Nhãn** (`contentWarning`, blog · truyện · album; danh sách cố định ở `src/lib/content-labels.ts`,
|
||||
tên vi/en ở `src/i18n` nhóm `labels`): `horror`, `blood`, `jumpscare`, `violence`, `self-harm`,
|
||||
`death` — **làm mờ ảnh** + banner; `politics`, `religion`, `strong-language`, `flashing-lights`,
|
||||
`spoilers` — chỉ banner. Nhãn lạ ⇒ build fail.
|
||||
- **Album**: nhãn và `ageRating` lấy từ **cả hai** file ngôn ngữ (cùng ảnh, hai trang) — gắn ở một
|
||||
bản là đủ; mốc tuổi chặt hơn được dùng (`albumWarning()` trong `src/lib/collections.ts`).
|
||||
- **Từng ảnh** có thể có nhãn riêng: `contentWarning` cạnh caption trong `gallery-photos/<album>.json`
|
||||
(admin → Gallery → "Nhãn") hoặc `captions.json` (`{"IMG_001.avif": {"vi":"…","en":"…","contentWarning":["blood"]}}`).
|
||||
- **Giới hạn tuổi** (`ageRating`: `13+` | `16+` | `18+`): phần nội dung thu gọn tới khi người đọc xác
|
||||
nhận tuổi; câu trả lời chỉ lưu localStorage `ageGate` (mốc tuổi, không ngày sinh) — xem chính sách
|
||||
quyền riêng tư §6. Tắt JS: bấm mở là tự xác nhận.
|
||||
- Làm mờ là lớp hiển thị, **không** phải kiểm soát truy cập (ảnh vẫn được tải). Thẻ danh sách, RSS và
|
||||
ảnh OG đều nêu nhãn; trích đoạn tìm kiếm không lấy banner và phần nội dung có giới hạn tuổi.
|
||||
|
||||
## 3. Frontmatter mẫu
|
||||
|
||||
```yaml
|
||||
@@ -71,6 +88,7 @@ series: "Đêm không tiếng"
|
||||
chapter: 1
|
||||
status: ongoing
|
||||
contentWarning: [horror]
|
||||
ageRating: "16+"
|
||||
tags: [horror, short-story]
|
||||
---
|
||||
```
|
||||
@@ -121,6 +139,6 @@ Tiện ích khuyến nghị: snippet VS Code cho từng frontmatter; `npm run ne
|
||||
- [ ] frontmatter đủ + đúng schema (`astro check` pass)
|
||||
- [ ] slug không dấu, chưa từng dùng
|
||||
- [ ] ảnh đã strip EXIF, có alt/caption
|
||||
- [ ] truyện: contentWarning đặt đúng; chương đánh số liên tục
|
||||
- [ ] nhãn nội dung (`contentWarning`) và mốc tuổi (`ageRating`) đặt đúng; truyện: chương đánh số liên tục
|
||||
- [ ] đọc lại trên preview mobile (dev server, viewport 390px)
|
||||
- [ ] bài EN/VI có `translationKey` nếu là bản dịch
|
||||
@@ -40,7 +40,8 @@
|
||||
```
|
||||
[thanh mảnh: ← series | tiêu đề chương | Aa] ← Aa mở ReadingControls
|
||||
[progress bar 2px sticky top]
|
||||
[ContentWarning nếu có → bấm mới hiện nội dung]
|
||||
[ContentNotice nếu có nhãn → banner; nhãn làm mờ ⇒ ảnh mờ tới khi tick "Hiện ảnh"]
|
||||
[AgeGate nếu có ageRating → bấm summary ⇒ hỏi tuổi ⇒ mới hiện nội dung]
|
||||
Literata 68ch, 1.125–1.25rem
|
||||
[Chương trước ─ Mục lục series ─ Chương sau]
|
||||
```
|
||||
|
||||
@@ -86,7 +86,7 @@ Rule ghi đè header cho **mọi** request (client không giả được). Worke
|
||||
| Build variables | `NODE_VERSION=26`, `PUBLIC_TURNSTILE_SITE_KEY=<site key>` |
|
||||
| Build cache | bật |
|
||||
|
||||
Bẫy đã gặp (19/10/2026): Deploy command của nhánh PR từng là `wrangler deploy` ⇒ mỗi PR (cả Dependabot) được đưa lên production 100%. Ngược lại, nếu Deploy command của `main` là `versions upload` thì merge **không** deploy — khi đó promote tay: `npx wrangler versions list` → `npx wrangler versions deploy <id>@100% --yes --message "main <sha>"`. Xác minh sau mỗi merge: `curl https://poli0981.dev/api/health` phải trả đúng `version.commit`.
|
||||
Bẫy đã gặp (19/10/2026): Deploy command của nhánh PR từng là `wrangler deploy` ⇒ mỗi PR (cả Dependabot) được đưa lên production 100%. Ngược lại, nếu Deploy command của `main` là `versions upload` thì merge **không** deploy — khi đó promote tay: `npx wrangler versions list` → `npx wrangler versions deploy <id>@100% --yes --message "main <sha>"`. Xác minh sau mỗi merge: `curl https://poli0981.dev/api/health` phải trả đúng `version.commit` (và `version.content` = commit repo nội dung đã publish). Từ v2.3.0 admin tự xuất bản sau mỗi lần lưu ⇒ Deploy command của `main` **phải** là `npx wrangler deploy`, nếu không mọi lần lưu dừng ở pha "đã merge — đang deploy" (đã xảy ra từ 10/2026 tới 11/2026: mọi deploy trong thời gian đó là promote tay). **Đã sửa ngày 21/11/2026** (Deploy command = `npx wrangler deploy`, Version command = `npx wrangler versions upload`); deployment do Workers Builds tạo hiện trong `npx wrangler deployments list` ngay sau khi build `main` xong, không cần promote.
|
||||
- Local (khẩn cấp): `npm run build && npx wrangler deploy` (lần đầu wrangler mở OAuth login).
|
||||
- Gắn domain: Workers & Pages → worker `poli0981-dev` → Settings → **Domains & Routes → Add → Custom domain** → `poli0981.dev` (tự tạo DNS + cert). `www.poli0981.dev` là custom domain thứ hai; worker entry redirect 301 về apex.
|
||||
- Worker widgets (không nối Workers Builds): `npx wrangler deploy --config workers/widgets/wrangler.jsonc` → kiểm tra Triggers có cron.
|
||||
|
||||
@@ -7,7 +7,10 @@
|
||||
`npm ci --ignore-scripts` → `check-install-scripts` → `wrangler types` (site + widgets) → prettier → eslint → `astro check` (TS 6) → **`typecheck` bằng TypeScript 7** (in `tsc -v`, kiểm site + widgets) → knip → **`test:coverage`** (`node:test`, ngưỡng 80% dòng, xuất `coverage/lcov.info`) → `npm audit --omit=dev --audit-level=high` → `gen-notices --check` → `check-exif --changed` → build (+ OG, Pagefind, `check-csp-hashes`) → **smoke test** (`npm run smoke`: chạy worker đã build bằng `wrangler dev`, kiểm trang/304/HEAD/`/media`/`/ext-img`/admin 403/`frame-ancestors`, pha ép bật cổng Turnstile kể cả cookie sai định dạng, pha denylist) → **cổng trợ năng** (từ v2.2.0: `npm run preview` chạy nền rồi `npm run test:a11y` — Playwright lái Chrome có sẵn trên runner, không tải trình duyệt; axe-core quét mọi trang trong sitemap của bản build, một trang mỗi template ở theme sáng và bề rộng điện thoại, và menu/tìm kiếm/lightbox/hộp báo lỗi/bảng Aa/bảng pháp lý khi đang mở; sau đó là test bàn phím, reflow 320/360/390px và `forced-colors`) → upload coverage làm artifact. Check `build` là **bắt buộc** (ruleset `main`), nên PR có vi phạm axe không merge được.
|
||||
- Job **`sonarcloud`** (sau `build`; chạy cho push `main` và PR cùng repo, bỏ qua Dependabot): tải coverage → `SonarSource/sonarqube-scan-action` (pin SHA) với `sonar-project.properties`; trên PR chờ **quality gate** ("Sonar way" cho new code: coverage ≥ 80%, trùng lặp ≤ 3%, rating A, hotspot đã review). Automatic analysis trên SonarCloud **tắt** (CI analysis thay thế); `SONAR_TOKEN` là secret của repo. `.svelte`/`.astro` không được Sonar phân tích — logic quan trọng nằm trong `.ts` để đo được.
|
||||
- **CodeQL** (default setup, repo public) · **Snyk** (GitHub app) · **`osv-scanner.yml`** (reusable workflow v2.7.0, SARIF, hằng tuần + khi đổi lockfile) · **`lighthouse.yml`** (`treosh/lighthouse-ci-action` pin SHA, preset mobile, chỉ cảnh báo).
|
||||
- **`content-bump.yml`** (nút **Xuất bản** của admin): trỏ submodule `src/content` về `content/main`, commit lên nhánh `content/bump`, mở/cập nhật PR, auto-merge (squash) nếu diff chỉ `.md/.json`, rồi `gh workflow run ci.yml --ref content/bump` để có check `build` (PR mở bằng GITHUB_TOKEN không kích hoạt `pull_request`). Merge ⇒ Workers Builds deploy.
|
||||
- **`content-bump.yml`** (từ v2.3.0 admin tự gọi sau **mỗi lần lưu/xoá**; nút **Xuất bản** còn lại để chạy lại; `concurrency` gộp các lần gọi dồn dập): trỏ submodule `src/content` về `content/main`, commit lên nhánh `content/bump`, mở/cập nhật PR, auto-merge (squash) nếu diff chỉ `.md/.json`, rồi `gh workflow run ci.yml --ref content/bump` để có check `build` (PR mở bằng GITHUB_TOKEN không kích hoạt `pull_request`). Merge ⇒ Workers Builds deploy.
|
||||
- **`qodana.yml`** (từ v2.3.0, PR + push `main` + tay): Qodana for JS (gói Ultimate, token `QODANA_TOKEN`), native mode trên Node 26 của runner sau `npm ci` + sinh types, profile `qodana.recommended` quét cả repo, `failThreshold: 0` (`qodana.yaml` ghi các inspection tắt kèm lý do); kết quả lên Qodana Cloud và — với `main` — SARIF vào Code scanning. Bỏ qua PR Dependabot/fork (không có secret) nên chỉ là check tư vấn. Không phân tích `.astro`/`.svelte`.
|
||||
- **Kiểm license**: `gen-notices --check` (dependency trực tiếp, bảng trong `THIRD-PARTY-NOTICES.md`) + `check-licenses` (toàn bộ lockfile, ngoại lệ theo gói) trong job `build` — chính sách ở `scripts/license-policy.mjs` (`12_LEGAL/THIRD_PARTY_NOTICES.md`). Qodana license audit cần Ultimate Plus nên không dùng.
|
||||
- **`triage.yml`** (issues + `pull_request_target`; **không checkout gì** — đọc `scripts/triage.mjs` của nhánh mặc định qua API rồi import từ bộ nhớ, nên không bao giờ chạy code của PR; Sonar S7631 bắt mọi checkout trong `pull_request_target`): đề xuất tính năng ⇒ nhãn `enhancement` + `out-of-scope`, bình luận song ngữ, đóng. Chạy khô bằng `workflow_dispatch`.
|
||||
- **Bẫy đã gặp**: khi `main` dính advisory, *mọi* PR (cả Dependabot) đỏ vì bước audit ⇒ vá gộp trong một PR rồi đóng các PR Dependabot bị thay thế. `gen-notices --check` từng đếm số gói transitive ⇒ PR bump nào cũng đỏ; nay chỉ kiểm chính sách license.
|
||||
|
||||
## 1. Nguyên tắc
|
||||
@@ -116,8 +119,9 @@ Commit và tag đều ký GPG; không dùng `--no-verify`.
|
||||
|
||||
## 8. Branch & release
|
||||
|
||||
- `main` protected (ruleset): PR + check `build` xanh; merge kiểu **squash**. Conventional Commits.
|
||||
- Mỗi PR: CI `build` + SonarCloud quality gate + CodeQL xanh trước khi merge; Workers Builds trên nhánh PR chỉ `versions upload`.
|
||||
- `main` protected (ruleset): PR + check bắt buộc duy nhất là `build` (ruleset cho phép cả 3 kiểu merge; quy ước của repo là **squash**). Conventional Commits.
|
||||
- Mỗi PR: ngoài `build` còn phải xanh (theo quy ước, ruleset không ép) SonarCloud quality gate, Qodana (ngưỡng 0) và CodeQL; Workers Builds trên nhánh PR chỉ `versions upload`.
|
||||
- Chế độ bảo trì (D21): PR tính năng mới bị bot `triage.yml` đóng; mẫu PR có ô chọn 5 loại thay đổi được nhận (`CONTRIBUTING.md`).
|
||||
- **Release**: tag `vX.Y.Z` có ký GPG trên commit `main` đã deploy + GitHub Release (notes lấy từ `CHANGELOG.md`). Deploy vẫn là "merge `main`" — tag chỉ đánh dấu mốc. `v2.0.0` = đợt nâng cấp 10/2026. Mỗi tag: sửa `sonar.projectVersion` trong `sonar-project.properties` cho khớp.
|
||||
- Sau merge: kiểm `https://poli0981.dev/api/health` trả đúng commit (`07` §9); nếu Workers Builds không deploy thì promote version của `main` bằng `wrangler versions deploy`.
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# Third-Party Notices / Ghi nhận bên thứ ba
|
||||
|
||||
> **Ghi chú nội bộ:** file này gồm 2 phần — (A) phần khung render lên `/legal/third-party`, (B) bảng package **tự sinh** bằng `scripts/gen-notices.mjs` trong CI (dựa trên `license-checker`), CI fail nếu bảng lệch với lockfile. Đừng sửa tay phần B.
|
||||
> **Ghi chú nội bộ:** file này gồm 2 phần — (A) phần khung render lên `/legal/third-party`, (B) bảng package **tự sinh** bằng `scripts/gen-notices.mjs` trong CI (đọc `package.json` của từng gói đã cài — không dùng `license-checker`), CI fail nếu bảng lệch với lockfile. Đừng sửa tay phần B.
|
||||
|
||||
---
|
||||
|
||||
@@ -21,7 +21,6 @@ Trang web này được xây dựng bằng phần mềm mã nguồn mở. Mỗi
|
||||
| Astro + @astrojs/* | MIT | framework |
|
||||
| Svelte | MIT | islands |
|
||||
| Tailwind CSS | MIT | styling |
|
||||
| GSAP | GSAP Standard License (miễn phí, Webflow) | kiểm tra đúng tên license trong bản phát hành khi cài |
|
||||
| Pagefind | MIT | search |
|
||||
| @vite-pwa/astro / Workbox | MIT | offline |
|
||||
| Zod | MIT | validation |
|
||||
@@ -37,8 +36,9 @@ Trang web này được xây dựng bằng phần mềm mã nguồn mở. Mỗi
|
||||
## Quy trình sinh tự động
|
||||
|
||||
```bash
|
||||
node scripts/gen-notices.mjs # ghi đè phần (B) từ npm ls --json + license-checker
|
||||
node scripts/gen-notices.mjs # ghi đè phần (B): dependency trực tiếp, license đọc từ node_modules/<pkg>/package.json
|
||||
node scripts/gen-notices.mjs --check # CI: so khớp, lệch ⇒ exit 1
|
||||
node scripts/check-licenses.mjs # CI: toàn bộ package-lock.json (transitive + binary mọi nền tảng)
|
||||
```
|
||||
|
||||
Quy tắc: package mới có license ngoài allowlist (MIT, Apache-2.0, ISC, BSD-2/3, OFL, GSAP Standard) ⇒ script cảnh báo đỏ, phải review tay trước khi merge.
|
||||
Quy tắc (`scripts/license-policy.mjs`, dùng chung cho hai script): license ngoài allowlist (MIT, Apache-2.0, ISC, BSD-2/3, OFL-1.1, 0BSD, Unlicense, CC0-1.0, BlueOak-1.0.0, Python-2.0; biểu thức SPDX `OR`/`AND`/`WITH` được hiểu) ⇒ CI đỏ, phải review tay và ghi ngoại lệ **theo gói** kèm lý do (hiện có: MPL-2.0 của satori/resvg/lightningcss/axe-core, LGPL-3.0-or-later của libvips trong sharp — đều chỉ chạy lúc build/test). Gói không khai license cũng làm CI đỏ.
|
||||
@@ -48,7 +48,8 @@ Item: title, link, pubDate, description, `<language>` theo bài, category = tags
|
||||
## 5. OG image tự sinh
|
||||
|
||||
- Build-time bằng Satori + resvg (hoặc `astro-og-canvas` nếu gọn hơn lúc triển khai): template 1200×630, nền glacier night (palette tối) + Waveline + title (Bricolage) + badge khu (Blog/Truyện/Project) + `poli0981.dev`.
|
||||
- Truyện có contentWarning: OG thêm dải màu horror + nhãn CW (không spoil chi tiết).
|
||||
- Bài/truyện có nhãn (`contentWarning`) hoặc mốc tuổi (`ageRating`): OG thêm dải màu horror "Cảnh báo · Kinh dị · 16+" bằng ngôn ngữ của bài (không spoil chi tiết). Thẻ OG chỉ có chữ nên không bao giờ lộ ảnh bìa.
|
||||
- RSS: description của mục có nhãn được thêm tiền tố "[Cảnh báo: Kinh dị · 16+] " (theo ngôn ngữ của mục) — feed reader không có banner.
|
||||
- Cache theo hash(title+khu) để build nhanh.
|
||||
|
||||
## 6. Dữ liệu có cấu trúc (JSON-LD)
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
Ước lượng theo "buổi tối" (~2–3h). Nguyên tắc quen thuộc: **xong P0 spikes mới viết feature** — spike nào fail thì sửa kế hoạch khi chưa tốn công.
|
||||
|
||||
Trạng thái tại 2026-10-24 (v2.0.0): ✅ xong · 🟡 đang làm · ⬜ chưa.
|
||||
Trạng thái tại 2026-11-21 (v2.3.0 — **chế độ bảo trì**): ✅ xong · 🟡 đang làm · ⬜ chưa.
|
||||
|
||||
## P0 — Spikes ✅
|
||||
|
||||
@@ -49,7 +49,15 @@ Trạng thái tại 2026-10-24 (v2.0.0): ✅ xong · 🟡 đang làm · ⬜ chư
|
||||
- [ ] Test 2 thiết bị thật + 1 máy lạ (bạn bè) — thu 1 vòng feedback
|
||||
- [ ] Đăng giới thiệu lên các kênh (dùng notify.py 😄), thêm link site vào bio YouTube/GitHub/Discord
|
||||
|
||||
## Hướng đi tiếp (sau v2.0)
|
||||
- **v2.3.0** (11/2026, bản tính năng cuối): nhãn nội dung + hỏi tuổi + ảnh mờ + banner cảnh báo (D22) · admin tự xuất bản và biết khi nào "đã lên web" (D23) · Qodana + kiểm license toàn cây (D24) · **chuyển sang chế độ bảo trì** (D21).
|
||||
|
||||
## Chế độ bảo trì (từ v2.3.0, 11/2026)
|
||||
|
||||
Không thêm tính năng mới. Chỉ: cập nhật dependency định kỳ · vá bảo mật (advisory High/Critical, lỗ hổng runtime) · nâng cấp lớn ngôn ngữ/runtime/framework · sửa lỗi (cả UI/UX, accessibility) · sửa lỗi ngôn ngữ. Chính sách: `CONTRIBUTING.md`; lịch: `17` §0–§1; bot đóng đề xuất tính năng: `.github/workflows/triage.yml`.
|
||||
|
||||
P4 còn mở vẫn làm được vì không phải tính năng. Bảng dưới đây **đóng băng** — giữ để biết đã cân nhắc gì; mục nào chỉ quay lại khi rơi vào một trong năm loại thay đổi được nhận (VD gộp TypeScript 7.1 = nâng cấp lớn).
|
||||
|
||||
## Hướng đi đã cân nhắc (đóng băng)
|
||||
|
||||
| Hướng | Vì sao | Điều kiện |
|
||||
|---|---|---|
|
||||
|
||||
@@ -2,6 +2,18 @@
|
||||
|
||||
Mục tiêu: site "để yên vẫn sống". Tổng thời gian bảo trì định kỳ ~15–30 phút/tuần.
|
||||
|
||||
## 0. Chế độ bảo trì (từ v2.3.0, 11/2026 — quyết định D21)
|
||||
|
||||
Không thêm tính năng mới. Repo chỉ nhận (`CONTRIBUTING.md`):
|
||||
|
||||
1. Cập nhật dependency định kỳ (Dependabot hằng tuần + gộp `npm update --save --before=<hôm nay − 3 ngày>` khoảng mỗi tháng, như PR #123/#134).
|
||||
2. Bảo mật: advisory **High/Critical** trong dependency hoặc lỗ hổng nghiêm trọng của Node.js/Workers runtime ⇒ sửa và deploy ngay, ngoài lịch; tính năng chỉ khi thật sự cần.
|
||||
3. Nâng cấp lớn ngôn ngữ/runtime/framework (Node 26 → 28, TS 7.1 thay alias TS 6, Astro/Svelte major…).
|
||||
4. Sửa lỗi, gồm UI/UX và accessibility.
|
||||
5. Sửa lỗi ngôn ngữ (chính tả gây hiểu nhầm, câu chữ không hợp văn hoá/giọng địa phương).
|
||||
|
||||
Issue/PR đề xuất tính năng: `.github/workflows/triage.yml` (logic `scripts/triage.mjs`) gắn `enhancement` + `out-of-scope`, trả lời song ngữ và đóng. Bỏ qua: chủ repo, bot, mục có nhãn `maintenance-exception` (ngoại lệ do chủ repo quyết), và mọi thao tác do chính chủ repo làm (mở lại, gắn nhãn). Thử khô: Actions → Triage → Run workflow (nhập tiêu đề). Form issue: lỗi, accessibility, ngôn ngữ; blank issue tắt; câu hỏi/ý tưởng → Discussions.
|
||||
|
||||
## 1. Lịch định kỳ
|
||||
|
||||
| Nhịp | Việc |
|
||||
@@ -9,7 +21,7 @@ Mục tiêu: site "để yên vẫn sống". Tổng thời gian bảo trì đị
|
||||
| **Hằng tuần** (thứ 2, sau khi Dependabot chạy) | Triage PR Dependabot: patch/minor xanh CI → merge; security alert → xử lý ≤ 48h. Liếc Discord `#site-reports` |
|
||||
| **Hằng tháng** | `npm outdated` đọc report weekly; nâng minor còn sót; **nâng tay `@typescript/native`** (Dependabot bỏ qua alias `npm:`) và xem TS 7.1 đã có JS API chưa (`02` §8); xem Web Analytics + Core Web Vitals; liếc Workers Logs (lọc `level: error`) + dashboard admin (trạng thái cron widgets, secret thiếu); SonarCloud không có issue mới trên `main` |
|
||||
| **Hằng quý** | Nâng major có kế hoạch (Astro/Tailwind/Wrangler — đọc upgrade guide trước); chạy lại ma trận error test `09` §5; backup ngoài (§4) |
|
||||
| **Hằng năm** | **Xoay secrets**: GITHUB_ISSUES_TOKEN (repo `site-reports`), GITHUB_CONTENT_TOKEN + GITHUB_PUBLISH_TOKEN (admin), GATE_SECRET (vô hiệu mọi vé cổng — làm lúc ít khách), STEAM_API_KEY, SONAR_TOKEN · rà `ADMIN_EMAILS` + policy Access · cập nhật `Expires` trong security.txt · đọc lại 7 trang legal (đổi thì tăng `v` của legalAck) · **rà trợ năng**: đọc lại `/legal/accessibility` + `ACCESSIBILITY.md`, đi một lượt bằng bàn phím và trình đọc màn hình, cập nhật ngày rà ở cả hai nơi · kiểm tra thẻ thanh toán còn hạn cho auto-renew domain |
|
||||
| **Hằng năm** | **Xoay secrets**: GITHUB_ISSUES_TOKEN (repo `site-reports`), GITHUB_CONTENT_TOKEN + GITHUB_PUBLISH_TOKEN (admin), GATE_SECRET (vô hiệu mọi vé cổng — làm lúc ít khách), STEAM_API_KEY, SONAR_TOKEN, QODANA_TOKEN (token project trên Qodana Cloud → secret repo) · rà `ADMIN_EMAILS` + policy Access · cập nhật `Expires` trong security.txt · đọc lại 7 trang legal (đổi thì tăng `v` của legalAck) · **rà trợ năng**: đọc lại `/legal/accessibility` + `ACCESSIBILITY.md`, đi một lượt bằng bàn phím và trình đọc màn hình, cập nhật ngày rà ở cả hai nơi · kiểm tra thẻ thanh toán còn hạn cho auto-renew domain |
|
||||
|
||||
Đặt reminder: dùng chính hệ notify/cron GitHub Actions quen thuộc — workflow cron tháng/quý/năm bắn Discord nhắc việc (input sẵn trong repo `.github`).
|
||||
|
||||
@@ -18,7 +30,7 @@ Mục tiêu: site "để yên vẫn sống". Tổng thời gian bảo trì đị
|
||||
1. Branch `chore/upgrade-<pkg>-vX` → đọc CHANGELOG/upgrade guide chính thức.
|
||||
2. `npm i <pkg>@latest` → chạy full CI local (`format/lint/check/knip/build`).
|
||||
3. Mở PR → CI (`build` + smoke) + SonarCloud xanh; Workers Builds upload version preview của nhánh → bấm qua 6 trang đại diện + search + form report (dashboard → Versions → alias của nhánh).
|
||||
4. Squash-merge → kiểm `/api/health` trả đúng commit (Workers Builds không deploy ⇒ `wrangler versions deploy`) → chạy nhanh ma trận lỗi 3 dòng đầu (404/403/429).
|
||||
4. Squash-merge → Workers Builds deploy `main` (Deploy command `npx wrangler deploy`, `07` §9) → kiểm `/api/health` trả đúng commit (nếu vẫn bản cũ: Deploy command lại thành `versions upload` ⇒ sửa trong dashboard, tạm thời `wrangler versions deploy <id>@100%`) → chạy nhanh ma trận lỗi 3 dòng đầu (404/403/429).
|
||||
5. Ghi vào `CHANGELOG.md`; ghi 1 dòng vào `poli0981.dev-docs/00_INDEX.md` nếu có breaking change ảnh hưởng quyết định cũ.
|
||||
|
||||
**Rollback**: `npx wrangler versions list` → `npx wrangler versions deploy <id-cũ>@100% --yes` (hoặc `wrangler rollback`). Secret mới đặt sau version đó sẽ không có trong version cũ — đặt lại nếu cần.
|
||||
@@ -27,7 +39,7 @@ Mục tiêu: site "để yên vẫn sống". Tổng thời gian bảo trì đị
|
||||
|
||||
- **Uptime** (tuỳ chọn, free): UptimeRobot/StatusCake ping `https://poli0981.dev/` 5 phút/lần → alert email/Discord. Đủ dùng, không cần status page.
|
||||
- **Lỗi runtime**: Workers Logs (log JSON có `event`/`ray`, `06` §10) → tra theo Ray ID mà người dùng gửi kèm báo lỗi; không cần Sentry ở quy mô này (ADR-05).
|
||||
- **Đang chạy bản nào**: `curl https://poli0981.dev/api/health` → `version.id` + `version.commit`; dashboard admin hiện cùng thông tin.
|
||||
- **Đang chạy bản nào**: `curl https://poli0981.dev/api/health` → `version.id` + `version.commit` + `version.content` (commit repo nội dung mà bản build dùng); dashboard admin hiện cùng thông tin, thanh Xuất bản báo pha "đang build / đã merge — đang deploy / đã lên web".
|
||||
- **Admin**: `/admin/activity/` (audit log 90 ngày + commit repo content) — liếc khi nghi có thao tác lạ.
|
||||
- **Cron widgets**: tự cảnh báo qua Discord khi fail 3 lần (11 §5).
|
||||
|
||||
|
||||
+45
@@ -0,0 +1,45 @@
|
||||
# JetBrains Qodana — run by .github/workflows/qodana.yml on every PR and on main
|
||||
# (docs 08 §0). Reference: https://www.jetbrains.com/help/qodana/configuration-reference.html
|
||||
#
|
||||
# Qodana for JS is WebStorm's inspection engine. It reads .ts/.js/.mjs, CSS, JSON, YAML and
|
||||
# Markdown — not .astro or .svelte, which stay with astro check, eslint-plugin-astro/-svelte
|
||||
# and Prettier in ci.yml.
|
||||
version: "1.0"
|
||||
linter: qodana-js
|
||||
|
||||
# Native mode: the workflow sets up Node from .nvmrc and runs `npm ci` itself, so the analysis
|
||||
# resolves the same Node 26 and node_modules as the build (the Docker image ships its own Node).
|
||||
withinDocker: false
|
||||
|
||||
# Quality gate: the first run's 11 findings were fixed or, for one inspection, switched off
|
||||
# below with the reason, so any problem now is a new one and turns the check red.
|
||||
failThreshold: 0
|
||||
|
||||
profile:
|
||||
name: qodana.recommended
|
||||
inspections:
|
||||
# Not source code: build output, coverage, generated types, the content submodule (prose,
|
||||
# in its own repo), the design docs and the frontmatter templates.
|
||||
- group: ALL
|
||||
ignore:
|
||||
- "dist/**"
|
||||
- "coverage/**"
|
||||
- ".astro/**"
|
||||
- ".wrangler/**"
|
||||
- "src/content/**"
|
||||
- "poli0981.dev-docs/**"
|
||||
- "docs/templates/**"
|
||||
- "public/pagefind/**"
|
||||
- "worker-configuration.d.ts"
|
||||
- "workers/widgets/worker-configuration.d.ts"
|
||||
# Prose checkers don't read Vietnamese: every other word of the bilingual UI strings,
|
||||
# comments and docs would be a "typo".
|
||||
- inspection: SpellCheckingInspection
|
||||
enabled: false
|
||||
- inspection: GrazieInspection
|
||||
enabled: false
|
||||
# "Import can be shortened" wants tsconfig's `@/` alias or extensionless paths. The build
|
||||
# scripts and astro.config.mjs run under plain Node, where `@/` doesn't resolve and a
|
||||
# TypeScript import needs its `.ts`; in src/ relative vs alias imports are a style choice.
|
||||
- inspection: ES6PreferShortImport
|
||||
enabled: false
|
||||
@@ -37,7 +37,7 @@ const CONTENT = /\bcontent\s*=\s*(?:"([^"]*)"|'([^']*)')/i;
|
||||
// CodeQL js/bad-tag-filter found three separate holes here, one patch at a time, so the
|
||||
// cases below are now asserted on every run instead of being re-reasoned from scratch.
|
||||
const SCRIPT = /<script(\s[^>]*)?>([\s\S]*?)<\/script(\s[^>]*)?>/gi;
|
||||
const JSON_LD = /type=("|')?application\/ld\+json/i;
|
||||
const JSON_LD = /type=["']?application\/ld\+json/i;
|
||||
// Inline <style> blocks need their hash in the policy just the same, and Astro misses some:
|
||||
// the styles of a component rendered only from MDX content (Callout) shipped unhashed, so the
|
||||
// browser dropped them. A style *attribute* can never pass a policy without 'unsafe-inline'.
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
/**
|
||||
* Licence check over the whole dependency tree. CI runs it in the `build` job (docs 08 §6).
|
||||
*
|
||||
* node scripts/check-licenses.mjs
|
||||
*
|
||||
* gen-notices.mjs writes THIRD-PARTY-NOTICES.md from the direct dependencies only (what is
|
||||
* installed differs per platform, and that file must not). This check reads package-lock.json
|
||||
* instead, which records the declared licence of EVERY package — transitive ones and each
|
||||
* platform's binaries included — so it gives the same answer on Windows and on Linux CI, with
|
||||
* nothing installed.
|
||||
*
|
||||
* A package passes when its licence expression is satisfied by ALLOWED, or by the one licence
|
||||
* its REVIEWED entry clears (scripts/license-policy.mjs). A package with no licence, or one
|
||||
* that is not an SPDX expression, fails. So does a REVIEWED entry that no longer matches any
|
||||
* package: the list should say what is actually in the tree.
|
||||
*/
|
||||
import { readFileSync } from "node:fs";
|
||||
import { ALLOWED, REVIEWED, reviewFor, satisfies } from "./license-policy.mjs";
|
||||
|
||||
const PREFIX = "node_modules/";
|
||||
const lock = JSON.parse(readFileSync("package-lock.json", "utf8"));
|
||||
|
||||
/** null when the package is fine, "reviewed" when its REVIEWED entry clears it, else why not. */
|
||||
function verdict(name, license) {
|
||||
if (!license) return "declares no licence";
|
||||
try {
|
||||
if (satisfies(license, ALLOWED)) return null;
|
||||
const review = reviewFor(name);
|
||||
if (review && satisfies(license, new Set([...ALLOWED, review.license]))) return "reviewed";
|
||||
return `${license} is outside the policy`;
|
||||
} catch (error) {
|
||||
return error.message;
|
||||
}
|
||||
}
|
||||
|
||||
const problems = new Set();
|
||||
const byName = (a, b) => a.localeCompare(b);
|
||||
const reviewed = new Set();
|
||||
const usedReviews = new Set();
|
||||
let total = 0;
|
||||
|
||||
for (const [path, entry] of Object.entries(lock.packages ?? {})) {
|
||||
// "" is this project; anything without node_modules/ would be a workspace or a link.
|
||||
if (!path.includes(PREFIX) || entry.link) continue;
|
||||
const name = path.slice(path.lastIndexOf(PREFIX) + PREFIX.length);
|
||||
total++;
|
||||
const result = verdict(name, entry.license);
|
||||
if (result === "reviewed") {
|
||||
reviewed.add(name);
|
||||
usedReviews.add(reviewFor(name));
|
||||
} else if (result) {
|
||||
problems.add(`${name}@${entry.version}: ${result}`);
|
||||
}
|
||||
}
|
||||
|
||||
for (const entry of REVIEWED) {
|
||||
if (!usedReviews.has(entry)) {
|
||||
problems.add(`REVIEWED entry for ${entry.packages.join(", ")} matches no package — remove it`);
|
||||
}
|
||||
}
|
||||
|
||||
if (problems.size > 0) {
|
||||
console.error(`Licence check failed (${problems.size}):`);
|
||||
for (const problem of [...problems].sort(byName)) console.error(` ${problem}`);
|
||||
console.error(
|
||||
"Clear a package in REVIEWED (scripts/license-policy.mjs) with a reason, or drop it.",
|
||||
);
|
||||
process.exit(1);
|
||||
}
|
||||
console.log(
|
||||
`licences ok — ${total} packages in package-lock.json; cleared by review: ` +
|
||||
`${reviewed.size} (${[...reviewed].sort(byName).join(", ")})`,
|
||||
);
|
||||
+35
-39
@@ -11,46 +11,41 @@
|
||||
* `license-checker`. Same source of truth, one less dependency to vet — which is the
|
||||
* point of the exercise.
|
||||
*
|
||||
* Any license outside ALLOWED is reported. That is deliberately noisy: an unexpected
|
||||
* license is exactly the thing a human should look at, so it fails rather than being
|
||||
* quietly folded into the table. Cleared cases go in REVIEWED with a reason.
|
||||
* Any license outside the shared policy's ALLOWED list is reported. That is deliberately
|
||||
* noisy: an unexpected license is exactly the thing a human should look at, so it fails rather
|
||||
* than being quietly folded into the table. Cleared packages go in REVIEWED with a reason
|
||||
* (scripts/license-policy.mjs, shared with check-licenses.mjs, which covers the whole tree).
|
||||
*
|
||||
* The block holds nothing that changes on a routine version bump (no versions, no package
|
||||
* count): it used to print the size of the resolved tree, so every Dependabot PR that added
|
||||
* or dropped one transitive package failed CI here.
|
||||
*/
|
||||
import { readFileSync, writeFileSync, existsSync } from "node:fs";
|
||||
import { ALLOWED, reviewFor, satisfies } from "./license-policy.mjs";
|
||||
|
||||
const NOTICES = "THIRD-PARTY-NOTICES.md";
|
||||
const BEGIN = "<!-- BEGIN GENERATED — edit scripts/gen-notices.mjs, not this block -->";
|
||||
const END = "<!-- END GENERATED -->";
|
||||
|
||||
// docs 12: the licenses that need no discussion.
|
||||
const ALLOWED = new Set([
|
||||
"MIT",
|
||||
"Apache-2.0",
|
||||
"ISC",
|
||||
"BSD-2-Clause",
|
||||
"BSD-3-Clause",
|
||||
"OFL-1.1",
|
||||
"0BSD",
|
||||
"Unlicense",
|
||||
"CC0-1.0",
|
||||
"MIT OR Apache-2.0",
|
||||
"(MIT OR Apache-2.0)",
|
||||
"Apache-2.0 WITH LLVM-exception",
|
||||
"BlueOak-1.0.0",
|
||||
"Python-2.0",
|
||||
]);
|
||||
/** Whether a license expression passes without review; an unparseable one never does. */
|
||||
function allowedOutright(license) {
|
||||
try {
|
||||
return satisfies(license, ALLOWED);
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// Licenses cleared by hand. A reason is required — "we shipped it anyway" is not one.
|
||||
const REVIEWED = new Map([
|
||||
[
|
||||
"MPL-2.0",
|
||||
"File-level copyleft. satori and @resvg/resvg-js are used unmodified as build-time " +
|
||||
"tools and never shipped to the browser, so no source-disclosure obligation is triggered.",
|
||||
],
|
||||
]);
|
||||
/** Whether the package's REVIEWED entry clears its license. */
|
||||
function clearedByReview(name, license) {
|
||||
const review = reviewFor(name);
|
||||
if (!review) return false;
|
||||
try {
|
||||
return satisfies(license, new Set([...ALLOWED, review.license]));
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function licenseOf(name) {
|
||||
const p = `node_modules/${name}/package.json`;
|
||||
@@ -98,7 +93,7 @@ for (const { name } of direct) {
|
||||
}
|
||||
|
||||
const flagged = [...byLicense.entries()]
|
||||
.filter(([lic]) => !ALLOWED.has(lic))
|
||||
.filter(([lic]) => !allowedOutright(lic))
|
||||
.sort((a, b) => a[0].localeCompare(b[0]));
|
||||
|
||||
// ---------------------------------------------------------------- render
|
||||
@@ -142,10 +137,11 @@ const lines = [
|
||||
if (flagged.length > 0) {
|
||||
lines.push("## Licenses outside the standard allowlist", "");
|
||||
for (const [lic, list] of flagged) {
|
||||
const note = REVIEWED.get(lic);
|
||||
lines.push(`**${lic}** — ${list.length} package(s): ${list.map((n) => `\`${n}\``).join(", ")}`);
|
||||
lines.push("");
|
||||
lines.push(note ? `> Reviewed: ${note}` : `> ⚠️ NOT YET REVIEWED.`);
|
||||
lines.push(`**${lic}** — ${list.length} package(s):`, "");
|
||||
for (const name of list) {
|
||||
const note = clearedByReview(name, lic) ? `reviewed: ${reviewFor(name).reason}` : null;
|
||||
lines.push(`- \`${name}\` — ${note ?? "⚠️ NOT YET REVIEWED."}`);
|
||||
}
|
||||
lines.push("");
|
||||
}
|
||||
}
|
||||
@@ -175,7 +171,9 @@ if (start === -1 || stop === -1) {
|
||||
}
|
||||
const next = current.slice(0, start) + generated + current.slice(stop + END.length);
|
||||
|
||||
const unreviewed = flagged.filter(([lic]) => !REVIEWED.has(lic));
|
||||
const unreviewed = flagged.flatMap(([lic, list]) =>
|
||||
list.filter((name) => !clearedByReview(name, lic)).map((name) => `${name} (${lic})`),
|
||||
);
|
||||
|
||||
if (process.argv.includes("--check")) {
|
||||
if (next !== current) {
|
||||
@@ -187,8 +185,8 @@ if (process.argv.includes("--check")) {
|
||||
}
|
||||
if (unreviewed.length > 0) {
|
||||
console.error(
|
||||
`Unreviewed license(s) in the dependency tree: ${unreviewed.map(([l]) => l).join(", ")}\n` +
|
||||
`Review them and add an entry to REVIEWED in scripts/gen-notices.mjs.`,
|
||||
`Unreviewed license(s) among the direct dependencies: ${unreviewed.join(", ")}\n` +
|
||||
`Review them and add an entry to REVIEWED in scripts/license-policy.mjs.`,
|
||||
);
|
||||
process.exit(1);
|
||||
}
|
||||
@@ -197,8 +195,6 @@ if (process.argv.includes("--check")) {
|
||||
writeFileSync(NOTICES, next);
|
||||
console.log(`wrote ${NOTICES} — ${direct.length} direct, ${resolvedCount} resolved packages`);
|
||||
if (unreviewed.length > 0) {
|
||||
console.log(
|
||||
` note: ${unreviewed.length} license(s) need review: ${unreviewed.map(([l]) => l).join(", ")}`,
|
||||
);
|
||||
console.log(` note: ${unreviewed.length} package(s) need review: ${unreviewed.join(", ")}`);
|
||||
}
|
||||
}
|
||||
+13
-4
@@ -12,6 +12,9 @@ import { fileURLToPath } from "node:url";
|
||||
import path from "node:path";
|
||||
import { ogKey } from "../src/lib/og.ts";
|
||||
import { PALETTE } from "../src/lib/palette.ts";
|
||||
import { labelNames } from "../src/lib/content-labels.ts";
|
||||
import vi from "../src/i18n/vi.ts";
|
||||
import en from "../src/i18n/en.ts";
|
||||
|
||||
const root = fileURLToPath(new URL("..", import.meta.url));
|
||||
const fontsDir = path.join(root, "src/assets/fonts");
|
||||
@@ -69,7 +72,7 @@ function entryCard({ title, badge, cw }) {
|
||||
const t = esc(title);
|
||||
const size = t.length > 70 ? 50 : t.length > 45 ? 60 : 74;
|
||||
const strip = cw
|
||||
? `<div style="display:flex; align-items:center; align-self:flex-start; padding:6px 18px; border-radius:999px; background:${mix(C.horror, C.bg, 0.18)}; color:${C.horror}; font-size:22px; font-weight:500;">CW · ${esc(cw)}</div>`
|
||||
? `<div style="display:flex; align-items:center; align-self:flex-start; padding:6px 18px; border-radius:999px; background:${mix(C.horror, C.bg, 0.18)}; color:${C.horror}; font-size:22px; font-weight:500;">${esc(cw)}</div>`
|
||||
: "";
|
||||
return html(
|
||||
SHELL(`
|
||||
@@ -141,10 +144,16 @@ for (const { dir, section, titleKey } of SECTIONS) {
|
||||
const id = relPosix.replace(/\.(md|mdx)$/, "");
|
||||
const lang = data.lang === "en" ? "en" : "vi";
|
||||
const title = data[titleKey] ?? id;
|
||||
// A labelled post or chapter says so on its card, in its own language: a link preview
|
||||
// shows no banner. Cards are text only, so no image of the item ever appears on them.
|
||||
const strings = lang === "en" ? en : vi;
|
||||
const labels = Array.isArray(data.contentWarning) ? data.contentWarning.map(String) : [];
|
||||
const parts = [
|
||||
...labelNames(labels, strings.labels),
|
||||
...(data.ageRating ? [String(data.ageRating)] : []),
|
||||
];
|
||||
const cw =
|
||||
section === "story" && Array.isArray(data.contentWarning) && data.contentWarning.length
|
||||
? data.contentWarning.join(" · ")
|
||||
: null;
|
||||
section !== "project" && parts.length ? [strings.cw.title, ...parts].join(" · ") : null;
|
||||
const png = await render(entryCard({ title, badge: BADGES[section][lang], cw }));
|
||||
writeFileSync(path.join(outDir, `${ogKey(section, id)}.png`), png);
|
||||
count++;
|
||||
|
||||
@@ -0,0 +1,122 @@
|
||||
/**
|
||||
* Licence policy shared by scripts/gen-notices.mjs (direct dependencies → the table in
|
||||
* THIRD-PARTY-NOTICES.md) and scripts/check-licenses.mjs (every package in package-lock.json).
|
||||
* See docs 08 §6 and docs 12.
|
||||
*
|
||||
* The code is GPL-3.0-only. ALLOWED holds the licences that need no discussion. Anything else
|
||||
* has to be cleared PER PACKAGE in REVIEWED, with a reason: clearing a licence for everyone
|
||||
* would let the next package under it in without anyone looking (that is how
|
||||
* @axe-core/playwright once passed under a note written for satori).
|
||||
*/
|
||||
|
||||
/** SPDX licence identifiers that need no review. */
|
||||
export const ALLOWED = new Set([
|
||||
"MIT",
|
||||
"Apache-2.0",
|
||||
"ISC",
|
||||
"BSD-2-Clause",
|
||||
"BSD-3-Clause",
|
||||
"OFL-1.1",
|
||||
"0BSD",
|
||||
"Unlicense",
|
||||
"CC0-1.0",
|
||||
"BlueOak-1.0.0",
|
||||
"Python-2.0",
|
||||
]);
|
||||
|
||||
/**
|
||||
* Packages cleared by hand: `packages` are exact names or a prefix ending in `*`, `license`
|
||||
* is the one extra licence the entry allows for them. "We shipped it anyway" is not a reason.
|
||||
*/
|
||||
export const REVIEWED = [
|
||||
{
|
||||
packages: ["satori", "@resvg/resvg-js", "@resvg/resvg-js-*"],
|
||||
license: "MPL-2.0",
|
||||
reason:
|
||||
"File-level copyleft. Used unmodified at build time to draw the OG cards " +
|
||||
"(scripts/gen-og.mjs); never shipped to the browser or the Worker.",
|
||||
},
|
||||
{
|
||||
packages: ["axe-core", "@axe-core/playwright"],
|
||||
license: "MPL-2.0",
|
||||
reason:
|
||||
"File-level copyleft. Runs only in the accessibility tests (tests/a11y); never shipped.",
|
||||
},
|
||||
{
|
||||
packages: ["lightningcss", "lightningcss-*"],
|
||||
license: "MPL-2.0",
|
||||
reason:
|
||||
"File-level copyleft. Vite and Tailwind run it unmodified at build time to transform " +
|
||||
"this site's own CSS; the tool itself is not shipped.",
|
||||
},
|
||||
{
|
||||
packages: ["@img/sharp-libvips-*", "@img/sharp-win32-*", "@img/sharp-wasm32"],
|
||||
license: "LGPL-3.0-or-later",
|
||||
reason:
|
||||
"sharp's prebuilt libvips, loaded unmodified by Astro's image service at build time; " +
|
||||
"none of it is shipped. LGPL-3.0 is compatible with GPL-3.0.",
|
||||
},
|
||||
];
|
||||
|
||||
/** The REVIEWED entry that covers a package, if any. */
|
||||
export function reviewFor(name) {
|
||||
return REVIEWED.find((entry) =>
|
||||
entry.packages.some((pattern) =>
|
||||
pattern.endsWith("*") ? name.startsWith(pattern.slice(0, -1)) : name === pattern,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether an SPDX licence expression is satisfied by a set of allowed identifiers:
|
||||
* `A OR B` needs one side, `A AND B` needs both, parentheses group, and `X WITH exception`
|
||||
* counts as X (an exception only adds permissions). Throws a SyntaxError for anything that
|
||||
* is not an expression, such as "SEE LICENSE IN LICENSE".
|
||||
*/
|
||||
export function satisfies(expression, allowed) {
|
||||
const tokens = expression.replaceAll("(", " ( ").replaceAll(")", " ) ").trim().split(/\s+/);
|
||||
let at = 0;
|
||||
const isOperator = (token, op) => token?.toUpperCase() === op;
|
||||
const fail = () => {
|
||||
throw new SyntaxError(`Not an SPDX expression: "${expression}"`);
|
||||
};
|
||||
|
||||
function primary() {
|
||||
const token = tokens[at++];
|
||||
if (token === "(") {
|
||||
const value = anyOf();
|
||||
if (tokens[at++] !== ")") fail();
|
||||
return value;
|
||||
}
|
||||
if (!token || token === ")" || ["AND", "OR", "WITH"].some((op) => isOperator(token, op))) {
|
||||
fail();
|
||||
}
|
||||
if (isOperator(tokens[at], "WITH")) {
|
||||
if (!tokens[at + 1]) fail();
|
||||
at += 2;
|
||||
}
|
||||
return allowed.has(token);
|
||||
}
|
||||
function allOf() {
|
||||
let value = primary();
|
||||
while (isOperator(tokens[at], "AND")) {
|
||||
at++;
|
||||
const next = primary();
|
||||
value = value && next;
|
||||
}
|
||||
return value;
|
||||
}
|
||||
function anyOf() {
|
||||
let value = allOf();
|
||||
while (isOperator(tokens[at], "OR")) {
|
||||
at++;
|
||||
const next = allOf();
|
||||
value = value || next;
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
const result = anyOf();
|
||||
if (at !== tokens.length) fail();
|
||||
return result;
|
||||
}
|
||||
@@ -108,6 +108,11 @@ async function withWorker(port, vars, run) {
|
||||
const base = `http://127.0.0.1:${port}`;
|
||||
const get = (path, init) =>
|
||||
fetch(`${base}${path}`, { redirect: "manual", signal: AbortSignal.timeout(15000), ...init });
|
||||
// A phase that can't run is a failure, reported with the tail of wrangler's own output.
|
||||
const fail = (error) => {
|
||||
failures.push(String(error));
|
||||
console.error(error, `\n${log.slice(-4000)}`);
|
||||
};
|
||||
try {
|
||||
let up = false;
|
||||
for (let i = 0; i < 60 && !up; i++) {
|
||||
@@ -116,11 +121,10 @@ async function withWorker(port, vars, run) {
|
||||
() => sleep(1000).then(() => false),
|
||||
);
|
||||
}
|
||||
if (!up) throw new Error(`wrangler dev did not come up on ${base}`);
|
||||
await run(get, port);
|
||||
if (up) await run(get, port);
|
||||
else fail(new Error(`wrangler dev did not come up on ${base}`));
|
||||
} catch (error) {
|
||||
failures.push(String(error));
|
||||
console.error(error, `\n${log.slice(-4000)}`);
|
||||
fail(error);
|
||||
} finally {
|
||||
stop(server);
|
||||
}
|
||||
@@ -272,8 +276,12 @@ await withWorker(8788, {}, async (get, port) => {
|
||||
"/api/admin/content without Access → 403",
|
||||
(await get("/api/admin/content")).status === 403,
|
||||
);
|
||||
// Well-formed but signed by nobody: real JSON header and claims, a junk signature. Built
|
||||
// here rather than pasted as a token literal, which secret scanners rightly flag.
|
||||
const part = (value) => Buffer.from(JSON.stringify(value)).toString("base64url");
|
||||
const forgedJwt = `${part({ alg: "RS256" })}.${part({ email: "a@b.c" })}.c2ln`;
|
||||
const forged = await get("/api/admin/content", {
|
||||
headers: { "cf-access-jwt-assertion": "eyJhbGciOiJSUzI1NiJ9.eyJlbWFpbCI6ImFAYi5jIn0.c2ln" },
|
||||
headers: { "cf-access-jwt-assertion": forgedJwt },
|
||||
});
|
||||
expect("/api/admin with a forged JWT → 403", forged.status === 403);
|
||||
});
|
||||
|
||||
@@ -0,0 +1,76 @@
|
||||
/**
|
||||
* Maintenance-mode triage (CONTRIBUTING.md): an issue or pull request that asks for a new
|
||||
* feature is labelled and closed with an explanation; everything else is left for the owner.
|
||||
* .github/workflows/triage.yml reads this file from the default branch through the API and runs
|
||||
* it in actions/github-script: nothing is checked out, so no pull request's code ever runs.
|
||||
*
|
||||
* Deliberately narrow: only clear signals count (the title, or a label the reporter could not
|
||||
* set by accident). A bug report that happens to say "add" is not a feature request.
|
||||
*/
|
||||
|
||||
export const LABELS = {
|
||||
/** Marks a feature request (GitHub's default label, reused). */
|
||||
feature: "enhancement",
|
||||
/** Closed because new features are out of scope while the project is in maintenance mode. */
|
||||
closed: "out-of-scope",
|
||||
/** The owner's exception: the bot leaves the item alone. */
|
||||
exception: "maintenance-exception",
|
||||
};
|
||||
|
||||
// Tested against the trimmed title. Each pattern is linear: no two quantifiers compete for the
|
||||
// same characters.
|
||||
const FEATURE_TITLES = [
|
||||
/^feat(\([^)]*\))?!?:/i, // conventional commits: "feat: …", "feat(ui)!: …"
|
||||
/^\[(feat|feature|features|enhancement|request|idea|tính năng|đề xuất)\b/iu,
|
||||
/\bfeature[\s-]+request\b/i,
|
||||
/\b(new|add|adding)(\s+a)?\s+feature\b/i,
|
||||
/(đề xuất|yêu cầu|thêm|bổ sung)\s+tính năng|tính năng mới/iu,
|
||||
];
|
||||
|
||||
/** People whose items are never closed: the owner and collaborators, and bots. */
|
||||
const TRUSTED = new Set(["OWNER", "MEMBER", "COLLABORATOR"]);
|
||||
|
||||
/**
|
||||
* What to do with one issue or pull request.
|
||||
*
|
||||
* @param {{ title: string, labels: string[], author: string, association?: string,
|
||||
* sender?: string, owner?: string, state?: string }} item
|
||||
* `association` is the author's (GitHub's author_association); `sender` is whoever
|
||||
* triggered the event, so the owner reopening or relabelling an item is never undone.
|
||||
* @returns {{ action: "close" | "none", reason: string }}
|
||||
*/
|
||||
export function decide(item) {
|
||||
const labels = item.labels.map((label) => label.toLowerCase());
|
||||
if (item.state && item.state !== "open") return { action: "none", reason: "not open" };
|
||||
if (labels.includes(LABELS.exception)) return { action: "none", reason: "owner's exception" };
|
||||
if (TRUSTED.has(item.association ?? "")) return { action: "none", reason: "trusted author" };
|
||||
if (item.author.endsWith("[bot]")) return { action: "none", reason: "bot" };
|
||||
if (item.sender && item.owner && item.sender === item.owner) {
|
||||
return { action: "none", reason: "the owner acted on it" };
|
||||
}
|
||||
if (labels.includes(LABELS.feature)) return { action: "close", reason: "labelled as a feature" };
|
||||
const title = item.title.trim();
|
||||
if (FEATURE_TITLES.some((pattern) => pattern.test(title))) {
|
||||
return { action: "close", reason: "the title asks for a feature" };
|
||||
}
|
||||
return { action: "none", reason: "not a feature request" };
|
||||
}
|
||||
|
||||
/** The comment left on a closed item, in both of the project's languages. */
|
||||
export function closingComment(kind) {
|
||||
const what = kind === "pull_request" ? "pull request" : "issue";
|
||||
return [
|
||||
"**Vietnamese / Tiếng Việt** — Cảm ơn bạn! Dự án đang ở **chế độ bảo trì**: không nhận tính năng",
|
||||
"mới. Repo chỉ nhận cập nhật dependency, vá bảo mật, nâng cấp runtime/framework, sửa lỗi (kể",
|
||||
"cả UI/UX và accessibility) và sửa lỗi ngôn ngữ. Vì vậy mục này được đóng tự động. Nếu bạn",
|
||||
"nghĩ đây là lỗi chứ không phải tính năng mới, hãy trả lời bên dưới — chủ repo sẽ xem lại.",
|
||||
"",
|
||||
`**English** — Thank you! This project is in **maintenance mode** and does not take new`,
|
||||
`features. It accepts dependency updates, security fixes, runtime/framework upgrades, bug fixes`,
|
||||
`(including UI/UX and accessibility) and language fixes, so this ${what} was closed`,
|
||||
`automatically. If you think it is a bug rather than a new feature, reply below and the owner`,
|
||||
`will take another look.`,
|
||||
"",
|
||||
"→ [CONTRIBUTING.md](https://github.com/poli0981/poli0981-dev/blob/main/CONTRIBUTING.md)",
|
||||
].join("\n");
|
||||
}
|
||||
@@ -4,7 +4,7 @@ sonar.organization=poli0981
|
||||
sonar.projectKey=poli0981_poli0981-dev
|
||||
sonar.projectName=poli0981-dev
|
||||
# Bumped with each release tag; "previous version" new-code periods start from it.
|
||||
sonar.projectVersion=2.2.0
|
||||
sonar.projectVersion=2.3.0
|
||||
sonar.sourceEncoding=UTF-8
|
||||
|
||||
# .github is analyzed too: the workflow rules (pinned actions, no npx/install scripts) are
|
||||
|
||||
@@ -0,0 +1,254 @@
|
||||
---
|
||||
import { useTranslations } from "../i18n";
|
||||
import { homePath, type Locale } from "../i18n/routing";
|
||||
import { withAge } from "../lib/age-gate";
|
||||
import { minAge, type AgeRating } from "../lib/content-labels";
|
||||
|
||||
interface Props {
|
||||
rating: AgeRating;
|
||||
locale: Locale;
|
||||
}
|
||||
|
||||
// Folds an age-rated text away until the reader confirms their age (src/lib/age-gate.ts).
|
||||
// - In the HTML the text is a closed <details>: the safe state needs no script, and without
|
||||
// JavaScript opening it is the confirmation (privacy policy §8: core content works with
|
||||
// JavaScript off).
|
||||
// - With JavaScript, the summary asks first, in a native modal <dialog> (focus stays inside,
|
||||
// Esc cancels — it never means "yes"); the answer is kept in this browser's localStorage.
|
||||
// - It never pops up on its own: the page around it (title, banner, navigation) stays usable.
|
||||
// Search indexes the page's title, not anything inside the gate.
|
||||
const { rating, locale } = Astro.props;
|
||||
const t = useTranslations(locale);
|
||||
const age = minAge(rating) ?? 18;
|
||||
---
|
||||
|
||||
<!-- Search indexes none of it: not the text, and not the status lines either — they would
|
||||
become the search excerpt of a page the reader has not been allowed into. -->
|
||||
<div class="age-gate" data-min-age={age} data-pagefind-ignore>
|
||||
<!-- The answer's state sits above the text, where the reader is, not after a long chapter. -->
|
||||
<p class="age-status" data-state="allow" hidden>
|
||||
<span>{withAge(t.cw.confirmed, age)}</span>
|
||||
<button type="button" class="age-reset">{t.cw.reset}</button>
|
||||
</p>
|
||||
<p class="age-status" data-state="deny" hidden>
|
||||
<span>{withAge(t.cw.denied, age)}</span>
|
||||
<a href={homePath(locale)}>{t.cw.home}</a>
|
||||
<button type="button" class="age-retry">{t.cw.retry}</button>
|
||||
</p>
|
||||
|
||||
<details class="age-fold">
|
||||
<summary class="age-summary">
|
||||
<span class="age-badge">{rating}</span>
|
||||
<span>{withAge(t.cw.gate, age)}</span>
|
||||
<!-- "Select to confirm and read": true until the reader has answered yes. -->
|
||||
<span class="age-hint">{t.cw.gateHint}</span>
|
||||
</summary>
|
||||
<div class="age-body" data-pagefind-ignore>
|
||||
<slot />
|
||||
</div>
|
||||
</details>
|
||||
|
||||
<dialog class="age-dialog" aria-labelledby="age-question" aria-describedby="age-explain">
|
||||
<form method="dialog">
|
||||
<h2 id="age-question">{withAge(t.cw.question, age)}</h2>
|
||||
<p id="age-explain">{withAge(t.cw.explain, age)}</p>
|
||||
<div class="age-actions">
|
||||
<button type="submit" value="yes" class="age-yes">{withAge(t.cw.yes, age)}</button>
|
||||
<!-- Focus starts here: pressing Enter by habit must not mean "yes". -->
|
||||
<button type="submit" value="no" class="age-no" autofocus>{t.cw.no}</button>
|
||||
</div>
|
||||
</form>
|
||||
</dialog>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
import { answer, decide, readAnswer, resetAnswer, saveAnswer } from "../lib/age-gate";
|
||||
|
||||
// localStorage can throw on access (blocked storage); the answer then lives for this page.
|
||||
let store: Storage | null = null;
|
||||
try {
|
||||
store = window.localStorage;
|
||||
} catch {
|
||||
store = null;
|
||||
}
|
||||
let current = readAnswer(store);
|
||||
|
||||
for (const gate of document.querySelectorAll<HTMLElement>(".age-gate")) {
|
||||
const age = Number(gate.dataset.minAge);
|
||||
const fold = gate.querySelector<HTMLDetailsElement>(".age-fold");
|
||||
const summary = fold?.querySelector("summary");
|
||||
const dialog = gate.querySelector<HTMLDialogElement>(".age-dialog");
|
||||
const allowRow = gate.querySelector<HTMLElement>('[data-state="allow"]');
|
||||
const denyRow = gate.querySelector<HTMLElement>('[data-state="deny"]');
|
||||
if (!fold || !summary || !dialog || !allowRow || !denyRow || !age) continue;
|
||||
|
||||
const render = () => {
|
||||
const decision = decide(current, age);
|
||||
gate.dataset.decision = decision;
|
||||
fold.open = decision === "allow";
|
||||
fold.hidden = decision === "deny";
|
||||
allowRow.hidden = decision !== "allow";
|
||||
denyRow.hidden = decision !== "deny";
|
||||
};
|
||||
|
||||
summary.addEventListener("click", (event) => {
|
||||
if (decide(current, age) === "allow") return; // an ordinary fold from here on
|
||||
event.preventDefault();
|
||||
dialog.returnValue = "";
|
||||
dialog.showModal();
|
||||
});
|
||||
|
||||
// The browser also opens a <details> by itself — find-in-page, a #:~:text= link from a
|
||||
// search engine, an #id inside the text. Without a "yes" on record, fold it straight back.
|
||||
fold.addEventListener("toggle", () => {
|
||||
if (fold.open && decide(current, age) !== "allow") fold.open = false;
|
||||
});
|
||||
|
||||
dialog.addEventListener("close", () => {
|
||||
const choice = dialog.returnValue; // "yes", "no", or "" when cancelled with Esc
|
||||
if (choice !== "yes" && choice !== "no") return;
|
||||
current = answer(current, age, choice === "yes");
|
||||
saveAnswer(store, current);
|
||||
render();
|
||||
// "Yes": the summary, right above the text — the dialog may have handed focus back to
|
||||
// "Chọn lại", which render() just hid. "No": the summary is hidden now, so focus goes to
|
||||
// the row that explains why and offers to choose again.
|
||||
if (choice === "yes") summary.focus();
|
||||
else denyRow.querySelector("button")?.focus();
|
||||
});
|
||||
|
||||
denyRow.querySelector(".age-retry")?.addEventListener("click", () => {
|
||||
dialog.returnValue = "";
|
||||
dialog.showModal();
|
||||
});
|
||||
|
||||
allowRow.querySelector(".age-reset")?.addEventListener("click", () => {
|
||||
resetAnswer(store);
|
||||
current = readAnswer(null);
|
||||
render();
|
||||
summary.focus();
|
||||
});
|
||||
|
||||
render();
|
||||
}
|
||||
</script>
|
||||
|
||||
<style>
|
||||
.age-gate {
|
||||
display: grid;
|
||||
gap: 0.75rem;
|
||||
}
|
||||
.age-fold {
|
||||
border: 1px solid color-mix(in srgb, var(--horror) 55%, var(--line));
|
||||
border-radius: var(--radius-card);
|
||||
}
|
||||
.age-fold[open] {
|
||||
border-color: var(--line);
|
||||
}
|
||||
.age-summary {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: 0.5rem 0.75rem;
|
||||
min-block-size: 2.75rem;
|
||||
padding: 0.9rem 1.1rem;
|
||||
cursor: pointer;
|
||||
list-style: none;
|
||||
color: var(--text);
|
||||
}
|
||||
.age-summary::-webkit-details-marker {
|
||||
display: none;
|
||||
}
|
||||
.age-fold[open] > .age-summary {
|
||||
border-block-end: 1px solid var(--line);
|
||||
}
|
||||
.age-hint {
|
||||
color: var(--muted);
|
||||
}
|
||||
.age-gate[data-decision="allow"] .age-hint {
|
||||
display: none;
|
||||
}
|
||||
.age-badge {
|
||||
padding: 0.1em 0.55em;
|
||||
border-radius: 999px;
|
||||
border: 1px solid color-mix(in srgb, var(--horror) 45%, transparent);
|
||||
background: color-mix(in srgb, var(--horror) 18%, transparent);
|
||||
font-family: var(--ff-mono);
|
||||
font-size: var(--text-meta);
|
||||
font-weight: 600;
|
||||
}
|
||||
.age-body {
|
||||
padding: 1.1rem;
|
||||
}
|
||||
.age-status[hidden],
|
||||
.age-fold[hidden] {
|
||||
display: none;
|
||||
}
|
||||
.age-status {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: 0.5rem 1rem;
|
||||
margin: 0;
|
||||
color: var(--muted);
|
||||
font-size: var(--text-meta);
|
||||
}
|
||||
.age-status a {
|
||||
color: var(--accent);
|
||||
}
|
||||
.age-dialog {
|
||||
max-inline-size: min(30rem, calc(100vw - 2rem));
|
||||
padding: 1.4rem 1.5rem;
|
||||
border: 1px solid var(--line-strong);
|
||||
border-radius: var(--radius-modal);
|
||||
background: var(--surface);
|
||||
color: var(--text);
|
||||
box-shadow: var(--shadow-elevated);
|
||||
}
|
||||
.age-dialog::backdrop {
|
||||
background: var(--overlay, rgb(2 6 23 / 0.66));
|
||||
}
|
||||
.age-dialog h2 {
|
||||
margin: 0 0 0.6rem;
|
||||
font-size: var(--text-lead);
|
||||
}
|
||||
.age-dialog p {
|
||||
margin: 0 0 1.2rem;
|
||||
color: var(--muted);
|
||||
}
|
||||
.age-actions {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 0.6rem;
|
||||
}
|
||||
.age-actions button {
|
||||
min-block-size: 2.75rem;
|
||||
padding: 0.5rem 1rem;
|
||||
border: 1px solid var(--line-strong);
|
||||
border-radius: var(--radius-control);
|
||||
background: var(--elevated);
|
||||
color: var(--text);
|
||||
cursor: pointer;
|
||||
}
|
||||
.age-actions .age-yes {
|
||||
border-color: var(--accent);
|
||||
background: var(--accent);
|
||||
color: var(--accent-contrast);
|
||||
}
|
||||
.age-status button {
|
||||
min-block-size: 2.75rem;
|
||||
padding: 0.25rem 0.75rem;
|
||||
border: 1px solid var(--line-strong);
|
||||
border-radius: var(--radius-control);
|
||||
background: transparent;
|
||||
color: var(--text);
|
||||
cursor: pointer;
|
||||
}
|
||||
@media (forced-colors: active) {
|
||||
.age-fold,
|
||||
.age-badge,
|
||||
.age-dialog {
|
||||
border-color: CanvasText;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,119 @@
|
||||
---
|
||||
import { useTranslations } from "../i18n";
|
||||
import type { Locale } from "../i18n/routing";
|
||||
import { labelNames, needsBlur, type AgeRating } from "../lib/content-labels";
|
||||
|
||||
interface Props {
|
||||
/** The item's content labels (src/lib/content-labels.ts). */
|
||||
labels: readonly string[];
|
||||
ageRating?: AgeRating | undefined;
|
||||
locale: Locale;
|
||||
}
|
||||
|
||||
// The banner at the top of a labelled post, chapter or album. When a label blurs images, the
|
||||
// region this sits in must carry `data-cw-blur` (global.css): every image in it stays blurred
|
||||
// until "Hiện ảnh" is ticked. That is a real checkbox read by CSS `:has()`, so it works with
|
||||
// JavaScript off and nothing sharp shows before a script runs. Search skips the banner.
|
||||
const { labels, ageRating, locale } = Astro.props;
|
||||
const t = useTranslations(locale);
|
||||
const names = labelNames(labels, t.labels);
|
||||
const blur = needsBlur(labels);
|
||||
---
|
||||
|
||||
{
|
||||
(names.length > 0 || ageRating) && (
|
||||
<div class="cw-notice" role="note" aria-labelledby="cw-title" data-pagefind-ignore>
|
||||
<p class="cw-head">
|
||||
<span class="cw-icon" aria-hidden="true">
|
||||
⚠
|
||||
</span>
|
||||
<strong id="cw-title">{t.cw.title}</strong>
|
||||
</p>
|
||||
<ul class="cw-tags" role="list">
|
||||
{names.map((name) => (
|
||||
<li class="cw-tag">{name}</li>
|
||||
))}
|
||||
{ageRating && <li class="cw-tag cw-age">{ageRating}</li>}
|
||||
</ul>
|
||||
{blur && (
|
||||
<p class="cw-blur-row">
|
||||
<span>{t.cw.blurNote}</span>
|
||||
<label class="cw-reveal">
|
||||
<input type="checkbox" class="cw-reveal-input" />
|
||||
{t.cw.reveal}
|
||||
</label>
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
<style>
|
||||
.cw-notice {
|
||||
display: grid;
|
||||
gap: 0.6rem;
|
||||
margin-block: 0 1.75rem;
|
||||
padding: 0.9rem 1.1rem;
|
||||
border: 1px solid color-mix(in srgb, var(--horror) 55%, var(--line));
|
||||
border-radius: var(--radius-card);
|
||||
background: color-mix(in srgb, var(--horror) 10%, var(--surface));
|
||||
color: var(--text);
|
||||
}
|
||||
.cw-head {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
margin: 0;
|
||||
}
|
||||
.cw-icon {
|
||||
color: var(--horror);
|
||||
font-size: 1.1em;
|
||||
}
|
||||
.cw-tags {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 0.35rem;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
list-style: none;
|
||||
}
|
||||
.cw-tag {
|
||||
padding: 0.1em 0.55em;
|
||||
border-radius: 999px;
|
||||
border: 1px solid color-mix(in srgb, var(--horror) 45%, transparent);
|
||||
background: color-mix(in srgb, var(--horror) 18%, transparent);
|
||||
font-family: var(--ff-mono);
|
||||
font-size: var(--text-meta);
|
||||
}
|
||||
.cw-age {
|
||||
font-weight: 600;
|
||||
}
|
||||
.cw-blur-row {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: 0.5rem 1rem;
|
||||
margin: 0;
|
||||
color: var(--muted);
|
||||
font-size: var(--text-meta);
|
||||
}
|
||||
.cw-reveal {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 0.4rem;
|
||||
min-block-size: 2.75rem; /* WCAG 2.5.8: a comfortable target, not just the box */
|
||||
color: var(--text);
|
||||
cursor: pointer;
|
||||
}
|
||||
.cw-reveal-input {
|
||||
inline-size: 1.1rem;
|
||||
block-size: 1.1rem;
|
||||
accent-color: var(--accent);
|
||||
}
|
||||
@media (forced-colors: active) {
|
||||
.cw-notice,
|
||||
.cw-tag {
|
||||
border-color: CanvasText;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -1,81 +0,0 @@
|
||||
---
|
||||
interface Props {
|
||||
warnings: string[];
|
||||
title?: string;
|
||||
hint?: string;
|
||||
}
|
||||
// JS-free reveal via native <details> — keyboard-accessible and CSP-clean.
|
||||
const { warnings, title = "Cảnh báo nội dung", hint = "Bấm để đọc" } = Astro.props;
|
||||
---
|
||||
|
||||
<details class="cw">
|
||||
<summary class="cw-summary">
|
||||
<span class="cw-icon" aria-hidden="true">⚠</span>
|
||||
<span class="cw-title">{title}</span>
|
||||
{
|
||||
warnings.length > 0 && (
|
||||
<span class="cw-tags">
|
||||
{warnings.map((w) => (
|
||||
<span class="cw-tag">{w}</span>
|
||||
))}
|
||||
</span>
|
||||
)
|
||||
}
|
||||
<span class="cw-hint">{hint}</span>
|
||||
</summary>
|
||||
<div class="cw-body">
|
||||
<slot />
|
||||
</div>
|
||||
</details>
|
||||
|
||||
<style>
|
||||
.cw {
|
||||
border: 1px solid color-mix(in srgb, var(--horror) 55%, var(--line));
|
||||
border-radius: var(--radius-card);
|
||||
background: color-mix(in srgb, var(--horror) 10%, var(--surface));
|
||||
}
|
||||
.cw-summary {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: 0.5rem 0.75rem;
|
||||
padding: 0.9rem 1.1rem;
|
||||
cursor: pointer;
|
||||
list-style: none;
|
||||
color: var(--text);
|
||||
}
|
||||
.cw-summary::-webkit-details-marker {
|
||||
display: none;
|
||||
}
|
||||
.cw-icon {
|
||||
color: var(--horror);
|
||||
font-size: 1.1em;
|
||||
}
|
||||
.cw-title {
|
||||
font-weight: 600;
|
||||
}
|
||||
.cw-tags {
|
||||
display: inline-flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 0.35rem;
|
||||
}
|
||||
.cw-tag {
|
||||
padding: 0.1em 0.5em;
|
||||
border-radius: 999px;
|
||||
background: color-mix(in srgb, var(--horror) 30%, transparent);
|
||||
color: color-mix(in srgb, var(--horror) 30%, var(--text));
|
||||
font-family: var(--ff-mono);
|
||||
font-size: var(--text-meta);
|
||||
}
|
||||
.cw-hint {
|
||||
margin-inline-start: auto;
|
||||
color: var(--muted);
|
||||
font-size: var(--text-meta);
|
||||
}
|
||||
.cw[open] .cw-hint {
|
||||
display: none;
|
||||
}
|
||||
.cw-body {
|
||||
padding: 0 1.1rem 1.1rem;
|
||||
}
|
||||
</style>
|
||||
@@ -1,9 +1,11 @@
|
||||
---
|
||||
import { Image } from "astro:assets";
|
||||
import MediaImage from "./MediaImage.astro";
|
||||
import { type GalleryEntry } from "../lib/collections";
|
||||
import { albumWarning, type GalleryEntry } from "../lib/collections";
|
||||
import type { GalleryPhoto } from "../lib/gallery";
|
||||
import { sectionPath, type Locale } from "../i18n/routing";
|
||||
import { useTranslations } from "../i18n";
|
||||
import { labelNames, needsBlur } from "../lib/content-labels";
|
||||
|
||||
interface Props {
|
||||
entry: GalleryEntry;
|
||||
@@ -17,11 +19,18 @@ const { entry, cover, locale, headingLevel = 3 } = Astro.props;
|
||||
const Title = `h${headingLevel}` as const;
|
||||
const href = sectionPath("gallery", locale, entry.data.album);
|
||||
const year = entry.data.date.getFullYear();
|
||||
// The cover stays blurred when the album (in either language) or that photo carries a label
|
||||
// that blurs images, or when the album is age-rated; the card says why.
|
||||
const t = useTranslations(locale);
|
||||
const { labels: albumLabels, ageRating } = await albumWarning(entry.data.album);
|
||||
const labels = [...new Set([...albumLabels, ...cover.labels])];
|
||||
const blurCover = needsBlur(labels) || Boolean(ageRating);
|
||||
const warning = [...labelNames(labels, t.labels), ...(ageRating ? [ageRating] : [])].join(" · ");
|
||||
---
|
||||
|
||||
<article class="card">
|
||||
<a class="card-link" href={href}>
|
||||
<div class="cover">
|
||||
<div class="cover" data-cw-blur={blurCover ? "" : undefined}>
|
||||
{
|
||||
cover.kind === "local" ? (
|
||||
<Image
|
||||
@@ -40,6 +49,15 @@ const year = entry.data.date.getFullYear();
|
||||
<div class="body">
|
||||
<Title class="title">{entry.data.title}</Title>
|
||||
<span class="year">{year}</span>
|
||||
{
|
||||
warning && (
|
||||
<span class="cw">
|
||||
<span aria-hidden="true">⚠</span>
|
||||
<span class="sr-only">{t.cw.title}:</span>
|
||||
{warning}
|
||||
</span>
|
||||
)
|
||||
}
|
||||
</div>
|
||||
</a>
|
||||
</article>
|
||||
@@ -70,11 +88,22 @@ const year = entry.data.date.getFullYear();
|
||||
}
|
||||
.body {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: baseline;
|
||||
justify-content: space-between;
|
||||
gap: 0.75rem;
|
||||
gap: 0.25rem 0.75rem;
|
||||
padding: 0.9rem 1.1rem 1rem;
|
||||
}
|
||||
/* Its own line under the title; the gap stands in for the whitespace the build strips. */
|
||||
.cw {
|
||||
display: inline-flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 0.35em;
|
||||
flex-basis: 100%;
|
||||
color: color-mix(in srgb, var(--horror) 35%, var(--text));
|
||||
font-family: var(--ff-mono);
|
||||
font-size: var(--text-meta);
|
||||
}
|
||||
.title {
|
||||
font-size: var(--text-lead);
|
||||
font-weight: 700;
|
||||
|
||||
@@ -0,0 +1,99 @@
|
||||
---
|
||||
import { Image } from "astro:assets";
|
||||
import MediaImage from "./MediaImage.astro";
|
||||
import type { GalleryPhoto } from "../lib/gallery";
|
||||
import type { Locale } from "../i18n/routing";
|
||||
|
||||
interface Props {
|
||||
photos: GalleryPhoto[];
|
||||
/** The lightbox slide (full-size image) each thumbnail links to. */
|
||||
hrefs: string[];
|
||||
/** Per photo: blurred on its own (a label of its own, in an album that isn't blurred). */
|
||||
blurred: boolean[];
|
||||
/** Per photo: the accessible name — "open", the caption, and any warning. */
|
||||
labels: string[];
|
||||
locale: Locale;
|
||||
}
|
||||
|
||||
// The album's thumbnails. Each links to its full-size image, so the album works without JS;
|
||||
// the lightbox island takes over plain clicks once it hydrates.
|
||||
const { photos, hrefs, blurred, labels } = Astro.props;
|
||||
---
|
||||
|
||||
<div class="photo-grid">
|
||||
{
|
||||
photos.map((p, i) => (
|
||||
<a
|
||||
class:list={["thumb", { "cw-photo": blurred[i] }]}
|
||||
href={hrefs[i]}
|
||||
data-lightbox-index={i}
|
||||
aria-label={labels[i]}
|
||||
>
|
||||
{p.kind === "local" ? (
|
||||
<Image
|
||||
src={p.image}
|
||||
alt=""
|
||||
widths={[400, 800]}
|
||||
sizes="(max-width: 640px) 50vw, 320px"
|
||||
loading={i === 0 ? "eager" : "lazy"}
|
||||
decoding="async"
|
||||
{...(i === 0 ? { fetchpriority: "high" as const } : {})}
|
||||
/>
|
||||
) : (
|
||||
<MediaImage
|
||||
media={p.media}
|
||||
alt=""
|
||||
sizes="(max-width: 640px) 50vw, 320px"
|
||||
loading={i === 0 ? "eager" : "lazy"}
|
||||
{...(i === 0 ? { fetchpriority: "high" as const } : {})}
|
||||
/>
|
||||
)}
|
||||
</a>
|
||||
))
|
||||
}
|
||||
</div>
|
||||
|
||||
<style>
|
||||
.photo-grid {
|
||||
margin-block-start: 1.5rem;
|
||||
display: grid;
|
||||
gap: 0.75rem;
|
||||
/* minmax(0, 1fr), not 1fr: a `1fr` column is at least as wide as its photos' minimum
|
||||
content size, which made the first column 235px wide and the page wider than a
|
||||
320px screen. With a zero minimum the columns stay equal. */
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
}
|
||||
@media (min-width: 640px) {
|
||||
.photo-grid {
|
||||
grid-template-columns: repeat(3, minmax(0, 1fr));
|
||||
}
|
||||
}
|
||||
@media (min-width: 960px) {
|
||||
.photo-grid {
|
||||
grid-template-columns: repeat(4, minmax(0, 1fr));
|
||||
}
|
||||
}
|
||||
.thumb {
|
||||
display: block;
|
||||
padding: 0;
|
||||
border: 1px solid var(--line);
|
||||
border-radius: var(--radius-card);
|
||||
background: var(--surface);
|
||||
overflow: clip;
|
||||
cursor: pointer;
|
||||
aspect-ratio: 1 / 1;
|
||||
transition:
|
||||
transform var(--duration-fast) var(--ease-site),
|
||||
border-color var(--duration-fast) var(--ease-site);
|
||||
}
|
||||
.thumb:hover {
|
||||
transform: translateY(-2px);
|
||||
border-color: color-mix(in srgb, var(--accent) 40%, var(--line));
|
||||
}
|
||||
.thumb :global(img) {
|
||||
display: block;
|
||||
inline-size: 100%;
|
||||
block-size: 100%;
|
||||
object-fit: cover;
|
||||
}
|
||||
</style>
|
||||
@@ -3,9 +3,12 @@
|
||||
import { prefersReducedMotion } from "../lib/motion";
|
||||
|
||||
/**
|
||||
* `blur`: the photo has a content label that blurs images (src/lib/content-labels.ts);
|
||||
* `warning` names it. Such a slide opens blurred, behind a "show" button, unless the page's
|
||||
* own "Hiện ảnh" box (ContentNotice) is ticked.
|
||||
* @type {{
|
||||
* slides: { src: string, srcset: string, width: number, height: number, alt: string }[],
|
||||
* labels: { viewer: string, close: string, prev: string, next: string, counter: string }
|
||||
* slides: { src: string, srcset: string, width: number, height: number, alt: string, blur?: boolean, warning?: string }[],
|
||||
* labels: { viewer: string, close: string, prev: string, next: string, counter: string, reveal?: string }
|
||||
* }}
|
||||
*/
|
||||
let { slides = [], labels } = $props();
|
||||
@@ -15,8 +18,12 @@
|
||||
let dialogEl = $state(null);
|
||||
let trackEl = $state(null);
|
||||
let opener = null; // element to restore focus to on close
|
||||
/** @type {Record<number, boolean>} slides shown unblurred in this viewing */
|
||||
let revealed = $state({});
|
||||
let pageRevealed = $state(false);
|
||||
|
||||
const current = $derived(slides[index]);
|
||||
const veiled = $derived(Boolean(current?.blur) && !pageRevealed && !revealed[index]);
|
||||
const counter = $derived(
|
||||
labels.counter.replace("{i}", String(index + 1)).replace("{n}", String(slides.length)),
|
||||
);
|
||||
@@ -25,6 +32,7 @@
|
||||
if (i < 0 || i >= slides.length) return;
|
||||
opener = document.activeElement;
|
||||
index = i;
|
||||
pageRevealed = document.querySelector(".cw-reveal-input:checked") !== null;
|
||||
open = true;
|
||||
await tick();
|
||||
dialogEl?.querySelector(".close")?.focus();
|
||||
@@ -151,9 +159,11 @@
|
||||
<div class="bar">
|
||||
<!-- Arrowing to another photo announces its position and its caption: focus stays on
|
||||
the button, so nothing else would say which photo is now showing. -->
|
||||
<span class="count" aria-live="polite"
|
||||
>{counter}<span class="sr-only"> — {current.alt}</span></span
|
||||
>
|
||||
<span class="count" aria-live="polite">
|
||||
{counter}<span class="sr-only">
|
||||
— {current.alt}{veiled && current.warning ? ` — ${current.warning}` : ""}
|
||||
</span>
|
||||
</span>
|
||||
<button type="button" class="close" onclick={close} aria-label={labels.close}>✕</button>
|
||||
</div>
|
||||
|
||||
@@ -162,8 +172,10 @@
|
||||
class="nav prev"
|
||||
onclick={prev}
|
||||
disabled={index === 0}
|
||||
aria-label={labels.prev}>‹</button
|
||||
aria-label={labels.prev}
|
||||
>
|
||||
‹
|
||||
</button>
|
||||
|
||||
<div
|
||||
class="track"
|
||||
@@ -174,6 +186,7 @@
|
||||
onpointercancel={onPointerUp}
|
||||
>
|
||||
<img
|
||||
class:veiled
|
||||
src={current.src}
|
||||
srcset={current.srcset}
|
||||
sizes="92vw"
|
||||
@@ -182,6 +195,21 @@
|
||||
alt={current.alt}
|
||||
decoding="async"
|
||||
/>
|
||||
{#if veiled}
|
||||
<div class="veil">
|
||||
{#if current.warning}<p>{current.warning}</p>{/if}
|
||||
<!-- The button goes away once used, so focus moves on to the close button. -->
|
||||
<button
|
||||
type="button"
|
||||
onclick={() => {
|
||||
revealed[index] = true;
|
||||
keepFocus();
|
||||
}}
|
||||
>
|
||||
{labels.reveal ?? "Show"}
|
||||
</button>
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
<button
|
||||
@@ -189,8 +217,10 @@
|
||||
class="nav next"
|
||||
onclick={next}
|
||||
disabled={index === slides.length - 1}
|
||||
aria-label={labels.next}>›</button
|
||||
aria-label={labels.next}
|
||||
>
|
||||
›
|
||||
</button>
|
||||
|
||||
<!-- The same words are the image's alt and the dialog's description (aria-describedby
|
||||
still resolves a hidden node), so the visible copy is hidden from the reading order
|
||||
@@ -275,6 +305,43 @@
|
||||
block-size: auto;
|
||||
object-fit: contain;
|
||||
}
|
||||
.track {
|
||||
position: relative;
|
||||
}
|
||||
.track img.veiled {
|
||||
filter: blur(1.5rem) saturate(0.6);
|
||||
clip-path: inset(0);
|
||||
}
|
||||
.veil {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
display: grid;
|
||||
place-content: center;
|
||||
justify-items: center;
|
||||
gap: 0.75rem;
|
||||
padding: 1rem;
|
||||
text-align: center;
|
||||
color: var(--text);
|
||||
}
|
||||
.veil p {
|
||||
margin: 0;
|
||||
padding: 0.35rem 0.75rem;
|
||||
border-radius: var(--radius-control);
|
||||
background: color-mix(in srgb, var(--bg) 80%, transparent);
|
||||
font-size: var(--text-meta);
|
||||
}
|
||||
.veil button {
|
||||
min-block-size: 2.75rem;
|
||||
padding: 0.5rem 1.1rem;
|
||||
border: 1px solid var(--line-strong);
|
||||
border-radius: var(--radius-control);
|
||||
background: var(--bg);
|
||||
color: var(--text);
|
||||
cursor: pointer;
|
||||
}
|
||||
.veil button:hover {
|
||||
border-color: var(--accent);
|
||||
}
|
||||
.caption {
|
||||
grid-column: 1 / -1;
|
||||
grid-row: 3;
|
||||
|
||||
@@ -5,6 +5,7 @@ import { type BlogEntry, readingTime } from "../lib/collections";
|
||||
import { sectionPath, type Locale } from "../i18n/routing";
|
||||
import { useTranslations } from "../i18n";
|
||||
import { formatDate, isoDate } from "../lib/format";
|
||||
import { labelNames, needsBlur } from "../lib/content-labels";
|
||||
|
||||
interface Props {
|
||||
entry: BlogEntry;
|
||||
@@ -18,13 +19,20 @@ const Title = `h${headingLevel}` as const;
|
||||
const t = useTranslations(locale);
|
||||
const href = sectionPath("blog", locale, entry.id);
|
||||
const mins = readingTime(entry.body);
|
||||
// A labelled or age-rated post: its cover stays blurred here (no "show" box on a card — open
|
||||
// the post), and the card names the labels and any age rating.
|
||||
const blurCover = needsBlur(entry.data.contentWarning) || Boolean(entry.data.ageRating);
|
||||
const warning = [
|
||||
...labelNames(entry.data.contentWarning, t.labels),
|
||||
...(entry.data.ageRating ? [entry.data.ageRating] : []),
|
||||
].join(" · ");
|
||||
---
|
||||
|
||||
<article class="card">
|
||||
<a class="card-link" href={href}>
|
||||
{
|
||||
(entry.data.cover || entry.data.coverMedia) && (
|
||||
<div class="card-cover">
|
||||
<div class="card-cover" data-cw-blur={blurCover ? "" : undefined}>
|
||||
{entry.data.cover ? (
|
||||
<Image
|
||||
src={entry.data.cover}
|
||||
@@ -53,6 +61,15 @@ const mins = readingTime(entry.body);
|
||||
<span class="dot" aria-hidden="true">·</span>
|
||||
<span>{mins} {t.post.minRead}</span>
|
||||
</div>
|
||||
{
|
||||
warning && (
|
||||
<p class="card-cw">
|
||||
<span aria-hidden="true">⚠</span>
|
||||
<span class="sr-only">{t.cw.title}:</span>
|
||||
{warning}
|
||||
</p>
|
||||
)
|
||||
}
|
||||
</div>
|
||||
</a>
|
||||
</article>
|
||||
@@ -109,4 +126,14 @@ const mins = readingTime(entry.body);
|
||||
font-family: var(--ff-mono);
|
||||
font-size: var(--text-meta);
|
||||
}
|
||||
/* The build strips whitespace between the icon and the words: the gap spaces them. */
|
||||
.card-cw {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 0.35em;
|
||||
margin-block-start: 0.5rem;
|
||||
color: color-mix(in srgb, var(--horror) 35%, var(--text));
|
||||
font-family: var(--ff-mono);
|
||||
font-size: var(--text-meta);
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,55 @@
|
||||
---
|
||||
import { Image } from "astro:assets";
|
||||
import type { ImageMetadata } from "astro";
|
||||
import MediaImage from "./MediaImage.astro";
|
||||
import type { MediaRef } from "../lib/media";
|
||||
|
||||
interface Props {
|
||||
/** A local cover (src/assets), or */
|
||||
cover?: ImageMetadata | undefined;
|
||||
/** an R2 upload; its alt text, when set in the admin, describes it (else decorative). */
|
||||
coverMedia?: (MediaRef & { alt?: string }) | undefined;
|
||||
}
|
||||
|
||||
// A post's cover image. Its own component so the post page can put it inside the age check
|
||||
// when the post is age-rated, and outside it otherwise.
|
||||
const { cover, coverMedia } = Astro.props;
|
||||
---
|
||||
|
||||
{
|
||||
(cover || coverMedia) && (
|
||||
<div class="post-cover">
|
||||
{cover ? (
|
||||
<Image
|
||||
src={cover}
|
||||
alt=""
|
||||
widths={[720, 1080, 1440]}
|
||||
sizes="(max-width: 768px) 100vw, 720px"
|
||||
fetchpriority="high"
|
||||
/>
|
||||
) : (
|
||||
coverMedia && (
|
||||
<MediaImage
|
||||
media={coverMedia}
|
||||
alt={coverMedia.alt ?? ""}
|
||||
sizes="(max-width: 768px) 100vw, 720px"
|
||||
loading="eager"
|
||||
fetchpriority="high"
|
||||
/>
|
||||
)
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
<style>
|
||||
.post-cover {
|
||||
margin-block-end: 2rem;
|
||||
}
|
||||
.post-cover :global(img) {
|
||||
inline-size: 100%;
|
||||
block-size: auto;
|
||||
border-radius: var(--radius-card);
|
||||
border: 1px solid var(--line);
|
||||
}
|
||||
</style>
|
||||
@@ -122,8 +122,10 @@
|
||||
type="button"
|
||||
class:active={size === key}
|
||||
aria-pressed={size === key}
|
||||
onclick={() => setSize(key)}>{text}</button
|
||||
onclick={() => setSize(key)}
|
||||
>
|
||||
{text}
|
||||
</button>
|
||||
{/each}
|
||||
</div>
|
||||
</div>
|
||||
@@ -135,8 +137,10 @@
|
||||
type="button"
|
||||
class:active={theme === key}
|
||||
aria-pressed={theme === key}
|
||||
onclick={() => setTheme(key)}>{text}</button
|
||||
onclick={() => setTheme(key)}
|
||||
>
|
||||
{text}
|
||||
</button>
|
||||
{/each}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -249,9 +249,9 @@
|
||||
spellcheck="false"
|
||||
/>
|
||||
<!-- The name starts with the visible "Esc" so voice control can target it (WCAG 2.5.3). -->
|
||||
<button type="button" class="close" onclick={close} aria-label={`Esc — ${labels.close}`}
|
||||
>Esc</button
|
||||
>
|
||||
<button type="button" class="close" onclick={close} aria-label={`Esc — ${labels.close}`}>
|
||||
Esc
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div class="results">
|
||||
|
||||
@@ -3,6 +3,7 @@ import { type StoryEntry } from "../lib/collections";
|
||||
import { sectionPath, type Locale } from "../i18n/routing";
|
||||
import { useTranslations } from "../i18n";
|
||||
import { formatDate, isoDate } from "../lib/format";
|
||||
import { labelNames } from "../lib/content-labels";
|
||||
|
||||
interface Props {
|
||||
entry: StoryEntry;
|
||||
@@ -18,7 +19,11 @@ const statusLabel = {
|
||||
dropped: t.story.statusDropped,
|
||||
}[entry.data.status];
|
||||
|
||||
const hasCW = entry.data.contentWarning.length > 0;
|
||||
// Every label, translated, plus the age rating — the reader decides before opening it.
|
||||
const warning = [
|
||||
...labelNames(entry.data.contentWarning, t.labels),
|
||||
...(entry.data.ageRating ? [entry.data.ageRating] : []),
|
||||
].join(" · ");
|
||||
---
|
||||
|
||||
<article class="card story">
|
||||
@@ -27,9 +32,11 @@ const hasCW = entry.data.contentWarning.length > 0;
|
||||
<div class="badges">
|
||||
<span class:list={["status", entry.data.status]}>{statusLabel}</span>
|
||||
{
|
||||
hasCW && (
|
||||
<span class="cw-badge" title={entry.data.contentWarning.join(", ")}>
|
||||
⚠ {entry.data.contentWarning[0]}
|
||||
warning && (
|
||||
<span class="cw-badge">
|
||||
<span aria-hidden="true">⚠</span>
|
||||
<span class="sr-only">{t.cw.title}:</span>
|
||||
{warning}
|
||||
</span>
|
||||
)
|
||||
}
|
||||
@@ -87,6 +94,9 @@ const hasCW = entry.data.contentWarning.length > 0;
|
||||
border-color: color-mix(in srgb, var(--ok) 45%, var(--line));
|
||||
}
|
||||
.cw-badge {
|
||||
/* The build strips whitespace between the icon and the words: the gap spaces them. */
|
||||
display: inline-flex;
|
||||
gap: 0.35em;
|
||||
padding: 0.1em 0.55em;
|
||||
border-radius: 999px;
|
||||
font-family: var(--ff-mono);
|
||||
|
||||
@@ -56,8 +56,10 @@
|
||||
class="gh-repo"
|
||||
href={`https://github.com/${item.repo}`}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer">{item.repo}</a
|
||||
rel="noopener noreferrer"
|
||||
>
|
||||
{item.repo}
|
||||
</a>
|
||||
{#if item.detail}
|
||||
<span class="gh-detail">· {item.detail}</span>
|
||||
{/if}
|
||||
|
||||
@@ -21,6 +21,7 @@
|
||||
"gallery.save": "Lưu album",
|
||||
"gallery.delete": "Xoá album",
|
||||
publish: "Xuất bản",
|
||||
"publish.auto": "Tự xuất bản",
|
||||
"denylist.add": "Chặn IP",
|
||||
"denylist.remove": "Bỏ chặn IP",
|
||||
};
|
||||
@@ -58,8 +59,8 @@
|
||||
<section class="card">
|
||||
<div class="section-head">
|
||||
<h2>Nhật ký admin</h2>
|
||||
<label class="muted small"
|
||||
>Lọc
|
||||
<label class="muted small">
|
||||
Lọc
|
||||
<select bind:value={filter}>
|
||||
<option value="">Tất cả</option>
|
||||
<option value="content">Nội dung</option>
|
||||
@@ -96,9 +97,9 @@
|
||||
<ol class="log">
|
||||
{#each data.commits as commit (commit.sha)}
|
||||
<li>
|
||||
<a href={commit.url} target="_blank" rel="noopener noreferrer"
|
||||
><code>{shortSha(commit.sha)}</code></a
|
||||
>
|
||||
<a href={commit.url} target="_blank" rel="noopener noreferrer">
|
||||
<code>{shortSha(commit.sha)}</code>
|
||||
</a>
|
||||
<span class="what">{commit.message}</span>
|
||||
<span class="muted small when" title={dateTime(commit.date)}>
|
||||
{ago(commit.date)} · {commit.author}
|
||||
|
||||
@@ -59,9 +59,9 @@
|
||||
|
||||
{#if sessionLost}
|
||||
<div class="session" role="alert">
|
||||
<span
|
||||
>Phiên đăng nhập Cloudflare Access đã hết hạn. Bản nháp đang viết vẫn được giữ trên máy.</span
|
||||
>
|
||||
<span>
|
||||
Phiên đăng nhập Cloudflare Access đã hết hạn. Bản nháp đang viết vẫn được giữ trên máy.
|
||||
</span>
|
||||
<button type="button" onclick={() => location.reload()}>Đăng nhập lại</button>
|
||||
</div>
|
||||
{/if}
|
||||
@@ -99,8 +99,10 @@
|
||||
<button
|
||||
type="button"
|
||||
class={pending.danger ? "danger" : "primary"}
|
||||
onclick={() => answer(true)}>{pending.confirmLabel}</button
|
||||
onclick={() => answer(true)}
|
||||
>
|
||||
{pending.confirmLabel}
|
||||
</button>
|
||||
</div>
|
||||
{/if}
|
||||
</dialog>
|
||||
|
||||
@@ -71,7 +71,8 @@
|
||||
function create() {
|
||||
if (!newPath || taken) return;
|
||||
const params = new URLSearchParams({ new: collection, slug: slug.trim(), lang: newLang });
|
||||
if (collection === "stories") params.set("series", series.trim());
|
||||
// No series = a one-shot story (stories/<slug>.md).
|
||||
if (collection === "stories" && series.trim()) params.set("series", series.trim());
|
||||
location.href = `/admin/edit/?${params}`;
|
||||
}
|
||||
|
||||
@@ -86,7 +87,7 @@
|
||||
<div class="page-head">
|
||||
<div>
|
||||
<h1>Nội dung</h1>
|
||||
<p>Lưu là commit vào repo nội dung; bấm “Xuất bản” để đưa lên site.</p>
|
||||
<p>Lưu hoặc xoá là commit vào repo nội dung rồi tự xuất bản lên site (thường 10–15 phút).</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -99,8 +100,8 @@
|
||||
create();
|
||||
}}
|
||||
>
|
||||
<label
|
||||
>Loại
|
||||
<label>
|
||||
Loại
|
||||
<select bind:value={collection}>
|
||||
{#each Object.values(COLLECTIONS).filter((spec) => spec.creatable) as spec (spec.id)}
|
||||
<option value={spec.id}>{spec.label}</option>
|
||||
@@ -108,10 +109,13 @@
|
||||
</select>
|
||||
</label>
|
||||
{#if collection === "stories"}
|
||||
<label>Bộ truyện (slug) <input bind:value={series} placeholder="dem-khong-tieng" /></label>
|
||||
<label>
|
||||
Bộ truyện (slug, để trống nếu truyện một chương)
|
||||
<input bind:value={series} placeholder="dem-khong-tieng" />
|
||||
</label>
|
||||
{/if}
|
||||
<label
|
||||
>Slug
|
||||
<label>
|
||||
Slug
|
||||
<input
|
||||
bind:value={slug}
|
||||
placeholder="ten-bai-viet"
|
||||
@@ -121,11 +125,11 @@
|
||||
spellcheck="false"
|
||||
/>
|
||||
</label>
|
||||
<label
|
||||
>Ngôn ngữ
|
||||
<select bind:value={newLang}
|
||||
><option value="vi">vi</option><option value="en">en</option></select
|
||||
>
|
||||
<label>
|
||||
Ngôn ngữ
|
||||
<select bind:value={newLang}>
|
||||
<option value="vi">vi</option><option value="en">en</option>
|
||||
</select>
|
||||
</label>
|
||||
<button type="submit" class="primary" disabled={!newPath || taken}>Tạo</button>
|
||||
</form>
|
||||
@@ -179,9 +183,9 @@
|
||||
{:else if groups.length === 0}
|
||||
<p class="muted">
|
||||
{#if filtered}
|
||||
Không có mục nào khớp bộ lọc. <button type="button" class="ghost" onclick={clearFilters}
|
||||
>Xoá bộ lọc</button
|
||||
>
|
||||
Không có mục nào khớp bộ lọc. <button type="button" class="ghost" onclick={clearFilters}>
|
||||
Xoá bộ lọc
|
||||
</button>
|
||||
{:else}
|
||||
Repo nội dung chưa có bài nào.
|
||||
{/if}
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
import { onMount } from "svelte";
|
||||
import { api, describeError } from "./api";
|
||||
import { ago, dateTime, shortSha } from "./format";
|
||||
import { PHASE_TEXT } from "@/lib/admin/publish-phase";
|
||||
|
||||
/**
|
||||
* @typedef {{ id: string; label: string; total: number; drafts: number; vi: number; en: number }} CollectionCount
|
||||
@@ -11,7 +12,7 @@
|
||||
* widgets: { yt: string; steam: string; gh: string; lastRun: string } | null;
|
||||
* config: import("@/lib/admin/status").ConfigStatus;
|
||||
* }} Overview
|
||||
* @typedef {{ contentHead: string; published: string; pr: { number: number; url: string; checks: string | null } | null; run: { status: string; conclusion: string | null; url: string } | null }} Publish
|
||||
* @typedef {{ contentHead: string; published: string; live: string | null; phase: import("@/lib/admin/publish-phase").PublishPhase; pr: { number: number; url: string; checks: string | null } | null; run: { status: string; conclusion: string | null; url: string } | null }} Publish
|
||||
*/
|
||||
|
||||
/** @type {Overview | null} */
|
||||
@@ -60,8 +61,10 @@
|
||||
<a
|
||||
href={`https://github.com/poli0981/poli0981-dev/commit/${overview.config.version.commit}`}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"><code>{shortSha(overview.config.version.commit)}</code></a
|
||||
rel="noopener noreferrer"
|
||||
>
|
||||
<code>{shortSha(overview.config.version.commit)}</code>
|
||||
</a>
|
||||
{/if}
|
||||
· triển khai {ago(overview.config.version.timestamp)}
|
||||
</p>
|
||||
@@ -89,11 +92,13 @@
|
||||
{#if overview.content}
|
||||
<table>
|
||||
<thead>
|
||||
<tr
|
||||
><th scope="col">Loại</th><th scope="col">Tổng</th><th scope="col">vi</th><th
|
||||
scope="col">en</th
|
||||
><th scope="col">Nháp</th></tr
|
||||
>
|
||||
<tr>
|
||||
<th scope="col">Loại</th><th scope="col">Tổng</th><th scope="col">vi</th><th
|
||||
scope="col"
|
||||
>
|
||||
en
|
||||
</th><th scope="col">Nháp</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{#each overview.content.collections as c (c.id)}
|
||||
@@ -102,10 +107,9 @@
|
||||
<td>{c.total}</td>
|
||||
<td>{c.vi}</td>
|
||||
<td>{c.en}</td>
|
||||
<td
|
||||
>{#if c.drafts}<span class="pill" data-tone="warn">{c.drafts}</span
|
||||
>{:else}0{/if}</td
|
||||
>
|
||||
<td>
|
||||
{#if c.drafts}<span class="pill" data-tone="warn">{c.drafts}</span>{:else}0{/if}
|
||||
</td>
|
||||
</tr>
|
||||
{/each}
|
||||
</tbody>
|
||||
@@ -122,22 +126,26 @@
|
||||
<section class="card">
|
||||
<h2>Xuất bản</h2>
|
||||
{#if publish}
|
||||
{#if publish.contentHead === publish.published}
|
||||
<p><span class="pill" data-tone="ok">Đã đồng bộ</span></p>
|
||||
<p>
|
||||
<span class="pill" data-tone={PHASE_TEXT[publish.phase].tone}>
|
||||
{PHASE_TEXT[publish.phase].label}
|
||||
</span>
|
||||
</p>
|
||||
<p class="muted small">
|
||||
Repo nội dung <code>{shortSha(publish.contentHead)}</code> · đã merge
|
||||
<code>{shortSha(publish.published)}</code>
|
||||
{#if publish.live}· đang chạy <code>{shortSha(publish.live)}</code>{/if}
|
||||
</p>
|
||||
{#if publish.phase === "deploying"}
|
||||
<p class="muted small">
|
||||
Site đang dùng nội dung <code>{shortSha(publish.published)}</code>.
|
||||
</p>
|
||||
{:else}
|
||||
<p><span class="pill" data-tone="warn">Có thay đổi chưa xuất bản</span></p>
|
||||
<p class="muted small">
|
||||
Repo <code>{shortSha(publish.contentHead)}</code> · site
|
||||
<code>{shortSha(publish.published)}</code>
|
||||
Thường mất 1–3 phút sau khi merge. Lâu hơn: kiểm tra Workers Builds trên Cloudflare.
|
||||
</p>
|
||||
{/if}
|
||||
{#if publish.run?.conclusion === "failure"}
|
||||
{#if publish.phase === "failed" && publish.run}
|
||||
<p class="small">
|
||||
<span class="pill" data-tone="err">Lần chạy gần nhất lỗi</span>
|
||||
<a href={publish.run.url} target="_blank" rel="noopener noreferrer">Xem log ↗</a>
|
||||
<a href={publish.pr?.url ?? publish.run.url} target="_blank" rel="noopener noreferrer">
|
||||
Xem lỗi ↗
|
||||
</a>
|
||||
</p>
|
||||
{/if}
|
||||
{:else}
|
||||
@@ -150,15 +158,15 @@
|
||||
<p><a href="/admin/media/">{overview.media.count} ảnh</a> trong thư viện R2.</p>
|
||||
{#if overview.widgets}
|
||||
<p class="pills">
|
||||
<span class="pill" data-tone={tone(overview.widgets.yt)}
|
||||
>YouTube {overview.widgets.yt}</span
|
||||
>
|
||||
<span class="pill" data-tone={tone(overview.widgets.steam)}
|
||||
>Steam {overview.widgets.steam}</span
|
||||
>
|
||||
<span class="pill" data-tone={tone(overview.widgets.gh)}
|
||||
>GitHub {overview.widgets.gh}</span
|
||||
>
|
||||
<span class="pill" data-tone={tone(overview.widgets.yt)}>
|
||||
YouTube {overview.widgets.yt}
|
||||
</span>
|
||||
<span class="pill" data-tone={tone(overview.widgets.steam)}>
|
||||
Steam {overview.widgets.steam}
|
||||
</span>
|
||||
<span class="pill" data-tone={tone(overview.widgets.gh)}>
|
||||
GitHub {overview.widgets.gh}
|
||||
</span>
|
||||
</p>
|
||||
<p class="muted small" title={dateTime(overview.widgets.lastRun)}>
|
||||
Cron widgets chạy {ago(overview.widgets.lastRun)}
|
||||
|
||||
@@ -6,6 +6,7 @@
|
||||
import { confirmAction, toast } from "./ui";
|
||||
import { dateTime } from "./format";
|
||||
import { collectionOf, newEntryPath, validateFrontmatter } from "@/lib/admin/collections";
|
||||
import { afterSaveMessage } from "@/lib/admin/publish-phase";
|
||||
import { mediaFallbackSrc, mediaPictureHtml } from "@/lib/media";
|
||||
|
||||
/** @type {{ path?: string | null; create?: { collection: string; slug: string; lang: string; series?: string } | null }} */
|
||||
@@ -48,10 +49,13 @@
|
||||
const field = spec?.fields.find((f) => f.key === e.field);
|
||||
const message = {
|
||||
required: "Bắt buộc.",
|
||||
type: "Sai kiểu dữ liệu.",
|
||||
type: field?.integer ? "Cần một số nguyên." : "Sai kiểu dữ liệu.",
|
||||
option: "Chọn một giá trị trong danh sách.",
|
||||
max: `Tối đa ${field?.max ?? ""} ký tự.`,
|
||||
format: field?.type === "url" ? "Cần một URL http(s)." : "Sai định dạng.",
|
||||
min: `Nhỏ nhất là ${field?.min ?? ""}.`,
|
||||
conflict: "Bài đã có ảnh bìa local (cover trong file) — chỉ được dùng một trong hai.",
|
||||
missing: "Album này chưa có ảnh — tạo album ở trang Gallery trước.",
|
||||
}[e.code];
|
||||
return [e.field, message];
|
||||
}),
|
||||
@@ -200,7 +204,9 @@
|
||||
sha = result.sha;
|
||||
dirty = false;
|
||||
clearDraft();
|
||||
toast("Đã lưu vào repo nội dung — bấm “Xuất bản” để đưa lên site.");
|
||||
const message = afterSaveMessage(result.publish, "Đã lưu");
|
||||
toast(message.text, message.kind);
|
||||
if (message.queued) dispatchEvent(new Event("admin:published"));
|
||||
if (isNew) {
|
||||
isNew = false;
|
||||
history.replaceState(
|
||||
@@ -265,6 +271,19 @@
|
||||
touch();
|
||||
}
|
||||
|
||||
/**
|
||||
* Tick or untick one option of a multiselect; the list keeps the options' own order, and an
|
||||
* empty list is dropped from the frontmatter on save.
|
||||
* @param {{ key: string; options?: readonly string[] }} field @param {string} option @param {boolean} on
|
||||
*/
|
||||
function toggleOption(field, option, on) {
|
||||
/** @type {string[]} */
|
||||
const before = data[field.key] ?? [];
|
||||
const chosen = on ? [...before, option] : before.filter((item) => item !== option);
|
||||
data[field.key] = (field.options ?? []).filter((item) => chosen.includes(item));
|
||||
touch();
|
||||
}
|
||||
|
||||
/** @param {string} key */
|
||||
const invalid = (key) => triedSave && key in fieldError;
|
||||
</script>
|
||||
@@ -291,8 +310,10 @@
|
||||
onclick={save}
|
||||
disabled={saving || loading || Boolean(loadError)}
|
||||
aria-keyshortcuts="Control+S Meta+S"
|
||||
title="Lưu (Ctrl/⌘+S)">Lưu</button
|
||||
title="Lưu (Ctrl/⌘+S)"
|
||||
>
|
||||
Lưu
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -321,22 +342,69 @@
|
||||
{@const errorId = `err-${field.key}`}
|
||||
<div class="field">
|
||||
{#if field.type === "checkbox"}
|
||||
<label class="check"
|
||||
><input type="checkbox" bind:checked={data[field.key]} /> {field.label}</label
|
||||
>
|
||||
<label class="check">
|
||||
<input type="checkbox" bind:checked={data[field.key]} />
|
||||
{field.label}
|
||||
</label>
|
||||
{:else if field.type === "media"}
|
||||
<span class="label">{field.label}</span>
|
||||
{#if data[field.key]?.id}
|
||||
<img class="cover" src={mediaFallbackSrc(data[field.key])} alt="" />
|
||||
<div class="row">
|
||||
<button type="button" onclick={() => (picking = "cover")}>Đổi ảnh</button>
|
||||
<button type="button" onclick={() => ((data[field.key] = undefined), touch())}
|
||||
>Bỏ</button
|
||||
>
|
||||
<button type="button" onclick={() => ((data[field.key] = undefined), touch())}>
|
||||
Bỏ
|
||||
</button>
|
||||
</div>
|
||||
<!-- The alt travels with this post: picking copies the library's text once,
|
||||
and editing it here changes only this cover, not the library. -->
|
||||
<label>
|
||||
<span class="label">Mô tả ảnh bìa (alt)</span>
|
||||
<input
|
||||
maxlength="300"
|
||||
value={data[field.key].alt ?? ""}
|
||||
oninput={(event) => {
|
||||
const alt = event.currentTarget.value.trim();
|
||||
const next = { ...data[field.key] };
|
||||
if (alt) next.alt = alt;
|
||||
else delete next.alt;
|
||||
data[field.key] = next;
|
||||
}}
|
||||
placeholder="Ảnh cho thấy gì — để trống nếu chỉ trang trí"
|
||||
/>
|
||||
</label>
|
||||
{:else}
|
||||
<button type="button" onclick={() => (picking = "cover")}>Chọn ảnh bìa</button>
|
||||
{/if}
|
||||
{#if invalid(field.key)}
|
||||
<span class="field-error" id={errorId}>{fieldError[field.key]}</span>
|
||||
{/if}
|
||||
{:else if field.type === "multiselect"}
|
||||
<fieldset
|
||||
class="multi"
|
||||
aria-describedby={invalid(field.key)
|
||||
? errorId
|
||||
: field.hint
|
||||
? `hint-${field.key}`
|
||||
: undefined}
|
||||
>
|
||||
<legend class="label">{field.label}</legend>
|
||||
{#each field.options ?? [] as option (option)}
|
||||
<label class="check">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={(data[field.key] ?? []).includes(option)}
|
||||
onchange={(event) => toggleOption(field, option, event.currentTarget.checked)}
|
||||
/>
|
||||
{field.optionLabels?.[option] ?? option}
|
||||
</label>
|
||||
{/each}
|
||||
</fieldset>
|
||||
{#if invalid(field.key)}
|
||||
<span class="field-error" id={errorId}>{fieldError[field.key]}</span>
|
||||
{:else if field.hint}
|
||||
<span class="hint" id={`hint-${field.key}`}>{field.hint}</span>
|
||||
{/if}
|
||||
{:else}
|
||||
<label>
|
||||
<span class="label">{field.label}{field.required ? " *" : ""}</span>
|
||||
@@ -354,14 +422,16 @@
|
||||
aria-describedby={invalid(field.key) ? errorId : undefined}
|
||||
>
|
||||
<option value={undefined}>—</option>
|
||||
{#each field.options ?? [] as option (option)}<option value={option}
|
||||
>{option}</option
|
||||
>{/each}
|
||||
{#each field.options ?? [] as option (option)}<option value={option}>
|
||||
{option}
|
||||
</option>{/each}
|
||||
</select>
|
||||
{:else if field.type === "tags"}
|
||||
<!-- On every keystroke, not on change: Ctrl/⌘+S while the cursor is still
|
||||
here must save what is typed, and `change` only fires on blur. -->
|
||||
<input
|
||||
value={(data[field.key] ?? []).join(", ")}
|
||||
onchange={(event) => setTags(field.key, event.currentTarget.value)}
|
||||
oninput={(event) => setTags(field.key, event.currentTarget.value)}
|
||||
placeholder="cách nhau bởi dấu phẩy"
|
||||
/>
|
||||
{:else if field.type === "number"}
|
||||
@@ -412,8 +482,10 @@
|
||||
aria-controls="panel-edit"
|
||||
aria-selected={tab === "edit"}
|
||||
tabindex={tab === "edit" ? 0 : -1}
|
||||
onclick={() => (tab = "edit")}>Soạn</button
|
||||
onclick={() => (tab = "edit")}
|
||||
>
|
||||
Soạn
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
role="tab"
|
||||
@@ -421,11 +493,14 @@
|
||||
aria-controls="panel-preview"
|
||||
aria-selected={tab === "preview"}
|
||||
tabindex={tab === "preview" ? 0 : -1}
|
||||
onclick={() => (tab = "preview")}>Xem trước</button
|
||||
onclick={() => (tab = "preview")}
|
||||
>
|
||||
Xem trước
|
||||
</button>
|
||||
</div>
|
||||
<button type="button" class="insert" onclick={() => (picking = "insert")}>Chèn ảnh</button
|
||||
>
|
||||
<button type="button" class="insert" onclick={() => (picking = "insert")}>
|
||||
Chèn ảnh
|
||||
</button>
|
||||
</div>
|
||||
{#if tab === "edit"}
|
||||
<div role="tabpanel" id="panel-edit" aria-labelledby="tab-edit">
|
||||
@@ -537,6 +612,18 @@
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
.multi {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fill, minmax(10rem, 1fr));
|
||||
gap: 0.35rem 0.75rem;
|
||||
margin: 0;
|
||||
padding: 0.6rem 0.75rem 0.75rem;
|
||||
border: 1px solid var(--line);
|
||||
border-radius: var(--radius-control);
|
||||
}
|
||||
.multi legend {
|
||||
padding-inline: 0.25rem;
|
||||
}
|
||||
.cover {
|
||||
display: block;
|
||||
inline-size: 100%;
|
||||
|
||||
@@ -4,9 +4,12 @@
|
||||
import MediaPicker from "./MediaPicker.svelte";
|
||||
import { confirmAction, toast } from "./ui";
|
||||
import { SLUG_PATTERN } from "@/lib/admin/collections";
|
||||
import { afterSaveMessage } from "@/lib/admin/publish-phase";
|
||||
import { LABEL_IDS } from "@/lib/content-labels";
|
||||
import { mediaFallbackSrc } from "@/lib/media";
|
||||
import vi from "@/i18n/vi";
|
||||
|
||||
/** @typedef {{ id: string; w: number; h: number; caption: { vi: string; en: string } }} Photo */
|
||||
/** @typedef {{ id: string; w: number; h: number; caption: { vi: string; en: string }; contentWarning?: string[] }} Photo */
|
||||
/** @typedef {{ album: string; titles: Record<string, string>; photos: Photo[]; sha: string | null; coverIndex: number; local: number }} Album */
|
||||
/** @typedef {{ album: string; titles: Record<string, string>; photos: Photo[]; sha: string | null; local: number; coverId: string | null }} Editing */
|
||||
|
||||
@@ -119,6 +122,19 @@
|
||||
picking = false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Tick or untick one of a photo's labels; the list keeps the label order, and a photo with
|
||||
* none has no `contentWarning` key at all in the saved JSON.
|
||||
* @param {Photo} photo @param {string} id @param {boolean} on
|
||||
*/
|
||||
function togglePhotoLabel(photo, id, on) {
|
||||
const before = photo.contentWarning ?? [];
|
||||
const chosen = on ? [...before, id] : before.filter((label) => label !== id);
|
||||
const labels = LABEL_IDS.filter((label) => chosen.includes(label));
|
||||
if (labels.length > 0) photo.contentWarning = labels;
|
||||
else delete photo.contentWarning;
|
||||
}
|
||||
|
||||
/** @param {Photo} photo */
|
||||
function removePhoto(photo) {
|
||||
if (!current) return;
|
||||
@@ -143,7 +159,7 @@
|
||||
const cover = current.photos.findIndex((p) => p.id === current?.coverId);
|
||||
saving = true;
|
||||
try {
|
||||
await api("/api/admin/gallery", "PUT", {
|
||||
const result = await api("/api/admin/gallery", "PUT", {
|
||||
album,
|
||||
photos: current.photos,
|
||||
sha: current.sha,
|
||||
@@ -158,7 +174,9 @@
|
||||
}
|
||||
: {}),
|
||||
});
|
||||
toast("Đã lưu album vào repo nội dung — bấm “Xuất bản” để đưa lên site.");
|
||||
const message = afterSaveMessage(result.publish, "Đã lưu album");
|
||||
toast(message.text, message.kind);
|
||||
if (message.queued) dispatchEvent(new Event("admin:published"));
|
||||
creating = false;
|
||||
await load();
|
||||
const saved = albums.find((a) => a.album === album);
|
||||
@@ -179,8 +197,10 @@
|
||||
);
|
||||
if (!ok) return;
|
||||
try {
|
||||
await api("/api/admin/gallery", "DELETE", { album: current.album });
|
||||
toast("Đã xoá album.");
|
||||
const result = await api("/api/admin/gallery", "DELETE", { album: current.album });
|
||||
const message = afterSaveMessage(result.publish, "Đã xoá album");
|
||||
toast(message.text, message.kind);
|
||||
if (message.queued) dispatchEvent(new Event("admin:published"));
|
||||
current = null;
|
||||
baseline = "";
|
||||
await load();
|
||||
@@ -216,9 +236,9 @@
|
||||
onclick={() => open(album)}
|
||||
>
|
||||
<span>{album.titles.vi ?? album.album}</span>
|
||||
<span class="meta"
|
||||
>{album.photos.length} ảnh R2{album.local ? ` · ${album.local} ảnh repo` : ""}</span
|
||||
>
|
||||
<span class="meta">
|
||||
{album.photos.length} ảnh R2{album.local ? ` · ${album.local} ảnh repo` : ""}
|
||||
</span>
|
||||
</button>
|
||||
</li>
|
||||
{/each}
|
||||
@@ -274,14 +294,34 @@
|
||||
>
|
||||
<img src={mediaFallbackSrc(photo)} alt="" />
|
||||
<div class="captions">
|
||||
<label
|
||||
><span class="sr-only">Chú thích tiếng Việt, ảnh {index + 1}</span>
|
||||
<input bind:value={photo.caption.vi} placeholder="Chú thích (vi)" /></label
|
||||
>
|
||||
<label
|
||||
><span class="sr-only">English caption, photo {index + 1}</span>
|
||||
<input bind:value={photo.caption.en} placeholder="Caption (en)" /></label
|
||||
>
|
||||
<label>
|
||||
<span class="sr-only">Chú thích tiếng Việt, ảnh {index + 1}</span>
|
||||
<input bind:value={photo.caption.vi} placeholder="Chú thích (vi)" />
|
||||
</label>
|
||||
<label>
|
||||
<span class="sr-only">English caption, photo {index + 1}</span>
|
||||
<input bind:value={photo.caption.en} placeholder="Caption (en)" />
|
||||
</label>
|
||||
<!-- This photo's own content labels: blurred on the site when one asks for it. -->
|
||||
<details class="photo-labels">
|
||||
<summary>
|
||||
Nhãn{photo.contentWarning?.length ? ` (${photo.contentWarning.length})` : ""}
|
||||
<span class="sr-only">của ảnh {index + 1}</span>
|
||||
</summary>
|
||||
<div class="label-list">
|
||||
{#each LABEL_IDS as id (id)}
|
||||
<label class="check">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={photo.contentWarning?.includes(id) ?? false}
|
||||
onchange={(event) =>
|
||||
togglePhotoLabel(photo, id, event.currentTarget.checked)}
|
||||
/>
|
||||
{vi.labels[id]}
|
||||
</label>
|
||||
{/each}
|
||||
</div>
|
||||
</details>
|
||||
</div>
|
||||
<div class="order">
|
||||
<button
|
||||
@@ -289,25 +329,33 @@
|
||||
class="cover-pick"
|
||||
aria-pressed={current.coverId === photo.id}
|
||||
aria-label={`Đặt ảnh ${index + 1} làm ảnh bìa`}
|
||||
onclick={() => current && (current.coverId = photo.id)}>★</button
|
||||
onclick={() => current && (current.coverId = photo.id)}
|
||||
>
|
||||
★
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
aria-label={`Đưa ảnh ${index + 1} lên`}
|
||||
disabled={index === 0}
|
||||
onclick={() => move(index, index - 1)}>↑</button
|
||||
onclick={() => move(index, index - 1)}
|
||||
>
|
||||
↑
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
aria-label={`Đưa ảnh ${index + 1} xuống`}
|
||||
disabled={index === current.photos.length - 1}
|
||||
onclick={() => move(index, index + 1)}>↓</button
|
||||
onclick={() => move(index, index + 1)}
|
||||
>
|
||||
↓
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
aria-label={`Bỏ ảnh ${index + 1} khỏi album`}
|
||||
onclick={() => removePhoto(photo)}>✕</button
|
||||
onclick={() => removePhoto(photo)}
|
||||
>
|
||||
✕
|
||||
</button>
|
||||
</div>
|
||||
</li>
|
||||
{/each}
|
||||
@@ -321,9 +369,9 @@
|
||||
{#if !creating}
|
||||
<button type="button" class="danger" onclick={removeAlbum}>Xoá album</button>
|
||||
{/if}
|
||||
<button type="button" class="primary push" onclick={save} disabled={saving || !dirty}
|
||||
>{saving ? "Đang lưu…" : "Lưu album"}</button
|
||||
>
|
||||
<button type="button" class="primary push" onclick={save} disabled={saving || !dirty}>
|
||||
{saving ? "Đang lưu…" : "Lưu album"}
|
||||
</button>
|
||||
</div>
|
||||
</section>
|
||||
{/if}
|
||||
@@ -425,6 +473,23 @@
|
||||
display: grid;
|
||||
gap: 0.35rem;
|
||||
}
|
||||
.photo-labels summary {
|
||||
cursor: pointer;
|
||||
color: var(--muted);
|
||||
font-size: var(--text-meta);
|
||||
}
|
||||
.label-list {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fill, minmax(9rem, 1fr));
|
||||
gap: 0.25rem 0.75rem;
|
||||
padding-block: 0.35rem;
|
||||
font-size: var(--text-meta);
|
||||
}
|
||||
.label-list .check {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.4rem;
|
||||
}
|
||||
.order {
|
||||
display: flex;
|
||||
gap: 0.25rem;
|
||||
|
||||
@@ -159,8 +159,8 @@
|
||||
}}
|
||||
>
|
||||
<p>Kéo thả ảnh vào đây, hoặc</p>
|
||||
<label class="button pick"
|
||||
>Chọn tệp
|
||||
<label class="button pick">
|
||||
Chọn tệp
|
||||
<input
|
||||
type="file"
|
||||
accept="image/*"
|
||||
@@ -254,21 +254,24 @@
|
||||
{/if}
|
||||
</p>
|
||||
<div class="row">
|
||||
<button type="button" onclick={() => copy(mediaPictureHtml(item, item.alt), "HTML")}
|
||||
>Copy HTML</button
|
||||
>
|
||||
<button type="button" onclick={() => copy(mediaPictureHtml(item, item.alt), "HTML")}>
|
||||
Copy HTML
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onclick={() => copy(`{ id: "${item.id}", w: ${item.w}, h: ${item.h} }`, "ID")}
|
||||
>Copy ID</button
|
||||
>
|
||||
Copy ID
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="danger"
|
||||
onclick={() => remove(item)}
|
||||
disabled={used.length > 0}
|
||||
title={used.length ? "Gỡ ảnh khỏi các bài trước khi xoá" : undefined}>Xoá</button
|
||||
title={used.length ? "Gỡ ảnh khỏi các bài trước khi xoá" : undefined}
|
||||
>
|
||||
Xoá
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</li>
|
||||
|
||||
@@ -24,6 +24,8 @@
|
||||
let items = $state([]);
|
||||
let status = $state("");
|
||||
let query = $state("");
|
||||
/** Alt text for the next upload: inserted images and covers copy it from the library. */
|
||||
let uploadAlt = $state("");
|
||||
/** @type {string[]} */
|
||||
let selected = $state([]);
|
||||
/** @type {HTMLDialogElement | undefined} */
|
||||
@@ -67,7 +69,7 @@
|
||||
for (const file of Array.from(input.files ?? [])) {
|
||||
status = `Đang xử lý ${file.name}…`;
|
||||
try {
|
||||
const { item } = await uploadImage(file);
|
||||
const { item } = await uploadImage(file, uploadAlt.trim());
|
||||
items = cache = [item, ...items.filter((i) => i.id !== item.id)];
|
||||
if (multiple && !selected.includes(item.id)) selected = [...selected, item.id];
|
||||
status = "";
|
||||
@@ -76,6 +78,7 @@
|
||||
}
|
||||
}
|
||||
input.value = "";
|
||||
uploadAlt = "";
|
||||
}
|
||||
|
||||
/** @param {MediaItem} item */
|
||||
@@ -98,9 +101,16 @@
|
||||
<div class="top">
|
||||
<strong id="picker-title">{multiple ? "Chọn ảnh (nhiều)" : "Chọn ảnh"}</strong>
|
||||
<input type="search" bind:value={query} placeholder="Tìm ảnh" aria-label="Tìm ảnh" />
|
||||
<label class="button upload"
|
||||
>Tải ảnh lên <input type="file" accept="image/*" multiple onchange={upload} /></label
|
||||
>
|
||||
<input
|
||||
class="alt"
|
||||
bind:value={uploadAlt}
|
||||
maxlength="300"
|
||||
placeholder="Mô tả (alt) cho ảnh sắp tải"
|
||||
aria-label="Mô tả (alt) cho ảnh sắp tải lên"
|
||||
/>
|
||||
<label class="button upload">
|
||||
Tải ảnh lên <input type="file" accept="image/*" multiple onchange={upload} />
|
||||
</label>
|
||||
<button type="button" onclick={() => load(true)} title="Tải lại danh sách">↻</button>
|
||||
<button type="button" onclick={onclose}>Đóng</button>
|
||||
</div>
|
||||
@@ -152,7 +162,8 @@
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
.top input[type="search"] {
|
||||
.top input[type="search"],
|
||||
.top .alt {
|
||||
flex: 1;
|
||||
min-inline-size: 10rem;
|
||||
}
|
||||
|
||||
@@ -2,9 +2,11 @@
|
||||
import { onMount } from "svelte";
|
||||
import { api, describeError } from "./api";
|
||||
import { toast } from "./ui";
|
||||
import { canPublish, PHASE_TEXT } from "@/lib/admin/publish-phase";
|
||||
|
||||
/** @typedef {{ number: number; url: string; autoMerge: boolean; checks: string | null }} PullRequest */
|
||||
/** @typedef {{ contentHead: string; published: string; pr: PullRequest | null; run: { status: string; conclusion: string | null; url: string } | null; singleToken?: boolean }} Status */
|
||||
/** @typedef {import("@/lib/admin/publish-phase").PublishPhase} Phase */
|
||||
/** @typedef {{ contentHead: string; published: string; live: string | null; phase: Phase; pr: PullRequest | null; run: { status: string; conclusion: string | null; url: string } | null; singleToken?: boolean }} Status */
|
||||
|
||||
/** @type {Status | null} */
|
||||
let status = $state(null);
|
||||
@@ -12,14 +14,7 @@
|
||||
let failedToLoad = $state(false);
|
||||
|
||||
const short = (/** @type {string} */ sha) => sha.slice(0, 7);
|
||||
const pending = $derived(status !== null && status.contentHead !== status.published);
|
||||
const running = $derived(
|
||||
status !== null && (status.run?.status === "in_progress" || status.run?.status === "queued"),
|
||||
);
|
||||
const checking = $derived(status?.pr?.checks === "pending");
|
||||
const runFailed = $derived(
|
||||
status !== null && !status.pr && !running && status.run?.conclusion === "failure",
|
||||
);
|
||||
const moving = $derived(status?.phase === "building" || status?.phase === "deploying");
|
||||
|
||||
/** @type {ReturnType<typeof setTimeout> | undefined} */
|
||||
let timer;
|
||||
@@ -28,7 +23,7 @@
|
||||
function schedule() {
|
||||
clearTimeout(timer);
|
||||
if (document.visibilityState !== "visible") return;
|
||||
const delay = running || checking ? 5_000 : pending ? 30_000 : 60_000;
|
||||
const delay = moving ? 10_000 : status?.phase === "pending" ? 30_000 : 60_000;
|
||||
timer = setTimeout(refresh, delay);
|
||||
}
|
||||
|
||||
@@ -42,12 +37,13 @@
|
||||
schedule();
|
||||
}
|
||||
|
||||
// Saves publish on their own; this is the retry for a failed or never-started publish.
|
||||
async function publish() {
|
||||
busy = true;
|
||||
try {
|
||||
await api("/api/admin/publish", "POST");
|
||||
toast("Đã gửi yêu cầu xuất bản — workflow đang chạy.");
|
||||
if (status) status.run = { status: "queued", conclusion: null, url: status.run?.url ?? "" };
|
||||
if (status) status.phase = "building";
|
||||
schedule();
|
||||
} catch (error) {
|
||||
toast(describeError(error), "error");
|
||||
@@ -58,13 +54,17 @@
|
||||
|
||||
onMount(() => {
|
||||
void refresh();
|
||||
// A save elsewhere in the admin just started a publish: look again soon.
|
||||
const onSaved = () => setTimeout(refresh, 3_000);
|
||||
const onVisible = () => {
|
||||
if (document.visibilityState === "visible") void refresh();
|
||||
else clearTimeout(timer);
|
||||
};
|
||||
addEventListener("admin:published", onSaved);
|
||||
document.addEventListener("visibilitychange", onVisible);
|
||||
return () => {
|
||||
clearTimeout(timer);
|
||||
removeEventListener("admin:published", onSaved);
|
||||
document.removeEventListener("visibilitychange", onVisible);
|
||||
};
|
||||
});
|
||||
@@ -74,46 +74,32 @@
|
||||
{#if status}
|
||||
{#if status.pr}
|
||||
<a href={status.pr.url} target="_blank" rel="noopener noreferrer">PR #{status.pr.number}</a>
|
||||
<span class="state" data-state={status.pr.checks ?? "pending"}>
|
||||
{status.pr.checks === "success"
|
||||
? status.pr.autoMerge
|
||||
? "build xanh — đang merge"
|
||||
: "build xanh — chờ review"
|
||||
: status.pr.checks === "failure"
|
||||
? "build lỗi"
|
||||
: "đang build…"}
|
||||
</span>
|
||||
{:else if running}
|
||||
<span class="state" data-state="pending">đang chuẩn bị PR…</span>
|
||||
{:else if runFailed && status.run}
|
||||
<a
|
||||
class="state"
|
||||
data-state="failure"
|
||||
href={status.run.url}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer">lần xuất bản trước lỗi ↗</a
|
||||
>
|
||||
{:else if pending}
|
||||
<span class="state" data-state="pending">có thay đổi chưa xuất bản</span>
|
||||
{:else}
|
||||
<span class="state" data-state="success">đã xuất bản ({short(status.published)})</span>
|
||||
{:else if status.phase === "failed" && status.run}
|
||||
<a href={status.run.url} target="_blank" rel="noopener noreferrer">log ↗</a>
|
||||
{/if}
|
||||
<span class="state" data-tone={PHASE_TEXT[status.phase].tone}>
|
||||
{PHASE_TEXT[status.phase].label}
|
||||
{#if status.phase === "live" && status.live}({short(status.live)}){/if}
|
||||
</span>
|
||||
{#if status.singleToken}
|
||||
<a
|
||||
class="warn"
|
||||
href="/admin/security/"
|
||||
title="Xuất bản đang dùng chung token nội dung — xem trang Bảo mật"
|
||||
>⚠<span class="sr-only">Xuất bản đang dùng chung token nội dung</span></a
|
||||
>
|
||||
⚠<span class="sr-only">Xuất bản đang dùng chung token nội dung</span>
|
||||
</a>
|
||||
{/if}
|
||||
<button
|
||||
type="button"
|
||||
class="primary"
|
||||
onclick={publish}
|
||||
disabled={busy || !pending || running || checking}>Xuất bản</button
|
||||
disabled={busy || !canPublish(status.phase)}
|
||||
>
|
||||
{status.phase === "failed" ? "Xuất bản lại" : "Xuất bản"}
|
||||
</button>
|
||||
{:else if failedToLoad}
|
||||
<span class="state" data-state="failure">không đọc được trạng thái xuất bản</span>
|
||||
<span class="state" data-tone="err">không đọc được trạng thái xuất bản</span>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
@@ -128,10 +114,13 @@
|
||||
.state {
|
||||
color: var(--muted);
|
||||
}
|
||||
.state[data-state="success"] {
|
||||
.state[data-tone="ok"] {
|
||||
color: var(--ok);
|
||||
}
|
||||
.state[data-state="failure"] {
|
||||
.state[data-tone="warn"] {
|
||||
color: var(--warn);
|
||||
}
|
||||
.state[data-tone="err"] {
|
||||
color: var(--err);
|
||||
}
|
||||
.warn {
|
||||
|
||||
@@ -100,8 +100,8 @@
|
||||
void add();
|
||||
}}
|
||||
>
|
||||
<label
|
||||
>Địa chỉ hoặc dải CIDR
|
||||
<label>
|
||||
Địa chỉ hoặc dải CIDR
|
||||
<input
|
||||
bind:value={cidr}
|
||||
required
|
||||
@@ -110,11 +110,11 @@
|
||||
spellcheck="false"
|
||||
/>
|
||||
</label>
|
||||
<label
|
||||
>Lý do <input bind:value={reason} maxlength="200" placeholder="vd. cào dữ liệu" /></label
|
||||
>
|
||||
<label
|
||||
>Thời hạn
|
||||
<label>
|
||||
Lý do <input bind:value={reason} maxlength="200" placeholder="vd. cào dữ liệu" />
|
||||
</label>
|
||||
<label>
|
||||
Thời hạn
|
||||
<select bind:value={duration}>
|
||||
<option value="1">1 giờ</option>
|
||||
<option value="24">1 ngày</option>
|
||||
@@ -146,10 +146,9 @@
|
||||
<td title={dateTime(entry.until)}>
|
||||
{entry.until ? (expired(entry) ? "đã hết hạn" : ago(entry.until)) : "không"}
|
||||
</td>
|
||||
<td
|
||||
><button type="button" class="danger" onclick={() => remove(entry)}>Gỡ</button
|
||||
></td
|
||||
>
|
||||
<td>
|
||||
<button type="button" class="danger" onclick={() => remove(entry)}>Gỡ</button>
|
||||
</td>
|
||||
</tr>
|
||||
{/each}
|
||||
</tbody>
|
||||
|
||||
@@ -1,14 +1,18 @@
|
||||
---
|
||||
import BaseLayout from "@/layouts/BaseLayout.astro";
|
||||
import Lightbox from "@/components/Lightbox.svelte";
|
||||
import { Image, getImage } from "astro:assets";
|
||||
import MediaImage from "@/components/MediaImage.astro";
|
||||
import { getImage } from "astro:assets";
|
||||
import GalleryGrid from "@/components/GalleryGrid.astro";
|
||||
import { mediaSrcset, mediaUrl, variantWidths } from "@/lib/media";
|
||||
import type { GalleryEntry } from "@/lib/collections";
|
||||
import type { GalleryPhoto } from "@/lib/gallery";
|
||||
import { sectionPath, type Locale } from "@/i18n/routing";
|
||||
import { useTranslations } from "@/i18n";
|
||||
import { formatDate } from "@/lib/format";
|
||||
import ContentNotice from "@/components/ContentNotice.astro";
|
||||
import AgeGate from "@/components/AgeGate.astro";
|
||||
import { labelNames, needsBlur } from "@/lib/content-labels";
|
||||
import { albumWarning } from "@/lib/collections";
|
||||
|
||||
interface Props {
|
||||
locale: Locale;
|
||||
@@ -18,6 +22,19 @@ interface Props {
|
||||
const { entry, photos, locale } = Astro.props as Props;
|
||||
const t = useTranslations(locale);
|
||||
|
||||
// Labels: the album's own blur every photo; a photo's own blur just that one. The notice
|
||||
// lists both, and its "Hiện ảnh" box un-blurs the page's photos and the viewer's slides.
|
||||
// The album's labels and age rating come from both language entries (same photos).
|
||||
const { labels: albumLabels, ageRating } = await albumWarning(entry.data.album);
|
||||
const albumBlur = needsBlur(albumLabels);
|
||||
const allLabels = [...new Set([...albumLabels, ...photos.flatMap((p) => p.labels)])];
|
||||
const photoBlur = photos.map((p) => albumBlur || needsBlur(p.labels));
|
||||
const anyPhotoBlur = !albumBlur && photoBlur.some(Boolean);
|
||||
const warningOf = (p: GalleryPhoto) => {
|
||||
const names = labelNames([...new Set([...albumLabels, ...p.labels])], t.labels);
|
||||
return names.length ? t.cw.photo.replace("{labels}", names.join(", ")) : "";
|
||||
};
|
||||
|
||||
// Full-size AVIF slides for the lightbox island (plain <img> with /_astro URLs → CSP-safe).
|
||||
const slides = await Promise.all(
|
||||
photos.map(async (p) => {
|
||||
@@ -30,6 +47,8 @@ const slides = await Promise.all(
|
||||
width: p.media.w,
|
||||
height: p.media.h,
|
||||
alt: p.alt[locale],
|
||||
blur: albumBlur || needsBlur(p.labels),
|
||||
warning: warningOf(p),
|
||||
};
|
||||
}
|
||||
const full = await getImage({
|
||||
@@ -44,13 +63,24 @@ const slides = await Promise.all(
|
||||
width: p.image.width,
|
||||
height: p.image.height,
|
||||
alt: p.alt[locale],
|
||||
blur: albumBlur || needsBlur(p.labels),
|
||||
warning: warningOf(p),
|
||||
};
|
||||
}),
|
||||
);
|
||||
const hrefs = slides.map((slide) => slide.src);
|
||||
const ownBlur = photoBlur.map((blurred) => blurred && !albumBlur);
|
||||
const thumbLabels = photos.map((p) =>
|
||||
[t.gallery.open, p.alt[locale], warningOf(p)].filter(Boolean).join(" — "),
|
||||
);
|
||||
---
|
||||
|
||||
<BaseLayout title={entry.data.title} description={entry.data.description} {locale}>
|
||||
<section class="page py-section">
|
||||
<section
|
||||
class="page py-section"
|
||||
data-cw-blur={albumBlur ? "" : undefined}
|
||||
data-cw-scope={anyPhotoBlur ? "" : undefined}
|
||||
>
|
||||
<nav class="crumb" aria-label={t.landmarks.breadcrumb}>
|
||||
<a href={sectionPath("gallery", locale)}>{t.nav.gallery}</a>
|
||||
<span aria-hidden="true">/</span>
|
||||
@@ -60,45 +90,23 @@ const slides = await Promise.all(
|
||||
{entry.data.description && <p class="lead">{entry.data.description}</p>}
|
||||
<p class="date">{formatDate(entry.data.date, locale)}</p>
|
||||
|
||||
{
|
||||
/* Each thumbnail links to its full-size image, so the album works without JS; the
|
||||
lightbox island takes over plain clicks once it hydrates. */
|
||||
}
|
||||
<div class="photo-grid">
|
||||
{
|
||||
photos.map((p, i) => (
|
||||
<a
|
||||
class="thumb"
|
||||
href={slides[i].src}
|
||||
data-lightbox-index={i}
|
||||
aria-label={`${t.gallery.open} — ${p.alt[locale]}`}
|
||||
>
|
||||
{p.kind === "local" ? (
|
||||
<Image
|
||||
src={p.image}
|
||||
alt=""
|
||||
widths={[400, 800]}
|
||||
sizes="(max-width: 640px) 50vw, 320px"
|
||||
loading={i === 0 ? "eager" : "lazy"}
|
||||
decoding="async"
|
||||
{...(i === 0 ? { fetchpriority: "high" as const } : {})}
|
||||
/>
|
||||
) : (
|
||||
<MediaImage
|
||||
media={p.media}
|
||||
alt=""
|
||||
sizes="(max-width: 640px) 50vw, 320px"
|
||||
loading={i === 0 ? "eager" : "lazy"}
|
||||
{...(i === 0 ? { fetchpriority: "high" as const } : {})}
|
||||
/>
|
||||
)}
|
||||
</a>
|
||||
))
|
||||
}
|
||||
</div>
|
||||
<ContentNotice labels={allLabels} ageRating={ageRating} {locale} />
|
||||
|
||||
<Lightbox client:idle {slides} labels={t.gallery} />
|
||||
{
|
||||
ageRating ? (
|
||||
<AgeGate rating={ageRating} {locale}>
|
||||
<GalleryGrid {photos} {hrefs} blurred={ownBlur} labels={thumbLabels} {locale} />
|
||||
</AgeGate>
|
||||
) : (
|
||||
<GalleryGrid {photos} {hrefs} blurred={ownBlur} labels={thumbLabels} {locale} />
|
||||
)
|
||||
}
|
||||
</section>
|
||||
{
|
||||
/* Outside the labelled section on purpose: its blur rule would otherwise also blur the
|
||||
viewer's photo, which has its own "show" button. */
|
||||
}
|
||||
<Lightbox client:idle {slides} labels={{ ...t.gallery, reveal: t.cw.reveal }} />
|
||||
</BaseLayout>
|
||||
|
||||
<style>
|
||||
@@ -126,46 +134,4 @@ const slides = await Promise.all(
|
||||
font-family: var(--ff-mono);
|
||||
font-size: var(--text-meta);
|
||||
}
|
||||
.photo-grid {
|
||||
margin-block-start: 1.5rem;
|
||||
display: grid;
|
||||
gap: 0.75rem;
|
||||
/* minmax(0, 1fr), not 1fr: a `1fr` column is at least as wide as its photos' minimum
|
||||
content size, which made the first column 235px wide and the page wider than a
|
||||
320px screen. With a zero minimum the columns stay equal. */
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
}
|
||||
@media (min-width: 640px) {
|
||||
.photo-grid {
|
||||
grid-template-columns: repeat(3, minmax(0, 1fr));
|
||||
}
|
||||
}
|
||||
@media (min-width: 960px) {
|
||||
.photo-grid {
|
||||
grid-template-columns: repeat(4, minmax(0, 1fr));
|
||||
}
|
||||
}
|
||||
.thumb {
|
||||
display: block;
|
||||
padding: 0;
|
||||
border: 1px solid var(--line);
|
||||
border-radius: var(--radius-card);
|
||||
background: var(--surface);
|
||||
overflow: clip;
|
||||
cursor: pointer;
|
||||
aspect-ratio: 1 / 1;
|
||||
transition:
|
||||
transform var(--duration-fast) var(--ease-site),
|
||||
border-color var(--duration-fast) var(--ease-site);
|
||||
}
|
||||
.thumb:hover {
|
||||
transform: translateY(-2px);
|
||||
border-color: color-mix(in srgb, var(--accent) 40%, var(--line));
|
||||
}
|
||||
.thumb :global(img) {
|
||||
display: block;
|
||||
inline-size: 100%;
|
||||
block-size: 100%;
|
||||
object-fit: cover;
|
||||
}
|
||||
</style>
|
||||
+1
-1
Submodule src/content updated: 54afc276b3...98f7692ff8.
+11
-1
@@ -2,9 +2,15 @@ import { defineCollection, type SchemaContext } from "astro:content";
|
||||
import { z } from "astro/zod";
|
||||
import { glob } from "astro/loaders";
|
||||
import { mediaRefSchema as mediaRef } from "./lib/media-schema";
|
||||
import { AGE_RATINGS, LABEL_IDS } from "./lib/content-labels";
|
||||
|
||||
const LANG = z.enum(["vi", "en"]);
|
||||
|
||||
/** Content labels (src/lib/content-labels.ts): a banner, plus blurred images for visual ones. */
|
||||
const contentWarning = z.array(z.enum(LABEL_IDS)).default([]);
|
||||
/** An age rating also folds the text away until the reader confirms their age. */
|
||||
const ageRating = z.enum(AGE_RATINGS).optional();
|
||||
|
||||
/** A cover is either a local asset (`cover`) or an R2 upload (`coverMedia`), not both. */
|
||||
const hasOneCover = (data: { cover?: unknown; coverMedia?: unknown }) =>
|
||||
!(data.cover && data.coverMedia);
|
||||
@@ -24,6 +30,8 @@ const base = ({ image }: SchemaContext) =>
|
||||
cover: image().optional(),
|
||||
coverMedia: mediaRef.optional(),
|
||||
draft: z.boolean().default(false),
|
||||
contentWarning, // e.g. ['horror', 'blood']
|
||||
ageRating,
|
||||
});
|
||||
|
||||
// Markdown/MDX files, ignoring `_`-prefixed partials.
|
||||
@@ -44,7 +52,6 @@ const stories = defineCollection({
|
||||
series: z.string().optional(),
|
||||
chapter: z.number().int().positive().optional(),
|
||||
status: z.enum(["ongoing", "complete", "dropped"]).default("ongoing"),
|
||||
contentWarning: z.array(z.string()).default([]), // e.g. ['horror', 'blood']
|
||||
})
|
||||
.refine(hasOneCover, ONE_COVER),
|
||||
});
|
||||
@@ -91,6 +98,9 @@ const gallery = defineCollection({
|
||||
description: z.string().optional(),
|
||||
album: z.string(), // = folder name under src/assets/gallery/<album>/
|
||||
coverIndex: z.number().default(0),
|
||||
// For the whole album; single photos can carry their own (captions.json, gallery-photos).
|
||||
contentWarning,
|
||||
ageRating,
|
||||
}),
|
||||
});
|
||||
|
||||
|
||||
Vendored
+2
@@ -6,6 +6,8 @@
|
||||
|
||||
/** The git commit this build was made from, or null (set by `vite.define` in astro.config.mjs). */
|
||||
declare const __BUILD_COMMIT__: string | null;
|
||||
/** The poli0981/content commit the build's src/content pointed at, or null (same place). */
|
||||
declare const __CONTENT_COMMIT__: string | null;
|
||||
|
||||
declare namespace App {
|
||||
interface Locals {
|
||||
|
||||
+32
-2
@@ -74,8 +74,38 @@ const en: UIStrings = {
|
||||
statusOngoing: "Ongoing",
|
||||
statusComplete: "Complete",
|
||||
statusDropped: "Dropped",
|
||||
cwTitle: "Content warning",
|
||||
cwHint: "Tap to read",
|
||||
},
|
||||
labels: {
|
||||
horror: "Horror",
|
||||
blood: "Blood and gore",
|
||||
jumpscare: "Jump scares",
|
||||
violence: "Violence",
|
||||
"self-harm": "Self-harm and suicide",
|
||||
death: "Death",
|
||||
politics: "Politics",
|
||||
religion: "Religion",
|
||||
"strong-language": "Strong language",
|
||||
"flashing-lights": "Flashing lights",
|
||||
spoilers: "Spoilers",
|
||||
},
|
||||
cw: {
|
||||
title: "Content warning",
|
||||
blurNote: "Images on this page are blurred.",
|
||||
reveal: "Show images",
|
||||
feedPrefix: "Content warning",
|
||||
gate: "This part is for readers aged {age} and over",
|
||||
gateHint: "select to confirm and read",
|
||||
question: "Are you {age} or older?",
|
||||
explain:
|
||||
"What follows is not suitable for readers under {age}. Your answer is kept in this browser only and is never sent anywhere.",
|
||||
yes: "Yes, I'm {age} or older",
|
||||
no: "No",
|
||||
denied: "This part is for readers aged {age} and over, so it stays hidden.",
|
||||
retry: "Choose again",
|
||||
confirmed: "You confirmed you are {age} or older in this browser.",
|
||||
reset: "Reset",
|
||||
home: "Go to the home page",
|
||||
photo: "Photo with a content warning: {labels}",
|
||||
},
|
||||
reader: {
|
||||
aria: "Reading settings",
|
||||
|
||||
+34
-2
@@ -72,8 +72,40 @@ const vi = {
|
||||
statusOngoing: "Đang ra",
|
||||
statusComplete: "Hoàn thành",
|
||||
statusDropped: "Tạm dừng",
|
||||
cwTitle: "Cảnh báo nội dung",
|
||||
cwHint: "Bấm để đọc",
|
||||
},
|
||||
// Content labels (src/lib/content-labels.ts), keyed by label id.
|
||||
labels: {
|
||||
horror: "Kinh dị",
|
||||
blood: "Máu me",
|
||||
jumpscare: "Hù doạ bất ngờ",
|
||||
violence: "Bạo lực",
|
||||
"self-harm": "Tự hại, tự sát",
|
||||
death: "Cái chết",
|
||||
politics: "Chính trị",
|
||||
religion: "Tôn giáo",
|
||||
"strong-language": "Ngôn từ mạnh",
|
||||
"flashing-lights": "Ánh sáng nhấp nháy",
|
||||
spoilers: "Tiết lộ nội dung",
|
||||
},
|
||||
// The content-warning banner and the age check ({age} = 13, 16 or 18).
|
||||
cw: {
|
||||
title: "Cảnh báo nội dung",
|
||||
blurNote: "Ảnh trong trang này được làm mờ.",
|
||||
reveal: "Hiện ảnh",
|
||||
feedPrefix: "Cảnh báo",
|
||||
gate: "Phần này dành cho người từ {age} tuổi trở lên",
|
||||
gateHint: "bấm để xác nhận và đọc",
|
||||
question: "Bạn đã đủ {age} tuổi?",
|
||||
explain:
|
||||
"Phần tiếp theo không phù hợp với người dưới {age} tuổi. Câu trả lời chỉ được lưu trên trình duyệt này, không gửi đi đâu.",
|
||||
yes: "Có, tôi đủ {age} tuổi",
|
||||
no: "Chưa",
|
||||
denied: "Phần này dành cho người từ {age} tuổi trở lên nên đang được ẩn.",
|
||||
retry: "Chọn lại",
|
||||
confirmed: "Đã xác nhận đủ {age} tuổi trên trình duyệt này.",
|
||||
reset: "Đặt lại",
|
||||
home: "Về trang chủ",
|
||||
photo: "Ảnh có cảnh báo: {labels}",
|
||||
},
|
||||
reader: {
|
||||
aria: "Tùy chỉnh đọc",
|
||||
|
||||
@@ -1,12 +1,14 @@
|
||||
---
|
||||
import { Image } from "astro:assets";
|
||||
import MediaImage from "../components/MediaImage.astro";
|
||||
import BaseLayout from "./BaseLayout.astro";
|
||||
import Prose from "../components/Prose.astro";
|
||||
import Waveline from "../components/Waveline.svelte";
|
||||
import TagPill from "../components/TagPill.astro";
|
||||
import Pagination from "../components/Pagination.astro";
|
||||
import ContentNotice from "../components/ContentNotice.astro";
|
||||
import AgeGate from "../components/AgeGate.astro";
|
||||
import PostCover from "../components/PostCover.astro";
|
||||
import type { BlogEntry } from "../lib/collections";
|
||||
import { labelNames, needsBlur } from "../lib/content-labels";
|
||||
import { useTranslations } from "../i18n";
|
||||
import { sectionPath, type Locale } from "../i18n/routing";
|
||||
import { formatDate, isoDate } from "../lib/format";
|
||||
@@ -34,8 +36,11 @@ const {
|
||||
next = null,
|
||||
} = Astro.props;
|
||||
const t = useTranslations(locale);
|
||||
const { title, description, date, updated, tags, cover, coverMedia } = entry.data;
|
||||
const { title, description, date, updated, tags, cover, coverMedia, contentWarning, ageRating } =
|
||||
entry.data;
|
||||
const blogHref = sectionPath("blog", locale);
|
||||
const blur = needsBlur(contentWarning);
|
||||
const rating = ageRating ?? labelNames(contentWarning, t.labels).join(", ");
|
||||
|
||||
const pathname = Astro.url.pathname;
|
||||
const alternates = translationHref
|
||||
@@ -58,6 +63,7 @@ const postSchema = {
|
||||
image: new URL(ogUrl("blog", entry.id), SITE.url).href,
|
||||
mainEntityOfPage: { "@type": "WebPage", "@id": canonicalUrl },
|
||||
...(tags.length > 0 ? { keywords: tags.join(", ") } : {}),
|
||||
...(rating ? { contentRating: rating } : {}),
|
||||
url: canonicalUrl,
|
||||
};
|
||||
// Mirrors the visible breadcrumb below, so the two can't drift.
|
||||
@@ -82,7 +88,7 @@ const crumbs = breadcrumbSchema([
|
||||
}}
|
||||
image={ogUrl("blog", entry.id)}
|
||||
>
|
||||
<article class="reading-column post" data-pagefind-body>
|
||||
<article class="reading-column post" data-pagefind-body data-cw-blur={blur ? "" : undefined}>
|
||||
<nav class="breadcrumb" aria-label={t.landmarks.breadcrumb} data-pagefind-ignore>
|
||||
<a href={blogHref}>{t.nav.blog}</a>
|
||||
<span aria-hidden="true">/</span>
|
||||
@@ -124,36 +130,28 @@ const crumbs = breadcrumbSchema([
|
||||
}
|
||||
</header>
|
||||
|
||||
<ContentNotice labels={contentWarning} {ageRating} {locale} />
|
||||
|
||||
{
|
||||
(cover || coverMedia) && (
|
||||
<div class="post-cover">
|
||||
{cover ? (
|
||||
<Image
|
||||
src={cover}
|
||||
alt=""
|
||||
widths={[720, 1080, 1440]}
|
||||
sizes="(max-width: 768px) 100vw, 720px"
|
||||
fetchpriority="high"
|
||||
/>
|
||||
) : (
|
||||
coverMedia && (
|
||||
<MediaImage
|
||||
media={coverMedia}
|
||||
alt=""
|
||||
sizes="(max-width: 768px) 100vw, 720px"
|
||||
loading="eager"
|
||||
fetchpriority="high"
|
||||
/>
|
||||
)
|
||||
)}
|
||||
</div>
|
||||
/* An age-rated post folds its cover away with the text: a reader who says "no" sees
|
||||
neither. */
|
||||
ageRating ? (
|
||||
<AgeGate rating={ageRating} {locale}>
|
||||
<PostCover {cover} {coverMedia} />
|
||||
<Prose class="post-body">
|
||||
<slot />
|
||||
</Prose>
|
||||
</AgeGate>
|
||||
) : (
|
||||
<Fragment>
|
||||
<PostCover {cover} {coverMedia} />
|
||||
<Prose class="post-body">
|
||||
<slot />
|
||||
</Prose>
|
||||
</Fragment>
|
||||
)
|
||||
}
|
||||
|
||||
<Prose class="post-body">
|
||||
<slot />
|
||||
</Prose>
|
||||
|
||||
<footer class="post-foot" data-pagefind-ignore>
|
||||
<Waveline client:visible height={36} />
|
||||
<Pagination
|
||||
@@ -223,15 +221,6 @@ const crumbs = breadcrumbSchema([
|
||||
font-size: var(--text-meta);
|
||||
font-family: var(--ff-mono);
|
||||
}
|
||||
.post-cover {
|
||||
margin-block-end: 2rem;
|
||||
}
|
||||
.post-cover :global(img) {
|
||||
inline-size: 100%;
|
||||
block-size: auto;
|
||||
border-radius: var(--radius-card);
|
||||
border: 1px solid var(--line);
|
||||
}
|
||||
.post-foot {
|
||||
margin-block-start: 3rem;
|
||||
display: flex;
|
||||
|
||||
@@ -2,7 +2,8 @@
|
||||
import BaseLayout from "./BaseLayout.astro";
|
||||
import Prose from "../components/Prose.astro";
|
||||
import Waveline from "../components/Waveline.svelte";
|
||||
import ContentWarning from "../components/ContentWarning.astro";
|
||||
import ContentNotice from "../components/ContentNotice.astro";
|
||||
import AgeGate from "../components/AgeGate.astro";
|
||||
import ReadingControls from "../components/ReadingControls.svelte";
|
||||
import Pagination from "../components/Pagination.astro";
|
||||
import type { StoryEntry } from "../lib/collections";
|
||||
@@ -10,6 +11,7 @@ import { useTranslations } from "../i18n";
|
||||
import type { Locale } from "../i18n/routing";
|
||||
import { SITE, authorRef } from "../lib/seo";
|
||||
import { ogUrl } from "../lib/og";
|
||||
import { labelNames, needsBlur } from "../lib/content-labels";
|
||||
|
||||
interface NavLink {
|
||||
href: string;
|
||||
@@ -34,8 +36,9 @@ const {
|
||||
translationHref = null,
|
||||
} = Astro.props;
|
||||
const t = useTranslations(locale);
|
||||
const { title, description, series, contentWarning } = entry.data;
|
||||
const hasCW = contentWarning.length > 0;
|
||||
const { title, description, series, contentWarning, ageRating } = entry.data;
|
||||
const blur = needsBlur(contentWarning);
|
||||
const rating = ageRating ?? labelNames(contentWarning, t.labels).join(", ");
|
||||
|
||||
const pathname = Astro.url.pathname;
|
||||
const alternates = translationHref
|
||||
@@ -51,7 +54,7 @@ const storySchema = {
|
||||
description,
|
||||
inLanguage: locale === "vi" ? "vi-VN" : "en-US",
|
||||
...(series ? { isPartOf: { "@type": "CreativeWorkSeries", name: series } } : {}),
|
||||
...(hasCW ? { contentRating: contentWarning.join(", ") } : {}),
|
||||
...(rating ? { contentRating: rating } : {}),
|
||||
author: authorRef(),
|
||||
url: new URL(pathname, SITE.url).href,
|
||||
};
|
||||
@@ -76,19 +79,25 @@ const storySchema = {
|
||||
<ReadingControls client:idle labels={t.reader} />
|
||||
</div>
|
||||
|
||||
<article id="reader-root" class="reading-column reader" data-pagefind-body>
|
||||
<article
|
||||
id="reader-root"
|
||||
class="reading-column reader"
|
||||
data-pagefind-body
|
||||
data-cw-blur={blur ? "" : undefined}
|
||||
>
|
||||
<header class="reader-head">
|
||||
{series && <p class="series">{series}</p>}
|
||||
<h1>{title}</h1>
|
||||
</header>
|
||||
|
||||
<ContentNotice labels={contentWarning} {ageRating} {locale} />
|
||||
{
|
||||
hasCW ? (
|
||||
<ContentWarning warnings={contentWarning} title={t.story.cwTitle} hint={t.story.cwHint}>
|
||||
ageRating ? (
|
||||
<AgeGate rating={ageRating} {locale}>
|
||||
<Prose reader>
|
||||
<slot />
|
||||
</Prose>
|
||||
</ContentWarning>
|
||||
</AgeGate>
|
||||
) : (
|
||||
<Prose reader>
|
||||
<slot />
|
||||
|
||||
@@ -13,6 +13,7 @@ type AuditAction =
|
||||
| "gallery.save"
|
||||
| "gallery.delete"
|
||||
| "publish"
|
||||
| "publish.auto"
|
||||
| "denylist.add"
|
||||
| "denylist.remove";
|
||||
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
import { env } from "cloudflare:workers";
|
||||
import { GITHUB_CONTENT_TOKEN, GITHUB_PUBLISH_TOKEN } from "astro:env/server";
|
||||
import { log } from "../log";
|
||||
import { recordAudit } from "./audit";
|
||||
import { dispatchPublish } from "./github";
|
||||
|
||||
// Every admin save or delete publishes by itself: it starts .github/workflows/content-bump.yml,
|
||||
// which points src/content at the content repo's main, and CI + auto-merge + Workers Builds
|
||||
// take it live. Saves in quick succession don't pile up — the workflow's concurrency group
|
||||
// keeps one run going and one waiting, and the waiting one always reads the newest main.
|
||||
|
||||
/** The token that may start the publish workflow (falls back to the content token). */
|
||||
export const publishToken = (): string | undefined => GITHUB_PUBLISH_TOKEN ?? GITHUB_CONTENT_TOKEN;
|
||||
|
||||
/** "queued" when the workflow was started, "failed" when it could not be (the save stands). */
|
||||
export type AutoPublish = "queued" | "failed";
|
||||
|
||||
/**
|
||||
* Start a publish after a content commit. Never throws: the commit already succeeded, so a
|
||||
* dispatch problem is reported back to the editor (which offers "Xuất bản" by hand) instead
|
||||
* of turning a good save into an error.
|
||||
*/
|
||||
export async function autoPublish(admin: string, commit: string): Promise<AutoPublish> {
|
||||
const token = publishToken();
|
||||
if (!token) return "failed";
|
||||
try {
|
||||
await dispatchPublish(token);
|
||||
} catch (error) {
|
||||
log.warn("admin.autopublish_failed", {
|
||||
admin,
|
||||
commit,
|
||||
error: error instanceof Error ? error.message : String(error),
|
||||
});
|
||||
return "failed";
|
||||
}
|
||||
await recordAudit(env.KV, {
|
||||
admin,
|
||||
action: "publish.auto",
|
||||
target: "content → site",
|
||||
detail: commit,
|
||||
});
|
||||
return "queued";
|
||||
}
|
||||
@@ -1,3 +1,5 @@
|
||||
import vi from "../../i18n/vi";
|
||||
import { AGE_RATINGS, LABEL_IDS } from "../content-labels";
|
||||
import { MEDIA_ID } from "../media";
|
||||
|
||||
// What the admin can edit: per-collection form fields and file-path rules. Shared by the
|
||||
@@ -5,7 +7,16 @@ import { MEDIA_ID } from "../media";
|
||||
// Mirrors src/content.config.ts; the CI build on the publish PR is the final validator.
|
||||
|
||||
type FieldType =
|
||||
"text" | "textarea" | "date" | "select" | "tags" | "number" | "checkbox" | "url" | "media";
|
||||
| "text"
|
||||
| "textarea"
|
||||
| "date"
|
||||
| "select"
|
||||
| "multiselect"
|
||||
| "tags"
|
||||
| "number"
|
||||
| "checkbox"
|
||||
| "url"
|
||||
| "media";
|
||||
|
||||
interface FieldSpec {
|
||||
key: string;
|
||||
@@ -13,10 +24,21 @@ interface FieldSpec {
|
||||
type: FieldType;
|
||||
required?: boolean;
|
||||
options?: readonly string[];
|
||||
/** How the editor names each option (defaults to the option itself). */
|
||||
optionLabels?: Readonly<Record<string, string>>;
|
||||
/** Longest text (characters). */
|
||||
max?: number;
|
||||
/** Numbers: whole numbers only, and the smallest allowed. */
|
||||
integer?: boolean;
|
||||
min?: number;
|
||||
/** Text: the whole value must match. */
|
||||
pattern?: RegExp;
|
||||
hint?: string;
|
||||
}
|
||||
|
||||
const SLUG = "[a-z0-9][a-z0-9-]*";
|
||||
export const SLUG_PATTERN = new RegExp(`^${SLUG}$`);
|
||||
|
||||
export type CollectionId = "blog" | "stories" | "projects" | "faq" | "gallery" | "legal" | "now";
|
||||
|
||||
export interface CollectionSpec {
|
||||
@@ -48,6 +70,23 @@ const TRANSLATION: FieldSpec = {
|
||||
};
|
||||
const DRAFT: FieldSpec = { key: "draft", label: "Bản nháp (ẩn khỏi site)", type: "checkbox" };
|
||||
const COVER: FieldSpec = { key: "coverMedia", label: "Ảnh bìa", type: "media" };
|
||||
// Content labels and age rating (src/lib/content-labels.ts): the site shows a banner, blurs
|
||||
// images for the visual labels, and asks the reader's age for a rated item.
|
||||
const LABELS: FieldSpec = {
|
||||
key: "contentWarning",
|
||||
label: "Nhãn nội dung",
|
||||
type: "multiselect",
|
||||
options: LABEL_IDS,
|
||||
optionLabels: vi.labels,
|
||||
hint: "Kinh dị, máu me, hù doạ, bạo lực, tự hại, cái chết: ảnh bị làm mờ. Còn lại: chỉ banner.",
|
||||
};
|
||||
const AGE: FieldSpec = {
|
||||
key: "ageRating",
|
||||
label: "Giới hạn tuổi",
|
||||
type: "select",
|
||||
options: AGE_RATINGS,
|
||||
hint: "Có giới hạn tuổi thì phần nội dung được ẩn tới khi người đọc xác nhận tuổi.",
|
||||
};
|
||||
|
||||
const LONGFORM: readonly FieldSpec[] = [
|
||||
{ key: "title", label: "Tiêu đề", type: "text", required: true, max: 120 },
|
||||
@@ -58,6 +97,8 @@ const LONGFORM: readonly FieldSpec[] = [
|
||||
{ key: "updated", label: "Cập nhật", type: "date" },
|
||||
{ key: "tags", label: "Thẻ", type: "tags" },
|
||||
COVER,
|
||||
LABELS,
|
||||
AGE,
|
||||
DRAFT,
|
||||
];
|
||||
|
||||
@@ -71,14 +112,13 @@ export const COLLECTIONS: Record<CollectionId, CollectionSpec> = {
|
||||
fields: [
|
||||
...LONGFORM,
|
||||
{ key: "series", label: "Tên bộ truyện", type: "text" },
|
||||
{ key: "chapter", label: "Chương", type: "number" },
|
||||
{ key: "chapter", label: "Chương", type: "number", integer: true, min: 1 },
|
||||
{
|
||||
key: "status",
|
||||
label: "Trạng thái",
|
||||
type: "select",
|
||||
options: ["ongoing", "complete", "dropped"],
|
||||
},
|
||||
{ key: "contentWarning", label: "Cảnh báo nội dung", type: "tags" },
|
||||
],
|
||||
},
|
||||
projects: {
|
||||
@@ -140,9 +180,12 @@ export const COLLECTIONS: Record<CollectionId, CollectionSpec> = {
|
||||
label: "Mã album",
|
||||
type: "text",
|
||||
required: true,
|
||||
hint: "Chữ thường, số, gạch nối",
|
||||
pattern: SLUG_PATTERN,
|
||||
hint: "Chữ thường, số, gạch nối — album phải đã có ảnh",
|
||||
},
|
||||
{ key: "coverIndex", label: "Ảnh bìa (thứ tự, từ 0)", type: "number" },
|
||||
LABELS,
|
||||
AGE,
|
||||
],
|
||||
},
|
||||
legal: {
|
||||
@@ -170,11 +213,10 @@ export const COLLECTIONS: Record<CollectionId, CollectionSpec> = {
|
||||
},
|
||||
};
|
||||
|
||||
const SLUG = "[a-z0-9][a-z0-9-]*";
|
||||
// Stories are stories/<series>/<chapter>.md, or stories/<slug>.md for a one-shot.
|
||||
const ENTRY_PATH = new RegExp(
|
||||
`^(blog|projects|faq|gallery|legal|now)/${SLUG}\\.mdx?$|^stories/${SLUG}/${SLUG}\\.mdx?$`,
|
||||
`^(blog|projects|faq|gallery|legal|now)/${SLUG}\\.mdx?$|^stories/(${SLUG}/)?${SLUG}\\.mdx?$`,
|
||||
);
|
||||
export const SLUG_PATTERN = new RegExp(`^${SLUG}$`);
|
||||
|
||||
/** The collection a content path belongs to, or null if the admin may not touch it. */
|
||||
export function collectionOf(path: string): CollectionSpec | null {
|
||||
@@ -192,10 +234,10 @@ export function newEntryPath(
|
||||
series?: string,
|
||||
): string | null {
|
||||
if (!COLLECTIONS[collection]?.creatable || !SLUG_PATTERN.test(slug)) return null;
|
||||
if (collection === "stories") {
|
||||
if (!series || !SLUG_PATTERN.test(series)) return null;
|
||||
return `stories/${series}/${slug}.md`;
|
||||
if (collection === "stories" && series) {
|
||||
return SLUG_PATTERN.test(series) ? `stories/${series}/${slug}.md` : null;
|
||||
}
|
||||
// No series: a one-shot story (stories/<slug>.md), or any other collection.
|
||||
return `${collection}/${slug}.md`;
|
||||
}
|
||||
|
||||
@@ -204,7 +246,13 @@ export function galleryPhotosPath(album: string): string | null {
|
||||
return SLUG_PATTERN.test(album) ? `gallery-photos/${album}.json` : null;
|
||||
}
|
||||
|
||||
type FieldErrorCode = "required" | "type" | "option" | "max" | "format";
|
||||
/**
|
||||
* `min`: a number below the field's minimum. `conflict`: the value can't coexist with another
|
||||
* key (a local `cover` next to `coverMedia`). `missing`: it names something that doesn't
|
||||
* exist (an album without photos — checked by the API, which can see the repos).
|
||||
*/
|
||||
type FieldErrorCode =
|
||||
"required" | "type" | "option" | "max" | "format" | "min" | "conflict" | "missing";
|
||||
|
||||
export interface FieldError {
|
||||
field: string;
|
||||
@@ -243,7 +291,8 @@ function checkField(field: FieldSpec, value: unknown): FieldErrorCode | null {
|
||||
case "text":
|
||||
case "textarea":
|
||||
if (typeof value !== "string") return "type";
|
||||
return field.max !== undefined && value.length > field.max ? "max" : null;
|
||||
if (field.max !== undefined && value.length > field.max) return "max";
|
||||
return field.pattern && !field.pattern.test(value) ? "format" : null;
|
||||
case "url":
|
||||
if (typeof value !== "string") return "type";
|
||||
return isHttpUrl(value) ? null : "format";
|
||||
@@ -254,8 +303,13 @@ function checkField(field: FieldSpec, value: unknown): FieldErrorCode | null {
|
||||
return typeof value === "string" && (field.options ?? []).includes(value) ? null : "option";
|
||||
case "tags":
|
||||
return Array.isArray(value) && value.every((tag) => typeof tag === "string") ? null : "type";
|
||||
case "multiselect":
|
||||
if (!Array.isArray(value)) return "type";
|
||||
return value.every((item) => (field.options ?? []).includes(item)) ? null : "option";
|
||||
case "number":
|
||||
return typeof value === "number" && Number.isFinite(value) ? null : "type";
|
||||
if (typeof value !== "number" || !Number.isFinite(value)) return "type";
|
||||
if (field.integer && !Number.isInteger(value)) return "type";
|
||||
return field.min !== undefined && value < field.min ? "min" : null;
|
||||
case "checkbox":
|
||||
return typeof value === "boolean" ? null : "type";
|
||||
case "media":
|
||||
@@ -289,5 +343,10 @@ export function validateFrontmatter(
|
||||
const code = checkField(field, value);
|
||||
if (code) errors.push({ field: field.key, code });
|
||||
}
|
||||
// The content schema allows one cover: a local image (`cover`, set by hand in the repo) or
|
||||
// an R2 upload (`coverMedia`, set here) — not both.
|
||||
if (!isEmpty(data.cover) && !isEmpty(data.coverMedia)) {
|
||||
errors.push({ field: "coverMedia", code: "conflict" });
|
||||
}
|
||||
return errors;
|
||||
}
|
||||
+13
-6
@@ -82,11 +82,13 @@ interface TreeEntry {
|
||||
}
|
||||
|
||||
/**
|
||||
* Every text file of the content repo's main branch, in ONE GraphQL request (three
|
||||
* directory levels: collection/series/file), plus the commit it was read at.
|
||||
* Every text file of the content repo's main branch — or of one commit, `at` — in ONE
|
||||
* GraphQL request (three directory levels: collection/series/file), plus the commit it was
|
||||
* read at.
|
||||
*/
|
||||
export async function listContentFiles(
|
||||
token: string,
|
||||
at?: string,
|
||||
): Promise<{ head: string; files: RepoFile[] }> {
|
||||
const blob = "... on Blob { oid text }";
|
||||
const level = (inner: string) => `entries { path type object { ${blob} ${inner} } }`;
|
||||
@@ -99,8 +101,10 @@ export async function listContentFiles(
|
||||
}
|
||||
}`;
|
||||
const data = await graphql<{
|
||||
repository: { ref: { target: { oid: string } }; object: { entries: TreeEntry[] } };
|
||||
}>(token, query, { ...CONTENT_REPO, expr: `${BRANCH}:` });
|
||||
repository: { ref: { target: { oid: string } }; object: { entries: TreeEntry[] } | null };
|
||||
}>(token, query, { ...CONTENT_REPO, expr: `${at ?? BRANCH}:` });
|
||||
// A commit the repo doesn't have (yet) has no tree: report it as empty, not as a crash.
|
||||
if (!data.repository.object) return { head: at ?? data.repository.ref.target.oid, files: [] };
|
||||
|
||||
const files: RepoFile[] = [];
|
||||
const walk = (entries: TreeEntry[]) => {
|
||||
@@ -116,7 +120,7 @@ export async function listContentFiles(
|
||||
}
|
||||
};
|
||||
walk(data.repository.object.entries);
|
||||
return { head: data.repository.ref.target.oid, files };
|
||||
return { head: at ?? data.repository.ref.target.oid, files };
|
||||
}
|
||||
|
||||
/** One file of the content repo at main, or null if it doesn't exist. */
|
||||
@@ -199,7 +203,10 @@ export async function commitContent(
|
||||
|
||||
export interface PublishStatus {
|
||||
contentHead: string;
|
||||
/** The content commit the live site is built from (gitlink in the site repo's main). */
|
||||
/**
|
||||
* The content commit the site repo's main points at (the src/content gitlink): merged, but
|
||||
* live only once Workers Builds has deployed that main — compare with versionInfo().content.
|
||||
*/
|
||||
published: string;
|
||||
pr: {
|
||||
number: number;
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
// Where a content change is on its way to the live site, as one word for the admin. Shared
|
||||
// by /api/admin/publish (which computes it) and the PublishBar and Dashboard (which show it),
|
||||
// so "published" can no longer mean "merged into main" while production still runs the old
|
||||
// content — the symptom behind the Oct 2026 "content pushed but not on the web".
|
||||
//
|
||||
// content repo main ──dispatch──▶ content/bump PR ──build──▶ merged into site main ──deploy──▶ live
|
||||
// (pending) (building · review · failed) (deploying) (live)
|
||||
|
||||
export type PublishPhase = "live" | "pending" | "building" | "review" | "deploying" | "failed";
|
||||
|
||||
export interface PhaseInput {
|
||||
/** poli0981/content main. */
|
||||
contentHead: string;
|
||||
/** The content commit the site repo's main points at (src/content gitlink). */
|
||||
published: string;
|
||||
/** The content commit the running Worker was built with; null when unknown (local dev). */
|
||||
live: string | null;
|
||||
pr: { autoMerge: boolean; checks: "pending" | "success" | "failure" | null } | null;
|
||||
run: { status: string; conclusion: string | null } | null;
|
||||
}
|
||||
|
||||
const RUNNING = new Set(["queued", "in_progress", "requested", "waiting", "pending"]);
|
||||
|
||||
export function publishPhase(status: PhaseInput): PublishPhase {
|
||||
// Without a build-time content commit, main's pointer is the best available stand-in.
|
||||
const live = status.live ?? status.published;
|
||||
if (live === status.contentHead) return "live";
|
||||
const { pr, run } = status;
|
||||
if (pr) {
|
||||
if (pr.checks === "failure") return "failed";
|
||||
// content-bump.yml leaves auto-merge off when the publish touches .mdx (code at build time).
|
||||
return pr.autoMerge ? "building" : "review";
|
||||
}
|
||||
if (run && RUNNING.has(run.status)) return "building";
|
||||
if (status.published === status.contentHead) return "deploying";
|
||||
if (run?.conclusion === "failure") return "failed";
|
||||
return "pending";
|
||||
}
|
||||
|
||||
/** How each phase reads in the admin (Vietnamese), and the tone of its badge. */
|
||||
export const PHASE_TEXT: Record<
|
||||
PublishPhase,
|
||||
{ label: string; tone: "ok" | "warn" | "err" | "info" }
|
||||
> = {
|
||||
live: { label: "đã lên web", tone: "ok" },
|
||||
pending: { label: "có thay đổi chưa xuất bản", tone: "warn" },
|
||||
building: { label: "đang build…", tone: "info" },
|
||||
review: { label: "chờ duyệt (có file .mdx)", tone: "warn" },
|
||||
deploying: { label: "đã merge — đang deploy…", tone: "info" },
|
||||
failed: { label: "xuất bản lỗi", tone: "err" },
|
||||
};
|
||||
|
||||
/** Phases in which nothing is moving, so starting a publish by hand makes sense. */
|
||||
export const canPublish = (phase: PublishPhase) => phase === "pending" || phase === "failed";
|
||||
|
||||
/**
|
||||
* The admin's toast after a save or delete, from the `publish` field the API returns
|
||||
* ("queued" | "failed", lib/admin/autopublish). `done` says what happened, e.g. "Đã lưu".
|
||||
*/
|
||||
export function afterSaveMessage(
|
||||
publish: unknown,
|
||||
done: string,
|
||||
): { text: string; kind: "ok" | "info"; queued: boolean } {
|
||||
return publish === "queued"
|
||||
? {
|
||||
text: `${done} — đang tự xuất bản, thường lên web sau 10–15 phút.`,
|
||||
kind: "ok",
|
||||
queued: true,
|
||||
}
|
||||
: {
|
||||
text: `${done}, nhưng chưa tự xuất bản được — bấm “Xuất bản” trên thanh trên cùng.`,
|
||||
kind: "info",
|
||||
queued: false,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
// The age check on age-rated pages (src/components/AgeGate.astro): the reader says whether they
|
||||
// are old enough, and the answer is remembered in THIS browser only — localStorage, never a
|
||||
// cookie, never sent anywhere. It stores the age thresholds answered, not an age or a birth date:
|
||||
// ok = the highest age the reader confirmed ("I am 16 or older" → 16)
|
||||
// no = the lowest age they said they are NOT ("I am not 18 yet" → 18)
|
||||
// It is a courtesy check, not age verification: anyone can answer anything, and without
|
||||
// JavaScript the folded text simply opens.
|
||||
|
||||
const KEY = "ageGate";
|
||||
|
||||
export interface AgeAnswer {
|
||||
v: 1;
|
||||
ok: number | null;
|
||||
no: number | null;
|
||||
}
|
||||
|
||||
export type AgeDecision = "allow" | "deny" | "ask";
|
||||
|
||||
const EMPTY: AgeAnswer = { v: 1, ok: null, no: null };
|
||||
|
||||
type ReadStore = Pick<Storage, "getItem">;
|
||||
type WriteStore = Pick<Storage, "setItem" | "removeItem">;
|
||||
|
||||
const isAge = (value: unknown): value is number =>
|
||||
typeof value === "number" && Number.isInteger(value) && value > 0 && value < 100;
|
||||
|
||||
/** The stored answer; anything missing, unreadable or malformed reads as "never answered". */
|
||||
export function readAnswer(storage: ReadStore | null): AgeAnswer {
|
||||
try {
|
||||
const raw = storage?.getItem(KEY);
|
||||
const value: unknown = raw ? JSON.parse(raw) : null;
|
||||
if (typeof value !== "object" || value === null || (value as { v?: unknown }).v !== 1) {
|
||||
return EMPTY;
|
||||
}
|
||||
const { ok, no } = value as { ok?: unknown; no?: unknown };
|
||||
return { v: 1, ok: isAge(ok) ? ok : null, no: isAge(no) ? no : null };
|
||||
} catch {
|
||||
return EMPTY; // storage blocked (private mode) or not JSON
|
||||
}
|
||||
}
|
||||
|
||||
/** What to do for a page that asks for `age`, given the stored answer. */
|
||||
export function decide(answer: AgeAnswer, age: number): AgeDecision {
|
||||
if (answer.ok !== null && answer.ok >= age) return "allow";
|
||||
if (answer.no !== null && answer.no <= age) return "deny";
|
||||
return "ask";
|
||||
}
|
||||
|
||||
/** The answer after the reader says yes or no to `age`; a new answer overrides an older one. */
|
||||
export function answer(previous: AgeAnswer, age: number, yes: boolean): AgeAnswer {
|
||||
if (yes) {
|
||||
const ok = Math.max(previous.ok ?? 0, age);
|
||||
// "Not 18" no longer stands once they say they are 18 or older.
|
||||
return { v: 1, ok, no: previous.no !== null && previous.no <= ok ? null : previous.no };
|
||||
}
|
||||
const no = Math.min(previous.no ?? Number.POSITIVE_INFINITY, age);
|
||||
return { v: 1, ok: previous.ok !== null && previous.ok >= no ? null : previous.ok, no };
|
||||
}
|
||||
|
||||
/** Remember an answer; false when the browser refuses (the choice then lasts for this page). */
|
||||
export function saveAnswer(storage: WriteStore | null, value: AgeAnswer): boolean {
|
||||
try {
|
||||
if (!storage) return false;
|
||||
storage.setItem(KEY, JSON.stringify(value));
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/** Forget every answer ("Đặt lại"). */
|
||||
export function resetAnswer(storage: WriteStore | null): void {
|
||||
try {
|
||||
storage?.removeItem(KEY);
|
||||
} catch {
|
||||
/* storage blocked: nothing was stored either */
|
||||
}
|
||||
}
|
||||
|
||||
/** Fill `{age}` in a string from the dictionaries. */
|
||||
export const withAge = (text: string, age: number) => text.replaceAll("{age}", String(age));
|
||||
@@ -1,5 +1,6 @@
|
||||
import { getCollection, type CollectionEntry } from "astro:content";
|
||||
import type { Locale } from "../i18n/routing";
|
||||
import { LABEL_IDS, minAge, type AgeRating, type ContentLabel } from "./content-labels";
|
||||
|
||||
export type BlogEntry = CollectionEntry<"blog">;
|
||||
export type StoryEntry = CollectionEntry<"stories">;
|
||||
@@ -58,6 +59,25 @@ export async function getFaqs(locale: Locale): Promise<FaqEntry[]> {
|
||||
return faqs.sort((a, b) => a.data.order - b.data.order);
|
||||
}
|
||||
|
||||
/**
|
||||
* An album's content labels and age rating, gathered from BOTH language entries: the vi and en
|
||||
* album pages show the same photos, so a label set on either applies to both, and the stricter
|
||||
* age rating wins.
|
||||
*/
|
||||
export async function albumWarning(
|
||||
album: string,
|
||||
): Promise<{ labels: ContentLabel[]; ageRating?: AgeRating }> {
|
||||
const entries = await getCollection("gallery", ({ data }) => data.album === album);
|
||||
const labels = LABEL_IDS.filter((id) =>
|
||||
entries.some(({ data }) => (data.contentWarning ?? []).includes(id)),
|
||||
);
|
||||
const ageRating = entries
|
||||
.map(({ data }) => data.ageRating)
|
||||
.filter((rating): rating is AgeRating => Boolean(rating))
|
||||
.sort((a, b) => (minAge(b) ?? 0) - (minAge(a) ?? 0))[0];
|
||||
return ageRating ? { labels, ageRating } : { labels };
|
||||
}
|
||||
|
||||
export async function getGalleryAlbums(locale: Locale): Promise<GalleryEntry[]> {
|
||||
const albums = await getCollection("gallery", ({ data }) => data.lang === locale);
|
||||
return albums.sort(byDateDesc);
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
// Content labels (content warnings) and age ratings: which labels exist, which of them blur
|
||||
// images, and the small rules the pages, feeds, OG cards and admin share. The labels' names
|
||||
// live with the other UI strings (src/i18n: `labels`), keyed by these ids.
|
||||
//
|
||||
// A label only informs — a banner naming it, and blurred images for the visual ones. An age
|
||||
// rating additionally folds the text away until the reader says they are old enough
|
||||
// (src/lib/age-gate.ts; the answer stays in their browser).
|
||||
|
||||
type LabelGroup = "horror" | "harm" | "society" | "other";
|
||||
|
||||
export const LABELS = {
|
||||
horror: { group: "horror", blur: true },
|
||||
blood: { group: "horror", blur: true },
|
||||
jumpscare: { group: "horror", blur: true },
|
||||
violence: { group: "harm", blur: true },
|
||||
"self-harm": { group: "harm", blur: true },
|
||||
death: { group: "harm", blur: true },
|
||||
politics: { group: "society", blur: false },
|
||||
religion: { group: "society", blur: false },
|
||||
"strong-language": { group: "other", blur: false },
|
||||
"flashing-lights": { group: "other", blur: false },
|
||||
spoilers: { group: "other", blur: false },
|
||||
} as const satisfies Record<string, { group: LabelGroup; blur: boolean }>;
|
||||
|
||||
export type ContentLabel = keyof typeof LABELS;
|
||||
|
||||
/** Every label id, in display order — the content schema's enum and the admin's options. */
|
||||
export const LABEL_IDS = Object.keys(LABELS) as [ContentLabel, ...ContentLabel[]];
|
||||
|
||||
export const AGE_RATINGS = ["13+", "16+", "18+"] as const;
|
||||
export type AgeRating = (typeof AGE_RATINGS)[number];
|
||||
|
||||
const isLabel = (id: string): id is ContentLabel => Object.hasOwn(LABELS, id);
|
||||
|
||||
/** Whether any of these labels asks for images to be blurred. */
|
||||
export function needsBlur(labels: readonly string[]): boolean {
|
||||
return labels.some((id) => isLabel(id) && LABELS[id].blur);
|
||||
}
|
||||
|
||||
/** The age an age rating asks for (18 for "18+"), or null without one. */
|
||||
export function minAge(rating: AgeRating | undefined | null): number | null {
|
||||
return rating ? Number.parseInt(rating, 10) : null;
|
||||
}
|
||||
|
||||
/** Label names in one language, in the order given (unknown ids are skipped). */
|
||||
export function labelNames(
|
||||
labels: readonly string[],
|
||||
names: Readonly<Record<ContentLabel, string>>,
|
||||
): string[] {
|
||||
return labels.filter(isLabel).map((id) => names[id]);
|
||||
}
|
||||
|
||||
/**
|
||||
* The words a feed or a link preview puts in front of a labelled item, e.g.
|
||||
* "[Cảnh báo: Kinh dị · 16+] ", or "" for an unlabelled one.
|
||||
*/
|
||||
export function warningPrefix(
|
||||
labels: readonly string[],
|
||||
rating: AgeRating | undefined | null,
|
||||
strings: { prefix: string; names: Readonly<Record<ContentLabel, string>> },
|
||||
): string {
|
||||
const parts = [...labelNames(labels, strings.names), ...(rating ? [rating] : [])];
|
||||
return parts.length ? `[${strings.prefix}: ${parts.join(" · ")}] ` : "";
|
||||
}
|
||||
+2
-2
@@ -42,8 +42,8 @@ export function plainText(markdown: string): string {
|
||||
// [ \t] rather than \s, which (under /m) could run across newlines and backtrack.
|
||||
return markdown
|
||||
.replace(/```[\s\S]*?```/g, "") // fenced code
|
||||
.replace(/!\[[^[\]]*\]\([^()]*\)/g, "") // images
|
||||
.replace(/\[([^[\]]+)\]\([^()]*\)/g, "$1") // links → their text
|
||||
.replace(/!\[[^[\]]*]\([^()]*\)/g, "") // images
|
||||
.replace(/\[([^[\]]+)]\([^()]*\)/g, "$1") // links → their text
|
||||
.replace(/^[ \t]{0,3}#{1,6}[ \t]+/gm, "") // headings
|
||||
.replace(/^[ \t]{0,3}>[ \t]?/gm, "") // blockquotes
|
||||
.replace(/^[ \t]*[-*+][ \t]+/gm, "") // list bullets
|
||||
|
||||
+26
-11
@@ -1,6 +1,7 @@
|
||||
import type { ImageMetadata } from "astro";
|
||||
import type { ContentLabel } from "./content-labels";
|
||||
import type { MediaRef } from "./media";
|
||||
import { galleryPhotoListSchema } from "./media-schema";
|
||||
import { galleryPhotoListSchema, photoLabelsSchema } from "./media-schema";
|
||||
|
||||
// An album's photos come from two places, merged in this order:
|
||||
// - local files under src/assets/gallery/<album>/ (build-time sharp), captions in a
|
||||
@@ -10,21 +11,33 @@ import { galleryPhotoListSchema } from "./media-schema";
|
||||
// here rather than as a content collection so a repo without that folder builds
|
||||
// without warnings.
|
||||
// Missing captions fail the build, and so does an album with no photos at all.
|
||||
// A photo may carry content labels of its own (`contentWarning` next to its caption, in
|
||||
// either place); unknown labels fail the build like they do in frontmatter.
|
||||
|
||||
type Caption = { vi: string; en: string };
|
||||
export type GalleryPhoto =
|
||||
| { kind: "local"; image: ImageMetadata; alt: Caption }
|
||||
| { kind: "media"; media: MediaRef; alt: Caption };
|
||||
| { kind: "local"; image: ImageMetadata; alt: Caption; labels: ContentLabel[] }
|
||||
| { kind: "media"; media: MediaRef; alt: Caption; labels: ContentLabel[] };
|
||||
|
||||
/** A photo's own labels, checked against the label list. */
|
||||
function photoLabels(value: unknown, where: string): ContentLabel[] {
|
||||
const parsed = photoLabelsSchema.safeParse(value);
|
||||
if (!parsed.success) throw new Error(`[gallery] Invalid contentWarning in ${where}.`);
|
||||
return parsed.data ?? [];
|
||||
}
|
||||
|
||||
// Vite requires static string-literal glob patterns.
|
||||
const IMAGES = import.meta.glob<ImageMetadata>(
|
||||
"/src/assets/gallery/**/*.{avif,webp,jpg,jpeg,png}",
|
||||
{ eager: true, import: "default" },
|
||||
);
|
||||
const CAPTIONS = import.meta.glob<Record<string, Caption>>("/src/assets/gallery/**/captions.json", {
|
||||
eager: true,
|
||||
import: "default",
|
||||
});
|
||||
const CAPTIONS = import.meta.glob<Record<string, Caption & { contentWarning?: unknown }>>(
|
||||
"/src/assets/gallery/**/captions.json",
|
||||
{
|
||||
eager: true,
|
||||
import: "default",
|
||||
},
|
||||
);
|
||||
const PHOTO_LISTS = import.meta.glob<unknown>("/src/content/gallery-photos/*.json", {
|
||||
eager: true,
|
||||
import: "default",
|
||||
@@ -43,11 +56,12 @@ function localPhotos(album: string): GalleryPhoto[] {
|
||||
}
|
||||
return entries.map(([path, image]) => {
|
||||
const file = path.slice(prefix.length);
|
||||
const alt = captions[file];
|
||||
if (!alt?.vi || !alt?.en) {
|
||||
const entry = captions[file];
|
||||
if (!entry?.vi || !entry?.en) {
|
||||
throw new Error(`[gallery] Missing vi/en caption for "${file}" in ${prefix}captions.json.`);
|
||||
}
|
||||
return { kind: "local", image, alt };
|
||||
const labels = photoLabels(entry.contentWarning, `${prefix}captions.json ("${file}")`);
|
||||
return { kind: "local", image, alt: { vi: entry.vi, en: entry.en }, labels };
|
||||
});
|
||||
}
|
||||
|
||||
@@ -66,10 +80,11 @@ function mediaPhotos(album: string): GalleryPhoto[] {
|
||||
if (!parsed.success) {
|
||||
throw new Error(`[gallery] Invalid ${file}: ${parsed.error.message}`);
|
||||
}
|
||||
return parsed.data.photos.map(({ caption, ...media }) => ({
|
||||
return parsed.data.photos.map(({ caption, contentWarning, ...media }) => ({
|
||||
kind: "media",
|
||||
media,
|
||||
alt: caption,
|
||||
labels: contentWarning ?? [],
|
||||
}));
|
||||
}
|
||||
|
||||
|
||||
@@ -7,14 +7,17 @@
|
||||
* section under any other `<h2>` (the "Models" and "Components" tables) is left alone and
|
||||
* keeps the page's language. The container is styled `display: contents` (prose.css).
|
||||
*/
|
||||
const HALVES: Record<string, string> = { English: "en", "Tiếng Việt": "vi" };
|
||||
const HALVES = new Map([
|
||||
["English", "en"],
|
||||
["Tiếng Việt", "vi"],
|
||||
]);
|
||||
|
||||
export function markLanguageHalves(html: string): string {
|
||||
return html
|
||||
.split(/(?=<h2[\s>])/)
|
||||
.map((section) => {
|
||||
const heading = /^<h2[^>]*>([^<]*)<\/h2>/.exec(section)?.[1].trim();
|
||||
const lang = heading === undefined ? undefined : HALVES[heading];
|
||||
const lang = heading === undefined ? undefined : HALVES.get(heading);
|
||||
return lang ? `<div lang="${lang}">${section}</div>` : section;
|
||||
})
|
||||
.join("");
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { z } from "astro/zod";
|
||||
import { LABEL_IDS } from "./content-labels";
|
||||
import { MEDIA_ID } from "./media";
|
||||
|
||||
/** An image uploaded to R2 through the admin (src/lib/media): id + master size. */
|
||||
@@ -9,11 +10,15 @@ export const mediaRefSchema = z.object({
|
||||
alt: z.string().max(300).optional(),
|
||||
});
|
||||
|
||||
/** Labels on one photo (src/lib/content-labels.ts); left out of the JSON when there are none. */
|
||||
export const photoLabelsSchema = z.array(z.enum(LABEL_IDS)).optional();
|
||||
|
||||
/** gallery-photos/<album>.json in the content repo: the album's R2 photos, in order. */
|
||||
export const galleryPhotoListSchema = z.object({
|
||||
photos: z.array(
|
||||
mediaRefSchema.omit({ alt: true }).extend({
|
||||
caption: z.object({ vi: z.string().min(1), en: z.string().min(1) }),
|
||||
contentWarning: photoLabelsSchema,
|
||||
}),
|
||||
),
|
||||
});
|
||||
+22
-2
@@ -1,18 +1,38 @@
|
||||
import type { RSSFeedItem } from "@astrojs/rss";
|
||||
import { useTranslations } from "../i18n";
|
||||
import { sectionPath, type Locale } from "../i18n/routing";
|
||||
import type { BlogEntry, StoryEntry } from "./collections";
|
||||
import { warningPrefix, type AgeRating } from "./content-labels";
|
||||
|
||||
function langTag(locale: Locale): string {
|
||||
return locale === "vi" ? "vi-vn" : "en-us";
|
||||
}
|
||||
|
||||
/**
|
||||
* The description, led by the item's content warning in its own language ("[Cảnh báo: Kinh
|
||||
* dị · 16+] …"): a feed reader shows no banner, so the warning has to travel with the text.
|
||||
*/
|
||||
function described(data: {
|
||||
description: string;
|
||||
lang: Locale;
|
||||
contentWarning?: string[];
|
||||
ageRating?: AgeRating;
|
||||
}): string {
|
||||
const t = useTranslations(data.lang);
|
||||
const prefix = warningPrefix(data.contentWarning ?? [], data.ageRating, {
|
||||
prefix: t.cw.feedPrefix,
|
||||
names: t.labels,
|
||||
});
|
||||
return `${prefix}${data.description}`;
|
||||
}
|
||||
|
||||
/** Blog item — description + categories. Full-content HTML is deferred (doc 13 §4). */
|
||||
export function blogFeedItem(post: BlogEntry): RSSFeedItem {
|
||||
return {
|
||||
title: post.data.title,
|
||||
link: sectionPath("blog", post.data.lang, post.id),
|
||||
pubDate: post.data.date,
|
||||
description: post.data.description,
|
||||
description: described(post.data),
|
||||
categories: post.data.tags,
|
||||
customData: `<dc:language>${langTag(post.data.lang)}</dc:language>`,
|
||||
};
|
||||
@@ -24,7 +44,7 @@ export function storyFeedItem(chapter: StoryEntry): RSSFeedItem {
|
||||
title: chapter.data.title,
|
||||
link: sectionPath("stories", chapter.data.lang, ...chapter.id.split("/")),
|
||||
pubDate: chapter.data.date,
|
||||
description: chapter.data.description,
|
||||
description: described(chapter.data),
|
||||
customData: `<dc:language>${langTag(chapter.data.lang)}</dc:language>`,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -9,6 +9,11 @@ export interface VersionInfo {
|
||||
timestamp: string | null;
|
||||
/** The commit Workers Builds built (astro.config.mjs defines __BUILD_COMMIT__). */
|
||||
commit: string | null;
|
||||
/**
|
||||
* The poli0981/content commit that build's src/content pointed at (__CONTENT_COMMIT__):
|
||||
* what the live site actually shows, as opposed to what the site repo's main points at.
|
||||
*/
|
||||
content: string | null;
|
||||
}
|
||||
|
||||
type VersionEnv = { CF_VERSION_METADATA?: Partial<WorkerVersionMetadata> };
|
||||
@@ -21,5 +26,6 @@ export function versionInfo(env: VersionEnv | undefined): VersionInfo {
|
||||
timestamp: meta?.timestamp || null,
|
||||
// `typeof` so this also runs where the build-time constant was never defined (tests).
|
||||
commit: typeof __BUILD_COMMIT__ === "string" ? __BUILD_COMMIT__ : null,
|
||||
content: typeof __CONTENT_COMMIT__ === "string" ? __CONTENT_COMMIT__ : null,
|
||||
};
|
||||
}
|
||||
@@ -2,16 +2,34 @@ import type { APIRoute } from "astro";
|
||||
import { env } from "cloudflare:workers";
|
||||
import { GITHUB_CONTENT_TOKEN } from "astro:env/server";
|
||||
import { recordAudit } from "@/lib/admin/audit";
|
||||
import { collectionOf, validateFrontmatter } from "@/lib/admin/collections";
|
||||
import { autoPublish } from "@/lib/admin/autopublish";
|
||||
import {
|
||||
collectionOf,
|
||||
galleryPhotosPath,
|
||||
validateFrontmatter,
|
||||
type FieldError,
|
||||
} from "@/lib/admin/collections";
|
||||
import { buildFile, splitFile, type Frontmatter } from "@/lib/admin/frontmatter";
|
||||
import { commitContent, listContentFiles, readContentFile } from "@/lib/admin/github";
|
||||
import { errorResponse, isPlainObject, json, readJson } from "@/lib/admin/http";
|
||||
import { localPhotoCount } from "@/lib/gallery";
|
||||
import { log } from "@/lib/log";
|
||||
|
||||
// Content entries of poli0981/content. Saving commits straight to the content repo's
|
||||
// main branch; nothing goes live until "Publish" (api/admin/publish).
|
||||
// Content entries of poli0981/content. Saving commits straight to the content repo's main
|
||||
// branch and then starts a publish (lib/admin/autopublish), so a save goes live on its own.
|
||||
export const prerender = false;
|
||||
|
||||
/**
|
||||
* An album entry must point at an album that has photos — local ones in this repo or an R2
|
||||
* list in the content repo — or the publish build fails (lib/gallery getAlbumPhotos).
|
||||
*/
|
||||
async function albumProblem(token: string, album: unknown): Promise<FieldError | null> {
|
||||
if (typeof album !== "string") return null; // validateFrontmatter already said why
|
||||
const list = galleryPhotosPath(album);
|
||||
if (!list || localPhotoCount(album) > 0 || (await readContentFile(token, list))) return null;
|
||||
return { field: "album", code: "missing" };
|
||||
}
|
||||
|
||||
const MAX_FILE_BYTES = 200_000;
|
||||
|
||||
export const GET: APIRoute = async ({ url }) => {
|
||||
@@ -81,6 +99,10 @@ export const PUT: APIRoute = async ({ request, locals }) => {
|
||||
if (!collection.creatable) return json({ error: "not_creatable" }, 400);
|
||||
}
|
||||
const errors = validateFrontmatter(collection, input.frontmatter);
|
||||
if (errors.length === 0 && collection.id === "gallery") {
|
||||
const problem = await albumProblem(GITHUB_CONTENT_TOKEN, input.frontmatter.album);
|
||||
if (problem) errors.push(problem);
|
||||
}
|
||||
if (errors.length > 0) return json({ error: "invalid_fields", fields: errors }, 400);
|
||||
|
||||
const original = input.sha ? await readContentFile(GITHUB_CONTENT_TOKEN, input.path) : null;
|
||||
@@ -94,9 +116,11 @@ export const PUT: APIRoute = async ({ request, locals }) => {
|
||||
}
|
||||
const verb = input.sha ? "update" : "add";
|
||||
const email = locals.admin?.email ?? "unknown";
|
||||
// The content repo is public: the commit says it came through the admin, but who it was
|
||||
// stays in the private audit log below.
|
||||
const commit = await commitContent(
|
||||
GITHUB_CONTENT_TOKEN,
|
||||
`content(${collection.id}): ${verb} ${input.path}\n\nvia admin (${email})`,
|
||||
`content(${collection.id}): ${verb} ${input.path}\n\nvia admin`,
|
||||
[{ path: input.path, text, expectSha: input.sha }],
|
||||
);
|
||||
const saved = await readContentFile(GITHUB_CONTENT_TOKEN, input.path);
|
||||
@@ -107,7 +131,8 @@ export const PUT: APIRoute = async ({ request, locals }) => {
|
||||
detail: commit,
|
||||
});
|
||||
log.info("admin.content_saved", { path: input.path, verb, commit, admin: email });
|
||||
return json({ commit, path: input.path, sha: saved?.sha ?? null });
|
||||
const publish = await autoPublish(email, commit);
|
||||
return json({ commit, path: input.path, sha: saved?.sha ?? null, publish });
|
||||
} catch (error) {
|
||||
return errorResponse(error);
|
||||
}
|
||||
@@ -128,7 +153,7 @@ export const DELETE: APIRoute = async ({ request, locals }) => {
|
||||
const email = locals.admin?.email ?? "unknown";
|
||||
const commit = await commitContent(
|
||||
GITHUB_CONTENT_TOKEN,
|
||||
`content: delete ${input.path}\n\nvia admin (${email})`,
|
||||
`content: delete ${input.path}\n\nvia admin`,
|
||||
[{ path: input.path, text: null, expectSha: input.sha }],
|
||||
);
|
||||
await recordAudit(env.KV, {
|
||||
@@ -138,7 +163,8 @@ export const DELETE: APIRoute = async ({ request, locals }) => {
|
||||
detail: commit,
|
||||
});
|
||||
log.info("admin.content_deleted", { path: input.path, commit, admin: email });
|
||||
return json({ commit });
|
||||
const publish = await autoPublish(email, commit);
|
||||
return json({ commit, publish });
|
||||
} catch (error) {
|
||||
return errorResponse(error);
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@ import type { APIRoute } from "astro";
|
||||
import { env } from "cloudflare:workers";
|
||||
import { GITHUB_CONTENT_TOKEN } from "astro:env/server";
|
||||
import { recordAudit } from "@/lib/admin/audit";
|
||||
import { autoPublish } from "@/lib/admin/autopublish";
|
||||
import { galleryPhotosPath, SLUG_PATTERN } from "@/lib/admin/collections";
|
||||
import { buildFile, splitFile } from "@/lib/admin/frontmatter";
|
||||
import {
|
||||
@@ -181,7 +182,7 @@ export const PUT: APIRoute = async ({ request, locals }) => {
|
||||
const verb = input.create ? "create" : "update";
|
||||
const commit = await commitContent(
|
||||
GITHUB_CONTENT_TOKEN,
|
||||
`content(gallery): ${verb} album ${input.album}\n\nvia admin (${email})`,
|
||||
`content(gallery): ${verb} album ${input.album}\n\nvia admin`,
|
||||
changes,
|
||||
);
|
||||
await recordAudit(env.KV, {
|
||||
@@ -191,7 +192,8 @@ export const PUT: APIRoute = async ({ request, locals }) => {
|
||||
detail: commit,
|
||||
});
|
||||
log.info("admin.gallery_saved", { album: input.album, verb, commit, admin: email });
|
||||
return json({ commit });
|
||||
const publish = await autoPublish(email, commit);
|
||||
return json({ commit, publish });
|
||||
} catch (error) {
|
||||
return errorResponse(error);
|
||||
}
|
||||
@@ -214,7 +216,7 @@ export const DELETE: APIRoute = async ({ request, locals }) => {
|
||||
const email = locals.admin?.email ?? "unknown";
|
||||
const commit = await commitContent(
|
||||
GITHUB_CONTENT_TOKEN,
|
||||
`content(gallery): delete album ${album}\n\nvia admin (${email})`,
|
||||
`content(gallery): delete album ${album}\n\nvia admin`,
|
||||
doomed.map((file) => ({ path: file.path, text: null, expectSha: file.sha })),
|
||||
);
|
||||
await recordAudit(env.KV, {
|
||||
@@ -224,7 +226,8 @@ export const DELETE: APIRoute = async ({ request, locals }) => {
|
||||
detail: commit,
|
||||
});
|
||||
log.info("admin.gallery_deleted", { album, commit, admin: email });
|
||||
return json({ commit, deleted: doomed.map((file) => file.path) });
|
||||
const publish = await autoPublish(email, commit);
|
||||
return json({ commit, deleted: doomed.map((file) => file.path), publish });
|
||||
} catch (error) {
|
||||
return errorResponse(error);
|
||||
}
|
||||
|
||||
@@ -7,6 +7,7 @@ import { errorResponse, json, readJson } from "@/lib/admin/http";
|
||||
import { assertDeclaredSize, BodyTooLargeError } from "@/lib/body";
|
||||
import { log } from "@/lib/log";
|
||||
import { MEDIA_ID } from "@/lib/media";
|
||||
import { versionInfo } from "@/lib/version";
|
||||
import {
|
||||
deleteMedia,
|
||||
listMedia,
|
||||
@@ -20,6 +21,22 @@ import {
|
||||
// The R2 media library: list, upload (transform once → R2), edit alt text, delete.
|
||||
export const prerender = false;
|
||||
|
||||
/**
|
||||
* Content files that mention an image: on the content repo's main AND in the content the
|
||||
* live site was built from. Main alone is not enough — an edit that dropped the image but is
|
||||
* not live yet would let the delete break the page visitors still see.
|
||||
*/
|
||||
async function filesUsing(token: string, id: string): Promise<string[]> {
|
||||
const live = versionInfo(env as unknown as Parameters<typeof versionInfo>[0]).content;
|
||||
const main = await listContentFiles(token);
|
||||
const snapshots = [main];
|
||||
if (live && live !== main.head) snapshots.push(await listContentFiles(token, live));
|
||||
const paths = snapshots.flatMap(({ files }) =>
|
||||
files.filter((file) => file.text.includes(id)).map((file) => file.path),
|
||||
);
|
||||
return [...new Set(paths)];
|
||||
}
|
||||
|
||||
/** Multipart framing (boundaries, the alt field, headers) on top of the file itself. */
|
||||
const FORM_OVERHEAD_BYTES = 64 * 1024;
|
||||
|
||||
@@ -117,8 +134,7 @@ export const DELETE: APIRoute = async ({ request, url, locals }) => {
|
||||
// Refuse while any content still points at it — the live site would break, and a
|
||||
// publish would fail the build anyway.
|
||||
if (GITHUB_CONTENT_TOKEN) {
|
||||
const { files } = await listContentFiles(GITHUB_CONTENT_TOKEN);
|
||||
const usedIn = files.filter((f) => f.text.includes(input.id)).map((f) => f.path);
|
||||
const usedIn = await filesUsing(GITHUB_CONTENT_TOKEN, input.id);
|
||||
if (usedIn.length) return json({ error: "in_use", usedIn }, 409);
|
||||
}
|
||||
await deleteMedia(env, input.id, url.origin);
|
||||
|
||||
@@ -2,22 +2,34 @@ import type { APIRoute } from "astro";
|
||||
import { env } from "cloudflare:workers";
|
||||
import { recordAudit } from "@/lib/admin/audit";
|
||||
import { GITHUB_CONTENT_TOKEN, GITHUB_PUBLISH_TOKEN } from "astro:env/server";
|
||||
import { publishToken } from "@/lib/admin/autopublish";
|
||||
import { dispatchPublish, publishStatus } from "@/lib/admin/github";
|
||||
import { errorResponse, json } from "@/lib/admin/http";
|
||||
import { publishPhase } from "@/lib/admin/publish-phase";
|
||||
import { log } from "@/lib/log";
|
||||
import { versionInfo } from "@/lib/version";
|
||||
|
||||
// Publish = run .github/workflows/content-bump.yml on the site repo: it points the
|
||||
// src/content submodule at content's main, opens/updates the content/bump PR, and lets
|
||||
// CI + auto-merge deploy it (Workers Builds). Edits that touch .mdx wait for review.
|
||||
// Saves and deletes start it on their own (lib/admin/autopublish); POST is the manual retry.
|
||||
export const prerender = false;
|
||||
|
||||
export const GET: APIRoute = async () => {
|
||||
if (!GITHUB_CONTENT_TOKEN) return json({ error: "not_configured" }, 503);
|
||||
try {
|
||||
const status = await publishStatus(GITHUB_CONTENT_TOKEN);
|
||||
// Without its own publish token, the content token is doing the dispatching — which
|
||||
// means it has rights on this repo too. The admin shows a warning for this.
|
||||
return json({ ...status, singleToken: !GITHUB_PUBLISH_TOKEN });
|
||||
// The admin runs in the same Worker as the public site, so the content commit this
|
||||
// build was made from is exactly what visitors are seeing.
|
||||
const live = versionInfo(env as unknown as Parameters<typeof versionInfo>[0]).content;
|
||||
return json({
|
||||
...status,
|
||||
live,
|
||||
phase: publishPhase({ ...status, live }),
|
||||
// Without its own publish token, the content token is doing the dispatching — which
|
||||
// means it has rights on this repo too. The admin shows a warning for this.
|
||||
singleToken: !GITHUB_PUBLISH_TOKEN,
|
||||
});
|
||||
} catch (error) {
|
||||
return errorResponse(error);
|
||||
}
|
||||
@@ -26,7 +38,7 @@ export const GET: APIRoute = async () => {
|
||||
export const POST: APIRoute = async ({ locals }) => {
|
||||
// Dispatching needs Actions write on the site repo — the publish token's only power.
|
||||
// Falls back to the content token for single-token setups.
|
||||
const token = GITHUB_PUBLISH_TOKEN ?? GITHUB_CONTENT_TOKEN;
|
||||
const token = publishToken();
|
||||
if (!token) return json({ error: "not_configured" }, 503);
|
||||
try {
|
||||
await dispatchPublish(token);
|
||||
|
||||
@@ -313,6 +313,35 @@ body::after {
|
||||
animation-delay: 0.34s;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ *
|
||||
* Content labels (src/lib/content-labels.ts, ContentNotice.astro). In a region marked
|
||||
* [data-cw-blur], every image is blurred until the reader ticks that region's "Hiện ảnh"
|
||||
* checkbox. Blurred is the default state and plain CSS: nothing sharp flashes before a
|
||||
* script runs, and it works with JavaScript off. A browser without :has() keeps the blur
|
||||
* (safe side). clip-path keeps the blur inside the image's own box.
|
||||
* ------------------------------------------------------------------ */
|
||||
[data-cw-blur] :is(img, video) {
|
||||
filter: blur(1.5rem) saturate(0.6);
|
||||
clip-path: inset(0);
|
||||
}
|
||||
[data-cw-blur]:has(.cw-reveal-input:checked) :is(img, video) {
|
||||
filter: none;
|
||||
clip-path: none;
|
||||
}
|
||||
/* Nothing to blur (a chapter without pictures): no "images are blurred / show" line. */
|
||||
[data-cw-blur]:not(:has(img, video)) .cw-blur-row {
|
||||
display: none;
|
||||
}
|
||||
/* One photo in an unlabelled album (its own contentWarning): blurred the same way. */
|
||||
.cw-photo :is(img, video) {
|
||||
filter: blur(1.5rem) saturate(0.6);
|
||||
clip-path: inset(0);
|
||||
}
|
||||
[data-cw-scope]:has(.cw-reveal-input:checked) .cw-photo :is(img, video) {
|
||||
filter: none;
|
||||
clip-path: none;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ *
|
||||
* Reduced motion — every animation/transition has a still branch.
|
||||
* ------------------------------------------------------------------ */
|
||||
|
||||
@@ -186,6 +186,91 @@ describe("reading settings", () => {
|
||||
});
|
||||
});
|
||||
|
||||
// The first chapter in the sitemap is rated 16+ and labelled horror (content repo), so the
|
||||
// age check and the image blur run on a real page.
|
||||
describe("age check and content warning", () => {
|
||||
const foldOpen = (page: Page) =>
|
||||
page.locator(".age-fold").evaluate((el) => (el as HTMLDetailsElement).open);
|
||||
const stored = (page: Page) => page.evaluate(() => localStorage.getItem("ageGate"));
|
||||
|
||||
it("starts folded, is scanned with the question open, and Esc never confirms", async () => {
|
||||
await withPage({}, chapterPath, async (page) => {
|
||||
assert.equal(await page.locator(".age-gate").count(), 1, "the chapter is age-rated");
|
||||
assert.equal(await foldOpen(page), false);
|
||||
await expectNoViolations(page, "chapter behind the age check");
|
||||
|
||||
await page.locator(".age-summary").focus();
|
||||
await page.keyboard.press("Enter");
|
||||
await page.waitForSelector(".age-dialog[open]");
|
||||
await expectNoViolations(page, "age question open");
|
||||
assert.equal(await focused(page), "button.age-no", "focus starts on No, not Yes");
|
||||
|
||||
await page.keyboard.press("Escape");
|
||||
await page.waitForSelector(".age-dialog:not([open])", { state: "attached" });
|
||||
assert.equal(await foldOpen(page), false, "Esc leaves the text folded");
|
||||
assert.equal(await stored(page), null, "Esc stores nothing");
|
||||
assert.equal(await focused(page), "summary.age-summary", "focus returns to the summary");
|
||||
|
||||
// Find-in-page or a #:~:text= link opens a <details> without asking anyone; without a
|
||||
// "yes" on record the gate folds it straight back.
|
||||
await page.evaluate(() => {
|
||||
const fold = document.querySelector<HTMLDetailsElement>(".age-fold");
|
||||
if (fold) fold.open = true;
|
||||
});
|
||||
await page.waitForFunction(
|
||||
() => document.querySelector<HTMLDetailsElement>(".age-fold")?.open === false,
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
it("No hides the text and says why; Yes opens it, is remembered, and can be reset", async () => {
|
||||
await withPage({}, chapterPath, async (page) => {
|
||||
await page.locator(".age-summary").click();
|
||||
await page.locator(".age-dialog .age-no").click();
|
||||
await page.waitForSelector('.age-status[data-state="deny"]:not([hidden])');
|
||||
assert.ok(await page.locator(".age-fold").isHidden(), "the text is gone, not just folded");
|
||||
assert.equal(await focused(page), "button.age-retry", "focus lands on the explanation");
|
||||
await expectNoViolations(page, "age check declined");
|
||||
|
||||
await page.keyboard.press("Enter");
|
||||
await page.waitForSelector(".age-dialog[open]");
|
||||
await page.locator(".age-dialog .age-yes").click();
|
||||
await page.waitForSelector(".age-fold[open]");
|
||||
// The dialog hands focus back to "Chọn lại", which is hidden now: it must not be lost.
|
||||
assert.equal(await focused(page), "summary.age-summary", "focus lands on the summary");
|
||||
assert.match((await stored(page)) ?? "", /"ok":16/);
|
||||
assert.ok(await page.locator(".age-body .prose p").first().isVisible(), "the text shows");
|
||||
|
||||
await page.reload();
|
||||
await settle(page);
|
||||
assert.equal(await foldOpen(page), true, "a confirmed age opens the text on the next visit");
|
||||
await page.locator(".age-reset").click();
|
||||
assert.equal(await foldOpen(page), false);
|
||||
assert.equal(await stored(page), null);
|
||||
});
|
||||
});
|
||||
|
||||
it("the 'show images' box un-blurs the page's images, from the keyboard too", async () => {
|
||||
await withPage({ confirmedAge: 18 }, chapterPath, async (page) => {
|
||||
// Stories carry no picture today: drop one into the text to watch the blur rule.
|
||||
await page.evaluate(() => {
|
||||
const img = document.createElement("img");
|
||||
img.id = "probe";
|
||||
img.alt = "probe";
|
||||
img.width = 10;
|
||||
img.height = 10;
|
||||
img.src = "data:image/gif;base64,R0lGODlhAQABAAAAACw=";
|
||||
document.querySelector("#reader-root .prose")?.appendChild(img);
|
||||
});
|
||||
const filter = () => page.locator("#probe").evaluate((el) => getComputedStyle(el).filter);
|
||||
assert.match(await filter(), /blur/, "blurred by default, before any script");
|
||||
await page.locator(".cw-reveal-input").focus();
|
||||
await page.keyboard.press("Space");
|
||||
assert.equal(await filter(), "none");
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
/**
|
||||
* Tab (or Shift+Tab) through the page and collect every control that receives focus while
|
||||
* covered by one of the fixed bars. Stops when focus reaches `until` or after `limit`
|
||||
@@ -247,7 +332,8 @@ describe("focus is not hidden under fixed bars (WCAG 2.4.11)", () => {
|
||||
});
|
||||
|
||||
it("story reader: nothing takes focus underneath the header or the reader bar going back up", async () => {
|
||||
await withPage({ viewport: PHONE }, chapterPath, async (page) => {
|
||||
// Age already confirmed: the walk should cross the chapter text, not a folded gate.
|
||||
await withPage({ viewport: PHONE, confirmedAge: 18 }, chapterPath, async (page) => {
|
||||
// Start from the last control of the chapter and walk backwards: only then does the
|
||||
// browser scroll controls in at the top edge, where the two sticky bars are.
|
||||
await page.evaluate(() => {
|
||||
|
||||
@@ -28,6 +28,9 @@ interface ContextOptions {
|
||||
forcedColors?: "active" | "none";
|
||||
/** false = a first-time visitor, who gets the legal notice sheet. */
|
||||
acknowledged?: boolean;
|
||||
/** An age the visitor already confirmed (src/lib/age-gate.ts), e.g. 18: age-rated text
|
||||
starts open. Unset = never answered, so it starts folded behind the age check. */
|
||||
confirmedAge?: number;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -42,6 +45,7 @@ export async function newContext(
|
||||
viewport = DESKTOP,
|
||||
forcedColors = "none",
|
||||
acknowledged = true,
|
||||
confirmedAge,
|
||||
}: ContextOptions = {},
|
||||
): Promise<BrowserContext> {
|
||||
const context = await browser.newContext({
|
||||
@@ -61,6 +65,15 @@ export async function newContext(
|
||||
}
|
||||
});
|
||||
}
|
||||
if (confirmedAge) {
|
||||
await context.addInitScript((age) => {
|
||||
try {
|
||||
localStorage.setItem("ageGate", JSON.stringify({ v: 1, ok: age, no: null }));
|
||||
} catch {
|
||||
/* storage unavailable: the text stays folded, which the tests would notice */
|
||||
}
|
||||
}, confirmedAge);
|
||||
}
|
||||
return context;
|
||||
}
|
||||
|
||||
|
||||
+10
-3
@@ -249,7 +249,11 @@ describe("/api/admin/overview and /api/admin/activity", () => {
|
||||
};
|
||||
assert.deepEqual(
|
||||
body.audit.map((e) => [e.action, e.target, e.admin]),
|
||||
[["content.save", "blog/b.md", OWNER]],
|
||||
// Newest first: the save, then the publish it started on its own.
|
||||
[
|
||||
["publish.auto", "content → site", OWNER],
|
||||
["content.save", "blog/b.md", OWNER],
|
||||
],
|
||||
);
|
||||
assert.equal(body.commits[0]?.message, "content(blog): update blog/b.md");
|
||||
|
||||
@@ -338,7 +342,10 @@ describe("/api/admin/gallery covers and deletion", () => {
|
||||
assert.equal(github?.files.get("gallery/other.md")?.includes("coverIndex"), false);
|
||||
assert.deepEqual(
|
||||
(await listAudit(kv.asBinding())).map((e) => [e.action, e.target]),
|
||||
[["gallery.save", "game"]],
|
||||
[
|
||||
["publish.auto", "content → site"],
|
||||
["gallery.save", "game"],
|
||||
],
|
||||
);
|
||||
});
|
||||
|
||||
@@ -372,7 +379,7 @@ describe("/api/admin/gallery covers and deletion", () => {
|
||||
assert.equal((await del({ album: "Bad Name" })).status, 400);
|
||||
assert.deepEqual(
|
||||
(await listAudit(kv.asBinding())).map((e) => e.action),
|
||||
["gallery.delete"],
|
||||
["publish.auto", "gallery.delete"],
|
||||
);
|
||||
setServerEnv({});
|
||||
assert.equal((await del({ album: "other" })).status, 503);
|
||||
|
||||
+131
-3
@@ -346,6 +346,59 @@ describe("/api/admin/content", () => {
|
||||
assert.match(github.files.get("blog/dem-dau.md") ?? "", /description: Mô tả mới/);
|
||||
});
|
||||
|
||||
it("publishes by itself after each save and delete, keeping the admin out of public commits", async () => {
|
||||
const saved = await call(
|
||||
contentApi.PUT,
|
||||
jsonRequest("PUT", { path: "blog/moi.md", sha: null, frontmatter: valid, body: "Hello" }),
|
||||
);
|
||||
assert.equal(((await saved.json()) as { publish: string }).publish, "queued");
|
||||
const deleted = await call(
|
||||
contentApi.DELETE,
|
||||
jsonRequest("DELETE", { path: "blog/moi.md", sha: github.sha("blog/moi.md") }),
|
||||
);
|
||||
assert.equal(((await deleted.json()) as { publish: string }).publish, "queued");
|
||||
assert.deepEqual(github.dispatched, ["main", "main"]);
|
||||
// The content repo is public: the commit says "via admin", the email stays in the audit log.
|
||||
for (const { message } of github.history) {
|
||||
assert.match(message, /\n\nvia admin$/);
|
||||
assert.doesNotMatch(message, /owner@example\.com/);
|
||||
}
|
||||
});
|
||||
|
||||
it("keeps a save that could not start its publish, and says so", async () => {
|
||||
github.failDispatch = 403;
|
||||
const { result } = await captureLogs(() =>
|
||||
call(
|
||||
contentApi.PUT,
|
||||
jsonRequest("PUT", { path: "blog/moi.md", sha: null, frontmatter: valid, body: "Hi" }),
|
||||
),
|
||||
);
|
||||
assert.equal(result.status, 200);
|
||||
assert.equal(((await result.json()) as { publish: string }).publish, "failed");
|
||||
assert.ok(github.files.has("blog/moi.md"));
|
||||
assert.deepEqual(github.dispatched, []);
|
||||
});
|
||||
|
||||
it("refuses an album entry pointing at an album with no photos", async () => {
|
||||
github.files.set("gallery/game.md", "---\ntitle: Game\nlang: vi\nalbum: game\n---\n");
|
||||
github.files.set("gallery-photos/game.json", JSON.stringify({ photos: [] }));
|
||||
const put = (album: string) =>
|
||||
call(
|
||||
contentApi.PUT,
|
||||
jsonRequest("PUT", {
|
||||
path: "gallery/game.md",
|
||||
sha: github.sha("gallery/game.md"),
|
||||
frontmatter: { title: "Game", lang: "vi", date: "2026-10-24", album },
|
||||
body: "",
|
||||
}),
|
||||
);
|
||||
assert.equal((await put("game")).status, 200);
|
||||
assert.deepEqual(await (await put("nope")).json(), {
|
||||
error: "invalid_fields",
|
||||
fields: [{ field: "album", code: "missing" }],
|
||||
});
|
||||
});
|
||||
|
||||
it("validates before writing anything", async () => {
|
||||
const put = (body: unknown) => call(contentApi.PUT, jsonRequest("PUT", body));
|
||||
assert.equal((await put({ path: 1 })).status, 400);
|
||||
@@ -473,8 +526,48 @@ describe("/api/admin/gallery", () => {
|
||||
},
|
||||
});
|
||||
assert.equal(created.status, 200);
|
||||
assert.equal(((await created.json()) as { publish: string }).publish, "queued");
|
||||
assert.match(github.files.get("gallery/trip-en.md") ?? "", /description: Hello/);
|
||||
assert.equal(JSON.parse(github.files.get("gallery-photos/trip.json") ?? "{}").photos.length, 1);
|
||||
assert.equal(github.dispatched.length, 2);
|
||||
});
|
||||
|
||||
it("keeps each photo's own content labels, and refuses unknown ones", async () => {
|
||||
const put = (list: unknown) =>
|
||||
call(
|
||||
galleryApi.PUT,
|
||||
jsonRequest(
|
||||
"PUT",
|
||||
{ album: "game", photos: list, sha: github.sha("gallery-photos/game.json") },
|
||||
"/api/admin/gallery",
|
||||
),
|
||||
);
|
||||
const labelled = [{ ...photos[0], contentWarning: ["horror", "blood"] }];
|
||||
assert.equal((await put(labelled)).status, 200);
|
||||
const saved = JSON.parse(github.files.get("gallery-photos/game.json") ?? "{}");
|
||||
assert.deepEqual(saved.photos[0].contentWarning, ["horror", "blood"]);
|
||||
// A photo without labels keeps no empty key in the JSON.
|
||||
assert.equal(
|
||||
JSON.parse(github.files.get("gallery-photos/trip.json") ?? '{"photos":[{}]}').photos[0]
|
||||
.contentWarning,
|
||||
undefined,
|
||||
);
|
||||
assert.equal((await put([{ ...photos[0], contentWarning: ["gore"] }])).status, 400);
|
||||
});
|
||||
|
||||
it("deletes an album and publishes that too", async () => {
|
||||
const response = await call(
|
||||
galleryApi.DELETE,
|
||||
jsonRequest("DELETE", { album: "game" }, "/api/admin/gallery"),
|
||||
);
|
||||
const result = (await response.json()) as { deleted: string[]; publish: string };
|
||||
assert.deepEqual(result.deleted.sort(), [
|
||||
"gallery-photos/game.json",
|
||||
"gallery/game-en.md",
|
||||
"gallery/game.md",
|
||||
]);
|
||||
assert.equal(result.publish, "queued");
|
||||
assert.match(github.history[0].message, /^content\(gallery\): delete album game\n\nvia admin$/);
|
||||
});
|
||||
|
||||
it("refuses bad input and existing albums", async () => {
|
||||
@@ -612,6 +705,35 @@ describe("/api/admin/media", () => {
|
||||
assert.equal(response.status, 409);
|
||||
assert.deepEqual(((await response.json()) as { usedIn: string[] }).usedIn, ["blog/a.md"]);
|
||||
});
|
||||
|
||||
it("also refuses while the live site's content still uses it", async () => {
|
||||
// Main no longer mentions the image, but the build visitors see was made before that.
|
||||
github.files.delete("blog/a.md");
|
||||
github.snapshots.set("live-commit", { "blog/a.md": "uses 0123456789abcdef" });
|
||||
await r2.put(
|
||||
"private/meta/0123456789abcdef.json",
|
||||
JSON.stringify({ id: "0123456789abcdef", variants: [] }),
|
||||
);
|
||||
const constants = globalThis as { __CONTENT_COMMIT__?: string };
|
||||
constants.__CONTENT_COMMIT__ = "live-commit";
|
||||
try {
|
||||
const response = await call(
|
||||
mediaApi.DELETE,
|
||||
jsonRequest("DELETE", { id: "0123456789abcdef" }, "/api/admin/media"),
|
||||
);
|
||||
assert.equal(response.status, 409);
|
||||
assert.deepEqual(((await response.json()) as { usedIn: string[] }).usedIn, ["blog/a.md"]);
|
||||
// A live commit the repo doesn't know (yet) reads as empty, not as an error.
|
||||
constants.__CONTENT_COMMIT__ = "unknown-commit";
|
||||
const gone = await call(
|
||||
mediaApi.DELETE,
|
||||
jsonRequest("DELETE", { id: "0123456789abcdef" }, "/api/admin/media"),
|
||||
);
|
||||
assert.equal(gone.status, 200);
|
||||
} finally {
|
||||
delete constants.__CONTENT_COMMIT__;
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("/api/admin/publish", () => {
|
||||
@@ -621,10 +743,16 @@ describe("/api/admin/publish", () => {
|
||||
|
||||
it("reports status (flagging single-token mode) and dispatches", async () => {
|
||||
setServerEnv({ GITHUB_CONTENT_TOKEN: TOKEN });
|
||||
const status = (await (
|
||||
await call(publishApi.GET, new Request("https://admin.poli0981.dev/api/admin/publish"))
|
||||
).json()) as { singleToken: boolean };
|
||||
const read = async () =>
|
||||
(await (
|
||||
await call(publishApi.GET, new Request("https://admin.poli0981.dev/api/admin/publish"))
|
||||
).json()) as { singleToken: boolean; phase: string; live: string | null };
|
||||
const status = await read();
|
||||
assert.equal(status.singleToken, true);
|
||||
assert.equal(status.live, null);
|
||||
assert.equal(status.phase, "live");
|
||||
github.head = "commit-9";
|
||||
assert.equal((await read()).phase, "pending");
|
||||
setServerEnv({ GITHUB_CONTENT_TOKEN: TOKEN, GITHUB_PUBLISH_TOKEN: "publish-token" });
|
||||
const dispatched = await call(
|
||||
publishApi.POST,
|
||||
|
||||
@@ -221,7 +221,13 @@ describe("GET /api/health", () => {
|
||||
assert.equal(response.headers.get("cache-control"), "no-store");
|
||||
assert.deepEqual(await response.json(), {
|
||||
ok: true,
|
||||
version: { id: "v-9", tag: null, timestamp: "2026-10-24T01:02:03Z", commit: null },
|
||||
version: {
|
||||
id: "v-9",
|
||||
tag: null,
|
||||
timestamp: "2026-10-24T01:02:03Z",
|
||||
commit: null,
|
||||
content: null,
|
||||
},
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -81,6 +81,52 @@ describe("frontmatter validation", () => {
|
||||
assert.equal(galleryPhotosPath("trip-2026"), "gallery-photos/trip-2026.json");
|
||||
assert.equal(galleryPhotosPath("../x"), null);
|
||||
});
|
||||
|
||||
it("takes content labels from the label list and an age rating from the ratings", () => {
|
||||
assert.deepEqual(
|
||||
validateFrontmatter(blog, {
|
||||
...valid,
|
||||
contentWarning: ["horror", "politics"],
|
||||
ageRating: "16+",
|
||||
}),
|
||||
[],
|
||||
);
|
||||
assert.deepEqual(validateFrontmatter(blog, { ...valid, contentWarning: ["gore"] }), [
|
||||
{ field: "contentWarning", code: "option" },
|
||||
]);
|
||||
assert.deepEqual(validateFrontmatter(blog, { ...valid, contentWarning: "horror" }), [
|
||||
{ field: "contentWarning", code: "type" },
|
||||
]);
|
||||
assert.deepEqual(validateFrontmatter(blog, { ...valid, ageRating: "21+" }), [
|
||||
{ field: "ageRating", code: "option" },
|
||||
]);
|
||||
const labels = COLLECTIONS.stories.fields.find((f) => f.key === "contentWarning");
|
||||
assert.equal(labels?.optionLabels?.horror, "Kinh dị");
|
||||
});
|
||||
|
||||
it("holds the admin to the content schema's own rules", () => {
|
||||
const stories = COLLECTIONS.stories;
|
||||
// chapter: z.number().int().positive()
|
||||
assert.deepEqual(validateFrontmatter(stories, { ...valid, chapter: 2 }), []);
|
||||
assert.deepEqual(validateFrontmatter(stories, { ...valid, chapter: 1.5 }), [
|
||||
{ field: "chapter", code: "type" },
|
||||
]);
|
||||
assert.deepEqual(validateFrontmatter(stories, { ...valid, chapter: 0 }), [
|
||||
{ field: "chapter", code: "min" },
|
||||
]);
|
||||
// One cover only: a local `cover` (kept untouched by the admin) or an R2 `coverMedia`.
|
||||
const cover = { id: "0123456789abcdef", w: 800, h: 600 };
|
||||
assert.deepEqual(validateFrontmatter(blog, { ...valid, cover: "./x.jpg", coverMedia: cover }), [
|
||||
{ field: "coverMedia", code: "conflict" },
|
||||
]);
|
||||
// An album is a slug (the folder and gallery-photos/<album>.json are named after it).
|
||||
const gallery = COLLECTIONS.gallery;
|
||||
const album = { title: "A", lang: "vi", date: "2026-10-24", album: "game" };
|
||||
assert.deepEqual(validateFrontmatter(gallery, album), []);
|
||||
assert.deepEqual(validateFrontmatter(gallery, { ...album, album: "Game Shots" }), [
|
||||
{ field: "album", code: "format" },
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("admin collections", () => {
|
||||
@@ -97,22 +143,25 @@ describe("admin collections", () => {
|
||||
assert.equal(newEntryPath("gallery", "trip"), null);
|
||||
});
|
||||
|
||||
it("rejects bad slugs and stories without a series", () => {
|
||||
it("rejects bad slugs; a story without a series is a one-shot", () => {
|
||||
assert.equal(newEntryPath("blog", "Hello World"), null);
|
||||
assert.equal(newEntryPath("blog", "../x"), null);
|
||||
assert.equal(newEntryPath("stories", "chuong-03"), null);
|
||||
assert.equal(newEntryPath("stories", "chuong-03", "Bad Series"), null);
|
||||
assert.equal(newEntryPath("stories", "mot-dem"), "stories/mot-dem.md");
|
||||
});
|
||||
|
||||
it("only maps editable content paths to a collection", () => {
|
||||
assert.equal(collectionOf("now/now-en.md")?.id, "now");
|
||||
assert.equal(collectionOf("blog/lan-dau-viet-truyen.mdx")?.id, "blog");
|
||||
assert.equal(collectionOf("stories/dem-khong-tieng/chuong-01.md")?.id, "stories");
|
||||
assert.equal(collectionOf("stories/mot-dem.md")?.id, "stories");
|
||||
for (const path of [
|
||||
"README.md",
|
||||
"blog/../README.md",
|
||||
"gallery-photos/game.json",
|
||||
"blog/x.txt",
|
||||
".github/x.md",
|
||||
"stories/a/b/c.md",
|
||||
]) {
|
||||
assert.equal(collectionOf(path), null, path);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,130 @@
|
||||
// Content labels and age ratings (src/lib/content-labels.ts), their names in both languages,
|
||||
// and the age check's stored answer (src/lib/age-gate.ts).
|
||||
import assert from "node:assert/strict";
|
||||
import { describe, it } from "node:test";
|
||||
import en from "../src/i18n/en.ts";
|
||||
import vi from "../src/i18n/vi.ts";
|
||||
import {
|
||||
AGE_RATINGS,
|
||||
LABEL_IDS,
|
||||
LABELS,
|
||||
labelNames,
|
||||
minAge,
|
||||
needsBlur,
|
||||
warningPrefix,
|
||||
} from "../src/lib/content-labels.ts";
|
||||
import {
|
||||
answer,
|
||||
decide,
|
||||
readAnswer,
|
||||
resetAnswer,
|
||||
saveAnswer,
|
||||
withAge,
|
||||
type AgeAnswer,
|
||||
} from "../src/lib/age-gate.ts";
|
||||
|
||||
describe("content labels", () => {
|
||||
it("has a name for every label in both languages, and nothing else", () => {
|
||||
for (const dict of [vi, en]) {
|
||||
assert.deepEqual(Object.keys(dict.labels).sort(), [...LABEL_IDS].sort());
|
||||
for (const id of LABEL_IDS) assert.ok(dict.labels[id].trim(), id);
|
||||
}
|
||||
});
|
||||
|
||||
it("blurs images only for the visual labels", () => {
|
||||
assert.equal(needsBlur(["politics", "spoilers"]), false);
|
||||
assert.equal(needsBlur(["politics", "blood"]), true);
|
||||
assert.equal(needsBlur(["not-a-label"]), false);
|
||||
assert.equal(needsBlur([]), false);
|
||||
assert.deepEqual(
|
||||
LABEL_IDS.filter((id) => LABELS[id].blur),
|
||||
["horror", "blood", "jumpscare", "violence", "self-harm", "death"],
|
||||
);
|
||||
});
|
||||
|
||||
it("reads the age out of a rating", () => {
|
||||
assert.deepEqual(
|
||||
AGE_RATINGS.map((rating) => minAge(rating)),
|
||||
[13, 16, 18],
|
||||
);
|
||||
assert.equal(minAge(undefined), null);
|
||||
assert.equal(minAge(null), null);
|
||||
});
|
||||
|
||||
it("names labels in order, skipping unknown ones", () => {
|
||||
assert.deepEqual(labelNames(["blood", "x", "horror"], vi.labels), ["Máu me", "Kinh dị"]);
|
||||
assert.deepEqual(labelNames(["politics"], en.labels), ["Politics"]);
|
||||
});
|
||||
|
||||
it("builds the feed/preview prefix, or nothing for an unlabelled item", () => {
|
||||
const strings = { prefix: vi.cw.feedPrefix, names: vi.labels };
|
||||
assert.equal(warningPrefix(["horror"], "16+", strings), "[Cảnh báo: Kinh dị · 16+] ");
|
||||
assert.equal(warningPrefix([], "18+", strings), "[Cảnh báo: 18+] ");
|
||||
assert.equal(warningPrefix([], undefined, strings), "");
|
||||
});
|
||||
});
|
||||
|
||||
/** A Storage stand-in; `fail` makes every call throw, like blocked storage in private mode. */
|
||||
function storage(fail = false) {
|
||||
const data = new Map<string, string>();
|
||||
const guard = () => {
|
||||
if (fail) throw new DOMException("blocked", "SecurityError");
|
||||
};
|
||||
return {
|
||||
data,
|
||||
getItem: (key: string) => (guard(), data.get(key) ?? null),
|
||||
setItem: (key: string, value: string) => (guard(), void data.set(key, value)),
|
||||
removeItem: (key: string) => (guard(), void data.delete(key)),
|
||||
};
|
||||
}
|
||||
|
||||
const none: AgeAnswer = { v: 1, ok: null, no: null };
|
||||
|
||||
describe("age check", () => {
|
||||
it("asks until answered, then allows or denies by threshold", () => {
|
||||
assert.equal(decide(none, 16), "ask");
|
||||
const sixteen = answer(none, 16, true);
|
||||
assert.deepEqual(sixteen, { v: 1, ok: 16, no: null });
|
||||
assert.equal(decide(sixteen, 13), "allow");
|
||||
assert.equal(decide(sixteen, 16), "allow");
|
||||
assert.equal(decide(sixteen, 18), "ask"); // 16+ says nothing about 18+
|
||||
const notEighteen = answer(sixteen, 18, false);
|
||||
assert.deepEqual(notEighteen, { v: 1, ok: 16, no: 18 });
|
||||
assert.equal(decide(notEighteen, 18), "deny");
|
||||
assert.equal(decide(notEighteen, 16), "allow");
|
||||
});
|
||||
|
||||
it("lets a newer answer override an older one", () => {
|
||||
const notSixteen = answer(none, 16, false);
|
||||
assert.equal(decide(notSixteen, 18), "deny"); // under 16 is under 18 too
|
||||
assert.equal(decide(notSixteen, 13), "ask");
|
||||
const eighteen = answer(notSixteen, 18, true);
|
||||
assert.deepEqual(eighteen, { v: 1, ok: 18, no: null });
|
||||
assert.deepEqual(answer(eighteen, 13, false), { v: 1, ok: null, no: 13 });
|
||||
});
|
||||
|
||||
it("stores only thresholds, reads garbage as unanswered, and survives blocked storage", () => {
|
||||
const store = storage();
|
||||
assert.equal(saveAnswer(store, answer(none, 18, true)), true);
|
||||
assert.equal(store.data.get("ageGate"), '{"v":1,"ok":18,"no":null}');
|
||||
assert.deepEqual(readAnswer(store), { v: 1, ok: 18, no: null });
|
||||
for (const raw of ["not json", "null", '{"v":2,"ok":18}', '{"v":1,"ok":"18","no":-1}']) {
|
||||
store.data.set("ageGate", raw);
|
||||
assert.deepEqual(readAnswer(store), none, raw);
|
||||
}
|
||||
resetAnswer(store);
|
||||
assert.equal(store.data.has("ageGate"), false);
|
||||
|
||||
const blocked = storage(true);
|
||||
assert.deepEqual(readAnswer(blocked), none);
|
||||
assert.equal(saveAnswer(blocked, none), false);
|
||||
assert.doesNotThrow(() => resetAnswer(blocked));
|
||||
assert.equal(saveAnswer(null, none), false);
|
||||
assert.deepEqual(readAnswer(null), none);
|
||||
});
|
||||
|
||||
it("fills the age into the dictionaries' strings", () => {
|
||||
assert.equal(withAge(vi.cw.question, 16), "Bạn đã đủ 16 tuổi?");
|
||||
assert.equal(withAge(en.cw.yes, 18), "Yes, I'm 18 or older");
|
||||
});
|
||||
});
|
||||
@@ -107,6 +107,25 @@ describe("collection queries", () => {
|
||||
);
|
||||
});
|
||||
|
||||
it("takes an album's labels and age rating from both language entries", async () => {
|
||||
setCollection("gallery", [
|
||||
{ id: "trip", data: { lang: "vi", album: "trip", contentWarning: ["blood"] } },
|
||||
{
|
||||
id: "trip-en",
|
||||
data: { lang: "en", album: "trip", contentWarning: ["horror", "blood"], ageRating: "16+" },
|
||||
},
|
||||
{ id: "dark", data: { lang: "vi", album: "dark", ageRating: "13+" } },
|
||||
{ id: "dark-en", data: { lang: "en", album: "dark", ageRating: "18+" } },
|
||||
{ id: "plain", data: { lang: "vi", album: "plain" } },
|
||||
]);
|
||||
assert.deepEqual(await collections.albumWarning("trip"), {
|
||||
labels: ["horror", "blood"],
|
||||
ageRating: "16+",
|
||||
});
|
||||
assert.deepEqual(await collections.albumWarning("dark"), { labels: [], ageRating: "18+" });
|
||||
assert.deepEqual(await collections.albumWarning("plain"), { labels: [] });
|
||||
});
|
||||
|
||||
it("counts reading time, tags, translations and story ids", async () => {
|
||||
assert.equal(collections.readingTime(undefined), 1);
|
||||
assert.equal(collections.readingTime("word ".repeat(1000)), 5);
|
||||
|
||||
+10
-4
@@ -242,18 +242,24 @@ describe("structured logs, version", () => {
|
||||
assert.deepEqual(fields, { ray: "abc", method: "GET", path: "/p" });
|
||||
});
|
||||
|
||||
it("reports the running version and build commit", () => {
|
||||
it("reports the running version, build commit and content commit", () => {
|
||||
assert.deepEqual(versionInfo(undefined), {
|
||||
id: null,
|
||||
tag: null,
|
||||
timestamp: null,
|
||||
commit: null,
|
||||
content: null,
|
||||
});
|
||||
(globalThis as { __BUILD_COMMIT__?: string }).__BUILD_COMMIT__ = "abc1234";
|
||||
const constants = globalThis as { __BUILD_COMMIT__?: string; __CONTENT_COMMIT__?: string };
|
||||
constants.__BUILD_COMMIT__ = "abc1234";
|
||||
constants.__CONTENT_COMMIT__ = "def5678";
|
||||
try {
|
||||
assert.equal(versionInfo({ CF_VERSION_METADATA: { id: "v1" } }).commit, "abc1234");
|
||||
const info = versionInfo({ CF_VERSION_METADATA: { id: "v1" } });
|
||||
assert.equal(info.commit, "abc1234");
|
||||
assert.equal(info.content, "def5678");
|
||||
} finally {
|
||||
delete (globalThis as { __BUILD_COMMIT__?: string }).__BUILD_COMMIT__;
|
||||
delete constants.__BUILD_COMMIT__;
|
||||
delete constants.__CONTENT_COMMIT__;
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
// The licence policy shared by scripts/gen-notices.mjs and scripts/check-licenses.mjs: the
|
||||
// SPDX expression evaluator and the per-package review lookup.
|
||||
import assert from "node:assert/strict";
|
||||
import { describe, it } from "node:test";
|
||||
import { ALLOWED, REVIEWED, reviewFor, satisfies } from "../scripts/license-policy.mjs";
|
||||
|
||||
describe("satisfies (SPDX expressions)", () => {
|
||||
it("accepts a single allowed identifier and refuses an unlisted one", () => {
|
||||
assert.equal(satisfies("MIT", ALLOWED), true);
|
||||
assert.equal(satisfies("GPL-2.0-only", ALLOWED), false);
|
||||
});
|
||||
|
||||
it("needs one side of OR and both sides of AND", () => {
|
||||
assert.equal(satisfies("MIT OR GPL-2.0-only", ALLOWED), true);
|
||||
assert.equal(satisfies("GPL-2.0-only OR MIT", ALLOWED), true);
|
||||
assert.equal(satisfies("Apache-2.0 AND LGPL-3.0-or-later", ALLOWED), false);
|
||||
assert.equal(
|
||||
satisfies(
|
||||
"Apache-2.0 AND LGPL-3.0-or-later AND MIT",
|
||||
new Set([...ALLOWED, "LGPL-3.0-or-later"]),
|
||||
),
|
||||
true,
|
||||
);
|
||||
});
|
||||
|
||||
it("binds AND tighter than OR and honours parentheses", () => {
|
||||
assert.equal(satisfies("GPL-2.0-only AND MIT OR ISC", ALLOWED), true);
|
||||
assert.equal(satisfies("GPL-2.0-only AND (MIT OR ISC)", ALLOWED), false);
|
||||
assert.equal(satisfies("(MIT OR Apache-2.0)", ALLOWED), true);
|
||||
});
|
||||
|
||||
it("treats `X WITH exception` as X and accepts lower-case operators", () => {
|
||||
assert.equal(satisfies("Apache-2.0 WITH LLVM-exception", ALLOWED), true);
|
||||
assert.equal(satisfies("GPL-2.0-only WITH Classpath-exception-2.0", ALLOWED), false);
|
||||
assert.equal(satisfies("MIT or Apache-2.0", ALLOWED), true);
|
||||
});
|
||||
|
||||
it("throws on text that is not an expression", () => {
|
||||
for (const bad of [
|
||||
"SEE LICENSE IN LICENSE",
|
||||
"",
|
||||
"(MIT",
|
||||
"MIT AND",
|
||||
"AND MIT",
|
||||
"MIT WITH",
|
||||
"MIT)",
|
||||
]) {
|
||||
assert.throws(() => satisfies(bad, ALLOWED), SyntaxError, bad);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("reviewFor (per-package clearance)", () => {
|
||||
it("matches exact names and prefix patterns only", () => {
|
||||
assert.equal(reviewFor("satori")?.license, "MPL-2.0");
|
||||
assert.equal(reviewFor("@resvg/resvg-js-linux-x64-gnu")?.license, "MPL-2.0");
|
||||
assert.equal(reviewFor("lightningcss-darwin-arm64")?.license, "MPL-2.0");
|
||||
assert.equal(reviewFor("@img/sharp-libvips-linux-x64")?.license, "LGPL-3.0-or-later");
|
||||
assert.equal(reviewFor("satori-html"), undefined);
|
||||
assert.equal(reviewFor("@img/sharp-linux-x64"), undefined);
|
||||
});
|
||||
|
||||
it("gives every entry a reason and a single extra licence", () => {
|
||||
for (const entry of REVIEWED) {
|
||||
assert.ok(entry.reason.length > 40, entry.packages.join(", "));
|
||||
assert.ok(!ALLOWED.has(entry.license), entry.license);
|
||||
assert.doesNotThrow(() => satisfies(entry.license, ALLOWED));
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,86 @@
|
||||
// Where a content change is on its way to the live site (lib/admin/publish-phase), and the
|
||||
// admin's toast after a save.
|
||||
import assert from "node:assert/strict";
|
||||
import { describe, it } from "node:test";
|
||||
import {
|
||||
afterSaveMessage,
|
||||
canPublish,
|
||||
PHASE_TEXT,
|
||||
publishPhase,
|
||||
type PhaseInput,
|
||||
} from "../src/lib/admin/publish-phase.ts";
|
||||
|
||||
const base: PhaseInput = {
|
||||
contentHead: "c2",
|
||||
published: "c1",
|
||||
live: "c1",
|
||||
pr: null,
|
||||
run: null,
|
||||
};
|
||||
|
||||
describe("publishPhase", () => {
|
||||
it("is live once the running build has the content head", () => {
|
||||
assert.equal(publishPhase({ ...base, published: "c2", live: "c2" }), "live");
|
||||
// Unknown build-time content commit (local dev): main's pointer stands in for it.
|
||||
assert.equal(publishPhase({ ...base, published: "c2", live: null }), "live");
|
||||
});
|
||||
|
||||
it("follows the bump PR: building, waiting for review, or failed", () => {
|
||||
const pr = (autoMerge: boolean, checks: "pending" | "success" | "failure" | null) =>
|
||||
publishPhase({ ...base, pr: { autoMerge, checks } });
|
||||
assert.equal(pr(true, "pending"), "building");
|
||||
assert.equal(pr(true, "success"), "building");
|
||||
assert.equal(pr(true, null), "building");
|
||||
assert.equal(pr(false, "success"), "review");
|
||||
assert.equal(pr(true, "failure"), "failed");
|
||||
});
|
||||
|
||||
it("is building while the workflow runs, before any PR exists", () => {
|
||||
assert.equal(
|
||||
publishPhase({ ...base, run: { status: "in_progress", conclusion: null } }),
|
||||
"building",
|
||||
);
|
||||
assert.equal(
|
||||
publishPhase({ ...base, run: { status: "queued", conclusion: null } }),
|
||||
"building",
|
||||
);
|
||||
});
|
||||
|
||||
it("is deploying when main has the content but the running build doesn't", () => {
|
||||
assert.equal(publishPhase({ ...base, published: "c2", live: "c1" }), "deploying");
|
||||
});
|
||||
|
||||
it("reports a failed last run, and plain pending changes otherwise", () => {
|
||||
assert.equal(
|
||||
publishPhase({ ...base, run: { status: "completed", conclusion: "failure" } }),
|
||||
"failed",
|
||||
);
|
||||
assert.equal(
|
||||
publishPhase({ ...base, run: { status: "completed", conclusion: "success" } }),
|
||||
"pending",
|
||||
);
|
||||
assert.equal(publishPhase(base), "pending");
|
||||
});
|
||||
|
||||
it("offers a manual publish only when nothing is moving", () => {
|
||||
assert.deepEqual((Object.keys(PHASE_TEXT) as (keyof typeof PHASE_TEXT)[]).filter(canPublish), [
|
||||
"pending",
|
||||
"failed",
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("afterSaveMessage", () => {
|
||||
it("says the change is on its way, or how to publish it by hand", () => {
|
||||
const queued = afterSaveMessage("queued", "Đã lưu");
|
||||
assert.equal(queued.queued, true);
|
||||
assert.equal(queued.kind, "ok");
|
||||
assert.match(queued.text, /^Đã lưu — đang tự xuất bản/);
|
||||
for (const other of ["failed", undefined]) {
|
||||
const message = afterSaveMessage(other, "Đã xoá album");
|
||||
assert.equal(message.queued, false);
|
||||
assert.equal(message.kind, "info");
|
||||
assert.match(message.text, /^Đã xoá album, nhưng chưa tự xuất bản được/);
|
||||
}
|
||||
});
|
||||
});
|
||||
Loaded 100 of 103 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user