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
10 changes: 10 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,16 @@ Dates display in the selected language using UTC. Reading time is estimated at
200 words per minute, with a minimum of one minute.
Set optional `youtubeId` to an 11-character YouTube video ID to show a player.

### Article contents

Articles with at least one Markdown `##` or `###` heading automatically show an
index ("Indice" in Italian, "Contents" in English), with subsections nested under
their parent section. At desktop widths of 1100px and above, the index stays in a
sticky right sidebar; on smaller screens it appears in an expandable box before
the article body. The current section is highlighted while scrolling. Links work
without JavaScript, and articles without these headings keep the single-column
layout. No frontmatter setting or manually maintained list is needed.

### Tags

Use canonical English tag identifiers shared across both languages, for example
Expand Down
85 changes: 85 additions & 0 deletions src/components/TableOfContents.astro
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
---
import type { MarkdownHeading } from 'astro';

interface Props {
headings: MarkdownHeading[];
label: string;
showTitle?: boolean;
}

const { headings, label, showTitle = false } = Astro.props;
const sections: { heading: MarkdownHeading; children: MarkdownHeading[] }[] = [];
for (const heading of headings) {
const parent = sections.at(-1);
if (heading.depth === 3 && parent?.heading.depth === 2) {
parent.children.push(heading);
} else {
sections.push({ heading, children: [] });
}
}
---
<nav class="toc-nav" aria-label={label} data-table-of-contents>
{showTitle && <h2 class="toc-title">{label}</h2>}
<ul class="toc-list">
{sections.map(({ heading, children }) => (
<li>
<a href={`#${heading.slug}`} data-heading-id={heading.slug}>{heading.text}</a>
{children.length > 0 && <ul>
{children.map((child) => <li><a href={`#${child.slug}`} data-heading-id={child.slug}>{child.text}</a></li>)}
</ul>}
</li>
))}
</ul>
</nav>

<script>
const navigations = [...document.querySelectorAll<HTMLElement>('[data-table-of-contents]')];
const links = navigations.flatMap((nav) => [...nav.querySelectorAll<HTMLAnchorElement>('a[data-heading-id]')]);
const headings = [...new Set(links.map((link) => document.getElementById(link.dataset.headingId!)))]
.filter((heading): heading is HTMLElement => heading !== null);

