Skip to content

Commit

Permalink
Add hyperlink creation feature
Browse files Browse the repository at this point in the history
  • Loading branch information
choidabom committed Sep 3, 2024
1 parent 528d808 commit a3e2f94
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 0 deletions.
2 changes: 2 additions & 0 deletions frontend/src/components/editor/Editor.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import { selectSetting } from "../../store/settingSlice";
import { selectWorkspace } from "../../store/workspaceSlice";
import { imageUploader } from "../../utils/imageUploader";
import { intelligencePivot } from "../../utils/intelligence/intelligencePivot";
import { urlHyperlinkInserter } from "../../utils/urlHyperlinkInserter";
import { yorkieCodeMirror } from "../../utils/yorkie";
import ToolBar from "./ToolBar";

Expand Down Expand Up @@ -78,6 +79,7 @@ function Editor() {
...(settingStore.fileUpload.enable
? [imageUploader(handleUploadImage, editorStore.doc)]
: []),
urlHyperlinkInserter(editorStore.doc),
],
});

Expand Down
43 changes: 43 additions & 0 deletions frontend/src/utils/urlHyperlinkInserter.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import { EditorView } from "codemirror";
import { CodePairDocType } from "../store/editorSlice";

const isValidUrl = (url: string) => {
// eslint-disable-next-line no-useless-escape
const urlRegex = /^(https?|ftp):\/\/(-\.)?([^\s\/?\.#-]+\.?)+(\/[^\s]*)?$/i;
return urlRegex.test(url);
};

const insertLinkToEditor = (url: string, view: EditorView, doc: CodePairDocType) => {
const { from, to } = view.state.selection.main;
const selectedText = view.state.sliceDoc(from, to);
const insert = `[${selectedText}](${url})`;

doc.update((root, presence) => {
root.content.edit(from, to, insert);
presence.set({
selection: root.content.indexRangeToPosRange([
from + insert.length,
from + insert.length,
]),
});
});

view.dispatch({
changes: { from, to, insert },
selection: {
anchor: from + insert.length,
},
});
};

export const urlHyperlinkInserter = (doc: CodePairDocType) => {
return EditorView.domEventHandlers({
paste(event, view) {
const url = event.clipboardData?.getData("text/plain");
if (!url || !isValidUrl(url)) return;

insertLinkToEditor(url, view, doc);
event.preventDefault();
},
});
};

0 comments on commit a3e2f94

Please sign in to comment.