Skip to content

Install floating-ui, refactor RewardsTooltip #1822

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

Merged
merged 7 commits into from
Mar 10, 2025
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
2 changes: 1 addition & 1 deletion apps/hyperdrive-trading/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,6 @@
"@delvtech/hyperdrive-js": "^0.0.2",
"@headlessui/react": "^2.1.5",
"@heroicons/react": "^2.0.16",
"@radix-ui/react-tooltip": "^1.1.8",
"@rainbow-me/rainbowkit": "^2.2.3",
"@rollbar/react": "^0.11.1",
"@tanstack/query-core": "^4.36.1",
Expand Down Expand Up @@ -76,6 +75,7 @@
"react-hot-toast": "^2.4.0",
"react-loading-skeleton": "^3.3.1",
"react-use": "^17.4.2",
"@floating-ui/react": "0.27.5",
"rollbar": "^2.26.4",
"semver": "^7.6.3",
"viem": "^2.22.19",
Expand Down
261 changes: 261 additions & 0 deletions apps/hyperdrive-trading/src/ui/base/components/Popover/Popover.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,261 @@
/*
* This component file is lifted from https://floating-ui.com/docs/popover#reusable-popover-component
*/

/* eslint-disable react/prop-types */
/* eslint-disable @typescript-eslint/explicit-module-boundary-types */
import {
autoUpdate,
flip,
FloatingFocusManager,
FloatingPortal,
offset,
Placement,
safePolygon,
shift,
useDismiss,
useFloating,
useHover,
useId,
useInteractions,
useMergeRefs,
useRole,
} from "@floating-ui/react";
import * as React from "react";

interface PopoverOptions {
initialOpen?: boolean;
placement?: Placement;
modal?: boolean;
open?: boolean;
onOpenChange?: (open: boolean) => void;
}

function usePopover({
initialOpen = false,
placement = "top",
modal,
open: controlledOpen,
onOpenChange: setControlledOpen,
}: PopoverOptions = {}) {
const [uncontrolledOpen, setUncontrolledOpen] = React.useState(initialOpen);
const [labelId, setLabelId] = React.useState<string | undefined>();
const [descriptionId, setDescriptionId] = React.useState<
string | undefined
>();

const open = controlledOpen ?? uncontrolledOpen;
const setOpen = setControlledOpen ?? setUncontrolledOpen;

const data = useFloating({
placement,
open,
onOpenChange: setOpen,
whileElementsMounted: autoUpdate,
middleware: [
offset(5),
flip({
crossAxis: placement.includes("-"),
fallbackAxisSideDirection: "end",
padding: 5,
}),
shift({ padding: 5 }),
],
});

const context = data.context;

const hover = useHover(context, {
// allows the popover to remain open while user's cursor is inside it
// https://floating-ui.com/docs/usehover#handleclose
handleClose: safePolygon(),
});
const dismiss = useDismiss(context);
const role = useRole(context);

const interactions = useInteractions([hover, dismiss, role]);

return React.useMemo(
() => ({
open,
setOpen,
...interactions,
...data,
modal,
labelId,
descriptionId,
setLabelId,
setDescriptionId,
}),
[open, setOpen, interactions, data, modal, labelId, descriptionId],
);
}

type ContextType =
| (ReturnType<typeof usePopover> & {
setLabelId: React.Dispatch<React.SetStateAction<string | undefined>>;
setDescriptionId: React.Dispatch<
React.SetStateAction<string | undefined>
>;
})
| null;

const PopoverContext = React.createContext<ContextType>(null);

function usePopoverContext() {
const context = React.useContext(PopoverContext);

if (context == null) {
throw new Error("Popover components must be wrapped in <Popover />");
}

return context;
}

export function Popover({
children,
modal = false,
...restOptions
}: {
children: React.ReactNode;
} & PopoverOptions) {
// This can accept any props as options, e.g. `placement`,
// or other positioning options.
const popover = usePopover({ modal, ...restOptions });
return (
<PopoverContext.Provider value={popover}>
{children}
</PopoverContext.Provider>
);
}

interface PopoverTriggerProps {
children: React.ReactNode;
asChild?: boolean;
}

export const PopoverTrigger = React.forwardRef<
HTMLElement,
React.HTMLProps<HTMLElement> & PopoverTriggerProps
>(function PopoverTrigger({ children, asChild = false, ...props }, propRef) {
const context = usePopoverContext();
const childrenRef = (children as any).ref;

Check warning on line 142 in apps/hyperdrive-trading/src/ui/base/components/Popover/Popover.tsx

View workflow job for this annotation

GitHub Actions / verify (lint)

Unexpected any. Specify a different type
const ref = useMergeRefs([context.refs.setReference, propRef, childrenRef]);

// `asChild` allows the user to pass any element as the anchor
if (asChild && React.isValidElement(children)) {
return React.cloneElement(
children,
context.getReferenceProps({
ref,
...props,
...children.props,
"data-state": context.open ? "open" : "closed",
}),
);
}

return (
<button
ref={ref}
type="button"
// The user can style the trigger based on the state
data-state={context.open ? "open" : "closed"}
{...context.getReferenceProps(props)}
>
{children}
</button>
);
});

