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

Add support for community handles (e.g. !memes@lemmy.ml) #28

Merged
merged 2 commits into from
Jun 27, 2023
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
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@
"jsdom": "^22.1.0",
"lemmy-js-client": "0.18.0",
"lodash": "^4.17.21",
"mdast-util-gfm-autolink-literal-lemmy": "^1.0.3",
"photoswipe": "^5.3.7",
"prettier": "^2.8.8",
"react": "^18.2.0",
Expand Down
18 changes: 16 additions & 2 deletions src/features/shared/Markdown.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,11 @@ import {
} from "react-markdown/lib/react-markdown";
import Img from "../post/detail/Img";
import styled from "@emotion/styled";
import remarkGfm from "remark-gfm";
import { useAppSelector } from "../../store";
import LinkInterceptor from "./markdown/LinkInterceptor";
import buildCommunityPlugin from "./markdown/buildCommunityPlugin";
import customRemarkGfm from "./markdown/customRemarkGfm";
import { useMemo } from "react";

const Blockquote = styled.blockquote`
padding-left: 0.5rem;
Expand Down Expand Up @@ -46,6 +50,15 @@ const TableContainer = styled.div`
`;

export default function Markdown(props: ReactMarkdownOptions) {
const connectedInstance = useAppSelector(
(state) => state.auth.connectedInstance
);

const communityPlugin = useMemo(
() => buildCommunityPlugin(connectedInstance),
[connectedInstance]
);

return (
<ReactMarkdown
linkTarget="_blank"
Expand All @@ -59,9 +72,10 @@ export default function Markdown(props: ReactMarkdownOptions) {
<table {...props} />
</TableContainer>
),
a: (props) => <LinkInterceptor {...props} />,
...props.components,
}}
remarkPlugins={[remarkGfm]}
remarkPlugins={[communityPlugin, customRemarkGfm]}
/>
);
}
64 changes: 64 additions & 0 deletions src/features/shared/markdown/LinkInterceptor.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
import { LinkHTMLAttributes, MouseEvent, useCallback } from "react";
import { useAppSelector } from "../../../store";
import { useIonRouter } from "@ionic/react";
import { useBuildGeneralBrowseLink } from "../../../helpers/routes";

const COMMUNITY_RELATIVE_URL =
/^\/c\/([a-zA-Z0-9._%+-]+(@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,})?)\/?$/;

export default function LinkInterceptor(
props: LinkHTMLAttributes<HTMLAnchorElement>
) {
const connectedInstance = useAppSelector(
(state) => state.auth.connectedInstance
);
const router = useIonRouter();
const buildGeneralBrowseLink = useBuildGeneralBrowseLink();

const onClick = useCallback(
(e: MouseEvent) => {
if (!props.href) return;
if (e.metaKey || e.ctrlKey) return;

const url = new URL(props.href, `https://${connectedInstance}`);

const matchedCommunityHandle = matchLemmyCommunity(url.pathname);
if (url.hostname === connectedInstance && matchedCommunityHandle) {
e.preventDefault();

const [communityName, domain] = matchedCommunityHandle;

if (
!domain ||
(domain === url.hostname && domain === connectedInstance)
) {
router.push(buildGeneralBrowseLink(`/c/${communityName}`));
return;
}

router.push(
buildGeneralBrowseLink(
`/c/${communityName}@${domain ?? url.hostname}`
)
);
}
},
[buildGeneralBrowseLink, connectedInstance, props.href, router]
);

return (
<a {...props} target="_blank" rel="noopener noreferrer" onClick={onClick} />
);
}

function matchLemmyCommunity(
urlPathname: string
): [string, string] | [string] | null {
const matches = urlPathname.match(COMMUNITY_RELATIVE_URL);
if (matches && matches[1]) {
const [communityName, domain] = matches[1].split("@");
if (!domain) return [communityName];
return [communityName, domain];
}
return null;
}
87 changes: 87 additions & 0 deletions src/features/shared/markdown/buildCommunityPlugin.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
import { Plugin, Transformer } from "unified";
import { visit } from "unist-util-visit";
import { Parent, Text, Link } from "mdast";

interface CustomNode extends Text {}

interface CustomLink extends Link {
url: string;
}

// eslint-disable-next-line @typescript-eslint/no-explicit-any
type CustomTransformer = Transformer<any, any>;

