Skip to content

Commit

Permalink
fix(dropdown): add left and right repositioning for the rails dropdown
Browse files Browse the repository at this point in the history
  • Loading branch information
QuintonJason committed Oct 25, 2023
1 parent b859c9e commit 1d89206
Showing 1 changed file with 40 additions and 15 deletions.
55 changes: 40 additions & 15 deletions packages/sage-system/lib/dropdown.js
Original file line number Diff line number Diff line change
Expand Up @@ -191,48 +191,73 @@ Sage.dropdown = (function () {

function positionElement(el) {
let direction = null;

// Elements
const button = el;
const panel = el.lastElementChild
const panel = el.lastElementChild;
const win = panel.ownerDocument.defaultView;
const docEl = window.document.documentElement;

panel.style.top = ''; // resets the style

panel.style.left = ''; // resets the style

// Dimensions
const buttonDimensions = button.getBoundingClientRect();
const panelDimensions = panel.getBoundingClientRect();

const panelNewLoc = {
top: ( buttonDimensions.height / 2 ) + panelDimensions.height
}

top: (buttonDimensions.height / 2) + panelDimensions.height,
left: (buttonDimensions.width / 2) + panelDimensions.width,
};

const viewport = {
top: docEl.scrollTop,
bottom: window.pageYOffset + docEl.clientHeight,
}

left: docEl.scrollLeft,
right: window.pageXOffset + docEl.clientWidth,
};

const offset = {
top: panelDimensions.top + win.pageYOffset,
left: panelDimensions.left + win.pageXOffset,
bottom: (panelDimensions.top + win.pageYOffset)
bottom: (panelDimensions.top + win.pageYOffset),
right: (panelDimensions.left + win.pageXOffset),
};

const panelHeight = getHeight(panel);
const enoughSpaceAbove = viewport.top < ( offset.top + panelHeight);
const panelWidth = panelDimensions.width;
const enoughSpaceAbove = viewport.top < (offset.top + panelHeight);
const enoughSpaceBelow = viewport.bottom > (offset.bottom + panelHeight);

const enoughSpaceLeft = viewport.left < (offset.left + panelWidth);
const enoughSpaceRight = viewport.right > (offset.right + panelWidth);

if (!enoughSpaceBelow && enoughSpaceAbove) {
direction = 'above';
} else if (!enoughSpaceAbove && enoughSpaceBelow) {
direction = 'below';
} else if (!enoughSpaceRight && enoughSpaceLeft) {
direction = 'left';
} else if (!enoughSpaceLeft && enoughSpaceRight) {
direction = 'right';
}

if ( direction == 'above') {
console.log('direction: ', direction);

if (direction === 'above') {
panel.style.top = `-${panelNewLoc.top}px`;
} else if (direction === 'below') {
// panel.style.top = 'inherit';
// panel.style.bottom = 0;
} else if (direction === 'left') {
// panel.style.left = `-${panelNewLoc.left}px`;
panel.style.left = 'inherit';
panel.style.right = 0;
} else if (direction === 'right') {
panel.style.left = 0;
panel.style.right = 'inherit';
}
}

function open(el) {
el.setAttribute("aria-expanded", "true");
positionElement(el);
Expand Down

0 comments on commit 1d89206

Please sign in to comment.