Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 6 additions & 2 deletions app/[lang]/blog/[slug]/opengraph-image.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
// free of filesystem access at build time.

import { ImageResponse } from "next/og";
import { isLang, contentLangFor, imageLang } from "@/lib/domain";
import { isLang, blogLangFor, contentLangFor, imageLang } from "@/lib/domain";
import type { Lang } from "@/lib/domain";
import { formatEditorialDate } from "@/lib/blog/dates";
import { getArticleBySlug } from "@/lib/blog/server";
Expand Down Expand Up @@ -86,7 +86,11 @@ export default async function OpenGraphImage({

if (isLang(lang)) {
try {
const article = await getArticleBySlug(contentLangFor(l), slug);
// v1.8.8: under /zh the story may have its own (Chinese) slug; the cover
// always uses a Latin-script title (next/og has no CJK font, see imageLang).
const found = await getArticleBySlug(blogLangFor(l), slug);
const article =
found && found.lang === "zh" ? await getArticleBySlug(contentLangFor(l), found.alternateSlugs.en) : found;
if (article) {
title = clampTitle(article.title);
dateLabel = formatEditorialDate(article.eventDate, imageLang(l));
Expand Down
20 changes: 13 additions & 7 deletions app/[lang]/blog/[slug]/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -29,13 +29,13 @@ import { getModelPage } from "@/lib/seo/content/models";
import { absUrl, getSiteUrl } from "@/lib/seo/site";
import { pageMetadata } from "@/lib/seo/metadata";
import { markdownPathOf } from "@/lib/seo/registry";
import { LANG_TAG, PUNCT, contentLangFor, sectionOfEdition, toLang, type ContentLang } from "@/lib/domain";
import { CONTENT_LANGS, LANG_TAG, PUNCT, blogLangFor, sectionOfEdition, toLang, type ArticleLang } from "@/lib/domain";
import ContentLangNotice from "@/components/blog/ContentLangNotice";

export const revalidate = 300;

/** Firestore is never allowed to break the route: a failure reads as "no article". */
async function loadArticle(lang: ContentLang, slug: string): Promise<PublicArticle | null> {
async function loadArticle(lang: ArticleLang, slug: string): Promise<PublicArticle | null> {
try {
return await getArticleBySlug(lang, slug);
} catch {
Expand Down Expand Up @@ -90,18 +90,23 @@ export async function generateMetadata({
const { lang, slug } = await params;
const l = toLang(lang);

// The article's language: es/en have their own; /pt shows the English one.
const cl = contentLangFor(l);
const article = await loadArticle(cl, slug);
// The article's language: es/en have their own; /pt shows the English one;
// v1.8.8: /zh shows the story's Chinese text, or the English one if it has none.
const article = await loadArticle(blogLangFor(l), slug);
if (!article) return {};
const cl = article.lang;
const zhSlug = article.alternateSlugs.zh;

return pageMetadata({
lang: l,
contentLang: cl,
// A story with Chinese text exists in three languages: hreflang lists zh too.
...(zhSlug ? { locales: [...CONTENT_LANGS, "zh"] as const } : {}),
path: `/${l}/blog/${article.slug}`,
alternatePaths: {
es: `/es/blog/${article.alternateSlugs.es}`,
en: `/en/blog/${article.alternateSlugs.en}`,
...(zhSlug ? { zh: `/zh/blog/${zhSlug}` } : {}),
},
title: article.seoTitle,
description: article.metaDescription,
Expand All @@ -125,9 +130,9 @@ export default async function BlogArticlePage({
if (!hasLocale(lang)) notFound();
const l = toLang(lang);

const cl = contentLangFor(l);
const article = await loadArticle(cl, slug);
const article = await loadArticle(blogLangFor(l), slug);
if (!article) notFound();
const cl = article.lang;

const dict = await getDictionary(l);
const t = dict.blog;
Expand Down Expand Up @@ -208,6 +213,7 @@ export default async function BlogArticlePage({

<ContentLangNotice
lang={l}
show={cl !== l}
text={t.langNotice}
hrefs={{ es: blogArticlePath("es", article.alternateSlugs.es), en: blogArticlePath("en", article.alternateSlugs.en) }}
className="mt-4"
Expand Down
6 changes: 3 additions & 3 deletions app/[lang]/dictionaries/zh.json
Original file line number Diff line number Diff line change
Expand Up @@ -288,7 +288,7 @@
"blurb": "每天一条经过核实的AI新闻,附带来源。",
"cta": "阅读今日一期"
},
"langNotice": "AI Daily只以英文和西班牙文发布。你正在阅读英文版。",
"langNotice": "暂无中文版的报道以英文原文显示。",
"tech": {
"indexTitle": "AI Daily Tech",
"tagline": "每天一条科技新闻,写给用AI做开发的人。",
Expand All @@ -298,7 +298,7 @@
"empty": "AI Daily Tech每天发布一条经过核实的科技新闻。这里暂时还没有内容,你可以先看看AI新闻。",
"emptyCta": "阅读AI新闻",
"backToTech": "← 返回科技",
"langNotice": "AI Daily Tech只以英文和西班牙文发布。你正在阅读英文版。",
"langNotice": "暂无中文版的科技报道以英文原文显示。",
"feedTitle": "AI Daily Tech"
},
"pagination": {
Expand Down Expand Up @@ -373,7 +373,7 @@
"all": "查看全部报道",
"weekly": "每周摘要",
"lead": "头条",
"langNote": "新闻以英文显示。",
"langNote": "暂无中文版的报道以英文显示。",
"tech": "科技"
},
"teaser": {
Expand Down
8 changes: 5 additions & 3 deletions app/[lang]/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ import { homeAboutDoc } from "@/lib/seo/content/sitePages";
import { homeGraph } from "@/lib/seo/pageGraphs";
import { markdownPathOf } from "@/lib/seo/registry";
import { pageMetadata } from "@/lib/seo/metadata";
import { type Lang, toLang, INTL_LOCALE, PUNCT, contentLangFor } from "@/lib/domain";
import { type Lang, toLang, INTL_LOCALE, PUNCT, blogLangFor } from "@/lib/domain";

export const revalidate = 300;

Expand All @@ -80,10 +80,12 @@ const NEWS_WINDOW = 30;
*/
async function loadNews(lang: Lang): Promise<{ marquee: MarqueeItem[]; latest: LatestArticle[]; hasTech: boolean }> {
try {
// AI Daily is written in es/en; /pt shows the English headlines (and says so).
const articles = await listAllPublishedArticles(contentLangFor(lang), NEWS_WINDOW);
// AI Daily is written in es/en; /pt shows the English headlines (and says so);
// v1.8.8: /zh shows each story in Chinese when it has a Chinese version.
const articles = await listAllPublishedArticles(blogLangFor(lang), NEWS_WINDOW);
const latest = selectHomeLatest(articles, LATEST_COUNT).map((a) => ({
slug: a.slug,
lang: a.lang,
title: a.title,
deck: a.deck,
category: a.category,
Expand Down
16 changes: 13 additions & 3 deletions app/sitemap.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ import type { MetadataRoute } from "next";
import { loadArticles, loadBenchmarksAsOf, loadEditions } from "@/lib/seo/dynamic";
import { articleUrl, editionUrl, latestUpdated } from "@/lib/seo/dynamicUrls";
import { newest, toDate } from "@/lib/seo/dates";
import { staticSeoUrls, withoutEmptySectionIndexes, type SeoUrl } from "@/lib/seo/registry";
import { staticSeoUrls, withoutEmptySectionIndexes, zhBlogIndexUrls, type SeoUrl } from "@/lib/seo/registry";
import { CONTENT_LANGS, isContentLang, sectionOfEdition } from "@/lib/domain";
import { HREFLANG, LOCALES, X_DEFAULT_LOCALE, absUrl, swapLocale, type Locale } from "@/lib/seo/site";

Expand Down Expand Up @@ -57,7 +57,11 @@ export default async function sitemap(): Promise<MetadataRoute.Sitemap> {
const fallbackDate = new Date(0);

const [articlesByLang, editions, benchmarksAsOf] = await Promise.all([
Promise.all(LOCALES.map(async (l) => [l, isContentLang(l) ? await loadArticles(l) : []] as const)),
// v1.8.8: zh lists the stories that have their own Chinese text (the others
// are views of the English original and stay out, as under /pt).
Promise.all(
LOCALES.map(async (l) => [l, isContentLang(l) ? await loadArticles(l) : l === "zh" ? (await loadArticles("zh")).filter((a) => a.lang === "zh") : []] as const)
),
loadEditions(),
loadBenchmarksAsOf(),
]);
Expand All @@ -74,7 +78,13 @@ export default async function sitemap(): Promise<MetadataRoute.Sitemap> {
const newestTech = latestUpdated(articles.filter((a) => sectionOfEdition(a.edition) === "tech").map(articleUrl));

// v1.8.4: an index with no stories yet (the Tech one) stays out until its first story.
const urls = withoutEmptySectionIndexes(staticSeoUrls(lang), lang, articles).map((u): SeoUrl => {
// v1.8.8: the es/en indexes name the zh one once it exists (reciprocal hreflang).
const withZh = (section: "ai" | "tech") => articles.some((a) => a.alternateSlugs.zh && sectionOfEdition(a.edition) === section);
const zhLocales = { locales: [...CONTENT_LANGS, "zh"] as const };
const base = lang === "zh" ? [...staticSeoUrls(lang), ...zhBlogIndexUrls(articles)] : withoutEmptySectionIndexes(staticSeoUrls(lang), lang, articles);
const urls = base.map((u): SeoUrl => {
if (isContentLang(lang) && u.path === `/${lang}/blog` && withZh("ai")) u = { ...u, ...zhLocales };
if (isContentLang(lang) && u.path === `/${lang}/blog/tech` && withZh("tech")) u = { ...u, ...zhLocales };
// Pages whose content is driven by data take the data's date.
if (u.path === `/${lang}`) return { ...u, updated: newest(u.updated, newestArticle) ?? u.updated };
if (u.path === `/${lang}/blog`) return { ...u, updated: newest(u.updated, newestAi) ?? u.updated };
Expand Down
36 changes: 28 additions & 8 deletions components/blog/BlogIndexView.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ import {
import type { BlogFilterState } from "@/lib/blog/filters";
import { listAllPublishedArticles } from "@/lib/blog/server";
import type { ArticleCard, PublicArticle } from "@/lib/blog/types";
import { contentIsFallback, contentLangFor, type BlogSection, type ContentLang, type Lang } from "@/lib/domain";
import { CONTENT_LANGS, blogLangFor, contentIsFallback, contentLangFor, type ArticleLang, type BlogSection, type Lang } from "@/lib/domain";
import { pageMetadata } from "@/lib/seo/metadata";
import { getSiteUrl } from "@/lib/seo/site";
import { getXLinks } from "@/lib/social";
Expand Down Expand Up @@ -103,7 +103,15 @@ export function sectionCopy(dict: Dict, section: BlogSection) {
* Never let a Firestore problem break the page — an empty feed is a valid
* state, and `next build` runs without a service account by design.
*/
async function loadCards(lang: ContentLang, section: BlogSection): Promise<ArticleCard[]> {
/**
* v1.8.8 — the es/en/pt index of a section announces a /zh alternate once one of
* its stories has Chinese text (`hasZh` on the card), so hreflang stays reciprocal.
*/
function hasZhIndex(cards: ArticleCard[]): boolean {
return cards.some((c) => c.hasZh);
}

async function loadCards(lang: ArticleLang, section: BlogSection): Promise<ArticleCard[]> {
try {
const articles = await listAllPublishedArticles(lang, FILTER_WINDOW);
return cardsOfSection(articles, section).map(toCard);
Expand Down Expand Up @@ -135,6 +143,7 @@ function toCard(article: PublicArticle): ArticleCard {
models: article.models,
readingMinutes: article.readingMinutes,
image: article.image,
hasZh: Boolean(article.alternateSlugs.zh),
};
}

Expand Down Expand Up @@ -170,17 +179,27 @@ export async function blogIndexMetadata(lang: Lang, sp: BlogSearchParams, sectio
const dict = await getDictionary(lang);
const copy = sectionCopy(dict, section);

const cl = contentLangFor(lang);
// v1.8.8: /zh is its own index once a story of the section has Chinese text.
const cards = await loadCards(blogLangFor(lang), section);
const zhIndex = lang === "zh" && cards.some((c) => c.lang === "zh");
const cl = zhIndex ? "zh" : contentLangFor(lang);
const base = blogSectionIndexPath(cl, section);
const canonical = narrowed || page === 1 ? base : `${base}?page=${page}`;
const title = `${copy.title} — ${copy.tagline}`;

// v1.8.4: the Tech index before its first story is an empty listing. It is
// noindex until then (and out of sitemap.xml and llms.txt, see
// withoutEmptySectionIndexes), and indexable again with the first story.
const empty = section === "tech" && (await loadCards(cl, section)).length === 0;

const meta = pageMetadata({ lang, contentLang: cl, path: blogSectionIndexPath(lang, section), title, description: copy.description });
const empty = section === "tech" && cards.length === 0;

const meta = pageMetadata({
lang,
contentLang: cl,
...(zhIndex || hasZhIndex(cards) ? { locales: [...CONTENT_LANGS, "zh"] as const } : {}),
path: blogSectionIndexPath(lang, section),
title,
description: copy.description,
});
return {
...meta,
// Filter permutations are search results, not content: keeping them out of
Expand All @@ -191,7 +210,7 @@ export async function blogIndexMetadata(lang: Lang, sp: BlogSearchParams, sectio
...meta.alternates,
canonical,
// <link rel="alternate" type="application/rss+xml">: each index advertises its own feed.
types: { "application/rss+xml": blogSectionFeedPath(cl, section) },
types: { "application/rss+xml": blogSectionFeedPath(cl === "zh" ? "en" : cl, section) },
},
openGraph: { ...meta.openGraph, url: canonical },
};
Expand All @@ -207,7 +226,7 @@ export default async function BlogIndexView({ lang: l, sp, section }: { lang: La
const copy = sectionCopy(dict, section);
const basePath = blogSectionIndexPath(l, section);

const all = await loadCards(contentLangFor(l), section);
const all = await loadCards(blogLangFor(l), section);
const filtered = applyFilters(all, filters);
const { items, page, pages, total, hasPrev, hasNext } = paginate(filtered, requestedPage, BLOG_PAGE_SIZE);

Expand Down Expand Up @@ -289,6 +308,7 @@ export default async function BlogIndexView({ lang: l, sp, section }: { lang: La
<p className="mt-2 max-w-xl text-base text-ink-muted sm:text-lg">{copy.tagline}</p>
<ContentLangNotice
lang={l}
show={contentIsFallback(l) && (l !== "zh" || all.some((c) => c.lang !== "zh"))}
text={copy.langNotice}
hrefs={{ es: blogSectionIndexPath("es", section), en: blogSectionIndexPath("en", section) }}
className="mt-4"
Expand Down
9 changes: 8 additions & 1 deletion components/blog/ContentLangNotice.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,16 +13,23 @@ export default function ContentLangNotice({
lang,
text,
hrefs,
show,
className = "",
}: {
lang: Lang;
/**
* v1.8.8 — whether the shown content is in another language. Defaults to "the
* interface has no edition of its own" (pt); under /zh it is decided story by
* story, since stories now also come in Chinese.
*/
show?: boolean;
/** The translated notice (dict.blog.langNotice). */
text: string;
/** Where the same content lives in each language it was written in. */
hrefs: Record<ContentLang, string>;
className?: string;
}) {
if (!contentIsFallback(lang)) return null;
if (!(show ?? contentIsFallback(lang))) return null;

return (
<aside role="note" data-content-lang-notice className={["surface-soft border-l-4 p-4 text-sm", className].join(" ")}>
Expand Down
17 changes: 9 additions & 8 deletions components/home/LatestDaily.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ import Link from "next/link";
import type { PublicArticle } from "@/lib/blog/types";
import { formatEditorialDate } from "@/lib/blog/dates";
import { cardDisplayDate } from "@/components/blog/ArticleCardItem";
import { LANG_TAG, PUNCT, contentIsFallback, contentLangFor, type Lang } from "@/lib/domain";
import { LANG_TAG, PUNCT, contentIsFallback, type Lang } from "@/lib/domain";

type Dict = {
title: string;
Expand All @@ -33,7 +33,7 @@ type Dict = {
tech: string;
};

export type LatestArticle = Pick<PublicArticle, "slug" | "title" | "deck" | "category" | "edition" | "readingMinutes" | "eventDate" | "publishedAt">;
export type LatestArticle = Pick<PublicArticle, "slug" | "lang" | "title" | "deck" | "category" | "edition" | "readingMinutes" | "eventDate" | "publishedAt">;

/**
* The label of a story in a list. Daily stories are labelled by topic; the two
Expand Down Expand Up @@ -84,8 +84,9 @@ export default function LatestDaily({
const [lead, ...rest] = articles;
// v1.8.3: under /pt the stories are the English edition. The block now says so
// (the blog pages already did) and marks the English text with its language.
const fallbackContent = contentIsFallback(lang);
const contentLangTag = fallbackContent ? LANG_TAG[contentLangFor(lang)] : undefined;
// v1.8.8: story by story — under /zh a story may be Chinese or (older ones) English.
const fallbackContent = contentIsFallback(lang) && articles.some((a) => a.lang !== lang);
const tagOf = (a: LatestArticle) => (a.lang !== lang ? LANG_TAG[a.lang] : undefined);
// The top story shows label, date and reading time; the narrower secondary
// stories keep label + date so the line never wraps mid-way.
const meta = (a: LatestArticle, full: boolean) => {
Expand Down Expand Up @@ -139,8 +140,8 @@ export default function LatestDaily({
{PUNCT[lang].colon}
</span>
{meta(lead, true)}
<h3 lang={contentLangTag} className="blog-row-title mt-3 font-title text-xl font-semibold leading-snug text-ink sm:text-2xl">{lead.title}</h3>
{lead.deck ? <p lang={contentLangTag} className="mt-2 line-clamp-3 max-w-3xl text-sm leading-relaxed text-ink-muted">{lead.deck}</p> : null}
<h3 lang={tagOf(lead)} className="blog-row-title mt-3 font-title text-xl font-semibold leading-snug text-ink sm:text-2xl">{lead.title}</h3>
{lead.deck ? <p lang={tagOf(lead)} className="mt-2 line-clamp-3 max-w-3xl text-sm leading-relaxed text-ink-muted">{lead.deck}</p> : null}
</Link>

{rest.length > 0 ? (
Expand All @@ -149,8 +150,8 @@ export default function LatestDaily({
<li key={a.slug} className="min-w-0">
<Link href={`/${lang}/blog/${a.slug}`} className="blog-row group block h-full rounded-xl px-3 py-3">
{meta(a, false)}
<h3 lang={contentLangTag} className="blog-row-title mt-1.5 font-title text-base font-semibold leading-snug text-ink">{a.title}</h3>
{a.deck ? <p lang={contentLangTag} className="mt-1 line-clamp-2 text-sm leading-relaxed text-ink-muted">{a.deck}</p> : null}
<h3 lang={tagOf(a)} className="blog-row-title mt-1.5 font-title text-base font-semibold leading-snug text-ink">{a.title}</h3>
{a.deck ? <p lang={tagOf(a)} className="mt-1 line-clamp-2 text-sm leading-relaxed text-ink-muted">{a.deck}</p> : null}
</Link>
</li>
))}
Expand Down
7 changes: 4 additions & 3 deletions components/home/NewsMarquee.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
import Link from "next/link";
import { useEffect, useRef, useState, useSyncExternalStore } from "react";
import type { MarqueeItem } from "@/lib/blog/marquee";
import { LANG_TAG, contentIsFallback, contentLangFor, type Lang } from "@/lib/domain";
import { LANG_TAG, contentIsFallback, type Lang } from "@/lib/domain";

type Dict = { label: string; pause: string; play: string };

Expand All @@ -40,15 +40,16 @@ function useReducedMotion() {
function Headlines({ items, lang, hidden }: { items: MarqueeItem[]; lang: Lang; hidden?: boolean }) {
// v1.8.3: under an interface language without its own edition (pt) the headlines
// are English; say so to assistive tech and translation tools (WCAG 3.1.2).
const contentLangTag = contentIsFallback(lang) ? LANG_TAG[contentLangFor(lang)] : undefined;
// v1.8.8: headline by headline — under /zh a story may be Chinese or English.
const tagOf = (item: MarqueeItem) => (contentIsFallback(lang) && item.lang !== lang ? LANG_TAG[item.lang] : undefined);
return (
<ul className="flex shrink-0 items-center gap-8 pr-8" aria-hidden={hidden || undefined} inert={hidden || undefined}>
{items.map((item) => (
<li key={item.slug} className="flex shrink-0 items-center gap-8">
<Link
href={`/${lang}/blog/${item.slug}`}
tabIndex={hidden ? -1 : undefined}
lang={contentLangTag}
lang={tagOf(item)}
className="whitespace-nowrap text-sm text-ink-muted transition-colors hover:text-ink focus-visible:text-ink"
>
{item.title}
Expand Down
Loading