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

Handle custom admonition syntax #95

Merged
merged 5 commits into from
Sep 3, 2024
Merged
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
65 changes: 64 additions & 1 deletion frontend/src/components/Markdown/P.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,70 @@
import { HTMLAttributes } from "react";
import { HTMLAttributes, ReactNode } from "react";
import { Paragraph } from "../Paragraph";
import clsx from "clsx";

const WARNING_MARK = "~>";
const DANGER_MARK = "!>";
const NOTE_MARK = "->";

function getAdmonitionClassName(prefix: string) {
switch (prefix) {
case NOTE_MARK:
return "bg-sky-100 text-sky-800 dark:bg-sky-950 dark:text-sky-100";
case DANGER_MARK:
return "bg-red-100 text-red-800 dark:bg-red-950 dark:text-red-100";
case WARNING_MARK:
return "bg-yellow-100 text-yellow-800 dark:bg-yellow-950 dark:text-yellow-100";
default:
return "";
}
}

function getAdmonitionMatch(children: ReactNode) {
let content = "";

if (typeof children === "string") {
content = children;
} else if (Array.isArray(children) && typeof children[0] === "string") {
content = children[0];
}

if (!content) {
return null;
}

if (
content.startsWith(WARNING_MARK) ||
content.startsWith(DANGER_MARK) ||
content.startsWith(NOTE_MARK)
) {
return {
prefix: content.slice(0, 2),
content: content.slice(2).trim(),
};
}

return null;
}

export function MarkdownP({ children }: HTMLAttributes<HTMLParagraphElement>) {
const admonitionMatch = getAdmonitionMatch(children);

if (admonitionMatch) {
const { prefix, content } = admonitionMatch;
const className = getAdmonitionClassName(prefix);
const remainingContent = Array.isArray(children) ? children.slice(1) : null;

return (
<div
role="alert"
className={clsx("mt-5 px-3 py-2 [li>&:first-child]:mt-0", className)}
>
{content}
{remainingContent}
</div>
);
}

return (
<Paragraph className="mt-5 leading-7 [li>&:first-child]:mt-0">
{children}
Expand Down
Loading