Skip to content

Commit

Permalink
fix: open link on Mod-Click
Browse files Browse the repository at this point in the history
fixes #62
  • Loading branch information
dancormier committed May 19, 2022
1 parent 4c98748 commit 85c5392
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 0 deletions.
2 changes: 2 additions & 0 deletions src/rich-text/editor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ import { codePasteHandler } from "./plugins/code-paste-handler";
import { linkPasteHandler } from "./plugins/link-paste-handler";
import { linkPreviewPlugin, LinkPreviewProvider } from "./plugins/link-preview";
import { linkTooltipPlugin } from "./plugins/link-editor";
import { linkModClickHandler } from "./plugins/link-mod-click-handler";
import { plainTextPasteHandler } from "./plugins/plain-text-paste-handler";
import { spoilerToggle } from "./plugins/spoiler-toggle";
import { tables } from "./plugins/tables";
Expand Down Expand Up @@ -92,6 +93,7 @@ export class RichTextEditor extends BaseView {
this.options.codeblockOverrideLanguage
),
linkTooltipPlugin(this.options.parserFeatures),
linkModClickHandler(),
richTextImageUpload(
this.options.imageUpload,
this.options.parserFeatures.validateLink,
Expand Down
39 changes: 39 additions & 0 deletions src/rich-text/plugins/link-mod-click-handler.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import { Plugin, EditorState } from "prosemirror-state";
import { EditorView } from "prosemirror-view";
import { Mark } from "prosemirror-model";
import { richTextSchema as schema } from "../schema";

/**
* Returns the mark at cursor if it is of type `link`
* @param state The current editor state
*/
function findLinkAtCursor(state: EditorState): Mark {
const { $from, empty } = state.selection;
return (
empty && $from.marks().find((mark) => mark.type === schema.marks.link)
);
}

/** Plugin that opens link in new window/tab on Mod-click */
export const linkModClickHandler = () =>
new Plugin({
props: {
handleClick(
this,
view: EditorView,
pos: number,
event: MouseEvent
) {
const selectedLink = findLinkAtCursor(view.state);
const modPressed = event.getModifierState(
/Mac/.test(navigator.userAgent) ? "Meta" : "Control"
);

if (selectedLink && modPressed) {
window.open(selectedLink.attrs.href, "_blank");
}

return true;
},
},
});

0 comments on commit 85c5392

Please sign in to comment.