Fix misaligned tooltip positions in modal dialogs

This commit fixes a bug that causes tooltips to be slightly misaligned.

Tooltip positioning was incorrect during modal transitions due to their
initial movement, causing tooltips to align incorrectly at the start of
the animation rather than the end.

One way to solve this would be using `autoUpdate` from `floating-ui`
with `animationFrame: true`. However, this recalculates positions tens
of times per second, impacting performance. This is a monkey solution.

This commit adopts a more efficient approach by updating tooltip
positions only at the end of the transitions, which reduces calculations
and conserves resources.

Key changes:

- Addd transition end event listener for updating tooltip positions.
- Use throttling to eliminate excessive position recalculations.

Other supporting changes:

- Improve throttle function to support efficient recalculations of
  positions:
  - Add ability to optionally exclude the first execution (leading
    call).
  - Refactor to simplify it make it easier to follow and read.
  - Fix a bug where initial calls were incorrectly throttled if
    `dateNow()` returned `0`.
- Introduce and use a global hook for efficient DOM event management.
  This greatily introduce safety, reuse and testability of event
  listening.
This commit is contained in:
undergroundwires
2024-05-08 15:24:12 +02:00
parent a3343205b1
commit dd71536316
26 changed files with 1165 additions and 335 deletions

View File

@@ -1,78 +1,79 @@
import {
describe, it, expect, afterEach,
describe, it, expect,
} from 'vitest';
import { shallowMount } from '@vue/test-utils';
import { nextTick, defineComponent } from 'vue';
import { useEscapeKeyListener } from '@/presentation/components/Shared/Modal/Hooks/UseEscapeKeyListener';
import { type EventName, createWindowEventSpies } from '@tests/shared/Spies/WindowEventSpies';
import type { UseEventListener } from '@/presentation/components/Shared/Hooks/UseAutoUnsubscribedEventListener';
import { UseEventListenerStub } from '@tests/unit/shared/Stubs/UseEventListenerStub';
describe('useEscapeKeyListener', () => {
it('executes the callback when the Escape key is pressed', async () => {
it('executes the callback when the Escape key is pressed', () => {
// arrange
let callbackCalled = false;
const callback = () => {
callbackCalled = true;
};
createComponent(callback);
const escapeEvent = new KeyboardEvent('keyup', { key: 'Escape' });
const eventTarget = new EventTarget();
const context = new TestContext()
.withEventTarget(eventTarget)
.withCallback(callback);
// act
const event = new KeyboardEvent('keyup', { key: 'Escape' });
window.dispatchEvent(event);
await nextTick();
context.get();
eventTarget.dispatchEvent(escapeEvent);
// assert
expect(callbackCalled).to.equal(true);
});
it('does not execute the callback for other key presses', async () => {
it('does not execute the callback for other key presses', () => {
// arrange
let callbackCalled = false;
const callback = () => {
callbackCalled = true;
};
createComponent(callback);
const enterKeyEvent = new KeyboardEvent('keyup', { key: 'Enter' });
const eventTarget = new EventTarget();
const context = new TestContext()
.withEventTarget(eventTarget)
.withCallback(callback);
// act
const event = new KeyboardEvent('keyup', { key: 'Enter' });
window.dispatchEvent(event);
await nextTick();
context.get();
eventTarget.dispatchEvent(enterKeyEvent);
// assert
expect(callbackCalled).to.equal(false);
});
it('adds an event listener on component mount', () => {
// arrange
const expectedEventType: EventName = 'keyup';
const { isAddEventCalled } = createWindowEventSpies(afterEach);
// act
createComponent();
// assert
expect(isAddEventCalled(expectedEventType)).to.equal(true);
});
it('removes the event listener on component unmount', async () => {
// arrange
const expectedEventType: EventName = 'keyup';
const { isRemoveEventCalled } = createWindowEventSpies(afterEach);
// act
const wrapper = createComponent();
wrapper.unmount();
await nextTick();
// assert
expect(isRemoveEventCalled(expectedEventType)).to.equal(true);
});
});
function createComponent(callback = () => {}) {
return shallowMount(defineComponent({
setup() {
useEscapeKeyListener(callback);
},
template: '<div></div>',
}));
class TestContext {
private callback: () => void = () => { /* NOOP */ };
private useEventListener: UseEventListener = new UseEventListenerStub().get();
private eventTarget: EventTarget = new EventTarget();
public withCallback(callback: () => void): this {
this.callback = callback;
return this;
}
public withUseEventListener(useEventListener: UseEventListener): this {
this.useEventListener = useEventListener;
return this;
}
public withEventTarget(eventTarget: EventTarget = new EventTarget()): this {
this.eventTarget = eventTarget;
return this;
}
public get(): ReturnType<typeof useEscapeKeyListener> {
return useEscapeKeyListener(
this.callback,
this.eventTarget,
this.useEventListener,
);
}
}

View File

@@ -1,10 +1,11 @@
import {
describe, it, expect, afterEach,
describe, it, expect,
} from 'vitest';
import { shallowMount } from '@vue/test-utils';
import { nextTick } from 'vue';
import ModalContainer from '@/presentation/components/Shared/Modal/ModalContainer.vue';
import { createWindowEventSpies } from '@tests/shared/Spies/WindowEventSpies';
import ModalContainer, { INJECTION_KEY_ESCAPE_LISTENER } from '@/presentation/components/Shared/Modal/ModalContainer.vue';
import type { useEscapeKeyListener } from '@/presentation/components/Shared/Modal/Hooks/UseEscapeKeyListener';
import { expectExists } from '@tests/shared/Assertions/ExpectExists';
const DOM_MODAL_CONTAINER_SELECTOR = '.modal-container';
const COMPONENT_MODAL_OVERLAY_NAME = 'ModalOverlay';
@@ -73,15 +74,23 @@ describe('ModalContainer.vue', () => {
it('closes on pressing ESC key', async () => {
// arrange
createWindowEventSpies(afterEach);
const wrapper = mountComponent({ modelValue: true });
let escapeKeyCallback: (() => void) | undefined;
const escapeKeyListenerStub: typeof useEscapeKeyListener = (callback) => {
escapeKeyCallback = callback;
};
const wrapper = mountComponent({
modelValue: true,
escapeListener: escapeKeyListenerStub,
});
// act
const escapeEvent = new KeyboardEvent('keyup', { key: 'Escape' });
window.dispatchEvent(escapeEvent);
await wrapper.vm.$nextTick();
if (escapeKeyCallback) {
escapeKeyCallback();
}
await nextTick();
// assert
expectExists(escapeKeyCallback);
expect(wrapper.emitted('update:modelValue')).to.deep.equal([[false]]);
});
@@ -94,7 +103,7 @@ describe('ModalContainer.vue', () => {
// act
overlayMock.vm.$emit('transitionedOut');
contentMock.vm.$emit('transitionedOut');
await wrapper.vm.$nextTick();
await nextTick();
// assert
expect(wrapper.emitted('update:modelValue')).to.deep.equal([[false]]);
@@ -126,7 +135,7 @@ describe('ModalContainer.vue', () => {
// act
const overlayMock = wrapper.findComponent({ name: COMPONENT_MODAL_OVERLAY_NAME });
overlayMock.vm.$emit('click');
await wrapper.vm.$nextTick();
await nextTick();
// assert
expect(wrapper.emitted('update:modelValue')).to.equal(undefined);
@@ -139,7 +148,7 @@ describe('ModalContainer.vue', () => {
// act
const overlayMock = wrapper.findComponent({ name: COMPONENT_MODAL_OVERLAY_NAME });
overlayMock.vm.$emit('click');
await wrapper.vm.$nextTick();
await nextTick();
// assert
expect(wrapper.emitted('update:modelValue')).to.deep.equal([[false]]);
@@ -151,7 +160,7 @@ function mountComponent(options: {
readonly modelValue: boolean,
readonly closeOnOutsideClick?: boolean,
readonly slotHtml?: string,
readonly attachToDocument?: boolean,
readonly escapeListener?: typeof useEscapeKeyListener,
}) {
return shallowMount(ModalContainer, {
props: {
@@ -162,6 +171,10 @@ function mountComponent(options: {
},
slots: options.slotHtml !== undefined ? { default: options.slotHtml } : undefined,
global: {
provide: {
[INJECTION_KEY_ESCAPE_LISTENER]:
options?.escapeListener ?? (() => { /* NOP */ }),
},
stubs: {
[COMPONENT_MODAL_OVERLAY_NAME]: {
name: COMPONENT_MODAL_OVERLAY_NAME,