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:
@@ -1,53 +1,116 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { TimerStub } from '@tests/unit/shared/Stubs/TimerStub';
|
||||
import { throttle } from '@/application/Common/Timing/Throttle';
|
||||
import { throttle, type ThrottleOptions } from '@/application/Common/Timing/Throttle';
|
||||
import type { Timer } from '@/application/Common/Timing/Timer';
|
||||
import { formatAssertionMessage } from '@tests/shared/FormatAssertionMessage';
|
||||
|
||||
describe('throttle', () => {
|
||||
describe('validates parameters', () => {
|
||||
describe('throws if waitInMs is invalid', () => {
|
||||
// arrange
|
||||
const testCases = [
|
||||
describe('parameter validation', () => {
|
||||
describe('throws for invalid waitInMs', () => {
|
||||
const testCases: readonly {
|
||||
readonly description: string;
|
||||
readonly value: number;
|
||||
readonly expectedError: string;
|
||||
}[] = [
|
||||
{
|
||||
name: 'given zero',
|
||||
description: 'given zero',
|
||||
value: 0,
|
||||
expectedError: 'missing delay',
|
||||
},
|
||||
{
|
||||
name: 'given negative',
|
||||
description: 'given negative',
|
||||
value: -2,
|
||||
expectedError: 'negative delay',
|
||||
},
|
||||
];
|
||||
const noopCallback = () => { /* do nothing */ };
|
||||
for (const testCase of testCases) {
|
||||
it(`"${testCase.name}" throws "${testCase.expectedError}"`, () => {
|
||||
testCases.forEach((
|
||||
{ description, expectedError, value: waitInMs },
|
||||
) => {
|
||||
it(`"${description}" throws "${expectedError}"`, () => {
|
||||
// arrange
|
||||
const context = new TestContext()
|
||||
.withWaitInMs(waitInMs);
|
||||
// act
|
||||
const waitInMs = testCase.value;
|
||||
const act = () => throttle(noopCallback, waitInMs);
|
||||
const act = () => context.throttle();
|
||||
// assert
|
||||
expect(act).to.throw(testCase.expectedError);
|
||||
expect(act).to.throw(expectedError);
|
||||
});
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
it('should call the callback immediately', () => {
|
||||
it('executes the leading callback immediately', () => {
|
||||
// arrange
|
||||
const timer = new TimerStub();
|
||||
let totalRuns = 0;
|
||||
const callback = () => totalRuns++;
|
||||
const throttleFunc = throttle(callback, 500, timer);
|
||||
const throttleFunc = new TestContext()
|
||||
.withTimer(timer)
|
||||
.withCallback(callback)
|
||||
.throttle();
|
||||
|
||||
// act
|
||||
throttleFunc();
|
||||
|
||||
// assert
|
||||
expect(totalRuns).to.equal(1);
|
||||
});
|
||||
it('should call the callback again after the timeout', () => {
|
||||
it('executes the leading callback with initial arguments', () => {
|
||||
// arrange
|
||||
const expectedArguments = [1, 2, 3];
|
||||
const timer = new TimerStub();
|
||||
let lastArgs: readonly number[] | null = null;
|
||||
const callback = (...args: readonly number[]) => { lastArgs = args; };
|
||||
const waitInMs = 500;
|
||||
const throttleFunc = new TestContext()
|
||||
.withWaitInMs(waitInMs)
|
||||
.withTimer(timer)
|
||||
.withCallback(callback)
|
||||
.throttle();
|
||||
|
||||
// act
|
||||
throttleFunc(...expectedArguments);
|
||||
timer.tickNext(waitInMs / 3);
|
||||
throttleFunc(4, 5, 6);
|
||||
timer.tickNext(waitInMs / 3);
|
||||
throttleFunc(7, 8, 9);
|
||||
|
||||
// assert
|
||||
expect(lastArgs).to.deep.equal(expectedArguments);
|
||||
});
|
||||
it('executes the trailing callback with final arguments', () => {
|
||||
// arrange
|
||||
const expectedArguments = [1, 2, 3];
|
||||
const timer = new TimerStub();
|
||||
let lastArgs: readonly number[] | null = null;
|
||||
const callback = (...args: readonly number[]) => { lastArgs = args; };
|
||||
const waitInMs = 500;
|
||||
const throttleFunc = new TestContext()
|
||||
.withWaitInMs(waitInMs)
|
||||
.withTimer(timer)
|
||||
.withCallback(callback)
|
||||
.throttle();
|
||||
|
||||
// act
|
||||
throttleFunc(1, 2, 3);
|
||||
timer.tickNext(100);
|
||||
throttleFunc(4, 5, 6);
|
||||
timer.tickNext(100);
|
||||
throttleFunc(lastArgs);
|
||||
|
||||
// assert
|
||||
expect(lastArgs).to.deep.equal(expectedArguments);
|
||||
});
|
||||
it('executes the callback after the delay', () => {
|
||||
// arrange
|
||||
const timer = new TimerStub();
|
||||
let totalRuns = 0;
|
||||
const callback = () => totalRuns++;
|
||||
const waitInMs = 500;
|
||||
const throttleFunc = throttle(callback, waitInMs, timer);
|
||||
const throttleFunc = new TestContext()
|
||||
.withWaitInMs(waitInMs)
|
||||
.withTimer(timer)
|
||||
.withCallback(callback)
|
||||
.throttle();
|
||||
// act
|
||||
throttleFunc();
|
||||
totalRuns--; // So we don't count the initial run
|
||||
@@ -56,53 +119,207 @@ describe('throttle', () => {
|
||||
// assert
|
||||
expect(totalRuns).to.equal(1);
|
||||
});
|
||||
it('should call the callback at most once at given time', () => {
|
||||
it('limits calls to at most once per period', () => {
|
||||
// arrange
|
||||
const totalExpectedCalls = 2; // leading and trailing only
|
||||
const timer = new TimerStub();
|
||||
let totalRuns = 0;
|
||||
const callback = () => totalRuns++;
|
||||
const waitInMs = 500;
|
||||
const waitInMs = 200;
|
||||
const totalCalls = 10;
|
||||
const throttleFunc = throttle(callback, waitInMs, timer);
|
||||
const throttleFunc = new TestContext()
|
||||
.withWaitInMs(waitInMs)
|
||||
.withTimer(timer)
|
||||
.withCallback(callback)
|
||||
.throttle();
|
||||
// act
|
||||
for (let currentCall = 0; currentCall < totalCalls; currentCall++) {
|
||||
const currentTime = (waitInMs / totalCalls) * currentCall;
|
||||
timer.setCurrentTime(currentTime);
|
||||
throttleFunc();
|
||||
}
|
||||
timer.tickNext(waitInMs);
|
||||
// assert
|
||||
expect(totalRuns).to.equal(2); // one initial and one at the end
|
||||
expect(totalRuns).to.equal(totalExpectedCalls);
|
||||
});
|
||||
it('should call the callback as long as delay is waited', () => {
|
||||
it('executes the callback after each complete delay period', () => {
|
||||
// arrange
|
||||
const timer = new TimerStub();
|
||||
let totalRuns = 0;
|
||||
const callback = () => totalRuns++;
|
||||
const waitInMs = 500;
|
||||
const expectedTotalRuns = 10;
|
||||
const throttleFunc = throttle(callback, waitInMs, timer);
|
||||
const throttleFunc = new TestContext()
|
||||
.withWaitInMs(waitInMs)
|
||||
.withTimer(timer)
|
||||
.withCallback(callback)
|
||||
.throttle();
|
||||
// act
|
||||
for (let i = 0; i < expectedTotalRuns; i++) {
|
||||
Array.from({ length: expectedTotalRuns }).forEach(() => {
|
||||
throttleFunc();
|
||||
timer.tickNext(waitInMs);
|
||||
}
|
||||
});
|
||||
// assert
|
||||
expect(totalRuns).to.equal(expectedTotalRuns);
|
||||
});
|
||||
it('should call arguments as expected', () => {
|
||||
// arrange
|
||||
const timer = new TimerStub();
|
||||
const expected = [1, 2, 3];
|
||||
const actual = new Array<number>();
|
||||
const callback = (arg: number) => { actual.push(arg); };
|
||||
const waitInMs = 500;
|
||||
const throttleFunc = throttle(callback, waitInMs, timer);
|
||||
// act
|
||||
for (const arg of expected) {
|
||||
throttleFunc(arg);
|
||||
describe('leading call exclusion', () => {
|
||||
it('does not execute the callback immediately on the first call', () => {
|
||||
// arrange
|
||||
const timer = new TimerStub();
|
||||
let totalRuns = 0;
|
||||
const callback = () => totalRuns++;
|
||||
const throttleFunc = new TestContext()
|
||||
.withTimer(timer)
|
||||
.withCallback(callback)
|
||||
.withExcludeLeadingCall(true)
|
||||
.throttle();
|
||||
// act
|
||||
throttleFunc();
|
||||
// assert
|
||||
expect(totalRuns).to.equal(0);
|
||||
});
|
||||
it('executes the initial call after the initial wait time', () => {
|
||||
// arrange
|
||||
const timer = new TimerStub();
|
||||
let totalRuns = 0;
|
||||
const waitInMs = 200;
|
||||
const callback = () => totalRuns++;
|
||||
const throttleFunc = new TestContext()
|
||||
.withTimer(timer)
|
||||
.withCallback(callback)
|
||||
.withExcludeLeadingCall(true)
|
||||
.withWaitInMs(waitInMs)
|
||||
.throttle();
|
||||
// act
|
||||
throttleFunc();
|
||||
timer.tickNext(waitInMs);
|
||||
}
|
||||
// assert
|
||||
expect(expected).to.deep.equal(actual);
|
||||
// assert
|
||||
expect(totalRuns).to.equal(1);
|
||||
});
|
||||
it('executes two calls after two wait periods', () => {
|
||||
// arrange
|
||||
const expectedTotalRuns = 2;
|
||||
const calledArgs = new Array<string>();
|
||||
const timer = new TimerStub();
|
||||
const waitInMs = 300;
|
||||
let totalRuns = 0;
|
||||
const callback = (message: string) => {
|
||||
totalRuns++;
|
||||
calledArgs.push(message);
|
||||
};
|
||||
const throttleFunc = new TestContext()
|
||||
.withTimer(timer)
|
||||
.withCallback(callback)
|
||||
.withWaitInMs(waitInMs)
|
||||
.withExcludeLeadingCall(true)
|
||||
.throttle();
|
||||
// act
|
||||
Array.from({ length: expectedTotalRuns }).forEach((_, index) => {
|
||||
throttleFunc(`Call ${index} (zero-based, where initial call is 0)`);
|
||||
timer.tickNext(waitInMs);
|
||||
});
|
||||
// assert
|
||||
expect(totalRuns).to.equal(expectedTotalRuns, formatAssertionMessage([
|
||||
`Expected total runs to equal ${expectedTotalRuns}, but got ${totalRuns}.`,
|
||||
'Detailed call information:',
|
||||
...calledArgs.map((message, index) => `${index + 1}) ${message}`),
|
||||
]));
|
||||
});
|
||||
it('only executes once when multiple calls are made during the initial wait period', () => {
|
||||
// arrange
|
||||
const timer = new TimerStub();
|
||||
let totalRuns = 0;
|
||||
const callback = () => { totalRuns++; };
|
||||
const waitInMs = 300;
|
||||
const throttleFunc = new TestContext()
|
||||
.withTimer(timer)
|
||||
.withWaitInMs(waitInMs)
|
||||
.withCallback(callback)
|
||||
.withExcludeLeadingCall(true)
|
||||
.throttle();
|
||||
// act
|
||||
throttleFunc();
|
||||
timer.tickNext(waitInMs / 3);
|
||||
throttleFunc();
|
||||
timer.tickNext(waitInMs / 3);
|
||||
throttleFunc();
|
||||
timer.tickNext(waitInMs / 3);
|
||||
// assert
|
||||
expect(totalRuns).to.equal(1);
|
||||
});
|
||||
it('executes the last provided arguments only after the wait period expires', () => {
|
||||
// arrange
|
||||
const expectedLastArg = 'trailing call';
|
||||
const timer = new TimerStub();
|
||||
let actualLastArg: string | null = null;
|
||||
const callback = (arg: string) => {
|
||||
actualLastArg = arg;
|
||||
};
|
||||
const waitInMs = 300;
|
||||
const throttleFunc = new TestContext()
|
||||
.withTimer(timer)
|
||||
.withWaitInMs(waitInMs)
|
||||
.withCallback(callback)
|
||||
.withExcludeLeadingCall(true)
|
||||
.throttle();
|
||||
// act
|
||||
throttleFunc('leading call');
|
||||
timer.tickNext(waitInMs / 3);
|
||||
throttleFunc('call in the middle');
|
||||
timer.tickNext(waitInMs / 3);
|
||||
throttleFunc(expectedLastArg);
|
||||
timer.tickNext(waitInMs / 3);
|
||||
// assert
|
||||
expect(actualLastArg).to.equal(expectedLastArg);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
type CallbackType = Parameters<typeof throttle>[0];
|
||||
|
||||
class TestContext {
|
||||
private options: Partial<ThrottleOptions> | undefined = {
|
||||
timer: new TimerStub(),
|
||||
};
|
||||
|
||||
private waitInMs: number = 500;
|
||||
|
||||
private callback: CallbackType = () => { /* NO OP */ };
|
||||
|
||||
public withTimer(timer: Timer): this {
|
||||
return this.withOptions({
|
||||
...(this.options ?? {}),
|
||||
timer,
|
||||
});
|
||||
}
|
||||
|
||||
public withWaitInMs(waitInMs: number): this {
|
||||
this.waitInMs = waitInMs;
|
||||
return this;
|
||||
}
|
||||
|
||||
public withCallback(callback: CallbackType): this {
|
||||
this.callback = callback;
|
||||
return this;
|
||||
}
|
||||
|
||||
public withExcludeLeadingCall(excludeLeadingCall: boolean): this {
|
||||
return this.withOptions({
|
||||
...(this.options ?? {}),
|
||||
excludeLeadingCall,
|
||||
});
|
||||
}
|
||||
|
||||
public withOptions(options: Partial<ThrottleOptions> | undefined): this {
|
||||
this.options = options;
|
||||
return this;
|
||||
}
|
||||
|
||||
public throttle(): ReturnType<typeof throttle> {
|
||||
return throttle(
|
||||
this.callback,
|
||||
this.waitInMs,
|
||||
this.options,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -22,6 +22,7 @@ describe('DependencyProvider', () => {
|
||||
useCodeRunner: createTransientTests(),
|
||||
useDialog: createTransientTests(),
|
||||
useScriptDiagnosticsCollector: createTransientTests(),
|
||||
useAutoUnsubscribedEventListener: createTransientTests(),
|
||||
};
|
||||
Object.entries(testCases).forEach(([key, runTests]) => {
|
||||
const registeredKey = InjectionKeys[key].key;
|
||||
|
||||
@@ -6,6 +6,7 @@ import { useCollectionState } from '@/presentation/components/Shared/Hooks/UseCo
|
||||
import { UseCollectionStateStub } from '@tests/unit/shared/Stubs/UseCollectionStateStub';
|
||||
import { InjectionKeys } from '@/presentation/injectionSymbols';
|
||||
import { createSizeObserverStub } from '@tests/unit/shared/Stubs/SizeObserverStub';
|
||||
import { UseEventListenerStub } from '@tests/unit/shared/Stubs/UseEventListenerStub';
|
||||
|
||||
const DOM_SELECTOR_CARDS = '.cards';
|
||||
|
||||
@@ -54,6 +55,7 @@ function mountComponent(options?: {
|
||||
provide: {
|
||||
[InjectionKeys.useCollectionState.key]:
|
||||
() => options?.useCollectionState ?? new UseCollectionStateStub().get(),
|
||||
[InjectionKeys.useAutoUnsubscribedEventListener.key]: new UseEventListenerStub().get(),
|
||||
},
|
||||
stubs: {
|
||||
[sizeObserverName]: sizeObserverStub,
|
||||
|
||||
@@ -1,120 +1,81 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { shallowMount } from '@vue/test-utils';
|
||||
import { defineComponent, nextTick } from 'vue';
|
||||
import {
|
||||
type WindowWithEventListeners, useKeyboardInteractionState,
|
||||
} from '@/presentation/components/Scripts/View/Tree/TreeView/Node/UseKeyboardInteractionState';
|
||||
import { useKeyboardInteractionState } from '@/presentation/components/Scripts/View/Tree/TreeView/Node/UseKeyboardInteractionState';
|
||||
import type { UseEventListener } from '@/presentation/components/Shared/Hooks/UseAutoUnsubscribedEventListener';
|
||||
import { UseEventListenerStub } from '@tests/unit/shared/Stubs/UseEventListenerStub';
|
||||
|
||||
describe('useKeyboardInteractionState', () => {
|
||||
describe('isKeyboardBeingUsed', () => {
|
||||
it('should initialize as `false`', () => {
|
||||
it('initializes as `false`', () => {
|
||||
// arrange
|
||||
const { windowStub } = createWindowStub();
|
||||
const expectedValue = false;
|
||||
const context = new TestContext();
|
||||
// act
|
||||
const { returnObject } = mountWrapperComponent(windowStub);
|
||||
const { isKeyboardBeingUsed } = context.get();
|
||||
// assert
|
||||
expect(returnObject.isKeyboardBeingUsed.value).to.equal(false);
|
||||
expect(isKeyboardBeingUsed.value).to.equal(expectedValue);
|
||||
});
|
||||
|
||||
it('should set to `true` on keydown event', () => {
|
||||
it('becomes `true` on `keydown` event', () => {
|
||||
// arrange
|
||||
const { triggerEvent, windowStub } = createWindowStub();
|
||||
const expectedValue = true;
|
||||
const eventTarget = new EventTarget();
|
||||
const context = new TestContext()
|
||||
.withEventTarget(eventTarget);
|
||||
// act
|
||||
const { returnObject } = mountWrapperComponent(windowStub);
|
||||
triggerEvent('keydown');
|
||||
const { isKeyboardBeingUsed } = context.get();
|
||||
eventTarget.dispatchEvent(new Event('keydown'));
|
||||
// assert
|
||||
expect(returnObject.isKeyboardBeingUsed.value).to.equal(true);
|
||||
expect(isKeyboardBeingUsed.value).to.equal(expectedValue);
|
||||
});
|
||||
|
||||
it('should stay `false` on click event', () => {
|
||||
it('remains `false` on `click` event', () => {
|
||||
// arrange
|
||||
const { triggerEvent, windowStub } = createWindowStub();
|
||||
const expectedValue = false;
|
||||
const eventTarget = new EventTarget();
|
||||
const context = new TestContext()
|
||||
.withEventTarget(eventTarget);
|
||||
// act
|
||||
const { returnObject } = mountWrapperComponent(windowStub);
|
||||
triggerEvent('click');
|
||||
const { isKeyboardBeingUsed } = context.get();
|
||||
eventTarget.dispatchEvent(new Event('click'));
|
||||
// assert
|
||||
expect(returnObject.isKeyboardBeingUsed.value).to.equal(false);
|
||||
expect(isKeyboardBeingUsed.value).to.equal(expectedValue);
|
||||
});
|
||||
|
||||
it('should transition to `false` on click event after keydown event', () => {
|
||||
it('transitions back to `false` on `click` event after `keydown` event', () => {
|
||||
// arrange
|
||||
const { triggerEvent, windowStub } = createWindowStub();
|
||||
const expectedValue = false;
|
||||
const eventTarget = new EventTarget();
|
||||
const context = new TestContext()
|
||||
.withEventTarget(eventTarget);
|
||||
// act
|
||||
const { returnObject } = mountWrapperComponent(windowStub);
|
||||
triggerEvent('keydown');
|
||||
triggerEvent('click');
|
||||
const { isKeyboardBeingUsed } = context.get();
|
||||
eventTarget.dispatchEvent(new Event('keydown'));
|
||||
eventTarget.dispatchEvent(new Event('click'));
|
||||
// assert
|
||||
expect(returnObject.isKeyboardBeingUsed.value).to.equal(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('attach/detach', () => {
|
||||
it('should attach keydown and click events on mounted', () => {
|
||||
// arrange
|
||||
const { listeners, windowStub } = createWindowStub();
|
||||
// act
|
||||
mountWrapperComponent(windowStub);
|
||||
// assert
|
||||
expect(listeners.keydown).to.have.lengthOf(1);
|
||||
expect(listeners.click).to.have.lengthOf(1);
|
||||
});
|
||||
|
||||
it('should detach keydown and click events on unmounted', async () => {
|
||||
// arrange
|
||||
const { listeners, windowStub } = createWindowStub();
|
||||
// act
|
||||
const { wrapper } = mountWrapperComponent(windowStub);
|
||||
wrapper.unmount();
|
||||
await nextTick();
|
||||
// assert
|
||||
expect(listeners.keydown).to.have.lengthOf(0);
|
||||
expect(listeners.click).to.have.lengthOf(0);
|
||||
expect(isKeyboardBeingUsed.value).to.equal(expectedValue);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
function mountWrapperComponent(window: WindowWithEventListeners) {
|
||||
let returnObject: ReturnType<typeof useKeyboardInteractionState> | undefined;
|
||||
const wrapper = shallowMount(defineComponent({
|
||||
setup() {
|
||||
returnObject = useKeyboardInteractionState(window);
|
||||
},
|
||||
template: '<div></div>',
|
||||
}));
|
||||
if (!returnObject) {
|
||||
throw new Error('missing hook result');
|
||||
class TestContext {
|
||||
private eventTarget: EventTarget = new EventTarget();
|
||||
|
||||
private useEventListener: UseEventListener = new UseEventListenerStub().get();
|
||||
|
||||
public withEventTarget(eventTarget: EventTarget): this {
|
||||
this.eventTarget = eventTarget;
|
||||
return this;
|
||||
}
|
||||
return {
|
||||
returnObject,
|
||||
wrapper,
|
||||
};
|
||||
}
|
||||
|
||||
type EventListenerWindowFunction = (ev: Event) => unknown;
|
||||
type WindowEventKey = keyof WindowEventMap;
|
||||
public withUseEventListener(useEventListener: UseEventListener): this {
|
||||
this.useEventListener = useEventListener;
|
||||
return this;
|
||||
}
|
||||
|
||||
function createWindowStub() {
|
||||
const listeners: Partial<Record<WindowEventKey, EventListenerWindowFunction[]>> = {};
|
||||
const windowStub: WindowWithEventListeners = {
|
||||
addEventListener: (eventName: string, fn: EventListenerWindowFunction) => {
|
||||
if (!listeners[eventName]) {
|
||||
listeners[eventName] = [];
|
||||
}
|
||||
listeners[eventName].push(fn);
|
||||
},
|
||||
removeEventListener: (eventName: string, fn: EventListenerWindowFunction) => {
|
||||
if (!listeners[eventName]) return;
|
||||
const index = listeners[eventName].indexOf(fn);
|
||||
if (index > -1) {
|
||||
listeners[eventName].splice(index, 1);
|
||||
}
|
||||
},
|
||||
};
|
||||
return {
|
||||
windowStub,
|
||||
triggerEvent: (eventName: WindowEventKey) => {
|
||||
listeners[eventName]?.forEach((fn) => fn(new Event(eventName)));
|
||||
},
|
||||
listeners,
|
||||
};
|
||||
public get() {
|
||||
return useKeyboardInteractionState(
|
||||
this.eventTarget,
|
||||
this.useEventListener,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,172 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { shallowMount } from '@vue/test-utils';
|
||||
import { nextTick, shallowRef } from 'vue';
|
||||
import { useAutoUnsubscribedEventListener } from '@/presentation/components/Shared/Hooks/UseAutoUnsubscribedEventListener';
|
||||
import { expectExists } from '@tests/shared/Assertions/ExpectExists';
|
||||
import { expectDoesNotThrowAsync } from '@tests/shared/Assertions/ExpectThrowsAsync';
|
||||
|
||||
describe('UseAutoUnsubscribedEventListener', () => {
|
||||
describe('startListening', () => {
|
||||
describe('direct value', () => {
|
||||
it('immediately adds listener', () => {
|
||||
// arrange
|
||||
const eventTarget = new EventTarget();
|
||||
const eventType: keyof HTMLElementEventMap = 'abort';
|
||||
const expectedEvent = new CustomEvent(eventType);
|
||||
let actualEvent: Event | null = null;
|
||||
const callback = (event: Event) => {
|
||||
actualEvent = event;
|
||||
};
|
||||
// act
|
||||
const { returnObject } = mountWrapper();
|
||||
returnObject.startListening(eventTarget, eventType, callback);
|
||||
eventTarget.dispatchEvent(expectedEvent);
|
||||
// assert
|
||||
expect(actualEvent).to.equal(expectedEvent);
|
||||
});
|
||||
it('removes listener after component unmounts', () => {
|
||||
// arrange
|
||||
const expectedCallbackCall = false;
|
||||
let isCallbackCalled = false;
|
||||
const callback = () => {
|
||||
isCallbackCalled = true;
|
||||
};
|
||||
const eventTarget = new EventTarget();
|
||||
const eventType: keyof HTMLElementEventMap = 'abort';
|
||||
// act
|
||||
const { wrapper } = mountWrapper({
|
||||
setup: (listener) => listener.startListening(eventTarget, eventType, callback),
|
||||
});
|
||||
wrapper.unmount();
|
||||
eventTarget.dispatchEvent(new CustomEvent(eventType));
|
||||
// assert
|
||||
expect(isCallbackCalled).to.equal(expectedCallbackCall);
|
||||
});
|
||||
});
|
||||
describe('reference', () => {
|
||||
it('immediately adds listener', () => {
|
||||
// arrange
|
||||
const eventTarget = new EventTarget();
|
||||
const eventTargetRef = shallowRef(eventTarget);
|
||||
const eventType: keyof HTMLElementEventMap = 'abort';
|
||||
const expectedEvent = new CustomEvent(eventType);
|
||||
let actualEvent: Event | null = null;
|
||||
const callback = (event: Event) => {
|
||||
actualEvent = event;
|
||||
};
|
||||
// act
|
||||
const { returnObject } = mountWrapper();
|
||||
returnObject.startListening(eventTargetRef, eventType, callback);
|
||||
eventTarget.dispatchEvent(expectedEvent);
|
||||
// assert
|
||||
expect(actualEvent).to.equal(expectedEvent);
|
||||
});
|
||||
it('adds listener upon reference update', async () => {
|
||||
// arrange
|
||||
const oldValue = new EventTarget();
|
||||
const newValue = new EventTarget();
|
||||
const targetRef = shallowRef(oldValue);
|
||||
const eventType: keyof HTMLElementEventMap = 'abort';
|
||||
const expectedEvent = new CustomEvent(eventType);
|
||||
let actualEvent: Event | null = null;
|
||||
const callback = (event: Event) => {
|
||||
actualEvent = event;
|
||||
};
|
||||
// act
|
||||
const { returnObject } = mountWrapper();
|
||||
returnObject.startListening(targetRef, eventType, callback);
|
||||
targetRef.value = newValue;
|
||||
await nextTick();
|
||||
newValue.dispatchEvent(expectedEvent);
|
||||
// assert
|
||||
expect(actualEvent).to.equal(expectedEvent);
|
||||
});
|
||||
it('does not throw if initial element is undefined', () => {
|
||||
// arrange
|
||||
const targetRef = shallowRef(undefined);
|
||||
// act
|
||||
const { returnObject } = mountWrapper();
|
||||
const act = () => {
|
||||
returnObject.startListening(targetRef, 'abort', () => { /* NO OP */ });
|
||||
};
|
||||
// assert
|
||||
expect(act).to.not.throw();
|
||||
});
|
||||
it('does not throw when reference becomes undefined', async () => {
|
||||
// arrange
|
||||
const targetRef = shallowRef<EventTarget | undefined>(new EventTarget());
|
||||
// act
|
||||
const { returnObject } = mountWrapper();
|
||||
returnObject.startListening(targetRef, 'abort', () => { /* NO OP */ });
|
||||
const act = async () => {
|
||||
targetRef.value = undefined;
|
||||
await nextTick();
|
||||
};
|
||||
// assert
|
||||
await expectDoesNotThrowAsync(act);
|
||||
});
|
||||
it('removes listener on reference change', async () => {
|
||||
// arrange
|
||||
const expectedCallbackCall = false;
|
||||
let isCallbackCalled = false;
|
||||
const callback = () => {
|
||||
isCallbackCalled = true;
|
||||
};
|
||||
const oldValue = new EventTarget();
|
||||
const newValue = new EventTarget();
|
||||
const targetRef = shallowRef(oldValue);
|
||||
const eventType: keyof HTMLElementEventMap = 'abort';
|
||||
const expectedEvent = new CustomEvent(eventType);
|
||||
// act
|
||||
const { returnObject } = mountWrapper();
|
||||
returnObject.startListening(targetRef, eventType, callback);
|
||||
targetRef.value = newValue;
|
||||
await nextTick();
|
||||
oldValue.dispatchEvent(expectedEvent);
|
||||
// assert
|
||||
expect(isCallbackCalled).to.equal(expectedCallbackCall);
|
||||
});
|
||||
it('removes listener after component unmounts', () => {
|
||||
// arrange
|
||||
const expectedCallbackCall = false;
|
||||
let isCallbackCalled = false;
|
||||
const callback = () => {
|
||||
isCallbackCalled = true;
|
||||
};
|
||||
const target = new EventTarget();
|
||||
const targetRef = shallowRef(target);
|
||||
const eventType: keyof HTMLElementEventMap = 'abort';
|
||||
// act
|
||||
const { wrapper } = mountWrapper({
|
||||
setup: (listener) => listener.startListening(targetRef, eventType, callback),
|
||||
});
|
||||
wrapper.unmount();
|
||||
target.dispatchEvent(new CustomEvent(eventType));
|
||||
// assert
|
||||
expect(isCallbackCalled).to.equal(expectedCallbackCall);
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
function mountWrapper(options?: {
|
||||
readonly constructorArgs?: Parameters<typeof useAutoUnsubscribedEventListener>,
|
||||
/** Running inside `setup` allows simulating lifecycle events like unmounting. */
|
||||
readonly setup?: (returnObject: ReturnType<typeof useAutoUnsubscribedEventListener>) => void,
|
||||
}) {
|
||||
let returnObject: ReturnType<typeof useAutoUnsubscribedEventListener> | undefined;
|
||||
const wrapper = shallowMount({
|
||||
setup() {
|
||||
returnObject = useAutoUnsubscribedEventListener(...(options?.constructorArgs ?? []));
|
||||
if (options?.setup) {
|
||||
options.setup(returnObject);
|
||||
}
|
||||
},
|
||||
template: '<div></div>',
|
||||
});
|
||||
expectExists(returnObject);
|
||||
return {
|
||||
wrapper,
|
||||
returnObject,
|
||||
};
|
||||
}
|
||||
@@ -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,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -24,7 +24,8 @@ export class TimerStub implements Timer {
|
||||
}
|
||||
|
||||
public clearTimeout(timeoutId: TimeoutType): void {
|
||||
this.subscriptions[+timeoutId].unsubscribe();
|
||||
const subscriptionIndex = +timeoutId;
|
||||
this.subscriptions[subscriptionIndex].unsubscribe();
|
||||
}
|
||||
|
||||
public dateNow(): number {
|
||||
|
||||
15
tests/unit/shared/Stubs/UseEventListenerStub.ts
Normal file
15
tests/unit/shared/Stubs/UseEventListenerStub.ts
Normal file
@@ -0,0 +1,15 @@
|
||||
import type { UseEventListener } from '@/presentation/components/Shared/Hooks/UseAutoUnsubscribedEventListener';
|
||||
|
||||
export class UseEventListenerStub {
|
||||
public get(): UseEventListener {
|
||||
return () => ({
|
||||
startListening: (targetElementSource, eventType, eventResponseFunction) => {
|
||||
if (targetElementSource instanceof EventTarget) {
|
||||
targetElementSource.addEventListener(eventType, eventResponseFunction);
|
||||
return;
|
||||
}
|
||||
targetElementSource.value?.addEventListener(eventType, eventResponseFunction);
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user