Skip to content

Commit f16e6b3

Browse files
authored
Ensure caret visibility for showContextMenu (#701)
1 parent 3ce9032 commit f16e6b3

File tree

1 file changed

+24
-13
lines changed

1 file changed

+24
-13
lines changed

CoreEditor/src/api/ui.ts

Lines changed: 24 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,8 @@ import { MenuItem, Alert, TextBox } from 'markedit-api';
33

44
import { WebMenuItem } from '../@types/WebMenuItem';
55
import { WebPoint } from '../@types/WebPoint';
6-
import { getRect } from '../modules/selection';
6+
import { afterDomUpdate } from '../common/utils';
7+
import { getRect, scrollToSelection, isPositionVisible } from '../modules/selection';
78

89
export function addMainMenuItem(spec: MenuItem | MenuItem[]): void {
910
const items = Array.isArray(spec) ? spec : [spec];
@@ -13,19 +14,29 @@ export function addMainMenuItem(spec: MenuItem | MenuItem[]): void {
1314
}
1415

1516
export function showContextMenu(items: MenuItem[], location?: WebPoint) {
16-
window.nativeModules.ui.showContextMenu({
17-
items: items.map(item => createMenuItem(item, contextActions)),
18-
location: location ?? (() => {
19-
const rect = getRect(window.editor.state.selection.main.head);
20-
if (rect === undefined) {
21-
// Basically invalid, it should not happen
22-
return { x: 0, y: 0 };
23-
}
17+
const caretPos = window.editor.state.selection.main.head;
18+
const invokeNative = () => {
19+
window.nativeModules.ui.showContextMenu({
20+
items: items.map(item => createMenuItem(item, contextActions)),
21+
location: location ?? (() => {
22+
const rect = getRect(caretPos);
23+
if (rect === undefined) {
24+
// Basically invalid, it should not happen
25+
return { x: 0, y: 0 };
26+
}
2427

25-
// Default value set to the caret position
26-
return { x: rect.x, y: rect.y + rect.height + 10 };
27-
})(),
28-
});
28+
// Default value set to the caret position
29+
return { x: rect.x, y: rect.y + rect.height + 10 };
30+
})(),
31+
});
32+
};
33+
34+
if (location === undefined && !isPositionVisible(caretPos)) {
35+
scrollToSelection('nearest');
36+
afterDomUpdate(invokeNative);
37+
} else {
38+
invokeNative();
39+
}
2940
}
3041

3142
export function showAlert(spec: Alert): Promise<number> {

0 commit comments

Comments
 (0)