export const PopoverContent = React.forwardRef<
HTMLDivElement,
React.HTMLProps<HTMLDivElement>
>(function PopoverContent({ style, ...props }, propRef) {
const { context: floatingContext, ...context } = usePopoverContext();
const ref = useMergeRefs([context.refs.setFloating, propRef]);

if (!floatingContext.open) {
return null;
}

return (
<FloatingPortal>
<FloatingFocusManager
initialFocus={
/* Don't set an initial focus element prevents focus styling from
* appearing inside the popover when opened */
-1
}
context={floatingContext}
modal={context.modal}
>
<div
ref={ref}
style={{ ...context.floatingStyles, ...style }}
aria-labelledby={context.labelId}
aria-describedby={context.descriptionId}
{...context.getFloatingProps(props)}
>
{props.children}
</div>
</FloatingFocusManager>
</FloatingPortal>
);
});

export const PopoverHeading = React.forwardRef<
HTMLHeadingElement,
React.HTMLProps<HTMLHeadingElement>
>(function PopoverHeading(props, ref) {
const { setLabelId } = usePopoverContext();
const id = useId();

// Only sets `aria-labelledby` on the Popover root element
// if this component is mounted inside it.
React.useLayoutEffect(() => {
setLabelId(id);
return () => setLabelId(undefined);
}, [id, setLabelId]);

return (
<h2 {...props} ref={ref} id={id}>
{props.children}
</h2>
);
});

export const PopoverDescription = React.forwardRef<
HTMLParagraphElement,
React.HTMLProps<HTMLParagraphElement>
>(function PopoverDescription(props, ref) {
const { setDescriptionId } = usePopoverContext();
const id = useId();

// Only sets `aria-describedby` on the Popover root element
// if this component is mounted inside it.
React.useLayoutEffect(() => {
setDescriptionId(id);
return () => setDescriptionId(undefined);
}, [id, setDescriptionId]);

return <p {...props} ref={ref} id={id} />;
});

export const PopoverClose = React.forwardRef<
HTMLButtonElement,
React.ButtonHTMLAttributes<HTMLButtonElement>
>(function PopoverClose(props, ref) {
const { setOpen } = usePopoverContext();
return (
<button
type="button"
ref={ref}
{...props}
onClick={(event) => {
props.onClick?.(event);
setOpen(false);
}}
/>
);
});
Original file line number Diff line number Diff line change
Expand Up @@ -525,7 +525,6 @@ function LpApyStat({ hyperdrive }: { hyperdrive: HyperdriveConfig }) {
) : rewards?.length ? (
<RewardsTooltip
position="addLiquidity"
showMiles
hyperdriveAddress={hyperdrive.address}
baseRate={lpApy?.lpApy}
netRate={lpApy?.netLpApy}
Expand Down
5 changes: 1 addition & 4 deletions apps/hyperdrive-trading/src/ui/main.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ import { RainbowKitProvider } from "@rainbow-me/rainbowkit";
import "@rainbow-me/rainbowkit/styles.css";
import "@usecapsule/react-sdk/styles.css";

import * as Tooltip from "@radix-ui/react-tooltip";
import {
ErrorBoundary as RollbarErrorBoundary,
Provider as RollbarProvider,
Expand Down Expand Up @@ -70,9 +69,7 @@ root.render(
>
<RollbarErrorBoundary>
<RegionInfoProvider>
<Tooltip.Provider>
<App />
</Tooltip.Provider>
<App />
</RegionInfoProvider>
</RollbarErrorBoundary>
</RollbarProvider>
Expand Down
26 changes: 12 additions & 14 deletions apps/hyperdrive-trading/src/ui/markets/PoolRow/PoolStat.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,11 @@
import * as Tooltip from "@radix-ui/react-tooltip";
import classNames from "classnames";
import { ReactElement, ReactNode } from "react";
import Skeleton from "react-loading-skeleton";
import {
Popover,
PopoverContent,
PopoverTrigger,
} from "src/ui/base/components/Popover/Popover";

export interface PoolStatProps {
label: string;
Expand Down Expand Up @@ -47,20 +51,14 @@ export function PoolStat({

if (overlay) {
return (
<Tooltip.Root>
<Tooltip.Trigger className="flex w-full items-center whitespace-nowrap">
<Popover>
<PopoverTrigger className="flex w-full items-center whitespace-nowrap">
{poolStat}
</Tooltip.Trigger>
<Tooltip.Portal>
<Tooltip.Content
className="z-20 h-fit w-72 rounded-[0.6rem] bg-base-200 px-3 py-2 shadow-2xl"
sideOffset={5}
collisionPadding={12}
>
{overlay}
</Tooltip.Content>
</Tooltip.Portal>
</Tooltip.Root>
</PopoverTrigger>
<PopoverContent className="z-20 h-fit w-72 rounded-[0.6rem] bg-base-200 px-3 py-2 shadow-2xl">
{overlay}
</PopoverContent>
</Popover>
);
}

Expand Down
Loading
Loading