Skip to content
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
2 changes: 1 addition & 1 deletion .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -18,4 +18,4 @@ R2_SECRET_ACCESS_KEY = "your_secret_key"

NPM_REGISTRY = "https://registry.npmmirror.com"

DATABASE_URL = "your neon database url"
DATABASE_URL = "your neon database url"
4 changes: 4 additions & 0 deletions __mocks__/markdown-plugin-mock.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
const markdownPluginMock = () => {};

module.exports = markdownPluginMock;
module.exports.default = markdownPluginMock;
File renamed without changes.
75 changes: 75 additions & 0 deletions app/chat/components/markdown-preview-panel.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
import jotaiStore, { workspaceMarkdownContentAtom } from "@/atoms";
import { exportMarkdownFile, exportMarkdownPdf } from "@/lib/markdown-export";
import {
act,
fireEvent,
render,
screen,
waitFor,
} from "@testing-library/react";
import MarkdownPreview from "./markdown-preview-panel";

jest.mock("@/lib/markdown-export", () => ({
exportMarkdownFile: jest.fn(),
exportMarkdownPdf: jest.fn(async () => "refract-markdown.pdf"),
}));

jest.mock("react-markdown", () => ({
__esModule: true,
default: ({ children }: { children: string }) => <div>{children}</div>,
}));

jest.mock("./mermaid-chart", () => ({
__esModule: true,
default: ({ chart }: { chart: string }) => <div>{chart}</div>,
}));

const exportMarkdownFileMock = exportMarkdownFile as jest.MockedFunction<
typeof exportMarkdownFile
>;
const exportMarkdownPdfMock = exportMarkdownPdf as jest.MockedFunction<
typeof exportMarkdownPdf
>;

