Skip to content

Use a general approach to show tooltip, fix temporary tooltip bug #23574

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 11 commits into from
Mar 23, 2023
Merged
4 changes: 2 additions & 2 deletions templates/repo/issue/view_content/sidebar.tmpl
Original file line number Diff line number Diff line change
Expand Up @@ -664,9 +664,9 @@
{{if and (not (eq .Issue.PullRequest.HeadRepo.FullName .Issue.PullRequest.BaseRepo.FullName)) .CanWriteToHeadRepo}}
<div class="ui divider"></div>
<div class="inline field">
<div class="ui checkbox" id="allow-edits-from-maintainers"
<div class="ui checkbox tooltip" id="allow-edits-from-maintainers"
data-url="{{.Issue.Link}}"
data-prompt-tip="{{.locale.Tr "repo.pulls.allow_edits_from_maintainers_desc"}}"
data-tooltip-content="{{.locale.Tr "repo.pulls.allow_edits_from_maintainers_desc"}}"
data-prompt-error="{{.locale.Tr "repo.pulls.allow_edits_from_maintainers_err"}}"
>
<label><strong>{{.locale.Tr "repo.pulls.allow_edits_from_maintainers"}}</strong></label>
Expand Down
2 changes: 1 addition & 1 deletion templates/repo/sub_menu.tmpl
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@
</div>
<a class="ui segment language-stats">
{{range .LanguageStats}}
<div class="bar tooltip" style="width: {{.Percentage}}%; background-color: {{.Color}}" data-placement="top" data-content={{.Language}}>&nbsp;</div>
<div class="bar tooltip" style="width: {{.Percentage}}%; background-color: {{.Color}}" data-tooltip-placement="top" data-tooltip-content={{.Language}}>&nbsp;</div>
{{end}}
</a>
{{end}}
Expand Down
4 changes: 0 additions & 4 deletions web_src/js/components/DashboardRepoList.vue
Original file line number Diff line number Diff line change
Expand Up @@ -147,7 +147,6 @@
<script>
import {createApp, nextTick} from 'vue';
import $ from 'jquery';
import {initTooltip} from '../modules/tippy.js';
import {SvgIcon} from '../svg.js';

