-
-
Notifications
You must be signed in to change notification settings - Fork 213
Expand file tree
/
Copy pathuseCodeSelection.tsx
More file actions
69 lines (59 loc) · 2.32 KB
/
useCodeSelection.tsx
File metadata and controls
69 lines (59 loc) · 2.32 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
import { useState } from 'react';
import * as monaco from 'monaco-editor';
import useAppStore from '../store/store';
import CodeSelectionMenu from '../components/CodeSelectionMenu';
export const useCodeSelection = (editorType: 'markdown' | 'concerto' | 'json') => {
const [selectedText, setSelectedText] = useState('');
const [menuPosition, setMenuPosition] = useState<{ x: number; y: number } | null>(null);
const [showMenu, setShowMenu] = useState(false);
const enableCodeSelectionMenu = useAppStore((state) => state.aiConfig?.enableCodeSelectionMenu ?? true);
const handleSelection = (editor: monaco.editor.IStandaloneCodeEditor) => {
const selection = editor.getSelection();
if (selection && !selection.isEmpty()) {
const selectedText = editor.getModel()?.getValueInRange(selection).trim();
if (selectedText && selectedText.length > 0) {
const position = editor.getScrolledVisiblePosition(selection.getStartPosition());
const editorContainer = editor.getDomNode()?.closest('.editorwrapper');
const editorRect = editorContainer?.getBoundingClientRect();
let x: number, y: number;
if (editorRect && position) {
x = Math.max(editorRect.left + 20, Math.min(position.left, editorRect.right - 150));
y = Math.max(editorRect.top + 20, Math.min(position.top, editorRect.bottom - 50));
x = Math.max(10, Math.min(x, window.innerWidth - 150));
y = Math.max(10, Math.min(y, window.innerHeight - 50));
} else if (position) {
x = Math.max(10, Math.min(position.left, window.innerWidth - 150));
y = Math.max(10, Math.min(position.top, window.innerHeight - 50));
} else {
return;
}
setSelectedText(selectedText);
setMenuPosition({
x: x,
y: y
});
setShowMenu(true);
}
} else {
setShowMenu(false);
}
}
const closeMenu = () => {
setShowMenu(false);
setSelectedText('');
setMenuPosition(null);
};
const MenuComponent = (enableCodeSelectionMenu && showMenu && selectedText && menuPosition) ? (
<CodeSelectionMenu
selectedText={selectedText}
position={menuPosition}
onClose={closeMenu}
editorType={editorType}
/>
) : null;
return {
handleSelection,
closeMenu,
MenuComponent
};
};