Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.
TypeScript ai-agentsbill-of-materialserpinventory-managementleanmanufacturingmanufacturing-execution-systemmcp-servermesmrpopen-source-erppostgresqlproduction-planningqmsquality-management-systemreact-routerself-hostedsupabasetraceabilitytypescript
fix(academy): reliable TOC navigation and accurate scrollspy
Sidwebworks67c0c0b17fb0
diff --git a/apps/academy/app/components/OnThisPage.tsx b/apps/academy/app/components/OnThisPage.tsxindex eb7b671988..fb78b99f6f 100644--- a/apps/academy/app/components/OnThisPage.tsx+++ b/apps/academy/app/components/OnThisPage.tsx@@ -5,15 +5,18 @@ type TocLesson = { id: string; text: string };type TocTopic = { id: string; text: string; lessons: TocLesson[] };/** "On this page" rail — an outline of the article's `section[id]` topics and,- * nested under each, its lesson rows (`[data-toc-lesson]`). Scrollspies the- * active anchor. Renders nothing when the page has no such sections, so it- * self-hides on pages without a topic list. */+ * nested under each, its lesson rows (`[data-toc-lesson]`). Only the topic+ * carries the blue active state; lessons are quiet jump links. Renders nothing+ * when the page has no such sections. */export function OnThisPage() {const { pathname } = useLocation();const [topics, setTopics] = useState<TocTopic[]>([]);- const [active, setActive] = useState("");+ const [activeTopic, setActiveTopic] = useState("");const navRef = useRef<HTMLElement>(null);const activeRef = useRef<HTMLAnchorElement>(null);+ // While a click-driven scroll is animating, freeze the scrollspy so it can't+ // override the clicked topic as the page glides past intermediate sections.+ const suppressRef = useRef(false);// Keep the active entry visible inside the TOC's own scroll area (like docs) —// scrolls only the nav container, never the page.@@ -36,7 +39,7 @@ export function OnThisPage() {behavior: "smooth"});}- }, [active]);+ }, [activeTopic]);// biome-ignore lint/correctness/useExhaustiveDependencies: re-scan on route changeuseEffect(() => {@@ -56,24 +59,28 @@ export function OnThisPage() {.filter((t) => t.text.trim());setTopics(items);- // Observe every topic + lesson anchor, in document order, for scrollspy.- const nodes = sections.flatMap((section) => [- section,- ...Array.from(section.querySelectorAll<HTMLElement>("[data-toc-lesson]"))- ]);- if (nodes.length === 0) return;+ if (sections.length === 0) return;- // Active = the deepest anchor whose top has scrolled above the fold line.- // Iterating in document order means a lesson wins over its parent section- // (both are "above the line", the lesson is last).+ // Active topic = the deepest section whose top has scrolled above the+ // reading line (~a third down the viewport, where the eye actually is).+ // At the very bottom of the page the line can't reach the last section,+ // so snap to the final one.const recompute = () => {- const line = 120;- let current = nodes[0]?.id ?? "";- for (const n of nodes) {- if (n.getBoundingClientRect().top <= line) current = n.id;- else break;+ if (suppressRef.current) return;+ const line = Math.max(120, window.innerHeight * 0.33);+ const doc = document.documentElement;+ const atBottom =+ window.innerHeight + window.scrollY >= doc.scrollHeight - 2;+ let current = sections[0]?.id ?? "";+ if (atBottom) {+ current = sections[sections.length - 1]?.id ?? current;+ } else {+ for (const s of sections) {+ if (s.getBoundingClientRect().top <= line) current = s.id;+ else break;+ }}- setActive(current);+ setActiveTopic(current);};recompute();@@ -81,25 +88,69 @@ export function OnThisPage() {rootMargin: "-110px 0px -60% 0px",threshold: [0, 1]});- for (const n of nodes) observer.observe(n);+ for (const s of sections) observer.observe(s);window.addEventListener("scroll", recompute, { passive: true });+ window.addEventListener("resize", recompute, { passive: true });return () => {observer.disconnect();window.removeEventListener("scroll", recompute);+ window.removeEventListener("resize", recompute);};}, [pathname]);- // Explicit scroll on click — a bare `#hash` anchor gets swallowed by the SPA's- // scroll restoration, so drive it ourselves. scrollIntoView honors the target's- // scroll-margin (the fixed-header offset); the hash update lights the :target row.- const go = (id: string) => (e: MouseEvent) => {+ // Fully self-driven scroll. Native `#hash` anchors race the SPA router's+ // scroll restoration and browser smooth-scroll support is inconsistent, so:+ // preventDefault, update the hash via replaceState (no router navigation),+ // and animate window.scrollTo with our own rAF ease. A lesson click lights+ // its parent topic.+ const go = (id: string, topicId: string) => (e: MouseEvent) => {e.preventDefault();- setActive(id);- document.getElementById(id)?.scrollIntoView({- behavior: "smooth",- block: "start"- });+ const el = document.getElementById(id);+ if (!el) return;+ suppressRef.current = true;+ setActiveTopic(topicId);window.history.replaceState(null, "", `#${id}`);++ // Flash the jumped-to lesson row so the eye lands on it.+ if (el.hasAttribute("data-toc-lesson")) {+ el.classList.remove("lesson-flash");+ void el.offsetWidth; // restart the animation if re-clicked+ el.classList.add("lesson-flash");+ el.addEventListener(+ "animationend",+ () => el.classList.remove("lesson-flash"),+ { once: true }+ );+ }++ const HEADER_OFFSET = 96; // matches the targets' scroll-mt-24+ const startY = window.scrollY;+ const maxY = document.documentElement.scrollHeight - window.innerHeight;+ const targetY = Math.max(+ 0,+ Math.min(el.getBoundingClientRect().top + startY - HEADER_OFFSET, maxY)+ );++ if (window.matchMedia("(prefers-reduced-motion: reduce)").matches) {+ window.scrollTo(0, targetY);+ suppressRef.current = false;+ return;+ }++ const dist = targetY - startY;+ const duration = 420;+ const t0 = performance.now();+ const ease = (t: number) => 1 - (1 - t) ** 3; // easeOutCubic+ const step = (now: number) => {+ const p = Math.min(1, (now - t0) / duration);+ window.scrollTo(0, startY + dist * ease(p));+ if (p < 1) {+ requestAnimationFrame(step);+ } else {+ suppressRef.current = false;+ }+ };+ requestAnimationFrame(step);};if (topics.length === 0) return null;@@ -114,46 +165,34 @@ export function OnThisPage() {</p><ul className="m-0 flex list-none flex-col border-l border-ed-hairline p-0">{topics.flatMap((topic) => {- const topicInFocus =- active === topic.id || topic.lessons.some((l) => l.id === active);+ const isActive = activeTopic === topic.id;return [<li key={topic.id} className="-ml-px"><a- ref={active === topic.id ? activeRef : undefined}+ ref={isActive ? activeRef : undefined}href={`#${topic.id}`}- onClick={go(topic.id)}- aria-current={active === topic.id ? "location" : undefined}- className={`block border-l-2 py-1.5 pl-4 text-ed-13 leading-snug no-underline transition-colors duration-150 ${- active === topic.id- ? "border-ed-brand-ink font-demi text-ed-brand-ink"- : topicInFocus- ? "border-transparent font-demi text-ed-ink"- : "border-transparent font-demi text-ed-ink/60 hover:text-ed-ink"+ onClick={go(topic.id, topic.id)}+ aria-current={isActive ? "location" : undefined}+ className={`block border-l-2 py-1.5 pl-4 text-ed-13 font-demi leading-snug no-underline transition-colors duration-150 ${+ isActive+ ? "border-ed-brand-ink text-ed-brand-ink"+ : "border-transparent text-ed-ink/60 hover:text-ed-ink"}`}>{topic.text}</a></li>,- ...topic.lessons.map((lesson) => {- const isActive = active === lesson.id;- return (- <li key={lesson.id} className="-ml-px">- <a- ref={isActive ? activeRef : undefined}- href={`#${lesson.id}`}- onClick={go(lesson.id)}- aria-current={isActive ? "location" : undefined}- className={`block border-l-2 py-1 pl-7 text-ed-12 leading-snug no-underline transition-colors duration-150 ${- isActive- ? "border-ed-brand-ink font-book text-ed-brand-ink"- : "border-transparent font-book text-ed-ink/50 hover:text-ed-ink/80"- }`}- >- {lesson.text}- </a>- </li>- );- })+ ...topic.lessons.map((lesson) => (+ <li key={lesson.id} className="-ml-px">+ <a+ href={`#${lesson.id}`}+ onClick={go(lesson.id, topic.id)}+ className="block border-l-2 border-transparent py-1 pl-7 text-ed-12 font-book leading-snug text-ed-ink/50 no-underline transition-colors duration-150 hover:text-ed-ink/80"+ >+ {lesson.text}+ </a>+ </li>+ ))];})}</ul>diff --git a/apps/academy/app/root.tsx b/apps/academy/app/root.tsxindex 248b79fbd4..e0ebbe5439 100644--- a/apps/academy/app/root.tsx+++ b/apps/academy/app/root.tsx@@ -136,7 +136,7 @@ function Document({title?: string;}) {return (- <html lang="en" className="h-full overflow-x-hidden">+ <html lang="en" className="overflow-x-hidden"><head><meta charSet="utf-8" /><meta name="viewport" content="width=device-width, initial-scale=1" />@@ -144,7 +144,7 @@ function Document({<title>{title}</title><Links /></head>- <body className="h-full bg-background antialiased selection:bg-primary/10 selection:text-primary">+ <body className="bg-background antialiased selection:bg-primary/10 selection:text-primary"><TooltipProvider>{children}</TooltipProvider><Toaster position="bottom-right" visibleToasts={5} /><ScrollRestoration />diff --git a/apps/academy/app/routes/course+/$moduleId.$courseId.tsx b/apps/academy/app/routes/course+/$moduleId.$courseId.tsxindex ad083baf08..bbeb483368 100644--- a/apps/academy/app/routes/course+/$moduleId.$courseId.tsx+++ b/apps/academy/app/routes/course+/$moduleId.$courseId.tsx@@ -277,7 +277,7 @@ function LessonRow({id={tocAnchor ? `lesson-${lessonId}` : undefined}data-toc-lesson={tocAnchor ? "" : undefined}data-toc-title={tocAnchor ? name : undefined}- className="flex scroll-mt-24 items-center justify-between gap-3 rounded-lg px-2 py-2 no-underline transition-colors hover:bg-ed-ink/[0.03] target:bg-ed-accent-fill target:ring-1 target:ring-ed-blue-border"+ className="flex scroll-mt-24 items-center justify-between gap-3 rounded-lg px-2 py-2 no-underline transition-colors hover:bg-ed-ink/[0.03]"><span className="flex min-w-0 items-center gap-3"><LessonThumb completed={completed} className="w-16" />diff --git a/apps/academy/app/styles/editorial.css b/apps/academy/app/styles/editorial.cssindex 9f203e284d..085025537b 100644--- a/apps/academy/app/styles/editorial.css+++ b/apps/academy/app/styles/editorial.css@@ -129,9 +129,18 @@color: rgba(38, 35, 35, 0.78);}-/* Anchor navigation (the On-this-page TOC) glides; motion-sensitive users jump. */-@media (prefers-reduced-motion: no-preference) {- html {- scroll-behavior: smooth;+/* Flash a lesson row the TOC jumped to — hold the accent, then fade out. */+@keyframes lesson-flash {+ 0%,+ 55% {+ background-color: var(--color-ed-accent-fill);+ box-shadow: inset 0 0 0 1px var(--color-ed-blue-border);}+ 100% {+ background-color: transparent;+ box-shadow: inset 0 0 0 1px transparent;+ }+}+.lesson-flash {+ animation: lesson-flash 2.2s ease-out both;}