Auto-positioning: added another test for horizontal positioning

This commit is contained in:
Rainer Simon 2021-04-19 19:41:38 +02:00
parent 34c8daadc4
commit c778a8c282
1 changed files with 15 additions and 3 deletions

View File

@ -10,19 +10,22 @@ const setPosition = (wrapperEl, editorEl, selectedEl) => {
// Set visible
editorEl.style.opacity = 1;
// Default orientation
// Default orientation (upwards arrow, at bottom-left of shape)
const { left, top, right, height, bottom } = selectedEl.getBoundingClientRect();
editorEl.style.top = `${top + height - containerBounds.top}px`;
editorEl.style.left = `${left - containerBounds.left}px`;
const defaultOrientation = editorEl.children[1].getBoundingClientRect();
// Test 1: does right edge extend beyond the width of the page?
// If so, flip horizontally
if (defaultOrientation.right > window.innerWidth) {
// Default bounds clipped - flip horizontally
editorEl.classList.add('align-right');
editorEl.style.left = `${right - defaultOrientation.width - containerBounds.left}px`;
}
// Test 2: does the bottom edge extend beyond the height of the page?
// If so, flip vertically
if (defaultOrientation.bottom > window.innerHeight) {
// Flip vertically
const annotationTop = top + pageYOffset; // Annotation bottom relative to parents
@ -33,8 +36,11 @@ const setPosition = (wrapperEl, editorEl, selectedEl) => {
editorEl.style.bottom = `${containerHeight - annotationTop}px`;
}
// Check if vertical flip helped, push down if not
// Get bounding box in current orientation
const currentOrientation = editorEl.children[1].getBoundingClientRect();
// Test 3: does the top (still?) extend beyond top of the page?
// If so, push down
if (currentOrientation.top < 0) {
editorEl.style.top = `${-containerBounds.top}px`;
editorEl.style.bottom = 'auto';
@ -46,6 +52,12 @@ const setPosition = (wrapperEl, editorEl, selectedEl) => {
editorEl.classList.remove('align-bottom');
}
// Test 4: does the left edge extend beyond the start of the page?
// If so, push inward
if (currentOrientation.left < 0) {
editorEl.style.left = `${-containerBounds.left}px`;
}
}
export default setPosition;