export default function buildCommunityPlugin(connectedInstance: string) {
const communityPlugin: Plugin<[]> = (): CustomTransformer => {
const transformer: CustomTransformer = (tree) => {
const visitor = (
node: CustomNode | Parent,
index: number | null,
parent: Parent | undefined
) => {
if (node?.type === "text" && parent) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const { value } = node as any;

const regex = /!([\w-]+)@([^\s.,!?;)]+(?:\.[^\s.,!?;=)]+)+)/g;
let match;
let lastIndex = 0;
const newTextNodes: (Text | CustomLink)[] = [];

while ((match = regex.exec(value))) {
const [fullMatch, communityHandle, handleDomain] = match;
const start = match.index;
const end = start + fullMatch.length;

const before = value.slice(lastIndex, start);

if (before) {
newTextNodes.push({ type: "text", value: before });
}

const atDomain =
connectedInstance === handleDomain ? "" : `@${handleDomain}`;

const linkNode: CustomLink = {
type: "link",
url: `https://${connectedInstance}/c/${communityHandle}${atDomain}`,
children: [
{
type: "text",
value: fullMatch,
},
],
};

newTextNodes.push(linkNode);

lastIndex = end;
}

if (newTextNodes.length > 0) {
if (lastIndex < value.length) {
newTextNodes.push({
type: "text",
value: value.slice(lastIndex),
});
}

if (index !== null) {
parent.children.splice(index, 1, ...newTextNodes);
} else {
parent.children.push(...newTextNodes);
}
}
}
};

visit(tree, "text", (node, index, parent) =>
visitor(node as CustomNode, index, parent as Parent)
);
};

return transformer;
};

return communityPlugin;
}
53 changes: 53 additions & 0 deletions src/features/shared/markdown/customRemarkGfm.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
import { combineExtensions } from "micromark-util-combine-extensions";
import { gfmStrikethrough } from "micromark-extension-gfm-strikethrough";
import { gfmTable } from "micromark-extension-gfm-table";
import {
gfmAutolinkLiteralFromMarkdown,
gfmAutolinkLiteralToMarkdown,
} from "mdast-util-gfm-autolink-literal-lemmy";
import {
gfmStrikethroughFromMarkdown,
gfmStrikethroughToMarkdown,
} from "mdast-util-gfm-strikethrough";
import { gfmTableFromMarkdown, gfmTableToMarkdown } from "mdast-util-gfm-table";
import { Options } from "remark-gfm";

export default function customRemarkGfm(
this: import("unified").Processor,
options = {}
) {
const data = this.data();

add("micromarkExtensions", gfm());
add("fromMarkdownExtensions", gfmFromMarkdown());
add("toMarkdownExtensions", gfmToMarkdown(options));

function add(field: string, value: unknown) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const list: any = data[field] ? data[field] : (data[field] = []);

list.push(value);
}
}

function gfm(options?: Options) {
return combineExtensions([gfmStrikethrough(options), gfmTable]);
}

function gfmFromMarkdown() {
return [
gfmAutolinkLiteralFromMarkdown,
gfmStrikethroughFromMarkdown,
gfmTableFromMarkdown,
];
}

function gfmToMarkdown(options?: Options) {
return {
extensions: [
gfmAutolinkLiteralToMarkdown,
gfmStrikethroughToMarkdown,
gfmTableToMarkdown(options),
],
};
}
3 changes: 3 additions & 0 deletions vite.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,4 +24,7 @@ export default defineConfig({
environment: "jsdom",
setupFiles: "./src/setupTests.ts",
},
optimizeDeps: {
exclude: ["mdast-util-gfm-autolink-literal-lemmy"],
},
});
10 changes: 10 additions & 0 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -4120,6 +4120,16 @@ mdast-util-from-markdown@^1.0.0:
unist-util-stringify-position "^3.0.0"
uvu "^0.5.0"

mdast-util-gfm-autolink-literal-lemmy@^1.0.3:
version "1.0.3"
resolved "https://registry.yarnpkg.com/mdast-util-gfm-autolink-literal-lemmy/-/mdast-util-gfm-autolink-literal-lemmy-1.0.3.tgz#c0b5bbf5718546ac9b38817cf64d9518eeca35f8"
integrity sha512-++DZgjmTxa0WVAOZM5Crq9M+H0f8CKE82vR33bUYxeiXhVhLAjhRSbAUNzOpSC+d9KxKgxV+ptdhVrh7aRyxnQ==
dependencies:
"@types/mdast" "^3.0.0"
ccount "^2.0.0"
mdast-util-find-and-replace "^2.0.0"
micromark-util-character "^1.0.0"

mdast-util-gfm-autolink-literal@^1.0.0:
version "1.0.3"
resolved "https://registry.yarnpkg.com/mdast-util-gfm-autolink-literal/-/mdast-util-gfm-autolink-literal-1.0.3.tgz#67a13abe813d7eba350453a5333ae1bc0ec05c06"
Expand Down