if (headings.length > 0) {
let activeId = '';
let scheduled = false;

const updateActiveHeading = () => {
scheduled = false;
let current = headings[0];
for (const heading of headings) {
if (heading.getBoundingClientRect().top > 96) break;
current = heading;
}
// The last section may be too short to reach the top of the viewport.
if (window.scrollY > 0 && window.innerHeight + window.scrollY >= document.documentElement.scrollHeight - 2) {
current = headings[headings.length - 1];
}
if (current.id !== activeId) {
activeId = current.id;
for (const link of links) {
if (link.dataset.headingId === activeId) link.setAttribute('aria-current', 'location');
else link.removeAttribute('aria-current');
}
}

const sidebar = document.querySelector<HTMLElement>('.toc-sidebar');
const activeLink = sidebar?.querySelector<HTMLElement>('[aria-current="location"]');
if (sidebar && activeLink && sidebar.clientHeight > 0) {
const panel = sidebar.getBoundingClientRect();
const active = activeLink.getBoundingClientRect();
if (active.top < panel.top) sidebar.scrollTop += active.top - panel.top;
else if (active.bottom > panel.bottom) sidebar.scrollTop += active.bottom - panel.bottom;
}
};

const scheduleUpdate = () => {
if (scheduled) return;
scheduled = true;
window.requestAnimationFrame(updateActiveHeading);
};
window.addEventListener('scroll', scheduleUpdate, { passive: true });
window.addEventListener('resize', scheduleUpdate);
window.addEventListener('hashchange', scheduleUpdate);
window.addEventListener('load', scheduleUpdate, { once: true });
updateActiveHeading();
}
</script>
5 changes: 3 additions & 2 deletions src/layouts/Base.astro
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,9 @@ interface Props {
lang: Language;
alternatives?: { lang: Language; url: string }[];
activeNav?: 'posts' | 'archive' | 'search' | 'tags' | 'about' | 'faq';
wideArticle?: boolean;
}
const { title, description, lang, alternatives = [], activeNav } = Astro.props;
const { title, description, lang, alternatives = [], activeNav, wideArticle = false } = Astro.props;
const canonical = new URL(Astro.url.pathname, Astro.site);
const labels = lang === 'it'
? { posts: 'Articoli', archive: 'Archivio', search: 'Cerca', tags: 'Tags', about: 'Chi siamo', faq: 'FAQ', nav: 'Navigazione principale', languages: 'Lingua', skip: 'Vai al contenuto', theme: 'Tema scuro' }
Expand Down Expand Up @@ -75,7 +76,7 @@ const navigation = [
</nav>
</div>
</header>
<main id="main" tabindex="-1"><slot /></main>
<main id="main" class:list={{ 'main-with-toc': wideArticle }} tabindex="-1"><slot /></main>
<footer class="site-footer">
<span>© {new Date().getFullYear()} <a href={`/${lang}/`}>{siteConfig.name}</a></span>
<span>Italiano / English</span>
Expand Down
61 changes: 34 additions & 27 deletions src/pages/[lang]/blog/[slug].astro
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
import { render } from 'astro:content';
import Base from '../../../layouts/Base.astro';
import YouTube from '../../../components/YouTube.astro';
import TableOfContents from '../../../components/TableOfContents.astro';
import { visiblePosts, postUrl, readingMinutes, formatDate, type Post } from '../../../lib/posts';
import { tagUrl } from '../../../lib/tags';
export async function getStaticPaths() {
Expand All @@ -16,32 +17,38 @@ const { lang } = post.data;
const related = (await visiblePosts()).filter((item) => item.data.translationKey === post.data.translationKey);
const alternatives = related.map((item) => ({ lang: item.data.lang, url: postUrl(item) }));
const toc = headings.filter((heading) => heading.depth === 2 || heading.depth === 3);
const tocLabel = lang === 'it' ? 'Indice' : 'Contents';
---
<Base title={post.data.title} description={post.data.description} lang={lang} alternatives={alternatives} activeNav="posts">
<article class="post-single">
<a class="back-link" href={`/${lang}/`}>← {lang === 'it' ? 'Tutti gli articoli' : 'All posts'}</a>
<header class="post-header">
<h1>{post.data.title}</h1>
<p class="post-description">{post.data.description}</p>
<div class="post-meta">
<time datetime={post.data.pubDate.toISOString()}>{formatDate(post.data.pubDate, lang)}</time>
<span aria-hidden="true">·</span>
<span>{readingMinutes(post)} {lang === 'it' ? 'min di lettura' : 'min read'}</span>
<span aria-hidden="true">·</span><span>{post.data.author}</span>
</div>
{post.data.draft && <p class="draft">{lang === 'it' ? 'Bozza: non viene pubblicata' : 'Draft: excluded from publication'}</p>}
{related.filter((item) => item.id !== post.id).map((item) => (
<p class="translation-link"><a href={postUrl(item)} lang={item.data.lang} hreflang={item.data.lang}>{item.data.lang === 'it' ? 'Leggi in italiano →' : 'Read in English →'}</a></p>
))}
{post.data.tags.length > 0 && <ul class="post-tags" aria-label="Tags">
{post.data.tags.map((tag) => <li><a href={tagUrl(lang, tag)} rel="tag">{tag}</a></li>)}
</ul>}
</header>
{toc.length > 1 && <details class="table-of-contents" open>
<summary>{lang === 'it' ? 'In questo articolo' : 'On this page'}</summary>
<ul>{toc.map((heading) => <li class:list={{ 'toc-subheading': heading.depth === 3 }}><a href={`#${heading.slug}`}>{heading.text}</a></li>)}</ul>
</details>}
{post.data.youtubeId && <YouTube id={post.data.youtubeId} title={post.data.title} />}
<div class="prose"><Content /></div>
</article>
<Base title={post.data.title} description={post.data.description} lang={lang} alternatives={alternatives} activeNav="posts" wideArticle={toc.length > 0}>
<div class:list={{ 'post-layout': true, 'post-layout-with-toc': toc.length > 0 }}>
<article class="post-single">
<a class="back-link" href={`/${lang}/`}>← {lang === 'it' ? 'Tutti gli articoli' : 'All posts'}</a>
<header class="post-header">
<h1>{post.data.title}</h1>
<p class="post-description">{post.data.description}</p>
<div class="post-meta">
<time datetime={post.data.pubDate.toISOString()}>{formatDate(post.data.pubDate, lang)}</time>
<span aria-hidden="true">·</span>
<span>{readingMinutes(post)} {lang === 'it' ? 'min di lettura' : 'min read'}</span>
<span aria-hidden="true">·</span><span>{post.data.author}</span>
</div>
{post.data.draft && <p class="draft">{lang === 'it' ? 'Bozza: non viene pubblicata' : 'Draft: excluded from publication'}</p>}
{related.filter((item) => item.id !== post.id).map((item) => (
<p class="translation-link"><a href={postUrl(item)} lang={item.data.lang} hreflang={item.data.lang}>{item.data.lang === 'it' ? 'Leggi in italiano →' : 'Read in English →'}</a></p>
))}
{post.data.tags.length > 0 && <ul class="post-tags" aria-label="Tags">
{post.data.tags.map((tag) => <li><a href={tagUrl(lang, tag)} rel="tag">{tag}</a></li>)}
</ul>}
</header>
{toc.length > 0 && <details class="table-of-contents toc-inline" open>
<summary>{tocLabel}</summary>
<TableOfContents headings={toc} label={tocLabel} />
</details>}
{post.data.youtubeId && <YouTube id={post.data.youtubeId} title={post.data.title} />}
<div class="prose"><Content /></div>
</article>
{toc.length > 0 && <aside class="toc-sidebar">
<TableOfContents headings={toc} label={tocLabel} showTitle />
</aside>}
</div>
</Base>
17 changes: 15 additions & 2 deletions src/styles/global.css
Original file line number Diff line number Diff line change
Expand Up @@ -116,8 +116,15 @@ main:focus { outline: none; }
.translation-link { font-size: 13px; margin: 14px 0 0; }
.table-of-contents, .faq-list details { border: 1px solid var(--border); background: var(--surface); padding: 18px 22px; border-radius: 8px; margin: 24px 0; }
.table-of-contents summary, .faq-list summary { font-weight: 600; }
.table-of-contents ul { padding-left: 18px; font-size: 14px; margin-bottom: 0; }
.toc-subheading { margin-left: 18px; }
.post-single { min-width: 0; }
.toc-sidebar { display: none; }
.toc-title { margin: 0 0 16px; font-size: 14px; font-weight: 650; letter-spacing: normal; }
.toc-list, .toc-list ul { list-style: none; padding: 0; margin: 0; font-size: 13px; line-height: 1.5; }
.toc-list ul { padding-left: 16px; }
.toc-list a { display: block; border-left: 2px solid transparent; padding: 7px 12px; color: var(--muted); }
.toc-list a:hover { color: var(--text); text-decoration: none; }
.toc-list a[aria-current='location'] { color: var(--focus); border-left-color: var(--focus); font-weight: 600; }
.toc-inline .toc-nav { margin-top: 14px; }
.faq-list p { margin: 16px 0 0; }
.prose { font-size: 18px; line-height: 1.85; }
.prose h2 { margin: 40px 0 20px; font-size: 28px; }
Expand All @@ -134,6 +141,12 @@ main:focus { outline: none; }
.archive-entry .draft { margin-bottom: 0; }
.social-links { display: flex; gap: 20px; flex-wrap: wrap; margin-top: 24px; font-size: 14px; }
.site-footer { max-width: 736px; width: calc(100% - 48px); margin: 0 auto; padding: 24px 0 30px; border-top: 1px solid var(--border); display: flex; flex-wrap: wrap; justify-content: space-between; gap: 8px 24px; font-size: 12px; color: var(--muted); }
@media (min-width: 1100px) {
main.main-with-toc { width: min(100% - 80px, 1040px); }
.post-layout-with-toc { display: grid; grid-template-columns: minmax(0, 736px) 240px; gap: 64px; align-items: start; }
.toc-inline { display: none; }
.toc-sidebar { display: block; position: sticky; top: 24px; max-height: calc(100vh - 48px); max-height: calc(100dvh - 48px); overflow-y: auto; overscroll-behavior: contain; scrollbar-width: thin; padding: 6px 6px 6px 20px; border-left: 1px solid var(--border); }
}
@media (max-width: 850px) {
.header-inner { flex-wrap: wrap; gap: 10px 20px; padding: 16px 24px 8px; }
.brand-tools { flex: 1; }
Expand Down
Loading