brewlog/templates/timeline.html
Jon Seager 949f65ac16
refactor(timeline): denormalize data and simplify frontend
Database:
- Add slug, roaster_slug, brew_data_json columns to timeline_events
- Migration backfills existing data from related tables
- Remove 9-way LEFT JOIN from list query, read directly from columns

Frontend:
- Use CSS :nth-of-type(odd/even) for alternating timeline layout
- Remove JavaScript class manipulation when appending month events
- Simplify infinite scroll month-merging logic

This eliminates query-time JOINs across 5 tables and ~20 lines of
client-side JavaScript for pattern maintenance.
2026-02-03 08:53:29 +00:00

214 lines
7 KiB
HTML

{% extends "base.html" %} {% block title %}Brewlog · Timeline{% endblock %} {% block content %}
<header class="flex flex-col gap-2">
<h1 class="text-3xl font-semibold">Timeline</h1>
<p class="max-w-2xl text-sm text-stone-600">
Follow the history of roasters and roasts in Brewlog.
</p>
</header>
<div class="mt-8">
<section
class="space-y-12"
id="timeline-events"
data-role="timeline-months"
data-empty="{{ months.is_empty() }}"
>
{% if months.is_empty() %}
<p
class="rounded-lg border border-dashed border-amber-300 bg-amber-100/60 p-6 text-sm text-stone-600"
data-role="timeline-empty-state"
>
No events yet.
</p>
{% else %} {% for month in months %} {% include "partials/timeline_month.html" %} {% endfor %}
{% endif %}
<div
id="timeline-loader"
class="mt-8 flex flex-col items-center gap-3"
data-next-url="{% if events.has_next() %}{{ navigator.fragment_page_href(events.next_page().unwrap()) }}{% else %}{% endif %}"
data-has-more="{{ events.has_next() }}"
data-empty="{{ months.is_empty() }}"
>
<button
id="timeline-load-more"
type="button"
class="inline-flex items-center gap-2 rounded-full border border-amber-500 px-4 py-2 text-sm font-semibold text-amber-700 transition hover:border-amber-400 hover:text-amber-600 disabled:cursor-not-allowed disabled:border-amber-200 disabled:text-amber-300"
style="{% if months.is_empty() || !events.has_next() %}display: none{% endif %}"
>
<span aria-hidden="true"></span>
Load more
</button>
<p id="timeline-status" class="text-xs text-stone-500" hidden>Loading…</p>
<p id="timeline-end" class="text-sm text-stone-500" style="{% if events.has_next() || months.is_empty() %}display: none{% endif %}">No more events.</p>
<p id="timeline-error" class="text-sm text-red-600" hidden></p>
</div>
<div id="timeline-sentinel" class="h-1"></div>
</section>
</div>
<script type="module">
const loader = document.getElementById("timeline-loader")
const monthsContainer = document.getElementById("timeline-events")
const loadMoreButton = document.getElementById("timeline-load-more")
const statusLine = document.getElementById("timeline-status")
const endLine = document.getElementById("timeline-end")
const errorLine = document.getElementById("timeline-error")
const sentinel = document.getElementById("timeline-sentinel")
const emptyState = document.querySelector('[data-role="timeline-empty-state"]')
if (loader && monthsContainer && sentinel) {
let nextUrl = loader.dataset.nextUrl || ""
let hasMorePages = loader.dataset.hasMore === "true"
let loading = false
const observer = new IntersectionObserver(
(entries) => {
if (entries.some((entry) => entry.isIntersecting) && hasMorePages && nextUrl) {
void loadMore()
}
},
{ rootMargin: "200px" }
)
const setHasMore = (hasMore, url) => {
hasMorePages = hasMore
nextUrl = url || ""
loader.dataset.hasMore = hasMore ? "true" : "false"
loader.dataset.nextUrl = nextUrl
if (!hasMore) {
if (loadMoreButton) loadMoreButton.style.display = "none"
if (endLine) endLine.style.display = ""
observer.disconnect()
}
}
const appendMonths = (chunk) => {
const monthsFragment = chunk.querySelector("[data-chunk-months]")
if (!monthsFragment) {
return
}
for (const monthNode of Array.from(monthsFragment.children)) {
const anchor = monthNode.id
if (!anchor) {
continue
}
const existing = document.getElementById(anchor)
if (existing) {
// Merge new events into existing month
const existingList = existing.querySelector("ol")
const newList = monthNode.querySelector("ol")
if (existingList && newList) {
// CSS :nth-of-type handles alternating pattern automatically
const newItems = Array.from(newList.querySelectorAll(".timeline-item"))
existingList.append(...newItems)
}
} else {
monthsContainer.insertBefore(monthNode, loader)
}
}
}
const clearEmptyState = () => {
if (emptyState && !emptyState.hidden) {
emptyState.hidden = true
loader.dataset.empty = "false"
}
}
const loadMore = async () => {
if (loading || !hasMorePages || !nextUrl) return
loading = true
if (statusLine) {
statusLine.hidden = false
}
if (errorLine) {
errorLine.hidden = true
}
try {
const response = await fetch(nextUrl, {
headers: {
"X-Requested-With": "fetch",
"datastar-request": "true",
},
})
if (!response.ok) {
throw new Error(`Unexpected response: ${response.status}`)
}
const html = await response.text()
const template = document.createElement("template")
template.innerHTML = html.trim()
const chunk = template.content.querySelector("[data-timeline-chunk]")
if (!chunk) {
throw new Error("Invalid timeline chunk payload")
}
appendMonths(chunk)
clearEmptyState()
const hasMore = chunk.dataset.hasMore === "true"
const url = chunk.dataset.nextUrl || ""
setHasMore(hasMore, url)
} catch (error) {
console.error(error)
if (errorLine) {
errorLine.textContent = "Failed to load more events. Please try again."
errorLine.hidden = false
}
} finally {
loading = false
if (statusLine) {
statusLine.hidden = true
}
}
}
if (loadMoreButton) {
loadMoreButton.addEventListener("click", () => {
void loadMore()
})
}
if (hasMorePages && loader.dataset.empty !== "true") {
observer.observe(sentinel)
}
}
// Sticky header detection - observe all current and future headings
const stickyObserver = new IntersectionObserver(
(entries) => {
entries.forEach((entry) => {
entry.target.classList.toggle("is-stuck", !entry.isIntersecting)
})
},
{ rootMargin: "-1px 0px 0px 0px", threshold: 1 }
)
// Use MutationObserver to watch for new month headings being added
const mutationObserver = new MutationObserver((mutations) => {
mutations.forEach((mutation) => {
mutation.addedNodes.forEach((node) => {
if (node.nodeType === Node.ELEMENT_NODE) {
const heading = node.querySelector?.(".timeline-heading")
if (heading) {
stickyObserver.observe(heading)
}
}
})
})
})
const timelineContainer = document.getElementById("timeline-events")
if (timelineContainer) {
mutationObserver.observe(timelineContainer, { childList: true })
}
// Observe existing headings
document.querySelectorAll(".timeline-heading").forEach((heading) => {
stickyObserver.observe(heading)
})
</script>
{% endblock %}