[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>
);