Improve tooltip performance
@@ -8,49 +8,27 @@ const TOOLTIP_BASE = {
appendTo: document.body,
};
-let tooltipInstances = [];
-const globalPlugin = {
- fn(instance) {
- return {
- onCreate() {
- tooltipInstances = tooltipInstances.concat(instance);
- },
- onDestroy() {
- tooltipInstances = tooltipInstances.filter((i) => i !== instance);
- },
- };
- },
-};
-
-tippy.setDefaultProps({
- plugins: [globalPlugin],
-});
-
/**
- * Registers tooltips for the page
- * If called again, destroys existing tooltips and registers them again (useful for progressive rendering)
- * @param {HTMLElement} container - Registers the tooltips for the given container
+ * Registers tooltips for the given element
+ * If called again, destroys any existing tooltip for the element and
+ * registers them again (useful for progressive rendering)
+ * @param {HTMLElement} element - Registers the tooltips for the given element
*/
-function registerTooltips(container) {
- if (!container) {
- container = document;
+function registerTooltip(element) {
+ if (element._tippy) {
+ element._tippy.destroy();
}
- tooltipInstances.forEach((instance) => {
- if (instance.props.container === container) {
- instance.destroy();
- }
- });
-
+ if (
+ element.hasAttribute("tooltip") &&
+ !element.hasAttribute("data-html-tooltip")
+ ) {
tippy(
- container.querySelectorAll(
- '[tooltip]:not([tooltip=""]):not([data-html-tooltip])'
- ),
+ element,
Object.assign(
{
content: (element) =>
element.getAttribute("tooltip").replace(/<br[ /]?\/?>|\\n/g, "\n"),
- container: container,
onCreate(instance) {
instance.reference.setAttribute("title", instance.props.content);
},
@@ -64,14 +42,15 @@ function registerTooltips(container) {
TOOLTIP_BASE
)
);
+ }
+ if (element.hasAttribute("data-html-tooltip")) {
tippy(
- container.querySelectorAll("[data-html-tooltip]"),
+ element,
Object.assign(
{
content: (element) => element.getAttribute("data-html-tooltip"),
allowHTML: true,
- container: container,
onCreate(instance) {
instance.props.interactive =
instance.reference.getAttribute("data-tooltip-interactive") ===
@@ -82,6 +61,7 @@ function registerTooltips(container) {
)
);
}
+}
/**
* Displays a tooltip for three seconds on the provided element after interaction
@@ -113,8 +93,8 @@ function init() {
"[tooltip], [data-html-tooltip]",
"-tooltip-",
1000,
- function () {
- registerTooltips(null);
+ (element) => {
+ registerTooltip(element);
}
);
