Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor: toc component and global constant #133

Merged
merged 4 commits into from
Nov 30, 2024
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
4 changes: 2 additions & 2 deletions .github/workflows/ci.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ jobs:
uses: actions/checkout@v3

- name: ⚙️ Setup PNPM
uses: pnpm/action-setup@v2.2.1
uses: pnpm/action-setup@v4
with:
version: 8

Expand All @@ -49,7 +49,7 @@ jobs:
uses: actions/checkout@v3

- name: ⚙️ Setup PNPM
uses: pnpm/action-setup@v2.2.1
uses: pnpm/action-setup@v4
with:
version: 8

Expand Down
6 changes: 3 additions & 3 deletions data/giscus.ts → constants/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import type { GiscusProps } from "@giscus/react";
import type { GiscusProps } from '@giscus/react';

const giscusConfigs: GiscusProps = {
export const GISCUS_CONFIGS: GiscusProps = {
repo: 'JohnsonMao/JohnsonMao.github.io',
repoId: 'MDEwOlJlcG9zaXRvcnkzOTU2NjE1MDM=',
category: 'Announcements',
Expand All @@ -12,4 +12,4 @@ const giscusConfigs: GiscusProps = {
loading: 'lazy',
};

export default giscusConfigs;
export const HEADER_HEIGHT = 100;
5 changes: 3 additions & 2 deletions data/i18n/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,8 @@ const dictionaries: Record<Locale, () => Promise<Dictionary>> = {
en: () => import('./locales/en.json'),
};

export const getDictionary = (locale: Locale) => dictionaries[locale]();

export const isLocale = (language: string): language is Locale =>
locales.findIndex((locale) => locale === language) > -1;

export const getDictionary = (locale: Locale) =>
isLocale(locale) ? dictionaries[locale]() : dictionaries[defaultLocale]();
5 changes: 3 additions & 2 deletions src/app/[lang]/Header.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import { CSSProperties, useCallback, useRef, useState } from 'react';

import { HEADER_HEIGHT } from '~/constants';
import Container from '@/components/Container';
import Image from '@/components/Image';
import Link from '@/components/Link';
Expand All @@ -15,7 +16,7 @@ type HeaderProps = {
scrollThreshold?: number;
} & React.PropsWithChildren;

function Header({ avatar, children, scrollThreshold = 100 }: HeaderProps) {
function Header({ avatar, children, scrollThreshold = HEADER_HEIGHT }: HeaderProps) {
const isMounted = useIsMounted();
const [avatarScale, setAvatarScale] = useState(0);
const [headerFixed, setHeaderFixed] = useState(true);
Expand Down Expand Up @@ -52,7 +53,7 @@ function Header({ avatar, children, scrollThreshold = 100 }: HeaderProps) {

const handleAvatarScale = useCallback(
(scrollY: number) => {
setWillChange(scrollY < scrollThreshold + 100);
setWillChange(scrollY < scrollThreshold + HEADER_HEIGHT);
if (scrollY > scrollThreshold) {
setAvatarScale(1);
} else {
Expand Down
3 changes: 1 addition & 2 deletions src/app/css/globals.css

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 2 additions & 2 deletions src/components/Comment.tsx
Original file line number Diff line number Diff line change
@@ -1,15 +1,15 @@
'use client';

import { useTheme } from 'next-themes';
import { GISCUS_CONFIGS } from '~/constants';
import Giscus from '@giscus/react';
import giscusConfigs from '~/data/giscus';

function Comment() {
const { resolvedTheme } = useTheme();
const isDarkTheme = resolvedTheme === 'dark';
const giscusTheme = isDarkTheme ? 'noborder_dark' : 'noborder_light';

return <Giscus {...giscusConfigs} theme={giscusTheme} />;
return <Giscus {...GISCUS_CONFIGS} theme={giscusTheme} />;
}

export default Comment;
87 changes: 57 additions & 30 deletions src/components/TableOfContents.tsx
Original file line number Diff line number Diff line change
@@ -1,37 +1,74 @@
'use client';

import { useEffect, useLayoutEffect, useState } from 'react';
import { useCallback, useEffect, useMemo, useState } from 'react';

import useIntersectionObserver from '@/hooks/useIntersectionObserver';
import { HEADER_HEIGHT } from '~/constants';
import cn from '@/utils/cn';
import useScroll, { ScrollHandler } from '@/hooks/useScroll';
import Collapse from './Collapse';
import Link from './Link';

type TableOfContentsProps = {
targetId: `#${string}`;
className?: string;
type HeadingType = {
id: string;
offsetTop: number;
text: string | undefined;
children?: HeadingType[];
};

type Heading = {
type HeadingOffsetType = {
id: string;
text: string | undefined;
children?: Heading[];
offsetTop: number;
};

function TableOfContents({ className, targetId }: TableOfContentsProps) {
type TableOfContentsProps = {
targetId: `#${string}`;
className?: string;
scrollThreshold?: number;
};

function TableOfContents({
className,
targetId,
scrollThreshold = HEADER_HEIGHT,
}: TableOfContentsProps) {
const [activeId, setActiveId] = useState('');
const [headings, setHeadings] = useState<Heading[]>([]);
const [entry, setElementRef] = useIntersectionObserver();
const [headings, setHeadings] = useState<HeadingType[]>([]);
const headingOffsets = useMemo<HeadingOffsetType[]>(
() =>
headings
.flatMap<HeadingOffsetType>(({ id, offsetTop, children }) => [
{ id, offsetTop },
...(children || []).map<HeadingOffsetType>((child) => ({
id: child.id,
offsetTop: child.offsetTop,
})),
])
.sort((a, b) => b.offsetTop - a.offsetTop),
[headings]
);

const handleScroll = useCallback<ScrollHandler>(
({ y }) => {
const visibleHeading = headingOffsets.find(
({ offsetTop }) => Math.ceil(y + scrollThreshold) >= offsetTop
);
setActiveId(visibleHeading?.id || '');
},
[headingOffsets, scrollThreshold]
);

useScroll({ handler: handleScroll, initial: true });

useEffect(() => {
const headingElements = Array.from(
document.querySelectorAll(`${targetId} h2, ${targetId} h3`)
document.querySelectorAll<HTMLHeadingElement>(
`${targetId} h2, ${targetId} h3`
)
);
setElementRef(headingElements);
setHeadings(
headingElements.reduce<Heading[]>(
(result, { id, tagName, textContent }) => {
const heading = { id, text: textContent?.slice(1) };
headingElements.reduce<HeadingType[]>(
(result, { id, offsetTop, tagName, textContent }) => {
const heading = { id, offsetTop, text: textContent?.slice(1) };
const lastHeading = result.at(-1);

if (tagName === 'H2') {
Expand All @@ -44,22 +81,12 @@ function TableOfContents({ className, targetId }: TableOfContentsProps) {
[]
)
);
}, [targetId, setElementRef]);

useLayoutEffect(() => {
const visibleHeadings = entry.filter(
({ isIntersecting }) => isIntersecting
);

if (visibleHeadings.length > 0) {
setActiveId(visibleHeadings[0].target.id);
}
}, [entry]);
}, [targetId]);

const isActive = (id: string, children: Heading[]) =>
const isActive = (id: string, children: HeadingType[]) =>
id === activeId || children.some((child) => child.id === activeId);

const getLinkClassName = (id: string, children: Heading[] = []) =>
const getLinkClassName = (id: string, children: HeadingType[] = []) =>
cn(
'transition-colors mb-0.5 block overflow-hidden text-ellipsis whitespace-nowrap hover:underline',
isActive(id, children)
Expand All @@ -69,7 +96,7 @@ function TableOfContents({ className, targetId }: TableOfContentsProps) {

return (
<nav aria-label="Table of contents" className={className}>
<ul className="text-sm">
<ul className="group text-sm">
{headings.map(({ id, text, children }) => (
<li key={id}>
<Link href={`#${id}`} className={getLinkClassName(id, children)}>
Expand Down
21 changes: 9 additions & 12 deletions src/hooks/useScroll.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ export type ScrollHandler = (
element: ScrollElement
) => void;

export type UseScroll = {
export type UseScrollProps = {
ref?: RefObject<ScrollElement>;
initial?: boolean;
handler: ScrollHandler;
Expand All @@ -16,7 +16,7 @@ export type UseScroll = {
/**
* This hook allows tracking the scroll position of a specified DOM element or the window.
*/
function useScroll({ ref, initial, handler }: UseScroll) {
function useScroll({ ref, initial, handler }: UseScrollProps) {
const internalElementRef = useRef<ScrollElement>(null);

const scrollHandler = useCallback(() => {
Expand All @@ -38,23 +38,20 @@ function useScroll({ ref, initial, handler }: UseScroll) {
}, [scrollHandler]);

const register = useCallback(
(element: ScrollElement) => {
internalElementRef.current?.removeEventListener('scroll', scrollHandler);
(element: ScrollElement, initial = false) => {
remove();
internalElementRef.current = element;
internalElementRef.current?.addEventListener('scroll', scrollHandler);
if (initial) scrollHandler();
return remove;
},
[scrollHandler]
[scrollHandler, remove]
);

useEffect(() => {
const element = ref?.current || window;

internalElementRef.current = element;
element.addEventListener('scroll', scrollHandler);
if (initial) scrollHandler();

return () => element.removeEventListener('scroll', scrollHandler);
}, [ref, initial, scrollHandler]);
return register(element, initial);
}, [ref, initial, register]);

return {
remove,
Expand Down
6 changes: 5 additions & 1 deletion tailwind.config.js
Original file line number Diff line number Diff line change
@@ -1,12 +1,16 @@
const colors = require('tailwindcss/colors');
const plugin = require('tailwindcss/plugin');
const { HEADER_HEIGHT } = require('./constants');

/** @type {import('tailwindcss').Config} */
const tailwindcssConfig = {
content: ['./src/**/*.{js,ts,jsx,tsx}'],
darkMode: 'class',
theme: {
extend: {
spacing: {
header: `${HEADER_HEIGHT}px`,
},
colors: {
primary: { ...colors.violet, DEFAULT: colors.violet[500] },
},
Expand Down Expand Up @@ -56,7 +60,7 @@ const tailwindcssConfig = {
cursor: theme('cursor.pointer'),
},
'.top-header-height': {
top: `var(--header-height)`,
top: theme('spacing.header'),
},
});
addComponents({
Expand Down
4 changes: 2 additions & 2 deletions tests/components/comment.test.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { render, screen } from '@testing-library/react';
import { GiscusProps } from '@giscus/react';
import giscusConfigs from '~/data/giscus';
import { GISCUS_CONFIGS } from '~/constants';
import Comment from '@/components/Comment';

const getGiscusProps = jest.fn();
Expand All @@ -24,7 +24,7 @@ describe('Comment component', () => {
render(<Comment />);
const comment = screen.getByTestId('comment');
const expectedProps: GiscusProps = JSON.parse(
JSON.stringify(giscusConfigs)
JSON.stringify(GISCUS_CONFIGS)
);
expectedProps.theme = `noborder_${theme}`;
expect(comment).toBeInTheDocument();
Expand Down
Loading