-
Notifications
You must be signed in to change notification settings - Fork 67
Expand file tree
/
Copy pathuseOnLinkDetected.ts
More file actions
73 lines (64 loc) · 2.03 KB
/
Copy pathuseOnLinkDetected.ts
File metadata and controls
73 lines (64 loc) · 2.03 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
import { useEffect } from 'react';
import { type Editor } from '@tiptap/react';
import { getMarkRange, getMarksBetween } from '@tiptap/core';
import type { EditorState } from '@tiptap/pm/state';
import type { MarkType } from '@tiptap/pm/model';
import { emitLinkDetected, type LinkEmitterRef } from './emitLinkDetected';
import {
nativeLeafText,
tiptapPosToNativePos,
} from '../nativeMappers/positionMapping';
function findLinkRangeAt(
state: EditorState,
linkType: MarkType
): { from: number; to: number } | null {
const $pos = state.selection.$from;
const direct = getMarkRange($pos, linkType);
if (direct) return direct;
if ($pos.pos > 0) {
const $before = state.doc.resolve($pos.pos - 1);
const before = getMarkRange($before, linkType);
if (before && before.to === $pos.pos) return before;
}
return null;
}
export const useOnLinkDetected = (
editor: Editor | null,
ref: LinkEmitterRef
) => {
useEffect(() => {
if (!editor) return;
const handleUpdate = () => {
const { state } = editor;
const linkType = state.schema.marks.link;
if (!linkType) return;
const range = findLinkRangeAt(state, linkType);
if (!range) {
const last = ref.current.lastEmitted;
if (!last || last.url === '') return;
emitLinkDetected(ref.current, {
text: '',
url: '',
start: 0,
end: 0,
});
return;
}
const linkMark = getMarksBetween(range.from, range.to, state.doc).find(
(entry) => entry.mark.type === linkType
)?.mark;
if (!linkMark) return;
emitLinkDetected(ref.current, {
text: nativeLeafText(state.doc, range.from, range.to),
url: (linkMark.attrs.href as string | undefined) ?? '',
start: tiptapPosToNativePos(state.doc, range.from),
end: tiptapPosToNativePos(state.doc, range.to),
});
};
handleUpdate();
editor.on('transaction', handleUpdate);
return () => {
editor.off('transaction', handleUpdate);
};
}, [editor, ref]);
};