Skip to content

Commit

Permalink
pass id prop to headings
Browse files Browse the repository at this point in the history
  • Loading branch information
julianbenegas committed Oct 24, 2023
1 parent d4570bf commit 447be8f
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 7 deletions.
38 changes: 31 additions & 7 deletions packages/basehub/src/react/rich-text/index.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
/* eslint-disable jsx-a11y/alt-text */
/* eslint-disable @next/next/no-img-element */
import * as React from "react";
import { extractTextFromChildren } from "./util/extract-text-from-react-node";

/**
* TODOs
Expand Down Expand Up @@ -118,12 +119,30 @@ type Handlers = {
children?: React.ReactNode;
} & ({ isTaskListItem: false } | { isTaskListItem: true; checked: boolean })
) => React.ReactElement;
h1: (props: { children?: React.ReactNode }) => React.ReactElement;
h2: (props: { children?: React.ReactNode }) => React.ReactElement;
h3: (props: { children?: React.ReactNode }) => React.ReactElement;
h4: (props: { children?: React.ReactNode }) => React.ReactElement;
h5: (props: { children?: React.ReactNode }) => React.ReactElement;
h6: (props: { children?: React.ReactNode }) => React.ReactElement;
h1: (props: {
children?: React.ReactNode;
id: string | null;
}) => React.ReactElement;
h2: (props: {
children?: React.ReactNode;
id: string | null;
}) => React.ReactElement;
h3: (props: {
children?: React.ReactNode;
id: string | null;
}) => React.ReactElement;
h4: (props: {
children?: React.ReactNode;
id: string | null;
}) => React.ReactElement;
h5: (props: {
children?: React.ReactNode;
id: string | null;
}) => React.ReactElement;
h6: (props: {
children?: React.ReactNode;
id: string | null;
}) => React.ReactElement;
hr: () => React.ReactElement;
img: (props: {
children?: React.ReactNode;
Expand Down Expand Up @@ -319,7 +338,12 @@ const Node = ({
case "heading":
const handlerTag = `h${node.attrs.level}` as keyof Handlers;
handler = components?.[handlerTag] ?? defaultHandlers[handlerTag];
props = { children } satisfies ExtractPropsForHandler<Handlers["h1"]>;

const id =
extractTextFromChildren(children).toLowerCase().replace(/\s/g, "-") ||
null;

props = { children, id } satisfies ExtractPropsForHandler<Handlers["h1"]>;
break;
case "horizontalRule":
handler = components?.hr ?? defaultHandlers.hr;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import { Children, isValidElement, ReactNode } from "react";

export function extractTextFromChildren(children?: ReactNode) {
let textContent = "";

Children.forEach(children, (child) => {
if (typeof child === "string" || typeof child === "number") {
textContent += child;
} else if (isValidElement(child) && child.props.children) {
textContent += extractTextFromChildren(child.props.children);
}
});

return textContent;
}

0 comments on commit 447be8f

Please sign in to comment.