Commit a0ebd5ca authored by Vitaly Slobodin's avatar Vitaly Slobodin

Merge branch 'slashmanov/popovers-lazy-init' into 'master'

Lazy initialization for user popovers

See merge request gitlab-org/gitlab!80597
parents 050ba3e6 674fc2fc
import $ from 'jquery';
import syntaxHighlight from '~/syntax_highlight';
import initUserPopovers from '../../user_popovers';
import highlightCurrentUser from './highlight_current_user';
import renderMath from './render_math';
import renderMermaid from './render_mermaid';
......@@ -20,7 +19,6 @@ $.fn.renderGFM = function renderGFM() {
renderMermaid(this.find('.js-render-mermaid'));
}
highlightCurrentUser(this.find('.gfm-project_member').get());
initUserPopovers(this.find('.js-user-link').get());
const mrPopoverElements = this.find('.gfm-merge_request').get();
if (mrPopoverElements.length) {
......
......@@ -7,8 +7,6 @@ import TimeAgoTooltip from '~/vue_shared/components/time_ago_tooltip.vue';
import UserAvatarLink from '~/vue_shared/components/user_avatar/user_avatar_link.vue';
import glFeatureFlagsMixin from '~/vue_shared/mixins/gl_feature_flags_mixin';
import initUserPopovers from '../../user_popovers';
/**
* CommitItem
*
......@@ -82,11 +80,6 @@ export default {
return this.commit.description_html.replace(/^
/, '');
},
},
created() {
this.$nextTick(() => {
initUserPopovers(this.$el.querySelectorAll('.js-user-link'));
});
},
safeHtmlConfig: {
ADD_TAGS: ['gl-emoji'],
},
......
......@@ -4,7 +4,6 @@ import { mapState } from 'vuex';
import MembersTableCell from 'ee_else_ce/members/components/table/members_table_cell.vue';
import { canOverride, canRemove, canResend, canUpdate } from 'ee_else_ce/members/utils';
import { mergeUrlParams } from '~/lib/utils/url_utility';
import initUserPopovers from '~/user_popovers';
import UserDate from '~/vue_shared/components/user_date.vue';
import {
FIELD_KEY_ACTIONS,
......@@ -85,9 +84,6 @@ export default {
return this.tabQueryParamValue === TAB_QUERY_PARAM_VALUES.invite;
},
},
mounted() {
initUserPopovers(this.$el.querySelectorAll('.js-user-link'));
},
methods: {
hasActionButtons(member) {
return (
......
......@@ -3,7 +3,6 @@ import { mapGetters, mapActions } from 'vuex';
import highlightCurrentUser from '~/behaviors/markdown/highlight_current_user';
import createFlash from '~/flash';
import { __ } from '~/locale';
import initUserPopovers from '~/user_popovers';
import TimelineEntryItem from '~/vue_shared/components/notes/timeline_entry_item.vue';
import OrderedLayout from '~/vue_shared/components/ordered_layout.vue';
import glFeatureFlagsMixin from '~/vue_shared/mixins/gl_feature_flags_mixin';
......@@ -169,7 +168,6 @@ export default {
updated() {
this.$nextTick(() => {
highlightCurrentUser(this.$el.querySelectorAll('.gfm-project_member'));
initUserPopovers(this.$el.querySelectorAll('.js-user-link'));
});
},
beforeDestroy() {
......
......@@ -57,41 +57,35 @@ const populateUserInfo = (user) => {
);
};
const initializedPopovers = new Map();
let domObservedForChanges = false;
function initPopover(el, user, mountPopover) {
const preloadedUserInfo = getPreloadedUserInfo(el.dataset);
const addPopoversToModifiedTree = new MutationObserver(() => {
const userLinks = document?.querySelectorAll('.js-user-link, .gfm-project_member');
Object.assign(user, preloadedUserInfo);
if (userLinks) {
addPopovers(userLinks); /* eslint-disable-line no-use-before-define */
if (preloadedUserInfo.userId) {
populateUserInfo(user);
}
});
function observeBody() {
if (!domObservedForChanges) {
addPopoversToModifiedTree.observe(document.body, {
subtree: true,
childList: true,
});
domObservedForChanges = true;
}
}
export default function addPopovers(elements = document.querySelectorAll('.js-user-link')) {
const userLinks = Array.from(elements);
const UserPopoverComponent = Vue.extend(UserPopover);
const popoverInstance = new UserPopoverComponent({
propsData: {
target: el,
user,
},
});
mountPopover(popoverInstance);
// wait for component to actually mount
setTimeout(() => {
// trigger an event to force tooltip to show
const event = new MouseEvent('mouseenter');
event.isSelfTriggered = true;
el.dispatchEvent(event);
});
}
observeBody();
return userLinks
.filter(({ dataset }) => dataset.user || dataset.userId)
.map((el) => {
if (initializedPopovers.has(el)) {
return initializedPopovers.get(el);
}
function initPopovers(userLinks, mountPopover) {
userLinks
.filter(({ dataset, user }) => !user && (dataset.user || dataset.userId))
.forEach((el) => {
const user = {
location: null,
bio: null,
......@@ -99,31 +93,60 @@ export default function addPopovers(elements = document.querySelectorAll('.js-us
status: null,
loaded: false,
};
const renderedPopover = new UserPopoverComponent({
propsData: {
target: el,
user,
},
el.user = user;
const init = initPopover.bind(null, el, user, mountPopover);
el.addEventListener('mouseenter', init, { once: true });
el.addEventListener('mouseenter', ({ target, isSelfTriggered }) => {
if (!isSelfTriggered) return;
removeTitle(target);
});
el.addEventListener('mouseleave', ({ target }) => {
target.removeAttribute('aria-describedby');
});
});
}
initializedPopovers.set(el, renderedPopover);
const userLinkSelector = 'a.js-user-link, a.gfm-project_member';
renderedPopover.$mount();
const getUserLinkNodes = (node) => {
if (!('matches' in node)) return null;
if (node.matches(userLinkSelector)) return [node];
return Array.from(node.querySelectorAll(userLinkSelector));
};
el.addEventListener('mouseenter', ({ target }) => {
removeTitle(target);
const preloadedUserInfo = getPreloadedUserInfo(target.dataset);
let observer;
Object.assign(user, preloadedUserInfo);
export default function addPopovers(
elements = document.querySelectorAll('.js-user-link'),
mountPopover = (popoverInstance) => popoverInstance.$mount(),
) {
const userLinks = Array.from(elements);
if (preloadedUserInfo.userId) {
populateUserInfo(user);
}
});
el.addEventListener('mouseleave', ({ target }) => {
target.removeAttribute('aria-describedby');
});
initPopovers(userLinks, mountPopover);
if (!observer) {
observer = new MutationObserver((mutationsList) => {
const newUserLinks = mutationsList
.filter((mutation) => mutation.type === 'childList' && mutation.addedNodes)
.reduce((acc, mutation) => {
const userLinkNodes = Array.from(mutation.addedNodes)
.flatMap(getUserLinkNodes)
.filter(Boolean);
acc.push(...userLinkNodes);
return acc;
}, []);
if (newUserLinks.length !== 0) {
initPopovers(newUserLinks, mountPopover);
}
});
observer.observe(document.body, {
subtree: true,
childList: true,
});
return renderedPopover;
document.addEventListener('beforeunload', () => {
observer.disconnect();
});
}
}
......@@ -18,7 +18,6 @@ import { toggleContainerClasses } from '~/lib/utils/dom_utils';
import { visitUrl, joinPaths } from '~/lib/utils/url_utility';
import { s__ } from '~/locale';
import Tracking from '~/tracking';
import initUserPopovers from '~/user_popovers';
import AlertDetailsTable from '~/vue_shared/components/alert_details_table.vue';
import TimeAgoTooltip from '~/vue_shared/components/time_ago_tooltip.vue';
import { PAGE_CONFIG, SEVERITY_LEVELS } from '../constants';
......@@ -175,7 +174,6 @@ export default {
updated() {
this.$nextTick(() => {
highlightCurrentUser(this.$el.querySelectorAll('.gfm-project_member'));
initUserPopovers(this.$el.querySelectorAll('.js-user-link'));
});
},
methods: {
......
......@@ -10,7 +10,6 @@ import createFlash from '~/flash';
import { TYPE_VULNERABILITY } from '~/graphql_shared/constants';
import { convertToGraphQLId } from '~/graphql_shared/utils';
import { s__ } from '~/locale';
import initUserPopovers from '~/user_popovers';
import glFeatureFlagMixin from '~/vue_shared/mixins/gl_feature_flags_mixin';
import { normalizeGraphQLNote } from '../helpers';
import GenericReportSection from './generic_report/report_section.vue';
......@@ -117,11 +116,6 @@ export default {
this.stopPolling();
this.unbindVisibilityListener();
},
updated() {
this.$nextTick(() => {
initUserPopovers(this.$el.querySelectorAll('.js-user-link'));
});
},
methods: {
startPolling() {
if (this.pollInterval) {
......
......@@ -18,11 +18,9 @@ import createMockApollo from 'helpers/mock_apollo_helper';
import { shallowMountExtended } from 'helpers/vue_test_utils_helper';
import waitForPromises from 'helpers/wait_for_promises';
import createFlash from '~/flash';
import initUserPopovers from '~/user_popovers';
import { addTypenamesToDiscussion, generateNote } from './mock_data';
jest.mock('~/flash');
jest.mock('~/user_popovers');
Vue.use(VueApollo);
......@@ -138,13 +136,6 @@ describe('Vulnerability Footer', () => {
});
});
it('calls initUserPopovers when the component is updated', async () => {
createWrapper({ queryHandler: discussionsHandler({ discussions: [] }) });
expect(initUserPopovers).not.toHaveBeenCalled();
await waitForPromises();
expect(initUserPopovers).toHaveBeenCalled();
});
it('shows an error the discussions could not be retrieved', async () => {
await createWrapperAndFetchDiscussions({
errors: [{ message: 'Something went wrong' }],
......
......@@ -6,8 +6,6 @@ import Component from '~/diffs/components/commit_item.vue';
import { getTimeago } from '~/lib/utils/datetime_utility';
import CommitPipelineStatus from '~/projects/tree/components/commit_pipeline_status_component.vue';
jest.mock('~/user_popovers');
const TEST_AUTHOR_NAME = 'test';
const TEST_AUTHOR_EMAIL = 'test+test@gitlab.com';
const TEST_AUTHOR_GRAVATAR = `${TEST_HOST}/avatar/test?s=40`;
......
......@@ -21,7 +21,6 @@ import {
BADGE_LABELS_PENDING_OWNER_APPROVAL,
TAB_QUERY_PARAM_VALUES,
} from '~/members/constants';
import * as initUserPopovers from '~/user_popovers';
import {
member as memberMock,
directMember,
......@@ -257,14 +256,6 @@ describe('MembersTable', () => {
});
});
it('initializes user popovers when mounted', () => {
const initUserPopoversMock = jest.spyOn(initUserPopovers, 'default');
createComponent();
expect(initUserPopoversMock).toHaveBeenCalled();
});
it('adds QA selector to table', () => {
createComponent();
......
......@@ -18,8 +18,6 @@ import '~/behaviors/markdown/render_gfm';
import OrderedLayout from '~/vue_shared/components/ordered_layout.vue';
import * as mockData from '../mock_data';
jest.mock('~/user_popovers', () => jest.fn());
setTestTimeout(1000);
const TYPE_COMMENT_FORM = 'comment-form';
......
......@@ -18,12 +18,13 @@ describe('User Popovers', () => {
return link;
};
const findPopovers = () => {
return Array.from(document.querySelectorAll('[data-testid="user-popover"]'));
};
const dummyUser = { name: 'root' };
const dummyUserStatus = { message: 'active' };
let popovers;
const triggerEvent = (eventName, el) => {
const event = new MouseEvent(eventName, {
bubbles: true,
......@@ -45,29 +46,49 @@ describe('User Popovers', () => {
.spyOn(UsersCache, 'retrieveStatusById')
.mockImplementation((userId) => userStatusCacheSpy(userId));
popovers = initUserPopovers(document.querySelectorAll(selector));
initUserPopovers(document.querySelectorAll(selector), (popoverInstance) => {
const mountingRoot = document.createElement('div');
document.body.appendChild(mountingRoot);
popoverInstance.$mount(mountingRoot);
});
});
it('initializes a popover for each user link with a user id', () => {
const linksWithUsers = findFixtureLinks();
describe('shows a placeholder popover on hover', () => {
let linksWithUsers;
beforeEach(() => {
linksWithUsers = findFixtureLinks();
linksWithUsers.forEach((el) => {
triggerEvent('mouseenter', el);
});
});
expect(linksWithUsers.length).toBe(popovers.length);
});
it('for initial links', () => {
expect(findPopovers().length).toBe(linksWithUsers.length);
});
it('adds popovers to user links added to the DOM tree after the initial call', async () => {
document.body.appendChild(createUserLink());
document.body.appendChild(createUserLink());
it('for elements added after initial load', async () => {
const addedLinks = [createUserLink(), createUserLink()];
addedLinks.forEach((link) => {
document.body.appendChild(link);
});
const linksWithUsers = findFixtureLinks();
await Promise.resolve();
expect(linksWithUsers.length).toBe(popovers.length + 2);
addedLinks.forEach((link) => {
triggerEvent('mouseenter', link);
});
expect(findPopovers().length).toBe(linksWithUsers.length + addedLinks.length);
});
});
it('does not initialize the user popovers twice for the same element', () => {
const newPopovers = initUserPopovers(document.querySelectorAll(selector));
const samePopovers = popovers.every((popover, index) => newPopovers[index] === popover);
const [firstUserLink] = findFixtureLinks();
triggerEvent('mouseenter', firstUserLink);
triggerEvent('mouseleave', firstUserLink);
triggerEvent('mouseenter', firstUserLink);
expect(samePopovers).toBe(true);
expect(findPopovers().length).toBe(1);
});
describe('when user link emits mouseenter event', () => {
......@@ -86,11 +107,11 @@ describe('User Popovers', () => {
expect(userLink.dataset.originalTitle).toBeFalsy();
});
it('populates popovers with preloaded user data', () => {
it('populates popover with preloaded user data', () => {
const { name, userId, username } = userLink.dataset;
const [firstPopover] = popovers;
const [firstPopover] = findFixtureLinks();
expect(firstPopover.$props.user).toEqual(
expect(firstPopover.user).toEqual(
expect.objectContaining({
name,
userId,
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment