Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(build): Upgrade @popperjs/* to @floating-ui/react-* #67

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 8 additions & 3 deletions .storybook/preview.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,16 @@
import { MemoryRouter } from 'react-router-dom';
import Style from './style';

export const decorators = [
(Story) => (
<>
<MemoryRouter initialEntries={['/']}>
<Style />
<Story />
</>
<div className="flex h-screen items-center justify-center">
<div>
<Story />
</div>
</div>
</MemoryRouter>
),
];

Expand Down
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,8 @@
"prepare": "husky install"
},
"dependencies": {
"@popperjs/core": "^2.11.5",
"@floating-ui/react-dom": "^0.6.3",
"@floating-ui/react-dom-interactions": "^0.4.0",
"classnames": "^2.3.1",
"react-icons": "^4.3.1",
"react-indiana-drag-scroll": "^2.1.0"
Expand Down
2 changes: 1 addition & 1 deletion src/components/Tooltip/Tooltip.stories.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,6 @@ export const DefaultTooltip = Template.bind({});
DefaultTooltip.storyName = 'Default';
DefaultTooltip.args = {
content: 'Tooltip content',
placement: 'top',
placement: 'bottom',
children: <Button>Default tooltip</Button>,
};
184 changes: 129 additions & 55 deletions src/components/Tooltip/index.tsx
Original file line number Diff line number Diff line change
@@ -1,86 +1,160 @@
import { createPopper, Instance, Placement } from '@popperjs/core';
import { FC, PropsWithChildren, ReactNode, useEffect, useRef, useState } from 'react';
import { FC, PropsWithChildren, ReactNode, RefObject, useEffect, useRef, useState } from 'react';
import classNames from 'classnames';
import { arrow, autoPlacement, Placement, shift } from '@floating-ui/core';
import {
autoUpdate,
flip,
Middleware,
offset,
useClick,
useFloating,
useFocus,
useHover,
useInteractions,
useRole,
} from '@floating-ui/react-dom-interactions';

export type TooltipProps = PropsWithChildren<{
className?: string;
content: ReactNode;
placement?: Placement;
placement?: 'auto' | Placement;
trigger?: 'hover' | 'click';
style?: 'dark' | 'light' | 'auto';
animation?: false | `duration-${number}`;
arrow?: boolean;
}>;

/**
* @see https://floating-ui.com/docs/react-dom-interactions
*/
export const Tooltip: FC<TooltipProps> = ({
animation = 'duration-300',
arrow = true,
children,
className,
content,
placement = 'top',
trigger = 'hover',
style = 'dark',
animation = 'duration-300',
arrow = true,
trigger = 'hover',
}) => {
const tooltipRef = useRef<HTMLDivElement>(null);
const wrapperRef = useRef<HTMLSpanElement>(null);
const popperInstance = useRef<Instance>();
const [visible, setVisible] = useState(false);
const arrowRef = useRef<HTMLDivElement>(null);
const [open, setOpen] = useState(false);

useEffect(() => {
if (wrapperRef.current && tooltipRef.current) {
popperInstance.current = createPopper(wrapperRef.current, tooltipRef.current, {
placement,
modifiers: [
{
name: 'offset',
options: {
offset: [0, 8],
},
},
{ name: 'eventListeners', enabled: true },
],
});
}
}, [placement]);
const floatingTooltip = useFloating<HTMLElement>({
middleware: floatingMiddleware({ arrowRef, placement }),
onOpenChange: setOpen,
open,
placement: floatingPlacement({ placement }),
});
const {
context,
floating,
middlewareData: { arrow: { x: arrowX, y: arrowY } = {} },
reference,
refs,
strategy,
update,
x,
y,
} = floatingTooltip;

const show = () => {
setVisible(true);
popperInstance.current?.update();
};
const { getFloatingProps, getReferenceProps } = useInteractions([
useClick(context, { enabled: trigger === 'click' }),
useFocus(context),
useHover(context, { enabled: trigger === 'hover' }),
useRole(context, { role: 'tooltip' }),
]);

const hide = () => setTimeout(() => setVisible(false), 100);
useEffect(() => {
if (refs.reference.current && refs.floating.current && open) {
return autoUpdate(refs.reference.current, refs.floating.current, update);
}
}, [open, refs.floating, refs.reference, update]);

return (
<>
<div className="w-fit" {...getReferenceProps({ ref: reference })}>
{children}
</div>
<div
className={classNames(
'tooltip absolute z-10 inline-block rounded-lg py-2 px-3 text-sm font-medium shadow-sm',
animation !== false && `transition-opacity ${animation}`,
{
'invisible opacity-0': !visible,
'bg-gray-900 text-white dark:bg-gray-700': style === 'dark',
'border border-gray-200 bg-white text-gray-900': style === 'light',
'border border-gray-200 bg-white text-gray-900 dark:border-none dark:bg-gray-700 dark:text-white':
style === 'auto',
{...getFloatingProps({
className: classNames(
'absolute inline-block rounded-lg py-2 px-3 text-sm font-medium shadow-sm',
animation !== false && `transition-opacity ${animation}`,
{
'invisible opacity-0': !open,
'bg-gray-900 text-white dark:bg-gray-700': style === 'dark',
'border border-gray-200 bg-white text-gray-900': style === 'light',
'border border-gray-200 bg-white text-gray-900 dark:border-none dark:bg-gray-700 dark:text-white':
style === 'auto',
},
className,
),
ref: floating,
style: {
position: strategy,
top: y ?? '',
left: x ?? '',
},
className,
)}
ref={tooltipRef}
role="tooltip"
})}
>
{content}
{arrow && <div className="tooltip-arrow" data-popper-arrow />}
<div className="relative z-20">{content}</div>
{arrow && (
<div
className={classNames({
'absolute z-10 h-5 w-5 rotate-45 bg-gray-900 dark:bg-gray-700': style === 'dark',
'absolute h-5 w-5 rotate-45 bg-white': style === 'light',
'absolute h-5 w-5 rotate-45 bg-white dark:bg-gray-700': style === 'auto',
})}
ref={arrowRef}
style={{
top: arrowY ?? '',
left: arrowX ?? '',
right: '',
bottom: '',
[floatingArrowPlacement({ placement: floatingTooltip.placement })]: '-4px',
}}
>
&nbsp;
</div>
)}
</div>
<span
className="w-fit"
ref={wrapperRef}
onFocus={show}
onBlur={hide}
{...(trigger === 'hover' ? { onMouseEnter: show, onMouseLeave: hide } : { onClick: show })}
>
{children}
</span>
</>
);
};

/**
* @see https://floating-ui.com/docs/middleware
*/
function floatingMiddleware({
arrowRef,
placement,
}: {
arrowRef: RefObject<HTMLDivElement>;
placement: 'auto' | Placement;
}): Middleware[] {
const middleware = [];

middleware.push(offset(4));
middleware.push(placement === 'auto' ? autoPlacement() : flip());
middleware.push(shift({ padding: 8 }));

if (arrowRef.current) {
middleware.push(arrow({ element: arrowRef.current }));
}

return middleware;
}

function floatingPlacement({ placement }: { placement: 'auto' | Placement }): Placement | undefined {
return placement === 'auto' ? undefined : placement;
}

function floatingArrowPlacement({ placement }: { placement: Placement }): Placement {
return {
top: 'bottom',
right: 'left',
bottom: 'top',
left: 'right',
}[placement.split('-')[0]] as Placement;
}
42 changes: 39 additions & 3 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -1539,6 +1539,35 @@
minimatch "^3.0.4"
strip-json-comments "^3.1.1"

"@floating-ui/core@^0.6.2":
version "0.6.2"
resolved "https://registry.yarnpkg.com/@floating-ui/core/-/core-0.6.2.tgz#f2813f0e5f3d5ed7af5029e1a082203dadf02b7d"
integrity sha512-jktYRmZwmau63adUG3GKOAVCofBXkk55S/zQ94XOorAHhwqFIOFAy1rSp2N0Wp6/tGbe9V3u/ExlGZypyY17rg==

"@floating-ui/dom@^0.4.5":
version "0.4.5"
resolved "https://registry.yarnpkg.com/@floating-ui/dom/-/dom-0.4.5.tgz#2e88d16646119cc67d44683f75ee99840475bbfa"
integrity sha512-b+prvQgJt8pieaKYMSJBXHxX/DYwdLsAWxKYqnO5dO2V4oo/TYBZJAUQCVNjTWWsrs6o4VDrNcP9+E70HAhJdw==
dependencies:
"@floating-ui/core" "^0.6.2"

"@floating-ui/react-dom-interactions@^0.4.0":
version "0.4.0"
resolved "https://registry.yarnpkg.com/@floating-ui/react-dom-interactions/-/react-dom-interactions-0.4.0.tgz#b4d951aaa3b0a66cd0b2787a7bf9d5d7b2f12021"
integrity sha512-pcXxg2QVrQmlo54v39fIfPNda3bkFibuQVji0b4I9PLXOTV+KI5phc8ANnKLdfttfsYap/0bAknS9dQW97KShw==
dependencies:
"@floating-ui/react-dom" "^0.6.3"
aria-hidden "^1.1.3"
use-isomorphic-layout-effect "^1.1.1"

"@floating-ui/react-dom@^0.6.3":
version "0.6.3"
resolved "https://registry.yarnpkg.com/@floating-ui/react-dom/-/react-dom-0.6.3.tgz#7b64cfd4fd12e4a0515dbf1b2be16e48c9a06c5a"
integrity sha512-hC+pS5D6AgS2wWjbmSQ6UR6Kpy+drvWGJIri6e1EDGADTPsCaa4KzCgmCczHrQeInx9tqs81EyDmbKJYY2swKg==
dependencies:
"@floating-ui/dom" "^0.4.5"
use-isomorphic-layout-effect "^1.1.1"

"@gar/promisify@^1.0.1":
version "1.1.3"
resolved "https://registry.yarnpkg.com/@gar/promisify/-/promisify-1.1.3.tgz#555193ab2e3bb3b6adc3d551c9c030d9e860daf6"
Expand Down Expand Up @@ -1916,7 +1945,7 @@
schema-utils "^3.0.0"
source-map "^0.7.3"

"@popperjs/core@^2.11.5", "@popperjs/core@^2.5.4", "@popperjs/core@^2.6.0", "@popperjs/core@^2.9.3":
"@popperjs/core@^2.5.4", "@popperjs/core@^2.6.0", "@popperjs/core@^2.9.3":
version "2.11.5"
resolved "https://registry.yarnpkg.com/@popperjs/core/-/core-2.11.5.tgz#db5a11bf66bdab39569719555b0f76e138d7bd64"
integrity sha512-9X2obfABZuDVLCgPK9aX0a/x4jaOEweTTWE2+9sr0Qqqevj2Uv5XorvusThmc9XGYpS9yI+fhh8RTafBtGposw==
Expand Down Expand Up @@ -4373,6 +4402,13 @@ argparse@^2.0.1:
resolved "https://registry.yarnpkg.com/argparse/-/argparse-2.0.1.tgz#246f50f3ca78a3240f6c997e8a9bd1eac49e4b38"
integrity sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==

aria-hidden@^1.1.3:
version "1.1.3"
resolved "https://registry.yarnpkg.com/aria-hidden/-/aria-hidden-1.1.3.tgz#bb48de18dc84787a3c6eee113709c473c64ec254"
integrity sha512-RhVWFtKH5BiGMycI72q2RAFMLQi8JP9bLuQXgR5a8Znp7P5KOIADSJeyfI8PCVxLEp067B2HbP5JIiI/PXIZeA==
dependencies:
tslib "^1.0.0"

aria-query@^4.2.2:
version "4.2.2"
resolved "https://registry.yarnpkg.com/aria-query/-/aria-query-4.2.2.tgz#0d2ca6c9aceb56b8977e9fed6aed7e15bbd2f83b"
Expand Down Expand Up @@ -14580,7 +14616,7 @@ tsconfig-paths@^3.12.0:
minimist "^1.2.0"
strip-bom "^3.0.0"

tslib@^1.8.1:
tslib@^1.0.0, tslib@^1.8.1:
version "1.14.1"
resolved "https://registry.yarnpkg.com/tslib/-/tslib-1.14.1.tgz#cf2d38bdc34a134bcaf1091c41f6619e2f672d00"
integrity sha512-Xni35NKzjgMrwevysHTCArtLDpPvye8zV/0E4EyYn43P7/7qvQwPh9BGkHewbMulVntbigmcT7rdX3BNo9wRJg==
Expand Down Expand Up @@ -14895,7 +14931,7 @@ use-composed-ref@^1.0.0:
resolved "https://registry.yarnpkg.com/use-composed-ref/-/use-composed-ref-1.2.1.tgz#9bdcb5ccd894289105da2325e1210079f56bf849"
integrity sha512-6+X1FLlIcjvFMAeAD/hcxDT8tmyrWnbSPMU0EnxQuDLIxokuFzWliXBiYZuGIx+mrAMLBw0WFfCkaPw8ebzAhw==

use-isomorphic-layout-effect@^1.0.0:
use-isomorphic-layout-effect@^1.0.0, use-isomorphic-layout-effect@^1.1.1:
version "1.1.2"
resolved "https://registry.yarnpkg.com/use-isomorphic-layout-effect/-/use-isomorphic-layout-effect-1.1.2.tgz#497cefb13d863d687b08477d9e5a164ad8c1a6fb"
integrity sha512-49L8yCO3iGT/ZF9QttjwLF/ZD9Iwto5LnH5LmEdk/6cFmXddqi2ulF0edxTwjj+7mqvpVVGQWvbXZdn32wRSHA==
Expand Down