describe("MarkdownPreview", () => {
beforeEach(() => {
act(() => {
jotaiStore.set(workspaceMarkdownContentAtom, "# Report\n\nHello export");
});
});

afterEach(() => {
act(() => {
jotaiStore.set(workspaceMarkdownContentAtom, "");
});
jest.clearAllMocks();
});

it("exports the raw markdown content from the export menu", async () => {
render(<MarkdownPreview />);

fireEvent.keyDown(screen.getByRole("button", { name: /export/i }), {
key: "ArrowDown",
});
fireEvent.click(await screen.findByRole("menuitem", { name: /markdown/i }));

expect(exportMarkdownFileMock).toHaveBeenCalledWith(
"# Report\n\nHello export",
);
});

it("downloads the rendered markdown preview as a pdf", async () => {
render(<MarkdownPreview />);

fireEvent.keyDown(screen.getByRole("button", { name: /export/i }), {
key: "ArrowDown",
});
fireEvent.click(await screen.findByRole("menuitem", { name: /pdf/i }));

await waitFor(() =>
expect(exportMarkdownPdfMock).toHaveBeenCalledWith({
sourceElement: expect.any(HTMLElement),
}),
);
});
});
95 changes: 81 additions & 14 deletions app/chat/components/markdown-preview-panel.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,19 @@
import "@/styles/markdown-preview.css";
import "katex/dist/katex.min.css";
import { workspaceMarkdownContentAtom } from "@/atoms";
import { Button } from "@/components/ui/button";
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { ScrollArea } from "@/components/ui/scroll-area";
import { exportMarkdownFile, exportMarkdownPdf } from "@/lib/markdown-export";
import { useAtomValue } from "jotai";
import { ChevronDown, Download, FileText } from "lucide-react";
import type { ComponentPropsWithoutRef, ReactNode } from "react";
import { memo } from "react";
import { memo, useCallback, useRef, useState } from "react";
import Markdown from "react-markdown";
import rehypeKatex from "rehype-katex";
import rehypeRaw from "rehype-raw";
Expand Down Expand Up @@ -50,22 +59,80 @@ const MarkdownPreBlock = ({

const MarkdownPreview = () => {
const markdownContent = useAtomValue(workspaceMarkdownContentAtom);
const previewRef = useRef<HTMLElement>(null);
const [isExportingPdf, setIsExportingPdf] = useState(false);
const hasMarkdownContent = markdownContent.trim().length > 0;

const handleExportMarkdown = useCallback(() => {
exportMarkdownFile(markdownContent);
}, [markdownContent]);

const handleExportPdf = useCallback(async () => {
if (isExportingPdf || !hasMarkdownContent || !previewRef.current) {
return;
}

setIsExportingPdf(true);

try {
await exportMarkdownPdf({
sourceElement: previewRef.current,
});
} finally {
setIsExportingPdf(false);
}
}, [hasMarkdownContent, isExportingPdf]);

return (
<ScrollArea className="h-full w-full p-6">
<article className="prose prose-sm dark:prose-invert markdown-body max-w-none">
<Markdown
remarkPlugins={[remarkGfm, remarkMath]}
rehypePlugins={[rehypeRaw, rehypeKatex]}
components={{
code: MarkdownCodeBlock,
pre: MarkdownPreBlock,
}}
<div className="flex h-full min-h-0 flex-col">
<div className="flex items-center justify-end border-b px-4 py-3">
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button
type="button"
size="sm"
variant="outline"
disabled={!hasMarkdownContent}
className="transition-colors duration-200"
>
<Download className="size-3.5" />
Export
<ChevronDown className="size-3.5" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="min-w-40">
<DropdownMenuItem
onClick={handleExportPdf}
disabled={isExportingPdf}
>
<FileText className="size-4" />
{isExportingPdf ? "PDF..." : "PDF"}
</DropdownMenuItem>
<DropdownMenuItem onClick={handleExportMarkdown}>
<FileText className="size-4" />
Markdown
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</div>
<ScrollArea className="min-h-0 flex-1 p-6">
<article
ref={previewRef}
className="prose prose-sm dark:prose-invert markdown-body max-w-none"
>
{markdownContent}
</Markdown>
</article>
</ScrollArea>
<Markdown
remarkPlugins={[remarkGfm, remarkMath]}
rehypePlugins={[rehypeRaw, rehypeKatex]}
components={{
code: MarkdownCodeBlock,
pre: MarkdownPreBlock,
}}
>
{markdownContent}
</Markdown>
</article>
</ScrollArea>
</div>
);
};

Expand Down
6 changes: 5 additions & 1 deletion jest.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,12 @@ const customJestConfig: Config = {
setupFilesAfterEnv: ["<rootDir>/jest.setup.ts"],
moduleNameMapper: {
"^.+\\.module\\.(css|sass|scss)$": "identity-obj-proxy",
"^.+\\.(css|sass|scss)$": "<rootDir>/__mocks__/styleMock.js",
"^.+\\.(css|sass|scss)$": "<rootDir>/__mocks__/style-mock.js",
"^@/(.*)$": "<rootDir>/$1",
"^rehype-katex$": "<rootDir>/__mocks__/markdown-plugin-mock.js",
"^rehype-raw$": "<rootDir>/__mocks__/markdown-plugin-mock.js",
"^remark-gfm$": "<rootDir>/__mocks__/markdown-plugin-mock.js",
"^remark-math$": "<rootDir>/__mocks__/markdown-plugin-mock.js",
},
testEnvironment: "jest-environment-jsdom",
testPathIgnorePatterns: ["<rootDir>/tests/e2e/"],
Expand Down
60 changes: 41 additions & 19 deletions jest.setup.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,11 @@
import "@testing-library/jest-dom";
import {
ReadableStream,
TransformStream,
WritableStream,
} from "node:stream/web";
import { TextDecoder, TextEncoder } from "node:util";
import { MessageChannel, MessagePort } from "node:worker_threads";
import type { ReactNode } from "react";
import enMessages from "./messages/en.json";

Expand Down Expand Up @@ -43,36 +50,21 @@ jest.mock("next-intl", () => ({

if (typeof globalThis.TransformStream === "undefined") {
Object.defineProperty(globalThis, "TransformStream", {
value: class TransformStream {
readable: unknown;
writable: unknown;
constructor() {
this.readable = {};
this.writable = {};
}
},
value: TransformStream,
writable: true,
});
}

if (typeof globalThis.ReadableStream === "undefined") {
Object.defineProperty(globalThis, "ReadableStream", {
value: class ReadableStream {
getReader() {
return this;
}
},
value: ReadableStream,
writable: true,
});
}

if (typeof globalThis.WritableStream === "undefined") {
Object.defineProperty(globalThis, "WritableStream", {
value: class WritableStream {
getWriter() {
return this;
}
},
value: WritableStream,
writable: true,
});
}
Expand All @@ -82,10 +74,40 @@ if (typeof globalThis.fetch === "undefined") {
value: jest.fn(async () => ({
ok: true,
status: 200,
headers: new Headers(),
headers: {
get: () => null,
},
json: async () => ({}),
text: async () => "",
})),
writable: true,
});
}

if (typeof globalThis.TextDecoder === "undefined") {
Object.defineProperty(globalThis, "TextDecoder", {
value: TextDecoder,
writable: true,
});
}

if (typeof globalThis.TextEncoder === "undefined") {
Object.defineProperty(globalThis, "TextEncoder", {
value: TextEncoder,
writable: true,
});
}

if (typeof globalThis.MessageChannel === "undefined") {
Object.defineProperty(globalThis, "MessageChannel", {
value: MessageChannel,
writable: true,
});
}

if (typeof globalThis.MessagePort === "undefined") {
Object.defineProperty(globalThis, "MessagePort", {
value: MessagePort,
writable: true,
});
}
Loading
Loading