[Glitch] Replace react-overlays with Floating UI

Port 296750204a to glitch-soc

Signed-off-by: Claire <claire.github-309c@sitedethib.com>
This commit is contained in:
diondiondion authored and Claire committed 2026-06-27 16:11:37 +02:00
1 parent d8312fceea
commit 79c1aaf4e6
26 files changed
+554 -468

No files matched your search

@@ -1,12 +1,10 @@
import { useCallback, useId, useRef, useState } from 'react';
import { useCallback, useId, useState } from 'react';
import type { FC } from 'react';
import { defineMessages, FormattedMessage, useIntl } from 'react-intl';
import classNames from 'classnames';
import Overlay from 'react-overlays/esm/Overlay';
import { useAccount } from '@/flavours/glitch/hooks/useAccount';
import { useRelationship } from '@/flavours/glitch/hooks/useRelationship';
import { useAppSelector } from '@/flavours/glitch/store';
@@ -20,6 +18,7 @@ import { CopyButton } from '../copy_button';
import { DisplayName } from '../display_name';
import { Icon } from '../icon';
import { NavigationFocusTarget } from '../navigation_focus_target';
import { Popover } from '../popover';
import { AccountBadges } from './badges';
import classes from './styles.module.scss';
@@ -82,7 +81,8 @@ const AccountNameHelp: FC<{
const accessibilityId = useId();
const intl = useIntl();
const [open, setOpen] = useState(false);
const triggerRef = useRef<HTMLButtonElement>(null);
const [triggerElement, setTriggerElement] =
useState<HTMLButtonElement | null>(null);
const handleClick = useCallback(() => {
setOpen((prev) => !prev);
@@ -94,7 +94,7 @@ const AccountNameHelp: FC<{
<>
<button
type='button'
ref={triggerRef}
ref={setTriggerElement}
className={classes.handleHelpButton}
onClick={handleClick}
aria-expanded={open}
@@ -108,12 +108,11 @@ const AccountNameHelp: FC<{
/>
</button>
<Overlay
show={open}
rootClose
target={triggerRef as React.RefObject<HTMLButtonElement>}
onHide={handleClick}
offset={[5, 5]}
<Popover
isOpen={open}
reference={triggerElement}
onClose={handleClick}
offset={5}
>
{({ props }) => (
<div
@@ -192,7 +191,7 @@ const AccountNameHelp: FC<{
</CopyButton>
</div>
)}
</Overlay>
</Popover>
</>
);
};
@@ -4,22 +4,14 @@ import { FormattedMessage, useIntl } from 'react-intl';
import classNames from 'classnames';
import type {
OffsetValue,
UsePopperOptions,
} from 'react-overlays/esm/usePopper';
import Overlay from 'react-overlays/Overlay';
import CloseIcon from '@/material-icons/400-24px/close.svg?react';
import { useSelectableClick } from 'flavours/glitch/hooks/useSelectableClick';
import { IconButton } from '../icon_button';
import { Popover } from '../popover';
import classes from './styles.module.scss';
const offset = [0, 4] as OffsetValue;
const popperConfig = { strategy: 'fixed' } as UsePopperOptions;
export const AltTextBadge: React.FC<{
description: string;
className?: string;
@@ -28,7 +20,9 @@ export const AltTextBadge: React.FC<{
const uniqueId = useId();
const popoverId = `${uniqueId}-popover`;
const titleId = `${uniqueId}-title`;
const buttonRef = useRef<HTMLButtonElement>(null);
const [buttonElement, setButtonElement] = useState<HTMLButtonElement | null>(
null,
);
const popoverRef = useRef<HTMLDivElement>(null);
const [open, setOpen] = useState(false);
@@ -41,8 +35,8 @@ export const AltTextBadge: React.FC<{
const handleClose = useCallback(() => {
setOpen(false);
buttonRef.current?.focus();
}, [setOpen]);
buttonElement?.focus();
}, [buttonElement]);
const [handleMouseDown, handleMouseUp] = useSelectableClick(handleClose);
@@ -50,7 +44,7 @@ export const AltTextBadge: React.FC<{
<>
<button
type='button'
ref={buttonRef}
ref={setButtonElement}
className={classNames('media-gallery__alt__label', className)}
onClick={handleClick}
aria-expanded={open}
@@ -60,15 +54,12 @@ export const AltTextBadge: React.FC<{
ALT
</button>
<Overlay
rootClose
onHide={handleClose}
show={open}
target={buttonRef as React.RefObject<HTMLButtonElement>}
<Popover
isOpen={open}
onClose={handleClose}
reference={buttonElement}
placement='top-end'
flip
offset={offset}
popperConfig={popperConfig}
offset={4}
>
{({ props }) => (
<div {...props} className='hover-card-controller'>
@@ -105,7 +96,7 @@ export const AltTextBadge: React.FC<{
</div>
</div>
)}
</Overlay>
</Popover>
</>
);
};
@@ -5,14 +5,13 @@ import classNames from 'classnames';
import ImmutablePropTypes from 'react-immutable-proptypes';
import ImmutablePureComponent from 'react-immutable-pure-component';
import Overlay from 'react-overlays/Overlay';
import AutosuggestAccountContainer from '../features/compose/containers/autosuggest_account_container';
import { AutosuggestEmoji } from './autosuggest_emoji';
import { AutosuggestHashtag } from './autosuggest_hashtag';
import { LocalCustomEmojiProvider } from './emoji/context';
import { textAtCursorMatchesToken } from './autosuggest/utils';
import { Popover } from './popover';
export default class AutosuggestInput extends ImmutablePureComponent {
@@ -129,6 +128,10 @@ export default class AutosuggestInput extends ImmutablePureComponent {
this.setState({ focused: true });
};
onCloseMenu = () => {
this.setState({ suggestionsHidden: true });
};
onSuggestionClick = (e) => {
const suggestion = this.props.suggestions.get(e.currentTarget.getAttribute('data-index'));
e.preventDefault();
@@ -197,7 +200,12 @@ export default class AutosuggestInput extends ImmutablePureComponent {
/>
<LocalCustomEmojiProvider>
<Overlay show={!(suggestionsHidden || suggestions.isEmpty())} offset={[0, 0]} placement='bottom' target={this.input} popperConfig={{ strategy: 'fixed' }}>
<Popover
reference={this.input}
isOpen={!(suggestionsHidden || suggestions.isEmpty())}
onClose={this.onCloseMenu}
flip={false}
>
{({ props }) => (
<div {...props}>
<div className='autosuggest-textarea__suggestions' style={{ width: this.input?.clientWidth }}>
@@ -205,7 +213,7 @@ export default class AutosuggestInput extends ImmutablePureComponent {
</div>
</div>
)}
</Overlay>
</Popover>
</LocalCustomEmojiProvider>
</div>
);
@@ -5,7 +5,6 @@ import classNames from 'classnames';
import ImmutablePropTypes from 'react-immutable-proptypes';
import Overlay from 'react-overlays/Overlay';
import Textarea from 'react-textarea-autosize';
import AutosuggestAccountContainer from '../features/compose/containers/autosuggest_account_container';
@@ -14,6 +13,7 @@ import { AutosuggestEmoji } from './autosuggest_emoji';
import { AutosuggestHashtag } from './autosuggest_hashtag';
import { LocalCustomEmojiProvider } from './emoji/context';
import { textAtCursorMatchesToken } from './autosuggest/utils';
import { Popover } from './popover';
const AutosuggestTextarea = forwardRef(({
value,
@@ -36,6 +36,7 @@ const AutosuggestTextarea = forwardRef(({
const [suggestionsHidden, setSuggestionsHidden] = useState(true);
const [selectedSuggestion, setSelectedSuggestion] = useState(0);
const [textareaElement, setTextareaElement] = useState(null);
const lastTokenRef = useRef(null);
const tokenStartRef = useRef(0);
@@ -110,7 +111,7 @@ const AutosuggestTextarea = forwardRef(({
onKeyDown(e);
}, [disabled, suggestions, suggestionsHidden, selectedSuggestion, setSelectedSuggestion, setSuggestionsHidden, onSuggestionSelected, onKeyDown]);
const handleBlur = useCallback(() => {
const closeMenu = useCallback(() => {
setSuggestionsHidden(true);
}, [setSuggestionsHidden]);
@@ -173,10 +174,15 @@ const AutosuggestTextarea = forwardRef(({
);
};
const handleRef = useCallback((element) => {
textareaRef.current = element;
setTextareaElement(element);
}, []);
return (
<div className={classNames('autosuggest-textarea', className)}>
<Textarea
ref={textareaRef}
ref={handleRef}
className='autosuggest-textarea__textarea'
disabled={disabled}
placeholder={placeholder}
@@ -186,7 +192,7 @@ const AutosuggestTextarea = forwardRef(({
onKeyDown={handleKeyDown}
onKeyUp={onKeyUp}
onFocus={handleFocus}
onBlur={handleBlur}
onBlur={closeMenu}
onPaste={handlePaste}
onDrop={handleDrop}
dir='auto'
@@ -196,15 +202,20 @@ const AutosuggestTextarea = forwardRef(({
/>
<LocalCustomEmojiProvider>
<Overlay show={!(suggestionsHidden || suggestions.isEmpty())} offset={[0, 0]} placement='bottom' target={textareaRef} popperConfig={{ strategy: 'fixed' }}>
<Popover
matchReferenceWidth
isOpen={!(suggestionsHidden || suggestions.isEmpty())}
onClose={closeMenu}
reference={textareaElement}
>
{({ props }) => (
<div {...props}>
<div className='autosuggest-textarea__suggestions' style={{ width: textareaRef.current?.clientWidth }}>
<div className='autosuggest-textarea__suggestions' style={{ width: textareaElement?.clientWidth }}>
{suggestions.map(renderSuggestion)}
</div>
</div>
)}
</Overlay>
</Popover>
</LocalCustomEmojiProvider>
</div>
);
@@ -1,4 +1,4 @@
import { useCallback, useId, useMemo, useRef, useState } from 'react';
import { useCallback, useId, useMemo, useState } from 'react';
import type { ComponentPropsWithoutRef, FC } from 'react';
import { useIntl } from 'react-intl';
@@ -6,15 +6,12 @@ import type { MessageDescriptor } from 'react-intl';
import classNames from 'classnames';
import Overlay from 'react-overlays/Overlay';
import UnfoldMoreIcon from '@/material-icons/400-24px/unfold_more.svg?react';
import type { SelectItem } from '../dropdown_selector';
import { DropdownSelector } from '../dropdown_selector';
import { Icon } from '../icon';
import { matchWidth } from './utils';
import { Popover } from '../popover';
interface DropdownProps {
disabled?: boolean;
@@ -42,7 +39,9 @@ export const Dropdown: FC<
...buttonProps
}) => {
const intl = useIntl();
const buttonRef = useRef<HTMLButtonElement>(null);
const [buttonElement, setButtonElement] = useState<HTMLButtonElement | null>(
null,
);
const uniqueId = useId();
const buttonId = id ?? `${uniqueId}-button`;
const listboxId = `${uniqueId}-listbox`;
@@ -52,16 +51,16 @@ export const Dropdown: FC<
const handleToggle = useCallback(() => {
if (!disabled) {
setOpen((prevOpen) => {
buttonRef.current?.focus();
buttonElement?.focus();
return !prevOpen;
});
}
}, [disabled]);
}, [buttonElement, disabled]);
const handleClose = useCallback(() => {
setOpen(false);
buttonRef.current?.focus();
}, []);
buttonElement?.focus();
}, [buttonElement]);
const currentText = useMemo(
() =>
@@ -93,7 +92,7 @@ export const Dropdown: FC<
},
className,
)}
ref={buttonRef}
ref={setButtonElement}
>
{currentText}
<Icon
@@ -103,17 +102,12 @@ export const Dropdown: FC<
/>
</button>
<Overlay
show={open}
offset={[0, 0]}
<Popover
matchReferenceWidth
isOpen={open}
placement='bottom-start'
onHide={handleClose}
flip
target={buttonRef as React.RefObject<HTMLButtonElement>}
popperConfig={{
strategy: 'fixed',
modifiers: [matchWidth],
}}
onClose={handleClose}
reference={buttonElement}
>
{({ props, placement }) => (
<div {...props} className={`${classPrefix}__overlay`}>
@@ -135,7 +129,7 @@ export const Dropdown: FC<
</div>
</div>
)}
</Overlay>
</Popover>
</>
);
};
@@ -1,17 +0,0 @@
import type { Modifier, UsePopperState } from 'react-overlays/esm/usePopper';
export const matchWidth: Modifier<'sameWidth', UsePopperState> = {
name: 'sameWidth',
enabled: true,
phase: 'beforeWrite',
requires: ['computeStyles'],
fn: ({ state }) => {
if (state.styles.popper) {
state.styles.popper.width = `${state.rects.reference.width}px`;
}
},
effect: ({ state }) => {
const reference = state.elements.reference as HTMLElement;
state.elements.popper.style.width = `${reference.offsetWidth}px`;
},
};
@@ -13,13 +13,6 @@ import { Link } from 'react-router-dom';
import type { Map as ImmutableMap } from 'immutable';
import type {
OffsetValue,
UsePopperOptions,
Placement,
} from 'react-overlays/esm/usePopper';
import Overlay from 'react-overlays/Overlay';
import { fetchRelationships } from 'flavours/glitch/actions/accounts';
import {
openDropdownMenu,
@@ -40,6 +33,8 @@ import { useAppDispatch, useAppSelector } from 'flavours/glitch/store';
import { Icon } from './icon';
import type { IconProp } from './icon';
import { IconButton } from './icon_button';
import type { PopoverProps } from './popover';
import { Popover } from './popover';
let id = 0;
@@ -302,8 +297,8 @@ interface DropdownProps<Item extends object | null = MenuItem> {
title?: string;
disabled?: boolean;
scrollable?: boolean;
placement?: Placement;
offset?: OffsetValue;
placement?: PopoverProps['placement'];
offset?: PopoverProps['offset'];
/**
* Prevent the `ScrollableList` with this scrollKey
* from being scrolled while the dropdown is open
@@ -321,8 +316,6 @@ interface DropdownProps<Item extends object | null = MenuItem> {
onItemClick?: ItemClickFn<Item>;
}
const popperConfig = { strategy: 'fixed' } as UsePopperOptions;
export const Dropdown = <Item extends object | null = MenuItem>({
children,
icon,
@@ -334,7 +327,7 @@ export const Dropdown = <Item extends object | null = MenuItem>({
disabled,
scrollable,
placement = 'bottom',
offset = [5, 5],
offset = 5,
status,
needsStatusRefresh,
forceDropdown = false,
@@ -352,7 +345,9 @@ export const Dropdown = <Item extends object | null = MenuItem>({
);
const [currentId] = useState(id++);
const open = currentId === openDropdownId;
const buttonRef = useRef<HTMLButtonElement>(null);
const [buttonElement, setButtonElement] = useState<HTMLButtonElement | null>(
null,
);
const menuId = useId();
const prefetchAccountId = status
? status.getIn(['account', 'id'])
@@ -360,8 +355,8 @@ export const Dropdown = <Item extends object | null = MenuItem>({
const statusId = status?.get('id') as string | undefined;
const handleClose = useCallback(() => {
if (buttonRef.current) {
buttonRef.current.focus({ preventScroll: true });
if (buttonElement) {
buttonElement.focus({ preventScroll: true });
}
dispatch(
@@ -372,7 +367,7 @@ export const Dropdown = <Item extends object | null = MenuItem>({
);
dispatch(closeDropdownMenu({ id: currentId }));
}, [dispatch, currentId]);
}, [buttonElement, dispatch, currentId]);
const handleItemClick = useCallback(
(e: React.MouseEvent) => {
@@ -489,7 +484,7 @@ export const Dropdown = <Item extends object | null = MenuItem>({
onBlur: unsetIsKeypress,
'aria-expanded': open,
'aria-controls': menuId,
ref: buttonRef,
ref: setButtonElement,
};
if (children) {
@@ -513,22 +508,16 @@ export const Dropdown = <Item extends object | null = MenuItem>({
<>
{button}
<Overlay
show={open}
<Popover
isOpen={open}
onClose={handleClose}
offset={offset}
placement={placement}
flip
target={buttonRef as React.RefObject<HTMLButtonElement>}
popperConfig={popperConfig}
reference={buttonElement}
>
{({ props, arrowProps, placement }) => (
{({ props, placement }) => (
<div {...props} className={className} id={menuId}>
<div className={`dropdown-animation dropdown-menu ${placement}`}>
<div
className={`dropdown-menu__arrow ${placement}`}
{...arrowProps}
/>
<DropdownMenu
items={items}
loading={loading}
@@ -542,7 +531,7 @@ export const Dropdown = <Item extends object | null = MenuItem>({
</div>
</div>
)}
</Overlay>
</Popover>
</>
);
};
@@ -14,16 +14,13 @@ import { useIntl } from 'react-intl';
import classNames from 'classnames';
import Overlay from 'react-overlays/Overlay';
import KeyboardArrowDownIcon from '@/material-icons/400-24px/keyboard_arrow_down.svg?react';
import KeyboardArrowUpIcon from '@/material-icons/400-24px/keyboard_arrow_up.svg?react';
import SearchIcon from '@/material-icons/400-24px/search.svg?react';
import { matchWidth } from 'flavours/glitch/components/dropdown/utils';
import { IconButton } from 'flavours/glitch/components/icon_button';
import { useOnClickOutside } from 'flavours/glitch/hooks/useOnClickOutside';
import { LoadingIndicator } from '../loading_indicator';
import { Popover } from '../popover';
import classes from './combobox.module.scss';
import { FormFieldWrapper } from './form_field_wrapper';
@@ -236,8 +233,12 @@ const ComboboxWithRef = <Item extends ComboboxItem, GroupKey extends string>(
) => {
const intl = useIntl();
const wrapperRef = useRef<HTMLDivElement>(null);
const inputRef = useRef<HTMLInputElement>(null);
const popoverRef = useRef<HTMLDivElement>(null);
const [inputElement, setInputElement] = useState<HTMLInputElement | null>(
null,
);
const [popoverElement, setPopoverElement] = useState<HTMLDivElement | null>(
null,
);
// This ref tracks whether the menu was just closed following a
// selection, and prevents the menu from re-opening again
@@ -275,24 +276,27 @@ const ComboboxWithRef = <Item extends ComboboxItem, GroupKey extends string>(
const openMenu = useCallback(() => {
setShouldMenuOpen(true);
inputRef.current?.focus();
}, []);
inputElement?.focus();
}, [inputElement]);
const closeMenu = useCallback(() => {
setShouldMenuOpen(false);
}, []);
const highlightItem = useCallback((id: string | null) => {
setHighlightedItemId(id);
if (id) {
const itemElement = popoverRef.current?.querySelector<HTMLLIElement>(
`[data-item-id='${id}']`,
);
if (itemElement && popoverRef.current) {
scrollItemIntoView(itemElement, popoverRef.current);
const highlightItem = useCallback(
(id: string | null) => {
setHighlightedItemId(id);
if (id) {
const itemElement = popoverElement?.querySelector<HTMLLIElement>(
`[data-item-id='${id}']`,
);
if (itemElement && popoverElement) {
scrollItemIntoView(itemElement, popoverElement);
}
}
}
}, []);
},
[popoverElement],
);
const resetHighlight = useCallback(() => {
const firstItem = flatItems[0];
@@ -353,9 +357,16 @@ const ComboboxWithRef = <Item extends ComboboxItem, GroupKey extends string>(
}
}
}
inputRef.current?.focus();
inputElement?.focus();
},
[closeMenu, closeOnSelect, getIsItemDisabled, flatItems, onSelectItem],
[
flatItems,
inputElement,
getIsItemDisabled,
onSelectItem,
closeOnSelect,
closeMenu,
],
);
const handleSelectItem = useCallback(
@@ -406,8 +417,6 @@ const ComboboxWithRef = <Item extends ComboboxItem, GroupKey extends string>(
[getItemId, highlightItem, highlightedItemId, flatItems],
);
useOnClickOutside(wrapperRef, closeMenu);
const handleInputKeyDown = useCallback(
(e: React.KeyboardEvent<HTMLInputElement>) => {
onKeyDown?.(e);
@@ -489,9 +498,9 @@ const ComboboxWithRef = <Item extends ComboboxItem, GroupKey extends string>(
);
});
const mergeRefs = useCallback(
const mergeInputRefs = useCallback(
(element: HTMLInputElement | null) => {
inputRef.current = element;
setInputElement(element);
if (typeof ref === 'function') {
ref(element);
} else if (ref) {
@@ -525,7 +534,7 @@ const ComboboxWithRef = <Item extends ComboboxItem, GroupKey extends string>(
onKeyDown={handleInputKeyDown}
icon={icon ?? undefined}
className={classNames(classes.input, className)}
ref={mergeRefs}
ref={mergeInputRefs}
/>
{hasMenuContent && (
<IconButton
@@ -551,20 +560,23 @@ const ComboboxWithRef = <Item extends ComboboxItem, GroupKey extends string>(
<span role='status' aria-live='polite' className='sr-only'>
{isMenuOpen && statusMessage}
</span>
<Overlay
show={isMenuOpen}
offset={[0, 1]}
<Popover
matchReferenceWidth
isOpen={isMenuOpen}
onClose={closeMenu}
offset={1}
placement='bottom-start'
onHide={closeMenu}
ref={popoverRef}
target={inputRef as React.RefObject<HTMLInputElement>}
container={wrapperRef as React.RefObject<HTMLDivElement>}
popperConfig={{
modifiers: [matchWidth],
}}
strategy='absolute'
popoverElement={popoverElement}
reference={inputElement}
container={null}
>
{({ props, placement }) => (
<div {...props} className={classNames(classes.popover, placement)}>
<div
{...props}
ref={setPopoverElement}
className={classNames(classes.popover, placement)}
>
<StatusMessageWrapper
showStatus={showStatusMessageInMenu}
isLoading={isLoading}
@@ -608,7 +620,7 @@ const ComboboxWithRef = <Item extends ComboboxItem, GroupKey extends string>(
</StatusMessageWrapper>
</div>
)}
</Overlay>
</Popover>
</div>
);
};
@@ -2,23 +2,18 @@ import { useEffect, useRef, useState, useCallback } from 'react';
import { useLocation } from 'react-router-dom';
import type {
OffsetValue,
UsePopperOptions,
} from 'react-overlays/esm/usePopper';
import Overlay from 'react-overlays/Overlay';
import { HoverCardAccount } from 'flavours/glitch/components/hover_card_account';
import type { PopoverProps } from 'flavours/glitch/components/popover';
import { Popover } from 'flavours/glitch/components/popover';
import { useTimeout } from 'flavours/glitch/hooks/useTimeout';
const offset = [-12, 4] as OffsetValue;
const offset: PopoverProps['offset'] = { crossAxis: -12, mainAxis: 4 } as const;
const enterDelay = 750;
const leaveDelay = 150;
// Only open the card if the mouse was moved within this time,
// to avoid triggering the card without intentional mouse movement
// (e.g. when content changed underneath the mouse cursor)
const activeMovementThreshold = 150;
const popperConfig = { strategy: 'fixed' } as UsePopperOptions;
const isHoverCardAnchor = (element: HTMLElement) =>
element.matches('[data-hover-card-account]');
@@ -212,21 +207,18 @@ export const HoverCardController: React.FC = () => {
]);
return (
<Overlay
rootClose
onHide={handleClose}
show={open}
target={anchor}
<Popover
onClose={handleClose}
isOpen={open}
reference={anchor}
placement='bottom-start'
flip
offset={offset}
popperConfig={popperConfig}
>
{({ props }) => (
<div {...props} className='hover-card-controller'>
<HoverCardAccount accountId={accountId} ref={cardRef} />
</div>
)}
</Overlay>
</Popover>
);
};
@@ -1,15 +1,15 @@
import { useState, useRef, useCallback, useId } from 'react';
import { useState, useCallback, useId } from 'react';
import { FormattedMessage } from 'react-intl';
import Overlay from 'react-overlays/Overlay';
import { Popover } from './popover';
export const LearnMoreLink: React.FC<{ children: React.ReactNode }> = ({
children,
}) => {
const accessibilityId = useId();
const [open, setOpen] = useState(false);
const triggerRef = useRef<HTMLButtonElement>(null);
const [trigger, setTrigger] = useState<HTMLButtonElement | null>(null);
const handleClick = useCallback(() => {
setOpen(!open);
@@ -19,7 +19,7 @@ export const LearnMoreLink: React.FC<{ children: React.ReactNode }> = ({
<>
<button
className='link-button'
ref={triggerRef}
ref={setTrigger}
onClick={handleClick}
aria-expanded={open}
aria-controls={accessibilityId}
@@ -31,13 +31,12 @@ export const LearnMoreLink: React.FC<{ children: React.ReactNode }> = ({
/>
</button>
<Overlay
show={open}
rootClose
onHide={handleClick}
offset={[5, 5]}
<Popover
isOpen={open}
onClose={handleClick}
offset={5}
placement='bottom-end'
target={triggerRef as React.RefObject<HTMLButtonElement>}
reference={trigger}
>
{({ props }) => (
<div
@@ -62,7 +61,7 @@ export const LearnMoreLink: React.FC<{ children: React.ReactNode }> = ({
</div>
</div>
)}
</Overlay>
</Popover>
</>
);
};
@@ -0,0 +1,203 @@
import { useEffect } from 'react';
import type {
ReferenceType,
Placement,
OffsetOptions,
Strategy,
} from '@floating-ui/react-dom';
import {
useFloating,
autoUpdate,
inline,
offset as offsetMiddleware,
shift,
flip as flipMiddleware,
size,
hide,
} from '@floating-ui/react-dom';
import { useOnClickOutside } from '@/flavours/glitch/hooks/useOnClickOutside';
import { Portal } from './portal';
export interface PopoverProps {
/**
* Set the visibility of the popover
*/
isOpen?: boolean;
/**
* Callback triggered when the popover needs to be closed
* (e.g. because the Esc key was pressed).
*/
onClose: (e: Event) => void;
/**
* Pass an element that the popover should be attached to.
* Must come from `useState`, not `useRef`.
*/
reference: ReferenceType | null;
/**
* Pass the popover element (useful if you also need the element
* in the parent and already have it in state).
* Must come from `useState`, not `useRef`.
*/
popoverElement?: HTMLElement | null;
/**
* Control which element the popover will be rendered into.
* Passing `null` will render the popover in place.
*/
container?: HTMLElement | null;
/**
* Control where the overlay element is positioned in relation
* to the reference element
*/
placement?: Placement;
/**
* Control the distance between popover and reference
*/
offset?: OffsetOptions;
/**
* Allow the popover to flip to the other side of the reference
* if there's no room in the specified direction. Enabled by default.
*/
flip?: boolean;
/**
* Change the positioning strategy, defaults to 'fixed'
* but can be changed to 'absolute'
*/
strategy?: Strategy;
/**
* Adapt the popover's width to match that of the reference,
* useful when attached to text input.
*/
matchReferenceWidth?: boolean;
/**
* Control whether to close the popover when clicking outside
* of it (enabled by default).
*/
closeOnClickOutside?: boolean;
/**
* Render prop that must return the popover element.
*/
children: (value: {
/**
* The popover's final computed placement. Can be used to
* adjust the popover's style based on its position.
*/
placement: Placement | undefined;
/**
* Re-computes the popover's position – call this when an
* action inside of the popover has changed its size.
*/
update: () => void;
/**
* These props must be passed to the popover element to
* enable it to be sized and positioned. The `ref` prop
* is not passed when the `popoverElement` prop is provided.
*/
props: Record<string, unknown> & {
ref?: React.RefCallback<HTMLElement>;
style: React.CSSProperties;
};
}) => React.ReactNode;
}
export const Popover: React.FC<PopoverProps> = ({
isOpen,
onClose,
reference,
popoverElement,
placement = 'bottom',
offset,
strategy = 'fixed',
flip = true,
container,
matchReferenceWidth = false,
closeOnClickOutside = true,
children,
}) => {
const {
placement: computedPlacement,
update,
refs,
floatingStyles,
middlewareData,
elements,
} = useFloating({
elements: {
reference,
floating: popoverElement,
},
placement,
strategy,
whileElementsMounted: autoUpdate,
middleware: [
offsetMiddleware(offset),
inline(),
shift(),
flip ? flipMiddleware() : null,
matchReferenceWidth
? size({
apply({ rects, elements }) {
Object.assign(elements.floating.style, {
minWidth: `${rects.reference.width}px`,
});
},
})
: null,
hide(),
],
});
// Close when clicking outside the popover
useOnClickOutside(
[
elements.floating,
// Only pass reference if it's not a "virtual element"
elements.reference instanceof Element ? elements.reference : null,
],
(e) => {
onClose(e);
},
isOpen && closeOnClickOutside,
);
// Close when pressing Escape
useEffect(() => {
if (!isOpen) {
return () => null;
}
function closeOnEscape(event: KeyboardEvent) {
if (event.key === 'Escape') {
onClose(event);
}
}
document.addEventListener('keyup', closeOnEscape);
return () => {
document.removeEventListener('keyup', closeOnEscape);
};
}, [isOpen, onClose]);
if (!isOpen) {
return null;
}
return (
<Portal container={container}>
{children({
placement: computedPlacement,
update,
props: {
ref: popoverElement ? undefined : refs.setFloating,
style: floatingStyles,
'data-popover-placement': computedPlacement,
'data-popover-reference-hidden': middlewareData.hide?.referenceHidden,
'data-popover-escaped': middlewareData.hide?.escaped,
},
})}
</Portal>
);
};
@@ -0,0 +1,21 @@
import { createPortal } from 'react-dom';
interface PortalProps {
/**
* The element to render the Portal's children into.
* Must be an object, e.g. the result of a getElementById() call.
* Set to `null` to render the children in place,
* i.e. effectively disable the Portal's functionality
*/
readonly container?: HTMLElement | SVGElement | null;
readonly children?: React.ReactNode;
}
export const Portal: React.FC<PortalProps> = ({
container,
children,
}: PortalProps) => {
if (container === null) return children;
return createPortal(children, container ?? document.body);
};
@@ -187,7 +187,7 @@ const BoostOrQuoteMenu: FC<ReblogButtonProps> = ({ status, counters }) => {
return (
<Dropdown
placement='bottom-start'
offset={[-19, 5]} // This aligns button icon with menu icons
offset={{ mainAxis: 5, crossAxis: -19 }} // This aligns button icon with menu icons
items={items}
renderItem={renderMenuItem}
onOpen={handleDropdownOpen}
@@ -1,16 +1,15 @@
import { useEffect, useRef, useState, useId } from 'react';
import { useEffect, useState, useId } from 'react';
import { FormattedMessage, useIntl } from 'react-intl';
import classNames from 'classnames';
import Overlay from 'react-overlays/Overlay';
import { useDismissible } from '@/flavours/glitch/hooks/useDismissible';
import MoreHorizIcon from '@/material-icons/400-24px/more_horiz.svg?react';
import { Button } from '../button';
import { Icon } from '../icon';
import { Popover } from '../popover';
import classes from './remove_quote_hint.module.css';
@@ -28,7 +27,9 @@ export const RemoveQuoteHint: React.FC<{
className?: string;
children: (dismiss: () => void) => React.ReactNode;
}> = ({ canShowHint, className, children }) => {
const anchorRef = useRef<HTMLDivElement>(null);
const [anchorElement, setAnchorElement] = useState<HTMLDivElement | null>(
null,
);
const intl = useIntl();
const { wasDismissed, dismiss } = useDismissible(DISMISSIBLE_BANNER_ID);
@@ -57,16 +58,16 @@ export const RemoveQuoteHint: React.FC<{
}, [shouldShowHint, uniqueId]);
return (
<div className={className} ref={anchorRef}>
<div className={className} ref={setAnchorElement}>
{children(dismiss)}
{shouldShowHint && isOnlyHint && (
<Overlay
show
flip
offset={[12, 10]}
<Popover
isOpen
offset={{ mainAxis: 10, crossAxis: 12 }}
placement='bottom-end'
target={anchorRef as React.RefObject<HTMLDivElement>}
container={anchorRef as React.RefObject<HTMLDivElement>}
reference={anchorElement}
container={anchorElement}
onClose={dismiss}
>
{({ props, placement }) => (
<div
@@ -113,7 +114,7 @@ export const RemoveQuoteHint: React.FC<{
</FormattedMessage>
</div>
)}
</Overlay>
</Popover>
)}
</div>
);
@@ -5,8 +5,6 @@ import { defineMessages, useIntl } from 'react-intl';
import classNames from 'classnames';
import type { OffsetValue } from 'react-overlays/esm/usePopper';
import type { ModalType } from '@/flavours/glitch/actions/modal';
import { openModal } from '@/flavours/glitch/actions/modal';
import { Dropdown } from '@/flavours/glitch/components/dropdown_menu';
@@ -118,7 +116,7 @@ export const AccountImageEdit: FC<{
<Dropdown
items={items}
placement={location === 'header' ? 'bottom-end' : 'bottom-start'}
offset={popperOffset}
offset={6}
className={classes.imageMenu}
icon='camera'
title={intl.formatMessage(messages.replace)}
@@ -127,5 +125,3 @@ export const AccountImageEdit: FC<{
/>
);
};
const popperOffset = [0, 6] as OffsetValue;
@@ -1,15 +1,14 @@
import { useCallback, useId, useRef, useState } from 'react';
import { useCallback, useId, useState } from 'react';
import type { ChangeEventHandler, FC } from 'react';
import { FormattedMessage } from 'react-intl';
import { useParams } from 'react-router';
import Overlay from 'react-overlays/esm/Overlay';
import { AccountTabs } from '@/flavours/glitch/components/account_header/tabs';
import { Toggle } from '@/flavours/glitch/components/form_fields';
import { Icon } from '@/flavours/glitch/components/icon';
import { Popover } from '@/flavours/glitch/components/popover';
import KeyboardArrowDownIcon from '@/material-icons/400-24px/keyboard_arrow_down.svg?react';
import { useAccountContext } from '../hooks/useAccountContext';
@@ -32,10 +31,12 @@ export const AccountFilters: FC = () => {
const FilterDropdown: FC = () => {
const [open, setOpen] = useState(false);
const buttonRef = useRef<HTMLButtonElement>(null);
const [buttonElement, setButtonElement] = useState<HTMLButtonElement | null>(
null,
);
const handleClick = useCallback(() => {
setOpen(true);
setOpen((prev) => !prev);
}, []);
const handleHide = useCallback(() => {
setOpen(false);
@@ -55,14 +56,13 @@ const FilterDropdown: FC = () => {
);
const accessibleId = useId();
const containerRef = useRef<HTMLDivElement>(null);
return (
<div ref={containerRef}>
<div>
<button
type='button'
className={classes.filterSelectButton}
ref={buttonRef}
ref={setButtonElement}
onClick={handleClick}
aria-expanded={open}
aria-controls={`${accessibleId}-wrapper`}
@@ -97,13 +97,13 @@ const FilterDropdown: FC = () => {
className={classes.filterSelectIcon}
/>
</button>
<Overlay
show={open}
target={buttonRef as React.RefObject<HTMLButtonElement>}
<Popover
isOpen={open}
reference={buttonElement}
placement='bottom-start'
rootClose
onHide={handleHide}
container={containerRef as React.RefObject<HTMLDivElement>}
onClose={handleHide}
strategy='absolute'
container={null}
>
{({ props }) => (
<div
@@ -138,7 +138,7 @@ const FilterDropdown: FC = () => {
/>
</div>
)}
</Overlay>
</Popover>
</div>
);
};
@@ -1,11 +1,10 @@
import { useState, useRef, useCallback, useId } from 'react';
import { useState, useCallback, useId } from 'react';
import { FormattedMessage, useIntl, defineMessages } from 'react-intl';
import classNames from 'classnames';
import Overlay from 'react-overlays/Overlay';
import { Popover } from '@/flavours/glitch/components/popover';
import QuestionMarkIcon from '@/material-icons/400-24px/question_mark.svg?react';
import { Icon } from 'flavours/glitch/components/icon';
import { useSelectableClick } from 'flavours/glitch/hooks/useSelectableClick';
@@ -17,7 +16,7 @@ const messages = defineMessages({
export const InfoButton: React.FC = () => {
const intl = useIntl();
const [open, setOpen] = useState(false);
const triggerRef = useRef<HTMLButtonElement>(null);
const [trigger, setTrigger] = useState<HTMLButtonElement | null>(null);
const accessibilityId = useId();
const handleClick = useCallback(() => {
@@ -31,7 +30,7 @@ export const InfoButton: React.FC = () => {
<button
type='button'
className={classNames('help-button', { active: open })}
ref={triggerRef}
ref={setTrigger}
onClick={handleClick}
aria-expanded={open}
aria-controls={accessibilityId}
@@ -40,13 +39,12 @@ export const InfoButton: React.FC = () => {
<Icon id='' icon={QuestionMarkIcon} />
</button>
<Overlay
show={open}
rootClose
<Popover
isOpen={open}
placement='top'
onHide={handleClick}
offset={[5, 5]}
target={triggerRef as React.RefObject<HTMLButtonElement>}
onClose={handleClick}
offset={5}
reference={trigger}
>
{({ props }) => (
<div // eslint-disable-line jsx-a11y/no-noninteractive-element-interactions
@@ -82,7 +80,7 @@ export const InfoButton: React.FC = () => {
/>
</div>
)}
</Overlay>
</Popover>
</>
);
};
@@ -1,17 +1,14 @@
import PropTypes from 'prop-types';
import { useCallback, useState, useRef } from 'react';
import Overlay from 'react-overlays/Overlay';
import { useCallback, useState } from 'react';
import { DropdownSelector } from 'flavours/glitch/components/dropdown_selector';
import { IconButton } from 'flavours/glitch/components/icon_button';
import { Popover } from 'flavours/glitch/components/popover';
export const DropdownIconButton = ({ value, disabled, icon, onChange, iconComponent, title, options }) => {
const containerRef = useRef(null);
const [activeElement, setActiveElement] = useState(null);
const [open, setOpen] = useState(false);
const [placement, setPlacement] = useState('bottom');
const [containerElement, setContainerElement] = useState(null);
const handleToggle = useCallback(() => {
if (open && activeElement) {
@@ -31,12 +28,8 @@ export const DropdownIconButton = ({ value, disabled, icon, onChange, iconCompon
setOpen(false);
}, [open, setOpen, activeElement, setActiveElement]);
const handleOverlayEnter = useCallback((state) => {
setPlacement(state.placement);
}, [setPlacement]);
return (
<div ref={containerRef}>
<div ref={setContainerElement}>
<IconButton
disabled={disabled}
icon={icon}
@@ -48,7 +41,12 @@ export const DropdownIconButton = ({ value, disabled, icon, onChange, iconCompon
inverted
/>
<Overlay show={open} offset={[5, 5]} placement={placement} flip target={containerRef} popperConfig={{ strategy: 'fixed', onFirstUpdate: handleOverlayEnter }}>
<Popover
isOpen={open}
offset={5}
reference={containerElement}
onClose={handleClose}
>
{({ props, placement }) => (
<div {...props}>
<div className={`dropdown-animation privacy-dropdown__dropdown ${placement}`}>
@@ -61,7 +59,7 @@ export const DropdownIconButton = ({ value, disabled, icon, onChange, iconCompon
</div>
</div>
)}
</Overlay>
</Popover>
</div>
);
};
@@ -6,11 +6,11 @@ import { defineMessages, FormattedMessage } from 'react-intl';
import classNames from 'classnames';
import { supportsPassiveEvents } from 'detect-passive-events';
import Overlay from 'react-overlays/Overlay';
import MoodIcon from '@/material-icons/400-20px/mood.svg?react';
import { IconButton } from 'flavours/glitch/components/icon_button';
import { IconButton } from '@/flavours/glitch/components/icon_button';
import { injectIntl } from '@/flavours/glitch/components/intl';
import { Popover } from '@/flavours/glitch/components/popover';
import { EmojiPicker as EmojiPickerAsync } from '../../ui/util/async-components';
@@ -175,16 +175,7 @@ class EmojiPickerMenuImpl extends PureComponent {
readyToFocus: false,
};
handleDocumentClick = e => {
if (this.node && !this.node.contains(e.target) && !this.props.pickerButtonRef.contains(e.target)) {
this.props.onClose();
}
};
componentDidMount() {
document.addEventListener('click', this.handleDocumentClick, { capture: true });
document.addEventListener('touchend', this.handleDocumentClick, listenerOptions);
// Because of https://github.com/react-bootstrap/react-bootstrap/issues/2614 we need
// to wait for a frame before focusing
requestAnimationFrame(() => {
@@ -196,11 +187,6 @@ class EmojiPickerMenuImpl extends PureComponent {
});
}
componentWillUnmount() {
document.removeEventListener('click', this.handleDocumentClick, { capture: true });
document.removeEventListener('touchend', this.handleDocumentClick, listenerOptions);
}
setRef = c => {
this.node = c;
};
@@ -307,7 +293,7 @@ class EmojiPickerDropdown extends PureComponent {
state = {
active: false,
loading: false,
placement: 'bottom',
target: null,
};
setRef = (c) => {
@@ -344,31 +330,17 @@ class EmojiPickerDropdown extends PureComponent {
}
};
handleKeyDown = e => {
if (e.key === 'Escape') {
this.onHideDropdown();
}
};
setTargetRef = c => {
this.target = c;
};
findTarget = () => {
return this.target;
};
handleOverlayEnter = (state) => {
this.setState({ placement: state.placement });
this.setState({ target: c });
};
render() {
const { intl, onPickEmoji, onSkinTone, skinTone, frequentlyUsedEmojis, disabled } = this.props;
const title = intl.formatMessage(messages.emoji);
const { active, loading, placement } = this.state;
const { active, loading, target } = this.state;
return (
<div className='emoji-picker-dropdown' onKeyDown={this.handleKeyDown} ref={this.setTargetRef}>
<div className='emoji-picker-dropdown' ref={this.setTargetRef}>
<IconButton
title={title}
aria-expanded={active}
@@ -380,23 +352,25 @@ class EmojiPickerDropdown extends PureComponent {
inverted
/>
<Overlay show={active} placement={placement} flip target={this.findTarget} popperConfig={{ strategy: 'fixed', onFirstUpdate: this.handleOverlayEnter }}>
<Popover
isOpen={active}
reference={target}
onClose={this.onHideDropdown}
>
{({ props, placement }) => (
<div {...props} style={{ ...props.style }}>
<div className={`dropdown-animation ${placement}`}>
<EmojiPickerMenu
loading={loading}
onClose={this.onHideDropdown}
onPick={onPickEmoji}
onSkinTone={onSkinTone}
skinTone={skinTone}
frequentlyUsedEmojis={frequentlyUsedEmojis}
pickerButtonRef={this.target}
/>
</div>
<div {...props} className={`dropdown-animation ${placement}`}>
<EmojiPickerMenu
loading={loading}
onClose={this.onHideDropdown}
onPick={onPickEmoji}
onSkinTone={onSkinTone}
skinTone={skinTone}
frequentlyUsedEmojis={frequentlyUsedEmojis}
pickerButtonRef={this.target}
/>
</div>
)}
</Overlay>
</Popover>
</div>
);
}
@@ -8,9 +8,8 @@ import { createSelector } from '@reduxjs/toolkit';
import { Map as ImmutableMap } from 'immutable';
import fuzzysort from 'fuzzysort';
import Overlay from 'react-overlays/Overlay';
import type { State, Placement } from 'react-overlays/usePopper';
import { Popover } from '@/flavours/glitch/components/popover';
import CancelIcon from '@/material-icons/400-24px/cancel-fill.svg?react';
import SearchIcon from '@/material-icons/400-24px/search.svg?react';
import TranslateIcon from '@/material-icons/400-24px/translate.svg?react';
@@ -203,34 +202,13 @@ const LanguageDropdownMenu: React.FC<{
const isSearching = searchValue !== '';
useEffect(() => {
const handleDocumentClick = (e: MouseEvent) => {
if (
nodeRef.current &&
e.target instanceof HTMLElement &&
!nodeRef.current.contains(e.target)
) {
onClose();
e.stopPropagation();
}
};
document.addEventListener('click', handleDocumentClick, { capture: true });
// Because of https://github.com/react-bootstrap/react-bootstrap/issues/2614 we need
// to wait for a frame before focusing
requestAnimationFrame(() => {
if (nodeRef.current) {
const element = nodeRef.current.querySelector<HTMLInputElement>(
'input[type="search"]',
);
if (element) element.focus();
}
});
return () => {
document.removeEventListener('click', handleDocumentClick);
};
}, [onClose]);
if (nodeRef.current) {
const element = nodeRef.current.querySelector<HTMLInputElement>(
'input[type="search"]',
);
if (element) element.focus();
}
}, []);
const results = useMemo(() => {
if (searchValue === '') {
@@ -326,10 +304,9 @@ const LanguageDropdownMenu: React.FC<{
export const LanguageDropdown: React.FC = () => {
const [open, setOpen] = useState(false);
const [placement, setPlacement] = useState<Placement | undefined>('bottom');
const [guess, setGuess] = useState('');
const activeElementRef = useRef<HTMLElement>(null);
const targetRef = useRef<HTMLButtonElement>(null);
const activeElementRef = useRef<HTMLElement | null>(null);
const [targetElement, setTargetElement] = useState<HTMLElement | null>(null);
const intl = useIntl();
@@ -369,13 +346,6 @@ export const LanguageDropdown: React.FC = () => {
[dispatch],
);
const handleOverlayEnter = useCallback(
(state: Partial<State>) => {
setPlacement(state.placement);
},
[setPlacement],
);
useEffect(() => {
if (isTextLongEnoughForGuess(text)) {
debouncedGuess(text, setGuess);
@@ -402,7 +372,7 @@ export const LanguageDropdown: React.FC = () => {
<>
<button
type='button'
ref={targetRef}
ref={setTargetElement}
title={intl.formatMessage(messages.changeLanguage)}
aria-expanded={open}
onClick={handleToggle}
@@ -416,13 +386,11 @@ export const LanguageDropdown: React.FC = () => {
<span className='dropdown-button__label'>{current[2] ?? value}</span>
</button>
<Overlay
show={open}
offset={[5, 5]}
placement={placement}
flip
target={targetRef as React.RefObject<HTMLButtonElement>}
popperConfig={{ strategy: 'fixed', onFirstUpdate: handleOverlayEnter }}
<Popover
isOpen={open}
onClose={handleClose}
offset={5}
reference={targetElement}
>
{({ props, placement }) => (
<div {...props}>
@@ -438,7 +406,7 @@ export const LanguageDropdown: React.FC = () => {
</div>
</div>
)}
</Overlay>
</Popover>
</>
);
};
@@ -4,10 +4,8 @@ import { defineMessages, useIntl } from 'react-intl';
import classNames from 'classnames';
import type { OverlayProps } from 'react-overlays/Overlay';
import Overlay from 'react-overlays/Overlay';
import type { StatusVisibility } from '@/flavours/glitch/api_types/statuses';
import { Popover } from '@/flavours/glitch/components/popover';
import AlternateEmailIcon from '@/material-icons/400-24px/alternate_email.svg?react';
import LockIcon from '@/material-icons/400-24px/lock.svg?react';
import PublicIcon from '@/material-icons/400-24px/public.svg?react';
@@ -58,7 +56,6 @@ interface PrivacyDropdownProps {
value: StatusVisibility;
onChange: (value: StatusVisibility) => void;
noDirect?: boolean;
container?: OverlayProps['container'];
disabled?: boolean;
}
@@ -66,11 +63,12 @@ const PrivacyDropdown: React.FC<PrivacyDropdownProps> = ({
value,
onChange,
noDirect,
container,
disabled,
}) => {
const intl = useIntl();
const overlayTargetRef = useRef<HTMLDivElement>(null);
const [popoverTarget, setPopoverTarget] = useState<HTMLDivElement | null>(
null,
);
const previousFocusTargetRef = useRef<HTMLElement>(null);
const [isOpen, setIsOpen] = useState(false);
@@ -142,7 +140,7 @@ const PrivacyDropdown: React.FC<PrivacyDropdownProps> = ({
options.find((item) => item.value === value) ?? options.at(0);
return (
<div ref={overlayTargetRef}>
<div ref={setPopoverTarget}>
<button
type='button'
title={intl.formatMessage(messages.change_privacy)}
@@ -166,14 +164,11 @@ const PrivacyDropdown: React.FC<PrivacyDropdownProps> = ({
)}
</button>
<Overlay
show={isOpen}
offset={[5, 5]}
placement='bottom'
flip
target={overlayTargetRef as React.RefObject<HTMLDivElement>}
container={container}
popperConfig={{ strategy: 'fixed' }}
<Popover
isOpen={isOpen}
offset={5}
reference={popoverTarget}
onClose={handleClose}
>
{({ props, placement }) => (
<div {...props}>
@@ -190,7 +185,7 @@ const PrivacyDropdown: React.FC<PrivacyDropdownProps> = ({
</div>
</div>
)}
</Overlay>
</Popover>
</div>
);
};
@@ -1,11 +1,9 @@
import type { PropsWithChildren } from 'react';
import { useCallback, useState, useRef, useId } from 'react';
import { useCallback, useState, useId } from 'react';
import classNames from 'classnames';
import type { Placement, State as PopperState } from '@popperjs/core';
import Overlay from 'react-overlays/Overlay';
import { Popover } from '@/flavours/glitch/components/popover';
import ArrowDropDownIcon from '@/material-icons/400-24px/arrow_drop_down.svg?react';
import type { SelectItem } from 'flavours/glitch/components/dropdown_selector';
import { DropdownSelector } from 'flavours/glitch/components/dropdown_selector';
@@ -18,7 +16,6 @@ interface DropdownProps {
onChange: (value: string) => void;
'aria-labelledby': string;
'aria-describedby'?: string;
placement?: Placement;
}
const Dropdown: React.FC<DropdownProps> = ({
@@ -28,22 +25,21 @@ const Dropdown: React.FC<DropdownProps> = ({
onChange,
'aria-labelledby': ariaLabelledBy,
'aria-describedby': ariaDescribedBy,
placement: initialPlacement = 'bottom-end',
}) => {
const containerRef = useRef<HTMLDivElement>(null);
const buttonRef = useRef<HTMLButtonElement>(null);
const [buttonElement, setButtonElement] = useState<HTMLButtonElement | null>(
null,
);
const [isOpen, setOpen] = useState<boolean>(false);
const [placement, setPlacement] = useState<Placement>(initialPlacement);
const uniqueId = useId();
const menuId = `${uniqueId}-menu`;
const buttonLabelId = `${uniqueId}-button`;
const handleClose = useCallback(() => {
if (isOpen && buttonRef.current) {
buttonRef.current.focus({ preventScroll: true });
if (isOpen && buttonElement) {
buttonElement.focus({ preventScroll: true });
}
setOpen(false);
}, [isOpen]);
}, [isOpen, buttonElement]);
const handleToggle = useCallback(() => {
if (isOpen) {
@@ -53,20 +49,13 @@ const Dropdown: React.FC<DropdownProps> = ({
}
}, [isOpen, handleClose]);
const handleOverlayEnter = useCallback(
(state: Partial<PopperState>) => {
if (state.placement) setPlacement(state.placement);
},
[setPlacement],
);
const valueOption = options.find((item) => item.value === value);
return (
<div ref={containerRef}>
<div>
<button
type='button'
ref={buttonRef}
ref={setButtonElement}
onClick={handleToggle}
disabled={disabled}
aria-expanded={isOpen}
@@ -81,30 +70,29 @@ const Dropdown: React.FC<DropdownProps> = ({
<Icon id='down' icon={ArrowDropDownIcon} />
</button>
<Overlay
show={isOpen}
offset={[5, 5]}
placement={placement}
flip
target={containerRef as React.RefObject<HTMLDivElement>}
popperConfig={{ strategy: 'fixed', onFirstUpdate: handleOverlayEnter }}
<Popover
isOpen={isOpen}
offset={5}
placement='bottom-end'
reference={buttonElement}
onClose={handleClose}
>
{({ props, placement }) => (
<div {...props} id={menuId}>
<div
className={`dropdown-animation privacy-dropdown__dropdown ${placement}`}
>
<DropdownSelector
items={options}
value={value}
onClose={handleClose}
onChange={onChange}
classNamePrefix='privacy-dropdown'
/>
</div>
<div
{...props}
id={menuId}
className={`dropdown-animation privacy-dropdown__dropdown ${placement}`}
>
<DropdownSelector
items={options}
value={value}
onClose={handleClose}
onChange={onChange}
classNamePrefix='privacy-dropdown'
/>
</div>
)}
</Overlay>
</Popover>
</div>
);
};
@@ -53,14 +53,6 @@ export const BoostModal: React.FC<{
onClose();
}, [onClose]);
const findContainer = useCallback(
() =>
document.getElementsByClassName(
'modal-root__container',
)[0] as HTMLDivElement,
[],
);
return (
<div className='modal-root__modal safety-action-modal'>
<div className='safety-action-modal__top'>
@@ -117,7 +109,6 @@ export const BoostModal: React.FC<{
<PrivacyDropdown
noDirect
value={privacy}
container={findContainer}
onChange={onPrivacyChange}
disabled={statusVisibility === 'private'}
/>
@@ -4,13 +4,8 @@ import { useIntl, defineMessages } from 'react-intl';
import { useLocation } from 'react-router-dom';
import type {
OffsetValue,
UsePopperOptions,
} from 'react-overlays/esm/usePopper';
import Overlay from 'react-overlays/Overlay';
import { DropdownMenu } from 'flavours/glitch/components/dropdown_menu';
import { Popover } from 'flavours/glitch/components/popover';
import { useIdentity } from 'flavours/glitch/identity_context';
import type { MenuItem } from 'flavours/glitch/models/dropdown_menu';
import { useAppSelector } from 'flavours/glitch/store';
@@ -27,9 +22,6 @@ const messages = defineMessages({
muteHashtag: { id: 'hashtag.mute', defaultMessage: 'Mute #{hashtag}' },
});
const offset = [5, 5] as OffsetValue;
const popperConfig = { strategy: 'fixed' } as UsePopperOptions;
const isHashtagLink = (
element: HTMLAnchorElement | null,
): element is HTMLAnchorElement => {
@@ -135,30 +127,19 @@ export const HashtagMenuController: React.FC = () => {
}
return (
<Overlay
show={open}
offset={offset}
placement='bottom'
flip
target={element}
popperConfig={popperConfig}
>
{({ props, arrowProps, placement }) => (
<div {...props}>
<div className={`dropdown-animation dropdown-menu ${placement}`}>
<div
className={`dropdown-menu__arrow ${placement}`}
{...arrowProps}
/>
<DropdownMenu
items={menu}
onClose={handleClose}
openedViaKeyboard={false}
/>
</div>
<Popover isOpen={open} offset={5} reference={element} onClose={handleClose}>
{({ props, placement }) => (
<div
{...props}
className={`dropdown-animation dropdown-menu ${placement}`}
>
<DropdownMenu
items={menu}
onClose={handleClose}
openedViaKeyboard={false}
/>
</div>
)}
</Overlay>
</Popover>
);
};
@@ -3,47 +3,45 @@
*/
import type { RefObject } from 'react';
import { useEffect } from 'react';
import { useEffect, useEffectEvent } from 'react';
type ElementRef = RefObject<HTMLElement | null>;
type PlainElement = Element | null;
type ElementOrRef = PlainElement | RefObject<PlainElement>;
export function useOnClickOutside(
excludedElementRef: ElementRef | ElementRef[] | null,
excludedElement: ElementOrRef | ElementOrRef[],
onClick: (e: MouseEvent) => void,
enabled = true,
) {
useEffect(() => {
// If the search popover is expanded, close it when tabbing or
// clicking outside of it or the search form, while allowing
// tabbing or clicking inside of the popover
if (enabled) {
function handleClickOutside(event: MouseEvent) {
const excludedRefs = Array.isArray(excludedElementRef)
? excludedElementRef
: [excludedElementRef];
const handleClickOutside = useEffectEvent((event: MouseEvent) => {
const excludedRefs = Array.isArray(excludedElement)
? excludedElement
: [excludedElement];
for (const ref of excludedRefs) {
const excludedElement = ref?.current;
for (const ref of excludedRefs) {
const excludedElement = ref instanceof Element ? ref : ref?.current;
// Bail out if the clicked element or the currently focused element
// is inside of excludedElement. We're also checking the focused element
// to prevent an issue in Chrome where initiating a drag inside of an
// input (to select the text inside of it) and ending that drag outside
// of the input fires a click event, breaking our excludedElement rule.
if (
excludedElement &&
(excludedElement === event.target ||
excludedElement === document.activeElement ||
excludedElement.contains(event.target as Node) ||
excludedElement.contains(document.activeElement))
) {
return;
}
}
onClick(event);
// Bail out if the clicked element or the currently focused element
// is inside of excludedElement. We're also checking the focused element
// to prevent an issue in Chrome where initiating a drag inside of an
// input (to select the text inside of it) and ending that drag outside
// of the input fires a click event, breaking our excludedElement rule.
if (
excludedElement &&
(excludedElement === event.target ||
excludedElement === document.activeElement ||
excludedElement.contains(event.target as Node) ||
excludedElement.contains(document.activeElement))
) {
return;
}
}
onClick(event);
});
useEffect(() => {
if (enabled) {
document.addEventListener('click', handleClickOutside);
return () => {
@@ -51,5 +49,5 @@ export function useOnClickOutside(
};
}
return () => null;
}, [enabled, excludedElementRef, onClick]);
}, [enabled, excludedElement, onClick]);
}
@@ -372,7 +372,7 @@
}
}
body > [data-popper-placement] {
body > [data-popover-placement] {
z-index: 9999;
}
@@ -6016,10 +6016,6 @@ a.status-card {
}
.visibility-dropdown {
&__overlay[data-popper-placement] {
z-index: 9999;
}
&.disabled {
opacity: 0.6;
cursor: default;
@@ -11062,7 +11058,7 @@ noscript {
}
}
.hover-card-controller[data-popper-reference-hidden='true'] {
.hover-card-controller[data-popover-reference-hidden='true'] {
opacity: 0;
pointer-events: none;
}