Skip to content

Commit

Permalink
feat: add relativeTo argument to getDocumentPosition for anchor p…
Browse files Browse the repository at this point in the history
…ositioning in complex DOM
  • Loading branch information
McManning committed May 23, 2023
1 parent a00f377 commit 556ea0c
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 32 deletions.
4 changes: 2 additions & 2 deletions src/components/Thread/Reply.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -80,8 +80,8 @@ export const Reply = React.forwardRef<HTMLDivElement, ReplyProps>(({ thread, nod

{/* TODO: Disable when hasActiveEditor.
See: https://github.com/osuresearch/ui/issues/54 */}
<Item key="edit">Edit reply</Item>
<Item key="delete"><Text c="error">Delete</Text></Item>
<Item key="edit" textValue="Edit">Edit reply</Item>
<Item key="delete" textValue="Delete"><Text c="error">Delete</Text></Item>
</Menu>
)}
</Group>
Expand Down
41 changes: 11 additions & 30 deletions src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,41 +14,22 @@ export function isInViewport(window: Window, rect: Rect) {
}

/**
* Get absolute position of the element in the root document.
*
* This also accounts for elements within nested iframes.
* Get the position of an element in the document relative to some parent
*/
export function getDocumentPosition(el: Element): { top: number; left: number } {
const doc = el.ownerDocument;
const win = doc.defaultView;
if (!win) {
return { top: -1, left: -1 };
export function getDocumentPosition(el: HTMLElement, relativeTo?: HTMLElement) {
let left = 0;
let top = 0;
let current = el;

while (current && current !== relativeTo && !isNaN(current.offsetLeft) && !isNaN(current.offsetTop)) {
left += current.offsetLeft - current.scrollLeft;
top += current.offsetTop - current.scrollTop;
current = current.offsetParent as HTMLElement;
}

const rect = el.getBoundingClientRect();
const scrollLeft = win.scrollX || doc.documentElement.scrollLeft;
const scrollTop = win.scrollY || doc.documentElement.scrollTop;

// // If the element is in an iframe, we need to recurse upward.
// if (win.frameElement) {
// const framePosition = getDocumentPosition(win.frameElement);
// return {
// top: Math.round(framePosition.top + rect.top + scrollTop),
// left: Math.round(framePosition.left + rect.left + scrollLeft)
// };
// }

return {
top: Math.round(rect.top + scrollTop),
left: Math.round(rect.left + scrollLeft)
};
return { top, left };
}

// function sortThreads(threads: HTMLElement[], anchors: HTMLElement[]): HTMLElement[] {
// // sort anchors by top and then re-map the sorted indices back to threads.

// }

/**
* Reflow all threads below (below in DOM, above in index number and top)
* the given thread index to make room for the thread at the given index
Expand Down

0 comments on commit 556ea0c

Please sign in to comment.