Skip to content

Commit

Permalink
Allow the link plugin to optionally specify a custom href for link te…
Browse files Browse the repository at this point in the history
…xt (udecode#1687)

* Allow the link plugin to optionally specify a custom href for link text

* changeset
  • Loading branch information
davisg123 authored Jul 10, 2022
1 parent 7b2ed8c commit 36ad33a
Show file tree
Hide file tree
Showing 3 changed files with 63 additions and 3 deletions.
5 changes: 5 additions & 0 deletions .changeset/friendly-cats-divide.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@udecode/plate-link': patch
---

Allow the link plugin to optionally specify a custom href for link text
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
/** @jsx jsx */

import { createPlateEditor } from '@udecode/plate-core';
import { jsx } from '@udecode/plate-test-utils';
import { createLinkPlugin } from '../../../createLinkPlugin';

jsx;

const input = (
<editor>
<hp>
google.com
<cursor />
</hp>
</editor>
) as any;

const text = ' ';

const output = (
<editor>
<hp>
<htext />
<element type="a" url="http://google.com">
google.com
</element>{' '}
</hp>
</editor>
) as any;

describe('when inserting a space with a link element at the beginning of a block using a custom href', () => {
it('should wrap the url in a link', () => {
const editor = createPlateEditor({
editor: input,
plugins: [
createLinkPlugin({
options: {
isUrl: (url) => url === 'google.com',
getUrlHref: (url) => {
return 'http://google.com';
},
},
}),
],
});

editor.insertText(text);

expect(input.children).toEqual(output.children);
});
});
10 changes: 7 additions & 3 deletions packages/nodes/link/src/withLink.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,13 +47,17 @@ const upsertLink = <V extends Value>(

const upsertLinkIfValid = <V extends Value>(
editor: PlateEditor<V>,
{ isUrl }: { isUrl: any }
{ isUrl, getUrlHref }: { isUrl: any; getUrlHref: any }
) => {
const rangeFromBlockStart = getRangeFromBlockStart(editor);
const textFromBlockStart = getEditorString(editor, rangeFromBlockStart);
const hrefFromBlockStart = getUrlHref?.(textFromBlockStart);

if (rangeFromBlockStart && isUrl(textFromBlockStart)) {
upsertLink(editor, { url: textFromBlockStart, at: rangeFromBlockStart });
upsertLink(editor, {
url: hrefFromBlockStart || textFromBlockStart,
at: rangeFromBlockStart,
});
return true;
}
};
Expand Down Expand Up @@ -83,7 +87,7 @@ export const withLink = <
if (text === ' ' && isCollapsed(editor.selection)) {
const selection = editor.selection as Range;

if (upsertLinkIfValid(editor, { isUrl })) {
if (upsertLinkIfValid(editor, { isUrl, getUrlHref })) {
moveSelection(editor, { unit: 'offset' });
return insertText(text);
}
Expand Down

0 comments on commit 36ad33a

Please sign in to comment.