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
25 changes: 22 additions & 3 deletions apps/member/src/app/admin/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -807,6 +807,13 @@ function Events({ api, site }: { api: AdminApi; site: Site }) {
);
}

/** A text box whose typed text stays as typed, while the parsed value goes to onChange. */
function TextAsList({ label, initial, onChange, hint, multiline }: { label: string; initial: string; onChange: (v: string) => void; hint?: string; multiline?: boolean }) {
const [text, setText] = useState(initial);
return <Field label={label} value={text} hint={hint} multiline={multiline} style={multiline ? { minHeight: 90, textAlignVertical: 'top' } : undefined}
onChangeText={(v) => { setText(v); onChange(v); }} />;
}

function Pages({ api, site }: { api: AdminApi; site: Site }) {
const t = useTheme();
const [pages, setPages] = useState<ContentPage[] | null>(null);
Expand Down Expand Up @@ -846,9 +853,21 @@ function Pages({ api, site }: { api: AdminApi; site: Site }) {
<Field label="Summary" value={edit.summary} onChangeText={(v) => setEdit({ ...edit, summary: v })} hint="Shown on cards and used as the search-result description if you leave the SEO description empty." />
<Field label="Body" value={edit.body} onChangeText={(v) => setEdit({ ...edit, body: v })} multiline style={{ minHeight: 220, textAlignVertical: 'top' }} hint={edit.slug === 'home'
? 'Your home page. Title is the headline, Summary the intro. In the body: lines starting with "- " are the checklist, a line starting with "## " starts a section, and each card is a title line with its text on the next line. Leave a blank line between blocks.'
: 'Separate paragraphs with a blank line.'} />
<Field label="SEO title (optional)" value={edit.seoTitle ?? ''} onChangeText={(v) => setEdit({ ...edit, seoTitle: v })} />
<Field label="SEO description (optional)" value={edit.seoDescription ?? ''} onChangeText={(v) => setEdit({ ...edit, seoDescription: v })} />
: 'Separate paragraphs with a blank line. "## " starts a heading, lines starting with "- " make a list, a short title line with text under it makes a question and answer, and [link text](https://…) or [link text](/other-page) makes a link.'} />
<Field label="SEO title (optional)" value={edit.seoTitle ?? ''} onChangeText={(v) => setEdit({ ...edit, seoTitle: v })} hint="What search results show. Aim for under 60 characters." />
<Field label="SEO description (optional)" value={edit.seoDescription ?? ''} onChangeText={(v) => setEdit({ ...edit, seoDescription: v })} hint="Aim for 120 to 160 characters." />
{edit.placement === 'guides' ? (
<>
<ChipPicker label="Notice above the article" options={['none', 'medical', 'products']} value={edit.notice ?? 'none'} onChange={(v: any) => setEdit({ ...edit, notice: v === 'none' ? undefined : v })} />
<Field label="Last reviewed (YYYY-MM-DD, optional)" value={edit.reviewedAt ?? ''} onChangeText={(v) => setEdit({ ...edit, reviewedAt: v.trim() || undefined })} hint="The date you last checked the facts. Shown on the article. Update it when you re-check medical or research news." />
<TextAsList key={'src-' + edit.slug} label="Sources (one per line: Title | https://…)" multiline
initial={(edit.sources ?? []).map((x) => `${x.title} | ${x.url}`).join('\n')}
onChange={(v) => setEdit((e) => e && ({ ...e, sources: v.split('\n').map((l) => l.split('|')).filter((x) => x.length >= 2 && x[0].trim()).map(([t, ...u]) => ({ title: t.trim(), url: u.join('|').trim() })) }))} />
<TextAsList key={'rel-' + edit.slug} label="Related articles (web addresses, comma separated, optional)" initial={(edit.related ?? []).join(', ')}
hint="Shown under Keep reading. Articles in the same category fill any gaps."
onChange={(v) => setEdit((e) => e && ({ ...e, related: v.split(',').map((x) => x.trim()).filter(Boolean) }))} />
</>
) : null}
<Toggle label="Published" value={edit.published} onChange={(v) => setEdit({ ...edit, published: v })} />
<ErrorText error={error} />
<View style={{ flexDirection: 'row', gap: 8, flexWrap: 'wrap' }}>
Expand Down
90 changes: 75 additions & 15 deletions apps/web/app/[slug]/page.tsx
Original file line number Diff line number Diff line change
@@ -1,38 +1,98 @@
import type { Metadata } from 'next';
import { notFound } from 'next/navigation';
import { HOME_SLUG } from '@whatbox/core';
import { baseUrl, getPage, getSite } from '../../lib/site';
import { categorySlug, faqPairs, HOME_SLUG, readingMinutes, relatedArticles } from '@whatbox/core';
import { baseUrl, getPage, getPages, getSite } from '../../lib/site';
import { Body } from '../body';

type Props = { params: Promise<{ slug: string }> };

const longDate = (d: string) => new Date(d.length === 10 ? d + 'T12:00:00Z' : d).toLocaleDateString('en-US', { year: 'numeric', month: 'long', day: 'numeric', timeZone: 'UTC' });

export async function generateMetadata({ params }: Props): Promise<Metadata> {
const { slug } = await params;
const page = slug === HOME_SLUG ? null : await getPage(slug);
if (!page) return {};
const title = page.seoTitle || page.title;
const description = page.seoDescription || page.summary;
const url = `${await baseUrl()}/${page.slug}`;
return {
title: page.seoTitle || page.title,
description: page.seoDescription || page.summary,
alternates: { canonical: `${await baseUrl()}/${page.slug}` },
openGraph: { title: page.seoTitle || page.title, description: page.seoDescription || page.summary, type: page.kind === 'article' ? 'article' : 'website' },
title: { absolute: title.length > 50 ? title : `${title} | ${(await getSite()).name}` },
description,
alternates: { canonical: url },
openGraph: { title, description, url, type: page.kind === 'article' ? 'article' : 'website', ...(page.kind === 'article' ? { modifiedTime: page.updatedAt } : {}) },
twitter: { card: 'summary', title, description },
};
}

export default async function ContentPage({ params }: Props) {
const { slug } = await params;
if (slug === HOME_SLUG) notFound(); // the landing copy, shown at /
const [page, site] = await Promise.all([getPage(slug), getSite()]);
const [page, site, pages, base] = await Promise.all([getPage(slug), getSite(), getPages(), baseUrl()]);
if (!page) notFound();
const ld = page.kind === 'article'
? { '@context': 'https://schema.org', '@type': 'Article', headline: page.title, description: page.summary, dateModified: page.updatedAt, publisher: { '@type': 'Organization', name: site.name } }
: null;
const url = `${base}/${page.slug}`;
const isArticle = page.kind === 'article';
const cat = page.category ? { name: page.category, url: `/guides/${categorySlug(page.category)}` } : null;
const org = { '@type': 'Organization', name: site.name, url: base + '/' };
const ld: object[] = [];
if (isArticle) {
ld.push({
'@context': 'https://schema.org', '@type': 'Article', headline: page.title, description: page.seoDescription || page.summary,
dateModified: page.updatedAt, ...(page.reviewedAt ? { datePublished: page.reviewedAt } : {}),
mainEntityOfPage: url, author: org, publisher: org, ...(cat ? { articleSection: cat.name } : {}),
...(page.sources?.length ? { citation: page.sources.map((s) => s.url) } : {}),
});
ld.push({
'@context': 'https://schema.org', '@type': 'BreadcrumbList', itemListElement: [
{ '@type': 'ListItem', position: 1, name: site.name, item: base + '/' },
{ '@type': 'ListItem', position: 2, name: 'Resources', item: base + '/guides' },
...(cat ? [{ '@type': 'ListItem', position: 3, name: cat.name, item: base + cat.url }] : []),
{ '@type': 'ListItem', position: cat ? 4 : 3, name: page.title, item: url },
],
});
}
const faq = faqPairs(page);
if (faq.length >= 2) ld.push({ '@context': 'https://schema.org', '@type': 'FAQPage', mainEntity: faq.map((f) => ({ '@type': 'Question', name: f.q, acceptedAnswer: { '@type': 'Answer', text: f.a } })) });
const related = isArticle ? relatedArticles(page, pages) : [];
return (
<article className="article">
{ld ? <script type="application/ld+json" dangerouslySetInnerHTML={{ __html: JSON.stringify(ld) }} /> : null}
{page.category ? <span className="eyebrow">{page.category}</span> : null}
{ld.map((d, i) => <script key={i} type="application/ld+json" dangerouslySetInnerHTML={{ __html: JSON.stringify(d).replace(/</g, '\\u003c') }} />)}
{isArticle ? (
<nav aria-label="Breadcrumb" className="crumbs">
<a href="/guides">Resources</a>{cat ? <> <span aria-hidden="true">/</span> <a href={cat.url}>{cat.name}</a></> : null}
</nav>
) : null}
<h1>{page.title}</h1>
{page.summary && page.kind === 'article' ? <p className="lead" style={{ margin: 0 }}>{page.summary}</p> : null}
{page.body.split(/\n\n+/).map((p, i) => <p key={i} style={{ margin: 0 }}>{p}</p>)}
<p className="article-cta"><a href="/guides">More guides</a></p>
{page.summary && isArticle ? <p className="lead" style={{ margin: 0 }}>{page.summary}</p> : null}
{isArticle ? (
<p className="meta muted">{readingMinutes(page)} min read{page.reviewedAt ? <> · Last reviewed <time dateTime={page.reviewedAt}>{longDate(page.reviewedAt)}</time></> : null}</p>
) : null}
{page.notice === 'medical' ? (
<aside className="notice"><strong>Not medical advice.</strong> This article is general information, checked against the sources listed below. Talk with your doctor or a sexual health clinic about your own situation.</aside>
) : page.notice === 'products' ? (
<aside className="notice"><strong>About these links.</strong> We list products and companies members have found useful. {site.name} is not paid to include them. Check sizes, prices and fit with the seller before you buy.</aside>
) : null}
<Body body={page.body} />
{page.sources?.length ? (
<section className="sources" aria-labelledby="sources-h">
<h2 id="sources-h">Sources</h2>
<ul>{page.sources.map((s) => <li key={s.url}><a href={s.url} target="_blank" rel="noopener">{s.title}</a></li>)}</ul>
</section>
) : null}
{related.length ? (
<section className="related" aria-labelledby="related-h">
<h2 id="related-h">Keep reading</h2>
<div className="cols">
{related.map((r) => (
<div className="card guide" key={r.slug}>
{r.category ? <span className="eyebrow small">{r.category}</span> : null}
<h3><a href={`/${r.slug}`}>{r.title}</a></h3>
<p className="muted" style={{ margin: 0 }}>{r.summary}</p>
</div>
))}
</div>
</section>
) : null}
<p className="article-cta"><a href={isArticle && cat ? cat.url : '/guides'}>{isArticle && cat ? `More in ${cat.name}` : 'All resources'}</a></p>
</article>
);
}
30 changes: 30 additions & 0 deletions apps/web/app/body.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
// Renders a public page's body (see parseBody in @whatbox/core for the format admins type).
import { parseBody, parseInline } from '@whatbox/core';

export function Rich({ text }: { text: string }) {
return (
<>
{parseInline(text).map((r, i) => {
if (r.type === 'bold') return <strong key={i}>{r.text}</strong>;
if (r.type === 'link') {
const external = /^https?:\/\//i.test(r.href);
return <a key={i} href={r.href} {...(external ? { target: '_blank', rel: 'noopener' } : {})}>{r.text}</a>;
}
return r.text;
})}
</>
);
}

export function Body({ body }: { body: string }) {
return (
<div className="prose">
{parseBody(body).map((b, i) => {
if (b.type === 'heading') return b.level === 2 ? <h2 key={i}><Rich text={b.text} /></h2> : <h3 key={i}><Rich text={b.text} /></h3>;
if (b.type === 'list') return <ul key={i}>{b.items.map((t, j) => <li key={j}><Rich text={t} /></li>)}</ul>;
if (b.type === 'titled') return <div key={i} className="qa"><h3><Rich text={b.title} /></h3><p><Rich text={b.text} /></p></div>;
return <p key={i}><Rich text={b.text} /></p>;
})}
</div>
);
}
18 changes: 18 additions & 0 deletions apps/web/app/globals.css
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,24 @@ main:focus{outline:none}
.article{max-width:760px;margin:0 auto;padding:48px max(5vw,16px);display:grid;gap:16px}
.article h1{font-size:clamp(32px,5vw,44px)}
.article-cta{margin:16px 0 0;font-weight:700}
.prose{display:grid;gap:14px}
.prose p,.prose ul{margin:0}
.prose h2{font-size:26px;margin-top:14px}
.prose h3{margin:0 0 4px}
.prose ul{padding-left:1.3em;display:grid;gap:6px}
.qa p{margin:0}
.crumbs{font-size:15px;display:flex;gap:8px;flex-wrap:wrap}
.meta{margin:0;font-size:15px}
.notice{background:var(--accentSoft);border-radius:12px;padding:14px 16px;font-size:16px}
.sources,.related{display:grid;gap:12px;margin-top:20px;border-top:1px solid var(--line);padding-top:20px}
.sources h2,.related h2{font-size:22px}
.sources ul{margin:0;padding-left:1.2em;font-size:15px;display:grid;gap:4px}
.related .cols{grid-template-columns:repeat(auto-fit,minmax(200px,1fr))}
.topics{display:flex;flex-wrap:wrap;gap:8px}
.topics a{background:var(--surface);border:1px solid var(--line);border-radius:999px;padding:6px 14px;text-decoration:none;color:var(--ink);font-weight:600;font-size:15px}
.topic{display:grid;gap:16px;margin-top:12px}
.topic .section-title a{color:inherit;text-decoration:none}
.footer-topics{border-bottom:1px solid rgba(255,255,255,.15);padding-bottom:12px}
details{background:var(--surface);border:1px solid var(--line);border-radius:14px;padding:16px 18px}
summary{font-weight:700;cursor:pointer}
.scene{display:block;width:100%;height:auto;margin-bottom:18px;border-radius:28px;overflow:hidden}
Expand Down
41 changes: 41 additions & 0 deletions apps/web/app/guides/[topic]/page.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import type { Metadata } from 'next';
import { notFound } from 'next/navigation';
import { articleCategories } from '@whatbox/core';
import { baseUrl, getPages, getSite } from '../../../lib/site';
import { ArticleCards } from '../list';

type Props = { params: Promise<{ topic: string }> };

const find = async (topic: string) => (await getPages().then(articleCategories)).find((c) => c.slug === topic);

export async function generateMetadata({ params }: Props): Promise<Metadata> {
const { topic } = await params;
const [cat, site] = await Promise.all([find(topic), getSite()]);
if (!cat) return {};
return {
title: `${cat.name}: articles and guides`,
description: `${cat.articles.length} ${site.name} articles on ${cat.name.toLowerCase()}: ${cat.articles.slice(0, 3).map((a) => a.title).join(', ')}.`.slice(0, 160),
alternates: { canonical: `${await baseUrl()}/guides/${cat.slug}` },
};
}

export default async function Topic({ params }: Props) {
const { topic } = await params;
const [cat, base, site] = await Promise.all([find(topic), baseUrl(), getSite()]);
if (!cat) notFound();
const ld = {
'@context': 'https://schema.org', '@type': 'BreadcrumbList', itemListElement: [
{ '@type': 'ListItem', position: 1, name: site.name, item: base + '/' },
{ '@type': 'ListItem', position: 2, name: 'Resources', item: base + '/guides' },
{ '@type': 'ListItem', position: 3, name: cat.name, item: `${base}/guides/${cat.slug}` },
],
};
return (
<section className="wrap section">
<script type="application/ld+json" dangerouslySetInnerHTML={{ __html: JSON.stringify(ld).replace(/</g, '\\u003c') }} />
<nav aria-label="Breadcrumb" className="crumbs"><a href="/guides">Resources</a></nav>
<h1 style={{ fontSize: 40 }}>{cat.name}</h1>
<ArticleCards articles={cat.articles} hideCategory />
</section>
);
}
15 changes: 15 additions & 0 deletions apps/web/app/guides/list.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import type { ContentPage } from '@whatbox/core';

export function ArticleCards({ articles, hideCategory }: { articles: ContentPage[]; hideCategory?: boolean }) {
return (
<div className="cols">
{articles.map((g) => (
<article className="card guide" key={g.slug}>
{g.category && !hideCategory ? <span className="eyebrow small">{g.category}</span> : null}
<h3><a href={`/${g.slug}`}>{g.title}</a></h3>
<p className="muted" style={{ margin: 0 }}>{g.summary}</p>
</article>
))}
</div>
);
}
36 changes: 23 additions & 13 deletions apps/web/app/guides/page.tsx
Original file line number Diff line number Diff line change
@@ -1,22 +1,32 @@
import type { Metadata } from 'next';
import { getPages } from '../../lib/site';
import { articleCategories } from '@whatbox/core';
import { baseUrl, getPages, getSite } from '../../lib/site';
import { ArticleCards } from './list';

export const metadata: Metadata = { title: 'Guides and stories' };
export async function generateMetadata(): Promise<Metadata> {
const site = await getSite();
return {
title: 'Articles and resources',
description: `Guides, advice and resources from ${site.name}: ${site.audience.toLowerCase()}.`,
alternates: { canonical: `${await baseUrl()}/guides` },
};
}

export default async function Guides() {
const guides = (await getPages()).filter((p) => p.placement === 'guides');
const [cats, site] = await Promise.all([getPages().then(articleCategories), getSite()]);
return (
<section className="wrap section">
<h1 style={{ fontSize: 40 }}>Guides and stories</h1>
<div className="cols">
{guides.map((g) => (
<article className="card" key={g.slug}>
<span className="eyebrow" style={{ fontSize: 13 }}>{g.category}</span>
<h2 style={{ fontSize: 20, margin: '6px 0' }}><a href={`/${g.slug}`} style={{ color: 'inherit', textDecoration: 'none' }}>{g.title}</a></h2>
<p className="muted" style={{ margin: 0 }}>{g.summary}</p>
</article>
))}
</div>
<h1 style={{ fontSize: 40 }}>Articles and resources</h1>
<p className="lead">Honest guides and useful links from the {site.name} team. Free to read, no account needed.</p>
{cats.length > 1 ? (
<nav aria-label="Topics" className="topics">{cats.map((c) => <a key={c.slug} href={`#${c.slug}`}>{c.name}</a>)}</nav>
) : null}
{cats.map((c) => (
<section key={c.slug} id={c.slug} className="topic" aria-labelledby={`h-${c.slug}`}>
<h2 id={`h-${c.slug}`} className="section-title"><a href={`/guides/${c.slug}`}>{c.name}</a></h2>
<ArticleCards articles={c.articles} hideCategory />
</section>
))}
</section>
);
}
Loading
Loading