chore: extract tooltip into package

- chore: add sanity check unit test
- chore: added tailwind.config.js to fix build
- chore: .swcrc added for tests to pass
- chore(deps): sass is not a dependency
- fix: manually import the tooltip css to fix tooltips not showing up
- chore: Run lint:fix against code
- chore: Fix use of mock in @k8slens/core

Signed-off-by: Gabriel <gaccettola@mirantis.com>
Signed-off-by: Sebastian Malton <sebastian@malton.name>
This commit is contained in:
Gabriel authored and Sebastian Malton committed 2023-04-19 09:21:04 -04:00
1 parent c7df928acc
commit 01059d8cb1
42 files changed
+268 -101

No files matched your search

@@ -0,0 +1,51 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`<Tooltip /> does not render to DOM if not visibile 1`] = `
<body>
<div>
<div
id="my-target"
>
Target Text
</div>
</div>
</body>
`;
exports[`<Tooltip /> renders to DOM when forced to by visibile prop 1`] = `
<body>
<div>
<div
class="Tooltip right visible"
role="tooltip"
style="left: 10px; top: 0px;"
>
I am a tooltip
</div>
<div
id="my-target"
>
Target Text
</div>
</div>
</body>
`;
exports[`<Tooltip /> renders to DOM when hovering over target 1`] = `
<body>
<div>
<div
class="Tooltip right visible"
role="tooltip"
style="left: 10px; top: 0px;"
>
I am a tooltip
</div>
<div
id="my-target"
>
Target Text
</div>
</div>
</body>
`;
@@ -0,0 +1,7 @@
/**
* Copyright (c) OpenLens Authors. All rights reserved.
* Licensed under MIT License. See LICENSE in root directory for more information.
*/
export * from "./tooltip";
export * from "./withTooltip";
@@ -0,0 +1,92 @@
/**
* Copyright (c) OpenLens Authors. All rights reserved.
* Licensed under MIT License. See LICENSE in root directory for more information.
*/
.Tooltip {
position: fixed;
margin: 0 !important;
background: var(--mainBackground);
font-size: small;
font-weight: normal;
border-radius: 3px;
color: var(--textColorAccent);
white-space: normal;
padding: .5em;
text-align: center;
pointer-events: none;
transition: opacity 150ms 150ms ease-in-out;
z-index: 100000;
box-shadow: 0 8px 16px rgba(0,0,0,0.24);
left: 0;
top: 0;
opacity: 0;
visibility: hidden;
&.visible {
opacity: 1;
visibility: visible;
}
&:empty {
display: none;
}
&.formatter {
&.nowrap {
&, * {
white-space: nowrap;
}
}
&.narrow {
max-width: 300px;
text-overflow: ellipsis;
word-wrap: break-word;
text-align: left;
}
&.small {
font-size: 12px;
}
&.warning {
color: var(--colorError);
}
&.tableView {
display: grid;
gap: var(--padding);
grid-template-columns: max-content 1fr;
grid-template-rows: repeat(2, 1fr);
> .flex {
display: contents;
}
> * {
white-space: pre-wrap;
word-break: break-word;
}
.title {
grid-column: 1 / 3;
color: var(--textColorAccent);
text-align: center;
font-weight: bold;
}
.name {
text-align: right;
color: var(--textColorAccent);
}
.value {
text-align: left;
color: var(--textColorSecondary);
}
}
}
}
@@ -0,0 +1,72 @@
/**
* Copyright (c) OpenLens Authors. All rights reserved.
* Licensed under MIT License. See LICENSE in root directory for more information.
*/
import { render } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import assert from "assert";
import React from "react";
import { Tooltip } from "./tooltip";
describe("<Tooltip />", () => {
let requestAnimationFrameSpy: jest.SpyInstance<number, [callback: FrameRequestCallback]>;
beforeEach(() => {
requestAnimationFrameSpy = jest.spyOn(window, "requestAnimationFrame");
requestAnimationFrameSpy.mockImplementation((cb) => {
cb(0);
return 0;
});
});
afterEach(() => {
requestAnimationFrameSpy.mockRestore();
});
it("does not render to DOM if not visible", () => {
const result = render(
<>
<Tooltip targetId="my-target" usePortal={false}>
I am a tooltip
</Tooltip>
<div id="my-target">Target Text</div>
</>,
);
expect(result.baseElement).toMatchSnapshot();
});
it("renders to DOM when hovering over target", () => {
const result = render(
<>
<Tooltip targetId="my-target" data-testid="tooltip" usePortal={false}>
I am a tooltip
</Tooltip>
<div id="my-target">Target Text</div>
</>,
);
const target = result.baseElement.querySelector("#my-target");
assert(target);
userEvent.hover(target);
expect(result.baseElement).toMatchSnapshot();
});
it("renders to DOM when forced to by visible prop", () => {
const result = render(
<>
<Tooltip targetId="my-target" data-testid="tooltip" visible={true} usePortal={false}>
I am a tooltip
</Tooltip>
<div id="my-target">Target Text</div>
</>,
);
expect(result.baseElement).toMatchSnapshot();
});
});
@@ -0,0 +1,242 @@
/**
* Copyright (c) OpenLens Authors. All rights reserved.
* Licensed under MIT License. See LICENSE in root directory for more information.
*/
import "./tooltip.scss";
import React from "react";
import { createPortal } from "react-dom";
import { observer } from "mobx-react";
import type { IClassName } from "@k8slens/utilities";
import { cssNames } from "@k8slens/utilities";
import { observable, makeObservable, action } from "mobx";
import autoBindReact from "auto-bind/react";
export enum TooltipPosition {
TOP = "top",
BOTTOM = "bottom",
LEFT = "left",
RIGHT = "right",
TOP_LEFT = "top_left",
TOP_RIGHT = "top_right",
BOTTOM_LEFT = "bottom_left",
BOTTOM_RIGHT = "bottom_right",
}
export interface TooltipProps {
targetId: string; // html-id of target element to bind for
tooltipOnParentHover?: boolean; // detect hover on parent of target
visible?: boolean; // initial visibility
offset?: number; // offset from target element in pixels (all sides)
usePortal?: boolean; // renders element outside of parent (in body), disable for "easy-styling", default: true
preferredPositions?: TooltipPosition | TooltipPosition[];
className?: IClassName;
formatters?: TooltipContentFormatters;
style?: React.CSSProperties;
children?: React.ReactNode;
}
export interface TooltipContentFormatters {
narrow?: boolean; // max-width
warning?: boolean; // color
small?: boolean; // font-size
nowrap?: boolean; // white-space
tableView?: boolean;
}
const defaultProps: Partial<TooltipProps> = {
usePortal: true,
offset: 10,
};
@observer
export class Tooltip extends React.Component<TooltipProps> {
static defaultProps = defaultProps as object;
@observable.ref elem: HTMLDivElement | null = null;
@observable activePosition?: TooltipPosition;
@observable isVisible = false;
@observable isContentVisible = false; // animation manager
constructor(props: TooltipProps) {
super(props);
makeObservable(this);
autoBindReact(this);
}
get targetElem(): HTMLElement | null {
return document.getElementById(this.props.targetId);
}
get hoverTarget(): HTMLElement | null {
if (this.props.tooltipOnParentHover) {
return this.targetElem?.parentElement ?? null;
}
return this.targetElem;
}
componentDidMount() {
this.hoverTarget?.addEventListener("mouseenter", this.onEnterTarget);
this.hoverTarget?.addEventListener("mouseleave", this.onLeaveTarget);
this.refreshPosition();
}
componentDidUpdate() {
this.refreshPosition();
}
componentWillUnmount() {
this.hoverTarget?.removeEventListener("mouseenter", this.onEnterTarget);
this.hoverTarget?.removeEventListener("mouseleave", this.onLeaveTarget);
}
@action
protected onEnterTarget() {
this.isVisible = true;
requestAnimationFrame(action(() => (this.isContentVisible = true)));
}
@action
protected onLeaveTarget() {
this.isVisible = false;
this.isContentVisible = false;
}
refreshPosition() {
const { preferredPositions } = this.props;
const { elem, targetElem } = this;
if (!elem || !targetElem) {
return;
}
const positions = new Set<TooltipPosition>([
...[preferredPositions ?? []].flat(),
TooltipPosition.RIGHT,
TooltipPosition.BOTTOM,
TooltipPosition.TOP,
TooltipPosition.LEFT,
TooltipPosition.TOP_RIGHT,
TooltipPosition.TOP_LEFT,
TooltipPosition.BOTTOM_RIGHT,
TooltipPosition.BOTTOM_LEFT,
]);
// reset position first and get all possible client-rect area for tooltip element
this.setPosition(elem, { left: 0, top: 0 });
const selfBounds = elem.getBoundingClientRect();
const targetBounds = targetElem.getBoundingClientRect();
const { innerWidth: viewportWidth, innerHeight: viewportHeight } = window;
// find proper position
for (const pos of positions) {
const { left, top, right, bottom } = this.getPosition(pos, selfBounds, targetBounds);
const fitsToWindow =
left >= 0 && top >= 0 && right <= viewportWidth && bottom <= viewportHeight;
if (fitsToWindow) {
this.activePosition = pos;
this.setPosition(elem, { top, left });
return;
}
}
// apply fallback position if nothing helped from above
const fallbackPosition = Array.from(positions)[0];
const { left, top } = this.getPosition(fallbackPosition, selfBounds, targetBounds);
this.activePosition = fallbackPosition;
this.setPosition(elem, { left, top });
}
protected setPosition(elem: HTMLDivElement, pos: { left: number; top: number }) {
elem.style.left = `${pos.left}px`;
elem.style.top = `${pos.top}px`;
}
protected getPosition(position: TooltipPosition, tooltipBounds: DOMRect, targetBounds: DOMRect) {
let left: number;
let top: number;
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
const offset = this.props.offset!;
const horizontalCenter = targetBounds.left + (targetBounds.width - tooltipBounds.width) / 2;
const verticalCenter = targetBounds.top + (targetBounds.height - tooltipBounds.height) / 2;
const topCenter = targetBounds.top - tooltipBounds.height - offset;
const bottomCenter = targetBounds.bottom + offset;
switch (position) {
case "top":
left = horizontalCenter;
top = topCenter;
break;
case "bottom":
left = horizontalCenter;
top = bottomCenter;
break;
case "left":
top = verticalCenter;
left = targetBounds.left - tooltipBounds.width - offset;
break;
case "right":
top = verticalCenter;
left = targetBounds.right + offset;
break;
case "top_left":
left = targetBounds.left;
top = topCenter;
break;
case "top_right":
left = targetBounds.right - tooltipBounds.width;
top = topCenter;
break;
case "bottom_left":
top = bottomCenter;
left = targetBounds.left;
break;
case "bottom_right":
top = bottomCenter;
left = targetBounds.right - tooltipBounds.width;
break;
default:
throw new TypeError("Invalid props.postition value");
}
return {
left,
top,
right: left + tooltipBounds.width,
bottom: top + tooltipBounds.height,
};
}
render() {
const { style, formatters, usePortal, children, visible = this.isVisible } = this.props;
if (!visible) {
return null;
}
const className = cssNames("Tooltip", this.props.className, formatters, this.activePosition, {
visible: this.isContentVisible || this.props.visible,
formatter: !!formatters,
});
const tooltip = (
<div className={className} style={style} ref={(elem) => (this.elem = elem)} role="tooltip">
{children}
</div>
);
if (usePortal) {
return createPortal(tooltip, document.body);
}
return tooltip;
}
}
@@ -0,0 +1,72 @@
/**
* Copyright (c) OpenLens Authors. All rights reserved.
* Licensed under MIT License. See LICENSE in root directory for more information.
*/
// Tooltip decorator for simple composition with other components
import type { ReactNode } from "react";
import React, { useState } from "react";
import type { TooltipProps } from "./tooltip";
import { Tooltip } from "./tooltip";
import { isReactNode } from "@k8slens/utilities";
import uniqueId from "lodash/uniqueId";
import type { SingleOrMany } from "@k8slens/utilities";
export interface TooltipDecoratorProps {
tooltip?: ReactNode | Omit<TooltipProps, "targetId">;
/**
* forces tooltip to detect the target's parent for mouse events. This is
* useful for displaying tooltips even when the target is "disabled"
*/
tooltipOverrideDisabled?: boolean;
id?: string;
children?: SingleOrMany<React.ReactNode>;
}
export function withTooltip<TargetProps>(
Target: TargetProps extends Pick<TooltipDecoratorProps, "id" | "children">
? React.FunctionComponent<TargetProps>
: never,
): React.FunctionComponent<TargetProps & TooltipDecoratorProps> {
const DecoratedComponent = (props: TargetProps & TooltipDecoratorProps) => {
// TODO: Remove side-effect to allow deterministic unit testing
const [defaultTooltipId] = useState(uniqueId("tooltip_target_"));
let { id: targetId, children: targetChildren } = props;
const {
tooltip,
tooltipOverrideDisabled,
id: _unusedId,
children: _unusedTargetChildren,
...targetProps
} = props;
if (tooltip) {
const tooltipProps: TooltipProps = {
targetId: targetId || defaultTooltipId,
tooltipOnParentHover: tooltipOverrideDisabled,
formatters: { narrow: true },
...(isReactNode(tooltip) ? { children: tooltip } : tooltip),
};
targetId = tooltipProps.targetId;
targetChildren = (
<>
<div>{targetChildren}</div>
<Tooltip {...tooltipProps} />
</>
);
}
return (
<Target id={targetId} {...(targetProps as any)}>
{targetChildren}
</Target>
);
};
DecoratedComponent.displayName = `withTooltip(${Target.displayName || Target.name})`;
return DecoratedComponent;
}