chore: use long press for tooltip on touch device

This commit is contained in:
Matthew Russell 2024-02-12 12:49:55 -08:00
parent a0aa0065b6
commit 405d41a26c
No known key found for this signature in database

View File

@ -1,5 +1,5 @@
import type { ReactNode } from 'react'; import type { ReactNode, TouchEvent } from 'react';
import React from 'react'; import React, { useEffect, useRef, useState } from 'react';
import { import {
Provider, Provider,
Root, Root,
@ -12,10 +12,10 @@ import classNames from 'classnames';
const tooltipContentClasses = const tooltipContentClasses =
'max-w-sm bg-vega-light-100 dark:bg-vega-dark-100 border border-vega-light-200 dark:border-vega-dark-200 px-2 py-1 z-20 rounded text-xs text-black dark:text-white break-word'; 'max-w-sm bg-vega-light-100 dark:bg-vega-dark-100 border border-vega-light-200 dark:border-vega-dark-200 px-2 py-1 z-20 rounded text-xs text-black dark:text-white break-word';
export interface TooltipProps { export interface TooltipProps {
children: React.ReactElement; children: React.ReactElement;
description?: string | ReactNode; description?: string | ReactNode;
open?: boolean;
align?: 'start' | 'center' | 'end'; align?: 'start' | 'center' | 'end';
side?: 'top' | 'right' | 'bottom' | 'left'; side?: 'top' | 'right' | 'bottom' | 'left';
sideOffset?: number; sideOffset?: number;
@ -28,20 +28,50 @@ export const TOOLTIP_TRIGGER_CLASS_NAME = (underline?: boolean) =>
underline, underline,
}); });
const useLongPress = (callback: (e: TouchEvent<HTMLElement>) => void) => {
const timer = useRef<number>();
const onTouchStart = (e: TouchEvent<HTMLElement>) => {
e.preventDefault();
timer.current = setTimeout(callback, 1000);
};
useEffect(() => {
return () => {
if (timer.current) {
clearInterval(timer.current);
}
};
}, []);
return {
onTouchStart,
};
};
// Conditionally rendered tooltip if description content is provided. // Conditionally rendered tooltip if description content is provided.
export const Tooltip = ({ export const Tooltip = ({
children, children,
description, description,
open,
sideOffset, sideOffset,
align = 'start', align = 'start',
side = 'bottom', side = 'bottom',
underline, underline,
}: TooltipProps) => }: TooltipProps) => {
description ? ( const [open, setOpen] = useState(false);
const { onTouchStart } = useLongPress(() => {
setOpen(true);
});
return description ? (
<Provider delayDuration={200} skipDelayDuration={100}> <Provider delayDuration={200} skipDelayDuration={100}>
<Root open={open}> <Root open={open} onOpenChange={setOpen}>
<Trigger asChild className={TOOLTIP_TRIGGER_CLASS_NAME(underline)}> <Trigger
asChild
className={TOOLTIP_TRIGGER_CLASS_NAME(underline)}
onTouchStart={onTouchStart}
>
{children} {children}
</Trigger> </Trigger>
{description && ( {description && (
@ -67,6 +97,7 @@ export const Tooltip = ({
) : ( ) : (
children children
); );
};
export const TextChildrenTooltip = ({ export const TextChildrenTooltip = ({
children, children,