feat(content): content labels, an age check, blurred images and a warning banner (#138)
* feat(content): content labels, an age check, blurred images and a warning banner Posts, chapters and albums can carry content labels and an age rating: - Labels (src/lib/content-labels.ts, names in src/i18n `labels`): horror, blood, jumpscare, violence, self-harm, death — banner and blurred images; politics, religion, strong-language, flashing-lights, spoilers — banner only. `contentWarning` moves from stories to every long-form entry and albums, and single gallery photos can carry their own (R2 list or captions.json). Unknown labels fail the build. - Banner (ContentNotice.astro, replaces ContentWarning.astro): names every label in the page's language, skipped by search. Images in a labelled region are blurred in plain CSS by default — nothing sharp flashes before a script — and a real "Hiện ảnh" checkbox un-blurs them through :has(), so it works with the keyboard and with JavaScript off. A region without pictures shows no such line. - Age check (AgeGate.astro, src/lib/age-gate.ts) for `ageRating` 13+/16+/18+: the text sits in a closed <details> (search indexes the title, not the text); its summary asks in a native modal <dialog> — focus starts on "No", Esc cancels and never means yes, "No" explains and offers to choose again — and the answer is kept in localStorage only (age thresholds, never an age or birth date). It never pops up on its own, and without JavaScript the summary simply opens the text. - Everywhere else: story/post/album cards name the labels (blurred covers), the lightbox shows labelled photos blurred behind "Hiện ảnh", RSS descriptions start with the warning in the item's language, OG cards carry it for blog posts too, JSON-LD contentRating. The post page now uses the cover's alt text when there is one. - Admin: a `multiselect` field for labels (with Vietnamese names), an age-rating select, and per-photo labels in the gallery manager. - Content (poli0981/content 98f7692): privacy policy §6 lists the age-check answer; "Đêm không tiếng" chapters 1–2 are rated 16+. - Tests: label and age-check logic, admin validation, labels kept on album save, RSS prefix; the accessibility suite scans the gate folded and asked, checks focus, Esc, No/Yes/reset and the keyboard reveal. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * test(a11y): appendChild for the blur probe (astro check's DOM typing) Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(content): findings from an independent review of the labels branch - Album pages: the lightbox now sits outside the labelled section, whose blur rule also blurred the viewer's photo — its "show" button removed the veil but not the blur. - Age check: the browser 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 the gate now folds it straight back. After "Chọn lại" → "Có", focus moves to the summary instead of being lost with the row that just hid. - Search indexes nothing inside the gate, not even its status lines, which could have become the excerpt of a page the reader has not been let into. - Albums take their labels and age rating from BOTH language entries (same photos, two pages; the stricter rating wins), on the album page and on its card. - An age-rated post folds its cover away with the text (PostCover.astro), and post and album cards blur the cover of age-rated items too. The album card names the cover photo's own labels, not only the album's. - Tests: the gate re-folds an unasked open and keeps focus after choosing again; albumWarning merges both languages. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
15559ecc90
commit
484907439a
41 files changed
+1593
-257
No files matched your search
@@ -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
|
||||
|
||||
|
||||
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.
|
||||
@@ -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,20 @@ 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.
|
||||
- **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 +86,7 @@ series: "Đêm không tiếng"
|
||||
chapter: 1
|
||||
status: ongoing
|
||||
contentWarning: [horror]
|
||||
ageRating: "16+"
|
||||
tags: [horror, short-story]
|
||||
---
|
||||
```
|
||||
@@ -121,6 +137,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]
|
||||
```
|
||||
|
||||
@@ -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)
|
||||
|
||||
+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,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();
|
||||
@@ -152,7 +160,9 @@
|
||||
<!-- 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>
|
||||
{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>
|
||||
@@ -176,6 +186,7 @@
|
||||
onpointercancel={onPointerUp}
|
||||
>
|
||||
<img
|
||||
class:veiled
|
||||
src={current.src}
|
||||
srcset={current.srcset}
|
||||
sizes="92vw"
|
||||
@@ -184,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
|
||||
@@ -279,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>
|
||||
@@ -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);
|
||||
|
||||
@@ -271,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>
|
||||
@@ -366,6 +379,32 @@
|
||||
{#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>
|
||||
@@ -573,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%;
|
||||
|
||||
@@ -5,9 +5,11 @@
|
||||
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 */
|
||||
|
||||
@@ -120,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;
|
||||
@@ -287,6 +302,26 @@
|
||||
<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
|
||||
@@ -438,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;
|
||||
|
||||
@@ -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,
|
||||
}),
|
||||
});
|
||||
|
||||
|
||||
+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 />
|
||||
|
||||
@@ -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,6 +24,8 @@ 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. */
|
||||
@@ -57,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 },
|
||||
@@ -67,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,
|
||||
];
|
||||
|
||||
@@ -87,7 +119,6 @@ export const COLLECTIONS: Record<CollectionId, CollectionSpec> = {
|
||||
type: "select",
|
||||
options: ["ongoing", "complete", "dropped"],
|
||||
},
|
||||
{ key: "contentWarning", label: "Cảnh báo nội dung", type: "tags" },
|
||||
],
|
||||
},
|
||||
projects: {
|
||||
@@ -153,6 +184,8 @@ export const COLLECTIONS: Record<CollectionId, CollectionSpec> = {
|
||||
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: {
|
||||
@@ -270,6 +303,9 @@ 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":
|
||||
if (typeof value !== "number" || !Number.isFinite(value)) return "type";
|
||||
if (field.integer && !Number.isInteger(value)) return "type";
|
||||
|
||||
@@ -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(" · ")}] ` : "";
|
||||
}
|
||||
+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 ?? [],
|
||||
}));
|
||||
}
|
||||
|
||||
|
||||
@@ -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>`,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
|
||||
@@ -532,6 +532,29 @@ describe("/api/admin/gallery", () => {
|
||||
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,
|
||||
|
||||
@@ -82,6 +82,28 @@ describe("frontmatter validation", () => {
|
||||
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()
|
||||
|
||||
@@ -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);
|
||||
|
||||
+13
-2
@@ -20,11 +20,15 @@ const entry = (id: string, lang: string, date: string) => ({
|
||||
});
|
||||
|
||||
before(() => {
|
||||
const politics = entry("post-en", "en", "2026-10-03");
|
||||
setCollection("blog", [
|
||||
entry("post-vi", "vi", "2026-10-01"),
|
||||
entry("post-en", "en", "2026-10-03"),
|
||||
{ ...politics, data: { ...politics.data, contentWarning: ["politics"] } },
|
||||
]);
|
||||
const chapter = entry("series/ch-1", "vi", "2026-10-02");
|
||||
setCollection("stories", [
|
||||
{ ...chapter, data: { ...chapter.data, contentWarning: ["horror"], ageRating: "16+" } },
|
||||
]);
|
||||
setCollection("stories", [entry("series/ch-1", "vi", "2026-10-02")]);
|
||||
});
|
||||
|
||||
const xml = async (feed: (context: APIContext) => Promise<Response>, site?: string) =>
|
||||
@@ -51,4 +55,11 @@ describe("RSS feeds", () => {
|
||||
assert.match(stories, /About series\/ch-1/);
|
||||
assert.doesNotMatch(stories, /post-vi/);
|
||||
});
|
||||
|
||||
it("puts each item's content warning in front of its description, in its language", async () => {
|
||||
const body = await xml(allFeed, "https://poli0981.dev");
|
||||
assert.match(body, /\[Cảnh báo: Kinh dị · 16\+\] About series\/ch-1/);
|
||||
assert.match(body, /\[Content warning: Politics\] About post-en/);
|
||||
assert.match(body, /<description>About post-vi<\/description>/);
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user