Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import { moveCursorToMouseEvent } from '../cursor-helpers.js';
import { getEditorSurfaceElement } from '../../core/helpers/editorSurface.js';
import { getItems } from './menuItems.js';
import { getEditorContext } from './utils.js';
import { clampMenuPositionToBounds, resolveMenuBounds } from './menu-position.js';
import { CONTEXT_MENU_HANDLED_FLAG } from './event-flags.js';
import { isMacOS } from '../../core/utilities/isMacOS.js';

Expand Down Expand Up @@ -36,6 +37,24 @@ const sections = ref([]);
const selectedId = ref(null);
const currentContext = ref(null); // Store context for action execution

const repositionMenu = () => {
Comment thread
caio-pizzol marked this conversation as resolved.
const menuRect = menuRef.value?.getBoundingClientRect();
if (!menuRect || menuRect.width <= 0 || menuRect.height <= 0) return;

const bounds = resolveMenuBounds(getEditorSurfaceElement(props.editor), window);
menuPosition.value = clampMenuPositionToBounds(menuPosition.value, menuRect, bounds);
};

let repositionScheduled = false;
const scheduleMenuReposition = () => {
if (repositionScheduled) return;
repositionScheduled = true;
nextTick(() => {
repositionScheduled = false;
repositionMenu();
});
};

const TABLE_SURFACE_SELECTOR = '.superdoc-table-fragment, .superdoc-table-cell';

const hasExpandedSelection = (selection) => {
Expand Down Expand Up @@ -201,6 +220,7 @@ const renderCustomItem = async (itemId) => {
element.innerHTML = '';
element.appendChild(customElement);
element.hasCustomContent = true;
scheduleMenuReposition();
}
} catch (error) {
console.warn(`[ContextMenu] Error rendering custom item ${itemId}:`, error);
Expand All @@ -209,6 +229,7 @@ const renderCustomItem = async (itemId) => {
element.innerHTML = '';
element.appendChild(fallbackElement);
element.hasCustomContent = true;
scheduleMenuReposition();
}
};

