Skip to content

Commit

Permalink
feat: paste as link
Browse files Browse the repository at this point in the history
  • Loading branch information
sibiraj-s committed Feb 9, 2021
1 parent 2bf3796 commit 83420ad
Show file tree
Hide file tree
Showing 3 changed files with 56 additions and 0 deletions.
1 change: 1 addition & 0 deletions src/lib/editor.component.ts
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,7 @@ export class NgxEditorComponent implements ControlValueAccessor, OnInit, OnChang
}));

this.editor.registerPlugin(plugins.image(this.injector));
this.editor.registerPlugin(plugins.link());
}

ngOnInit(): void {
Expand Down
1 change: 1 addition & 0 deletions src/lib/plugins/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,3 +4,4 @@ export { default as attributes } from './attributes';
export { default as focus } from './focus';
export { default as blur } from './blur';
export { default as image } from './image';
export { default as link } from './link';
54 changes: 54 additions & 0 deletions src/lib/plugins/link.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
import { Fragment, Slice, Node as ProseMirrorNode } from 'prosemirror-model';
import { Plugin, PluginKey } from 'prosemirror-state';

const HTTP_LINK_REGEX = /((https?:\/\/)?[\w-]+(\.[\w-]+)+\.?(:\d+)?(\/\S*)?)$/;

const linkify = (fragment: Fragment): Fragment => {
const linkified: ProseMirrorNode[] = [];

fragment.forEach((child: ProseMirrorNode) => {
if (child.isText) {
const text = child.text as string;
let pos = 0;

const match: RegExpMatchArray | null = HTTP_LINK_REGEX.exec(text);

if (match) {
const start = match.index;
const end = start + match[0].length;
const link = child.type.schema.marks.link;

if (start > 0) {
linkified.push(child.cut(pos, start));
}

const urlText = text.slice(start, end);
linkified.push(
child.cut(start, end).mark(link.create({ href: urlText }).addToSet(child.marks))
);
pos = end;
}

if (pos < text.length) {
linkified.push(child.cut(pos));
}
} else {
linkified.push(child.copy(linkify(child.content)));
}
});

return Fragment.fromArray(linkified);
};

const linkPlugin = () => {
return new Plugin({
key: new PluginKey('link'),
props: {
transformPasted: (slice: Slice) => {
return new Slice(linkify(slice.content), slice.openStart, slice.openEnd);
}
}
});
};

export default linkPlugin;

0 comments on commit 83420ad

Please sign in to comment.