fix: reposition dropdowns when resizing window

This commit is contained in:
Antonella Sgarlatta
2021-06-30 18:50:38 -03:00
parent ad53f059e1
commit afc84b5702
4 changed files with 104 additions and 62 deletions

View File

@@ -2,13 +2,19 @@ import { AppState } from '@/ui_models/app_state';
import { toDirective, useCloseOnBlur, useCloseOnClickOutside } from './utils';
import { observer } from 'mobx-react-lite';
import { NotesOptions } from './NotesOptions';
import { useRef } from 'preact/hooks';
import { useCallback, useEffect, useRef } from 'preact/hooks';
type Props = {
appState: AppState;
};
const NotesContextMenu = observer(({ appState }: Props) => {
const {
contextMenuOpen,
contextMenuPosition,
contextMenuMaxHeight,
} = appState.notes;
const contextMenuRef = useRef<HTMLDivElement>();
const [closeOnBlur] = useCloseOnBlur(
contextMenuRef,
@@ -20,13 +26,24 @@ const NotesContextMenu = observer(({ appState }: Props) => {
(open: boolean) => appState.notes.setContextMenuOpen(open)
);
return appState.notes.contextMenuOpen ? (
const reloadContextMenuLayout = useCallback(() => {
appState.notes.reloadContextMenuLayout();
}, [appState.notes]);
useEffect(() => {
window.addEventListener('resize', reloadContextMenuLayout);
return () => {
window.removeEventListener('resize', reloadContextMenuLayout);
};
}, [reloadContextMenuLayout]);
return contextMenuOpen ? (
<div
ref={contextMenuRef}
className="sn-dropdown min-w-80 max-h-120 max-w-xs flex flex-col py-2 overflow-y-auto fixed"
style={{
...appState.notes.contextMenuPosition,
maxHeight: appState.notes.contextMenuMaxHeight,
...contextMenuPosition,
maxHeight: contextMenuMaxHeight,
}}
>
<NotesOptions appState={appState} closeOnBlur={closeOnBlur} />

View File

@@ -11,6 +11,7 @@ import {
} from '@reach/disclosure';
import { Switch } from './Switch';
import { observer } from 'mobx-react-lite';
import { useEffect } from 'react';
type Props = {
appState: AppState;
@@ -45,16 +46,27 @@ const SearchOptions = observer(({ appState }: Props) => {
}
}
const updateWidthAndPosition = () => {
const rect = buttonRef.current.getBoundingClientRect();
setMaxWidth(rect.right - 16);
setPosition({
top: rect.bottom,
right: document.body.clientWidth - rect.right,
});
};
useEffect(() => {
window.addEventListener('resize', updateWidthAndPosition);
return () => {
window.removeEventListener('resize', updateWidthAndPosition);
};
}, []);
return (
<Disclosure
open={open}
onChange={() => {
const rect = buttonRef.current.getBoundingClientRect();
setMaxWidth(rect.right - 16);
setPosition({
top: rect.bottom,
right: document.body.clientWidth - rect.right,
});
updateWidthAndPosition();
setOpen(!open);
}}
>