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: 2 additions & 0 deletions src/editor/plugins/autocomplete/transformers/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,14 @@ import arrows from "./arrows";
import blockquote from "./blockquote";
import heading from "./heading";
import bullet_list from "./bullet_list";
import link from "./link";

const transformers: { [key: string]: Transformer<any> } = {
arrows,
heading,
blockquote,
bullet_list,
link,
//
};

Expand Down
29 changes: 29 additions & 0 deletions src/editor/plugins/autocomplete/transformers/link.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import { describe, expect, it } from "vitest";
import linkTransformer from "./link";

describe("transformer.link", () => {
describe("activate", () => {
it("activates for valid markdown link", () => {
const text = "[Example](https://example.com)";
const props = linkTransformer.activate(text);
expect(props).toEqual({
title: "Example",
url: "https://example.com",
matchLength: text.length,
});
});

it("returns undefined for non-link text", () => {
const props = linkTransformer.activate("not a link");
expect(props).toBeUndefined();
});

it("only uses first link in string", () => {
const props = linkTransformer.activate(
"foo [One](https://one.com) bar [Two](https://two.com)",
);
expect(props?.title).toBe("One");
expect(props?.url).toBe("https://one.com");
});
});
});
51 changes: 51 additions & 0 deletions src/editor/plugins/autocomplete/transformers/link.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
import { TextSelection } from "prosemirror-state";
import { EditorView } from "prosemirror-view";
import { schema } from "prosemirror-markdown";

import type { activator, transformer, Transformer } from "../types";

const reLink = /\[([^\]]+)\]\(([^)]+)\)/;

interface Props {
title: string;
url: string;
matchLength: number;
}

const activate: activator<Props> = (text: string): undefined | Props => {
const match = reLink.exec(text);
if (match) {
return {
title: match[1],
url: match[2],
matchLength: match[0].length,
};
}
return undefined;
};

const transform: transformer<Props> = (
view: EditorView,
_: string,
{ title, url, matchLength }: Props,
): boolean => {
const node = schema.text(title, [schema.marks.link.create({ href: url })]);

const { $cursor } = view.state.selection as TextSelection;
if (!$cursor) return false;
view.dispatch(
view.state.tr
.replaceRangeWith($cursor.pos - matchLength, $cursor.pos, node)
.insertText(" ")
.scrollIntoView(),
);

return true;
};

const _transformer: Transformer<Props> = {
activate,
transform,
};

export default _transformer;