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

fix: invalid markdown link preview #1805

Merged
merged 2 commits into from
Jan 12, 2025
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
39 changes: 25 additions & 14 deletions src/features/comment/CommentLinks.tsx
Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
import spoiler from "@aeharding/remark-lemmy-spoiler";
import { uniqBy } from "es-toolkit";
import { Text } from "mdast";
import { defaultUrlTransform } from "react-markdown";
import remarkParse from "remark-parse";
import { unified } from "unified";
import { SKIP, visit } from "unist-util-visit";
import { CONTINUE, EXIT, SKIP, visit } from "unist-util-visit";

import CommentLink from "#/features/post/link/CommentLink";
import customRemarkGfm from "#/features/shared/markdown/customRemarkGfm";
Expand Down Expand Up @@ -45,30 +44,42 @@ export default function CommentLinks({ markdown }: CommentLinksProps) {
const mdastTree = processor.parse(markdown);
processor.runSync(mdastTree, markdown);

let links: LinkData[] = [];
const links: LinkData[] = [];
const urlMap = new Map<string, true>();

visit(mdastTree, ["details", "link", "image"], (node) => {
// don't show links within spoilers
if (node.type === "details") return SKIP;

if (node.type === "link" || (!showCommentImages && node.type === "image"))
if (
node.type === "link" ||
(!showCommentImages && node.type === "image")
) {
const url = parseUrl(node.url, connectedInstanceUrl)?.href;

// Skip if not a valid URL
if (!url) return CONTINUE;

// Skip if the URL is not a valid URL,
// according to default markdown link parser logic
if (!defaultUrlTransform(url)) return CONTINUE;

// Skip if the URL has already been added
if (urlMap.has(url)) return CONTINUE;

urlMap.set(url, true);

links.push({
type: node.type,
// normalize relative links
url: parseUrl(node.url, connectedInstanceUrl)?.href ?? node.url,
url,
text:
"children" in node ? (node.children[0] as Text)?.value : undefined,
});
});

// Dedupe by url
links = uniqBy(links, ({ url }) => url);

// e.g. `http://127.0.0.1:8080”`
links = links.filter(({ url }) => defaultUrlTransform(url));

// Max 4 links
links = links.slice(0, 4);
if (links.length === 4) return EXIT;
}
});

return links.map((link, index) => <CommentLink link={link} key={index} />);
})();
Expand Down
Loading