const {appSubUrl, assetUrlPrefix, pageData} = window.config;
Expand Down Expand Up @@ -238,9 +237,6 @@ const sfc = {
mounted() {
const el = document.getElementById('dashboard-repo-list');
this.changeReposFilter(this.reposFilter);
for (const elTooltip of el.querySelectorAll('.tooltip')) {
initTooltip(elTooltip);
}
$(el).find('.dropdown').dropdown();
nextTick(() => {
this.$refs.search.focus();
Expand Down
12 changes: 0 additions & 12 deletions web_src/js/components/DiffFileList.vue
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,6 @@
</template>

<script>
import {initTooltip} from '../modules/tippy.js';
import {doLoadMoreFiles} from '../features/repo-diff.js';

const {pageData} = window.config;
Expand All @@ -30,17 +29,6 @@ export default {
data: () => {
return pageData.diffFileInfo;
},
watch: {
fileListIsVisible(newValue) {
if (newValue === true) {
this.$nextTick(() => {
for (const el of this.$refs.root.querySelectorAll('.tooltip')) {
initTooltip(el);
}
});
}
}
},
mounted() {
document.getElementById('show-file-list-btn').addEventListener('click', this.toggleFileList);
},
Expand Down
7 changes: 0 additions & 7 deletions web_src/js/features/common-global.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ import {initCompColorPicker} from './comp/ColorPicker.js';
import {showGlobalErrorMessage} from '../bootstrap.js';
import {attachCheckboxAria, attachDropdownAria} from './aria.js';
import {handleGlobalEnterQuickSubmit} from './comp/QuickSubmit.js';
import {initTooltip} from '../modules/tippy.js';
import {svg} from '../svg.js';
import {hideElem, showElem, toggleElem} from '../utils/dom.js';

Expand Down Expand Up @@ -67,12 +66,6 @@ export function initGlobalButtonClickOnEnter() {
});
}

export function initGlobalTooltips() {
for (const el of document.getElementsByClassName('tooltip')) {
initTooltip(el);
}
}

export function initGlobalCommon() {
// Undo Safari emoji glitch fix at high enough zoom levels
if (navigator.userAgent.match('Safari')) {
Expand Down
5 changes: 0 additions & 5 deletions web_src/js/features/repo-diff.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ import {initCompReactionSelector} from './comp/ReactionSelector.js';
import {initRepoIssueContentHistory} from './repo-issue-content.js';
import {validateTextareaNonEmpty} from './comp/EasyMDE.js';
import {initViewedCheckboxListenerFor, countAndUpdateViewedFiles} from './pull-view-file.js';
import {initTooltip} from '../modules/tippy.js';

const {csrfToken} = window.config;

Expand Down Expand Up @@ -60,10 +59,6 @@ export function initRepoDiffConversationForm() {
const $newConversationHolder = $(await $.post($form.attr('action'), formDataString));
const {path, side, idx} = $newConversationHolder.data();

$newConversationHolder.find('.tooltip').each(function () {
initTooltip(this);
});

$form.closest('.conversation-holder').replaceWith($newConversationHolder);
if ($form.closest('tr').data('line-type') === 'same') {
$(`[data-path="${path}"] a.add-code-comment[data-idx="${idx}"]`).addClass('invisible');
Expand Down
5 changes: 1 addition & 4 deletions web_src/js/features/repo-issue.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import {attachTribute} from './tribute.js';
import {createCommentEasyMDE, getAttachedEasyMDE} from './comp/EasyMDE.js';
import {initEasyMDEImagePaste} from './comp/ImagePaste.js';
import {initCompMarkupContentPreviewTab} from './comp/MarkupContentPreview.js';
import {initTooltip, showTemporaryTooltip, createTippy} from '../modules/tippy.js';
import {showTemporaryTooltip, createTippy} from '../modules/tippy.js';
import {hideElem, showElem, toggleElem} from '../utils/dom.js';
import {setFileFolding} from './file-fold.js';

Expand Down Expand Up @@ -280,10 +280,7 @@ export function initRepoPullRequestAllowMaintainerEdit() {
const $checkbox = $('#allow-edits-from-maintainers');
if (!$checkbox.length) return;

const promptTip = $checkbox.attr('data-prompt-tip');
const promptError = $checkbox.attr('data-prompt-error');

initTooltip($checkbox[0], {content: promptTip});
$checkbox.checkbox({
'onChange': () => {
const checked = $checkbox.checkbox('is checked');
Expand Down
2 changes: 1 addition & 1 deletion web_src/js/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,6 @@ import {
initGlobalFormDirtyLeaveConfirm,
initGlobalLinkActions,
initHeadNavbarContentToggle,
initGlobalTooltips,
} from './features/common-global.js';
import {initRepoTopicBar} from './features/repo-home.js';
import {initAdminEmails} from './features/admin/emails.js';
Expand Down Expand Up @@ -89,6 +88,7 @@ import {initFormattingReplacements} from './features/formatting.js';
import {initCopyContent} from './features/copycontent.js';
import {initCaptcha} from './features/captcha.js';
import {initRepositoryActionView} from './components/RepoActionView.vue';
import {initGlobalTooltips} from './modules/tippy.js';

// Run time-critical code as soon as possible. This is safe to do because this
// script appears at the end of <body> and rendered HTML is accessible at that point.
Expand Down
110 changes: 90 additions & 20 deletions web_src/js/modules/tippy.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import tippy from 'tippy.js';
export function createTippy(target, opts = {}) {
const instance = tippy(target, {
appendTo: document.body,
placement: target.getAttribute('data-placement') || 'top-start',
placement: 'top-start',
animation: false,
allowHTML: false,
hideOnClick: false,
Expand All @@ -25,38 +25,108 @@ export function createTippy(target, opts = {}) {
return instance;
}

export function initTooltip(el, props = {}) {
const content = el.getAttribute('data-content') || props.content;
function getTippyTooltipContent(target) {
// prefer to always use the "[data-tooltip-content]" attribute
// for backward compatibility, we also support the ".tooltip[data-content]" attribute
let content = target.getAttribute('data-tooltip-content');
if (!content && target.classList.contains('tooltip')) {
content = target.getAttribute('data-content');
}
return content;
}

/**
* Attach a tippy tooltip to the given target element.
* If the target element already has a tippy tooltip attached, the tooltip will be updated with the new content.
* If the target element has no content, then no tooltip will be attached, and it returns null.
* @param target {HTMLElement}
* @param content {null|string}
* @returns {null|tippy}
*/
function attachTippyTooltip(target, content = null) {
content = content ?? getTippyTooltipContent(target);
if (!content) return null;
if (!el.hasAttribute('aria-label')) el.setAttribute('aria-label', content);
return createTippy(el, {

const props = {
content,
delay: 100,
role: 'tooltip',
...(el.getAttribute('data-tooltip-interactive') === 'true' ? {interactive: true} : {}),
...props,
});
}
placement: target.getAttribute('data-tooltip-placement') || 'top-start',
...(target.getAttribute('data-tooltip-interactive') === 'true' ? {interactive: true} : {}),
};

export function showTemporaryTooltip(target, content) {
let tippy, oldContent;
if (target._tippy) {
tippy = target._tippy;
oldContent = tippy.props.content;
if (!target._tippy) {
createTippy(target, props);
} else {
tippy = initTooltip(target, {content});
target._tippy.setProps(props);
}
return target._tippy;
}

/**
* creating tippy instance is expensive, so we only create it when the user hovers over the element
* @param e {Event}
*/
function lazyTippyOnMouseEnter(e) {
e.target.removeEventListener('mouseenter', lazyTippyOnMouseEnter, true);
attachTippyTooltip(this);
}

/**
* Activate the tippy tooltip for all children elements
* And if the element has no aria-label, use the tooltip content as aria-label
* @param target {HTMLElement}
*/
function attachChildrenLazyTippyTooltip(target) {
// the selector must match the logic in getTippyTooltipContent
for (const el of target.querySelectorAll('[data-tooltip-content], .tooltip[data-content]')) {
el.addEventListener('mouseenter', lazyTippyOnMouseEnter, true);

// meanwhile, if the element has no aria-label, use the tooltip content as aria-label
if (!el.hasAttribute('aria-label')) {
const content = getTippyTooltipContent(el);
if (content) {
el.setAttribute('aria-label', content);
}
}
}
}

export function initGlobalTooltips() {
// use MutationObserver to detect new elements added to the DOM, or attributes changed
const observer = new MutationObserver((mutationList) => {
for (const mutation of mutationList) {
if (mutation.type === 'childList') {
for (const el of mutation.addedNodes) {
// handle all "tooltip" elements in newly added nodes, skip non-related nodes (eg: "#text")
if (el.querySelectorAll) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this line looks broken.

Copy link
Contributor Author

@wxiaoguang wxiaoguang Mar 20, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not broken, just a quick check to see the "node" has querySelectorAll function, which is needed by attachChildrenLazyTippyTooltip below.

Otherwise some nodes (like #text) couldn't be used to attach tippy.


I agree that there would be other approaches to check if the node is non-#text, at the moment, this quick check is clear and fast IMO.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Use node.nodeType please, it's much more clear.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can you provide a list for the types?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should be [Node.ELEMENT_NODE,Node.DOCUMENT_FRAGMENT_NODE].includes(el.nodeType).

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

But that's slower than the if (el.querySelectorAll) check. Do you really want to do so?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Alternatively 'querySelectorAll' in el would also make the indent clear enough for me.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

OK, then 'querySelectorAll' in el : ba8ad89

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ok

attachChildrenLazyTippyTooltip(el);
}
}
} else if (mutation.type === 'attributes') {
// sync the tooltip content if the attributes change
attachTippyTooltip(mutation.target);
}
}
});
observer.observe(document, {
subtree: true,
childList: true,
attributeFilter: ['data-tooltip-content', 'data-content'],
});

attachChildrenLazyTippyTooltip(document.documentElement);
}

export function showTemporaryTooltip(target, content) {
const tippy = target._tippy ?? attachTippyTooltip(target, content);
tippy.setContent(content);
if (!tippy.state.isShown) tippy.show();
tippy.setProps({
onHidden: (tippy) => {
if (oldContent) {
tippy.setContent(oldContent);
tippy.setProps({onHidden: undefined});
} else {
// reset the default tooltip content, if no default, then this temporary tooltip could be destroyed
if (!attachTippyTooltip(target)) {
tippy.destroy();
// after destroy, the `_tippy` is detached, it can't do "setProps (etc...)" anymore
}
},
});
Expand Down