From 97e9485040c2f8601c3055228e13c26da847ffc3 Mon Sep 17 00:00:00 2001 From: "thomas.ekstrand" Date: Sat, 24 Feb 2024 09:27:24 -0600 Subject: [PATCH] format, lint, remove hash if all closed --- src/components/FaqAccordion.tsx | 32 ++++++++++++++++++++------------ 1 file changed, 20 insertions(+), 12 deletions(-) diff --git a/src/components/FaqAccordion.tsx b/src/components/FaqAccordion.tsx index 4a9a3993..2eb9670d 100644 --- a/src/components/FaqAccordion.tsx +++ b/src/components/FaqAccordion.tsx @@ -1,4 +1,3 @@ -import BrowserOnly from "@docusaurus/BrowserOnly"; import { Accordion, AccordionItem, @@ -21,7 +20,8 @@ export interface Faq { * @return {Element|null} The heading or null */ const findNearestHeading = (element: Element): Element | null => { - const isHeading = (element: Element): boolean => /^H[1-6]$/.test(element.tagName); + const isHeading = (element: Element): boolean => + /^H[1-6]$/.test(element.tagName); let currentElement: Element | null = element; while (currentElement !== null) { @@ -47,25 +47,33 @@ const findNearestHeading = (element: Element): Element | null => { * @param {[type]} void [description] * @return {[type]} [description] */ -const updateURLWithNearestHeadingId = (targetElementUuid: string): void => { - const targetElement: HTMLElement | null = document.getElementById(`accordion__heading-${targetElementUuid}`); +const updateUrlWithNearestHeadingId = (targetElementUuid: string): void => { + const targetElement: HTMLElement | null = document.getElementById( + `accordion__heading-${targetElementUuid}`, + ); - const nearestHeading: Element | null = targetElement ? findNearestHeading(targetElement) : null; + const nearestHeading: Element | null = targetElement + ? findNearestHeading(targetElement) + : null; - if (nearestHeading && nearestHeading.id) { - window.history.pushState({}, '', `#${nearestHeading.id}`); + // Add the hash without scrolling the page + if (nearestHeading?.id) { + window.history.pushState({}, "", `#${nearestHeading.id}`); } -} -export const FaqAccordion = ({ - rows, -}: { rows: Faq[] }): JSX.Element => { + // If they're all collapsed, remove the hash + if (!targetElement) { + window.location.hash = ''; + } +}; + +export const FaqAccordion = ({ rows }: { rows: Faq[] }): JSX.Element => { return ( { - updateURLWithNearestHeadingId(itemUuids); + updateUrlWithNearestHeadingId(itemUuids); }} > {rows.map((row, index) => (