anki/ts/graphs/tooltip.ts

47 lines
1.3 KiB
TypeScript
Raw Normal View History

// Copyright: Ankitects Pty Ltd and contributors
// License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
import throttle from "lodash.throttle";
2021-02-22 14:10:35 +01:00
function getOrCreateTooltipDiv(): HTMLDivElement {
const existingTooltip = document.getElementById("graphTooltip") as HTMLDivElement;
if (existingTooltip) {
return existingTooltip;
}
const tooltipDiv: HTMLDivElement = document.createElement("div");
tooltipDiv.id = "graphTooltip";
tooltipDiv.className = "graph-tooltip";
document.body.appendChild(tooltipDiv);
2021-02-22 14:44:31 +01:00
return tooltipDiv;
2021-02-22 14:10:35 +01:00
}
function showTooltipInner(msg: string, x: number, y: number): void {
2021-02-22 14:10:35 +01:00
const tooltipDiv = getOrCreateTooltipDiv();
tooltipDiv.innerHTML = msg;
2020-06-29 07:05:08 +02:00
// move tooltip away from edge as user approaches right side
const shiftLeftAmount = Math.round(
tooltipDiv.clientWidth * 1.2 * (x / document.body.clientWidth)
);
2021-01-30 02:35:33 +01:00
const adjustedX = x + 40 - shiftLeftAmount;
const adjustedY = y + 40;
tooltipDiv.style.left = `${adjustedX}px`;
tooltipDiv.style.top = `${adjustedY}px`;
tooltipDiv.style.opacity = "1";
}
export const showTooltip = throttle(showTooltipInner, 16);
export function hideTooltip(): void {
2021-02-22 14:10:35 +01:00
const tooltipDiv = getOrCreateTooltipDiv();
showTooltip.cancel();
2021-01-30 02:35:33 +01:00
tooltipDiv.style.opacity = "0";
}