You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

tippy.js 6.9KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194
  1. import tippy, {followCursor} from 'tippy.js';
  2. import {isDocumentFragmentOrElementNode} from '../utils/dom.js';
  3. import {formatDatetime} from '../utils/time.js';
  4. const visibleInstances = new Set();
  5. export function createTippy(target, opts = {}) {
  6. // the callback functions should be destructured from opts,
  7. // because we should use our own wrapper functions to handle them, do not let the user override them
  8. const {onHide, onShow, onDestroy, role, theme, ...other} = opts;
  9. const instance = tippy(target, {
  10. appendTo: document.body,
  11. animation: false,
  12. allowHTML: false,
  13. hideOnClick: false,
  14. interactiveBorder: 20,
  15. ignoreAttributes: true,
  16. maxWidth: 500, // increase over default 350px
  17. onHide: (instance) => {
  18. visibleInstances.delete(instance);
  19. return onHide?.(instance);
  20. },
  21. onDestroy: (instance) => {
  22. visibleInstances.delete(instance);
  23. return onDestroy?.(instance);
  24. },
  25. onShow: (instance) => {
  26. // hide other tooltip instances so only one tooltip shows at a time
  27. for (const visibleInstance of visibleInstances) {
  28. if (visibleInstance.props.role === 'tooltip') {
  29. visibleInstance.hide();
  30. }
  31. }
  32. visibleInstances.add(instance);
  33. return onShow?.(instance);
  34. },
  35. arrow: `<svg width="16" height="7"><path d="m0 7 8-7 8 7Z" class="tippy-svg-arrow-outer"/><path d="m0 8 8-7 8 7Z" class="tippy-svg-arrow-inner"/></svg>`,
  36. role: role || 'menu', // HTML role attribute
  37. theme: theme || role || 'menu', // CSS theme, either "tooltip", "menu" or "box-with-header"
  38. plugins: [followCursor],
  39. ...other,
  40. });
  41. if (role === 'menu') {
  42. target.setAttribute('aria-haspopup', 'true');
  43. }
  44. return instance;
  45. }
  46. /**
  47. * Attach a tooltip tippy to the given target element.
  48. * If the target element already has a tooltip tippy attached, the tooltip will be updated with the new content.
  49. * If the target element has no content, then no tooltip will be attached, and it returns null.
  50. *
  51. * Note: "tooltip" doesn't equal to "tippy". "tooltip" means a auto-popup content, it just uses tippy as the implementation.
  52. *
  53. * @param target {HTMLElement}
  54. * @param content {null|string}
  55. * @returns {null|tippy}
  56. */
  57. function attachTooltip(target, content = null) {
  58. switchTitleToTooltip(target);
  59. content = content ?? target.getAttribute('data-tooltip-content');
  60. if (!content) return null;
  61. // when element has a clipboard target, we update the tooltip after copy
  62. // in which case it is undesirable to automatically hide it on click as
  63. // it would momentarily flash the tooltip out and in.
  64. const hasClipboardTarget = target.hasAttribute('data-clipboard-target');
  65. const hideOnClick = !hasClipboardTarget;
  66. const props = {
  67. content,
  68. delay: 100,
  69. role: 'tooltip',
  70. theme: 'tooltip',
  71. hideOnClick,
  72. placement: target.getAttribute('data-tooltip-placement') || 'top-start',
  73. followCursor: target.getAttribute('data-tooltip-follow-cursor') || false,
  74. ...(target.getAttribute('data-tooltip-interactive') === 'true' ? {interactive: true, aria: {content: 'describedby', expanded: false}} : {}),
  75. };
  76. if (!target._tippy) {
  77. createTippy(target, props);
  78. } else {
  79. target._tippy.setProps(props);
  80. }
  81. return target._tippy;
  82. }
  83. function switchTitleToTooltip(target) {
  84. let title = target.getAttribute('title');
  85. if (title) {
  86. // apply custom formatting to relative-time's tooltips
  87. if (target.tagName.toLowerCase() === 'relative-time') {
  88. const datetime = target.getAttribute('datetime');
  89. if (datetime) {
  90. title = formatDatetime(new Date(datetime));
  91. }
  92. }
  93. target.setAttribute('data-tooltip-content', title);
  94. target.setAttribute('aria-label', title);
  95. // keep the attribute, in case there are some other "[title]" selectors
  96. // and to prevent infinite loop with <relative-time> which will re-add
  97. // title if it is absent
  98. target.setAttribute('title', '');
  99. }
  100. }
  101. /**
  102. * Creating tooltip tippy instance is expensive, so we only create it when the user hovers over the element
  103. * According to https://www.w3.org/TR/DOM-Level-3-Events/#events-mouseevent-event-order , mouseover event is fired before mouseenter event
  104. * Some browsers like PaleMoon don't support "addEventListener('mouseenter', capture)"
  105. * The tippy by default uses "mouseenter" event to show, so we use "mouseover" event to switch to tippy
  106. * @param e {Event}
  107. */
  108. function lazyTooltipOnMouseHover(e) {
  109. e.target.removeEventListener('mouseover', lazyTooltipOnMouseHover, true);
  110. attachTooltip(this);
  111. }
  112. // Activate the tooltip for current element.
  113. // If the element has no aria-label, use the tooltip content as aria-label.
  114. function attachLazyTooltip(el) {
  115. el.addEventListener('mouseover', lazyTooltipOnMouseHover, {capture: true});
  116. // meanwhile, if the element has no aria-label, use the tooltip content as aria-label
  117. if (!el.hasAttribute('aria-label')) {
  118. const content = el.getAttribute('data-tooltip-content');
  119. if (content) {
  120. el.setAttribute('aria-label', content);
  121. }
  122. }
  123. }
  124. // Activate the tooltip for all children elements.
  125. function attachChildrenLazyTooltip(target) {
  126. for (const el of target.querySelectorAll('[data-tooltip-content]')) {
  127. attachLazyTooltip(el);
  128. }
  129. }
  130. export function initGlobalTooltips() {
  131. // use MutationObserver to detect new "data-tooltip-content" elements added to the DOM, or attributes changed
  132. const observerConnect = (observer) => observer.observe(document, {
  133. subtree: true,
  134. childList: true,
  135. attributeFilter: ['data-tooltip-content', 'title'],
  136. });
  137. const observer = new MutationObserver((mutationList, observer) => {
  138. const pending = observer.takeRecords();
  139. observer.disconnect();
  140. for (const mutation of [...mutationList, ...pending]) {
  141. if (mutation.type === 'childList') {
  142. // mainly for Vue components and AJAX rendered elements
  143. for (const el of mutation.addedNodes) {
  144. if (!isDocumentFragmentOrElementNode(el)) continue;
  145. attachChildrenLazyTooltip(el);
  146. if (el.hasAttribute('data-tooltip-content')) {
  147. attachLazyTooltip(el);
  148. }
  149. }
  150. } else if (mutation.type === 'attributes') {
  151. attachTooltip(mutation.target);
  152. }
  153. }
  154. observerConnect(observer);
  155. });
  156. observerConnect(observer);
  157. attachChildrenLazyTooltip(document.documentElement);
  158. }
  159. export function showTemporaryTooltip(target, content) {
  160. // if the target is inside a dropdown, don't show the tooltip because when the dropdown
  161. // closes, the tippy would be pushed unsightly to the top-left of the screen like seen
  162. // on the issue comment menu.
  163. if (target.closest('.ui.dropdown > .menu')) return;
  164. const tippy = target._tippy ?? attachTooltip(target, content);
  165. tippy.setContent(content);
  166. if (!tippy.state.isShown) tippy.show();
  167. tippy.setProps({
  168. onHidden: (tippy) => {
  169. // reset the default tooltip content, if no default, then this temporary tooltip could be destroyed
  170. if (!attachTooltip(target)) {
  171. tippy.destroy();
  172. }
  173. },
  174. });
  175. }