Skip to content

Commit

Permalink
Add default example on page load (#2834)
Browse files Browse the repository at this point in the history
  • Loading branch information
joshwooding authored Dec 8, 2023
1 parent 814e5ba commit 73a3022
Showing 1 changed file with 40 additions and 6 deletions.
46 changes: 40 additions & 6 deletions site/src/components/components/ExamplesListView.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,11 @@
import { FC, ReactElement, useState, Children } from "react";
import {
FC,
ReactElement,
useState,
Children,
useEffect,
useMemo,
} from "react";
import {
List,
SelectionChangeHandler,
Expand All @@ -9,22 +16,49 @@ import useIsMobileView from "../../utils/useIsMobileView";
import { formatComponentExampleName } from "./formatComponentExampleName";

import styles from "./ExamplesListView.module.css";
import { useParams, useRouter } from "next/navigation";

type ExamplesListViewProps = { examples: ReactElement[] };

function exampleNameToHash(exampleName: string) {
return exampleName.toLowerCase().replaceAll(" ", "-");
}

const ExamplesListView: FC<ExamplesListViewProps> = ({ examples }) => {
const examplesList: string[] = Children.map(examples, ({ props }) =>
formatComponentExampleName(props.exampleName, props.displayName)
);
const params = useParams();
const router = useRouter();

const [selectedItem, setSelectedItem] = useState<string | null>(
examplesList[0]
const examplesList: string[] = useMemo(
() =>
Children.map(examples, ({ props }) =>
formatComponentExampleName(props.exampleName, props.displayName)
),
[examples]
);

const [selectedItem, setSelectedItem] = useState<string | null>(null);

useEffect(() => {
// window.location.hash could be #hash?query=string and we only want the #hash part.
const hash = window.location.hash.substring(1).split("?")[0];
const exampleInHash = examplesList.find(
(example) => exampleNameToHash(example) === hash
);
setSelectedItem(exampleInHash ?? examplesList[0]);
}, [examplesList, params]);

const isMobileView = useIsMobileView();

const handleSelect: SelectionChangeHandler = (_, selectedItem) => {
setSelectedItem(selectedItem);
if (selectedItem) {
const hash = `#${exampleNameToHash(selectedItem)}`;
if (window.history.pushState) {
window.history.pushState(null, "", hash);
} else {
window.location.hash = hash;
}
}
};

const examplesArray = Children.toArray(examples) as ReactElement[];
Expand Down

1 comment on commit 73a3022

@vercel
Copy link

@vercel vercel bot commented on 73a3022 Dec 8, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please sign in to comment.