Expand Down Expand Up @@ -583,6 +604,9 @@ onMounted(() => {
searchQuery.value = '';
selectedId.value = flattenedItems.value[0]?.id || null;
isOpen.value = true;

await nextTick();
repositionMenu();
};
props.editor.on('contextMenu:open', contextMenuOpenHandler);

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
const CLIPPING_OVERFLOW = new Set(['auto', 'scroll', 'hidden', 'clip']);

/**
* Visible bounds (viewport coordinates) a fixed-position menu should stay within: the viewport
* minus any window scrollbar, intersected with every clipping ancestor's client box.
*
* @param {Element|null} anchorEl - Element inside the scroll area (e.g. the editor surface).
* @param {Window} view - Window used for measurements (injectable for tests).
* @returns {{ left: number, top: number, right: number, bottom: number }}
*/
export const resolveMenuBounds = (anchorEl, view) => {
const docEl = view.document.documentElement;
const bounds = { left: 0, top: 0, right: docEl.clientWidth, bottom: docEl.clientHeight };

let current = anchorEl;
while (current) {
const { overflowX, overflowY } = view.getComputedStyle(current);
const clipsX = CLIPPING_OVERFLOW.has(overflowX);
const clipsY = CLIPPING_OVERFLOW.has(overflowY);

if ((clipsX || clipsY) && current.getBoundingClientRect) {
const rect = current.getBoundingClientRect();
const clientLeft = rect.left + current.clientLeft;
const clientTop = rect.top + current.clientTop;

if (clipsX) {
bounds.left = Math.max(bounds.left, clientLeft);
bounds.right = Math.min(bounds.right, clientLeft + current.clientWidth);
}
if (clipsY) {
bounds.top = Math.max(bounds.top, clientTop);
bounds.bottom = Math.min(bounds.bottom, clientTop + current.clientHeight);
}
}

current = current.parentElement;
}

return bounds;
};

/**
* Clamp a fixed-position menu back inside `bounds` using its rendered rect. Shifts by how far the
* rect overflows each edge, so the result is correct regardless of the menu's containing block.
*
* @param {{ left: string, top: string }} position - Current CSS position (px strings).
* @param {{ left: number, top: number, right: number, bottom: number }} rect - Rendered menu rect.
* @param {{ left: number, top: number, right: number, bottom: number }} bounds - Allowed area.
* @param {number} [gutter=8] - Minimum gap from each edge.
* @returns {{ left: string, top: string }}
*/
export const clampMenuPositionToBounds = (position, rect, bounds, gutter = 8) => {
let left = parseFloat(position.left) || 0;
let top = parseFloat(position.top) || 0;

const menuWidth = rect.right - rect.left;
const menuHeight = rect.bottom - rect.top;
const boundsWidth = bounds.right - bounds.left;
const boundsHeight = bounds.bottom - bounds.top;
const fitsX = menuWidth <= boundsWidth;
const fitsY = menuHeight <= boundsHeight;
const gutterX = Math.min(gutter, Math.max(0, (boundsWidth - menuWidth) / 2));
const gutterY = Math.min(gutter, Math.max(0, (boundsHeight - menuHeight) / 2));

if (fitsX) {
if (rect.right > bounds.right - gutterX) left -= rect.right - (bounds.right - gutterX);
else if (rect.left < bounds.left + gutterX) left += bounds.left + gutterX - rect.left;
}

if (fitsY) {
if (rect.bottom > bounds.bottom - gutterY) top -= rect.bottom - (bounds.bottom - gutterY);
else if (rect.top < bounds.top + gutterY) top += bounds.top + gutterY - rect.top;
}

return { left: `${left}px`, top: `${top}px` };
};
Original file line number Diff line number Diff line change
Expand Up @@ -187,6 +187,148 @@ describe('ContextMenu.vue', () => {
expect(wrapper.find('.context-menu').element.style.top).toBe('200px');
});

it('keeps the rendered menu inside a clipping ancestor', async () => {
const clipper = document.createElement('div');
clipper.style.overflowX = 'hidden';
clipper.style.overflowY = 'hidden';
Object.defineProperties(clipper, {
clientWidth: { configurable: true, value: 600 },
clientHeight: { configurable: true, value: 760 },
});
clipper.append(surfaceElementMock);
document.body.append(clipper);

const viewportWidth = vi.spyOn(document.documentElement, 'clientWidth', 'get').mockReturnValue(1000);
const viewportHeight = vi.spyOn(document.documentElement, 'clientHeight', 'get').mockReturnValue(760);
const rect = vi.spyOn(HTMLElement.prototype, 'getBoundingClientRect').mockImplementation(function () {
if (this.classList.contains('context-menu')) {
const left = Number.parseFloat(this.style.left) || 0;
return { left, top: 200, right: left + 180, bottom: 306, width: 180, height: 106 };
}
if (this === clipper) {
return { left: 0, top: 0, right: 600, bottom: 760, width: 600, height: 760 };
}
return { left: 0, top: 0, right: 0, bottom: 0, width: 0, height: 0 };
});

const wrapper = mount(ContextMenu, { props: mockProps });
try {
const onContextMenuOpen = mockEditor.on.mock.calls.find((call) => call[0] === 'contextMenu:open')[1];
await onContextMenuOpen({ menuPosition: { left: '512px', top: '200px' } });

expect(wrapper.find('.context-menu').element.style.left).toBe('412px');
expect(wrapper.find('.context-menu').element.style.top).toBe('200px');
} finally {
wrapper.unmount();
rect.mockRestore();
viewportWidth.mockRestore();
viewportHeight.mockRestore();
clipper.remove();
}
});

it('uses viewport bounds when the editor surface is unavailable', async () => {
surfaceElementMock = null;
const viewportWidth = vi.spyOn(document.documentElement, 'clientWidth', 'get').mockReturnValue(1000);
const viewportHeight = vi.spyOn(document.documentElement, 'clientHeight', 'get').mockReturnValue(760);
const rect = vi.spyOn(HTMLElement.prototype, 'getBoundingClientRect').mockImplementation(function () {
if (this.classList.contains('context-menu')) {
const left = Number.parseFloat(this.style.left) || 0;
return { left, top: 200, right: left + 180, bottom: 306, width: 180, height: 106 };
}
return { left: 0, top: 0, right: 0, bottom: 0, width: 0, height: 0 };
});

const wrapper = mount(ContextMenu, { props: mockProps });
try {
const onContextMenuOpen = mockEditor.on.mock.calls.find((call) => call[0] === 'contextMenu:open')[1];
await onContextMenuOpen({ menuPosition: { left: '900px', top: '200px' } });

expect(wrapper.find('.context-menu').element.style.left).toBe('812px');
} finally {
wrapper.unmount();
rect.mockRestore();
viewportWidth.mockRestore();
viewportHeight.mockRestore();
}
});

it('repositions after a custom item changes the menu height', async () => {
const customRenderItem = createMockRenderItem('custom-item');
customRenderItem.render = () => {
const element = document.createElement('div');
element.dataset.tallCustomItem = '';
return element;
};
mockGetItems.mockReturnValue([{ id: 'custom-section', items: [customRenderItem] }]);

const viewportWidth = vi.spyOn(document.documentElement, 'clientWidth', 'get').mockReturnValue(1000);
const viewportHeight = vi.spyOn(document.documentElement, 'clientHeight', 'get').mockReturnValue(760);
const rect = vi.spyOn(HTMLElement.prototype, 'getBoundingClientRect').mockImplementation(function () {
if (this.classList.contains('context-menu')) {
const top = Number.parseFloat(this.style.top) || 0;
const height = this.querySelector('[data-tall-custom-item]') ? 200 : 100;
return { left: 100, top, right: 280, bottom: top + height, width: 180, height };
}
return { left: 0, top: 0, right: 0, bottom: 0, width: 0, height: 0 };
});

const wrapper = mount(ContextMenu, { props: mockProps });
try {
const onContextMenuOpen = mockEditor.on.mock.calls.find((call) => call[0] === 'contextMenu:open')[1];
await onContextMenuOpen({ menuPosition: { left: '100px', top: '650px' } });
await nextTick();
await nextTick();

expect(wrapper.find('.context-menu').element.style.top).toBe('552px');
} finally {
wrapper.unmount();
rect.mockRestore();
viewportWidth.mockRestore();
viewportHeight.mockRestore();
}
});

it('repositions when the search header grows a full menu', async () => {
mockGetItems.mockReturnValue(
createMockMenuItems(
1,
Array.from({ length: 40 }, (_, index) => ({
id: `item-${index}`,
label: `Item ${index}`,
showWhen: () => true,
})),
),
);

const viewportWidth = vi.spyOn(document.documentElement, 'clientWidth', 'get').mockReturnValue(1000);
const viewportHeight = vi.spyOn(document.documentElement, 'clientHeight', 'get').mockReturnValue(760);
const rect = vi.spyOn(HTMLElement.prototype, 'getBoundingClientRect').mockImplementation(function () {
if (this.classList.contains('context-menu')) {
const top = Number.parseFloat(this.style.top) || 0;
const height = this.querySelector('.context-menu-search-header') ? 330 : 300;
return { left: 100, top, right: 280, bottom: top + height, width: 180, height };
}
return { left: 0, top: 0, right: 0, bottom: 0, width: 0, height: 0 };
});

const wrapper = mount(ContextMenu, { props: mockProps });
try {
const onContextMenuOpen = mockEditor.on.mock.calls.find((call) => call[0] === 'contextMenu:open')[1];
await onContextMenuOpen({ menuPosition: { left: '100px', top: '452px' } });
await wrapper.find('.context-menu-hidden-input').setValue('Item');
await nextTick();
await nextTick();

expect(wrapper.find('.context-menu').element.style.top).toBe('422px');
} finally {
wrapper.unmount();
rect.mockRestore();
viewportWidth.mockRestore();
viewportHeight.mockRestore();
}
});

it('should not open menu when editor is read-only', async () => {
mockEditor.isEditable = false;
const wrapper = mount(ContextMenu, { props: mockProps });
Expand Down
Loading
Loading